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