]> arthur.barton.de Git - netdata.git/blob - src/rrd.c
fixed chart startup interpolation / extrapolation to allow the first point added...
[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 = time(NULL);
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("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("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("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) avl_insert_lock(&((st)->dimensions_index), (avl *)(rd))
226 #define rrddim_index_del(st,rd ) 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     debug(D_RRD_CALLS, "rrdset_set_name() old: %s, new: %s", st->name, name);
357
358     if(st->name) {
359         rrdset_index_del_name(&localhost, st);
360         rrdsetvar_rename_all(st);
361     }
362
363     char b[CONFIG_MAX_VALUE + 1];
364     char n[RRD_ID_LENGTH_MAX + 1];
365
366     snprintfz(n, RRD_ID_LENGTH_MAX, "%s.%s", st->type, name);
367     rrdset_strncpyz_name(b, n, CONFIG_MAX_VALUE);
368     st->name = config_get(st->id, "name", b);
369     st->hash_name = simple_hash(st->name);
370
371     rrdset_index_add_name(&localhost, st);
372 }
373
374 // ----------------------------------------------------------------------------
375 // cache directory
376
377 char *rrdset_cache_dir(const char *id)
378 {
379     char *ret = NULL;
380
381     static char *cache_dir = NULL;
382     if(!cache_dir) {
383         cache_dir = config_get("global", "cache directory", CACHE_DIR);
384         int r = mkdir(cache_dir, 0755);
385         if(r != 0 && errno != EEXIST)
386             error("Cannot create directory '%s'", cache_dir);
387     }
388
389     char b[FILENAME_MAX + 1];
390     char n[FILENAME_MAX + 1];
391     rrdset_strncpyz_name(b, id, FILENAME_MAX);
392
393     snprintfz(n, FILENAME_MAX, "%s/%s", cache_dir, b);
394     ret = config_get(id, "cache directory", n);
395
396     if(rrd_memory_mode == RRD_MEMORY_MODE_MAP || rrd_memory_mode == RRD_MEMORY_MODE_SAVE) {
397         int r = mkdir(ret, 0775);
398         if(r != 0 && errno != EEXIST)
399             error("Cannot create directory '%s'", ret);
400     }
401
402     return ret;
403 }
404
405 // ----------------------------------------------------------------------------
406 // core functions
407
408 void rrdset_reset(RRDSET *st)
409 {
410     debug(D_RRD_CALLS, "rrdset_reset() %s", st->name);
411
412     st->last_collected_time.tv_sec = 0;
413     st->last_collected_time.tv_usec = 0;
414     st->last_updated.tv_sec = 0;
415     st->last_updated.tv_usec = 0;
416     st->current_entry = 0;
417     st->counter = 0;
418     st->counter_done = 0;
419
420     RRDDIM *rd;
421     for(rd = st->dimensions; rd ; rd = rd->next) {
422         rd->last_collected_time.tv_sec = 0;
423         rd->last_collected_time.tv_usec = 0;
424         rd->counter = 0;
425         bzero(rd->values, rd->entries * sizeof(storage_number));
426     }
427 }
428
429 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)
430 {
431     if(!type || !type[0]) {
432         fatal("Cannot create rrd stats without a type.");
433         return NULL;
434     }
435
436     if(!id || !id[0]) {
437         fatal("Cannot create rrd stats without an id.");
438         return NULL;
439     }
440
441     char fullid[RRD_ID_LENGTH_MAX + 1];
442     char fullfilename[FILENAME_MAX + 1];
443     RRDSET *st = NULL;
444
445     snprintfz(fullid, RRD_ID_LENGTH_MAX, "%s.%s", type, id);
446
447     st = rrdset_find(fullid);
448     if(st) {
449         error("Cannot create rrd stats for '%s', it already exists.", fullid);
450         return st;
451     }
452
453     long entries = config_get_number(fullid, "history", rrd_default_history_entries);
454     if(entries < 5) entries = config_set_number(fullid, "history", 5);
455     if(entries > RRD_HISTORY_ENTRIES_MAX) entries = config_set_number(fullid, "history", RRD_HISTORY_ENTRIES_MAX);
456
457     int enabled = config_get_boolean(fullid, "enabled", 1);
458     if(!enabled) entries = 5;
459
460     unsigned long size = sizeof(RRDSET);
461     char *cache_dir = rrdset_cache_dir(fullid);
462
463     debug(D_RRD_CALLS, "Creating RRD_STATS for '%s.%s'.", type, id);
464
465     snprintfz(fullfilename, FILENAME_MAX, "%s/main.db", cache_dir);
466     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);
467     if(st) {
468         if(strcmp(st->magic, RRDSET_MAGIC) != 0) {
469             errno = 0;
470             info("Initializing file %s.", fullfilename);
471             bzero(st, size);
472         }
473         else if(strcmp(st->id, fullid) != 0) {
474             errno = 0;
475             error("File %s contents are not for chart %s. Clearing it.", fullfilename, fullid);
476             // munmap(st, size);
477             // st = NULL;
478             bzero(st, size);
479         }
480         else if(st->memsize != size || st->entries != entries) {
481             errno = 0;
482             error("File %s does not have the desired size. Clearing it.", fullfilename);
483             bzero(st, size);
484         }
485         else if(st->update_every != update_every) {
486             errno = 0;
487             error("File %s does not have the desired update frequency. Clearing it.", fullfilename);
488             bzero(st, size);
489         }
490         else if((time(NULL) - st->last_updated.tv_sec) > update_every * entries) {
491             errno = 0;
492             error("File %s is too old. Clearing it.", fullfilename);
493             bzero(st, size);
494         }
495     }
496
497     if(st) {
498         st->name = NULL;
499         st->type = NULL;
500         st->family = NULL;
501         st->context = NULL;
502         st->title = NULL;
503         st->units = NULL;
504         st->dimensions = NULL;
505         st->next = NULL;
506         st->mapped = rrd_memory_mode;
507         st->variables = NULL;
508         st->alarms = NULL;
509     }
510     else {
511         st = callocz(1, size);
512         st->mapped = RRD_MEMORY_MODE_RAM;
513     }
514
515     st->memsize = size;
516     st->entries = entries;
517     st->update_every = update_every;
518
519     if(st->current_entry >= st->entries) st->current_entry = 0;
520
521     strcpy(st->cache_filename, fullfilename);
522     strcpy(st->magic, RRDSET_MAGIC);
523
524     strcpy(st->id, fullid);
525     st->hash = simple_hash(st->id);
526
527     st->cache_dir = cache_dir;
528
529     st->chart_type = rrdset_type_id(config_get(st->id, "chart type", rrdset_type_name(chart_type)));
530     st->type       = config_get(st->id, "type", type);
531     st->family     = config_get(st->id, "family", family?family:st->type);
532     st->units      = config_get(st->id, "units", units?units:"");
533
534     st->context    = config_get(st->id, "context", context?context:st->id);
535     st->hash_context = simple_hash(st->context);
536
537     st->priority = config_get_number(st->id, "priority", priority);
538     st->enabled = enabled;
539
540     st->isdetail = 0;
541     st->debug = 0;
542
543     // if(!strcmp(st->id, "disk_util.dm-0")) {
544     //     st->debug = 1;
545     //     error("enabled debugging for '%s'", st->id);
546     // }
547     // else error("not enabled debugging for '%s'", st->id);
548
549     st->green = NAN;
550     st->red = NAN;
551
552     st->last_collected_time.tv_sec = 0;
553     st->last_collected_time.tv_usec = 0;
554     st->counter_done = 0;
555
556     st->gap_when_lost_iterations_above = (int) (
557             config_get_number(st->id, "gap when lost iterations above", RRD_DEFAULT_GAP_INTERPOLATIONS) + 2);
558
559     avl_init_lock(&st->dimensions_index, rrddim_compare);
560     avl_init_lock(&st->variables_root_index, rrdvar_compare);
561
562     pthread_rwlock_init(&st->rwlock, NULL);
563     rrdhost_rwlock(&localhost);
564
565     if(name && *name) rrdset_set_name(st, name);
566     else rrdset_set_name(st, id);
567
568     {
569         char varvalue[CONFIG_MAX_VALUE + 1];
570         snprintfz(varvalue, CONFIG_MAX_VALUE, "%s (%s)", title?title:"", st->name);
571         st->title = config_get(st->id, "title", varvalue);
572     }
573
574     st->rrdfamily = rrdfamily_create(st->family);
575     st->rrdhost = &localhost;
576
577     st->next = localhost.rrdset_root;
578     localhost.rrdset_root = st;
579
580     if(health_enabled) {
581         rrdsetvar_create(st, "last_collected_t", RRDVAR_TYPE_TIME_T, &st->last_collected_time.tv_sec, 0);
582         rrdsetvar_create(st, "collected_total_raw", RRDVAR_TYPE_TOTAL, &st->last_collected_total, 0);
583         rrdsetvar_create(st, "green", RRDVAR_TYPE_CALCULATED, &st->green, 0);
584         rrdsetvar_create(st, "red", RRDVAR_TYPE_CALCULATED, &st->red, 0);
585         rrdsetvar_create(st, "update_every", RRDVAR_TYPE_INT, &st->update_every, 0);
586     }
587
588     rrdset_index_add(&localhost, st);
589
590     rrdsetcalc_link_matching(st);
591     rrdcalctemplate_link_matching(st);
592
593     rrdhost_unlock(&localhost);
594
595     return(st);
596 }
597
598 RRDDIM *rrddim_add(RRDSET *st, const char *id, const char *name, long multiplier, long divisor, int algorithm)
599 {
600     char filename[FILENAME_MAX + 1];
601     char fullfilename[FILENAME_MAX + 1];
602
603     char varname[CONFIG_MAX_NAME + 1];
604     RRDDIM *rd = NULL;
605     unsigned long size = sizeof(RRDDIM) + (st->entries * sizeof(storage_number));
606
607     debug(D_RRD_CALLS, "Adding dimension '%s/%s'.", st->id, id);
608
609     rrdset_strncpyz_name(filename, id, FILENAME_MAX);
610     snprintfz(fullfilename, FILENAME_MAX, "%s/%s.db", st->cache_dir, filename);
611     if(rrd_memory_mode != RRD_MEMORY_MODE_RAM) rd = (RRDDIM *)mymmap(fullfilename, size, ((rrd_memory_mode == RRD_MEMORY_MODE_MAP)?MAP_SHARED:MAP_PRIVATE), 1);
612     if(rd) {
613         struct timeval now;
614         gettimeofday(&now, NULL);
615
616         if(strcmp(rd->magic, RRDDIMENSION_MAGIC) != 0) {
617             errno = 0;
618             info("Initializing file %s.", fullfilename);
619             bzero(rd, size);
620         }
621         else if(rd->memsize != size) {
622             errno = 0;
623             error("File %s does not have the desired size. Clearing it.", fullfilename);
624             bzero(rd, size);
625         }
626         else if(rd->multiplier != multiplier) {
627             errno = 0;
628             error("File %s does not have the same multiplier. Clearing it.", fullfilename);
629             bzero(rd, size);
630         }
631         else if(rd->divisor != divisor) {
632             errno = 0;
633             error("File %s does not have the same divisor. Clearing it.", fullfilename);
634             bzero(rd, size);
635         }
636         else if(rd->algorithm != algorithm) {
637             errno = 0;
638             error("File %s does not have the same algorithm. Clearing it.", fullfilename);
639             bzero(rd, size);
640         }
641         else if(rd->update_every != st->update_every) {
642             errno = 0;
643             error("File %s does not have the same refresh frequency. Clearing it.", fullfilename);
644             bzero(rd, size);
645         }
646         else if(usec_dt(&now, &rd->last_collected_time) > (rd->entries * rd->update_every * 1000000ULL)) {
647             errno = 0;
648             error("File %s is too old. Clearing it.", fullfilename);
649             bzero(rd, size);
650         }
651         else if(strcmp(rd->id, id) != 0) {
652             errno = 0;
653             error("File %s contents are not for dimension %s. Clearing it.", fullfilename, id);
654             // munmap(rd, size);
655             // rd = NULL;
656             bzero(rd, size);
657         }
658     }
659
660     if(rd) {
661         // we have a file mapped for rd
662         rd->mapped = rrd_memory_mode;
663         rd->flags = 0x00000000;
664         rd->variables = NULL;
665         rd->next = NULL;
666         rd->name = NULL;
667     }
668     else {
669         // if we didn't manage to get a mmap'd dimension, just create one
670
671         rd = callocz(1, size);
672         rd->mapped = RRD_MEMORY_MODE_RAM;
673     }
674     rd->memsize = size;
675
676     strcpy(rd->magic, RRDDIMENSION_MAGIC);
677     strcpy(rd->cache_filename, fullfilename);
678     strncpyz(rd->id, id, RRD_ID_LENGTH_MAX);
679     rd->hash = simple_hash(rd->id);
680
681     snprintfz(varname, CONFIG_MAX_NAME, "dim %s name", rd->id);
682     rd->name = config_get(st->id, varname, (name && *name)?name:rd->id);
683
684     snprintfz(varname, CONFIG_MAX_NAME, "dim %s algorithm", rd->id);
685     rd->algorithm = rrddim_algorithm_id(config_get(st->id, varname, rrddim_algorithm_name(algorithm)));
686
687     snprintfz(varname, CONFIG_MAX_NAME, "dim %s multiplier", rd->id);
688     rd->multiplier = config_get_number(st->id, varname, multiplier);
689
690     snprintfz(varname, CONFIG_MAX_NAME, "dim %s divisor", rd->id);
691     rd->divisor = config_get_number(st->id, varname, divisor);
692     if(!rd->divisor) rd->divisor = 1;
693
694     rd->entries = st->entries;
695     rd->update_every = st->update_every;
696
697     // prevent incremental calculation spikes
698     rd->counter = 0;
699     rd->updated = 0;
700     rd->calculated_value = 0;
701     rd->last_calculated_value = 0;
702     rd->collected_value = 0;
703     rd->last_collected_value = 0;
704     rd->collected_volume = 0;
705     rd->stored_volume = 0;
706     rd->last_stored_value = 0;
707     rd->values[st->current_entry] = pack_storage_number(0, SN_NOT_EXISTS);
708     rd->last_collected_time.tv_sec = 0;
709     rd->last_collected_time.tv_usec = 0;
710     rd->rrdset = st;
711
712     // append this dimension
713     pthread_rwlock_wrlock(&st->rwlock);
714     if(!st->dimensions)
715         st->dimensions = rd;
716     else {
717         RRDDIM *td = st->dimensions;
718         for(; td->next; td = td->next) ;
719         td->next = rd;
720     }
721
722     if(health_enabled) {
723         rrddimvar_create(rd, RRDVAR_TYPE_CALCULATED, NULL, NULL, &rd->last_stored_value, 0);
724         rrddimvar_create(rd, RRDVAR_TYPE_COLLECTED, NULL, "_raw", &rd->last_collected_value, 0);
725         rrddimvar_create(rd, RRDVAR_TYPE_TIME_T, NULL, "_last_collected_t", &rd->last_collected_time.tv_sec, 0);
726     }
727
728     pthread_rwlock_unlock(&st->rwlock);
729
730     rrddim_index_add(st, rd);
731
732     return(rd);
733 }
734
735 void rrddim_set_name(RRDSET *st, RRDDIM *rd, const char *name)
736 {
737     debug(D_RRD_CALLS, "rrddim_set_name() %s.%s", st->name, rd->name);
738
739     char varname[CONFIG_MAX_NAME + 1];
740     snprintfz(varname, CONFIG_MAX_NAME, "dim %s name", rd->id);
741     config_set_default(st->id, varname, name);
742
743     rrddimvar_rename_all(rd);
744 }
745
746 void rrddim_free(RRDSET *st, RRDDIM *rd)
747 {
748     debug(D_RRD_CALLS, "rrddim_free() %s.%s", st->name, rd->name);
749
750     if(rd == st->dimensions)
751         st->dimensions = rd->next;
752     else {
753         RRDDIM *i;
754         for (i = st->dimensions; i && i->next != rd; i = i->next) ;
755
756         if (i && i->next == rd)
757             i->next = rd->next;
758         else
759             error("Request to free dimension '%s.%s' but it is not linked.", st->id, rd->name);
760     }
761     rd->next = NULL;
762
763     while(rd->variables)
764         rrddimvar_free(rd->variables);
765
766     rrddim_index_del(st, rd);
767
768     // free(rd->annotations);
769     if(rd->mapped == RRD_MEMORY_MODE_SAVE) {
770         debug(D_RRD_CALLS, "Saving dimension '%s' to '%s'.", rd->name, rd->cache_filename);
771         savememory(rd->cache_filename, rd, rd->memsize);
772
773         debug(D_RRD_CALLS, "Unmapping dimension '%s'.", rd->name);
774         munmap(rd, rd->memsize);
775     }
776     else if(rd->mapped == RRD_MEMORY_MODE_MAP) {
777         debug(D_RRD_CALLS, "Unmapping dimension '%s'.", rd->name);
778         munmap(rd, rd->memsize);
779     }
780     else {
781         debug(D_RRD_CALLS, "Removing dimension '%s'.", rd->name);
782         freez(rd);
783     }
784 }
785
786 void rrdset_free_all(void)
787 {
788     info("Freeing all memory...");
789
790     rrdhost_rwlock(&localhost);
791
792     RRDSET *st;
793     for(st = localhost.rrdset_root; st ;) {
794         RRDSET *next = st->next;
795
796         pthread_rwlock_wrlock(&st->rwlock);
797
798         while(st->variables)
799             rrdsetvar_free(st->variables);
800
801         while(st->alarms)
802             rrdsetcalc_unlink(st->alarms);
803
804         while(st->dimensions)
805             rrddim_free(st, st->dimensions);
806
807         rrdset_index_del(&localhost, st);
808
809         st->rrdfamily->use_count--;
810         if(!st->rrdfamily->use_count)
811             rrdfamily_free(st->rrdfamily);
812
813         pthread_rwlock_unlock(&st->rwlock);
814
815         if(st->mapped == RRD_MEMORY_MODE_SAVE) {
816             debug(D_RRD_CALLS, "Saving stats '%s' to '%s'.", st->name, st->cache_filename);
817             savememory(st->cache_filename, st, st->memsize);
818
819             debug(D_RRD_CALLS, "Unmapping stats '%s'.", st->name);
820             munmap(st, st->memsize);
821         }
822         else if(st->mapped == RRD_MEMORY_MODE_MAP) {
823             debug(D_RRD_CALLS, "Unmapping stats '%s'.", st->name);
824             munmap(st, st->memsize);
825         }
826         else
827             freez(st);
828
829         st = next;
830     }
831     localhost.rrdset_root = NULL;
832
833     rrdhost_unlock(&localhost);
834
835     info("Memory cleanup completed...");
836 }
837
838 void rrdset_save_all(void) {
839     info("Saving database...");
840
841     RRDSET *st;
842     RRDDIM *rd;
843
844     rrdhost_rwlock(&localhost);
845     for(st = localhost.rrdset_root; st ; st = st->next) {
846         pthread_rwlock_wrlock(&st->rwlock);
847
848         if(st->mapped == RRD_MEMORY_MODE_SAVE) {
849             debug(D_RRD_CALLS, "Saving stats '%s' to '%s'.", st->name, st->cache_filename);
850             savememory(st->cache_filename, st, st->memsize);
851         }
852
853         for(rd = st->dimensions; rd ; rd = rd->next) {
854             if(likely(rd->mapped == RRD_MEMORY_MODE_SAVE)) {
855                 debug(D_RRD_CALLS, "Saving dimension '%s' to '%s'.", rd->name, rd->cache_filename);
856                 savememory(rd->cache_filename, rd, rd->memsize);
857             }
858         }
859
860         pthread_rwlock_unlock(&st->rwlock);
861     }
862     rrdhost_unlock(&localhost);
863 }
864
865
866 RRDSET *rrdset_find(const char *id)
867 {
868     debug(D_RRD_CALLS, "rrdset_find() for chart %s", id);
869
870     RRDSET *st = rrdset_index_find(&localhost, id, 0);
871     return(st);
872 }
873
874 RRDSET *rrdset_find_bytype(const char *type, const char *id)
875 {
876     debug(D_RRD_CALLS, "rrdset_find_bytype() for chart %s.%s", type, id);
877
878     char buf[RRD_ID_LENGTH_MAX + 1];
879
880     strncpyz(buf, type, RRD_ID_LENGTH_MAX - 1);
881     strcat(buf, ".");
882     int len = (int) strlen(buf);
883     strncpyz(&buf[len], id, (size_t) (RRD_ID_LENGTH_MAX - len));
884
885     return(rrdset_find(buf));
886 }
887
888 RRDSET *rrdset_find_byname(const char *name)
889 {
890     debug(D_RRD_CALLS, "rrdset_find_byname() for chart %s", name);
891
892     RRDSET *st = rrdset_index_find_name(&localhost, name, 0);
893     return(st);
894 }
895
896 RRDDIM *rrddim_find(RRDSET *st, const char *id)
897 {
898     debug(D_RRD_CALLS, "rrddim_find() for chart %s, dimension %s", st->name, id);
899
900     return rrddim_index_find(st, id, 0);
901 }
902
903 int rrddim_hide(RRDSET *st, const char *id)
904 {
905     debug(D_RRD_CALLS, "rrddim_hide() for chart %s, dimension %s", st->name, id);
906
907     RRDDIM *rd = rrddim_find(st, id);
908     if(unlikely(!rd)) {
909         error("Cannot find dimension with id '%s' on stats '%s' (%s).", id, st->name, st->id);
910         return 1;
911     }
912
913     rd->flags |= RRDDIM_FLAG_HIDDEN;
914     return 0;
915 }
916
917 int rrddim_unhide(RRDSET *st, const char *id)
918 {
919     debug(D_RRD_CALLS, "rrddim_unhide() for chart %s, dimension %s", st->name, id);
920
921     RRDDIM *rd = rrddim_find(st, id);
922     if(unlikely(!rd)) {
923         error("Cannot find dimension with id '%s' on stats '%s' (%s).", id, st->name, st->id);
924         return 1;
925     }
926
927     if(rd->flags & RRDDIM_FLAG_HIDDEN) rd->flags ^= RRDDIM_FLAG_HIDDEN;
928     return 0;
929 }
930
931 collected_number rrddim_set_by_pointer(RRDSET *st, RRDDIM *rd, collected_number value)
932 {
933     debug(D_RRD_CALLS, "rrddim_set_by_pointer() for chart %s, dimension %s, value " COLLECTED_NUMBER_FORMAT, st->name, rd->name, value);
934
935     gettimeofday(&rd->last_collected_time, NULL);
936     rd->collected_value = value;
937     rd->updated = 1;
938     rd->counter++;
939
940     return rd->last_collected_value;
941 }
942
943 collected_number rrddim_set(RRDSET *st, const char *id, collected_number value)
944 {
945     RRDDIM *rd = rrddim_find(st, id);
946     if(unlikely(!rd)) {
947         error("Cannot find dimension with id '%s' on stats '%s' (%s).", id, st->name, st->id);
948         return 0;
949     }
950
951     return rrddim_set_by_pointer(st, rd, value);
952 }
953
954 void rrdset_next_usec(RRDSET *st, unsigned long long microseconds)
955 {
956     if(!microseconds) rrdset_next(st);
957     else {
958         debug(D_RRD_CALLS, "rrdset_next_usec() for chart %s with microseconds %llu", st->name, microseconds);
959
960         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: NEXT: %llu microseconds", st->name, microseconds);
961         st->usec_since_last_update = microseconds;
962     }
963 }
964
965 void rrdset_next(RRDSET *st)
966 {
967     unsigned long long microseconds = 0;
968
969     if(likely(st->last_collected_time.tv_sec)) {
970         struct timeval now;
971         gettimeofday(&now, NULL);
972         microseconds = usec_dt(&now, &st->last_collected_time);
973     }
974     // prevent infinite loop
975     else microseconds = st->update_every * 1000000ULL;
976
977     rrdset_next_usec(st, microseconds);
978 }
979
980 void rrdset_next_plugins(RRDSET *st)
981 {
982     rrdset_next(st);
983 }
984
985 unsigned long long rrdset_done(RRDSET *st)
986 {
987     if(unlikely(netdata_exit)) return 0;
988
989     debug(D_RRD_CALLS, "rrdset_done() for chart %s", st->name);
990
991     RRDDIM *rd;
992
993     int
994         pthreadoldcancelstate;  // store the old cancelable pthread state, to restore it at the end
995
996     char
997         store_this_entry = 1,   // boolean: 1 = store this entry, 0 = don't store this entry
998         first_entry = 0;        // boolean: 1 = this is the first entry seen for this chart, 0 = all other entries
999
1000     unsigned int
1001         stored_entries = 0;     // the number of entries we have stored in the db, during this call to rrdset_done()
1002
1003     unsigned long long
1004         last_collect_ut,        // the timestamp in microseconds, of the last collected value
1005         now_collect_ut,         // the timestamp in microseconds, of this collected value (this is NOW)
1006         last_stored_ut,         // the timestamp in microseconds, of the last stored entry in the db
1007         next_store_ut,          // the timestamp in microseconds, of the next entry to store in the db
1008         update_every_ut = st->update_every * 1000000ULL; // st->update_every in microseconds
1009
1010     if(unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &pthreadoldcancelstate) != 0))
1011         error("Cannot set pthread cancel state to DISABLE.");
1012
1013     // a read lock is OK here
1014     pthread_rwlock_rdlock(&st->rwlock);
1015
1016 /*
1017     // enable the chart, if it was disabled
1018     if(unlikely(rrd_delete_unupdated_dimensions) && !st->enabled)
1019         st->enabled = 1;
1020 */
1021
1022     // check if the chart has a long time to be updated
1023     if(unlikely(st->usec_since_last_update > st->entries * update_every_ut)) {
1024         info("%s: took too long to be updated (%0.3Lf secs). Reseting it.", st->name, (long double)(st->usec_since_last_update / 1000000.0));
1025         rrdset_reset(st);
1026         st->usec_since_last_update = update_every_ut;
1027         first_entry = 1;
1028     }
1029     if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: microseconds since last update: %llu", st->name, st->usec_since_last_update);
1030
1031     // set last_collected_time
1032     if(unlikely(!st->last_collected_time.tv_sec)) {
1033         // it is the first entry
1034         // set the last_collected_time to now
1035         gettimeofday(&st->last_collected_time, NULL);
1036         last_collect_ut = st->last_collected_time.tv_sec * 1000000ULL + st->last_collected_time.tv_usec - update_every_ut;
1037
1038         // the first entry should not be stored
1039         store_this_entry = 0;
1040         first_entry = 1;
1041
1042         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);
1043     }
1044     else {
1045         // it is not the first entry
1046         // calculate the proper last_collected_time, using usec_since_last_update
1047         last_collect_ut = st->last_collected_time.tv_sec * 1000000ULL + st->last_collected_time.tv_usec;
1048         unsigned long long ut = last_collect_ut + st->usec_since_last_update;
1049         st->last_collected_time.tv_sec = (time_t) (ut / 1000000ULL);
1050         st->last_collected_time.tv_usec = (suseconds_t) (ut % 1000000ULL);
1051     }
1052
1053     // if this set has not been updated in the past
1054     // we fake the last_update time to be = now - usec_since_last_update
1055     if(unlikely(!st->last_updated.tv_sec)) {
1056         // it has never been updated before
1057         // set a fake last_updated, in the past using usec_since_last_update
1058         unsigned long long ut = st->last_collected_time.tv_sec * 1000000ULL + st->last_collected_time.tv_usec - st->usec_since_last_update;
1059         st->last_updated.tv_sec = (time_t) (ut / 1000000ULL);
1060         st->last_updated.tv_usec = (suseconds_t) (ut % 1000000ULL);
1061
1062         // the first entry should not be stored
1063         store_this_entry = 0;
1064         first_entry = 1;
1065
1066         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);
1067     }
1068
1069     // check if we will re-write the entire data set
1070     if(unlikely(usec_dt(&st->last_collected_time, &st->last_updated) > st->entries * update_every_ut)) {
1071         info("%s: too old data (last updated at %ld.%ld, last collected at %ld.%ld). Reseting 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);
1072         rrdset_reset(st);
1073
1074         st->usec_since_last_update = update_every_ut;
1075
1076         gettimeofday(&st->last_collected_time, NULL);
1077
1078         unsigned long long ut = st->last_collected_time.tv_sec * 1000000ULL + st->last_collected_time.tv_usec - st->usec_since_last_update;
1079         st->last_updated.tv_sec = (time_t) (ut / 1000000ULL);
1080         st->last_updated.tv_usec = (suseconds_t) (ut % 1000000ULL);
1081
1082         // the first entry should not be stored
1083         store_this_entry = 0;
1084         first_entry = 1;
1085     }
1086
1087     // these are the 3 variables that will help us in interpolation
1088     // last_stored_ut = the last time we added a value to the storage
1089     // now_collect_ut = the time the current value has been collected
1090     // next_store_ut  = the time of the next interpolation point
1091     last_stored_ut = st->last_updated.tv_sec * 1000000ULL + st->last_updated.tv_usec;
1092     now_collect_ut = st->last_collected_time.tv_sec * 1000000ULL + st->last_collected_time.tv_usec;
1093     next_store_ut  = (st->last_updated.tv_sec + st->update_every) * 1000000ULL;
1094
1095     if(unlikely(st->debug)) {
1096         debug(D_RRD_STATS, "%s: last_collect_ut = %0.3Lf (last collection time)", st->name, (long double)last_collect_ut/1000000.0);
1097         debug(D_RRD_STATS, "%s: now_collect_ut  = %0.3Lf (current collection time)", st->name, (long double)now_collect_ut/1000000.0);
1098         debug(D_RRD_STATS, "%s: last_stored_ut  = %0.3Lf (last updated time)", st->name, (long double)last_stored_ut/1000000.0);
1099         debug(D_RRD_STATS, "%s: next_store_ut   = %0.3Lf (next interpolation point)", st->name, (long double)next_store_ut/1000000.0);
1100     }
1101
1102     if(unlikely(!st->counter_done)) {
1103         store_this_entry = 0;
1104         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: Will not store the next entry.", st->name);
1105     }
1106     st->counter_done++;
1107
1108     // calculate totals and count the dimensions
1109     int dimensions;
1110     st->collected_total = 0;
1111     for( rd = st->dimensions, dimensions = 0 ; rd ; rd = rd->next, dimensions++ )
1112         if(likely(rd->updated)) st->collected_total += rd->collected_value;
1113
1114     uint32_t storage_flags = SN_EXISTS;
1115
1116     // process all dimensions to calculate their values
1117     // based on the collected figures only
1118     // at this stage we do not interpolate anything
1119     for( rd = st->dimensions ; rd ; rd = rd->next ) {
1120
1121         if(unlikely(!rd->updated)) {
1122             rd->calculated_value = 0;
1123             continue;
1124         }
1125
1126         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: START "
1127             " last_collected_value = " COLLECTED_NUMBER_FORMAT
1128             " collected_value = " COLLECTED_NUMBER_FORMAT
1129             " last_calculated_value = " CALCULATED_NUMBER_FORMAT
1130             " calculated_value = " CALCULATED_NUMBER_FORMAT
1131             , st->id, rd->name
1132             , rd->last_collected_value
1133             , rd->collected_value
1134             , rd->last_calculated_value
1135             , rd->calculated_value
1136             );
1137
1138         switch(rd->algorithm) {
1139             case RRDDIM_ABSOLUTE:
1140                 rd->calculated_value = (calculated_number)rd->collected_value
1141                     * (calculated_number)rd->multiplier
1142                     / (calculated_number)rd->divisor;
1143
1144                 if(unlikely(st->debug))
1145                     debug(D_RRD_STATS, "%s/%s: CALC ABS/ABS-NO-IN "
1146                         CALCULATED_NUMBER_FORMAT " = "
1147                         COLLECTED_NUMBER_FORMAT
1148                         " * " CALCULATED_NUMBER_FORMAT
1149                         " / " CALCULATED_NUMBER_FORMAT
1150                         , st->id, rd->name
1151                         , rd->calculated_value
1152                         , rd->collected_value
1153                         , (calculated_number)rd->multiplier
1154                         , (calculated_number)rd->divisor
1155                         );
1156                 break;
1157
1158             case RRDDIM_PCENT_OVER_ROW_TOTAL:
1159                 if(unlikely(!st->collected_total))
1160                     rd->calculated_value = 0;
1161                 else
1162                     // the percentage of the current value
1163                     // over the total of all dimensions
1164                     rd->calculated_value =
1165                           (calculated_number)100
1166                         * (calculated_number)rd->collected_value
1167                         / (calculated_number)st->collected_total;
1168
1169                 if(unlikely(st->debug))
1170                     debug(D_RRD_STATS, "%s/%s: CALC PCENT-ROW "
1171                         CALCULATED_NUMBER_FORMAT " = 100"
1172                         " * " COLLECTED_NUMBER_FORMAT
1173                         " / " COLLECTED_NUMBER_FORMAT
1174                         , st->id, rd->name
1175                         , rd->calculated_value
1176                         , rd->collected_value
1177                         , st->collected_total
1178                         );
1179                 break;
1180
1181             case RRDDIM_INCREMENTAL:
1182                 if(unlikely(rd->counter <= 1)) {
1183                     rd->calculated_value = 0;
1184                     continue;
1185                 }
1186
1187                 // if the new is smaller than the old (an overflow, or reset), set the old equal to the new
1188                 // to reset the calculation (it will give zero as the calculation for this second)
1189                 if(unlikely(rd->last_collected_value > rd->collected_value)) {
1190                     debug(D_RRD_STATS, "%s.%s: RESET or OVERFLOW. Last collected value = " COLLECTED_NUMBER_FORMAT ", current = " COLLECTED_NUMBER_FORMAT
1191                             , st->name, rd->name
1192                             , rd->last_collected_value
1193                             , rd->collected_value);
1194                     if(!(rd->flags & RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)) storage_flags = SN_EXISTS_RESET;
1195                     rd->last_collected_value = rd->collected_value;
1196                 }
1197
1198                 rd->calculated_value +=
1199                       (calculated_number)(rd->collected_value - rd->last_collected_value)
1200                     * (calculated_number)rd->multiplier
1201                     / (calculated_number)rd->divisor;
1202
1203                 if(unlikely(st->debug))
1204                     debug(D_RRD_STATS, "%s/%s: CALC INC PRE "
1205                         CALCULATED_NUMBER_FORMAT " = ("
1206                         COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT
1207                         ")"
1208                         " * " CALCULATED_NUMBER_FORMAT
1209                         " / " CALCULATED_NUMBER_FORMAT
1210                         , st->id, rd->name
1211                         , rd->calculated_value
1212                         , rd->collected_value, rd->last_collected_value
1213                         , (calculated_number)rd->multiplier
1214                         , (calculated_number)rd->divisor
1215                         );
1216                 break;
1217
1218             case RRDDIM_PCENT_OVER_DIFF_TOTAL:
1219                 if(unlikely(rd->counter <= 1)) {
1220                     rd->calculated_value = 0;
1221                     continue;
1222                 }
1223
1224                 // if the new is smaller than the old (an overflow, or reset), set the old equal to the new
1225                 // to reset the calculation (it will give zero as the calculation for this second)
1226                 if(unlikely(rd->last_collected_value > rd->collected_value)) {
1227                     debug(D_RRD_STATS, "%s.%s: RESET or OVERFLOW. Last collected value = " COLLECTED_NUMBER_FORMAT ", current = " COLLECTED_NUMBER_FORMAT
1228                     , st->name, rd->name
1229                     , rd->last_collected_value
1230                     , rd->collected_value);
1231                     if(!(rd->flags & RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)) storage_flags = SN_EXISTS_RESET;
1232                     rd->last_collected_value = rd->collected_value;
1233                 }
1234
1235                 // the percentage of the current increment
1236                 // over the increment of all dimensions together
1237                 if(unlikely(st->collected_total == st->last_collected_total))
1238                     rd->calculated_value = 0;
1239                 else
1240                     rd->calculated_value =
1241                           (calculated_number)100
1242                         * (calculated_number)(rd->collected_value - rd->last_collected_value)
1243                         / (calculated_number)(st->collected_total - st->last_collected_total);
1244
1245                 if(unlikely(st->debug))
1246                     debug(D_RRD_STATS, "%s/%s: CALC PCENT-DIFF "
1247                         CALCULATED_NUMBER_FORMAT " = 100"
1248                         " * (" COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT ")"
1249                         " / (" COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT ")"
1250                         , st->id, rd->name
1251                         , rd->calculated_value
1252                         , rd->collected_value, rd->last_collected_value
1253                         , st->collected_total, st->last_collected_total
1254                         );
1255                 break;
1256
1257             default:
1258                 // make the default zero, to make sure
1259                 // it gets noticed when we add new types
1260                 rd->calculated_value = 0;
1261
1262                 if(unlikely(st->debug))
1263                     debug(D_RRD_STATS, "%s/%s: CALC "
1264                         CALCULATED_NUMBER_FORMAT " = 0"
1265                         , st->id, rd->name
1266                         , rd->calculated_value
1267                         );
1268                 break;
1269         }
1270
1271         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: PHASE2 "
1272             " last_collected_value = " COLLECTED_NUMBER_FORMAT
1273             " collected_value = " COLLECTED_NUMBER_FORMAT
1274             " last_calculated_value = " CALCULATED_NUMBER_FORMAT
1275             " calculated_value = " CALCULATED_NUMBER_FORMAT
1276             , st->id, rd->name
1277             , rd->last_collected_value
1278             , rd->collected_value
1279             , rd->last_calculated_value
1280             , rd->calculated_value
1281             );
1282
1283     }
1284
1285     // at this point we have all the calculated values ready
1286     // it is now time to interpolate values on a second boundary
1287
1288     if(unlikely(now_collect_ut < next_store_ut)) {
1289         // this is collected in the same interpolation point
1290         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: THIS IS IN THE SAME INTERPOLATION POINT", st->name);
1291     }
1292
1293     unsigned long long first_ut = last_stored_ut;
1294     long long iterations = (now_collect_ut - last_stored_ut) / (update_every_ut);
1295     if((now_collect_ut % (update_every_ut)) == 0) iterations++;
1296
1297     for( ; next_store_ut <= now_collect_ut ; next_store_ut += update_every_ut, iterations-- ) {
1298 #ifdef NETDATA_INTERNAL_CHECKS
1299         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); }
1300 #endif
1301
1302         if(unlikely(st->debug)) {
1303             debug(D_RRD_STATS, "%s: last_stored_ut = %0.3Lf (last updated time)", st->name, (long double)last_stored_ut/1000000.0);
1304             debug(D_RRD_STATS, "%s: next_store_ut  = %0.3Lf (next interpolation point)", st->name, (long double)next_store_ut/1000000.0);
1305         }
1306
1307         st->last_updated.tv_sec = (time_t) (next_store_ut / 1000000ULL);
1308         st->last_updated.tv_usec = 0;
1309
1310         for( rd = st->dimensions ; likely(rd) ; rd = rd->next ) {
1311             calculated_number new_value;
1312
1313             switch(rd->algorithm) {
1314                 case RRDDIM_INCREMENTAL:
1315                     new_value = (calculated_number)
1316                         (      rd->calculated_value
1317                             * (calculated_number)(next_store_ut - last_collect_ut)
1318                             / (calculated_number)(now_collect_ut - last_collect_ut)
1319                         );
1320
1321                     if(unlikely(st->debug))
1322                         debug(D_RRD_STATS, "%s/%s: CALC2 INC "
1323                             CALCULATED_NUMBER_FORMAT " = "
1324                             CALCULATED_NUMBER_FORMAT
1325                             " * %llu"
1326                             " / %llu"
1327                             , st->id, rd->name
1328                             , new_value
1329                             , rd->calculated_value
1330                             , (next_store_ut - last_stored_ut)
1331                             , (now_collect_ut - last_stored_ut)
1332                             );
1333
1334                     rd->calculated_value -= new_value;
1335                     new_value += rd->last_calculated_value;
1336                     rd->last_calculated_value = 0;
1337                     new_value /= (calculated_number)st->update_every;
1338
1339                     if(unlikely(next_store_ut - last_stored_ut < update_every_ut)) {
1340                         if(unlikely(st->debug))
1341                             debug(D_RRD_STATS, "%s/%s: COLLECTION POINT IS SHORT " CALCULATED_NUMBER_FORMAT " - EXTRAPOLATING",
1342                                 st->id, rd->name
1343                                 , (calculated_number)(next_store_ut - last_stored_ut)
1344                                 );
1345                         new_value = new_value * (calculated_number)(st->update_every * 1000000) / (calculated_number)(next_store_ut - last_stored_ut);
1346                     }
1347
1348                     last_collect_ut = next_store_ut;
1349                     break;
1350
1351                 case RRDDIM_ABSOLUTE:
1352                 case RRDDIM_PCENT_OVER_ROW_TOTAL:
1353                 case RRDDIM_PCENT_OVER_DIFF_TOTAL:
1354                 default:
1355                     if(iterations == 1) {
1356                         // this is the last iteration
1357                         // do not interpolate
1358                         // just show the calculated value
1359
1360                         new_value = rd->calculated_value;
1361                     }
1362                     else {
1363                         // we have missed an update
1364                         // interpolate in the middle values
1365
1366                         new_value = (calculated_number)
1367                             (   (     (rd->calculated_value - rd->last_calculated_value)
1368                                     * (calculated_number)(next_store_ut - last_collect_ut)
1369                                     / (calculated_number)(now_collect_ut - last_collect_ut)
1370                                 )
1371                                 +  rd->last_calculated_value
1372                             );
1373
1374                         if(unlikely(st->debug))
1375                             debug(D_RRD_STATS, "%s/%s: CALC2 DEF "
1376                                 CALCULATED_NUMBER_FORMAT " = ((("
1377                                 "(" CALCULATED_NUMBER_FORMAT " - " CALCULATED_NUMBER_FORMAT ")"
1378                                 " * %llu"
1379                                 " / %llu) + " CALCULATED_NUMBER_FORMAT
1380                                 , st->id, rd->name
1381                                 , new_value
1382                                 , rd->calculated_value, rd->last_calculated_value
1383                                 , (next_store_ut - first_ut)
1384                                 , (now_collect_ut - first_ut), rd->last_calculated_value
1385                                 );
1386                     }
1387                     break;
1388             }
1389
1390             if(unlikely(!store_this_entry))
1391                 continue;
1392
1393             if(likely(rd->updated && rd->counter > 1 && iterations < st->gap_when_lost_iterations_above)) {
1394                 rd->values[st->current_entry] = pack_storage_number(new_value, storage_flags );
1395                 rd->last_stored_value = new_value;
1396
1397                 if(unlikely(st->debug))
1398                     debug(D_RRD_STATS, "%s/%s: STORE[%ld] "
1399                         CALCULATED_NUMBER_FORMAT " = " CALCULATED_NUMBER_FORMAT
1400                         , st->id, rd->name
1401                         , st->current_entry
1402                         , unpack_storage_number(rd->values[st->current_entry]), new_value
1403                         );
1404             }
1405             else {
1406                 if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: STORE[%ld] = NON EXISTING "
1407                         , st->id, rd->name
1408                         , st->current_entry
1409                         );
1410                 rd->values[st->current_entry] = pack_storage_number(0, SN_NOT_EXISTS);
1411                 rd->last_stored_value = NAN;
1412             }
1413
1414             stored_entries++;
1415
1416             if(unlikely(st->debug)) {
1417                 calculated_number t1 = new_value * (calculated_number)rd->multiplier / (calculated_number)rd->divisor;
1418                 calculated_number t2 = unpack_storage_number(rd->values[st->current_entry]);
1419                 calculated_number accuracy = accuracy_loss(t1, t2);
1420                 debug(D_RRD_STATS, "%s/%s: UNPACK[%ld] = " CALCULATED_NUMBER_FORMAT " FLAGS=0x%08x (original = " CALCULATED_NUMBER_FORMAT ", accuracy loss = " CALCULATED_NUMBER_FORMAT "%%%s)"
1421                         , st->id, rd->name
1422                         , st->current_entry
1423                         , t2
1424                         , get_storage_number_flags(rd->values[st->current_entry])
1425                         , t1
1426                         , accuracy
1427                         , (accuracy > ACCURACY_LOSS) ? " **TOO BIG** " : ""
1428                         );
1429
1430                 rd->collected_volume += t1;
1431                 rd->stored_volume += t2;
1432                 accuracy = accuracy_loss(rd->collected_volume, rd->stored_volume);
1433                 debug(D_RRD_STATS, "%s/%s: VOLUME[%ld] = " CALCULATED_NUMBER_FORMAT ", calculated  = " CALCULATED_NUMBER_FORMAT ", accuracy loss = " CALCULATED_NUMBER_FORMAT "%%%s"
1434                         , st->id, rd->name
1435                         , st->current_entry
1436                         , rd->stored_volume
1437                         , rd->collected_volume
1438                         , accuracy
1439                         , (accuracy > ACCURACY_LOSS) ? " **TOO BIG** " : ""
1440                         );
1441
1442             }
1443         }
1444         // reset the storage flags for the next point, if any;
1445         storage_flags = SN_EXISTS;
1446
1447         st->counter++;
1448         st->current_entry = ((st->current_entry + 1) >= st->entries) ? 0 : st->current_entry + 1;
1449         last_stored_ut = next_store_ut;
1450     }
1451
1452     st->last_collected_total  = st->collected_total;
1453
1454     for( rd = st->dimensions; rd ; rd = rd->next ) {
1455         if(unlikely(!rd->updated)) continue;
1456
1457         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);
1458         rd->last_collected_value = rd->collected_value;
1459
1460         switch(rd->algorithm) {
1461             case RRDDIM_INCREMENTAL:
1462                 if(unlikely(!first_entry)) {
1463                     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);
1464                     rd->last_calculated_value += rd->calculated_value;
1465                 }
1466                 else {
1467                     if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: THIS IS THE FIRST POINT", st->name);
1468                 }
1469                 break;
1470
1471             case RRDDIM_ABSOLUTE:
1472             case RRDDIM_PCENT_OVER_ROW_TOTAL:
1473             case RRDDIM_PCENT_OVER_DIFF_TOTAL:
1474                 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);
1475                 rd->last_calculated_value = rd->calculated_value;
1476                 break;
1477         }
1478
1479         rd->calculated_value = 0;
1480         rd->collected_value = 0;
1481         rd->updated = 0;
1482
1483         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: END "
1484             " last_collected_value = " COLLECTED_NUMBER_FORMAT
1485             " collected_value = " COLLECTED_NUMBER_FORMAT
1486             " last_calculated_value = " CALCULATED_NUMBER_FORMAT
1487             " calculated_value = " CALCULATED_NUMBER_FORMAT
1488             , st->id, rd->name
1489             , rd->last_collected_value
1490             , rd->collected_value
1491             , rd->last_calculated_value
1492             , rd->calculated_value
1493             );
1494     }
1495
1496     // ALL DONE ABOUT THE DATA UPDATE
1497     // --------------------------------------------------------------------
1498
1499 /*
1500     // find if there are any obsolete dimensions (not updated recently)
1501     if(unlikely(rrd_delete_unupdated_dimensions)) {
1502
1503         for( rd = st->dimensions; likely(rd) ; rd = rd->next )
1504             if((rd->last_collected_time.tv_sec + (rrd_delete_unupdated_dimensions * st->update_every)) < st->last_collected_time.tv_sec)
1505                 break;
1506
1507         if(unlikely(rd)) {
1508             RRDDIM *last;
1509             // there is dimension to free
1510             // upgrade our read lock to a write lock
1511             pthread_rwlock_unlock(&st->rwlock);
1512             pthread_rwlock_wrlock(&st->rwlock);
1513
1514             for( rd = st->dimensions, last = NULL ; likely(rd) ; ) {
1515                 // remove it only it is not updated in rrd_delete_unupdated_dimensions seconds
1516
1517                 if(unlikely((rd->last_collected_time.tv_sec + (rrd_delete_unupdated_dimensions * st->update_every)) < st->last_collected_time.tv_sec)) {
1518                     info("Removing obsolete dimension '%s' (%s) of '%s' (%s).", rd->name, rd->id, st->name, st->id);
1519
1520                     if(unlikely(!last)) {
1521                         st->dimensions = rd->next;
1522                         rd->next = NULL;
1523                         rrddim_free(st, rd);
1524                         rd = st->dimensions;
1525                         continue;
1526                     }
1527                     else {
1528                         last->next = rd->next;
1529                         rd->next = NULL;
1530                         rrddim_free(st, rd);
1531                         rd = last->next;
1532                         continue;
1533                     }
1534                 }
1535
1536                 last = rd;
1537                 rd = rd->next;
1538             }
1539
1540             if(unlikely(!st->dimensions)) {
1541                 info("Disabling chart %s (%s) since it does not have any dimensions", st->name, st->id);
1542                 st->enabled = 0;
1543             }
1544         }
1545     }
1546 */
1547
1548     pthread_rwlock_unlock(&st->rwlock);
1549
1550     if(unlikely(pthread_setcancelstate(pthreadoldcancelstate, NULL) != 0))
1551         error("Cannot set pthread cancel state to RESTORE (%d).", pthreadoldcancelstate);
1552
1553     return(st->usec_since_last_update);
1554 }