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