]> arthur.barton.de Git - netdata.git/blob - src/common.c
Add version to api/v1/charts
[netdata.git] / src / common.c
1 #include "common.h"
2
3 #ifdef __APPLE__
4 #define INHERIT_NONE 0
5 #endif /* __APPLE__ */
6 #if defined(__FreeBSD__) || defined(__APPLE__)
7 #    define O_NOATIME     0
8 #    define MADV_DONTFORK INHERIT_NONE
9 #endif /* __FreeBSD__ || __APPLE__*/
10
11 char *global_host_prefix = "";
12 int enable_ksm = 1;
13
14 volatile sig_atomic_t netdata_exit = 0;
15 const char *os_type = NETDATA_OS_TYPE;
16 const char *program_version = VERSION;
17
18 // ----------------------------------------------------------------------------
19 // memory allocation functions that handle failures
20
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
25 // routines.
26
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;
37 } memory_statistics;
38
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 };
41
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",
44                 line, file, function,
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
52         );
53
54         memcpy(&old, &memory_statistics, sizeof(struct memory_statistics));
55     //}
56 }
57
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);
63 #else
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;
68 #endif
69     print_allocations(file, function, line);
70 }
71
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);
76 #else
77     // this is for debugging - we don't care locking it
78     memory_statistics.memory_calls_made++;
79     memory_statistics.mmapped_memory += size;
80 #endif
81 }
82
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);
88 #else
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;
93 #endif
94     print_allocations(file, function, line);
95 }
96
97 static inline void realloc_accounting(const char *file, const char *function, const unsigned long line, void *ptr, size_t size) {
98     (void)ptr;
99
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);
104 #else
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;
109 #endif
110     print_allocations(file, function, line);
111 }
112
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;
115
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);
120 #else
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;
125 #endif
126     print_allocations(file, function, line);
127 }
128
129 static inline void free_accounting(const char *file, const char *function, const unsigned long line, void *ptr) {
130     (void)file;
131     (void)function;
132     (void)line;
133
134     if(likely(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);
138 #else
139         // this is for debugging - we don't care locking it
140         memory_statistics.memory_calls_made++;
141         memory_statistics.free_calls_made++;
142 #endif
143     }
144 }
145 #endif
146
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);
150 #else
151 char *strdupz(const char *s) {
152 #endif
153
154     char *t = strdup(s);
155     if (unlikely(!t)) fatal("Cannot strdup() string '%s'", s);
156     return t;
157 }
158
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);
162 #else
163 void *mallocz(size_t size) {
164 #endif
165
166     void *p = malloc(size);
167     if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", size);
168     return p;
169 }
170
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);
174 #else
175 void *callocz(size_t nmemb, size_t size) {
176 #endif
177
178     void *p = calloc(nmemb, size);
179     if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", nmemb * size);
180     return p;
181 }
182
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);
186 #else
187 void *reallocz(void *ptr, size_t size) {
188 #endif
189
190     void *p = realloc(ptr, size);
191     if (unlikely(!p)) fatal("Cannot re-allocate memory to %zu bytes.", size);
192     return p;
193 }
194
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);
198 #else
199 void freez(void *ptr) {
200 #endif
201
202     free(ptr);
203 }
204
205 void json_escape_string(char *dst, const char *src, size_t size) {
206     const char *t;
207     char *d = dst, *e = &dst[size - 1];
208
209     for(t = src; *t && d < e ;t++) {
210         if(unlikely(*t == '\\' || *t == '"')) {
211             if(unlikely(d + 1 >= e)) break;
212             *d++ = '\\';
213         }
214         *d++ = *t;
215     }
216
217     *d = '\0';
218 }
219
220 int sleep_usec(usec_t usec) {
221
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)
228     };
229
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;
235         } else {
236             error("Cannot nanosleep() for %llu microseconds.", usec);
237             break;
238         }
239     }
240
241     return 0;
242 #else
243     int ret = usleep(usec);
244     if(unlikely(ret == -1 && errno == EINVAL)) {
245         // on certain systems, usec has to be up to 999999
246         if(usec > 999999) {
247             int counter = usec / 999999;
248             while(counter--)
249                 usleep(999999);
250
251             usleep(usec % 999999);
252         }
253         else {
254             error("Cannot usleep() for %llu microseconds.", usec);
255             return ret;
256         }
257     }
258
259     if(ret != 0)
260         error("usleep() failed for %llu microseconds.", usec);
261
262     return ret;
263 #endif
264 }
265
266 unsigned char netdata_map_chart_names[256] = {
267         [0] = '\0', //
268         [1] = '_', //
269         [2] = '_', //
270         [3] = '_', //
271         [4] = '_', //
272         [5] = '_', //
273         [6] = '_', //
274         [7] = '_', //
275         [8] = '_', //
276         [9] = '_', //
277         [10] = '_', //
278         [11] = '_', //
279         [12] = '_', //
280         [13] = '_', //
281         [14] = '_', //
282         [15] = '_', //
283         [16] = '_', //
284         [17] = '_', //
285         [18] = '_', //
286         [19] = '_', //
287         [20] = '_', //
288         [21] = '_', //
289         [22] = '_', //
290         [23] = '_', //
291         [24] = '_', //
292         [25] = '_', //
293         [26] = '_', //
294         [27] = '_', //
295         [28] = '_', //
296         [29] = '_', //
297         [30] = '_', //
298         [31] = '_', //
299         [32] = '_', //
300         [33] = '_', // !
301         [34] = '_', // "
302         [35] = '_', // #
303         [36] = '_', // $
304         [37] = '_', // %
305         [38] = '_', // &
306         [39] = '_', // '
307         [40] = '_', // (
308         [41] = '_', // )
309         [42] = '_', // *
310         [43] = '_', // +
311         [44] = '.', // ,
312         [45] = '-', // -
313         [46] = '.', // .
314         [47] = '/', // /
315         [48] = '0', // 0
316         [49] = '1', // 1
317         [50] = '2', // 2
318         [51] = '3', // 3
319         [52] = '4', // 4
320         [53] = '5', // 5
321         [54] = '6', // 6
322         [55] = '7', // 7
323         [56] = '8', // 8
324         [57] = '9', // 9
325         [58] = '_', // :
326         [59] = '_', // ;
327         [60] = '_', // <
328         [61] = '_', // =
329         [62] = '_', // >
330         [63] = '_', // ?
331         [64] = '_', // @
332         [65] = 'a', // A
333         [66] = 'b', // B
334         [67] = 'c', // C
335         [68] = 'd', // D
336         [69] = 'e', // E
337         [70] = 'f', // F
338         [71] = 'g', // G
339         [72] = 'h', // H
340         [73] = 'i', // I
341         [74] = 'j', // J
342         [75] = 'k', // K
343         [76] = 'l', // L
344         [77] = 'm', // M
345         [78] = 'n', // N
346         [79] = 'o', // O
347         [80] = 'p', // P
348         [81] = 'q', // Q
349         [82] = 'r', // R
350         [83] = 's', // S
351         [84] = 't', // T
352         [85] = 'u', // U
353         [86] = 'v', // V
354         [87] = 'w', // W
355         [88] = 'x', // X
356         [89] = 'y', // Y
357         [90] = 'z', // Z
358         [91] = '_', // [
359         [92] = '/', // backslash
360         [93] = '_', // ]
361         [94] = '_', // ^
362         [95] = '_', // _
363         [96] = '_', // `
364         [97] = 'a', // a
365         [98] = 'b', // b
366         [99] = 'c', // c
367         [100] = 'd', // d
368         [101] = 'e', // e
369         [102] = 'f', // f
370         [103] = 'g', // g
371         [104] = 'h', // h
372         [105] = 'i', // i
373         [106] = 'j', // j
374         [107] = 'k', // k
375         [108] = 'l', // l
376         [109] = 'm', // m
377         [110] = 'n', // n
378         [111] = 'o', // o
379         [112] = 'p', // p
380         [113] = 'q', // q
381         [114] = 'r', // r
382         [115] = 's', // s
383         [116] = 't', // t
384         [117] = 'u', // u
385         [118] = 'v', // v
386         [119] = 'w', // w
387         [120] = 'x', // x
388         [121] = 'y', // y
389         [122] = 'z', // z
390         [123] = '_', // {
391         [124] = '_', // |
392         [125] = '_', // }
393         [126] = '_', // ~
394         [127] = '_', //
395         [128] = '_', //
396         [129] = '_', //
397         [130] = '_', //
398         [131] = '_', //
399         [132] = '_', //
400         [133] = '_', //
401         [134] = '_', //
402         [135] = '_', //
403         [136] = '_', //
404         [137] = '_', //
405         [138] = '_', //
406         [139] = '_', //
407         [140] = '_', //
408         [141] = '_', //
409         [142] = '_', //
410         [143] = '_', //
411         [144] = '_', //
412         [145] = '_', //
413         [146] = '_', //
414         [147] = '_', //
415         [148] = '_', //
416         [149] = '_', //
417         [150] = '_', //
418         [151] = '_', //
419         [152] = '_', //
420         [153] = '_', //
421         [154] = '_', //
422         [155] = '_', //
423         [156] = '_', //
424         [157] = '_', //
425         [158] = '_', //
426         [159] = '_', //
427         [160] = '_', //
428         [161] = '_', //
429         [162] = '_', //
430         [163] = '_', //
431         [164] = '_', //
432         [165] = '_', //
433         [166] = '_', //
434         [167] = '_', //
435         [168] = '_', //
436         [169] = '_', //
437         [170] = '_', //
438         [171] = '_', //
439         [172] = '_', //
440         [173] = '_', //
441         [174] = '_', //
442         [175] = '_', //
443         [176] = '_', //
444         [177] = '_', //
445         [178] = '_', //
446         [179] = '_', //
447         [180] = '_', //
448         [181] = '_', //
449         [182] = '_', //
450         [183] = '_', //
451         [184] = '_', //
452         [185] = '_', //
453         [186] = '_', //
454         [187] = '_', //
455         [188] = '_', //
456         [189] = '_', //
457         [190] = '_', //
458         [191] = '_', //
459         [192] = '_', //
460         [193] = '_', //
461         [194] = '_', //
462         [195] = '_', //
463         [196] = '_', //
464         [197] = '_', //
465         [198] = '_', //
466         [199] = '_', //
467         [200] = '_', //
468         [201] = '_', //
469         [202] = '_', //
470         [203] = '_', //
471         [204] = '_', //
472         [205] = '_', //
473         [206] = '_', //
474         [207] = '_', //
475         [208] = '_', //
476         [209] = '_', //
477         [210] = '_', //
478         [211] = '_', //
479         [212] = '_', //
480         [213] = '_', //
481         [214] = '_', //
482         [215] = '_', //
483         [216] = '_', //
484         [217] = '_', //
485         [218] = '_', //
486         [219] = '_', //
487         [220] = '_', //
488         [221] = '_', //
489         [222] = '_', //
490         [223] = '_', //
491         [224] = '_', //
492         [225] = '_', //
493         [226] = '_', //
494         [227] = '_', //
495         [228] = '_', //
496         [229] = '_', //
497         [230] = '_', //
498         [231] = '_', //
499         [232] = '_', //
500         [233] = '_', //
501         [234] = '_', //
502         [235] = '_', //
503         [236] = '_', //
504         [237] = '_', //
505         [238] = '_', //
506         [239] = '_', //
507         [240] = '_', //
508         [241] = '_', //
509         [242] = '_', //
510         [243] = '_', //
511         [244] = '_', //
512         [245] = '_', //
513         [246] = '_', //
514         [247] = '_', //
515         [248] = '_', //
516         [249] = '_', //
517         [250] = '_', //
518         [251] = '_', //
519         [252] = '_', //
520         [253] = '_', //
521         [254] = '_', //
522         [255] = '_'  //
523 };
524
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++;
529 }
530
531 unsigned char netdata_map_chart_ids[256] = {
532         [0] = '\0', //
533         [1] = '_', //
534         [2] = '_', //
535         [3] = '_', //
536         [4] = '_', //
537         [5] = '_', //
538         [6] = '_', //
539         [7] = '_', //
540         [8] = '_', //
541         [9] = '_', //
542         [10] = '_', //
543         [11] = '_', //
544         [12] = '_', //
545         [13] = '_', //
546         [14] = '_', //
547         [15] = '_', //
548         [16] = '_', //
549         [17] = '_', //
550         [18] = '_', //
551         [19] = '_', //
552         [20] = '_', //
553         [21] = '_', //
554         [22] = '_', //
555         [23] = '_', //
556         [24] = '_', //
557         [25] = '_', //
558         [26] = '_', //
559         [27] = '_', //
560         [28] = '_', //
561         [29] = '_', //
562         [30] = '_', //
563         [31] = '_', //
564         [32] = '_', //
565         [33] = '_', // !
566         [34] = '_', // "
567         [35] = '_', // #
568         [36] = '_', // $
569         [37] = '_', // %
570         [38] = '_', // &
571         [39] = '_', // '
572         [40] = '_', // (
573         [41] = '_', // )
574         [42] = '_', // *
575         [43] = '_', // +
576         [44] = '.', // ,
577         [45] = '-', // -
578         [46] = '.', // .
579         [47] = '_', // /
580         [48] = '0', // 0
581         [49] = '1', // 1
582         [50] = '2', // 2
583         [51] = '3', // 3
584         [52] = '4', // 4
585         [53] = '5', // 5
586         [54] = '6', // 6
587         [55] = '7', // 7
588         [56] = '8', // 8
589         [57] = '9', // 9
590         [58] = '_', // :
591         [59] = '_', // ;
592         [60] = '_', // <
593         [61] = '_', // =
594         [62] = '_', // >
595         [63] = '_', // ?
596         [64] = '_', // @
597         [65] = 'a', // A
598         [66] = 'b', // B
599         [67] = 'c', // C
600         [68] = 'd', // D
601         [69] = 'e', // E
602         [70] = 'f', // F
603         [71] = 'g', // G
604         [72] = 'h', // H
605         [73] = 'i', // I
606         [74] = 'j', // J
607         [75] = 'k', // K
608         [76] = 'l', // L
609         [77] = 'm', // M
610         [78] = 'n', // N
611         [79] = 'o', // O
612         [80] = 'p', // P
613         [81] = 'q', // Q
614         [82] = 'r', // R
615         [83] = 's', // S
616         [84] = 't', // T
617         [85] = 'u', // U
618         [86] = 'v', // V
619         [87] = 'w', // W
620         [88] = 'x', // X
621         [89] = 'y', // Y
622         [90] = 'z', // Z
623         [91] = '_', // [
624         [92] = '/', // backslash
625         [93] = '_', // ]
626         [94] = '_', // ^
627         [95] = '_', // _
628         [96] = '_', // `
629         [97] = 'a', // a
630         [98] = 'b', // b
631         [99] = 'c', // c
632         [100] = 'd', // d
633         [101] = 'e', // e
634         [102] = 'f', // f
635         [103] = 'g', // g
636         [104] = 'h', // h
637         [105] = 'i', // i
638         [106] = 'j', // j
639         [107] = 'k', // k
640         [108] = 'l', // l
641         [109] = 'm', // m
642         [110] = 'n', // n
643         [111] = 'o', // o
644         [112] = 'p', // p
645         [113] = 'q', // q
646         [114] = 'r', // r
647         [115] = 's', // s
648         [116] = 't', // t
649         [117] = 'u', // u
650         [118] = 'v', // v
651         [119] = 'w', // w
652         [120] = 'x', // x
653         [121] = 'y', // y
654         [122] = 'z', // z
655         [123] = '_', // {
656         [124] = '_', // |
657         [125] = '_', // }
658         [126] = '_', // ~
659         [127] = '_', //
660         [128] = '_', //
661         [129] = '_', //
662         [130] = '_', //
663         [131] = '_', //
664         [132] = '_', //
665         [133] = '_', //
666         [134] = '_', //
667         [135] = '_', //
668         [136] = '_', //
669         [137] = '_', //
670         [138] = '_', //
671         [139] = '_', //
672         [140] = '_', //
673         [141] = '_', //
674         [142] = '_', //
675         [143] = '_', //
676         [144] = '_', //
677         [145] = '_', //
678         [146] = '_', //
679         [147] = '_', //
680         [148] = '_', //
681         [149] = '_', //
682         [150] = '_', //
683         [151] = '_', //
684         [152] = '_', //
685         [153] = '_', //
686         [154] = '_', //
687         [155] = '_', //
688         [156] = '_', //
689         [157] = '_', //
690         [158] = '_', //
691         [159] = '_', //
692         [160] = '_', //
693         [161] = '_', //
694         [162] = '_', //
695         [163] = '_', //
696         [164] = '_', //
697         [165] = '_', //
698         [166] = '_', //
699         [167] = '_', //
700         [168] = '_', //
701         [169] = '_', //
702         [170] = '_', //
703         [171] = '_', //
704         [172] = '_', //
705         [173] = '_', //
706         [174] = '_', //
707         [175] = '_', //
708         [176] = '_', //
709         [177] = '_', //
710         [178] = '_', //
711         [179] = '_', //
712         [180] = '_', //
713         [181] = '_', //
714         [182] = '_', //
715         [183] = '_', //
716         [184] = '_', //
717         [185] = '_', //
718         [186] = '_', //
719         [187] = '_', //
720         [188] = '_', //
721         [189] = '_', //
722         [190] = '_', //
723         [191] = '_', //
724         [192] = '_', //
725         [193] = '_', //
726         [194] = '_', //
727         [195] = '_', //
728         [196] = '_', //
729         [197] = '_', //
730         [198] = '_', //
731         [199] = '_', //
732         [200] = '_', //
733         [201] = '_', //
734         [202] = '_', //
735         [203] = '_', //
736         [204] = '_', //
737         [205] = '_', //
738         [206] = '_', //
739         [207] = '_', //
740         [208] = '_', //
741         [209] = '_', //
742         [210] = '_', //
743         [211] = '_', //
744         [212] = '_', //
745         [213] = '_', //
746         [214] = '_', //
747         [215] = '_', //
748         [216] = '_', //
749         [217] = '_', //
750         [218] = '_', //
751         [219] = '_', //
752         [220] = '_', //
753         [221] = '_', //
754         [222] = '_', //
755         [223] = '_', //
756         [224] = '_', //
757         [225] = '_', //
758         [226] = '_', //
759         [227] = '_', //
760         [228] = '_', //
761         [229] = '_', //
762         [230] = '_', //
763         [231] = '_', //
764         [232] = '_', //
765         [233] = '_', //
766         [234] = '_', //
767         [235] = '_', //
768         [236] = '_', //
769         [237] = '_', //
770         [238] = '_', //
771         [239] = '_', //
772         [240] = '_', //
773         [241] = '_', //
774         [242] = '_', //
775         [243] = '_', //
776         [244] = '_', //
777         [245] = '_', //
778         [246] = '_', //
779         [247] = '_', //
780         [248] = '_', //
781         [249] = '_', //
782         [250] = '_', //
783         [251] = '_', //
784         [252] = '_', //
785         [253] = '_', //
786         [254] = '_', //
787         [255] = '_'  //
788 };
789
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++;
794 }
795
796 /*
797 // http://stackoverflow.com/questions/7666509/hash-function-for-string
798 uint32_t simple_hash(const char *name)
799 {
800     const char *s = name;
801     uint32_t hash = 5381;
802     int i;
803
804     while((i = *s++)) hash = ((hash << 5) + hash) + i;
805
806     // fprintf(stderr, "HASH: %lu %s\n", hash, name);
807
808     return hash;
809 }
810 */
811
812 /*
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;
817
818     // FNV-1a algorithm
819     while (*s) {
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);
825         hval *= 16777619;
826
827         // xor the bottom with the current octet
828         hval ^= (uint32_t) *s++;
829     }
830
831     // fprintf(stderr, "HASH: %u = %s\n", hval, name);
832     return hval;
833 }
834
835 uint32_t simple_uhash(const char *name) {
836     unsigned char *s = (unsigned char *) name;
837     uint32_t hval = 0x811c9dc5, c;
838
839     // FNV-1a algorithm
840     while ((c = *s++)) {
841         if (unlikely(c >= 'A' && c <= 'Z')) c += 'a' - 'A';
842         hval *= 16777619;
843         hval ^= c;
844     }
845     return hval;
846 }
847 */
848
849 /*
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;
854     uint32_t h = 0;
855
856     while(*s) {
857         h += *s++;
858         h += (h << 10);
859         h ^= (h >> 6);
860     }
861
862     h += (h << 3);
863     h ^= (h >> 11);
864     h += (h << 15);
865
866     // fprintf(stderr, "HASH: %u = %s\n", h, name);
867
868     return h;
869 }
870 */
871
872 void strreverse(char *begin, char *end) {
873     while (end > begin) {
874         // clearer code.
875         char aux = *end;
876         *end-- = *begin;
877         *begin++ = aux;
878     }
879 }
880
881 char *mystrsep(char **ptr, char *s) {
882     char *p = "";
883     while (p && !p[0] && *ptr) p = strsep(ptr, s);
884     return (p);
885 }
886
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;
892
893     // skip tailing spaces
894     // this way is way faster. Writes only one NUL char.
895     ssize_t l = strlen(s);
896     if (--l >= 0) {
897         char *p = s + l;
898         while (p > s && isspace(*p)) p--;
899         *++p = '\0';
900     }
901
902     if (!*s) return NULL;
903
904     return s;
905 }
906
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;
911 #endif
912     void *mem = NULL;
913
914     errno = 0;
915     int fd = open(filename, O_RDWR | O_CREAT | O_NOATIME, 0664);
916     if (fd != -1) {
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);
921
922 #ifdef MADV_MERGEABLE
923                 if (flags & MAP_SHARED || !enable_ksm || !ksm) {
924 #endif
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);
928                         mem = NULL;
929                     }
930                     else {
931 #ifdef NETDATA_LOG_ALLOCATIONS
932                         mmap_accounting(size);
933 #endif
934                         int advise = MADV_SEQUENTIAL | MADV_DONTFORK;
935                         if (flags & MAP_SHARED) advise |= MADV_WILLNEED;
936
937                         if (madvise(mem, size, advise) != 0 && log_madvise_1) {
938                             error("Cannot advise the kernel about the memory usage of file '%s'.", filename);
939                             log_madvise_1--;
940                         }
941                     }
942 #ifdef MADV_MERGEABLE
943                 }
944                 else {
945 /*
946                     // test - load the file into memory
947                     mem = calloc(1, size);
948                     if(mem) {
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);
952                         }
953                         else
954                             error("Cannot seek to beginning of file '%s'.", filename);
955                     }
956 */
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);
960                         mem = NULL;
961                     }
962                     else {
963 #ifdef NETDATA_LOG_ALLOCATIONS
964                         mmap_accounting(size);
965 #endif
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);
969                         } else
970                             error("Cannot seek to beginning of file '%s'.", filename);
971
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'.",
975                                   filename);
976                             log_madvise_2--;
977                         }
978
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'.",
981                                   filename);
982                             log_madvise_3--;
983                         }
984                     }
985                 }
986 #endif
987             }
988             else
989                 error("Cannot write to file '%s' at position %zu.", filename, size);
990         }
991         else
992             error("Cannot seek file '%s' to size %zu.", filename, size);
993
994         close(fd);
995     }
996     else
997         error("Cannot create/open file '%s'.", filename);
998
999     return mem;
1000 }
1001
1002 int savememory(const char *filename, void *mem, size_t size) {
1003     char tmpfilename[FILENAME_MAX + 1];
1004
1005     snprintfz(tmpfilename, FILENAME_MAX, "%s.%ld.tmp", filename, (long) getpid());
1006
1007     int fd = open(tmpfilename, O_RDWR | O_CREAT | O_NOATIME, 0664);
1008     if (fd < 0) {
1009         error("Cannot create/open file '%s'.", filename);
1010         return -1;
1011     }
1012
1013     if (write(fd, mem, size) != (ssize_t) size) {
1014         error("Cannot write to file '%s' %ld bytes.", filename, (long) size);
1015         close(fd);
1016         return -1;
1017     }
1018
1019     close(fd);
1020
1021     if (rename(tmpfilename, filename)) {
1022         error("Cannot rename '%s' to '%s'", tmpfilename, filename);
1023         return -1;
1024     }
1025
1026     return 0;
1027 }
1028
1029 int fd_is_valid(int fd) {
1030     return fcntl(fd, F_GETFD) != -1 || errno != EBADF;
1031 }
1032
1033 pid_t gettid(void) {
1034 #ifdef __FreeBSD__
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;
1040 #else
1041     return (pid_t)syscall(SYS_gettid);
1042 #endif /* __FreeBSD__, __APPLE__*/
1043 }
1044
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;
1048
1049     char *t = s;
1050     if (*t != '\0') {
1051         // find the string end
1052         while (*++t != '\0');
1053
1054         // trim trailing spaces/newlines/tabs
1055         while (--t > s && *t == '\n')
1056             *t = '\0';
1057     }
1058
1059     if (len)
1060         *len = t - s + 1;
1061
1062     return s;
1063 }
1064
1065 int vsnprintfz(char *dst, size_t n, const char *fmt, va_list args) {
1066     int size = vsnprintf(dst, n, fmt, args);
1067
1068     if (unlikely((size_t) size > n)) {
1069         // truncated
1070         size = (int)n;
1071     }
1072
1073     dst[size] = '\0';
1074     return size;
1075 }
1076
1077 int snprintfz(char *dst, size_t n, const char *fmt, ...) {
1078     va_list args;
1079
1080     va_start(args, fmt);
1081     int ret = vsnprintfz(dst, n, fmt, args);
1082     va_end(args);
1083
1084     return ret;
1085 }
1086
1087 // ----------------------------------------------------------------------------
1088 // system functions
1089 // to retrieve settings of the system
1090
1091 int processors = 1;
1092 long get_system_cpus(void) {
1093     processors = 1;
1094
1095     #ifdef __APPLE__
1096         int32_t tmp_processors;
1097
1098         if (unlikely(GETSYSCTL("hw.logicalcpu", tmp_processors))) {
1099             error("Assuming system has %d processors.", processors);
1100         } else {
1101             processors = tmp_processors;
1102         }
1103
1104         return processors;
1105     #elif __FreeBSD__
1106         int32_t tmp_processors;
1107
1108         if (unlikely(GETSYSCTL("hw.ncpu", tmp_processors))) {
1109             error("Assuming system has %d processors.", processors);
1110         } else {
1111             processors = tmp_processors;
1112         }
1113
1114         return processors;
1115     #else
1116
1117     char filename[FILENAME_MAX + 1];
1118     snprintfz(filename, FILENAME_MAX, "%s/proc/stat", global_host_prefix);
1119
1120     procfile *ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);
1121     if(!ff) {
1122         error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);
1123         return processors;
1124     }
1125
1126     ff = procfile_readall(ff);
1127     if(!ff) {
1128         error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);
1129         return processors;
1130     }
1131
1132     processors = 0;
1133     unsigned int i;
1134     for(i = 0; i < procfile_lines(ff); i++) {
1135         if(!procfile_linewords(ff, i)) continue;
1136
1137         if(strncmp(procfile_lineword(ff, i, 0), "cpu", 3) == 0) processors++;
1138     }
1139     processors--;
1140     if(processors < 1) processors = 1;
1141
1142     procfile_close(ff);
1143
1144     debug(D_SYSTEM, "System has %d processors.", processors);
1145     return processors;
1146
1147     #endif /* __APPLE__, __FreeBSD__ */
1148 }
1149
1150 pid_t pid_max = 32768;
1151 pid_t get_system_pid_max(void) {
1152     #ifdef __APPLE__
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
1155         pid_max = 99999;
1156         return pid_max;
1157     #elif __FreeBSD__
1158         int32_t tmp_pid_max;
1159
1160         if (unlikely(GETSYSCTL("kern.pid_max", tmp_pid_max))) {
1161             pid_max = 99999;
1162             error("Assuming system's maximum pid is %d.", pid_max);
1163         } else {
1164             pid_max = tmp_pid_max;
1165         }
1166
1167         return pid_max;
1168     #else
1169
1170     static char read = 0;
1171     if(unlikely(read)) return pid_max;
1172     read = 1;
1173
1174     char filename[FILENAME_MAX + 1];
1175     snprintfz(filename, FILENAME_MAX, "%s/proc/sys/kernel/pid_max", global_host_prefix);
1176
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);
1180         return pid_max;
1181     }
1182
1183     if(!max) {
1184         error("Cannot parse file '%s'. Assuming system supports %d pids.", filename, pid_max);
1185         return pid_max;
1186     }
1187
1188     pid_max = (pid_t) max;
1189     return pid_max;
1190
1191     #endif /* __APPLE__, __FreeBSD__ */
1192 }
1193
1194 unsigned int hz;
1195 void get_system_HZ(void) {
1196     long ticks;
1197
1198     if ((ticks = sysconf(_SC_CLK_TCK)) == -1) {
1199         error("Cannot get system clock ticks");
1200     }
1201
1202     hz = (unsigned int) ticks;
1203 }
1204
1205 /*
1206 // poor man cycle counting
1207 static unsigned long tsc;
1208 void begin_tsc(void) {
1209     unsigned long a, d;
1210     asm volatile ("cpuid\nrdtsc" : "=a" (a), "=d" (d) : "0" (0) : "ebx", "ecx");
1211     tsc = ((unsigned long)d << 32) | (unsigned long)a;
1212 }
1213 unsigned long end_tsc(void) {
1214     unsigned long a, d;
1215     asm volatile ("rdtscp" : "=a" (a), "=d" (d) : : "ecx");
1216     return (((unsigned long)d << 32) | (unsigned long)a) - tsc;
1217 }
1218 */