3 char *global_host_prefix = "";
6 volatile sig_atomic_t netdata_exit = 0;
8 // ----------------------------------------------------------------------------
9 // memory allocation functions that handle failures
11 // although netdata does not use memory allocations too often (netdata tries to
12 // maintain its memory footprint stable during runtime, i.e. all buffers are
13 // allocated during initialization and are adapted to current use throughout
14 // its lifetime), these can be used to override the default system allocation
17 #ifdef NETDATA_LOG_ALLOCATIONS
18 static struct memory_statistics {
19 volatile size_t malloc_calls_made;
20 volatile size_t calloc_calls_made;
21 volatile size_t realloc_calls_made;
22 volatile size_t strdup_calls_made;
23 volatile size_t free_calls_made;
24 volatile size_t memory_calls_made;
25 volatile size_t allocated_memory;
26 volatile size_t mmapped_memory;
29 static inline void print_allocations(const char *file, const char *function, const unsigned long line) {
30 static struct memory_statistics old = { 0, 0, 0, 0, 0, 0, 0, 0 };
32 //if(unlikely(!(memory_statistics.memory_calls_made % 5))) {
33 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",
35 (memory_statistics.allocated_memory + 512) / 1024, memory_statistics.allocated_memory - old.allocated_memory,
36 (memory_statistics.mmapped_memory + 512) / 1024, memory_statistics.mmapped_memory - old.mmapped_memory,
37 memory_statistics.malloc_calls_made, memory_statistics.malloc_calls_made - old.malloc_calls_made,
38 memory_statistics.calloc_calls_made, memory_statistics.calloc_calls_made - old.calloc_calls_made,
39 memory_statistics.realloc_calls_made, memory_statistics.realloc_calls_made - old.realloc_calls_made,
40 memory_statistics.strdup_calls_made, memory_statistics.strdup_calls_made - old.strdup_calls_made,
41 memory_statistics.free_calls_made, memory_statistics.free_calls_made - old.free_calls_made
44 memcpy(&old, &memory_statistics, sizeof(struct memory_statistics));
48 static inline void malloc_accounting(const char *file, const char *function, const unsigned long line, size_t size) {
49 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
50 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
51 __atomic_fetch_add(&memory_statistics.malloc_calls_made, 1, __ATOMIC_SEQ_CST);
52 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
54 // this is for debugging - we don't care locking it
55 memory_statistics.memory_calls_made++;
56 memory_statistics.malloc_calls_made++;
57 memory_statistics.allocated_memory += size;
59 print_allocations(file, function, line);
62 static inline void mmap_accounting(size_t size) {
63 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
64 __atomic_fetch_add(&memory_statistics.malloc_calls_made, 1, __ATOMIC_SEQ_CST);
65 __atomic_fetch_add(&memory_statistics.mmapped_memory, size, __ATOMIC_SEQ_CST);
67 // this is for debugging - we don't care locking it
68 memory_statistics.memory_calls_made++;
69 memory_statistics.mmapped_memory += size;
73 static inline void calloc_accounting(const char *file, const char *function, const unsigned long line, size_t size) {
74 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
75 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
76 __atomic_fetch_add(&memory_statistics.calloc_calls_made, 1, __ATOMIC_SEQ_CST);
77 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
79 // this is for debugging - we don't care locking it
80 memory_statistics.memory_calls_made++;
81 memory_statistics.calloc_calls_made++;
82 memory_statistics.allocated_memory += size;
84 print_allocations(file, function, line);
87 static inline void realloc_accounting(const char *file, const char *function, const unsigned long line, void *ptr, size_t size) {
90 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
91 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
92 __atomic_fetch_add(&memory_statistics.realloc_calls_made, 1, __ATOMIC_SEQ_CST);
93 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
95 // this is for debugging - we don't care locking it
96 memory_statistics.memory_calls_made++;
97 memory_statistics.realloc_calls_made++;
98 memory_statistics.allocated_memory += size;
100 print_allocations(file, function, line);
103 static inline void strdup_accounting(const char *file, const char *function, const unsigned long line, const char *s) {
104 size_t size = strlen(s) + 1;
106 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
107 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
108 __atomic_fetch_add(&memory_statistics.strdup_calls_made, 1, __ATOMIC_SEQ_CST);
109 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
111 // this is for debugging - we don't care locking it
112 memory_statistics.memory_calls_made++;
113 memory_statistics.strdup_calls_made++;
114 memory_statistics.allocated_memory += size;
116 print_allocations(file, function, line);
119 static inline void free_accounting(const char *file, const char *function, const unsigned long line, void *ptr) {
125 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
126 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
127 __atomic_fetch_add(&memory_statistics.free_calls_made, 1, __ATOMIC_SEQ_CST);
129 // this is for debugging - we don't care locking it
130 memory_statistics.memory_calls_made++;
131 memory_statistics.free_calls_made++;
137 #ifdef NETDATA_LOG_ALLOCATIONS
138 char *strdupz_int(const char *file, const char *function, const unsigned long line, const char *s) {
139 strdup_accounting(file, function, line, s);
141 char *strdupz(const char *s) {
145 if (unlikely(!t)) fatal("Cannot strdup() string '%s'", s);
149 #ifdef NETDATA_LOG_ALLOCATIONS
150 void *mallocz_int(const char *file, const char *function, const unsigned long line, size_t size) {
151 malloc_accounting(file, function, line, size);
153 void *mallocz(size_t size) {
156 void *p = malloc(size);
157 if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", size);
161 #ifdef NETDATA_LOG_ALLOCATIONS
162 void *callocz_int(const char *file, const char *function, const unsigned long line, size_t nmemb, size_t size) {
163 calloc_accounting(file, function, line, nmemb * size);
165 void *callocz(size_t nmemb, size_t size) {
168 void *p = calloc(nmemb, size);
169 if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", nmemb * size);
173 #ifdef NETDATA_LOG_ALLOCATIONS
174 void *reallocz_int(const char *file, const char *function, const unsigned long line, void *ptr, size_t size) {
175 realloc_accounting(file, function, line, ptr, size);
177 void *reallocz(void *ptr, size_t size) {
180 void *p = realloc(ptr, size);
181 if (unlikely(!p)) fatal("Cannot re-allocate memory to %zu bytes.", size);
185 #ifdef NETDATA_LOG_ALLOCATIONS
186 void freez_int(const char *file, const char *function, const unsigned long line, void *ptr) {
187 free_accounting(file, function, line, ptr);
189 void freez(void *ptr) {
195 // ----------------------------------------------------------------------------
198 inline unsigned long long timeval_usec(struct timeval *tv) {
199 return tv->tv_sec * 1000000ULL + tv->tv_usec;
202 // time(NULL) in nanoseconds
203 inline unsigned long long time_usec(void) {
205 gettimeofday(&now, NULL);
206 return timeval_usec(&now);
209 inline unsigned long long usec_dt(struct timeval *now, struct timeval *old) {
210 unsigned long long tv1 = timeval_usec(now);
211 unsigned long long tv2 = timeval_usec(old);
212 return (tv1 > tv2) ? (tv1 - tv2) : (tv2 - tv1);
215 int sleep_usec(unsigned long long usec) {
217 #ifndef NETDATA_WITH_USLEEP
218 // we expect microseconds (1.000.000 per second)
219 // but timespec is nanoseconds (1.000.000.000 per second)
220 struct timespec rem, req = {
221 .tv_sec = (time_t) (usec / 1000000),
222 .tv_nsec = (suseconds_t) ((usec % 1000000) * 1000)
225 while (nanosleep(&req, &rem) == -1) {
226 if (likely(errno == EINTR)) {
227 debug(D_SYSTEM, "nanosleep() interrupted (while sleeping for %llu microseconds).", usec);
228 req.tv_sec = rem.tv_sec;
229 req.tv_nsec = rem.tv_nsec;
231 error("Cannot nanosleep() for %llu microseconds.", usec);
238 int ret = usleep(usec);
239 if(unlikely(ret == -1 && errno == EINVAL)) {
240 // on certain systems, usec has to be up to 999999
242 int counter = usec / 999999;
246 usleep(usec % 999999);
249 error("Cannot usleep() for %llu microseconds.", usec);
255 error("usleep() failed for %llu microseconds.", usec);
261 unsigned char netdata_map_chart_names[256] = {
354 [92] = '/', // backslash
520 // make sure the supplied string
521 // is good for a netdata chart/dimension ID/NAME
522 void netdata_fix_chart_name(char *s) {
523 while ((*s = netdata_map_chart_names[(unsigned char) *s])) s++;
526 unsigned char netdata_map_chart_ids[256] = {
619 [92] = '/', // backslash
785 // make sure the supplied string
786 // is good for a netdata chart/dimension ID/NAME
787 void netdata_fix_chart_id(char *s) {
788 while ((*s = netdata_map_chart_ids[(unsigned char) *s])) s++;
792 // http://stackoverflow.com/questions/7666509/hash-function-for-string
793 uint32_t simple_hash(const char *name)
795 const char *s = name;
796 uint32_t hash = 5381;
799 while((i = *s++)) hash = ((hash << 5) + hash) + i;
801 // fprintf(stderr, "HASH: %lu %s\n", hash, name);
808 // http://isthe.com/chongo/tech/comp/fnv/#FNV-1a
809 uint32_t simple_hash(const char *name) {
810 unsigned char *s = (unsigned char *) name;
811 uint32_t hval = 0x811c9dc5;
815 // multiply by the 32 bit FNV magic prime mod 2^32
816 // NOTE: No need to optimize with left shifts.
817 // GCC will use imul instruction anyway.
818 // Tested with 'gcc -O3 -S'
819 //hval += (hval<<1) + (hval<<4) + (hval<<7) + (hval<<8) + (hval<<24);
822 // xor the bottom with the current octet
823 hval ^= (uint32_t) *s++;
826 // fprintf(stderr, "HASH: %u = %s\n", hval, name);
830 uint32_t simple_uhash(const char *name) {
831 unsigned char *s = (unsigned char *) name;
832 uint32_t hval = 0x811c9dc5, c;
836 if (unlikely(c >= 'A' && c <= 'Z')) c += 'a' - 'A';
844 // http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
845 // one at a time hash
846 uint32_t simple_hash(const char *name) {
847 unsigned char *s = (unsigned char *)name;
860 // fprintf(stderr, "HASH: %u = %s\n", h, name);
866 void strreverse(char *begin, char *end) {
869 while (end > begin) {
877 char *mystrsep(char **ptr, char *s) {
879 while (p && !p[0] && *ptr) p = strsep(ptr, s);
883 char *trim(char *s) {
884 // skip leading spaces
885 // and 'comments' as well!?
886 while (*s && isspace(*s)) s++;
887 if (!*s || *s == '#') return NULL;
889 // skip tailing spaces
890 // this way is way faster. Writes only one NUL char.
891 ssize_t l = strlen(s);
894 while (p > s && isspace(*p)) p--;
898 if (!*s) return NULL;
903 void *mymmap(const char *filename, size_t size, int flags, int ksm) {
904 static int log_madvise_1 = 1;
905 #ifdef MADV_MERGEABLE
906 static int log_madvise_2 = 1, log_madvise_3 = 1;
912 fd = open(filename, O_RDWR | O_CREAT | O_NOATIME, 0664);
914 if (lseek(fd, size, SEEK_SET) == (off_t) size) {
915 if (write(fd, "", 1) == 1) {
916 if (ftruncate(fd, size))
917 error("Cannot truncate file '%s' to size %zu. Will use the larger file.", filename, size);
919 #ifdef MADV_MERGEABLE
920 if (flags & MAP_SHARED || !enable_ksm || !ksm) {
922 mem = mmap(NULL, size, PROT_READ | PROT_WRITE, flags, fd, 0);
923 if (mem == MAP_FAILED) {
924 error("Cannot allocate SHARED memory for file '%s'.", filename);
928 #ifdef NETDATA_LOG_ALLOCATIONS
929 mmap_accounting(size);
931 int advise = MADV_SEQUENTIAL | MADV_DONTFORK;
932 if (flags & MAP_SHARED) advise |= MADV_WILLNEED;
934 if (madvise(mem, size, advise) != 0 && log_madvise_1) {
935 error("Cannot advise the kernel about the memory usage of file '%s'.", filename);
939 #ifdef MADV_MERGEABLE
943 // test - load the file into memory
944 mem = calloc(1, size);
946 if(lseek(fd, 0, SEEK_SET) == 0) {
947 if(read(fd, mem, size) != (ssize_t)size)
948 error("Cannot read from file '%s'", filename);
951 error("Cannot seek to beginning of file '%s'.", filename);
954 mem = mmap(NULL, size, PROT_READ | PROT_WRITE, flags | MAP_ANONYMOUS, -1, 0);
955 if (mem == MAP_FAILED) {
956 error("Cannot allocate PRIVATE ANONYMOUS memory for KSM for file '%s'.", filename);
960 #ifdef NETDATA_LOG_ALLOCATIONS
961 mmap_accounting(size);
963 if (lseek(fd, 0, SEEK_SET) == 0) {
964 if (read(fd, mem, size) != (ssize_t) size)
965 error("Cannot read from file '%s'", filename);
967 error("Cannot seek to beginning of file '%s'.", filename);
969 // don't use MADV_SEQUENTIAL|MADV_DONTFORK, they disable MADV_MERGEABLE
970 if (madvise(mem, size, MADV_SEQUENTIAL | MADV_DONTFORK) != 0 && log_madvise_2) {
971 error("Cannot advise the kernel about the memory usage (MADV_SEQUENTIAL|MADV_DONTFORK) of file '%s'.",
976 if (madvise(mem, size, MADV_MERGEABLE) != 0 && log_madvise_3) {
977 error("Cannot advise the kernel about the memory usage (MADV_MERGEABLE) of file '%s'.",
986 error("Cannot write to file '%s' at position %zu.", filename, size);
989 error("Cannot seek file '%s' to size %zu.", filename, size);
994 error("Cannot create/open file '%s'.", filename);
999 int savememory(const char *filename, void *mem, size_t size) {
1000 char tmpfilename[FILENAME_MAX + 1];
1002 snprintfz(tmpfilename, FILENAME_MAX, "%s.%ld.tmp", filename, (long) getpid());
1004 int fd = open(tmpfilename, O_RDWR | O_CREAT | O_NOATIME, 0664);
1006 error("Cannot create/open file '%s'.", filename);
1010 if (write(fd, mem, size) != (ssize_t) size) {
1011 error("Cannot write to file '%s' %ld bytes.", filename, (long) size);
1018 if (rename(tmpfilename, filename)) {
1019 error("Cannot rename '%s' to '%s'", tmpfilename, filename);
1026 int fd_is_valid(int fd) {
1027 return fcntl(fd, F_GETFD) != -1 || errno != EBADF;
1030 pid_t gettid(void) {
1031 return (pid_t)syscall(SYS_gettid);
1034 char *fgets_trim_len(char *buf, size_t buf_size, FILE *fp, size_t *len) {
1035 char *s = fgets(buf, (int)buf_size, fp);
1036 if (!s) return NULL;
1040 // find the string end
1041 while (*++t != '\0');
1043 // trim trailing spaces/newlines/tabs
1044 while (--t > s && *t == '\n')
1054 char *strncpyz(char *dst, const char *src, size_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) {
1093 procfile *ff = NULL;
1097 char filename[FILENAME_MAX + 1];
1098 snprintfz(filename, FILENAME_MAX, "%s/proc/stat", global_host_prefix);
1100 ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);
1102 error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);
1106 ff = procfile_readall(ff);
1108 error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);
1114 for(i = 0; i < procfile_lines(ff); i++) {
1115 if(!procfile_linewords(ff, i)) continue;
1117 if(strncmp(procfile_lineword(ff, i, 0), "cpu", 3) == 0) processors++;
1120 if(processors < 1) processors = 1;
1124 debug(D_SYSTEM, "System has %d processors.", processors);
1128 pid_t pid_max = 32768;
1129 pid_t get_system_pid_max(void) {
1130 procfile *ff = NULL;
1132 char filename[FILENAME_MAX + 1];
1133 snprintfz(filename, FILENAME_MAX, "%s/proc/sys/kernel/pid_max", global_host_prefix);
1134 ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);
1136 error("Cannot open file '%s'. Assuming system supports %d pids.", filename, pid_max);
1140 ff = procfile_readall(ff);
1142 error("Cannot read file '%s'. Assuming system supports %d pids.", filename, pid_max);
1146 pid_max = (pid_t)atoi(procfile_lineword(ff, 0, 0));
1150 error("Cannot parse file '%s'. Assuming system supports %d pids.", filename, pid_max);
1155 debug(D_SYSTEM, "System supports %d pids.", pid_max);
1160 void get_system_HZ(void) {
1163 if ((ticks = sysconf(_SC_CLK_TCK)) == -1) {
1167 hz = (unsigned int) ticks;
1170 int read_single_number_file(const char *filename, unsigned long long *result) {
1171 char buffer[1024 + 1];
1173 int fd = open(filename, O_RDONLY, 0666);
1174 if(unlikely(fd == -1)) return 1;
1176 ssize_t r = read(fd, buffer, 1024);
1177 if(unlikely(r == -1)) {
1183 *result = strtoull(buffer, NULL, 0);