]> arthur.barton.de Git - netdata.git/blob - src/rrd.c
365ad87624edd24d7fba6118dee66273e9ecad65
[netdata.git] / src / rrd.c
1 #include "common.h"
2
3 #define RRD_DEFAULT_GAP_INTERPOLATIONS 1
4
5 // ----------------------------------------------------------------------------
6 // globals
7
8 /*
9 // if not zero it gives the time (in seconds) to remove un-updated dimensions
10 // DO NOT ENABLE
11 // if dimensions are removed, the chart generation will have to run again
12 int rrd_delete_unupdated_dimensions = 0;
13 */
14
15 int rrd_update_every = UPDATE_EVERY;
16 int rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
17 int rrd_memory_mode = RRD_MEMORY_MODE_SAVE;
18
19 static int rrdset_compare(void* a, void* b);
20 static int rrdset_compare_name(void* a, void* b);
21 static int rrdfamily_compare(void *a, void *b);
22
23 // ----------------------------------------------------------------------------
24 // RRDHOST
25
26 RRDHOST localhost = {
27         .hostname = "localhost",
28         .rrdset_root = NULL,
29         .rrdset_root_rwlock = PTHREAD_RWLOCK_INITIALIZER,
30         .rrdset_root_index = {
31             { NULL, rrdset_compare },
32             AVL_LOCK_INITIALIZER
33         },
34         .rrdset_root_index_name = {
35             { NULL, rrdset_compare_name },
36             AVL_LOCK_INITIALIZER
37         },
38         .rrdfamily_root_index = {
39             { NULL, rrdfamily_compare },
40             AVL_LOCK_INITIALIZER
41         },
42         .variables_root_index = {
43             { NULL, rrdvar_compare },
44             AVL_LOCK_INITIALIZER
45         },
46         .health_log = {
47             .next_log_id = 1,
48             .next_alarm_id = 1,
49             .count = 0,
50             .max = 1000,
51             .alarms = NULL,
52             .alarm_log_rwlock = PTHREAD_RWLOCK_INITIALIZER
53         }
54 };
55
56 void rrdhost_init(char *hostname) {
57     localhost.hostname = hostname;
58     localhost.health_log.next_log_id =
59         localhost.health_log.next_alarm_id = now_realtime_sec();
60 }
61
62 void rrdhost_rwlock(RRDHOST *host) {
63     pthread_rwlock_wrlock(&host->rrdset_root_rwlock);
64 }
65
66 void rrdhost_rdlock(RRDHOST *host) {
67     pthread_rwlock_rdlock(&host->rrdset_root_rwlock);
68 }
69
70 void rrdhost_unlock(RRDHOST *host) {
71     pthread_rwlock_unlock(&host->rrdset_root_rwlock);
72 }
73
74 void rrdhost_check_rdlock_int(RRDHOST *host, const char *file, const char *function, const unsigned long line) {
75     int ret = pthread_rwlock_trywrlock(&host->rrdset_root_rwlock);
76
77     if(ret == 0)
78         fatal("RRDHOST '%s' should be read-locked, but it is not, at function %s() at line %lu of file '%s'", host->hostname, function, line, file);
79 }
80
81 void rrdhost_check_wrlock_int(RRDHOST *host, const char *file, const char *function, const unsigned long line) {
82     int ret = pthread_rwlock_tryrdlock(&host->rrdset_root_rwlock);
83
84     if(ret == 0)
85         fatal("RRDHOST '%s' should be write-locked, but it is not, at function %s() at line %lu of file '%s'", host->hostname, function, line, file);
86 }
87
88 // ----------------------------------------------------------------------------
89 // RRDFAMILY index
90
91 static int rrdfamily_compare(void *a, void *b) {
92     if(((RRDFAMILY *)a)->hash_family < ((RRDFAMILY *)b)->hash_family) return -1;
93     else if(((RRDFAMILY *)a)->hash_family > ((RRDFAMILY *)b)->hash_family) return 1;
94     else return strcmp(((RRDFAMILY *)a)->family, ((RRDFAMILY *)b)->family);
95 }
96
97 #define rrdfamily_index_add(host, rc) (RRDFAMILY *)avl_insert_lock(&((host)->rrdfamily_root_index), (avl *)(rc))
98 #define rrdfamily_index_del(host, rc) (RRDFAMILY *)avl_remove_lock(&((host)->rrdfamily_root_index), (avl *)(rc))
99
100 static RRDFAMILY *rrdfamily_index_find(RRDHOST *host, const char *id, uint32_t hash) {
101     RRDFAMILY tmp;
102     tmp.family = id;
103     tmp.hash_family = (hash)?hash:simple_hash(tmp.family);
104
105     return (RRDFAMILY *)avl_search_lock(&(host->rrdfamily_root_index), (avl *) &tmp);
106 }
107
108 RRDFAMILY *rrdfamily_create(const char *id) {
109     RRDFAMILY *rc = rrdfamily_index_find(&localhost, id, 0);
110     if(!rc) {
111         rc = callocz(1, sizeof(RRDFAMILY));
112
113         rc->family = strdupz(id);
114         rc->hash_family = simple_hash(rc->family);
115
116         // initialize the variables index
117         avl_init_lock(&rc->variables_root_index, rrdvar_compare);
118
119         RRDFAMILY *ret = rrdfamily_index_add(&localhost, rc);
120         if(ret != rc)
121             fatal("RRDFAMILY: INTERNAL ERROR: Expected to INSERT RRDFAMILY '%s' into index, but inserted '%s'.", rc->family, (ret)?ret->family:"NONE");
122     }
123
124     rc->use_count++;
125     return rc;
126 }
127
128 void rrdfamily_free(RRDFAMILY *rc) {
129     rc->use_count--;
130     if(!rc->use_count) {
131         RRDFAMILY *ret = rrdfamily_index_del(&localhost, rc);
132         if(ret != rc)
133             fatal("RRDFAMILY: INTERNAL ERROR: Expected to DELETE RRDFAMILY '%s' from index, but deleted '%s'.", rc->family, (ret)?ret->family:"NONE");
134
135         if(rc->variables_root_index.avl_tree.root != NULL)
136             fatal("RRDFAMILY: INTERNAL ERROR: Variables index of RRDFAMILY '%s' that is freed, is not empty.", rc->family);
137
138         freez((void *)rc->family);
139         freez(rc);
140     }
141 }
142
143 // ----------------------------------------------------------------------------
144 // RRDSET index
145
146 static int rrdset_compare(void* a, void* b) {
147     if(((RRDSET *)a)->hash < ((RRDSET *)b)->hash) return -1;
148     else if(((RRDSET *)a)->hash > ((RRDSET *)b)->hash) return 1;
149     else return strcmp(((RRDSET *)a)->id, ((RRDSET *)b)->id);
150 }
151
152 #define rrdset_index_add(host, st) (RRDSET *)avl_insert_lock(&((host)->rrdset_root_index), (avl *)(st))
153 #define rrdset_index_del(host, st) (RRDSET *)avl_remove_lock(&((host)->rrdset_root_index), (avl *)(st))
154
155 static RRDSET *rrdset_index_find(RRDHOST *host, const char *id, uint32_t hash) {
156     RRDSET tmp;
157     strncpyz(tmp.id, id, RRD_ID_LENGTH_MAX);
158     tmp.hash = (hash)?hash:simple_hash(tmp.id);
159
160     return (RRDSET *)avl_search_lock(&(host->rrdset_root_index), (avl *) &tmp);
161 }
162
163 // ----------------------------------------------------------------------------
164 // RRDSET name index
165
166 #define rrdset_from_avlname(avlname_ptr) ((RRDSET *)((avlname_ptr) - offsetof(RRDSET, avlname)))
167
168 static int rrdset_compare_name(void* a, void* b) {
169     RRDSET *A = rrdset_from_avlname(a);
170     RRDSET *B = rrdset_from_avlname(b);
171
172     // fprintf(stderr, "COMPARING: %s with %s\n", A->name, B->name);
173
174     if(A->hash_name < B->hash_name) return -1;
175     else if(A->hash_name > B->hash_name) return 1;
176     else return strcmp(A->name, B->name);
177 }
178
179 RRDSET *rrdset_index_add_name(RRDHOST *host, RRDSET *st) {
180     void *result;
181     // fprintf(stderr, "ADDING: %s (name: %s)\n", st->id, st->name);
182     result = avl_insert_lock(&host->rrdset_root_index_name, (avl *) (&st->avlname));
183     if(result) return rrdset_from_avlname(result);
184     return NULL;
185 }
186
187 RRDSET *rrdset_index_del_name(RRDHOST *host, RRDSET *st) {
188     void *result;
189     // fprintf(stderr, "DELETING: %s (name: %s)\n", st->id, st->name);
190     result = (RRDSET *)avl_remove_lock(&((host)->rrdset_root_index_name), (avl *)(&st->avlname));
191     if(result) return rrdset_from_avlname(result);
192     return NULL;
193 }
194
195 static RRDSET *rrdset_index_find_name(RRDHOST *host, const char *name, uint32_t hash) {
196     void *result = NULL;
197     RRDSET tmp;
198     tmp.name = name;
199     tmp.hash_name = (hash)?hash:simple_hash(tmp.name);
200
201     // fprintf(stderr, "SEARCHING: %s\n", name);
202     result = avl_search_lock(&host->rrdset_root_index_name, (avl *) (&(tmp.avlname)));
203     if(result) {
204         RRDSET *st = rrdset_from_avlname(result);
205         if(strcmp(st->magic, RRDSET_MAGIC))
206             error("Search for RRDSET %s returned an invalid RRDSET %s (name %s)", name, st->id, st->name);
207
208         // fprintf(stderr, "FOUND: %s\n", name);
209         return rrdset_from_avlname(result);
210     }
211     // fprintf(stderr, "NOT FOUND: %s\n", name);
212     return NULL;
213 }
214
215
216 // ----------------------------------------------------------------------------
217 // RRDDIM index
218
219 static int rrddim_compare(void* a, void* b) {
220     if(((RRDDIM *)a)->hash < ((RRDDIM *)b)->hash) return -1;
221     else if(((RRDDIM *)a)->hash > ((RRDDIM *)b)->hash) return 1;
222     else return strcmp(((RRDDIM *)a)->id, ((RRDDIM *)b)->id);
223 }
224
225 #define rrddim_index_add(st, rd) (RRDDIM *)avl_insert_lock(&((st)->dimensions_index), (avl *)(rd))
226 #define rrddim_index_del(st,rd ) (RRDDIM *)avl_remove_lock(&((st)->dimensions_index), (avl *)(rd))
227
228 static RRDDIM *rrddim_index_find(RRDSET *st, const char *id, uint32_t hash) {
229     RRDDIM tmp;
230     strncpyz(tmp.id, id, RRD_ID_LENGTH_MAX);
231     tmp.hash = (hash)?hash:simple_hash(tmp.id);
232
233     return (RRDDIM *)avl_search_lock(&(st->dimensions_index), (avl *) &tmp);
234 }
235
236 // ----------------------------------------------------------------------------
237 // chart types
238
239 int rrdset_type_id(const char *name)
240 {
241     if(unlikely(strcmp(name, RRDSET_TYPE_AREA_NAME) == 0)) return RRDSET_TYPE_AREA;
242     else if(unlikely(strcmp(name, RRDSET_TYPE_STACKED_NAME) == 0)) return RRDSET_TYPE_STACKED;
243     else if(unlikely(strcmp(name, RRDSET_TYPE_LINE_NAME) == 0)) return RRDSET_TYPE_LINE;
244     return RRDSET_TYPE_LINE;
245 }
246
247 const char *rrdset_type_name(int chart_type)
248 {
249     static char line[] = RRDSET_TYPE_LINE_NAME;
250     static char area[] = RRDSET_TYPE_AREA_NAME;
251     static char stacked[] = RRDSET_TYPE_STACKED_NAME;
252
253     switch(chart_type) {
254         case RRDSET_TYPE_LINE:
255             return line;
256
257         case RRDSET_TYPE_AREA:
258             return area;
259
260         case RRDSET_TYPE_STACKED:
261             return stacked;
262     }
263     return line;
264 }
265
266 // ----------------------------------------------------------------------------
267 // load / save
268
269 const char *rrd_memory_mode_name(int id)
270 {
271     static const char ram[] = RRD_MEMORY_MODE_RAM_NAME;
272     static const char map[] = RRD_MEMORY_MODE_MAP_NAME;
273     static const char save[] = RRD_MEMORY_MODE_SAVE_NAME;
274
275     switch(id) {
276         case RRD_MEMORY_MODE_RAM:
277             return ram;
278
279         case RRD_MEMORY_MODE_MAP:
280             return map;
281
282         case RRD_MEMORY_MODE_SAVE:
283         default:
284             return save;
285     }
286
287     return save;
288 }
289
290 int rrd_memory_mode_id(const char *name)
291 {
292     if(unlikely(!strcmp(name, RRD_MEMORY_MODE_RAM_NAME)))
293         return RRD_MEMORY_MODE_RAM;
294     else if(unlikely(!strcmp(name, RRD_MEMORY_MODE_MAP_NAME)))
295         return RRD_MEMORY_MODE_MAP;
296
297     return RRD_MEMORY_MODE_SAVE;
298 }
299
300 // ----------------------------------------------------------------------------
301 // algorithms types
302
303 int rrddim_algorithm_id(const char *name)
304 {
305     if(strcmp(name, RRDDIM_INCREMENTAL_NAME) == 0)          return RRDDIM_INCREMENTAL;
306     if(strcmp(name, RRDDIM_ABSOLUTE_NAME) == 0)             return RRDDIM_ABSOLUTE;
307     if(strcmp(name, RRDDIM_PCENT_OVER_ROW_TOTAL_NAME) == 0)         return RRDDIM_PCENT_OVER_ROW_TOTAL;
308     if(strcmp(name, RRDDIM_PCENT_OVER_DIFF_TOTAL_NAME) == 0)    return RRDDIM_PCENT_OVER_DIFF_TOTAL;
309     return RRDDIM_ABSOLUTE;
310 }
311
312 const char *rrddim_algorithm_name(int chart_type)
313 {
314     static char absolute[] = RRDDIM_ABSOLUTE_NAME;
315     static char incremental[] = RRDDIM_INCREMENTAL_NAME;
316     static char percentage_of_absolute_row[] = RRDDIM_PCENT_OVER_ROW_TOTAL_NAME;
317     static char percentage_of_incremental_row[] = RRDDIM_PCENT_OVER_DIFF_TOTAL_NAME;
318
319     switch(chart_type) {
320         case RRDDIM_ABSOLUTE:
321             return absolute;
322
323         case RRDDIM_INCREMENTAL:
324             return incremental;
325
326         case RRDDIM_PCENT_OVER_ROW_TOTAL:
327             return percentage_of_absolute_row;
328
329         case RRDDIM_PCENT_OVER_DIFF_TOTAL:
330             return percentage_of_incremental_row;
331     }
332     return absolute;
333 }
334
335 // ----------------------------------------------------------------------------
336 // chart names
337
338 char *rrdset_strncpyz_name(char *to, const char *from, size_t length)
339 {
340     char c, *p = to;
341
342     while (length-- && (c = *from++)) {
343         if(c != '.' && !isalnum(c))
344             c = '_';
345
346         *p++ = c;
347     }
348
349     *p = '\0';
350
351     return to;
352 }
353
354 void rrdset_set_name(RRDSET *st, const char *name)
355 {
356     if(unlikely(st->name && !strcmp(st->name, name)))
357         return;
358
359     debug(D_RRD_CALLS, "rrdset_set_name() old: %s, new: %s", st->name, name);
360
361     char b[CONFIG_MAX_VALUE + 1];
362     char n[RRD_ID_LENGTH_MAX + 1];
363
364     snprintfz(n, RRD_ID_LENGTH_MAX, "%s.%s", st->type, name);
365     rrdset_strncpyz_name(b, n, CONFIG_MAX_VALUE);
366
367     if(st->name) {
368         rrdset_index_del_name(&localhost, st);
369         st->name = config_set_default(st->id, "name", b);
370         st->hash_name = simple_hash(st->name);
371         rrdsetvar_rename_all(st);
372     }
373     else {
374         st->name = config_get(st->id, "name", b);
375         st->hash_name = simple_hash(st->name);
376     }
377
378     pthread_rwlock_wrlock(&st->rwlock);
379     RRDDIM *rd;
380     for(rd = st->dimensions; rd ;rd = rd->next)
381         rrddimvar_rename_all(rd);
382     pthread_rwlock_unlock(&st->rwlock);
383
384     if(unlikely(rrdset_index_add_name(&localhost, st) != st))
385         error("RRDSET: INTERNAL ERROR: attempted to index duplicate chart name '%s'", st->name);
386 }
387
388 // ----------------------------------------------------------------------------
389 // cache directory
390
391 char *rrdset_cache_dir(const char *id)
392 {
393     char *ret = NULL;
394
395     static char *cache_dir = NULL;
396     if(!cache_dir) {
397         cache_dir = config_get("global", "cache directory", CACHE_DIR);
398         int r = mkdir(cache_dir, 0755);
399         if(r != 0 && errno != EEXIST)
400             error("Cannot create directory '%s'", cache_dir);
401     }
402
403     char b[FILENAME_MAX + 1];
404     char n[FILENAME_MAX + 1];
405     rrdset_strncpyz_name(b, id, FILENAME_MAX);
406
407     snprintfz(n, FILENAME_MAX, "%s/%s", cache_dir, b);
408     ret = config_get(id, "cache directory", n);
409
410     if(rrd_memory_mode == RRD_MEMORY_MODE_MAP || rrd_memory_mode == RRD_MEMORY_MODE_SAVE) {
411         int r = mkdir(ret, 0775);
412         if(r != 0 && errno != EEXIST)
413             error("Cannot create directory '%s'", ret);
414     }
415
416     return ret;
417 }
418
419 // ----------------------------------------------------------------------------
420 // core functions
421
422 void rrdset_reset(RRDSET *st)
423 {
424     debug(D_RRD_CALLS, "rrdset_reset() %s", st->name);
425
426     st->last_collected_time.tv_sec = 0;
427     st->last_collected_time.tv_usec = 0;
428     st->last_updated.tv_sec = 0;
429     st->last_updated.tv_usec = 0;
430     st->current_entry = 0;
431     st->counter = 0;
432     st->counter_done = 0;
433
434     RRDDIM *rd;
435     for(rd = st->dimensions; rd ; rd = rd->next) {
436         rd->last_collected_time.tv_sec = 0;
437         rd->last_collected_time.tv_usec = 0;
438         rd->counter = 0;
439         memset(rd->values, 0, rd->entries * sizeof(storage_number));
440     }
441 }
442 static inline long align_entries_to_pagesize(long entries) {
443     if(entries < 5) entries = 5;
444     if(entries > RRD_HISTORY_ENTRIES_MAX) entries = RRD_HISTORY_ENTRIES_MAX;
445
446 #ifdef NETDATA_LOG_ALLOCATIONS
447     long page = (size_t)sysconf(_SC_PAGESIZE);
448
449     long size = sizeof(RRDDIM) + entries * sizeof(storage_number);
450     if(size % page) {
451         size -= (size % page);
452         size += page;
453
454         long n = (size - sizeof(RRDDIM)) / sizeof(storage_number);
455         return n;
456     }
457
458     return entries;
459 #else
460     return entries;
461 #endif
462 }
463
464 static inline void timeval_align(struct timeval *tv, int update_every) {
465     tv->tv_sec -= tv->tv_sec % update_every;
466     tv->tv_usec = 500000;
467 }
468
469 RRDSET *rrdset_create(const char *type, const char *id, const char *name, const char *family, const char *context, const char *title, const char *units, long priority, int update_every, int chart_type)
470 {
471     if(!type || !type[0]) {
472         fatal("Cannot create rrd stats without a type.");
473         return NULL;
474     }
475
476     if(!id || !id[0]) {
477         fatal("Cannot create rrd stats without an id.");
478         return NULL;
479     }
480
481     char fullid[RRD_ID_LENGTH_MAX + 1];
482     char fullfilename[FILENAME_MAX + 1];
483
484     snprintfz(fullid, RRD_ID_LENGTH_MAX, "%s.%s", type, id);
485
486     RRDSET *st = rrdset_find(fullid);
487     if(st) {
488         error("Cannot create rrd stats for '%s', it already exists.", fullid);
489         return st;
490     }
491
492     long rentries = config_get_number(fullid, "history", rrd_default_history_entries);
493     long entries = align_entries_to_pagesize(rentries);
494     if(entries != rentries) entries = config_set_number(fullid, "history", entries);
495
496     int enabled = config_get_boolean(fullid, "enabled", 1);
497     if(!enabled) entries = 5;
498
499     unsigned long size = sizeof(RRDSET);
500     char *cache_dir = rrdset_cache_dir(fullid);
501
502     debug(D_RRD_CALLS, "Creating RRD_STATS for '%s.%s'.", type, id);
503
504     snprintfz(fullfilename, FILENAME_MAX, "%s/main.db", cache_dir);
505     if(rrd_memory_mode != RRD_MEMORY_MODE_RAM) st = (RRDSET *)mymmap(fullfilename, size, ((rrd_memory_mode == RRD_MEMORY_MODE_MAP)?MAP_SHARED:MAP_PRIVATE), 0);
506     if(st) {
507         if(strcmp(st->magic, RRDSET_MAGIC) != 0) {
508             errno = 0;
509             info("Initializing file %s.", fullfilename);
510             memset(st, 0, size);
511         }
512         else if(strcmp(st->id, fullid) != 0) {
513             errno = 0;
514             error("File %s contents are not for chart %s. Clearing it.", fullfilename, fullid);
515             // munmap(st, size);
516             // st = NULL;
517             memset(st, 0, size);
518         }
519         else if(st->memsize != size || st->entries != entries) {
520             errno = 0;
521             error("File %s does not have the desired size. Clearing it.", fullfilename);
522             memset(st, 0, size);
523         }
524         else if(st->update_every != update_every) {
525             errno = 0;
526             error("File %s does not have the desired update frequency. Clearing it.", fullfilename);
527             memset(st, 0, size);
528         }
529         else if((now_realtime_sec() - st->last_updated.tv_sec) > update_every * entries) {
530             errno = 0;
531             error("File %s is too old. Clearing it.", fullfilename);
532             memset(st, 0, size);
533         }
534
535         // make sure the database is aligned
536         if(st->last_updated.tv_sec)
537             timeval_align(&st->last_updated, update_every);
538     }
539
540     if(st) {
541         st->name = NULL;
542         st->type = NULL;
543         st->family = NULL;
544         st->context = NULL;
545         st->title = NULL;
546         st->units = NULL;
547         st->dimensions = NULL;
548         st->next = NULL;
549         st->mapped = rrd_memory_mode;
550         st->variables = NULL;
551         st->alarms = NULL;
552         memset(&st->rwlock, 0, sizeof(pthread_rwlock_t));
553         memset(&st->avl, 0, sizeof(avl));
554         memset(&st->avlname, 0, sizeof(avl));
555         memset(&st->variables_root_index, 0, sizeof(avl_tree_lock));
556         memset(&st->dimensions_index, 0, sizeof(avl_tree_lock));
557     }
558     else {
559         st = callocz(1, size);
560         st->mapped = RRD_MEMORY_MODE_RAM;
561     }
562
563     st->memsize = size;
564     st->entries = entries;
565     st->update_every = update_every;
566
567     if(st->current_entry >= st->entries) st->current_entry = 0;
568
569     strcpy(st->cache_filename, fullfilename);
570     strcpy(st->magic, RRDSET_MAGIC);
571
572     strcpy(st->id, fullid);
573     st->hash = simple_hash(st->id);
574
575     st->cache_dir = cache_dir;
576
577     st->chart_type = rrdset_type_id(config_get(st->id, "chart type", rrdset_type_name(chart_type)));
578     st->type       = config_get(st->id, "type", type);
579     st->family     = config_get(st->id, "family", family?family:st->type);
580     st->units      = config_get(st->id, "units", units?units:"");
581
582     st->context    = config_get(st->id, "context", context?context:st->id);
583     st->hash_context = simple_hash(st->context);
584
585     st->priority = config_get_number(st->id, "priority", priority);
586     st->enabled = enabled;
587
588     st->isdetail = 0;
589     st->debug = 0;
590
591     // if(!strcmp(st->id, "disk_util.dm-0")) {
592     //     st->debug = 1;
593     //     error("enabled debugging for '%s'", st->id);
594     // }
595     // else error("not enabled debugging for '%s'", st->id);
596
597     st->green = NAN;
598     st->red = NAN;
599
600     st->last_collected_time.tv_sec = 0;
601     st->last_collected_time.tv_usec = 0;
602     st->counter_done = 0;
603
604     st->gap_when_lost_iterations_above = (int) (
605             config_get_number(st->id, "gap when lost iterations above", RRD_DEFAULT_GAP_INTERPOLATIONS) + 2);
606
607     avl_init_lock(&st->dimensions_index, rrddim_compare);
608     avl_init_lock(&st->variables_root_index, rrdvar_compare);
609
610     pthread_rwlock_init(&st->rwlock, NULL);
611     rrdhost_rwlock(&localhost);
612
613     if(name && *name) rrdset_set_name(st, name);
614     else rrdset_set_name(st, id);
615
616     {
617         char varvalue[CONFIG_MAX_VALUE + 1];
618         char varvalue2[CONFIG_MAX_VALUE + 1];
619         snprintfz(varvalue, CONFIG_MAX_VALUE, "%s (%s)", title?title:"", st->name);
620         json_escape_string(varvalue2, varvalue, sizeof(varvalue2));
621         st->title = config_get(st->id, "title", varvalue2);
622     }
623
624     st->rrdfamily = rrdfamily_create(st->family);
625     st->rrdhost = &localhost;
626
627     st->next = localhost.rrdset_root;
628     localhost.rrdset_root = st;
629
630     if(health_enabled) {
631         rrdsetvar_create(st, "last_collected_t", RRDVAR_TYPE_TIME_T, &st->last_collected_time.tv_sec, 0);
632         rrdsetvar_create(st, "collected_total_raw", RRDVAR_TYPE_TOTAL, &st->last_collected_total, 0);
633         rrdsetvar_create(st, "green", RRDVAR_TYPE_CALCULATED, &st->green, 0);
634         rrdsetvar_create(st, "red", RRDVAR_TYPE_CALCULATED, &st->red, 0);
635         rrdsetvar_create(st, "update_every", RRDVAR_TYPE_INT, &st->update_every, 0);
636     }
637
638     if(unlikely(rrdset_index_add(&localhost, st) != st))
639         error("RRDSET: INTERNAL ERROR: attempt to index duplicate chart '%s'", st->id);
640
641     rrdsetcalc_link_matching(st);
642     rrdcalctemplate_link_matching(st);
643
644     rrdhost_unlock(&localhost);
645
646     return(st);
647 }
648
649 RRDDIM *rrddim_add(RRDSET *st, const char *id, const char *name, long multiplier, long divisor, int algorithm)
650 {
651     RRDDIM *rd = rrddim_find(st, id);
652     if(rd) {
653         error("Cannot create rrd dimension '%s/%s', it already exists.", st->id, name);
654         return rd;
655     }
656
657     char filename[FILENAME_MAX + 1];
658     char fullfilename[FILENAME_MAX + 1];
659
660     char varname[CONFIG_MAX_NAME + 1];
661     unsigned long size = sizeof(RRDDIM) + (st->entries * sizeof(storage_number));
662
663     debug(D_RRD_CALLS, "Adding dimension '%s/%s'.", st->id, id);
664
665     rrdset_strncpyz_name(filename, id, FILENAME_MAX);
666     snprintfz(fullfilename, FILENAME_MAX, "%s/%s.db", st->cache_dir, filename);
667
668     if(rrd_memory_mode != RRD_MEMORY_MODE_RAM)
669         rd = (RRDDIM *)mymmap(fullfilename, size, ((rrd_memory_mode == RRD_MEMORY_MODE_MAP)?MAP_SHARED:MAP_PRIVATE), 1);
670
671     if(rd) {
672         struct timeval now;
673         now_realtime_timeval(&now);
674
675         if(strcmp(rd->magic, RRDDIMENSION_MAGIC) != 0) {
676             errno = 0;
677             info("Initializing file %s.", fullfilename);
678             memset(rd, 0, size);
679         }
680         else if(rd->memsize != size) {
681             errno = 0;
682             error("File %s does not have the desired size. Clearing it.", fullfilename);
683             memset(rd, 0, size);
684         }
685         else if(rd->multiplier != multiplier) {
686             errno = 0;
687             error("File %s does not have the same multiplier. Clearing it.", fullfilename);
688             memset(rd, 0, size);
689         }
690         else if(rd->divisor != divisor) {
691             errno = 0;
692             error("File %s does not have the same divisor. Clearing it.", fullfilename);
693             memset(rd, 0, size);
694         }
695         else if(rd->algorithm != algorithm) {
696             errno = 0;
697             error("File %s does not have the same algorithm. Clearing it.", fullfilename);
698             memset(rd, 0, size);
699         }
700         else if(rd->update_every != st->update_every) {
701             errno = 0;
702             error("File %s does not have the same refresh frequency. Clearing it.", fullfilename);
703             memset(rd, 0, size);
704         }
705         else if(dt_usec(&now, &rd->last_collected_time) > (rd->entries * rd->update_every * USEC_PER_SEC)) {
706             errno = 0;
707             error("File %s is too old. Clearing it.", fullfilename);
708             memset(rd, 0, size);
709         }
710         else if(strcmp(rd->id, id) != 0) {
711             errno = 0;
712             error("File %s contents are not for dimension %s. Clearing it.", fullfilename, id);
713             // munmap(rd, size);
714             // rd = NULL;
715             memset(rd, 0, size);
716         }
717     }
718
719     if(rd) {
720         // we have a file mapped for rd
721         rd->mapped = rrd_memory_mode;
722         rd->flags = 0x00000000;
723         rd->variables = NULL;
724         rd->next = NULL;
725         rd->name = NULL;
726         memset(&rd->avl, 0, sizeof(avl));
727     }
728     else {
729         // if we didn't manage to get a mmap'd dimension, just create one
730
731         rd = callocz(1, size);
732         rd->mapped = RRD_MEMORY_MODE_RAM;
733     }
734     rd->memsize = size;
735
736     strcpy(rd->magic, RRDDIMENSION_MAGIC);
737     strcpy(rd->cache_filename, fullfilename);
738     strncpyz(rd->id, id, RRD_ID_LENGTH_MAX);
739     rd->hash = simple_hash(rd->id);
740
741     snprintfz(varname, CONFIG_MAX_NAME, "dim %s name", rd->id);
742     rd->name = config_get(st->id, varname, (name && *name)?name:rd->id);
743
744     snprintfz(varname, CONFIG_MAX_NAME, "dim %s algorithm", rd->id);
745     rd->algorithm = rrddim_algorithm_id(config_get(st->id, varname, rrddim_algorithm_name(algorithm)));
746
747     snprintfz(varname, CONFIG_MAX_NAME, "dim %s multiplier", rd->id);
748     rd->multiplier = config_get_number(st->id, varname, multiplier);
749
750     snprintfz(varname, CONFIG_MAX_NAME, "dim %s divisor", rd->id);
751     rd->divisor = config_get_number(st->id, varname, divisor);
752     if(!rd->divisor) rd->divisor = 1;
753
754     rd->entries = st->entries;
755     rd->update_every = st->update_every;
756
757     // prevent incremental calculation spikes
758     rd->counter = 0;
759     rd->updated = 0;
760     rd->calculated_value = 0;
761     rd->last_calculated_value = 0;
762     rd->collected_value = 0;
763     rd->last_collected_value = 0;
764     rd->collected_volume = 0;
765     rd->stored_volume = 0;
766     rd->last_stored_value = 0;
767     rd->values[st->current_entry] = pack_storage_number(0, SN_NOT_EXISTS);
768     rd->last_collected_time.tv_sec = 0;
769     rd->last_collected_time.tv_usec = 0;
770     rd->rrdset = st;
771
772     // append this dimension
773     pthread_rwlock_wrlock(&st->rwlock);
774     if(!st->dimensions)
775         st->dimensions = rd;
776     else {
777         RRDDIM *td = st->dimensions;
778         for(; td->next; td = td->next) ;
779         td->next = rd;
780     }
781
782     if(health_enabled) {
783         rrddimvar_create(rd, RRDVAR_TYPE_CALCULATED, NULL, NULL, &rd->last_stored_value, 0);
784         rrddimvar_create(rd, RRDVAR_TYPE_COLLECTED, NULL, "_raw", &rd->last_collected_value, 0);
785         rrddimvar_create(rd, RRDVAR_TYPE_TIME_T, NULL, "_last_collected_t", &rd->last_collected_time.tv_sec, 0);
786     }
787
788     pthread_rwlock_unlock(&st->rwlock);
789
790     if(unlikely(rrddim_index_add(st, rd) != rd))
791         error("RRDDIM: INTERNAL ERROR: attempt to index duplicate dimension '%s' on chart '%s'", rd->id, st->id);
792
793     return(rd);
794 }
795
796 void rrddim_set_name(RRDSET *st, RRDDIM *rd, const char *name)
797 {
798     if(unlikely(rd->name && !strcmp(rd->name, name)))
799         return;
800
801     debug(D_RRD_CALLS, "rrddim_set_name() from %s.%s to %s.%s", st->name, rd->name, st->name, name);
802
803     char varname[CONFIG_MAX_NAME + 1];
804     snprintfz(varname, CONFIG_MAX_NAME, "dim %s name", rd->id);
805     rd->name = config_set_default(st->id, varname, name);
806
807     rrddimvar_rename_all(rd);
808 }
809
810 void rrddim_free(RRDSET *st, RRDDIM *rd)
811 {
812     debug(D_RRD_CALLS, "rrddim_free() %s.%s", st->name, rd->name);
813
814     if(rd == st->dimensions)
815         st->dimensions = rd->next;
816     else {
817         RRDDIM *i;
818         for (i = st->dimensions; i && i->next != rd; i = i->next) ;
819
820         if (i && i->next == rd)
821             i->next = rd->next;
822         else
823             error("Request to free dimension '%s.%s' but it is not linked.", st->id, rd->name);
824     }
825     rd->next = NULL;
826
827     while(rd->variables)
828         rrddimvar_free(rd->variables);
829
830     if(unlikely(rrddim_index_del(st, rd) != rd))
831         error("RRDDIM: INTERNAL ERROR: attempt to remove from index dimension '%s' on chart '%s', removed a different dimension.", rd->id, st->id);
832
833     // free(rd->annotations);
834     if(rd->mapped == RRD_MEMORY_MODE_SAVE) {
835         debug(D_RRD_CALLS, "Saving dimension '%s' to '%s'.", rd->name, rd->cache_filename);
836         savememory(rd->cache_filename, rd, rd->memsize);
837
838         debug(D_RRD_CALLS, "Unmapping dimension '%s'.", rd->name);
839         munmap(rd, rd->memsize);
840     }
841     else if(rd->mapped == RRD_MEMORY_MODE_MAP) {
842         debug(D_RRD_CALLS, "Unmapping dimension '%s'.", rd->name);
843         munmap(rd, rd->memsize);
844     }
845     else {
846         debug(D_RRD_CALLS, "Removing dimension '%s'.", rd->name);
847         freez(rd);
848     }
849 }
850
851 void rrdset_free_all(void)
852 {
853     info("Freeing all memory...");
854
855     rrdhost_rwlock(&localhost);
856
857     RRDSET *st;
858     for(st = localhost.rrdset_root; st ;) {
859         RRDSET *next = st->next;
860
861         pthread_rwlock_wrlock(&st->rwlock);
862
863         while(st->variables)
864             rrdsetvar_free(st->variables);
865
866         while(st->alarms)
867             rrdsetcalc_unlink(st->alarms);
868
869         while(st->dimensions)
870             rrddim_free(st, st->dimensions);
871
872         if(unlikely(rrdset_index_del(&localhost, st) != st))
873             error("RRDSET: INTERNAL ERROR: attempt to remove from index chart '%s', removed a different chart.", st->id);
874
875         rrdset_index_del_name(&localhost, st);
876
877         st->rrdfamily->use_count--;
878         if(!st->rrdfamily->use_count)
879             rrdfamily_free(st->rrdfamily);
880
881         pthread_rwlock_unlock(&st->rwlock);
882
883         if(st->mapped == RRD_MEMORY_MODE_SAVE) {
884             debug(D_RRD_CALLS, "Saving stats '%s' to '%s'.", st->name, st->cache_filename);
885             savememory(st->cache_filename, st, st->memsize);
886
887             debug(D_RRD_CALLS, "Unmapping stats '%s'.", st->name);
888             munmap(st, st->memsize);
889         }
890         else if(st->mapped == RRD_MEMORY_MODE_MAP) {
891             debug(D_RRD_CALLS, "Unmapping stats '%s'.", st->name);
892             munmap(st, st->memsize);
893         }
894         else
895             freez(st);
896
897         st = next;
898     }
899     localhost.rrdset_root = NULL;
900
901     rrdhost_unlock(&localhost);
902
903     info("Memory cleanup completed...");
904 }
905
906 void rrdset_save_all(void) {
907     info("Saving database...");
908
909     RRDSET *st;
910     RRDDIM *rd;
911
912     rrdhost_rdlock(&localhost);
913     for(st = localhost.rrdset_root; st ; st = st->next) {
914         pthread_rwlock_rdlock(&st->rwlock);
915
916         if(st->mapped == RRD_MEMORY_MODE_SAVE) {
917             debug(D_RRD_CALLS, "Saving stats '%s' to '%s'.", st->name, st->cache_filename);
918             savememory(st->cache_filename, st, st->memsize);
919         }
920
921         for(rd = st->dimensions; rd ; rd = rd->next) {
922             if(likely(rd->mapped == RRD_MEMORY_MODE_SAVE)) {
923                 debug(D_RRD_CALLS, "Saving dimension '%s' to '%s'.", rd->name, rd->cache_filename);
924                 savememory(rd->cache_filename, rd, rd->memsize);
925             }
926         }
927
928         pthread_rwlock_unlock(&st->rwlock);
929     }
930     rrdhost_unlock(&localhost);
931 }
932
933
934 RRDSET *rrdset_find(const char *id)
935 {
936     debug(D_RRD_CALLS, "rrdset_find() for chart %s", id);
937
938     RRDSET *st = rrdset_index_find(&localhost, id, 0);
939     return(st);
940 }
941
942 RRDSET *rrdset_find_bytype(const char *type, const char *id)
943 {
944     debug(D_RRD_CALLS, "rrdset_find_bytype() for chart %s.%s", type, id);
945
946     char buf[RRD_ID_LENGTH_MAX + 1];
947
948     strncpyz(buf, type, RRD_ID_LENGTH_MAX - 1);
949     strcat(buf, ".");
950     int len = (int) strlen(buf);
951     strncpyz(&buf[len], id, (size_t) (RRD_ID_LENGTH_MAX - len));
952
953     return(rrdset_find(buf));
954 }
955
956 RRDSET *rrdset_find_byname(const char *name)
957 {
958     debug(D_RRD_CALLS, "rrdset_find_byname() for chart %s", name);
959
960     RRDSET *st = rrdset_index_find_name(&localhost, name, 0);
961     return(st);
962 }
963
964 RRDDIM *rrddim_find(RRDSET *st, const char *id)
965 {
966     debug(D_RRD_CALLS, "rrddim_find() for chart %s, dimension %s", st->name, id);
967
968     return rrddim_index_find(st, id, 0);
969 }
970
971 int rrddim_hide(RRDSET *st, const char *id)
972 {
973     debug(D_RRD_CALLS, "rrddim_hide() for chart %s, dimension %s", st->name, id);
974
975     RRDDIM *rd = rrddim_find(st, id);
976     if(unlikely(!rd)) {
977         error("Cannot find dimension with id '%s' on stats '%s' (%s).", id, st->name, st->id);
978         return 1;
979     }
980
981     rd->flags |= RRDDIM_FLAG_HIDDEN;
982     return 0;
983 }
984
985 int rrddim_unhide(RRDSET *st, const char *id)
986 {
987     debug(D_RRD_CALLS, "rrddim_unhide() for chart %s, dimension %s", st->name, id);
988
989     RRDDIM *rd = rrddim_find(st, id);
990     if(unlikely(!rd)) {
991         error("Cannot find dimension with id '%s' on stats '%s' (%s).", id, st->name, st->id);
992         return 1;
993     }
994
995     if(rd->flags & RRDDIM_FLAG_HIDDEN) rd->flags ^= RRDDIM_FLAG_HIDDEN;
996     return 0;
997 }
998
999 collected_number rrddim_set_by_pointer(RRDSET *st, RRDDIM *rd, collected_number value)
1000 {
1001     debug(D_RRD_CALLS, "rrddim_set_by_pointer() for chart %s, dimension %s, value " COLLECTED_NUMBER_FORMAT, st->name, rd->name, value);
1002
1003     now_realtime_timeval(&rd->last_collected_time);
1004     rd->collected_value = value;
1005     rd->updated = 1;
1006     rd->counter++;
1007
1008     // fprintf(stderr, "%s.%s %llu " COLLECTED_NUMBER_FORMAT " dt %0.6f" " rate " CALCULATED_NUMBER_FORMAT "\n", st->name, rd->name, st->usec_since_last_update, value, (float)((double)st->usec_since_last_update / (double)1000000), (calculated_number)((value - rd->last_collected_value) * (calculated_number)rd->multiplier / (calculated_number)rd->divisor * 1000000.0 / (calculated_number)st->usec_since_last_update));
1009
1010     return rd->last_collected_value;
1011 }
1012
1013 collected_number rrddim_set(RRDSET *st, const char *id, collected_number value)
1014 {
1015     RRDDIM *rd = rrddim_find(st, id);
1016     if(unlikely(!rd)) {
1017         error("Cannot find dimension with id '%s' on stats '%s' (%s).", id, st->name, st->id);
1018         return 0;
1019     }
1020
1021     return rrddim_set_by_pointer(st, rd, value);
1022 }
1023
1024 void rrdset_next_usec_unfiltered(RRDSET *st, usec_t microseconds)
1025 {
1026     if(unlikely(!st->last_collected_time.tv_sec || !microseconds)) {
1027         // the first entry
1028         microseconds = st->update_every * USEC_PER_SEC;
1029     }
1030     st->usec_since_last_update = microseconds;
1031 }
1032
1033 void rrdset_next_usec(RRDSET *st, usec_t microseconds)
1034 {
1035     struct timeval now;
1036     now_realtime_timeval(&now);
1037
1038     if(unlikely(!st->last_collected_time.tv_sec)) {
1039         // the first entry
1040         microseconds = st->update_every * USEC_PER_SEC;
1041     }
1042     else if(unlikely(!microseconds)) {
1043         // no dt given by the plugin
1044         microseconds = dt_usec(&now, &st->last_collected_time);
1045     }
1046     else {
1047         // microseconds has the time since the last collection
1048         usec_t now_usec = timeval_usec(&now);
1049         usec_t last_usec = timeval_usec(&st->last_collected_time);
1050         usec_t since_last_usec = dt_usec(&now, &st->last_collected_time);
1051
1052         // verify the microseconds given is good
1053         if(unlikely(microseconds > since_last_usec)) {
1054             debug(D_RRD_CALLS, "dt %llu usec given is too big - it leads %llu usec to the future, for chart '%s' (%s).", microseconds, microseconds - since_last_usec, st->name, st->id);
1055
1056 #ifdef NETDATA_INTERNAL_CHECKS
1057             if(unlikely(last_usec + microseconds > now_usec + 1000))
1058                 error("dt %llu usec given is too big - it leads %llu usec to the future, for chart '%s' (%s).", microseconds, microseconds - since_last_usec, st->name, st->id);
1059 #endif
1060
1061             microseconds = since_last_usec;
1062         }
1063         else if(unlikely(microseconds < since_last_usec * 0.8)) {
1064             debug(D_RRD_CALLS, "dt %llu usec given is too small - expected %llu usec up to -20%%, for chart '%s' (%s).", microseconds, since_last_usec, st->name, st->id);
1065
1066 #ifdef NETDATA_INTERNAL_CHECKS
1067             error("dt %llu usec given is too small - expected %llu usec up to -20%%, for chart '%s' (%s).", microseconds, since_last_usec, st->name, st->id);
1068 #endif
1069             microseconds = since_last_usec;
1070         }
1071     }
1072     debug(D_RRD_CALLS, "rrdset_next_usec() for chart %s with microseconds %llu", st->name, microseconds);
1073
1074     if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: NEXT: %llu microseconds", st->name, microseconds);
1075     st->usec_since_last_update = microseconds;
1076 }
1077
1078 usec_t rrdset_done(RRDSET *st)
1079 {
1080     if(unlikely(netdata_exit)) return 0;
1081
1082     debug(D_RRD_CALLS, "rrdset_done() for chart %s", st->name);
1083
1084     RRDDIM *rd;
1085
1086     int
1087         pthreadoldcancelstate;  // store the old cancelable pthread state, to restore it at the end
1088
1089     char
1090         store_this_entry = 1,   // boolean: 1 = store this entry, 0 = don't store this entry
1091         first_entry = 0;        // boolean: 1 = this is the first entry seen for this chart, 0 = all other entries
1092
1093     unsigned int
1094         stored_entries = 0;     // the number of entries we have stored in the db, during this call to rrdset_done()
1095
1096     usec_t
1097         last_collect_ut,        // the timestamp in microseconds, of the last collected value
1098         now_collect_ut,         // the timestamp in microseconds, of this collected value (this is NOW)
1099         last_stored_ut,         // the timestamp in microseconds, of the last stored entry in the db
1100         next_store_ut,          // the timestamp in microseconds, of the next entry to store in the db
1101         update_every_ut = st->update_every * USEC_PER_SEC; // st->update_every in microseconds
1102
1103     if(unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &pthreadoldcancelstate) != 0))
1104         error("Cannot set pthread cancel state to DISABLE.");
1105
1106     // a read lock is OK here
1107     pthread_rwlock_rdlock(&st->rwlock);
1108
1109 /*
1110     // enable the chart, if it was disabled
1111     if(unlikely(rrd_delete_unupdated_dimensions) && !st->enabled)
1112         st->enabled = 1;
1113 */
1114
1115     // check if the chart has a long time to be updated
1116     if(unlikely(st->usec_since_last_update > st->entries * update_every_ut)) {
1117         info("%s: took too long to be updated (%0.3Lf secs). Resetting it.", st->name, (long double)(st->usec_since_last_update / 1000000.0));
1118         rrdset_reset(st);
1119         st->usec_since_last_update = update_every_ut;
1120         first_entry = 1;
1121     }
1122     if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: microseconds since last update: %llu", st->name, st->usec_since_last_update);
1123
1124     // set last_collected_time
1125     if(unlikely(!st->last_collected_time.tv_sec)) {
1126         // it is the first entry
1127         // set the last_collected_time to now
1128         now_realtime_timeval(&st->last_collected_time);
1129         timeval_align(&st->last_collected_time, st->update_every);
1130
1131         last_collect_ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec - update_every_ut;
1132
1133         // the first entry should not be stored
1134         store_this_entry = 0;
1135         first_entry = 1;
1136
1137         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: has not set last_collected_time. Setting it now. Will not store the next entry.", st->name);
1138     }
1139     else {
1140         // it is not the first entry
1141         // calculate the proper last_collected_time, using usec_since_last_update
1142         last_collect_ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec;
1143         usec_t ut = last_collect_ut + st->usec_since_last_update;
1144         st->last_collected_time.tv_sec = (time_t) (ut / USEC_PER_SEC);
1145         st->last_collected_time.tv_usec = (suseconds_t) (ut % USEC_PER_SEC);
1146     }
1147
1148     // if this set has not been updated in the past
1149     // we fake the last_update time to be = now - usec_since_last_update
1150     if(unlikely(!st->last_updated.tv_sec)) {
1151         // it has never been updated before
1152         // set a fake last_updated, in the past using usec_since_last_update
1153         usec_t ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec - st->usec_since_last_update;
1154         st->last_updated.tv_sec = (time_t) (ut / USEC_PER_SEC);
1155         st->last_updated.tv_usec = (suseconds_t) (ut % USEC_PER_SEC);
1156
1157         // the first entry should not be stored
1158         store_this_entry = 0;
1159         first_entry = 1;
1160
1161         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: initializing last_updated to now - %llu microseconds (%0.3Lf). Will not store the next entry.", st->name, st->usec_since_last_update, (long double)ut/1000000.0);
1162     }
1163
1164     // check if we will re-write the entire data set
1165     if(unlikely(dt_usec(&st->last_collected_time, &st->last_updated) > st->entries * update_every_ut)) {
1166         info("%s: too old data (last updated at %ld.%ld, last collected at %ld.%ld). Resetting it. Will not store the next entry.", st->name, st->last_updated.tv_sec, st->last_updated.tv_usec, st->last_collected_time.tv_sec, st->last_collected_time.tv_usec);
1167         rrdset_reset(st);
1168
1169         st->usec_since_last_update = update_every_ut;
1170
1171         now_realtime_timeval(&st->last_collected_time);
1172         timeval_align(&st->last_collected_time, st->update_every);
1173
1174         usec_t ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec - st->usec_since_last_update;
1175         st->last_updated.tv_sec = (time_t) (ut / USEC_PER_SEC);
1176         st->last_updated.tv_usec = (suseconds_t) (ut % USEC_PER_SEC);
1177
1178         // the first entry should not be stored
1179         store_this_entry = 0;
1180         first_entry = 1;
1181     }
1182
1183     // these are the 3 variables that will help us in interpolation
1184     // last_stored_ut = the last time we added a value to the storage
1185     // now_collect_ut = the time the current value has been collected
1186     // next_store_ut  = the time of the next interpolation point
1187     last_stored_ut = st->last_updated.tv_sec * USEC_PER_SEC + st->last_updated.tv_usec;
1188     now_collect_ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec;
1189     next_store_ut  = (st->last_updated.tv_sec + st->update_every) * USEC_PER_SEC;
1190
1191     if(unlikely(st->debug)) {
1192         debug(D_RRD_STATS, "%s: last_collect_ut = %0.3Lf (last collection time)", st->name, (long double)last_collect_ut/1000000.0);
1193         debug(D_RRD_STATS, "%s: now_collect_ut  = %0.3Lf (current collection time)", st->name, (long double)now_collect_ut/1000000.0);
1194         debug(D_RRD_STATS, "%s: last_stored_ut  = %0.3Lf (last updated time)", st->name, (long double)last_stored_ut/1000000.0);
1195         debug(D_RRD_STATS, "%s: next_store_ut   = %0.3Lf (next interpolation point)", st->name, (long double)next_store_ut/1000000.0);
1196     }
1197
1198     if(unlikely(!st->counter_done)) {
1199         store_this_entry = 0;
1200         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: Will not store the next entry.", st->name);
1201     }
1202     st->counter_done++;
1203
1204     // calculate totals and count the dimensions
1205     int dimensions;
1206     st->collected_total = 0;
1207     for( rd = st->dimensions, dimensions = 0 ; rd ; rd = rd->next, dimensions++ )
1208         if(likely(rd->updated)) st->collected_total += rd->collected_value;
1209
1210     uint32_t storage_flags = SN_EXISTS;
1211
1212     // process all dimensions to calculate their values
1213     // based on the collected figures only
1214     // at this stage we do not interpolate anything
1215     for( rd = st->dimensions ; rd ; rd = rd->next ) {
1216
1217         if(unlikely(!rd->updated)) {
1218             rd->calculated_value = 0;
1219             continue;
1220         }
1221
1222         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: START "
1223             " last_collected_value = " COLLECTED_NUMBER_FORMAT
1224             " collected_value = " COLLECTED_NUMBER_FORMAT
1225             " last_calculated_value = " CALCULATED_NUMBER_FORMAT
1226             " calculated_value = " CALCULATED_NUMBER_FORMAT
1227             , st->id, rd->name
1228             , rd->last_collected_value
1229             , rd->collected_value
1230             , rd->last_calculated_value
1231             , rd->calculated_value
1232             );
1233
1234         switch(rd->algorithm) {
1235             case RRDDIM_ABSOLUTE:
1236                 rd->calculated_value = (calculated_number)rd->collected_value
1237                     * (calculated_number)rd->multiplier
1238                     / (calculated_number)rd->divisor;
1239
1240                 if(unlikely(st->debug))
1241                     debug(D_RRD_STATS, "%s/%s: CALC ABS/ABS-NO-IN "
1242                         CALCULATED_NUMBER_FORMAT " = "
1243                         COLLECTED_NUMBER_FORMAT
1244                         " * " CALCULATED_NUMBER_FORMAT
1245                         " / " CALCULATED_NUMBER_FORMAT
1246                         , st->id, rd->name
1247                         , rd->calculated_value
1248                         , rd->collected_value
1249                         , (calculated_number)rd->multiplier
1250                         , (calculated_number)rd->divisor
1251                         );
1252                 break;
1253
1254             case RRDDIM_PCENT_OVER_ROW_TOTAL:
1255                 if(unlikely(!st->collected_total))
1256                     rd->calculated_value = 0;
1257                 else
1258                     // the percentage of the current value
1259                     // over the total of all dimensions
1260                     rd->calculated_value =
1261                           (calculated_number)100
1262                         * (calculated_number)rd->collected_value
1263                         / (calculated_number)st->collected_total;
1264
1265                 if(unlikely(st->debug))
1266                     debug(D_RRD_STATS, "%s/%s: CALC PCENT-ROW "
1267                         CALCULATED_NUMBER_FORMAT " = 100"
1268                         " * " COLLECTED_NUMBER_FORMAT
1269                         " / " COLLECTED_NUMBER_FORMAT
1270                         , st->id, rd->name
1271                         , rd->calculated_value
1272                         , rd->collected_value
1273                         , st->collected_total
1274                         );
1275                 break;
1276
1277             case RRDDIM_INCREMENTAL:
1278                 if(unlikely(rd->counter <= 1)) {
1279                     rd->calculated_value = 0;
1280                     continue;
1281                 }
1282
1283                 // if the new is smaller than the old (an overflow, or reset), set the old equal to the new
1284                 // to reset the calculation (it will give zero as the calculation for this second)
1285                 if(unlikely(rd->last_collected_value > rd->collected_value)) {
1286                     debug(D_RRD_STATS, "%s.%s: RESET or OVERFLOW. Last collected value = " COLLECTED_NUMBER_FORMAT ", current = " COLLECTED_NUMBER_FORMAT
1287                             , st->name, rd->name
1288                             , rd->last_collected_value
1289                             , rd->collected_value);
1290                     if(!(rd->flags & RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)) storage_flags = SN_EXISTS_RESET;
1291                     rd->last_collected_value = rd->collected_value;
1292                 }
1293
1294                 rd->calculated_value +=
1295                       (calculated_number)(rd->collected_value - rd->last_collected_value)
1296                     * (calculated_number)rd->multiplier
1297                     / (calculated_number)rd->divisor;
1298
1299                 if(unlikely(st->debug))
1300                     debug(D_RRD_STATS, "%s/%s: CALC INC PRE "
1301                         CALCULATED_NUMBER_FORMAT " = ("
1302                         COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT
1303                         ")"
1304                         " * " CALCULATED_NUMBER_FORMAT
1305                         " / " CALCULATED_NUMBER_FORMAT
1306                         , st->id, rd->name
1307                         , rd->calculated_value
1308                         , rd->collected_value, rd->last_collected_value
1309                         , (calculated_number)rd->multiplier
1310                         , (calculated_number)rd->divisor
1311                         );
1312                 break;
1313
1314             case RRDDIM_PCENT_OVER_DIFF_TOTAL:
1315                 if(unlikely(rd->counter <= 1)) {
1316                     rd->calculated_value = 0;
1317                     continue;
1318                 }
1319
1320                 // if the new is smaller than the old (an overflow, or reset), set the old equal to the new
1321                 // to reset the calculation (it will give zero as the calculation for this second)
1322                 if(unlikely(rd->last_collected_value > rd->collected_value)) {
1323                     debug(D_RRD_STATS, "%s.%s: RESET or OVERFLOW. Last collected value = " COLLECTED_NUMBER_FORMAT ", current = " COLLECTED_NUMBER_FORMAT
1324                     , st->name, rd->name
1325                     , rd->last_collected_value
1326                     , rd->collected_value);
1327                     if(!(rd->flags & RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)) storage_flags = SN_EXISTS_RESET;
1328                     rd->last_collected_value = rd->collected_value;
1329                 }
1330
1331                 // the percentage of the current increment
1332                 // over the increment of all dimensions together
1333                 if(unlikely(st->collected_total == st->last_collected_total))
1334                     rd->calculated_value = 0;
1335                 else
1336                     rd->calculated_value =
1337                           (calculated_number)100
1338                         * (calculated_number)(rd->collected_value - rd->last_collected_value)
1339                         / (calculated_number)(st->collected_total - st->last_collected_total);
1340
1341                 if(unlikely(st->debug))
1342                     debug(D_RRD_STATS, "%s/%s: CALC PCENT-DIFF "
1343                         CALCULATED_NUMBER_FORMAT " = 100"
1344                         " * (" COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT ")"
1345                         " / (" COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT ")"
1346                         , st->id, rd->name
1347                         , rd->calculated_value
1348                         , rd->collected_value, rd->last_collected_value
1349                         , st->collected_total, st->last_collected_total
1350                         );
1351                 break;
1352
1353             default:
1354                 // make the default zero, to make sure
1355                 // it gets noticed when we add new types
1356                 rd->calculated_value = 0;
1357
1358                 if(unlikely(st->debug))
1359                     debug(D_RRD_STATS, "%s/%s: CALC "
1360                         CALCULATED_NUMBER_FORMAT " = 0"
1361                         , st->id, rd->name
1362                         , rd->calculated_value
1363                         );
1364                 break;
1365         }
1366
1367         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: PHASE2 "
1368             " last_collected_value = " COLLECTED_NUMBER_FORMAT
1369             " collected_value = " COLLECTED_NUMBER_FORMAT
1370             " last_calculated_value = " CALCULATED_NUMBER_FORMAT
1371             " calculated_value = " CALCULATED_NUMBER_FORMAT
1372             , st->id, rd->name
1373             , rd->last_collected_value
1374             , rd->collected_value
1375             , rd->last_calculated_value
1376             , rd->calculated_value
1377             );
1378
1379     }
1380
1381     // at this point we have all the calculated values ready
1382     // it is now time to interpolate values on a second boundary
1383
1384     if(unlikely(now_collect_ut < next_store_ut)) {
1385         // this is collected in the same interpolation point
1386         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: THIS IS IN THE SAME INTERPOLATION POINT", st->name);
1387 #ifdef NETDATA_INTERNAL_CHECKS
1388         info("%s is collected in the same interpolation point: short by %llu microseconds", st->name, next_store_ut - now_collect_ut);
1389 #endif
1390     }
1391
1392     usec_t first_ut = last_stored_ut;
1393     long long iterations = (now_collect_ut - last_stored_ut) / (update_every_ut);
1394     if((now_collect_ut % (update_every_ut)) == 0) iterations++;
1395
1396     for( ; next_store_ut <= now_collect_ut ; last_collect_ut = next_store_ut, next_store_ut += update_every_ut, iterations-- ) {
1397 #ifdef NETDATA_INTERNAL_CHECKS
1398         if(iterations < 0) { error("%s: iterations calculation wrapped! first_ut = %llu, last_stored_ut = %llu, next_store_ut = %llu, now_collect_ut = %llu", st->name, first_ut, last_stored_ut, next_store_ut, now_collect_ut); }
1399 #endif
1400
1401         if(unlikely(st->debug)) {
1402             debug(D_RRD_STATS, "%s: last_stored_ut = %0.3Lf (last updated time)", st->name, (long double)last_stored_ut/1000000.0);
1403             debug(D_RRD_STATS, "%s: next_store_ut  = %0.3Lf (next interpolation point)", st->name, (long double)next_store_ut/1000000.0);
1404         }
1405
1406         st->last_updated.tv_sec = (time_t) (next_store_ut / USEC_PER_SEC);
1407         st->last_updated.tv_usec = 0;
1408
1409         for( rd = st->dimensions ; likely(rd) ; rd = rd->next ) {
1410             calculated_number new_value;
1411
1412             switch(rd->algorithm) {
1413                 case RRDDIM_INCREMENTAL:
1414                     new_value = (calculated_number)
1415                         (      rd->calculated_value
1416                             * (calculated_number)(next_store_ut - last_collect_ut)
1417                             / (calculated_number)(now_collect_ut - last_collect_ut)
1418                         );
1419
1420                     if(unlikely(st->debug))
1421                         debug(D_RRD_STATS, "%s/%s: CALC2 INC "
1422                             CALCULATED_NUMBER_FORMAT " = "
1423                             CALCULATED_NUMBER_FORMAT
1424                             " * %llu"
1425                             " / %llu"
1426                             , st->id, rd->name
1427                             , new_value
1428                             , rd->calculated_value
1429                             , (next_store_ut - last_stored_ut)
1430                             , (now_collect_ut - last_stored_ut)
1431                             );
1432
1433                     rd->calculated_value -= new_value;
1434                     new_value += rd->last_calculated_value;
1435                     rd->last_calculated_value = 0;
1436                     new_value /= (calculated_number)st->update_every;
1437
1438                     if(unlikely(next_store_ut - last_stored_ut < update_every_ut)) {
1439                         if(unlikely(st->debug))
1440                             debug(D_RRD_STATS, "%s/%s: COLLECTION POINT IS SHORT " CALCULATED_NUMBER_FORMAT " - EXTRAPOLATING",
1441                                 st->id, rd->name
1442                                 , (calculated_number)(next_store_ut - last_stored_ut)
1443                                 );
1444                         new_value = new_value * (calculated_number)(st->update_every * 1000000) / (calculated_number)(next_store_ut - last_stored_ut);
1445                     }
1446                     break;
1447
1448                 case RRDDIM_ABSOLUTE:
1449                 case RRDDIM_PCENT_OVER_ROW_TOTAL:
1450                 case RRDDIM_PCENT_OVER_DIFF_TOTAL:
1451                 default:
1452                     if(iterations == 1) {
1453                         // this is the last iteration
1454                         // do not interpolate
1455                         // just show the calculated value
1456
1457                         new_value = rd->calculated_value;
1458                     }
1459                     else {
1460                         // we have missed an update
1461                         // interpolate in the middle values
1462
1463                         new_value = (calculated_number)
1464                             (   (     (rd->calculated_value - rd->last_calculated_value)
1465                                     * (calculated_number)(next_store_ut - last_collect_ut)
1466                                     / (calculated_number)(now_collect_ut - last_collect_ut)
1467                                 )
1468                                 +  rd->last_calculated_value
1469                             );
1470
1471                         if(unlikely(st->debug))
1472                             debug(D_RRD_STATS, "%s/%s: CALC2 DEF "
1473                                 CALCULATED_NUMBER_FORMAT " = ((("
1474                                 "(" CALCULATED_NUMBER_FORMAT " - " CALCULATED_NUMBER_FORMAT ")"
1475                                 " * %llu"
1476                                 " / %llu) + " CALCULATED_NUMBER_FORMAT
1477                                 , st->id, rd->name
1478                                 , new_value
1479                                 , rd->calculated_value, rd->last_calculated_value
1480                                 , (next_store_ut - first_ut)
1481                                 , (now_collect_ut - first_ut), rd->last_calculated_value
1482                                 );
1483                     }
1484                     break;
1485             }
1486
1487             if(unlikely(!store_this_entry)) {
1488                 rd->values[st->current_entry] = pack_storage_number(0, SN_NOT_EXISTS);
1489                 continue;
1490             }
1491
1492             if(likely(rd->updated && rd->counter > 1 && iterations < st->gap_when_lost_iterations_above)) {
1493                 rd->values[st->current_entry] = pack_storage_number(new_value, storage_flags );
1494                 rd->last_stored_value = new_value;
1495
1496                 if(unlikely(st->debug))
1497                     debug(D_RRD_STATS, "%s/%s: STORE[%ld] "
1498                         CALCULATED_NUMBER_FORMAT " = " CALCULATED_NUMBER_FORMAT
1499                         , st->id, rd->name
1500                         , st->current_entry
1501                         , unpack_storage_number(rd->values[st->current_entry]), new_value
1502                         );
1503             }
1504             else {
1505                 if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: STORE[%ld] = NON EXISTING "
1506                         , st->id, rd->name
1507                         , st->current_entry
1508                         );
1509                 rd->values[st->current_entry] = pack_storage_number(0, SN_NOT_EXISTS);
1510                 rd->last_stored_value = NAN;
1511             }
1512
1513             stored_entries++;
1514
1515             if(unlikely(st->debug)) {
1516                 calculated_number t1 = new_value * (calculated_number)rd->multiplier / (calculated_number)rd->divisor;
1517                 calculated_number t2 = unpack_storage_number(rd->values[st->current_entry]);
1518                 calculated_number accuracy = accuracy_loss(t1, t2);
1519                 debug(D_RRD_STATS, "%s/%s: UNPACK[%ld] = " CALCULATED_NUMBER_FORMAT " FLAGS=0x%08x (original = " CALCULATED_NUMBER_FORMAT ", accuracy loss = " CALCULATED_NUMBER_FORMAT "%%%s)"
1520                         , st->id, rd->name
1521                         , st->current_entry
1522                         , t2
1523                         , get_storage_number_flags(rd->values[st->current_entry])
1524                         , t1
1525                         , accuracy
1526                         , (accuracy > ACCURACY_LOSS) ? " **TOO BIG** " : ""
1527                         );
1528
1529                 rd->collected_volume += t1;
1530                 rd->stored_volume += t2;
1531                 accuracy = accuracy_loss(rd->collected_volume, rd->stored_volume);
1532                 debug(D_RRD_STATS, "%s/%s: VOLUME[%ld] = " CALCULATED_NUMBER_FORMAT ", calculated  = " CALCULATED_NUMBER_FORMAT ", accuracy loss = " CALCULATED_NUMBER_FORMAT "%%%s"
1533                         , st->id, rd->name
1534                         , st->current_entry
1535                         , rd->stored_volume
1536                         , rd->collected_volume
1537                         , accuracy
1538                         , (accuracy > ACCURACY_LOSS) ? " **TOO BIG** " : ""
1539                         );
1540
1541             }
1542         }
1543         // reset the storage flags for the next point, if any;
1544         storage_flags = SN_EXISTS;
1545
1546         st->counter++;
1547         st->current_entry = ((st->current_entry + 1) >= st->entries) ? 0 : st->current_entry + 1;
1548         last_stored_ut = next_store_ut;
1549     }
1550
1551     st->last_collected_total  = st->collected_total;
1552
1553     for( rd = st->dimensions; rd ; rd = rd->next ) {
1554         if(unlikely(!rd->updated)) continue;
1555
1556         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: setting last_collected_value (old: " COLLECTED_NUMBER_FORMAT ") to last_collected_value (new: " COLLECTED_NUMBER_FORMAT ")", st->id, rd->name, rd->last_collected_value, rd->collected_value);
1557         rd->last_collected_value = rd->collected_value;
1558
1559         switch(rd->algorithm) {
1560             case RRDDIM_INCREMENTAL:
1561                 if(unlikely(!first_entry)) {
1562                     if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: setting last_calculated_value (old: " CALCULATED_NUMBER_FORMAT ") to last_calculated_value (new: " CALCULATED_NUMBER_FORMAT ")", st->id, rd->name, rd->last_calculated_value + rd->calculated_value, rd->calculated_value);
1563                     rd->last_calculated_value += rd->calculated_value;
1564                 }
1565                 else {
1566                     if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: THIS IS THE FIRST POINT", st->name);
1567                 }
1568                 break;
1569
1570             case RRDDIM_ABSOLUTE:
1571             case RRDDIM_PCENT_OVER_ROW_TOTAL:
1572             case RRDDIM_PCENT_OVER_DIFF_TOTAL:
1573                 if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: setting last_calculated_value (old: " CALCULATED_NUMBER_FORMAT ") to last_calculated_value (new: " CALCULATED_NUMBER_FORMAT ")", st->id, rd->name, rd->last_calculated_value, rd->calculated_value);
1574                 rd->last_calculated_value = rd->calculated_value;
1575                 break;
1576         }
1577
1578         rd->calculated_value = 0;
1579         rd->collected_value = 0;
1580         rd->updated = 0;
1581
1582         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: END "
1583             " last_collected_value = " COLLECTED_NUMBER_FORMAT
1584             " collected_value = " COLLECTED_NUMBER_FORMAT
1585             " last_calculated_value = " CALCULATED_NUMBER_FORMAT
1586             " calculated_value = " CALCULATED_NUMBER_FORMAT
1587             , st->id, rd->name
1588             , rd->last_collected_value
1589             , rd->collected_value
1590             , rd->last_calculated_value
1591             , rd->calculated_value
1592             );
1593     }
1594
1595     // ALL DONE ABOUT THE DATA UPDATE
1596     // --------------------------------------------------------------------
1597
1598 /*
1599     // find if there are any obsolete dimensions (not updated recently)
1600     if(unlikely(rrd_delete_unupdated_dimensions)) {
1601
1602         for( rd = st->dimensions; likely(rd) ; rd = rd->next )
1603             if((rd->last_collected_time.tv_sec + (rrd_delete_unupdated_dimensions * st->update_every)) < st->last_collected_time.tv_sec)
1604                 break;
1605
1606         if(unlikely(rd)) {
1607             RRDDIM *last;
1608             // there is dimension to free
1609             // upgrade our read lock to a write lock
1610             pthread_rwlock_unlock(&st->rwlock);
1611             pthread_rwlock_wrlock(&st->rwlock);
1612
1613             for( rd = st->dimensions, last = NULL ; likely(rd) ; ) {
1614                 // remove it only it is not updated in rrd_delete_unupdated_dimensions seconds
1615
1616                 if(unlikely((rd->last_collected_time.tv_sec + (rrd_delete_unupdated_dimensions * st->update_every)) < st->last_collected_time.tv_sec)) {
1617                     info("Removing obsolete dimension '%s' (%s) of '%s' (%s).", rd->name, rd->id, st->name, st->id);
1618
1619                     if(unlikely(!last)) {
1620                         st->dimensions = rd->next;
1621                         rd->next = NULL;
1622                         rrddim_free(st, rd);
1623                         rd = st->dimensions;
1624                         continue;
1625                     }
1626                     else {
1627                         last->next = rd->next;
1628                         rd->next = NULL;
1629                         rrddim_free(st, rd);
1630                         rd = last->next;
1631                         continue;
1632                     }
1633                 }
1634
1635                 last = rd;
1636                 rd = rd->next;
1637             }
1638
1639             if(unlikely(!st->dimensions)) {
1640                 info("Disabling chart %s (%s) since it does not have any dimensions", st->name, st->id);
1641                 st->enabled = 0;
1642             }
1643         }
1644     }
1645 */
1646
1647     pthread_rwlock_unlock(&st->rwlock);
1648
1649     if(unlikely(pthread_setcancelstate(pthreadoldcancelstate, NULL) != 0))
1650         error("Cannot set pthread cancel state to RESTORE (%d).", pthreadoldcancelstate);
1651
1652     return(st->usec_since_last_update);
1653 }