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