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