]> arthur.barton.de Git - netdata.git/blob - src/rrd.c
timing issues are logged as errors only when NETDATA_INTERNAL_CHECKS is defined
[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     debug(D_RRD_CALLS, "rrdset_set_name() old: %s, new: %s", st->name, name);
357
358     if(st->name) {
359         rrdset_index_del_name(&localhost, st);
360         rrdsetvar_rename_all(st);
361     }
362
363     char b[CONFIG_MAX_VALUE + 1];
364     char n[RRD_ID_LENGTH_MAX + 1];
365
366     snprintfz(n, RRD_ID_LENGTH_MAX, "%s.%s", st->type, name);
367     rrdset_strncpyz_name(b, n, CONFIG_MAX_VALUE);
368     st->name = config_get(st->id, "name", b);
369     st->hash_name = simple_hash(st->name);
370
371     rrdset_index_add_name(&localhost, st);
372 }
373
374 // ----------------------------------------------------------------------------
375 // cache directory
376
377 char *rrdset_cache_dir(const char *id)
378 {
379     char *ret = NULL;
380
381     static char *cache_dir = NULL;
382     if(!cache_dir) {
383         cache_dir = config_get("global", "cache directory", CACHE_DIR);
384         int r = mkdir(cache_dir, 0755);
385         if(r != 0 && errno != EEXIST)
386             error("Cannot create directory '%s'", cache_dir);
387     }
388
389     char b[FILENAME_MAX + 1];
390     char n[FILENAME_MAX + 1];
391     rrdset_strncpyz_name(b, id, FILENAME_MAX);
392
393     snprintfz(n, FILENAME_MAX, "%s/%s", cache_dir, b);
394     ret = config_get(id, "cache directory", n);
395
396     if(rrd_memory_mode == RRD_MEMORY_MODE_MAP || rrd_memory_mode == RRD_MEMORY_MODE_SAVE) {
397         int r = mkdir(ret, 0775);
398         if(r != 0 && errno != EEXIST)
399             error("Cannot create directory '%s'", ret);
400     }
401
402     return ret;
403 }
404
405 // ----------------------------------------------------------------------------
406 // core functions
407
408 void rrdset_reset(RRDSET *st)
409 {
410     debug(D_RRD_CALLS, "rrdset_reset() %s", st->name);
411
412     st->last_collected_time.tv_sec = 0;
413     st->last_collected_time.tv_usec = 0;
414     st->last_updated.tv_sec = 0;
415     st->last_updated.tv_usec = 0;
416     st->current_entry = 0;
417     st->counter = 0;
418     st->counter_done = 0;
419
420     RRDDIM *rd;
421     for(rd = st->dimensions; rd ; rd = rd->next) {
422         rd->last_collected_time.tv_sec = 0;
423         rd->last_collected_time.tv_usec = 0;
424         rd->counter = 0;
425         memset(rd->values, 0, rd->entries * sizeof(storage_number));
426     }
427 }
428 static long align_entries_to_pagesize(long entries) {
429     if(entries < 5) entries = 5;
430     if(entries > RRD_HISTORY_ENTRIES_MAX) entries = RRD_HISTORY_ENTRIES_MAX;
431
432 #ifdef NETDATA_LOG_ALLOCATIONS
433     long page = (size_t)sysconf(_SC_PAGESIZE);
434
435     long size = sizeof(RRDDIM) + entries * sizeof(storage_number);
436     if(size % page) {
437         size -= (size % page);
438         size += page;
439
440         long n = (size - sizeof(RRDDIM)) / sizeof(storage_number);
441         return n;
442     }
443
444     return entries;
445 #else
446     return entries;
447 #endif
448 }
449
450 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)
451 {
452     if(!type || !type[0]) {
453         fatal("Cannot create rrd stats without a type.");
454         return NULL;
455     }
456
457     if(!id || !id[0]) {
458         fatal("Cannot create rrd stats without an id.");
459         return NULL;
460     }
461
462     char fullid[RRD_ID_LENGTH_MAX + 1];
463     char fullfilename[FILENAME_MAX + 1];
464     RRDSET *st = NULL;
465
466     snprintfz(fullid, RRD_ID_LENGTH_MAX, "%s.%s", type, id);
467
468     st = rrdset_find(fullid);
469     if(st) {
470         error("Cannot create rrd stats for '%s', it already exists.", fullid);
471         return st;
472     }
473
474     long rentries = config_get_number(fullid, "history", rrd_default_history_entries);
475     long entries = align_entries_to_pagesize(rentries);
476     if(entries != rentries) entries = config_set_number(fullid, "history", entries);
477
478     int enabled = config_get_boolean(fullid, "enabled", 1);
479     if(!enabled) entries = 5;
480
481     unsigned long size = sizeof(RRDSET);
482     char *cache_dir = rrdset_cache_dir(fullid);
483
484     debug(D_RRD_CALLS, "Creating RRD_STATS for '%s.%s'.", type, id);
485
486     snprintfz(fullfilename, FILENAME_MAX, "%s/main.db", cache_dir);
487     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);
488     if(st) {
489         if(strcmp(st->magic, RRDSET_MAGIC) != 0) {
490             errno = 0;
491             info("Initializing file %s.", fullfilename);
492             memset(st, 0, size);
493         }
494         else if(strcmp(st->id, fullid) != 0) {
495             errno = 0;
496             error("File %s contents are not for chart %s. Clearing it.", fullfilename, fullid);
497             // munmap(st, size);
498             // st = NULL;
499             memset(st, 0, size);
500         }
501         else if(st->memsize != size || st->entries != entries) {
502             errno = 0;
503             error("File %s does not have the desired size. Clearing it.", fullfilename);
504             memset(st, 0, size);
505         }
506         else if(st->update_every != update_every) {
507             errno = 0;
508             error("File %s does not have the desired update frequency. Clearing it.", fullfilename);
509             memset(st, 0, size);
510         }
511         else if((time(NULL) - st->last_updated.tv_sec) > update_every * entries) {
512             errno = 0;
513             error("File %s is too old. Clearing it.", fullfilename);
514             memset(st, 0, size);
515         }
516     }
517
518     if(st) {
519         st->name = NULL;
520         st->type = NULL;
521         st->family = NULL;
522         st->context = NULL;
523         st->title = NULL;
524         st->units = NULL;
525         st->dimensions = NULL;
526         st->next = NULL;
527         st->mapped = rrd_memory_mode;
528         st->variables = NULL;
529         st->alarms = NULL;
530     }
531     else {
532         st = callocz(1, size);
533         st->mapped = RRD_MEMORY_MODE_RAM;
534     }
535
536     st->memsize = size;
537     st->entries = entries;
538     st->update_every = update_every;
539
540     if(st->current_entry >= st->entries) st->current_entry = 0;
541
542     strcpy(st->cache_filename, fullfilename);
543     strcpy(st->magic, RRDSET_MAGIC);
544
545     strcpy(st->id, fullid);
546     st->hash = simple_hash(st->id);
547
548     st->cache_dir = cache_dir;
549
550     st->chart_type = rrdset_type_id(config_get(st->id, "chart type", rrdset_type_name(chart_type)));
551     st->type       = config_get(st->id, "type", type);
552     st->family     = config_get(st->id, "family", family?family:st->type);
553     st->units      = config_get(st->id, "units", units?units:"");
554
555     st->context    = config_get(st->id, "context", context?context:st->id);
556     st->hash_context = simple_hash(st->context);
557
558     st->priority = config_get_number(st->id, "priority", priority);
559     st->enabled = enabled;
560
561     st->isdetail = 0;
562     st->debug = 0;
563
564     // if(!strcmp(st->id, "disk_util.dm-0")) {
565     //     st->debug = 1;
566     //     error("enabled debugging for '%s'", st->id);
567     // }
568     // else error("not enabled debugging for '%s'", st->id);
569
570     st->green = NAN;
571     st->red = NAN;
572
573     st->last_collected_time.tv_sec = 0;
574     st->last_collected_time.tv_usec = 0;
575     st->counter_done = 0;
576
577     st->gap_when_lost_iterations_above = (int) (
578             config_get_number(st->id, "gap when lost iterations above", RRD_DEFAULT_GAP_INTERPOLATIONS) + 2);
579
580     avl_init_lock(&st->dimensions_index, rrddim_compare);
581     avl_init_lock(&st->variables_root_index, rrdvar_compare);
582
583     pthread_rwlock_init(&st->rwlock, NULL);
584     rrdhost_rwlock(&localhost);
585
586     if(name && *name) rrdset_set_name(st, name);
587     else rrdset_set_name(st, id);
588
589     {
590         char varvalue[CONFIG_MAX_VALUE + 1];
591         snprintfz(varvalue, CONFIG_MAX_VALUE, "%s (%s)", title?title:"", st->name);
592         st->title = config_get(st->id, "title", varvalue);
593     }
594
595     st->rrdfamily = rrdfamily_create(st->family);
596     st->rrdhost = &localhost;
597
598     st->next = localhost.rrdset_root;
599     localhost.rrdset_root = st;
600
601     if(health_enabled) {
602         rrdsetvar_create(st, "last_collected_t", RRDVAR_TYPE_TIME_T, &st->last_collected_time.tv_sec, 0);
603         rrdsetvar_create(st, "collected_total_raw", RRDVAR_TYPE_TOTAL, &st->last_collected_total, 0);
604         rrdsetvar_create(st, "green", RRDVAR_TYPE_CALCULATED, &st->green, 0);
605         rrdsetvar_create(st, "red", RRDVAR_TYPE_CALCULATED, &st->red, 0);
606         rrdsetvar_create(st, "update_every", RRDVAR_TYPE_INT, &st->update_every, 0);
607     }
608
609     rrdset_index_add(&localhost, st);
610
611     rrdsetcalc_link_matching(st);
612     rrdcalctemplate_link_matching(st);
613
614     rrdhost_unlock(&localhost);
615
616     return(st);
617 }
618
619 RRDDIM *rrddim_add(RRDSET *st, const char *id, const char *name, long multiplier, long divisor, int algorithm)
620 {
621     char filename[FILENAME_MAX + 1];
622     char fullfilename[FILENAME_MAX + 1];
623
624     char varname[CONFIG_MAX_NAME + 1];
625     RRDDIM *rd = NULL;
626     unsigned long size = sizeof(RRDDIM) + (st->entries * sizeof(storage_number));
627
628     debug(D_RRD_CALLS, "Adding dimension '%s/%s'.", st->id, id);
629
630     rrdset_strncpyz_name(filename, id, FILENAME_MAX);
631     snprintfz(fullfilename, FILENAME_MAX, "%s/%s.db", st->cache_dir, filename);
632     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);
633     if(rd) {
634         struct timeval now;
635         gettimeofday(&now, NULL);
636
637         if(strcmp(rd->magic, RRDDIMENSION_MAGIC) != 0) {
638             errno = 0;
639             info("Initializing file %s.", fullfilename);
640             memset(rd, 0, size);
641         }
642         else if(rd->memsize != size) {
643             errno = 0;
644             error("File %s does not have the desired size. Clearing it.", fullfilename);
645             memset(rd, 0, size);
646         }
647         else if(rd->multiplier != multiplier) {
648             errno = 0;
649             error("File %s does not have the same multiplier. Clearing it.", fullfilename);
650             memset(rd, 0, size);
651         }
652         else if(rd->divisor != divisor) {
653             errno = 0;
654             error("File %s does not have the same divisor. Clearing it.", fullfilename);
655             memset(rd, 0, size);
656         }
657         else if(rd->algorithm != algorithm) {
658             errno = 0;
659             error("File %s does not have the same algorithm. Clearing it.", fullfilename);
660             memset(rd, 0, size);
661         }
662         else if(rd->update_every != st->update_every) {
663             errno = 0;
664             error("File %s does not have the same refresh frequency. Clearing it.", fullfilename);
665             memset(rd, 0, size);
666         }
667         else if(usec_dt(&now, &rd->last_collected_time) > (rd->entries * rd->update_every * 1000000ULL)) {
668             errno = 0;
669             error("File %s is too old. Clearing it.", fullfilename);
670             memset(rd, 0, size);
671         }
672         else if(strcmp(rd->id, id) != 0) {
673             errno = 0;
674             error("File %s contents are not for dimension %s. Clearing it.", fullfilename, id);
675             // munmap(rd, size);
676             // rd = NULL;
677             memset(rd, 0, size);
678         }
679     }
680
681     if(rd) {
682         // we have a file mapped for rd
683         rd->mapped = rrd_memory_mode;
684         rd->flags = 0x00000000;
685         rd->variables = NULL;
686         rd->next = NULL;
687         rd->name = NULL;
688     }
689     else {
690         // if we didn't manage to get a mmap'd dimension, just create one
691
692         rd = callocz(1, size);
693         rd->mapped = RRD_MEMORY_MODE_RAM;
694     }
695     rd->memsize = size;
696
697     strcpy(rd->magic, RRDDIMENSION_MAGIC);
698     strcpy(rd->cache_filename, fullfilename);
699     strncpyz(rd->id, id, RRD_ID_LENGTH_MAX);
700     rd->hash = simple_hash(rd->id);
701
702     snprintfz(varname, CONFIG_MAX_NAME, "dim %s name", rd->id);
703     rd->name = config_get(st->id, varname, (name && *name)?name:rd->id);
704
705     snprintfz(varname, CONFIG_MAX_NAME, "dim %s algorithm", rd->id);
706     rd->algorithm = rrddim_algorithm_id(config_get(st->id, varname, rrddim_algorithm_name(algorithm)));
707
708     snprintfz(varname, CONFIG_MAX_NAME, "dim %s multiplier", rd->id);
709     rd->multiplier = config_get_number(st->id, varname, multiplier);
710
711     snprintfz(varname, CONFIG_MAX_NAME, "dim %s divisor", rd->id);
712     rd->divisor = config_get_number(st->id, varname, divisor);
713     if(!rd->divisor) rd->divisor = 1;
714
715     rd->entries = st->entries;
716     rd->update_every = st->update_every;
717
718     // prevent incremental calculation spikes
719     rd->counter = 0;
720     rd->updated = 0;
721     rd->calculated_value = 0;
722     rd->last_calculated_value = 0;
723     rd->collected_value = 0;
724     rd->last_collected_value = 0;
725     rd->collected_volume = 0;
726     rd->stored_volume = 0;
727     rd->last_stored_value = 0;
728     rd->values[st->current_entry] = pack_storage_number(0, SN_NOT_EXISTS);
729     rd->last_collected_time.tv_sec = 0;
730     rd->last_collected_time.tv_usec = 0;
731     rd->rrdset = st;
732
733     // append this dimension
734     pthread_rwlock_wrlock(&st->rwlock);
735     if(!st->dimensions)
736         st->dimensions = rd;
737     else {
738         RRDDIM *td = st->dimensions;
739         for(; td->next; td = td->next) ;
740         td->next = rd;
741     }
742
743     if(health_enabled) {
744         rrddimvar_create(rd, RRDVAR_TYPE_CALCULATED, NULL, NULL, &rd->last_stored_value, 0);
745         rrddimvar_create(rd, RRDVAR_TYPE_COLLECTED, NULL, "_raw", &rd->last_collected_value, 0);
746         rrddimvar_create(rd, RRDVAR_TYPE_TIME_T, NULL, "_last_collected_t", &rd->last_collected_time.tv_sec, 0);
747     }
748
749     pthread_rwlock_unlock(&st->rwlock);
750
751     rrddim_index_add(st, rd);
752
753     return(rd);
754 }
755
756 void rrddim_set_name(RRDSET *st, RRDDIM *rd, const char *name)
757 {
758     debug(D_RRD_CALLS, "rrddim_set_name() %s.%s", st->name, rd->name);
759
760     char varname[CONFIG_MAX_NAME + 1];
761     snprintfz(varname, CONFIG_MAX_NAME, "dim %s name", rd->id);
762     config_set_default(st->id, varname, name);
763
764     rrddimvar_rename_all(rd);
765 }
766
767 void rrddim_free(RRDSET *st, RRDDIM *rd)
768 {
769     debug(D_RRD_CALLS, "rrddim_free() %s.%s", st->name, rd->name);
770
771     if(rd == st->dimensions)
772         st->dimensions = rd->next;
773     else {
774         RRDDIM *i;
775         for (i = st->dimensions; i && i->next != rd; i = i->next) ;
776
777         if (i && i->next == rd)
778             i->next = rd->next;
779         else
780             error("Request to free dimension '%s.%s' but it is not linked.", st->id, rd->name);
781     }
782     rd->next = NULL;
783
784     while(rd->variables)
785         rrddimvar_free(rd->variables);
786
787     rrddim_index_del(st, rd);
788
789     // free(rd->annotations);
790     if(rd->mapped == RRD_MEMORY_MODE_SAVE) {
791         debug(D_RRD_CALLS, "Saving dimension '%s' to '%s'.", rd->name, rd->cache_filename);
792         savememory(rd->cache_filename, rd, rd->memsize);
793
794         debug(D_RRD_CALLS, "Unmapping dimension '%s'.", rd->name);
795         munmap(rd, rd->memsize);
796     }
797     else if(rd->mapped == RRD_MEMORY_MODE_MAP) {
798         debug(D_RRD_CALLS, "Unmapping dimension '%s'.", rd->name);
799         munmap(rd, rd->memsize);
800     }
801     else {
802         debug(D_RRD_CALLS, "Removing dimension '%s'.", rd->name);
803         freez(rd);
804     }
805 }
806
807 void rrdset_free_all(void)
808 {
809     info("Freeing all memory...");
810
811     rrdhost_rwlock(&localhost);
812
813     RRDSET *st;
814     for(st = localhost.rrdset_root; st ;) {
815         RRDSET *next = st->next;
816
817         pthread_rwlock_wrlock(&st->rwlock);
818
819         while(st->variables)
820             rrdsetvar_free(st->variables);
821
822         while(st->alarms)
823             rrdsetcalc_unlink(st->alarms);
824
825         while(st->dimensions)
826             rrddim_free(st, st->dimensions);
827
828         rrdset_index_del(&localhost, st);
829
830         st->rrdfamily->use_count--;
831         if(!st->rrdfamily->use_count)
832             rrdfamily_free(st->rrdfamily);
833
834         pthread_rwlock_unlock(&st->rwlock);
835
836         if(st->mapped == RRD_MEMORY_MODE_SAVE) {
837             debug(D_RRD_CALLS, "Saving stats '%s' to '%s'.", st->name, st->cache_filename);
838             savememory(st->cache_filename, st, st->memsize);
839
840             debug(D_RRD_CALLS, "Unmapping stats '%s'.", st->name);
841             munmap(st, st->memsize);
842         }
843         else if(st->mapped == RRD_MEMORY_MODE_MAP) {
844             debug(D_RRD_CALLS, "Unmapping stats '%s'.", st->name);
845             munmap(st, st->memsize);
846         }
847         else
848             freez(st);
849
850         st = next;
851     }
852     localhost.rrdset_root = NULL;
853
854     rrdhost_unlock(&localhost);
855
856     info("Memory cleanup completed...");
857 }
858
859 void rrdset_save_all(void) {
860     info("Saving database...");
861
862     RRDSET *st;
863     RRDDIM *rd;
864
865     rrdhost_rwlock(&localhost);
866     for(st = localhost.rrdset_root; st ; st = st->next) {
867         pthread_rwlock_wrlock(&st->rwlock);
868
869         if(st->mapped == RRD_MEMORY_MODE_SAVE) {
870             debug(D_RRD_CALLS, "Saving stats '%s' to '%s'.", st->name, st->cache_filename);
871             savememory(st->cache_filename, st, st->memsize);
872         }
873
874         for(rd = st->dimensions; rd ; rd = rd->next) {
875             if(likely(rd->mapped == RRD_MEMORY_MODE_SAVE)) {
876                 debug(D_RRD_CALLS, "Saving dimension '%s' to '%s'.", rd->name, rd->cache_filename);
877                 savememory(rd->cache_filename, rd, rd->memsize);
878             }
879         }
880
881         pthread_rwlock_unlock(&st->rwlock);
882     }
883     rrdhost_unlock(&localhost);
884 }
885
886
887 RRDSET *rrdset_find(const char *id)
888 {
889     debug(D_RRD_CALLS, "rrdset_find() for chart %s", id);
890
891     RRDSET *st = rrdset_index_find(&localhost, id, 0);
892     return(st);
893 }
894
895 RRDSET *rrdset_find_bytype(const char *type, const char *id)
896 {
897     debug(D_RRD_CALLS, "rrdset_find_bytype() for chart %s.%s", type, id);
898
899     char buf[RRD_ID_LENGTH_MAX + 1];
900
901     strncpyz(buf, type, RRD_ID_LENGTH_MAX - 1);
902     strcat(buf, ".");
903     int len = (int) strlen(buf);
904     strncpyz(&buf[len], id, (size_t) (RRD_ID_LENGTH_MAX - len));
905
906     return(rrdset_find(buf));
907 }
908
909 RRDSET *rrdset_find_byname(const char *name)
910 {
911     debug(D_RRD_CALLS, "rrdset_find_byname() for chart %s", name);
912
913     RRDSET *st = rrdset_index_find_name(&localhost, name, 0);
914     return(st);
915 }
916
917 RRDDIM *rrddim_find(RRDSET *st, const char *id)
918 {
919     debug(D_RRD_CALLS, "rrddim_find() for chart %s, dimension %s", st->name, id);
920
921     return rrddim_index_find(st, id, 0);
922 }
923
924 int rrddim_hide(RRDSET *st, const char *id)
925 {
926     debug(D_RRD_CALLS, "rrddim_hide() for chart %s, dimension %s", st->name, id);
927
928     RRDDIM *rd = rrddim_find(st, id);
929     if(unlikely(!rd)) {
930         error("Cannot find dimension with id '%s' on stats '%s' (%s).", id, st->name, st->id);
931         return 1;
932     }
933
934     rd->flags |= RRDDIM_FLAG_HIDDEN;
935     return 0;
936 }
937
938 int rrddim_unhide(RRDSET *st, const char *id)
939 {
940     debug(D_RRD_CALLS, "rrddim_unhide() for chart %s, dimension %s", st->name, id);
941
942     RRDDIM *rd = rrddim_find(st, id);
943     if(unlikely(!rd)) {
944         error("Cannot find dimension with id '%s' on stats '%s' (%s).", id, st->name, st->id);
945         return 1;
946     }
947
948     if(rd->flags & RRDDIM_FLAG_HIDDEN) rd->flags ^= RRDDIM_FLAG_HIDDEN;
949     return 0;
950 }
951
952 collected_number rrddim_set_by_pointer(RRDSET *st, RRDDIM *rd, collected_number value)
953 {
954     debug(D_RRD_CALLS, "rrddim_set_by_pointer() for chart %s, dimension %s, value " COLLECTED_NUMBER_FORMAT, st->name, rd->name, value);
955
956     gettimeofday(&rd->last_collected_time, NULL);
957     rd->collected_value = value;
958     rd->updated = 1;
959     rd->counter++;
960
961     // 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));
962
963     return rd->last_collected_value;
964 }
965
966 collected_number rrddim_set(RRDSET *st, const char *id, collected_number value)
967 {
968     RRDDIM *rd = rrddim_find(st, id);
969     if(unlikely(!rd)) {
970         error("Cannot find dimension with id '%s' on stats '%s' (%s).", id, st->name, st->id);
971         return 0;
972     }
973
974     return rrddim_set_by_pointer(st, rd, value);
975 }
976
977 void rrdset_next_usec_unfiltered(RRDSET *st, unsigned long long microseconds)
978 {
979     if(unlikely(!st->last_collected_time.tv_sec || !microseconds)) {
980         // the first entry
981         microseconds = st->update_every * 1000000ULL;
982     }
983     st->usec_since_last_update = microseconds;
984 }
985
986 void rrdset_next_usec(RRDSET *st, unsigned long long microseconds)
987 {
988     struct timeval now;
989     gettimeofday(&now, NULL);
990
991     if(unlikely(!st->last_collected_time.tv_sec)) {
992         // the first entry
993         microseconds = st->update_every * 1000000ULL;
994     }
995     else if(unlikely(!microseconds)) {
996         // no dt given by the plugin
997         microseconds = usec_dt(&now, &st->last_collected_time);
998     }
999     else {
1000         // microseconds has the time since the last collection
1001         unsigned long long now_usec = timeval_usec(&now);
1002         unsigned long long last_usec = timeval_usec(&st->last_collected_time);
1003         unsigned long long since_last_usec = usec_dt(&now, &st->last_collected_time);
1004
1005         // verify the microseconds given is good
1006         if(unlikely(last_usec + microseconds > now_usec)) {
1007             debug(D_RRD_CALLS, "dt %llu usec given is too big - it leads %llu usec to the future, for chart '%s' (%s).", microseconds, last_usec + microseconds - now_usec, st->name, st->id);
1008
1009 #ifdef NETDATA_INTERNAL_CHECKS
1010             if(unlikely(last_usec + microseconds > now_usec + 1000))
1011                 error("dt %llu usec given is too big - it leads %llu usec to the future, for chart '%s' (%s).", microseconds, last_usec + microseconds - now_usec, st->name, st->id);
1012 #endif
1013
1014             microseconds = since_last_usec;
1015         }
1016         else if(unlikely(microseconds < since_last_usec * 0.8 || microseconds > since_last_usec * 1.2)) {
1017             debug(D_RRD_CALLS, "dt %llu usec given is wrong - expected %llu usec +/- 20%%, for chart '%s' (%s).", microseconds, since_last_usec, st->name, st->id);
1018
1019 #ifdef NETDATA_INTERNAL_CHECKS
1020             error("dt %llu usec given is wrong - expected %llu usec +/- 20%%, for chart '%s' (%s).", microseconds, since_last_usec, st->name, st->id);
1021 #endif
1022             microseconds = since_last_usec;
1023         }
1024     }
1025     debug(D_RRD_CALLS, "rrdset_next_usec() for chart %s with microseconds %llu", st->name, microseconds);
1026
1027     if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: NEXT: %llu microseconds", st->name, microseconds);
1028     st->usec_since_last_update = microseconds;
1029 }
1030
1031 unsigned long long rrdset_done(RRDSET *st)
1032 {
1033     if(unlikely(netdata_exit)) return 0;
1034
1035     debug(D_RRD_CALLS, "rrdset_done() for chart %s", st->name);
1036
1037     RRDDIM *rd;
1038
1039     int
1040         pthreadoldcancelstate;  // store the old cancelable pthread state, to restore it at the end
1041
1042     char
1043         store_this_entry = 1,   // boolean: 1 = store this entry, 0 = don't store this entry
1044         first_entry = 0;        // boolean: 1 = this is the first entry seen for this chart, 0 = all other entries
1045
1046     unsigned int
1047         stored_entries = 0;     // the number of entries we have stored in the db, during this call to rrdset_done()
1048
1049     unsigned long long
1050         last_collect_ut,        // the timestamp in microseconds, of the last collected value
1051         now_collect_ut,         // the timestamp in microseconds, of this collected value (this is NOW)
1052         last_stored_ut,         // the timestamp in microseconds, of the last stored entry in the db
1053         next_store_ut,          // the timestamp in microseconds, of the next entry to store in the db
1054         update_every_ut = st->update_every * 1000000ULL; // st->update_every in microseconds
1055
1056     if(unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &pthreadoldcancelstate) != 0))
1057         error("Cannot set pthread cancel state to DISABLE.");
1058
1059     // a read lock is OK here
1060     pthread_rwlock_rdlock(&st->rwlock);
1061
1062 /*
1063     // enable the chart, if it was disabled
1064     if(unlikely(rrd_delete_unupdated_dimensions) && !st->enabled)
1065         st->enabled = 1;
1066 */
1067
1068     // check if the chart has a long time to be updated
1069     if(unlikely(st->usec_since_last_update > st->entries * update_every_ut)) {
1070         info("%s: took too long to be updated (%0.3Lf secs). Reseting it.", st->name, (long double)(st->usec_since_last_update / 1000000.0));
1071         rrdset_reset(st);
1072         st->usec_since_last_update = update_every_ut;
1073         first_entry = 1;
1074     }
1075     if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: microseconds since last update: %llu", st->name, st->usec_since_last_update);
1076
1077     // set last_collected_time
1078     if(unlikely(!st->last_collected_time.tv_sec)) {
1079         // it is the first entry
1080         // set the last_collected_time to now
1081         gettimeofday(&st->last_collected_time, NULL);
1082         last_collect_ut = st->last_collected_time.tv_sec * 1000000ULL + st->last_collected_time.tv_usec - update_every_ut;
1083
1084         // the first entry should not be stored
1085         store_this_entry = 0;
1086         first_entry = 1;
1087
1088         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);
1089     }
1090     else {
1091         // it is not the first entry
1092         // calculate the proper last_collected_time, using usec_since_last_update
1093         last_collect_ut = st->last_collected_time.tv_sec * 1000000ULL + st->last_collected_time.tv_usec;
1094         unsigned long long ut = last_collect_ut + st->usec_since_last_update;
1095         st->last_collected_time.tv_sec = (time_t) (ut / 1000000ULL);
1096         st->last_collected_time.tv_usec = (suseconds_t) (ut % 1000000ULL);
1097     }
1098
1099     // if this set has not been updated in the past
1100     // we fake the last_update time to be = now - usec_since_last_update
1101     if(unlikely(!st->last_updated.tv_sec)) {
1102         // it has never been updated before
1103         // set a fake last_updated, in the past using usec_since_last_update
1104         unsigned long long ut = st->last_collected_time.tv_sec * 1000000ULL + st->last_collected_time.tv_usec - st->usec_since_last_update;
1105         st->last_updated.tv_sec = (time_t) (ut / 1000000ULL);
1106         st->last_updated.tv_usec = (suseconds_t) (ut % 1000000ULL);
1107
1108         // the first entry should not be stored
1109         store_this_entry = 0;
1110         first_entry = 1;
1111
1112         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);
1113     }
1114
1115     // check if we will re-write the entire data set
1116     if(unlikely(usec_dt(&st->last_collected_time, &st->last_updated) > st->entries * update_every_ut)) {
1117         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);
1118         rrdset_reset(st);
1119
1120         st->usec_since_last_update = update_every_ut;
1121
1122         gettimeofday(&st->last_collected_time, NULL);
1123
1124         unsigned long long ut = st->last_collected_time.tv_sec * 1000000ULL + st->last_collected_time.tv_usec - st->usec_since_last_update;
1125         st->last_updated.tv_sec = (time_t) (ut / 1000000ULL);
1126         st->last_updated.tv_usec = (suseconds_t) (ut % 1000000ULL);
1127
1128         // the first entry should not be stored
1129         store_this_entry = 0;
1130         first_entry = 1;
1131     }
1132
1133     // these are the 3 variables that will help us in interpolation
1134     // last_stored_ut = the last time we added a value to the storage
1135     // now_collect_ut = the time the current value has been collected
1136     // next_store_ut  = the time of the next interpolation point
1137     last_stored_ut = st->last_updated.tv_sec * 1000000ULL + st->last_updated.tv_usec;
1138     now_collect_ut = st->last_collected_time.tv_sec * 1000000ULL + st->last_collected_time.tv_usec;
1139     next_store_ut  = (st->last_updated.tv_sec + st->update_every) * 1000000ULL;
1140
1141     if(unlikely(st->debug)) {
1142         debug(D_RRD_STATS, "%s: last_collect_ut = %0.3Lf (last collection time)", st->name, (long double)last_collect_ut/1000000.0);
1143         debug(D_RRD_STATS, "%s: now_collect_ut  = %0.3Lf (current collection time)", st->name, (long double)now_collect_ut/1000000.0);
1144         debug(D_RRD_STATS, "%s: last_stored_ut  = %0.3Lf (last updated time)", st->name, (long double)last_stored_ut/1000000.0);
1145         debug(D_RRD_STATS, "%s: next_store_ut   = %0.3Lf (next interpolation point)", st->name, (long double)next_store_ut/1000000.0);
1146     }
1147
1148     if(unlikely(!st->counter_done)) {
1149         store_this_entry = 0;
1150         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: Will not store the next entry.", st->name);
1151     }
1152     st->counter_done++;
1153
1154     // calculate totals and count the dimensions
1155     int dimensions;
1156     st->collected_total = 0;
1157     for( rd = st->dimensions, dimensions = 0 ; rd ; rd = rd->next, dimensions++ )
1158         if(likely(rd->updated)) st->collected_total += rd->collected_value;
1159
1160     uint32_t storage_flags = SN_EXISTS;
1161
1162     // process all dimensions to calculate their values
1163     // based on the collected figures only
1164     // at this stage we do not interpolate anything
1165     for( rd = st->dimensions ; rd ; rd = rd->next ) {
1166
1167         if(unlikely(!rd->updated)) {
1168             rd->calculated_value = 0;
1169             continue;
1170         }
1171
1172         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: START "
1173             " last_collected_value = " COLLECTED_NUMBER_FORMAT
1174             " collected_value = " COLLECTED_NUMBER_FORMAT
1175             " last_calculated_value = " CALCULATED_NUMBER_FORMAT
1176             " calculated_value = " CALCULATED_NUMBER_FORMAT
1177             , st->id, rd->name
1178             , rd->last_collected_value
1179             , rd->collected_value
1180             , rd->last_calculated_value
1181             , rd->calculated_value
1182             );
1183
1184         switch(rd->algorithm) {
1185             case RRDDIM_ABSOLUTE:
1186                 rd->calculated_value = (calculated_number)rd->collected_value
1187                     * (calculated_number)rd->multiplier
1188                     / (calculated_number)rd->divisor;
1189
1190                 if(unlikely(st->debug))
1191                     debug(D_RRD_STATS, "%s/%s: CALC ABS/ABS-NO-IN "
1192                         CALCULATED_NUMBER_FORMAT " = "
1193                         COLLECTED_NUMBER_FORMAT
1194                         " * " CALCULATED_NUMBER_FORMAT
1195                         " / " CALCULATED_NUMBER_FORMAT
1196                         , st->id, rd->name
1197                         , rd->calculated_value
1198                         , rd->collected_value
1199                         , (calculated_number)rd->multiplier
1200                         , (calculated_number)rd->divisor
1201                         );
1202                 break;
1203
1204             case RRDDIM_PCENT_OVER_ROW_TOTAL:
1205                 if(unlikely(!st->collected_total))
1206                     rd->calculated_value = 0;
1207                 else
1208                     // the percentage of the current value
1209                     // over the total of all dimensions
1210                     rd->calculated_value =
1211                           (calculated_number)100
1212                         * (calculated_number)rd->collected_value
1213                         / (calculated_number)st->collected_total;
1214
1215                 if(unlikely(st->debug))
1216                     debug(D_RRD_STATS, "%s/%s: CALC PCENT-ROW "
1217                         CALCULATED_NUMBER_FORMAT " = 100"
1218                         " * " COLLECTED_NUMBER_FORMAT
1219                         " / " COLLECTED_NUMBER_FORMAT
1220                         , st->id, rd->name
1221                         , rd->calculated_value
1222                         , rd->collected_value
1223                         , st->collected_total
1224                         );
1225                 break;
1226
1227             case RRDDIM_INCREMENTAL:
1228                 if(unlikely(rd->counter <= 1)) {
1229                     rd->calculated_value = 0;
1230                     continue;
1231                 }
1232
1233                 // if the new is smaller than the old (an overflow, or reset), set the old equal to the new
1234                 // to reset the calculation (it will give zero as the calculation for this second)
1235                 if(unlikely(rd->last_collected_value > rd->collected_value)) {
1236                     debug(D_RRD_STATS, "%s.%s: RESET or OVERFLOW. Last collected value = " COLLECTED_NUMBER_FORMAT ", current = " COLLECTED_NUMBER_FORMAT
1237                             , st->name, rd->name
1238                             , rd->last_collected_value
1239                             , rd->collected_value);
1240                     if(!(rd->flags & RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)) storage_flags = SN_EXISTS_RESET;
1241                     rd->last_collected_value = rd->collected_value;
1242                 }
1243
1244                 rd->calculated_value +=
1245                       (calculated_number)(rd->collected_value - rd->last_collected_value)
1246                     * (calculated_number)rd->multiplier
1247                     / (calculated_number)rd->divisor;
1248
1249                 if(unlikely(st->debug))
1250                     debug(D_RRD_STATS, "%s/%s: CALC INC PRE "
1251                         CALCULATED_NUMBER_FORMAT " = ("
1252                         COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT
1253                         ")"
1254                         " * " CALCULATED_NUMBER_FORMAT
1255                         " / " CALCULATED_NUMBER_FORMAT
1256                         , st->id, rd->name
1257                         , rd->calculated_value
1258                         , rd->collected_value, rd->last_collected_value
1259                         , (calculated_number)rd->multiplier
1260                         , (calculated_number)rd->divisor
1261                         );
1262                 break;
1263
1264             case RRDDIM_PCENT_OVER_DIFF_TOTAL:
1265                 if(unlikely(rd->counter <= 1)) {
1266                     rd->calculated_value = 0;
1267                     continue;
1268                 }
1269
1270                 // if the new is smaller than the old (an overflow, or reset), set the old equal to the new
1271                 // to reset the calculation (it will give zero as the calculation for this second)
1272                 if(unlikely(rd->last_collected_value > rd->collected_value)) {
1273                     debug(D_RRD_STATS, "%s.%s: RESET or OVERFLOW. Last collected value = " COLLECTED_NUMBER_FORMAT ", current = " COLLECTED_NUMBER_FORMAT
1274                     , st->name, rd->name
1275                     , rd->last_collected_value
1276                     , rd->collected_value);
1277                     if(!(rd->flags & RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)) storage_flags = SN_EXISTS_RESET;
1278                     rd->last_collected_value = rd->collected_value;
1279                 }
1280
1281                 // the percentage of the current increment
1282                 // over the increment of all dimensions together
1283                 if(unlikely(st->collected_total == st->last_collected_total))
1284                     rd->calculated_value = 0;
1285                 else
1286                     rd->calculated_value =
1287                           (calculated_number)100
1288                         * (calculated_number)(rd->collected_value - rd->last_collected_value)
1289                         / (calculated_number)(st->collected_total - st->last_collected_total);
1290
1291                 if(unlikely(st->debug))
1292                     debug(D_RRD_STATS, "%s/%s: CALC PCENT-DIFF "
1293                         CALCULATED_NUMBER_FORMAT " = 100"
1294                         " * (" COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT ")"
1295                         " / (" COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT ")"
1296                         , st->id, rd->name
1297                         , rd->calculated_value
1298                         , rd->collected_value, rd->last_collected_value
1299                         , st->collected_total, st->last_collected_total
1300                         );
1301                 break;
1302
1303             default:
1304                 // make the default zero, to make sure
1305                 // it gets noticed when we add new types
1306                 rd->calculated_value = 0;
1307
1308                 if(unlikely(st->debug))
1309                     debug(D_RRD_STATS, "%s/%s: CALC "
1310                         CALCULATED_NUMBER_FORMAT " = 0"
1311                         , st->id, rd->name
1312                         , rd->calculated_value
1313                         );
1314                 break;
1315         }
1316
1317         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: PHASE2 "
1318             " last_collected_value = " COLLECTED_NUMBER_FORMAT
1319             " collected_value = " COLLECTED_NUMBER_FORMAT
1320             " last_calculated_value = " CALCULATED_NUMBER_FORMAT
1321             " calculated_value = " CALCULATED_NUMBER_FORMAT
1322             , st->id, rd->name
1323             , rd->last_collected_value
1324             , rd->collected_value
1325             , rd->last_calculated_value
1326             , rd->calculated_value
1327             );
1328
1329     }
1330
1331     // at this point we have all the calculated values ready
1332     // it is now time to interpolate values on a second boundary
1333
1334     if(unlikely(now_collect_ut < next_store_ut)) {
1335         // this is collected in the same interpolation point
1336         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: THIS IS IN THE SAME INTERPOLATION POINT", st->name);
1337     }
1338
1339     unsigned long long first_ut = last_stored_ut;
1340     long long iterations = (now_collect_ut - last_stored_ut) / (update_every_ut);
1341     if((now_collect_ut % (update_every_ut)) == 0) iterations++;
1342
1343     for( ; next_store_ut <= now_collect_ut ; last_collect_ut = next_store_ut, next_store_ut += update_every_ut, iterations-- ) {
1344 #ifdef NETDATA_INTERNAL_CHECKS
1345         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); }
1346 #endif
1347
1348         if(unlikely(st->debug)) {
1349             debug(D_RRD_STATS, "%s: last_stored_ut = %0.3Lf (last updated time)", st->name, (long double)last_stored_ut/1000000.0);
1350             debug(D_RRD_STATS, "%s: next_store_ut  = %0.3Lf (next interpolation point)", st->name, (long double)next_store_ut/1000000.0);
1351         }
1352
1353         st->last_updated.tv_sec = (time_t) (next_store_ut / 1000000ULL);
1354         st->last_updated.tv_usec = 0;
1355
1356         for( rd = st->dimensions ; likely(rd) ; rd = rd->next ) {
1357             calculated_number new_value;
1358
1359             switch(rd->algorithm) {
1360                 case RRDDIM_INCREMENTAL:
1361                     new_value = (calculated_number)
1362                         (      rd->calculated_value
1363                             * (calculated_number)(next_store_ut - last_collect_ut)
1364                             / (calculated_number)(now_collect_ut - last_collect_ut)
1365                         );
1366
1367                     if(unlikely(st->debug))
1368                         debug(D_RRD_STATS, "%s/%s: CALC2 INC "
1369                             CALCULATED_NUMBER_FORMAT " = "
1370                             CALCULATED_NUMBER_FORMAT
1371                             " * %llu"
1372                             " / %llu"
1373                             , st->id, rd->name
1374                             , new_value
1375                             , rd->calculated_value
1376                             , (next_store_ut - last_stored_ut)
1377                             , (now_collect_ut - last_stored_ut)
1378                             );
1379
1380                     rd->calculated_value -= new_value;
1381                     new_value += rd->last_calculated_value;
1382                     rd->last_calculated_value = 0;
1383                     new_value /= (calculated_number)st->update_every;
1384
1385                     if(unlikely(next_store_ut - last_stored_ut < update_every_ut)) {
1386                         if(unlikely(st->debug))
1387                             debug(D_RRD_STATS, "%s/%s: COLLECTION POINT IS SHORT " CALCULATED_NUMBER_FORMAT " - EXTRAPOLATING",
1388                                 st->id, rd->name
1389                                 , (calculated_number)(next_store_ut - last_stored_ut)
1390                                 );
1391                         new_value = new_value * (calculated_number)(st->update_every * 1000000) / (calculated_number)(next_store_ut - last_stored_ut);
1392                     }
1393                     break;
1394
1395                 case RRDDIM_ABSOLUTE:
1396                 case RRDDIM_PCENT_OVER_ROW_TOTAL:
1397                 case RRDDIM_PCENT_OVER_DIFF_TOTAL:
1398                 default:
1399                     if(iterations == 1) {
1400                         // this is the last iteration
1401                         // do not interpolate
1402                         // just show the calculated value
1403
1404                         new_value = rd->calculated_value;
1405                     }
1406                     else {
1407                         // we have missed an update
1408                         // interpolate in the middle values
1409
1410                         new_value = (calculated_number)
1411                             (   (     (rd->calculated_value - rd->last_calculated_value)
1412                                     * (calculated_number)(next_store_ut - last_collect_ut)
1413                                     / (calculated_number)(now_collect_ut - last_collect_ut)
1414                                 )
1415                                 +  rd->last_calculated_value
1416                             );
1417
1418                         if(unlikely(st->debug))
1419                             debug(D_RRD_STATS, "%s/%s: CALC2 DEF "
1420                                 CALCULATED_NUMBER_FORMAT " = ((("
1421                                 "(" CALCULATED_NUMBER_FORMAT " - " CALCULATED_NUMBER_FORMAT ")"
1422                                 " * %llu"
1423                                 " / %llu) + " CALCULATED_NUMBER_FORMAT
1424                                 , st->id, rd->name
1425                                 , new_value
1426                                 , rd->calculated_value, rd->last_calculated_value
1427                                 , (next_store_ut - first_ut)
1428                                 , (now_collect_ut - first_ut), rd->last_calculated_value
1429                                 );
1430                     }
1431                     break;
1432             }
1433
1434             if(unlikely(!store_this_entry)) {
1435                 rd->values[st->current_entry] = pack_storage_number(0, SN_NOT_EXISTS);
1436                 continue;
1437             }
1438
1439             if(likely(rd->updated && rd->counter > 1 && iterations < st->gap_when_lost_iterations_above)) {
1440                 rd->values[st->current_entry] = pack_storage_number(new_value, storage_flags );
1441                 rd->last_stored_value = new_value;
1442
1443                 if(unlikely(st->debug))
1444                     debug(D_RRD_STATS, "%s/%s: STORE[%ld] "
1445                         CALCULATED_NUMBER_FORMAT " = " CALCULATED_NUMBER_FORMAT
1446                         , st->id, rd->name
1447                         , st->current_entry
1448                         , unpack_storage_number(rd->values[st->current_entry]), new_value
1449                         );
1450             }
1451             else {
1452                 if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: STORE[%ld] = NON EXISTING "
1453                         , st->id, rd->name
1454                         , st->current_entry
1455                         );
1456                 rd->values[st->current_entry] = pack_storage_number(0, SN_NOT_EXISTS);
1457                 rd->last_stored_value = NAN;
1458             }
1459
1460             stored_entries++;
1461
1462             if(unlikely(st->debug)) {
1463                 calculated_number t1 = new_value * (calculated_number)rd->multiplier / (calculated_number)rd->divisor;
1464                 calculated_number t2 = unpack_storage_number(rd->values[st->current_entry]);
1465                 calculated_number accuracy = accuracy_loss(t1, t2);
1466                 debug(D_RRD_STATS, "%s/%s: UNPACK[%ld] = " CALCULATED_NUMBER_FORMAT " FLAGS=0x%08x (original = " CALCULATED_NUMBER_FORMAT ", accuracy loss = " CALCULATED_NUMBER_FORMAT "%%%s)"
1467                         , st->id, rd->name
1468                         , st->current_entry
1469                         , t2
1470                         , get_storage_number_flags(rd->values[st->current_entry])
1471                         , t1
1472                         , accuracy
1473                         , (accuracy > ACCURACY_LOSS) ? " **TOO BIG** " : ""
1474                         );
1475
1476                 rd->collected_volume += t1;
1477                 rd->stored_volume += t2;
1478                 accuracy = accuracy_loss(rd->collected_volume, rd->stored_volume);
1479                 debug(D_RRD_STATS, "%s/%s: VOLUME[%ld] = " CALCULATED_NUMBER_FORMAT ", calculated  = " CALCULATED_NUMBER_FORMAT ", accuracy loss = " CALCULATED_NUMBER_FORMAT "%%%s"
1480                         , st->id, rd->name
1481                         , st->current_entry
1482                         , rd->stored_volume
1483                         , rd->collected_volume
1484                         , accuracy
1485                         , (accuracy > ACCURACY_LOSS) ? " **TOO BIG** " : ""
1486                         );
1487
1488             }
1489         }
1490         // reset the storage flags for the next point, if any;
1491         storage_flags = SN_EXISTS;
1492
1493         st->counter++;
1494         st->current_entry = ((st->current_entry + 1) >= st->entries) ? 0 : st->current_entry + 1;
1495         last_stored_ut = next_store_ut;
1496     }
1497
1498     st->last_collected_total  = st->collected_total;
1499
1500     for( rd = st->dimensions; rd ; rd = rd->next ) {
1501         if(unlikely(!rd->updated)) continue;
1502
1503         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);
1504         rd->last_collected_value = rd->collected_value;
1505
1506         switch(rd->algorithm) {
1507             case RRDDIM_INCREMENTAL:
1508                 if(unlikely(!first_entry)) {
1509                     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);
1510                     rd->last_calculated_value += rd->calculated_value;
1511                 }
1512                 else {
1513                     if(unlikely(st->debug)) debug(D_RRD_STATS, "%s: THIS IS THE FIRST POINT", st->name);
1514                 }
1515                 break;
1516
1517             case RRDDIM_ABSOLUTE:
1518             case RRDDIM_PCENT_OVER_ROW_TOTAL:
1519             case RRDDIM_PCENT_OVER_DIFF_TOTAL:
1520                 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);
1521                 rd->last_calculated_value = rd->calculated_value;
1522                 break;
1523         }
1524
1525         rd->calculated_value = 0;
1526         rd->collected_value = 0;
1527         rd->updated = 0;
1528
1529         if(unlikely(st->debug)) debug(D_RRD_STATS, "%s/%s: END "
1530             " last_collected_value = " COLLECTED_NUMBER_FORMAT
1531             " collected_value = " COLLECTED_NUMBER_FORMAT
1532             " last_calculated_value = " CALCULATED_NUMBER_FORMAT
1533             " calculated_value = " CALCULATED_NUMBER_FORMAT
1534             , st->id, rd->name
1535             , rd->last_collected_value
1536             , rd->collected_value
1537             , rd->last_calculated_value
1538             , rd->calculated_value
1539             );
1540     }
1541
1542     // ALL DONE ABOUT THE DATA UPDATE
1543     // --------------------------------------------------------------------
1544
1545 /*
1546     // find if there are any obsolete dimensions (not updated recently)
1547     if(unlikely(rrd_delete_unupdated_dimensions)) {
1548
1549         for( rd = st->dimensions; likely(rd) ; rd = rd->next )
1550             if((rd->last_collected_time.tv_sec + (rrd_delete_unupdated_dimensions * st->update_every)) < st->last_collected_time.tv_sec)
1551                 break;
1552
1553         if(unlikely(rd)) {
1554             RRDDIM *last;
1555             // there is dimension to free
1556             // upgrade our read lock to a write lock
1557             pthread_rwlock_unlock(&st->rwlock);
1558             pthread_rwlock_wrlock(&st->rwlock);
1559
1560             for( rd = st->dimensions, last = NULL ; likely(rd) ; ) {
1561                 // remove it only it is not updated in rrd_delete_unupdated_dimensions seconds
1562
1563                 if(unlikely((rd->last_collected_time.tv_sec + (rrd_delete_unupdated_dimensions * st->update_every)) < st->last_collected_time.tv_sec)) {
1564                     info("Removing obsolete dimension '%s' (%s) of '%s' (%s).", rd->name, rd->id, st->name, st->id);
1565
1566                     if(unlikely(!last)) {
1567                         st->dimensions = rd->next;
1568                         rd->next = NULL;
1569                         rrddim_free(st, rd);
1570                         rd = st->dimensions;
1571                         continue;
1572                     }
1573                     else {
1574                         last->next = rd->next;
1575                         rd->next = NULL;
1576                         rrddim_free(st, rd);
1577                         rd = last->next;
1578                         continue;
1579                     }
1580                 }
1581
1582                 last = rd;
1583                 rd = rd->next;
1584             }
1585
1586             if(unlikely(!st->dimensions)) {
1587                 info("Disabling chart %s (%s) since it does not have any dimensions", st->name, st->id);
1588                 st->enabled = 0;
1589             }
1590         }
1591     }
1592 */
1593
1594     pthread_rwlock_unlock(&st->rwlock);
1595
1596     if(unlikely(pthread_setcancelstate(pthreadoldcancelstate, NULL) != 0))
1597         error("Cannot set pthread cancel state to RESTORE (%d).", pthreadoldcancelstate);
1598
1599     return(st->usec_since_last_update);
1600 }