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