6 # define MADV_DONTFORK INHERIT_NONE
7 #endif /* __FreeBSD__ */
9 char *global_host_prefix = "";
12 volatile sig_atomic_t netdata_exit = 0;
14 // ----------------------------------------------------------------------------
15 // memory allocation functions that handle failures
17 // although netdata does not use memory allocations too often (netdata tries to
18 // maintain its memory footprint stable during runtime, i.e. all buffers are
19 // allocated during initialization and are adapted to current use throughout
20 // its lifetime), these can be used to override the default system allocation
23 #ifdef NETDATA_LOG_ALLOCATIONS
24 static struct memory_statistics {
25 volatile size_t malloc_calls_made;
26 volatile size_t calloc_calls_made;
27 volatile size_t realloc_calls_made;
28 volatile size_t strdup_calls_made;
29 volatile size_t free_calls_made;
30 volatile size_t memory_calls_made;
31 volatile size_t allocated_memory;
32 volatile size_t mmapped_memory;
35 static inline void print_allocations(const char *file, const char *function, const unsigned long line) {
36 static struct memory_statistics old = { 0, 0, 0, 0, 0, 0, 0, 0 };
38 //if(unlikely(!(memory_statistics.memory_calls_made % 5))) {
39 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",
41 (memory_statistics.allocated_memory + 512) / 1024, memory_statistics.allocated_memory - old.allocated_memory,
42 (memory_statistics.mmapped_memory + 512) / 1024, memory_statistics.mmapped_memory - old.mmapped_memory,
43 memory_statistics.malloc_calls_made, memory_statistics.malloc_calls_made - old.malloc_calls_made,
44 memory_statistics.calloc_calls_made, memory_statistics.calloc_calls_made - old.calloc_calls_made,
45 memory_statistics.realloc_calls_made, memory_statistics.realloc_calls_made - old.realloc_calls_made,
46 memory_statistics.strdup_calls_made, memory_statistics.strdup_calls_made - old.strdup_calls_made,
47 memory_statistics.free_calls_made, memory_statistics.free_calls_made - old.free_calls_made
50 memcpy(&old, &memory_statistics, sizeof(struct memory_statistics));
54 static inline void malloc_accounting(const char *file, const char *function, const unsigned long line, size_t size) {
55 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
56 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
57 __atomic_fetch_add(&memory_statistics.malloc_calls_made, 1, __ATOMIC_SEQ_CST);
58 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
60 // this is for debugging - we don't care locking it
61 memory_statistics.memory_calls_made++;
62 memory_statistics.malloc_calls_made++;
63 memory_statistics.allocated_memory += size;
65 print_allocations(file, function, line);
68 static inline void mmap_accounting(size_t size) {
69 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
70 __atomic_fetch_add(&memory_statistics.malloc_calls_made, 1, __ATOMIC_SEQ_CST);
71 __atomic_fetch_add(&memory_statistics.mmapped_memory, size, __ATOMIC_SEQ_CST);
73 // this is for debugging - we don't care locking it
74 memory_statistics.memory_calls_made++;
75 memory_statistics.mmapped_memory += size;
79 static inline void calloc_accounting(const char *file, const char *function, const unsigned long line, size_t size) {
80 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
81 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
82 __atomic_fetch_add(&memory_statistics.calloc_calls_made, 1, __ATOMIC_SEQ_CST);
83 __atomic_fetch_add(&memory_statistics.allocated_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.calloc_calls_made++;
88 memory_statistics.allocated_memory += size;
90 print_allocations(file, function, line);
93 static inline void realloc_accounting(const char *file, const char *function, const unsigned long line, void *ptr, size_t size) {
96 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
97 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
98 __atomic_fetch_add(&memory_statistics.realloc_calls_made, 1, __ATOMIC_SEQ_CST);
99 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
101 // this is for debugging - we don't care locking it
102 memory_statistics.memory_calls_made++;
103 memory_statistics.realloc_calls_made++;
104 memory_statistics.allocated_memory += size;
106 print_allocations(file, function, line);
109 static inline void strdup_accounting(const char *file, const char *function, const unsigned long line, const char *s) {
110 size_t size = strlen(s) + 1;
112 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
113 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
114 __atomic_fetch_add(&memory_statistics.strdup_calls_made, 1, __ATOMIC_SEQ_CST);
115 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
117 // this is for debugging - we don't care locking it
118 memory_statistics.memory_calls_made++;
119 memory_statistics.strdup_calls_made++;
120 memory_statistics.allocated_memory += size;
122 print_allocations(file, function, line);
125 static inline void free_accounting(const char *file, const char *function, const unsigned long line, void *ptr) {
131 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
132 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
133 __atomic_fetch_add(&memory_statistics.free_calls_made, 1, __ATOMIC_SEQ_CST);
135 // this is for debugging - we don't care locking it
136 memory_statistics.memory_calls_made++;
137 memory_statistics.free_calls_made++;
143 #ifdef NETDATA_LOG_ALLOCATIONS
144 char *strdupz_int(const char *file, const char *function, const unsigned long line, const char *s) {
145 strdup_accounting(file, function, line, s);
147 char *strdupz(const char *s) {
151 if (unlikely(!t)) fatal("Cannot strdup() string '%s'", s);
155 #ifdef NETDATA_LOG_ALLOCATIONS
156 void *mallocz_int(const char *file, const char *function, const unsigned long line, size_t size) {
157 malloc_accounting(file, function, line, size);
159 void *mallocz(size_t size) {
162 void *p = malloc(size);
163 if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", size);
167 #ifdef NETDATA_LOG_ALLOCATIONS
168 void *callocz_int(const char *file, const char *function, const unsigned long line, size_t nmemb, size_t size) {
169 calloc_accounting(file, function, line, nmemb * size);
171 void *callocz(size_t nmemb, size_t size) {
174 void *p = calloc(nmemb, size);
175 if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", nmemb * size);
179 #ifdef NETDATA_LOG_ALLOCATIONS
180 void *reallocz_int(const char *file, const char *function, const unsigned long line, void *ptr, size_t size) {
181 realloc_accounting(file, function, line, ptr, size);
183 void *reallocz(void *ptr, size_t size) {
186 void *p = realloc(ptr, size);
187 if (unlikely(!p)) fatal("Cannot re-allocate memory to %zu bytes.", size);
191 #ifdef NETDATA_LOG_ALLOCATIONS
192 void freez_int(const char *file, const char *function, const unsigned long line, void *ptr) {
193 free_accounting(file, function, line, ptr);
195 void freez(void *ptr) {
201 // ----------------------------------------------------------------------------
204 inline unsigned long long timeval_usec(struct timeval *tv) {
205 return tv->tv_sec * 1000000ULL + tv->tv_usec;
208 // time(NULL) in nanoseconds
209 inline unsigned long long time_usec(void) {
211 gettimeofday(&now, NULL);
212 return timeval_usec(&now);
215 inline unsigned long long usec_dt(struct timeval *now, struct timeval *old) {
216 unsigned long long tv1 = timeval_usec(now);
217 unsigned long long tv2 = timeval_usec(old);
218 return (tv1 > tv2) ? (tv1 - tv2) : (tv2 - tv1);
221 int sleep_usec(unsigned long long usec) {
223 #ifndef NETDATA_WITH_USLEEP
224 // we expect microseconds (1.000.000 per second)
225 // but timespec is nanoseconds (1.000.000.000 per second)
226 struct timespec rem, req = {
227 .tv_sec = (time_t) (usec / 1000000),
228 .tv_nsec = (suseconds_t) ((usec % 1000000) * 1000)
231 while (nanosleep(&req, &rem) == -1) {
232 if (likely(errno == EINTR)) {
233 debug(D_SYSTEM, "nanosleep() interrupted (while sleeping for %llu microseconds).", usec);
234 req.tv_sec = rem.tv_sec;
235 req.tv_nsec = rem.tv_nsec;
237 error("Cannot nanosleep() for %llu microseconds.", usec);
244 int ret = usleep(usec);
245 if(unlikely(ret == -1 && errno == EINVAL)) {
246 // on certain systems, usec has to be up to 999999
248 int counter = usec / 999999;
252 usleep(usec % 999999);
255 error("Cannot usleep() for %llu microseconds.", usec);
261 error("usleep() failed for %llu microseconds.", usec);
267 unsigned char netdata_map_chart_names[256] = {
360 [92] = '/', // backslash
526 // make sure the supplied string
527 // is good for a netdata chart/dimension ID/NAME
528 void netdata_fix_chart_name(char *s) {
529 while ((*s = netdata_map_chart_names[(unsigned char) *s])) s++;
532 unsigned char netdata_map_chart_ids[256] = {
625 [92] = '/', // backslash
791 // make sure the supplied string
792 // is good for a netdata chart/dimension ID/NAME
793 void netdata_fix_chart_id(char *s) {
794 while ((*s = netdata_map_chart_ids[(unsigned char) *s])) s++;
798 // http://stackoverflow.com/questions/7666509/hash-function-for-string
799 uint32_t simple_hash(const char *name)
801 const char *s = name;
802 uint32_t hash = 5381;
805 while((i = *s++)) hash = ((hash << 5) + hash) + i;
807 // fprintf(stderr, "HASH: %lu %s\n", hash, name);
814 // http://isthe.com/chongo/tech/comp/fnv/#FNV-1a
815 uint32_t simple_hash(const char *name) {
816 unsigned char *s = (unsigned char *) name;
817 uint32_t hval = 0x811c9dc5;
821 // multiply by the 32 bit FNV magic prime mod 2^32
822 // NOTE: No need to optimize with left shifts.
823 // GCC will use imul instruction anyway.
824 // Tested with 'gcc -O3 -S'
825 //hval += (hval<<1) + (hval<<4) + (hval<<7) + (hval<<8) + (hval<<24);
828 // xor the bottom with the current octet
829 hval ^= (uint32_t) *s++;
832 // fprintf(stderr, "HASH: %u = %s\n", hval, name);
836 uint32_t simple_uhash(const char *name) {
837 unsigned char *s = (unsigned char *) name;
838 uint32_t hval = 0x811c9dc5, c;
842 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) {
1037 return (unsigned) pid;
1038 #else /* __FreeBSD__ */
1039 return (pid_t)syscall(SYS_gettid);
1040 #endif /* __FreeBSD__ */
1043 char *fgets_trim_len(char *buf, size_t buf_size, FILE *fp, size_t *len) {
1044 char *s = fgets(buf, (int)buf_size, fp);
1045 if (!s) return NULL;
1049 // find the string end
1050 while (*++t != '\0');
1052 // trim trailing spaces/newlines/tabs
1053 while (--t > s && *t == '\n')
1063 char *strncpyz(char *dst, const char *src, size_t n) {
1074 int vsnprintfz(char *dst, size_t n, const char *fmt, va_list args) {
1075 int size = vsnprintf(dst, n, fmt, args);
1077 if (unlikely((size_t) size > n)) {
1086 int snprintfz(char *dst, size_t n, const char *fmt, ...) {
1089 va_start(args, fmt);
1090 int ret = vsnprintfz(dst, n, fmt, args);
1096 // ----------------------------------------------------------------------------
1098 // to retrieve settings of the system
1101 long get_system_cpus(void) {
1104 char filename[FILENAME_MAX + 1];
1105 snprintfz(filename, FILENAME_MAX, "%s/proc/stat", global_host_prefix);
1107 procfile *ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);
1109 error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);
1113 ff = procfile_readall(ff);
1115 error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);
1121 for(i = 0; i < procfile_lines(ff); i++) {
1122 if(!procfile_linewords(ff, i)) continue;
1124 if(strncmp(procfile_lineword(ff, i, 0), "cpu", 3) == 0) processors++;
1127 if(processors < 1) processors = 1;
1131 debug(D_SYSTEM, "System has %d processors.", processors);
1135 pid_t pid_max = 32768;
1136 pid_t get_system_pid_max(void) {
1137 char filename[FILENAME_MAX + 1];
1138 snprintfz(filename, FILENAME_MAX, "%s/proc/sys/kernel/pid_max", global_host_prefix);
1139 procfile *ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);
1141 error("Cannot open file '%s'. Assuming system supports %d pids.", filename, pid_max);
1145 ff = procfile_readall(ff);
1147 error("Cannot read file '%s'. Assuming system supports %d pids.", filename, pid_max);
1151 pid_max = (pid_t)atoi(procfile_lineword(ff, 0, 0));
1155 error("Cannot parse file '%s'. Assuming system supports %d pids.", filename, pid_max);
1160 debug(D_SYSTEM, "System supports %d pids.", pid_max);
1165 void get_system_HZ(void) {
1168 if ((ticks = sysconf(_SC_CLK_TCK)) == -1) {
1172 hz = (unsigned int) ticks;
1175 int read_single_number_file(const char *filename, unsigned long long *result) {
1176 char buffer[1024 + 1];
1178 int fd = open(filename, O_RDONLY, 0666);
1179 if(unlikely(fd == -1)) return 1;
1181 ssize_t r = read(fd, buffer, 1024);
1182 if(unlikely(r == -1)) {
1188 *result = strtoull(buffer, NULL, 0);