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