6 #if defined(__FreeBSD__) || defined(__APPLE__)
8 # define MADV_DONTFORK INHERIT_NONE
9 #endif /* __FreeBSD__ || __APPLE__*/
11 char *global_host_prefix = "";
14 volatile sig_atomic_t netdata_exit = 0;
15 const char *os_type = NETDATA_OS_TYPE;
16 const char *program_version = VERSION;
18 // ----------------------------------------------------------------------------
19 // memory allocation functions that handle failures
21 // although netdata does not use memory allocations too often (netdata tries to
22 // maintain its memory footprint stable during runtime, i.e. all buffers are
23 // allocated during initialization and are adapted to current use throughout
24 // its lifetime), these can be used to override the default system allocation
27 #ifdef NETDATA_LOG_ALLOCATIONS
28 static struct memory_statistics {
29 volatile size_t malloc_calls_made;
30 volatile size_t calloc_calls_made;
31 volatile size_t realloc_calls_made;
32 volatile size_t strdup_calls_made;
33 volatile size_t free_calls_made;
34 volatile size_t memory_calls_made;
35 volatile size_t allocated_memory;
36 volatile size_t mmapped_memory;
39 static inline void print_allocations(const char *file, const char *function, const unsigned long line) {
40 static struct memory_statistics old = { 0, 0, 0, 0, 0, 0, 0, 0 };
42 //if(unlikely(!(memory_statistics.memory_calls_made % 5))) {
43 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",
45 (memory_statistics.allocated_memory + 512) / 1024, memory_statistics.allocated_memory - old.allocated_memory,
46 (memory_statistics.mmapped_memory + 512) / 1024, memory_statistics.mmapped_memory - old.mmapped_memory,
47 memory_statistics.malloc_calls_made, memory_statistics.malloc_calls_made - old.malloc_calls_made,
48 memory_statistics.calloc_calls_made, memory_statistics.calloc_calls_made - old.calloc_calls_made,
49 memory_statistics.realloc_calls_made, memory_statistics.realloc_calls_made - old.realloc_calls_made,
50 memory_statistics.strdup_calls_made, memory_statistics.strdup_calls_made - old.strdup_calls_made,
51 memory_statistics.free_calls_made, memory_statistics.free_calls_made - old.free_calls_made
54 memcpy(&old, &memory_statistics, sizeof(struct memory_statistics));
58 static inline void malloc_accounting(const char *file, const char *function, const unsigned long line, size_t size) {
59 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
60 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
61 __atomic_fetch_add(&memory_statistics.malloc_calls_made, 1, __ATOMIC_SEQ_CST);
62 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
64 // this is for debugging - we don't care locking it
65 memory_statistics.memory_calls_made++;
66 memory_statistics.malloc_calls_made++;
67 memory_statistics.allocated_memory += size;
69 print_allocations(file, function, line);
72 static inline void mmap_accounting(size_t size) {
73 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
74 __atomic_fetch_add(&memory_statistics.malloc_calls_made, 1, __ATOMIC_SEQ_CST);
75 __atomic_fetch_add(&memory_statistics.mmapped_memory, size, __ATOMIC_SEQ_CST);
77 // this is for debugging - we don't care locking it
78 memory_statistics.memory_calls_made++;
79 memory_statistics.mmapped_memory += size;
83 static inline void calloc_accounting(const char *file, const char *function, const unsigned long line, size_t size) {
84 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
85 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
86 __atomic_fetch_add(&memory_statistics.calloc_calls_made, 1, __ATOMIC_SEQ_CST);
87 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
89 // this is for debugging - we don't care locking it
90 memory_statistics.memory_calls_made++;
91 memory_statistics.calloc_calls_made++;
92 memory_statistics.allocated_memory += size;
94 print_allocations(file, function, line);
97 static inline void realloc_accounting(const char *file, const char *function, const unsigned long line, void *ptr, size_t size) {
100 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
101 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
102 __atomic_fetch_add(&memory_statistics.realloc_calls_made, 1, __ATOMIC_SEQ_CST);
103 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
105 // this is for debugging - we don't care locking it
106 memory_statistics.memory_calls_made++;
107 memory_statistics.realloc_calls_made++;
108 memory_statistics.allocated_memory += size;
110 print_allocations(file, function, line);
113 static inline void strdup_accounting(const char *file, const char *function, const unsigned long line, const char *s) {
114 size_t size = strlen(s) + 1;
116 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
117 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
118 __atomic_fetch_add(&memory_statistics.strdup_calls_made, 1, __ATOMIC_SEQ_CST);
119 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
121 // this is for debugging - we don't care locking it
122 memory_statistics.memory_calls_made++;
123 memory_statistics.strdup_calls_made++;
124 memory_statistics.allocated_memory += size;
126 print_allocations(file, function, line);
129 static inline void free_accounting(const char *file, const char *function, const unsigned long line, void *ptr) {
135 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
136 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
137 __atomic_fetch_add(&memory_statistics.free_calls_made, 1, __ATOMIC_SEQ_CST);
139 // this is for debugging - we don't care locking it
140 memory_statistics.memory_calls_made++;
141 memory_statistics.free_calls_made++;
147 #ifdef NETDATA_LOG_ALLOCATIONS
148 char *strdupz_int(const char *file, const char *function, const unsigned long line, const char *s) {
149 strdup_accounting(file, function, line, s);
151 char *strdupz(const char *s) {
155 if (unlikely(!t)) fatal("Cannot strdup() string '%s'", s);
159 #ifdef NETDATA_LOG_ALLOCATIONS
160 void *mallocz_int(const char *file, const char *function, const unsigned long line, size_t size) {
161 malloc_accounting(file, function, line, size);
163 void *mallocz(size_t size) {
166 void *p = malloc(size);
167 if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", size);
171 #ifdef NETDATA_LOG_ALLOCATIONS
172 void *callocz_int(const char *file, const char *function, const unsigned long line, size_t nmemb, size_t size) {
173 calloc_accounting(file, function, line, nmemb * size);
175 void *callocz(size_t nmemb, size_t size) {
178 void *p = calloc(nmemb, size);
179 if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", nmemb * size);
183 #ifdef NETDATA_LOG_ALLOCATIONS
184 void *reallocz_int(const char *file, const char *function, const unsigned long line, void *ptr, size_t size) {
185 realloc_accounting(file, function, line, ptr, size);
187 void *reallocz(void *ptr, size_t size) {
190 void *p = realloc(ptr, size);
191 if (unlikely(!p)) fatal("Cannot re-allocate memory to %zu bytes.", size);
195 #ifdef NETDATA_LOG_ALLOCATIONS
196 void freez_int(const char *file, const char *function, const unsigned long line, void *ptr) {
197 free_accounting(file, function, line, ptr);
199 void freez(void *ptr) {
205 void json_escape_string(char *dst, const char *src, size_t size) {
207 char *d = dst, *e = &dst[size - 1];
209 for(t = src; *t && d < e ;t++) {
210 if(unlikely(*t == '\\' || *t == '"')) {
211 if(unlikely(d + 1 >= e)) break;
220 int sleep_usec(usec_t usec) {
222 #ifndef NETDATA_WITH_USLEEP
223 // we expect microseconds (1.000.000 per second)
224 // but timespec is nanoseconds (1.000.000.000 per second)
225 struct timespec rem, req = {
226 .tv_sec = (time_t) (usec / 1000000),
227 .tv_nsec = (suseconds_t) ((usec % 1000000) * 1000)
230 while (nanosleep(&req, &rem) == -1) {
231 if (likely(errno == EINTR)) {
232 debug(D_SYSTEM, "nanosleep() interrupted (while sleeping for %llu microseconds).", usec);
233 req.tv_sec = rem.tv_sec;
234 req.tv_nsec = rem.tv_nsec;
236 error("Cannot nanosleep() for %llu microseconds.", usec);
243 int ret = usleep(usec);
244 if(unlikely(ret == -1 && errno == EINVAL)) {
245 // on certain systems, usec has to be up to 999999
247 int counter = usec / 999999;
251 usleep(usec % 999999);
254 error("Cannot usleep() for %llu microseconds.", usec);
260 error("usleep() failed for %llu microseconds.", usec);
266 unsigned char netdata_map_chart_names[256] = {
359 [92] = '/', // backslash
525 // make sure the supplied string
526 // is good for a netdata chart/dimension ID/NAME
527 void netdata_fix_chart_name(char *s) {
528 while ((*s = netdata_map_chart_names[(unsigned char) *s])) s++;
531 unsigned char netdata_map_chart_ids[256] = {
624 [92] = '/', // backslash
790 // make sure the supplied string
791 // is good for a netdata chart/dimension ID/NAME
792 void netdata_fix_chart_id(char *s) {
793 while ((*s = netdata_map_chart_ids[(unsigned char) *s])) s++;
797 // http://stackoverflow.com/questions/7666509/hash-function-for-string
798 uint32_t simple_hash(const char *name)
800 const char *s = name;
801 uint32_t hash = 5381;
804 while((i = *s++)) hash = ((hash << 5) + hash) + i;
806 // fprintf(stderr, "HASH: %lu %s\n", hash, name);
813 // http://isthe.com/chongo/tech/comp/fnv/#FNV-1a
814 uint32_t simple_hash(const char *name) {
815 unsigned char *s = (unsigned char *) name;
816 uint32_t hval = 0x811c9dc5;
820 // multiply by the 32 bit FNV magic prime mod 2^32
821 // NOTE: No need to optimize with left shifts.
822 // GCC will use imul instruction anyway.
823 // Tested with 'gcc -O3 -S'
824 //hval += (hval<<1) + (hval<<4) + (hval<<7) + (hval<<8) + (hval<<24);
827 // xor the bottom with the current octet
828 hval ^= (uint32_t) *s++;
831 // fprintf(stderr, "HASH: %u = %s\n", hval, name);
835 uint32_t simple_uhash(const char *name) {
836 unsigned char *s = (unsigned char *) name;
837 uint32_t hval = 0x811c9dc5, c;
841 if (unlikely(c >= 'A' && c <= 'Z')) c += 'a' - 'A';
850 // http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
851 // one at a time hash
852 uint32_t simple_hash(const char *name) {
853 unsigned char *s = (unsigned char *)name;
866 // fprintf(stderr, "HASH: %u = %s\n", h, name);
872 void strreverse(char *begin, char *end) {
873 while (end > begin) {
881 char *mystrsep(char **ptr, char *s) {
883 while (p && !p[0] && *ptr) p = strsep(ptr, s);
887 char *trim(char *s) {
888 // skip leading spaces
889 // and 'comments' as well!?
890 while (*s && isspace(*s)) s++;
891 if (!*s || *s == '#') return NULL;
893 // skip tailing spaces
894 // this way is way faster. Writes only one NUL char.
895 ssize_t l = strlen(s);
898 while (p > s && isspace(*p)) p--;
902 if (!*s) return NULL;
907 void *mymmap(const char *filename, size_t size, int flags, int ksm) {
908 static int log_madvise_1 = 1;
909 #ifdef MADV_MERGEABLE
910 static int log_madvise_2 = 1, log_madvise_3 = 1;
915 int fd = open(filename, O_RDWR | O_CREAT | O_NOATIME, 0664);
917 if (lseek(fd, size, SEEK_SET) == (off_t) size) {
918 if (write(fd, "", 1) == 1) {
919 if (ftruncate(fd, size))
920 error("Cannot truncate file '%s' to size %zu. Will use the larger file.", filename, size);
922 #ifdef MADV_MERGEABLE
923 if (flags & MAP_SHARED || !enable_ksm || !ksm) {
925 mem = mmap(NULL, size, PROT_READ | PROT_WRITE, flags, fd, 0);
926 if (mem == MAP_FAILED) {
927 error("Cannot allocate SHARED memory for file '%s'.", filename);
931 #ifdef NETDATA_LOG_ALLOCATIONS
932 mmap_accounting(size);
934 int advise = MADV_SEQUENTIAL | MADV_DONTFORK;
935 if (flags & MAP_SHARED) advise |= MADV_WILLNEED;
937 if (madvise(mem, size, advise) != 0 && log_madvise_1) {
938 error("Cannot advise the kernel about the memory usage of file '%s'.", filename);
942 #ifdef MADV_MERGEABLE
946 // test - load the file into memory
947 mem = calloc(1, size);
949 if(lseek(fd, 0, SEEK_SET) == 0) {
950 if(read(fd, mem, size) != (ssize_t)size)
951 error("Cannot read from file '%s'", filename);
954 error("Cannot seek to beginning of file '%s'.", filename);
957 mem = mmap(NULL, size, PROT_READ | PROT_WRITE, flags | MAP_ANONYMOUS, -1, 0);
958 if (mem == MAP_FAILED) {
959 error("Cannot allocate PRIVATE ANONYMOUS memory for KSM for file '%s'.", filename);
963 #ifdef NETDATA_LOG_ALLOCATIONS
964 mmap_accounting(size);
966 if (lseek(fd, 0, SEEK_SET) == 0) {
967 if (read(fd, mem, size) != (ssize_t) size)
968 error("Cannot read from file '%s'", filename);
970 error("Cannot seek to beginning of file '%s'.", filename);
972 // don't use MADV_SEQUENTIAL|MADV_DONTFORK, they disable MADV_MERGEABLE
973 if (madvise(mem, size, MADV_SEQUENTIAL | MADV_DONTFORK) != 0 && log_madvise_2) {
974 error("Cannot advise the kernel about the memory usage (MADV_SEQUENTIAL|MADV_DONTFORK) of file '%s'.",
979 if (madvise(mem, size, MADV_MERGEABLE) != 0 && log_madvise_3) {
980 error("Cannot advise the kernel about the memory usage (MADV_MERGEABLE) of file '%s'.",
989 error("Cannot write to file '%s' at position %zu.", filename, size);
992 error("Cannot seek file '%s' to size %zu.", filename, size);
997 error("Cannot create/open file '%s'.", filename);
1002 int savememory(const char *filename, void *mem, size_t size) {
1003 char tmpfilename[FILENAME_MAX + 1];
1005 snprintfz(tmpfilename, FILENAME_MAX, "%s.%ld.tmp", filename, (long) getpid());
1007 int fd = open(tmpfilename, O_RDWR | O_CREAT | O_NOATIME, 0664);
1009 error("Cannot create/open file '%s'.", filename);
1013 if (write(fd, mem, size) != (ssize_t) size) {
1014 error("Cannot write to file '%s' %ld bytes.", filename, (long) size);
1021 if (rename(tmpfilename, filename)) {
1022 error("Cannot rename '%s' to '%s'", tmpfilename, filename);
1029 int fd_is_valid(int fd) {
1030 return fcntl(fd, F_GETFD) != -1 || errno != EBADF;
1033 pid_t gettid(void) {
1035 return (pid_t)pthread_getthreadid_np();
1036 #elif defined(__APPLE__)
1037 uint64_t curthreadid;
1038 pthread_threadid_np(NULL, &curthreadid);
1039 return (pid_t)curthreadid;
1041 return (pid_t)syscall(SYS_gettid);
1042 #endif /* __FreeBSD__, __APPLE__*/
1045 char *fgets_trim_len(char *buf, size_t buf_size, FILE *fp, size_t *len) {
1046 char *s = fgets(buf, (int)buf_size, fp);
1047 if (!s) return NULL;
1051 // find the string end
1052 while (*++t != '\0');
1054 // trim trailing spaces/newlines/tabs
1055 while (--t > s && *t == '\n')
1065 int vsnprintfz(char *dst, size_t n, const char *fmt, va_list args) {
1066 int size = vsnprintf(dst, n, fmt, args);
1068 if (unlikely((size_t) size > n)) {
1077 int snprintfz(char *dst, size_t n, const char *fmt, ...) {
1080 va_start(args, fmt);
1081 int ret = vsnprintfz(dst, n, fmt, args);
1087 // ----------------------------------------------------------------------------
1089 // to retrieve settings of the system
1092 long get_system_cpus(void) {
1096 int32_t tmp_processors;
1098 if (unlikely(GETSYSCTL("hw.logicalcpu", tmp_processors))) {
1099 error("Assuming system has %d processors.", processors);
1101 processors = tmp_processors;
1106 int32_t tmp_processors;
1108 if (unlikely(GETSYSCTL("hw.ncpu", tmp_processors))) {
1109 error("Assuming system has %d processors.", processors);
1111 processors = tmp_processors;
1117 char filename[FILENAME_MAX + 1];
1118 snprintfz(filename, FILENAME_MAX, "%s/proc/stat", global_host_prefix);
1120 procfile *ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);
1122 error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);
1126 ff = procfile_readall(ff);
1128 error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);
1134 for(i = 0; i < procfile_lines(ff); i++) {
1135 if(!procfile_linewords(ff, i)) continue;
1137 if(strncmp(procfile_lineword(ff, i, 0), "cpu", 3) == 0) processors++;
1140 if(processors < 1) processors = 1;
1144 debug(D_SYSTEM, "System has %d processors.", processors);
1147 #endif /* __APPLE__, __FreeBSD__ */
1150 pid_t pid_max = 32768;
1151 pid_t get_system_pid_max(void) {
1153 // As we currently do not know a solution to query pid_max from the os
1154 // we use the number defined in bsd/sys/proc_internal.h in XNU sources
1158 int32_t tmp_pid_max;
1160 if (unlikely(GETSYSCTL("kern.pid_max", tmp_pid_max))) {
1162 error("Assuming system's maximum pid is %d.", pid_max);
1164 pid_max = tmp_pid_max;
1170 static char read = 0;
1171 if(unlikely(read)) return pid_max;
1174 char filename[FILENAME_MAX + 1];
1175 snprintfz(filename, FILENAME_MAX, "%s/proc/sys/kernel/pid_max", global_host_prefix);
1177 unsigned long long max = 0;
1178 if(read_single_number_file(filename, &max) != 0) {
1179 error("Cannot open file '%s'. Assuming system supports %d pids.", filename, pid_max);
1184 error("Cannot parse file '%s'. Assuming system supports %d pids.", filename, pid_max);
1188 pid_max = (pid_t) max;
1191 #endif /* __APPLE__, __FreeBSD__ */
1195 void get_system_HZ(void) {
1198 if ((ticks = sysconf(_SC_CLK_TCK)) == -1) {
1199 error("Cannot get system clock ticks");
1202 hz = (unsigned int) ticks;
1206 // poor man cycle counting
1207 static unsigned long tsc;
1208 void begin_tsc(void) {
1210 asm volatile ("cpuid\nrdtsc" : "=a" (a), "=d" (d) : "0" (0) : "ebx", "ecx");
1211 tsc = ((unsigned long)d << 32) | (unsigned long)a;
1213 unsigned long end_tsc(void) {
1215 asm volatile ("rdtscp" : "=a" (a), "=d" (d) : : "ecx");
1216 return (((unsigned long)d << 32) | (unsigned long)a) - tsc;