6 #if defined(__FreeBSD__) || defined(__APPLE__)
8 # define MADV_DONTFORK INHERIT_NONE
9 #endif /* __FreeBSD__ || __APPLE__*/
11 char *netdata_configured_config_dir = NULL;
12 char *netdata_configured_log_dir = NULL;
13 char *netdata_configured_plugins_dir = NULL;
14 char *netdata_configured_web_dir = NULL;
15 char *netdata_configured_cache_dir = NULL;
16 char *netdata_configured_varlib_dir = NULL;
17 char *netdata_configured_home_dir = NULL;
18 char *netdata_configured_host_prefix = NULL;
22 volatile sig_atomic_t netdata_exit = 0;
23 const char *os_type = NETDATA_OS_TYPE;
24 const char *program_version = VERSION;
26 // ----------------------------------------------------------------------------
27 // memory allocation functions that handle failures
29 // although netdata does not use memory allocations too often (netdata tries to
30 // maintain its memory footprint stable during runtime, i.e. all buffers are
31 // allocated during initialization and are adapted to current use throughout
32 // its lifetime), these can be used to override the default system allocation
35 #ifdef NETDATA_LOG_ALLOCATIONS
36 static struct memory_statistics {
37 volatile size_t malloc_calls_made;
38 volatile size_t calloc_calls_made;
39 volatile size_t realloc_calls_made;
40 volatile size_t strdup_calls_made;
41 volatile size_t free_calls_made;
42 volatile size_t memory_calls_made;
43 volatile size_t allocated_memory;
44 volatile size_t mmapped_memory;
47 static inline void print_allocations(const char *file, const char *function, const unsigned long line) {
48 static struct memory_statistics old = { 0, 0, 0, 0, 0, 0, 0, 0 };
50 //if(unlikely(!(memory_statistics.memory_calls_made % 5))) {
51 fprintf(stderr, "(%04lu@%-10.10s:%-15.15s): Allocated %zu KB (+%zu B), mmapped %zu KB (+%zu B): malloc %zu (+%zu), calloc %zu (+%zu), realloc %zu (+%zu), strdup %zu (+%zu), free %zu (+%zu)\n",
53 (memory_statistics.allocated_memory + 512) / 1024, memory_statistics.allocated_memory - old.allocated_memory,
54 (memory_statistics.mmapped_memory + 512) / 1024, memory_statistics.mmapped_memory - old.mmapped_memory,
55 memory_statistics.malloc_calls_made, memory_statistics.malloc_calls_made - old.malloc_calls_made,
56 memory_statistics.calloc_calls_made, memory_statistics.calloc_calls_made - old.calloc_calls_made,
57 memory_statistics.realloc_calls_made, memory_statistics.realloc_calls_made - old.realloc_calls_made,
58 memory_statistics.strdup_calls_made, memory_statistics.strdup_calls_made - old.strdup_calls_made,
59 memory_statistics.free_calls_made, memory_statistics.free_calls_made - old.free_calls_made
62 memcpy(&old, &memory_statistics, sizeof(struct memory_statistics));
66 static inline void malloc_accounting(const char *file, const char *function, const unsigned long line, size_t size) {
67 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
68 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
69 __atomic_fetch_add(&memory_statistics.malloc_calls_made, 1, __ATOMIC_SEQ_CST);
70 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
72 // this is for debugging - we don't care locking it
73 memory_statistics.memory_calls_made++;
74 memory_statistics.malloc_calls_made++;
75 memory_statistics.allocated_memory += size;
77 print_allocations(file, function, line);
80 static inline void mmap_accounting(size_t size) {
81 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
82 __atomic_fetch_add(&memory_statistics.malloc_calls_made, 1, __ATOMIC_SEQ_CST);
83 __atomic_fetch_add(&memory_statistics.mmapped_memory, size, __ATOMIC_SEQ_CST);
85 // this is for debugging - we don't care locking it
86 memory_statistics.memory_calls_made++;
87 memory_statistics.mmapped_memory += size;
91 static inline void calloc_accounting(const char *file, const char *function, const unsigned long line, size_t size) {
92 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
93 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
94 __atomic_fetch_add(&memory_statistics.calloc_calls_made, 1, __ATOMIC_SEQ_CST);
95 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
97 // this is for debugging - we don't care locking it
98 memory_statistics.memory_calls_made++;
99 memory_statistics.calloc_calls_made++;
100 memory_statistics.allocated_memory += size;
102 print_allocations(file, function, line);
105 static inline void realloc_accounting(const char *file, const char *function, const unsigned long line, void *ptr, size_t size) {
108 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
109 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
110 __atomic_fetch_add(&memory_statistics.realloc_calls_made, 1, __ATOMIC_SEQ_CST);
111 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
113 // this is for debugging - we don't care locking it
114 memory_statistics.memory_calls_made++;
115 memory_statistics.realloc_calls_made++;
116 memory_statistics.allocated_memory += size;
118 print_allocations(file, function, line);
121 static inline void strdup_accounting(const char *file, const char *function, const unsigned long line, const char *s) {
122 size_t size = strlen(s) + 1;
124 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
125 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
126 __atomic_fetch_add(&memory_statistics.strdup_calls_made, 1, __ATOMIC_SEQ_CST);
127 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
129 // this is for debugging - we don't care locking it
130 memory_statistics.memory_calls_made++;
131 memory_statistics.strdup_calls_made++;
132 memory_statistics.allocated_memory += size;
134 print_allocations(file, function, line);
137 static inline void free_accounting(const char *file, const char *function, const unsigned long line, void *ptr) {
143 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
144 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
145 __atomic_fetch_add(&memory_statistics.free_calls_made, 1, __ATOMIC_SEQ_CST);
147 // this is for debugging - we don't care locking it
148 memory_statistics.memory_calls_made++;
149 memory_statistics.free_calls_made++;
155 #ifdef NETDATA_LOG_ALLOCATIONS
156 char *strdupz_int(const char *file, const char *function, const unsigned long line, const char *s) {
157 strdup_accounting(file, function, line, s);
159 char *strdupz(const char *s) {
163 if (unlikely(!t)) fatal("Cannot strdup() string '%s'", s);
167 #ifdef NETDATA_LOG_ALLOCATIONS
168 void *mallocz_int(const char *file, const char *function, const unsigned long line, size_t size) {
169 malloc_accounting(file, function, line, size);
171 void *mallocz(size_t size) {
174 void *p = malloc(size);
175 if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", size);
179 #ifdef NETDATA_LOG_ALLOCATIONS
180 void *callocz_int(const char *file, const char *function, const unsigned long line, size_t nmemb, size_t size) {
181 calloc_accounting(file, function, line, nmemb * size);
183 void *callocz(size_t nmemb, size_t size) {
186 void *p = calloc(nmemb, size);
187 if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", nmemb * size);
191 #ifdef NETDATA_LOG_ALLOCATIONS
192 void *reallocz_int(const char *file, const char *function, const unsigned long line, void *ptr, size_t size) {
193 realloc_accounting(file, function, line, ptr, size);
195 void *reallocz(void *ptr, size_t size) {
198 void *p = realloc(ptr, size);
199 if (unlikely(!p)) fatal("Cannot re-allocate memory to %zu bytes.", size);
203 #ifdef NETDATA_LOG_ALLOCATIONS
204 void freez_int(const char *file, const char *function, const unsigned long line, void *ptr) {
205 free_accounting(file, function, line, ptr);
207 void freez(void *ptr) {
213 void json_escape_string(char *dst, const char *src, size_t size) {
215 char *d = dst, *e = &dst[size - 1];
217 for(t = src; *t && d < e ;t++) {
218 if(unlikely(*t == '\\' || *t == '"')) {
219 if(unlikely(d + 1 >= e)) break;
228 int sleep_usec(usec_t usec) {
230 #ifndef NETDATA_WITH_USLEEP
231 // we expect microseconds (1.000.000 per second)
232 // but timespec is nanoseconds (1.000.000.000 per second)
233 struct timespec rem, req = {
234 .tv_sec = (time_t) (usec / 1000000),
235 .tv_nsec = (suseconds_t) ((usec % 1000000) * 1000)
238 while (nanosleep(&req, &rem) == -1) {
239 if (likely(errno == EINTR)) {
240 debug(D_SYSTEM, "nanosleep() interrupted (while sleeping for %llu microseconds).", usec);
241 req.tv_sec = rem.tv_sec;
242 req.tv_nsec = rem.tv_nsec;
244 error("Cannot nanosleep() for %llu microseconds.", usec);
251 int ret = usleep(usec);
252 if(unlikely(ret == -1 && errno == EINVAL)) {
253 // on certain systems, usec has to be up to 999999
255 int counter = usec / 999999;
259 usleep(usec % 999999);
262 error("Cannot usleep() for %llu microseconds.", usec);
268 error("usleep() failed for %llu microseconds.", usec);
274 unsigned char netdata_map_chart_names[256] = {
367 [92] = '/', // backslash
533 // make sure the supplied string
534 // is good for a netdata chart/dimension ID/NAME
535 void netdata_fix_chart_name(char *s) {
536 while ((*s = netdata_map_chart_names[(unsigned char) *s])) s++;
539 unsigned char netdata_map_chart_ids[256] = {
632 [92] = '/', // backslash
798 // make sure the supplied string
799 // is good for a netdata chart/dimension ID/NAME
800 void netdata_fix_chart_id(char *s) {
801 while ((*s = netdata_map_chart_ids[(unsigned char) *s])) s++;
805 // http://stackoverflow.com/questions/7666509/hash-function-for-string
806 uint32_t simple_hash(const char *name)
808 const char *s = name;
809 uint32_t hash = 5381;
812 while((i = *s++)) hash = ((hash << 5) + hash) + i;
814 // fprintf(stderr, "HASH: %lu %s\n", hash, name);
821 // http://isthe.com/chongo/tech/comp/fnv/#FNV-1a
822 uint32_t simple_hash(const char *name) {
823 unsigned char *s = (unsigned char *) name;
824 uint32_t hval = 0x811c9dc5;
828 // multiply by the 32 bit FNV magic prime mod 2^32
829 // NOTE: No need to optimize with left shifts.
830 // GCC will use imul instruction anyway.
831 // Tested with 'gcc -O3 -S'
832 //hval += (hval<<1) + (hval<<4) + (hval<<7) + (hval<<8) + (hval<<24);
835 // xor the bottom with the current octet
836 hval ^= (uint32_t) *s++;
839 // fprintf(stderr, "HASH: %u = %s\n", hval, name);
843 uint32_t simple_uhash(const char *name) {
844 unsigned char *s = (unsigned char *) name;
845 uint32_t hval = 0x811c9dc5, c;
849 if (unlikely(c >= 'A' && c <= 'Z')) c += 'a' - 'A';
858 // http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
859 // one at a time hash
860 uint32_t simple_hash(const char *name) {
861 unsigned char *s = (unsigned char *)name;
874 // fprintf(stderr, "HASH: %u = %s\n", h, name);
880 void strreverse(char *begin, char *end) {
881 while (end > begin) {
889 char *mystrsep(char **ptr, char *s) {
891 while (p && !p[0] && *ptr) p = strsep(ptr, s);
895 char *trim(char *s) {
896 // skip leading spaces
897 // and 'comments' as well!?
898 while (*s && isspace(*s)) s++;
899 if (!*s || *s == '#') return NULL;
901 // skip tailing spaces
902 // this way is way faster. Writes only one NUL char.
903 ssize_t l = strlen(s);
906 while (p > s && isspace(*p)) p--;
910 if (!*s) return NULL;
915 void *mymmap(const char *filename, size_t size, int flags, int ksm) {
916 static int log_madvise_1 = 1;
917 #ifdef MADV_MERGEABLE
918 static int log_madvise_2 = 1, log_madvise_3 = 1;
923 int fd = open(filename, O_RDWR | O_CREAT | O_NOATIME, 0664);
925 if (lseek(fd, size, SEEK_SET) == (off_t) size) {
926 if (write(fd, "", 1) == 1) {
927 if (ftruncate(fd, size))
928 error("Cannot truncate file '%s' to size %zu. Will use the larger file.", filename, size);
930 #ifdef MADV_MERGEABLE
931 if (flags & MAP_SHARED || !enable_ksm || !ksm) {
933 mem = mmap(NULL, size, PROT_READ | PROT_WRITE, flags, fd, 0);
934 if (mem == MAP_FAILED) {
935 error("Cannot allocate SHARED memory for file '%s'.", filename);
939 #ifdef NETDATA_LOG_ALLOCATIONS
940 mmap_accounting(size);
942 int advise = MADV_SEQUENTIAL | MADV_DONTFORK;
943 if (flags & MAP_SHARED) advise |= MADV_WILLNEED;
945 if (madvise(mem, size, advise) != 0 && log_madvise_1) {
946 error("Cannot advise the kernel about the memory usage of file '%s'.", filename);
950 #ifdef MADV_MERGEABLE
954 // test - load the file into memory
955 mem = calloc(1, size);
957 if(lseek(fd, 0, SEEK_SET) == 0) {
958 if(read(fd, mem, size) != (ssize_t)size)
959 error("Cannot read from file '%s'", filename);
962 error("Cannot seek to beginning of file '%s'.", filename);
965 mem = mmap(NULL, size, PROT_READ | PROT_WRITE, flags | MAP_ANONYMOUS, -1, 0);
966 if (mem == MAP_FAILED) {
967 error("Cannot allocate PRIVATE ANONYMOUS memory for KSM for file '%s'.", filename);
971 #ifdef NETDATA_LOG_ALLOCATIONS
972 mmap_accounting(size);
974 if (lseek(fd, 0, SEEK_SET) == 0) {
975 if (read(fd, mem, size) != (ssize_t) size)
976 error("Cannot read from file '%s'", filename);
978 error("Cannot seek to beginning of file '%s'.", filename);
980 // don't use MADV_SEQUENTIAL|MADV_DONTFORK, they disable MADV_MERGEABLE
981 if (madvise(mem, size, MADV_SEQUENTIAL | MADV_DONTFORK) != 0 && log_madvise_2) {
982 error("Cannot advise the kernel about the memory usage (MADV_SEQUENTIAL|MADV_DONTFORK) of file '%s'.",
987 if (madvise(mem, size, MADV_MERGEABLE) != 0 && log_madvise_3) {
988 error("Cannot advise the kernel about the memory usage (MADV_MERGEABLE) of file '%s'.",
997 error("Cannot write to file '%s' at position %zu.", filename, size);
1000 error("Cannot seek file '%s' to size %zu.", filename, size);
1005 error("Cannot create/open file '%s'.", filename);
1010 int savememory(const char *filename, void *mem, size_t size) {
1011 char tmpfilename[FILENAME_MAX + 1];
1013 snprintfz(tmpfilename, FILENAME_MAX, "%s.%ld.tmp", filename, (long) getpid());
1015 int fd = open(tmpfilename, O_RDWR | O_CREAT | O_NOATIME, 0664);
1017 error("Cannot create/open file '%s'.", filename);
1021 if (write(fd, mem, size) != (ssize_t) size) {
1022 error("Cannot write to file '%s' %ld bytes.", filename, (long) size);
1029 if (rename(tmpfilename, filename)) {
1030 error("Cannot rename '%s' to '%s'", tmpfilename, filename);
1037 int fd_is_valid(int fd) {
1038 return fcntl(fd, F_GETFD) != -1 || errno != EBADF;
1041 pid_t gettid(void) {
1043 return (pid_t)pthread_getthreadid_np();
1044 #elif defined(__APPLE__)
1045 uint64_t curthreadid;
1046 pthread_threadid_np(NULL, &curthreadid);
1047 return (pid_t)curthreadid;
1049 return (pid_t)syscall(SYS_gettid);
1050 #endif /* __FreeBSD__, __APPLE__*/
1053 char *fgets_trim_len(char *buf, size_t buf_size, FILE *fp, size_t *len) {
1054 char *s = fgets(buf, (int)buf_size, fp);
1055 if (!s) return NULL;
1059 // find the string end
1060 while (*++t != '\0');
1062 // trim trailing spaces/newlines/tabs
1063 while (--t > s && *t == '\n')
1073 int vsnprintfz(char *dst, size_t n, const char *fmt, va_list args) {
1074 int size = vsnprintf(dst, n, fmt, args);
1076 if (unlikely((size_t) size > n)) {
1085 int snprintfz(char *dst, size_t n, const char *fmt, ...) {
1088 va_start(args, fmt);
1089 int ret = vsnprintfz(dst, n, fmt, args);
1095 // ----------------------------------------------------------------------------
1097 // to retrieve settings of the system
1100 long get_system_cpus(void) {
1104 int32_t tmp_processors;
1106 if (unlikely(GETSYSCTL("hw.logicalcpu", tmp_processors))) {
1107 error("Assuming system has %d processors.", processors);
1109 processors = tmp_processors;
1114 int32_t tmp_processors;
1116 if (unlikely(GETSYSCTL("hw.ncpu", tmp_processors))) {
1117 error("Assuming system has %d processors.", processors);
1119 processors = tmp_processors;
1125 char filename[FILENAME_MAX + 1];
1126 snprintfz(filename, FILENAME_MAX, "%s/proc/stat", netdata_configured_host_prefix);
1128 procfile *ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);
1130 error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);
1134 ff = procfile_readall(ff);
1136 error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);
1142 for(i = 0; i < procfile_lines(ff); i++) {
1143 if(!procfile_linewords(ff, i)) continue;
1145 if(strncmp(procfile_lineword(ff, i, 0), "cpu", 3) == 0) processors++;
1148 if(processors < 1) processors = 1;
1152 debug(D_SYSTEM, "System has %d processors.", processors);
1155 #endif /* __APPLE__, __FreeBSD__ */
1158 pid_t pid_max = 32768;
1159 pid_t get_system_pid_max(void) {
1161 // As we currently do not know a solution to query pid_max from the os
1162 // we use the number defined in bsd/sys/proc_internal.h in XNU sources
1166 int32_t tmp_pid_max;
1168 if (unlikely(GETSYSCTL("kern.pid_max", tmp_pid_max))) {
1170 error("Assuming system's maximum pid is %d.", pid_max);
1172 pid_max = tmp_pid_max;
1178 static char read = 0;
1179 if(unlikely(read)) return pid_max;
1182 char filename[FILENAME_MAX + 1];
1183 snprintfz(filename, FILENAME_MAX, "%s/proc/sys/kernel/pid_max", netdata_configured_host_prefix);
1185 unsigned long long max = 0;
1186 if(read_single_number_file(filename, &max) != 0) {
1187 error("Cannot open file '%s'. Assuming system supports %d pids.", filename, pid_max);
1192 error("Cannot parse file '%s'. Assuming system supports %d pids.", filename, pid_max);
1196 pid_max = (pid_t) max;
1199 #endif /* __APPLE__, __FreeBSD__ */
1203 void get_system_HZ(void) {
1206 if ((ticks = sysconf(_SC_CLK_TCK)) == -1) {
1207 error("Cannot get system clock ticks");
1210 hz = (unsigned int) ticks;
1214 // poor man cycle counting
1215 static unsigned long tsc;
1216 void begin_tsc(void) {
1218 asm volatile ("cpuid\nrdtsc" : "=a" (a), "=d" (d) : "0" (0) : "ebx", "ecx");
1219 tsc = ((unsigned long)d << 32) | (unsigned long)a;
1221 unsigned long end_tsc(void) {
1223 asm volatile ("rdtscp" : "=a" (a), "=d" (d) : : "ecx");
1224 return (((unsigned long)d << 32) | (unsigned long)a) - tsc;