extern StatBag S;
string hostname=arg()["carbon-ourname"];
- if(hostname.empty()) {
- char tmp[80];
- memset(tmp, 0, sizeof(tmp));
- gethostname(tmp, sizeof(tmp));
- char *p = strchr(tmp, '.');
- if(p) *p=0;
- hostname=tmp;
- boost::replace_all(hostname, ".", "_");
+ if (hostname.empty()) {
+ try {
+ hostname = getCarbonHostName();
+ }
+ catch(const std::exception& e) {
+ throw std::runtime_error(std::string("The 'carbon-ourname' setting has not been set and we are unable to determine the system's hostname: ") + e.what());
+ }
}
vector<string> carbonServers;
for (const auto& conf : *localCarbon) {
const auto& server = conf.server;
std::string hostname = conf.ourname;
- if(hostname.empty()) {
- char tmp[80];
- memset(tmp, 0, sizeof(tmp));
- gethostname(tmp, sizeof(tmp));
- char *p = strchr(tmp, '.');
- if(p) *p=0;
- hostname=tmp;
- boost::replace_all(hostname, ".", "_");
+ if (hostname.empty()) {
+ try {
+ hostname = getCarbonHostName();
+ }
+ catch(const std::exception& e) {
+ throw std::runtime_error(std::string("The 'ourname' setting in 'carbonServer()' has not been set and we are unable to determine the system's hostname: ") + e.what());
+ }
}
try {
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
+#include <limits.h>
#ifdef __FreeBSD__
# include <pthread_np.h>
#endif
#endif /* HAVE_PTHREAD_SETAFFINITY_NP */
return ENOSYS;
}
+
+static size_t getMaxHostNameSize()
+{
+#if defined(HOST_NAME_MAX)
+ return HOST_NAME_MAX;
+#endif
+
+#if defined(_SC_HOST_NAME_MAX)
+ auto tmp = sysconf(_SC_HOST_NAME_MAX);
+ if (tmp != -1) {
+ return tmp;
+ }
+#endif
+
+ /* _POSIX_HOST_NAME_MAX */
+ return 255;
+}
+
+std::string getCarbonHostName()
+{
+ std::string hostname;
+ hostname.resize(getMaxHostNameSize() + 1, 0);
+
+ if (gethostname(const_cast<char*>(hostname.c_str()), hostname.size()) != 0) {
+ throw std::runtime_error(stringerror());
+ }
+
+ auto pos = hostname.find(".");
+ if (pos != std::string::npos) {
+ hostname.resize(pos);
+ }
+
+ boost::replace_all(hostname, ".", "_");
+
+ return hostname;
+}
bool isSettingThreadCPUAffinitySupported();
int mapThreadToCPUList(pthread_t tid, const std::set<int>& cpus);
+
+std::string getCarbonHostName();
if(carbonServers.empty())
return;
- if(hostname.empty()) {
- char tmp[HOST_NAME_MAX+1];
- memset(tmp, 0, sizeof(tmp));
- if (gethostname(tmp, sizeof(tmp)) != 0) {
- throw std::runtime_error("The 'carbon-ourname' setting has not been set and we are unable to determine the system's hostname: " + stringerror());
+ if (hostname.empty()) {
+ try {
+ hostname = getCarbonHostName();
+ }
+ catch(const std::exception& e) {
+ throw std::runtime_error(std::string("The 'carbon-ourname' setting has not been set and we are unable to determine the system's hostname: ") + e.what());
}
- char *p = strchr(tmp, '.');
- if(p) *p=0;
-
- hostname=tmp;
- boost::replace_all(hostname, ".", "_");
}
registerAllStats();