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