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