]> arthur.barton.de Git - netdata.git/blob - src/rrdset.c
unified rrdset and rrddim to use enum for flags
[netdata.git] / src / rrdset.c
1 #define NETDATA_RRD_INTERNALS 1
2 #include "common.h"
3
4 #define RRD_DEFAULT_GAP_INTERPOLATIONS 1
5
6 // ----------------------------------------------------------------------------
7 // RRDSET index
8
9 int rrdset_compare(void* a, void* b) {
10     if(((RRDSET *)a)->hash < ((RRDSET *)b)->hash) return -1;
11     else if(((RRDSET *)a)->hash > ((RRDSET *)b)->hash) return 1;
12     else return strcmp(((RRDSET *)a)->id, ((RRDSET *)b)->id);
13 }
14
15 static RRDSET *rrdset_index_find(RRDHOST *host, const char *id, uint32_t hash) {
16     RRDSET tmp;
17     strncpyz(tmp.id, id, RRD_ID_LENGTH_MAX);
18     tmp.hash = (hash)?hash:simple_hash(tmp.id);
19
20     return (RRDSET *)avl_search_lock(&(host->rrdset_root_index), (avl *) &tmp);
21 }
22
23 // ----------------------------------------------------------------------------
24 // RRDSET name index
25
26 #define rrdset_from_avlname(avlname_ptr) ((RRDSET *)((avlname_ptr) - offsetof(RRDSET, avlname)))
27
28 int rrdset_compare_name(void* a, void* b) {
29     RRDSET *A = rrdset_from_avlname(a);
30     RRDSET *B = rrdset_from_avlname(b);
31
32     // fprintf(stderr, "COMPARING: %s with %s\n", A->name, B->name);
33
34     if(A->hash_name < B->hash_name) return -1;
35     else if(A->hash_name > B->hash_name) return 1;
36     else return strcmp(A->name, B->name);
37 }
38
39 RRDSET *rrdset_index_add_name(RRDHOST *host, RRDSET *st) {
40     void *result;
41     // fprintf(stderr, "ADDING: %s (name: %s)\n", st->id, st->name);
42     result = avl_insert_lock(&host->rrdset_root_index_name, (avl *) (&st->avlname));
43     if(result) return rrdset_from_avlname(result);
44     return NULL;
45 }
46
47 RRDSET *rrdset_index_del_name(RRDHOST *host, RRDSET *st) {
48     void *result;
49     // fprintf(stderr, "DELETING: %s (name: %s)\n", st->id, st->name);
50     result = (RRDSET *)avl_remove_lock(&((host)->rrdset_root_index_name), (avl *)(&st->avlname));
51     if(result) return rrdset_from_avlname(result);
52     return NULL;
53 }
54
55
56 // ----------------------------------------------------------------------------
57 // RRDSET - find charts
58
59 static inline RRDSET *rrdset_index_find_name(RRDHOST *host, const char *name, uint32_t hash) {
60     void *result = NULL;
61     RRDSET tmp;
62     tmp.name = name;
63     tmp.hash_name = (hash)?hash:simple_hash(tmp.name);
64
65     // fprintf(stderr, "SEARCHING: %s\n", name);
66     result = avl_search_lock(&host->rrdset_root_index_name, (avl *) (&(tmp.avlname)));
67     if(result) {
68         RRDSET *st = rrdset_from_avlname(result);
69         if(strcmp(st->magic, RRDSET_MAGIC))
70             error("Search for RRDSET %s returned an invalid RRDSET %s (name %s)", name, st->id, st->name);
71
72         // fprintf(stderr, "FOUND: %s\n", name);
73         return rrdset_from_avlname(result);
74     }
75     // fprintf(stderr, "NOT FOUND: %s\n", name);
76     return NULL;
77 }
78
79 inline RRDSET *rrdset_find(RRDHOST *host, const char *id) {
80     debug(D_RRD_CALLS, "rrdset_find() for chart '%s' in host '%s'", id, host->hostname);
81     RRDSET *st = rrdset_index_find(host, id, 0);
82     return(st);
83 }
84
85 inline RRDSET *rrdset_find_bytype(RRDHOST *host, const char *type, const char *id) {
86     debug(D_RRD_CALLS, "rrdset_find_bytype() for chart '%s.%s' in host '%s'", type, id, host->hostname);
87
88     char buf[RRD_ID_LENGTH_MAX + 1];
89     strncpyz(buf, type, RRD_ID_LENGTH_MAX - 1);
90     strcat(buf, ".");
91     int len = (int) strlen(buf);
92     strncpyz(&buf[len], id, (size_t) (RRD_ID_LENGTH_MAX - len));
93
94     return(rrdset_find(host, buf));
95 }
96
97 inline RRDSET *rrdset_find_byname(RRDHOST *host, const char *name) {
98     debug(D_RRD_CALLS, "rrdset_find_byname() for chart '%s' in host '%s'", name, host->hostname);
99     RRDSET *st = rrdset_index_find_name(host, name, 0);
100     return(st);
101 }
102
103
104 // ----------------------------------------------------------------------------
105 // RRDSET - rename charts
106
107 char *rrdset_strncpyz_name(char *to, const char *from, size_t length) {
108     char c, *p = to;
109
110     while (length-- && (c = *from++)) {
111         if(c != '.' && !isalnum(c))
112             c = '_';
113
114         *p++ = c;
115     }
116
117     *p = '\0';
118
119     return to;
120 }
121
122 void rrdset_set_name(RRDSET *st, const char *name) {
123     if(unlikely(st->name && !strcmp(st->name, name)))
124         return;
125
126     debug(D_RRD_CALLS, "rrdset_set_name() old: %s, new: %s", st->name, name);
127
128     char b[CONFIG_MAX_VALUE + 1];
129     char n[RRD_ID_LENGTH_MAX + 1];
130
131     snprintfz(n, RRD_ID_LENGTH_MAX, "%s.%s", st->type, name);
132     rrdset_strncpyz_name(b, n, CONFIG_MAX_VALUE);
133
134     if(st->name) {
135         rrdset_index_del_name(st->rrdhost, st);
136         st->name = config_set_default(st->id, "name", b);
137         st->hash_name = simple_hash(st->name);
138         rrdsetvar_rename_all(st);
139     }
140     else {
141         st->name = config_get(st->id, "name", b);
142         st->hash_name = simple_hash(st->name);
143     }
144
145     pthread_rwlock_wrlock(&st->rwlock);
146     RRDDIM *rd;
147     for(rd = st->dimensions; rd ;rd = rd->next)
148         rrddimvar_rename_all(rd);
149     pthread_rwlock_unlock(&st->rwlock);
150
151     if(unlikely(rrdset_index_add_name(st->rrdhost, st) != st))
152         error("RRDSET: INTERNAL ERROR: attempted to index duplicate chart name '%s'", st->name);
153 }
154
155
156 // ----------------------------------------------------------------------------
157 // RRDSET - reset a chart
158
159 void rrdset_reset(RRDSET *st) {
160     debug(D_RRD_CALLS, "rrdset_reset() %s", st->name);
161
162     st->last_collected_time.tv_sec = 0;
163     st->last_collected_time.tv_usec = 0;
164     st->last_updated.tv_sec = 0;
165     st->last_updated.tv_usec = 0;
166     st->current_entry = 0;
167     st->counter = 0;
168     st->counter_done = 0;
169
170     RRDDIM *rd;
171     for(rd = st->dimensions; rd ; rd = rd->next) {
172         rd->last_collected_time.tv_sec = 0;
173         rd->last_collected_time.tv_usec = 0;
174         rd->counter = 0;
175         memset(rd->values, 0, rd->entries * sizeof(storage_number));
176     }
177 }
178
179 // ----------------------------------------------------------------------------
180 // RRDSET - helpers for rrdset_create()
181
182 static inline long align_entries_to_pagesize(long entries) {
183     if(entries < 5) entries = 5;
184     if(entries > RRD_HISTORY_ENTRIES_MAX) entries = RRD_HISTORY_ENTRIES_MAX;
185
186 #ifdef NETDATA_LOG_ALLOCATIONS
187     long page = (size_t)sysconf(_SC_PAGESIZE);
188
189     long size = sizeof(RRDDIM) + entries * sizeof(storage_number);
190     if(size % page) {
191         size -= (size % page);
192         size += page;
193
194         long n = (size - sizeof(RRDDIM)) / sizeof(storage_number);
195         return n;
196     }
197
198     return entries;
199 #else
200     return entries;
201 #endif
202 }
203
204 static inline void timeval_align(struct timeval *tv, int update_every) {
205     tv->tv_sec -= tv->tv_sec % update_every;
206     tv->tv_usec = 500000;
207 }
208
209 // ----------------------------------------------------------------------------
210 // RRDSET - create a chart
211
212 RRDSET *rrdset_create(RRDHOST *host, const char *type, const char *id, const char *name, const char *family
213                       , const char *context, const char *title, const char *units, long priority
214                       , int update_every, int chart_type) {
215
216     if(!type || !type[0]) {
217         fatal("Cannot create rrd stats without a type.");
218         return NULL;
219     }
220
221     if(!id || !id[0]) {
222         fatal("Cannot create rrd stats without an id.");
223         return NULL;
224     }
225
226     char fullid[RRD_ID_LENGTH_MAX + 1];
227     char fullfilename[FILENAME_MAX + 1];
228
229     snprintfz(fullid, RRD_ID_LENGTH_MAX, "%s.%s", type, id);
230
231     RRDSET *st = rrdset_find(host, fullid);
232     if(st) {
233         debug(D_RRD_CALLS, "RRDSET '%s', already exists.", fullid);
234         return st;
235     }
236
237     long rentries = config_get_number(fullid, "history", host->rrd_history_entries);
238     long entries = align_entries_to_pagesize(rentries);
239     if(entries != rentries) entries = config_set_number(fullid, "history", entries);
240
241     int enabled = config_get_boolean(fullid, "enabled", 1);
242     if(!enabled) entries = 5;
243
244     unsigned long size = sizeof(RRDSET);
245     char *cache_dir = rrdset_cache_dir(host, fullid);
246
247     debug(D_RRD_CALLS, "Creating RRD_STATS for '%s.%s'.", type, id);
248
249     snprintfz(fullfilename, FILENAME_MAX, "%s/main.db", cache_dir);
250     if(host->rrd_memory_mode != RRD_MEMORY_MODE_RAM) st = (RRDSET *)mymmap(fullfilename, size, ((host->rrd_memory_mode == RRD_MEMORY_MODE_MAP)?MAP_SHARED:MAP_PRIVATE), 0);
251     if(st) {
252         if(strcmp(st->magic, RRDSET_MAGIC) != 0) {
253             errno = 0;
254             info("Initializing file %s.", fullfilename);
255             memset(st, 0, size);
256         }
257         else if(strcmp(st->id, fullid) != 0) {
258             errno = 0;
259             error("File %s contents are not for chart %s. Clearing it.", fullfilename, fullid);
260             // munmap(st, size);
261             // st = NULL;
262             memset(st, 0, size);
263         }
264         else if(st->memsize != size || st->entries != entries) {
265             errno = 0;
266             error("File %s does not have the desired size. Clearing it.", fullfilename);
267             memset(st, 0, size);
268         }
269         else if(st->update_every != update_every) {
270             errno = 0;
271             error("File %s does not have the desired update frequency. Clearing it.", fullfilename);
272             memset(st, 0, size);
273         }
274         else if((now_realtime_sec() - st->last_updated.tv_sec) > update_every * entries) {
275             errno = 0;
276             error("File %s is too old. Clearing it.", fullfilename);
277             memset(st, 0, size);
278         }
279
280         // make sure the database is aligned
281         if(st->last_updated.tv_sec)
282             timeval_align(&st->last_updated, update_every);
283     }
284
285     if(st) {
286         st->name = NULL;
287         st->type = NULL;
288         st->family = NULL;
289         st->context = NULL;
290         st->title = NULL;
291         st->units = NULL;
292         st->dimensions = NULL;
293         st->next = NULL;
294         st->rrd_memory_mode = host->rrd_memory_mode;
295         st->variables = NULL;
296         st->alarms = NULL;
297         memset(&st->rwlock, 0, sizeof(pthread_rwlock_t));
298         memset(&st->avl, 0, sizeof(avl));
299         memset(&st->avlname, 0, sizeof(avl));
300         memset(&st->variables_root_index, 0, sizeof(avl_tree_lock));
301         memset(&st->dimensions_index, 0, sizeof(avl_tree_lock));
302     }
303     else {
304         st = callocz(1, size);
305         st->rrd_memory_mode = RRD_MEMORY_MODE_RAM;
306     }
307
308     st->rrdhost = host;
309     st->memsize = size;
310     st->entries = entries;
311     st->update_every = update_every;
312
313     if(st->current_entry >= st->entries) st->current_entry = 0;
314
315     strcpy(st->cache_filename, fullfilename);
316     strcpy(st->magic, RRDSET_MAGIC);
317
318     strcpy(st->id, fullid);
319     st->hash = simple_hash(st->id);
320
321     st->cache_dir = cache_dir;
322
323     st->chart_type = rrdset_type_id(config_get(st->id, "chart type", rrdset_type_name(chart_type)));
324     st->type       = config_get(st->id, "type", type);
325     st->family     = config_get(st->id, "family", family?family:st->type);
326     st->units      = config_get(st->id, "units", units?units:"");
327
328     st->context    = config_get(st->id, "context", context?context:st->id);
329     st->hash_context = simple_hash(st->context);
330
331     st->priority = config_get_number(st->id, "priority", priority);
332     if(enabled)
333         rrdset_flag_set(st, RRDSET_FLAG_ENABLED);
334     else
335         rrdset_flag_clear(st, RRDSET_FLAG_ENABLED);
336
337     rrdset_flag_clear(st, RRDSET_FLAG_DETAIL);
338     rrdset_flag_clear(st, RRDSET_FLAG_DEBUG);
339
340     // if(!strcmp(st->id, "disk_util.dm-0")) {
341     //     st->debug = 1;
342     //     error("enabled debugging for '%s'", st->id);
343     // }
344     // else error("not enabled debugging for '%s'", st->id);
345
346     st->green = NAN;
347     st->red = NAN;
348
349     st->last_collected_time.tv_sec = 0;
350     st->last_collected_time.tv_usec = 0;
351     st->counter_done = 0;
352
353     st->gap_when_lost_iterations_above = (int) (
354             config_get_number(st->id, "gap when lost iterations above", RRD_DEFAULT_GAP_INTERPOLATIONS) + 2);
355
356     avl_init_lock(&st->dimensions_index, rrddim_compare);
357     avl_init_lock(&st->variables_root_index, rrdvar_compare);
358
359     pthread_rwlock_init(&st->rwlock, NULL);
360     rrdhost_rwlock(host);
361
362     if(name && *name) rrdset_set_name(st, name);
363     else rrdset_set_name(st, id);
364
365     {
366         char varvalue[CONFIG_MAX_VALUE + 1];
367         char varvalue2[CONFIG_MAX_VALUE + 1];
368         snprintfz(varvalue, CONFIG_MAX_VALUE, "%s (%s)", title?title:"", st->name);
369         json_escape_string(varvalue2, varvalue, sizeof(varvalue2));
370         st->title = config_get(st->id, "title", varvalue2);
371     }
372
373     st->rrdfamily = rrdfamily_create(host, st->family);
374
375     st->next = host->rrdset_root;
376     host->rrdset_root = st;
377
378     if(host->health_enabled) {
379         rrdsetvar_create(st, "last_collected_t", RRDVAR_TYPE_TIME_T, &st->last_collected_time.tv_sec, 0);
380         rrdsetvar_create(st, "collected_total_raw", RRDVAR_TYPE_TOTAL, &st->last_collected_total, 0);
381         rrdsetvar_create(st, "green", RRDVAR_TYPE_CALCULATED, &st->green, 0);
382         rrdsetvar_create(st, "red", RRDVAR_TYPE_CALCULATED, &st->red, 0);
383         rrdsetvar_create(st, "update_every", RRDVAR_TYPE_INT, &st->update_every, 0);
384     }
385
386     if(unlikely(rrdset_index_add(host, st) != st))
387         error("RRDSET: INTERNAL ERROR: attempt to index duplicate chart '%s'", st->id);
388
389     rrdsetcalc_link_matching(st);
390     rrdcalctemplate_link_matching(st);
391
392     rrdhost_unlock(host);
393
394     return(st);
395 }
396
397
398 // ----------------------------------------------------------------------------
399 // RRDSET - data collection iteration control
400
401 void rrdset_next_usec_unfiltered(RRDSET *st, usec_t microseconds) {
402     if(unlikely(!st->last_collected_time.tv_sec || !microseconds)) {
403         // the first entry
404         microseconds = st->update_every * USEC_PER_SEC;
405     }
406     st->usec_since_last_update = microseconds;
407 }
408
409 void rrdset_next_usec(RRDSET *st, usec_t microseconds)
410 {
411     struct timeval now;
412     now_realtime_timeval(&now);
413
414     if(unlikely(!st->last_collected_time.tv_sec)) {
415         // the first entry
416         microseconds = st->update_every * USEC_PER_SEC;
417     }
418     else if(unlikely(!microseconds)) {
419         // no dt given by the plugin
420         microseconds = dt_usec(&now, &st->last_collected_time);
421     }
422     else {
423         // microseconds has the time since the last collection
424 #ifdef NETDATA_INTERNAL_CHECKS
425         usec_t now_usec = timeval_usec(&now);
426         usec_t last_usec = timeval_usec(&st->last_collected_time);
427 #endif
428         usec_t since_last_usec = dt_usec(&now, &st->last_collected_time);
429
430         // verify the microseconds given is good
431         if(unlikely(microseconds > since_last_usec)) {
432             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);
433
434 #ifdef NETDATA_INTERNAL_CHECKS
435             if(unlikely(last_usec + microseconds > now_usec + 1000))
436                 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);
437 #endif
438
439             microseconds = since_last_usec;
440         }
441         else if(unlikely(microseconds < since_last_usec * 0.8)) {
442             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);
443
444 #ifdef NETDATA_INTERNAL_CHECKS
445             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);
446 #endif
447             microseconds = since_last_usec;
448         }
449     }
450     debug(D_RRD_CALLS, "rrdset_next_usec() for chart %s with microseconds %llu", st->name, microseconds);
451
452     if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
453         debug(D_RRD_STATS, "%s: NEXT: %llu microseconds", st->name, microseconds);
454
455     st->usec_since_last_update = microseconds;
456 }
457
458
459 // ----------------------------------------------------------------------------
460 // RRDSET - process the collected values for all dimensions of a chart
461
462 usec_t rrdset_done(RRDSET *st) {
463     if(unlikely(netdata_exit)) return 0;
464
465     debug(D_RRD_CALLS, "rrdset_done() for chart %s", st->name);
466
467     RRDDIM *rd;
468
469     int
470             pthreadoldcancelstate;  // store the old cancelable pthread state, to restore it at the end
471
472     char
473             store_this_entry = 1,   // boolean: 1 = store this entry, 0 = don't store this entry
474             first_entry = 0;        // boolean: 1 = this is the first entry seen for this chart, 0 = all other entries
475
476     unsigned int
477             stored_entries = 0;     // the number of entries we have stored in the db, during this call to rrdset_done()
478
479     usec_t
480             last_collect_ut,        // the timestamp in microseconds, of the last collected value
481             now_collect_ut,         // the timestamp in microseconds, of this collected value (this is NOW)
482             last_stored_ut,         // the timestamp in microseconds, of the last stored entry in the db
483             next_store_ut,          // the timestamp in microseconds, of the next entry to store in the db
484             update_every_ut = st->update_every * USEC_PER_SEC; // st->update_every in microseconds
485
486     if(unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &pthreadoldcancelstate) != 0))
487         error("Cannot set pthread cancel state to DISABLE.");
488
489     // a read lock is OK here
490     pthread_rwlock_rdlock(&st->rwlock);
491
492 /*
493     // enable the chart, if it was disabled
494     if(unlikely(rrd_delete_unupdated_dimensions) && !st->enabled)
495         st->enabled = 1;
496 */
497
498     // check if the chart has a long time to be updated
499     if(unlikely(st->usec_since_last_update > st->entries * update_every_ut)) {
500         info("%s: took too long to be updated (%0.3Lf secs). Resetting it.", st->name, (long double)(st->usec_since_last_update / 1000000.0));
501         rrdset_reset(st);
502         st->usec_since_last_update = update_every_ut;
503         first_entry = 1;
504     }
505
506     if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
507         debug(D_RRD_STATS, "%s: microseconds since last update: %llu", st->name, st->usec_since_last_update);
508
509     // set last_collected_time
510     if(unlikely(!st->last_collected_time.tv_sec)) {
511         // it is the first entry
512         // set the last_collected_time to now
513         now_realtime_timeval(&st->last_collected_time);
514         timeval_align(&st->last_collected_time, st->update_every);
515
516         last_collect_ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec - update_every_ut;
517
518         // the first entry should not be stored
519         store_this_entry = 0;
520         first_entry = 1;
521
522         if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
523             debug(D_RRD_STATS, "%s: has not set last_collected_time. Setting it now. Will not store the next entry.", st->name);
524     }
525     else {
526         // it is not the first entry
527         // calculate the proper last_collected_time, using usec_since_last_update
528         last_collect_ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec;
529         usec_t ut = last_collect_ut + st->usec_since_last_update;
530         st->last_collected_time.tv_sec = (time_t) (ut / USEC_PER_SEC);
531         st->last_collected_time.tv_usec = (suseconds_t) (ut % USEC_PER_SEC);
532     }
533
534     // if this set has not been updated in the past
535     // we fake the last_update time to be = now - usec_since_last_update
536     if(unlikely(!st->last_updated.tv_sec)) {
537         // it has never been updated before
538         // set a fake last_updated, in the past using usec_since_last_update
539         usec_t ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec - st->usec_since_last_update;
540         st->last_updated.tv_sec = (time_t) (ut / USEC_PER_SEC);
541         st->last_updated.tv_usec = (suseconds_t) (ut % USEC_PER_SEC);
542
543         // the first entry should not be stored
544         store_this_entry = 0;
545         first_entry = 1;
546
547         if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
548             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);
549     }
550
551     // check if we will re-write the entire data set
552     if(unlikely(dt_usec(&st->last_collected_time, &st->last_updated) > st->entries * update_every_ut)) {
553         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);
554         rrdset_reset(st);
555
556         st->usec_since_last_update = update_every_ut;
557
558         now_realtime_timeval(&st->last_collected_time);
559         timeval_align(&st->last_collected_time, st->update_every);
560
561         usec_t ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec - st->usec_since_last_update;
562         st->last_updated.tv_sec = (time_t) (ut / USEC_PER_SEC);
563         st->last_updated.tv_usec = (suseconds_t) (ut % USEC_PER_SEC);
564
565         // the first entry should not be stored
566         store_this_entry = 0;
567         first_entry = 1;
568     }
569
570     // these are the 3 variables that will help us in interpolation
571     // last_stored_ut = the last time we added a value to the storage
572     // now_collect_ut = the time the current value has been collected
573     // next_store_ut  = the time of the next interpolation point
574     last_stored_ut = st->last_updated.tv_sec * USEC_PER_SEC + st->last_updated.tv_usec;
575     now_collect_ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec;
576     next_store_ut  = (st->last_updated.tv_sec + st->update_every) * USEC_PER_SEC;
577
578     if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG))) {
579         debug(D_RRD_STATS, "%s: last_collect_ut = %0.3Lf (last collection time)", st->name, (long double)last_collect_ut/1000000.0);
580         debug(D_RRD_STATS, "%s: now_collect_ut  = %0.3Lf (current collection time)", st->name, (long double)now_collect_ut/1000000.0);
581         debug(D_RRD_STATS, "%s: last_stored_ut  = %0.3Lf (last updated time)", st->name, (long double)last_stored_ut/1000000.0);
582         debug(D_RRD_STATS, "%s: next_store_ut   = %0.3Lf (next interpolation point)", st->name, (long double)next_store_ut/1000000.0);
583     }
584
585     if(unlikely(!st->counter_done)) {
586         store_this_entry = 0;
587         if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
588             debug(D_RRD_STATS, "%s: Will not store the next entry.", st->name);
589     }
590     st->counter_done++;
591
592     // calculate totals and count the dimensions
593     int dimensions;
594     st->collected_total = 0;
595     for( rd = st->dimensions, dimensions = 0 ; rd ; rd = rd->next, dimensions++ )
596         if(likely(rrddim_flag_check(rd, RRDDIM_FLAG_UPDATED)))
597             st->collected_total += rd->collected_value;
598
599     uint32_t storage_flags = SN_EXISTS;
600
601     // process all dimensions to calculate their values
602     // based on the collected figures only
603     // at this stage we do not interpolate anything
604     for( rd = st->dimensions ; rd ; rd = rd->next ) {
605
606         if(unlikely(!rrddim_flag_check(rd, RRDDIM_FLAG_UPDATED))) {
607             rd->calculated_value = 0;
608             continue;
609         }
610
611         if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
612             debug(D_RRD_STATS, "%s/%s: START "
613                     " last_collected_value = " COLLECTED_NUMBER_FORMAT
614                     " collected_value = " COLLECTED_NUMBER_FORMAT
615                     " last_calculated_value = " CALCULATED_NUMBER_FORMAT
616                     " calculated_value = " CALCULATED_NUMBER_FORMAT
617                                       , st->id, rd->name
618                                       , rd->last_collected_value
619                                       , rd->collected_value
620                                       , rd->last_calculated_value
621                                       , rd->calculated_value
622             );
623
624         switch(rd->algorithm) {
625             case RRD_ALGORITHM_ABSOLUTE:
626                 rd->calculated_value = (calculated_number)rd->collected_value
627                                        * (calculated_number)rd->multiplier
628                                        / (calculated_number)rd->divisor;
629
630                 if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
631                     debug(D_RRD_STATS, "%s/%s: CALC ABS/ABS-NO-IN "
632                             CALCULATED_NUMBER_FORMAT " = "
633                             COLLECTED_NUMBER_FORMAT
634                             " * " CALCULATED_NUMBER_FORMAT
635                             " / " CALCULATED_NUMBER_FORMAT
636                           , st->id, rd->name
637                           , rd->calculated_value
638                           , rd->collected_value
639                           , (calculated_number)rd->multiplier
640                           , (calculated_number)rd->divisor
641                     );
642                 break;
643
644             case RRD_ALGORITHM_PCENT_OVER_ROW_TOTAL:
645                 if(unlikely(!st->collected_total))
646                     rd->calculated_value = 0;
647                 else
648                     // the percentage of the current value
649                     // over the total of all dimensions
650                     rd->calculated_value =
651                             (calculated_number)100
652                             * (calculated_number)rd->collected_value
653                             / (calculated_number)st->collected_total;
654
655                 if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
656                     debug(D_RRD_STATS, "%s/%s: CALC PCENT-ROW "
657                             CALCULATED_NUMBER_FORMAT " = 100"
658                                     " * " COLLECTED_NUMBER_FORMAT
659                             " / " COLLECTED_NUMBER_FORMAT
660                           , st->id, rd->name
661                           , rd->calculated_value
662                           , rd->collected_value
663                           , st->collected_total
664                     );
665                 break;
666
667             case RRD_ALGORITHM_INCREMENTAL:
668                 if(unlikely(rd->counter <= 1)) {
669                     rd->calculated_value = 0;
670                     continue;
671                 }
672
673                 // if the new is smaller than the old (an overflow, or reset), set the old equal to the new
674                 // to reset the calculation (it will give zero as the calculation for this second)
675                 if(unlikely(rd->last_collected_value > rd->collected_value)) {
676                     debug(D_RRD_STATS, "%s.%s: RESET or OVERFLOW. Last collected value = " COLLECTED_NUMBER_FORMAT ", current = " COLLECTED_NUMBER_FORMAT
677                           , st->name, rd->name
678                           , rd->last_collected_value
679                           , rd->collected_value);
680
681                     if(!(rrddim_flag_check(rd, RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)))
682                         storage_flags = SN_EXISTS_RESET;
683
684                     rd->last_collected_value = rd->collected_value;
685                 }
686
687                 rd->calculated_value +=
688                         (calculated_number)(rd->collected_value - rd->last_collected_value)
689                         * (calculated_number)rd->multiplier
690                         / (calculated_number)rd->divisor;
691
692                 if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
693                     debug(D_RRD_STATS, "%s/%s: CALC INC PRE "
694                             CALCULATED_NUMBER_FORMAT " = ("
695                             COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT
696                             ")"
697                                     " * " CALCULATED_NUMBER_FORMAT
698                             " / " CALCULATED_NUMBER_FORMAT
699                           , st->id, rd->name
700                           , rd->calculated_value
701                           , rd->collected_value, rd->last_collected_value
702                           , (calculated_number)rd->multiplier
703                           , (calculated_number)rd->divisor
704                     );
705                 break;
706
707             case RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL:
708                 if(unlikely(rd->counter <= 1)) {
709                     rd->calculated_value = 0;
710                     continue;
711                 }
712
713                 // if the new is smaller than the old (an overflow, or reset), set the old equal to the new
714                 // to reset the calculation (it will give zero as the calculation for this second)
715                 if(unlikely(rd->last_collected_value > rd->collected_value)) {
716                     debug(D_RRD_STATS, "%s.%s: RESET or OVERFLOW. Last collected value = " COLLECTED_NUMBER_FORMAT ", current = " COLLECTED_NUMBER_FORMAT
717                           , st->name, rd->name
718                           , rd->last_collected_value
719                           , rd->collected_value);
720
721                     if(!(rrddim_flag_check(rd, RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)))
722                         storage_flags = SN_EXISTS_RESET;
723
724                     rd->last_collected_value = rd->collected_value;
725                 }
726
727                 // the percentage of the current increment
728                 // over the increment of all dimensions together
729                 if(unlikely(st->collected_total == st->last_collected_total))
730                     rd->calculated_value = 0;
731                 else
732                     rd->calculated_value =
733                             (calculated_number)100
734                             * (calculated_number)(rd->collected_value - rd->last_collected_value)
735                             / (calculated_number)(st->collected_total - st->last_collected_total);
736
737                 if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
738                     debug(D_RRD_STATS, "%s/%s: CALC PCENT-DIFF "
739                             CALCULATED_NUMBER_FORMAT " = 100"
740                                     " * (" COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT ")"
741                                     " / (" COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT ")"
742                           , st->id, rd->name
743                           , rd->calculated_value
744                           , rd->collected_value, rd->last_collected_value
745                           , st->collected_total, st->last_collected_total
746                     );
747                 break;
748
749             default:
750                 // make the default zero, to make sure
751                 // it gets noticed when we add new types
752                 rd->calculated_value = 0;
753
754                 if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
755                     debug(D_RRD_STATS, "%s/%s: CALC "
756                             CALCULATED_NUMBER_FORMAT " = 0"
757                           , st->id, rd->name
758                           , rd->calculated_value
759                     );
760                 break;
761         }
762
763         if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
764             debug(D_RRD_STATS, "%s/%s: PHASE2 "
765                     " last_collected_value = " COLLECTED_NUMBER_FORMAT
766                     " collected_value = " COLLECTED_NUMBER_FORMAT
767                     " last_calculated_value = " CALCULATED_NUMBER_FORMAT
768                     " calculated_value = " CALCULATED_NUMBER_FORMAT
769                                       , st->id, rd->name
770                                       , rd->last_collected_value
771                                       , rd->collected_value
772                                       , rd->last_calculated_value
773                                       , rd->calculated_value
774             );
775
776     }
777
778     // at this point we have all the calculated values ready
779     // it is now time to interpolate values on a second boundary
780
781     if(unlikely(now_collect_ut < next_store_ut)) {
782         // this is collected in the same interpolation point
783
784         if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
785             debug(D_RRD_STATS, "%s: THIS IS IN THE SAME INTERPOLATION POINT", st->name);
786
787 #ifdef NETDATA_INTERNAL_CHECKS
788         info("%s is collected in the same interpolation point: short by %llu microseconds", st->name, next_store_ut - now_collect_ut);
789 #endif
790     }
791
792     usec_t first_ut = last_stored_ut;
793     long long iterations = (now_collect_ut - last_stored_ut) / (update_every_ut);
794     if((now_collect_ut % (update_every_ut)) == 0) iterations++;
795
796     for( ; next_store_ut <= now_collect_ut ; last_collect_ut = next_store_ut, next_store_ut += update_every_ut, iterations-- ) {
797 #ifdef NETDATA_INTERNAL_CHECKS
798         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); }
799 #endif
800
801         if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG))) {
802             debug(D_RRD_STATS, "%s: last_stored_ut = %0.3Lf (last updated time)", st->name, (long double)last_stored_ut/1000000.0);
803             debug(D_RRD_STATS, "%s: next_store_ut  = %0.3Lf (next interpolation point)", st->name, (long double)next_store_ut/1000000.0);
804         }
805
806         st->last_updated.tv_sec = (time_t) (next_store_ut / USEC_PER_SEC);
807         st->last_updated.tv_usec = 0;
808
809         for( rd = st->dimensions ; likely(rd) ; rd = rd->next ) {
810             calculated_number new_value;
811
812             switch(rd->algorithm) {
813                 case RRD_ALGORITHM_INCREMENTAL:
814                     new_value = (calculated_number)
815                             (      rd->calculated_value
816                                    * (calculated_number)(next_store_ut - last_collect_ut)
817                                    / (calculated_number)(now_collect_ut - last_collect_ut)
818                             );
819
820                     if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
821                         debug(D_RRD_STATS, "%s/%s: CALC2 INC "
822                                 CALCULATED_NUMBER_FORMAT " = "
823                                 CALCULATED_NUMBER_FORMAT
824                                 " * %llu"
825                                         " / %llu"
826                               , st->id, rd->name
827                               , new_value
828                               , rd->calculated_value
829                               , (next_store_ut - last_stored_ut)
830                               , (now_collect_ut - last_stored_ut)
831                         );
832
833                     rd->calculated_value -= new_value;
834                     new_value += rd->last_calculated_value;
835                     rd->last_calculated_value = 0;
836                     new_value /= (calculated_number)st->update_every;
837
838                     if(unlikely(next_store_ut - last_stored_ut < update_every_ut)) {
839                         if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
840                             debug(D_RRD_STATS, "%s/%s: COLLECTION POINT IS SHORT " CALCULATED_NUMBER_FORMAT " - EXTRAPOLATING",
841                                     st->id, rd->name
842                                   , (calculated_number)(next_store_ut - last_stored_ut)
843                             );
844                         new_value = new_value * (calculated_number)(st->update_every * 1000000) / (calculated_number)(next_store_ut - last_stored_ut);
845                     }
846                     break;
847
848                 case RRD_ALGORITHM_ABSOLUTE:
849                 case RRD_ALGORITHM_PCENT_OVER_ROW_TOTAL:
850                 case RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL:
851                 default:
852                     if(iterations == 1) {
853                         // this is the last iteration
854                         // do not interpolate
855                         // just show the calculated value
856
857                         new_value = rd->calculated_value;
858                     }
859                     else {
860                         // we have missed an update
861                         // interpolate in the middle values
862
863                         new_value = (calculated_number)
864                                 (   (     (rd->calculated_value - rd->last_calculated_value)
865                                           * (calculated_number)(next_store_ut - last_collect_ut)
866                                           / (calculated_number)(now_collect_ut - last_collect_ut)
867                                     )
868                                     +  rd->last_calculated_value
869                                 );
870
871                         if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
872                             debug(D_RRD_STATS, "%s/%s: CALC2 DEF "
873                                     CALCULATED_NUMBER_FORMAT " = ((("
874                                             "(" CALCULATED_NUMBER_FORMAT " - " CALCULATED_NUMBER_FORMAT ")"
875                                             " * %llu"
876                                             " / %llu) + " CALCULATED_NUMBER_FORMAT
877                                   , st->id, rd->name
878                                   , new_value
879                                   , rd->calculated_value, rd->last_calculated_value
880                                   , (next_store_ut - first_ut)
881                                   , (now_collect_ut - first_ut), rd->last_calculated_value
882                             );
883                     }
884                     break;
885             }
886
887             if(unlikely(!store_this_entry)) {
888                 rd->values[st->current_entry] = pack_storage_number(0, SN_NOT_EXISTS);
889                 continue;
890             }
891
892             if(likely(rrddim_flag_check(rd, RRDDIM_FLAG_UPDATED) && rd->counter > 1 && iterations < st->gap_when_lost_iterations_above)) {
893                 rd->values[st->current_entry] = pack_storage_number(new_value, storage_flags );
894                 rd->last_stored_value = new_value;
895
896                 if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
897                     debug(D_RRD_STATS, "%s/%s: STORE[%ld] "
898                             CALCULATED_NUMBER_FORMAT " = " CALCULATED_NUMBER_FORMAT
899                           , st->id, rd->name
900                           , st->current_entry
901                           , unpack_storage_number(rd->values[st->current_entry]), new_value
902                     );
903             }
904             else {
905                 if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
906                     debug(D_RRD_STATS, "%s/%s: STORE[%ld] = NON EXISTING "
907                           , st->id, rd->name
908                           , st->current_entry
909                     );
910                 rd->values[st->current_entry] = pack_storage_number(0, SN_NOT_EXISTS);
911                 rd->last_stored_value = NAN;
912             }
913
914             stored_entries++;
915
916             if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG))) {
917                 calculated_number t1 = new_value * (calculated_number)rd->multiplier / (calculated_number)rd->divisor;
918                 calculated_number t2 = unpack_storage_number(rd->values[st->current_entry]);
919                 calculated_number accuracy = accuracy_loss(t1, t2);
920                 debug(D_RRD_STATS, "%s/%s: UNPACK[%ld] = " CALCULATED_NUMBER_FORMAT " FLAGS=0x%08x (original = " CALCULATED_NUMBER_FORMAT ", accuracy loss = " CALCULATED_NUMBER_FORMAT "%%%s)"
921                       , st->id, rd->name
922                       , st->current_entry
923                       , t2
924                       , get_storage_number_flags(rd->values[st->current_entry])
925                       , t1
926                       , accuracy
927                       , (accuracy > ACCURACY_LOSS) ? " **TOO BIG** " : ""
928                 );
929
930                 rd->collected_volume += t1;
931                 rd->stored_volume += t2;
932                 accuracy = accuracy_loss(rd->collected_volume, rd->stored_volume);
933                 debug(D_RRD_STATS, "%s/%s: VOLUME[%ld] = " CALCULATED_NUMBER_FORMAT ", calculated  = " CALCULATED_NUMBER_FORMAT ", accuracy loss = " CALCULATED_NUMBER_FORMAT "%%%s"
934                       , st->id, rd->name
935                       , st->current_entry
936                       , rd->stored_volume
937                       , rd->collected_volume
938                       , accuracy
939                       , (accuracy > ACCURACY_LOSS) ? " **TOO BIG** " : ""
940                 );
941
942             }
943         }
944         // reset the storage flags for the next point, if any;
945         storage_flags = SN_EXISTS;
946
947         st->counter++;
948         st->current_entry = ((st->current_entry + 1) >= st->entries) ? 0 : st->current_entry + 1;
949         last_stored_ut = next_store_ut;
950     }
951
952     st->last_collected_total  = st->collected_total;
953
954     for( rd = st->dimensions; rd ; rd = rd->next ) {
955         if(unlikely(!rrddim_flag_check(rd, RRDDIM_FLAG_UPDATED)))
956             continue;
957
958         if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
959             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);
960
961         rd->last_collected_value = rd->collected_value;
962
963         switch(rd->algorithm) {
964             case RRD_ALGORITHM_INCREMENTAL:
965                 if(unlikely(!first_entry)) {
966                     if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
967                         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);
968                     rd->last_calculated_value += rd->calculated_value;
969                 }
970                 else {
971                     if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
972                         debug(D_RRD_STATS, "%s: THIS IS THE FIRST POINT", st->name);
973                 }
974                 break;
975
976             case RRD_ALGORITHM_ABSOLUTE:
977             case RRD_ALGORITHM_PCENT_OVER_ROW_TOTAL:
978             case RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL:
979                 if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
980                     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);
981                 rd->last_calculated_value = rd->calculated_value;
982                 break;
983         }
984
985         rd->calculated_value = 0;
986         rd->collected_value = 0;
987         rrddim_flag_clear(rd, RRDDIM_FLAG_UPDATED);
988
989         if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_DEBUG)))
990             debug(D_RRD_STATS, "%s/%s: END "
991                     " last_collected_value = " COLLECTED_NUMBER_FORMAT
992                     " collected_value = " COLLECTED_NUMBER_FORMAT
993                     " last_calculated_value = " CALCULATED_NUMBER_FORMAT
994                     " calculated_value = " CALCULATED_NUMBER_FORMAT
995                                       , st->id, rd->name
996                                       , rd->last_collected_value
997                                       , rd->collected_value
998                                       , rd->last_calculated_value
999                                       , rd->calculated_value
1000             );
1001     }
1002
1003     // ALL DONE ABOUT THE DATA UPDATE
1004     // --------------------------------------------------------------------
1005
1006 /*
1007     // find if there are any obsolete dimensions (not updated recently)
1008     if(unlikely(rrd_delete_unupdated_dimensions)) {
1009
1010         for( rd = st->dimensions; likely(rd) ; rd = rd->next )
1011             if((rd->last_collected_time.tv_sec + (rrd_delete_unupdated_dimensions * st->update_every)) < st->last_collected_time.tv_sec)
1012                 break;
1013
1014         if(unlikely(rd)) {
1015             RRDDIM *last;
1016             // there is dimension to free
1017             // upgrade our read lock to a write lock
1018             pthread_rwlock_unlock(&st->rwlock);
1019             pthread_rwlock_wrlock(&st->rwlock);
1020
1021             for( rd = st->dimensions, last = NULL ; likely(rd) ; ) {
1022                 // remove it only it is not updated in rrd_delete_unupdated_dimensions seconds
1023
1024                 if(unlikely((rd->last_collected_time.tv_sec + (rrd_delete_unupdated_dimensions * st->update_every)) < st->last_collected_time.tv_sec)) {
1025                     info("Removing obsolete dimension '%s' (%s) of '%s' (%s).", rd->name, rd->id, st->name, st->id);
1026
1027                     if(unlikely(!last)) {
1028                         st->dimensions = rd->next;
1029                         rd->next = NULL;
1030                         rrddim_free(st, rd);
1031                         rd = st->dimensions;
1032                         continue;
1033                     }
1034                     else {
1035                         last->next = rd->next;
1036                         rd->next = NULL;
1037                         rrddim_free(st, rd);
1038                         rd = last->next;
1039                         continue;
1040                     }
1041                 }
1042
1043                 last = rd;
1044                 rd = rd->next;
1045             }
1046
1047             if(unlikely(!st->dimensions)) {
1048                 info("Disabling chart %s (%s) since it does not have any dimensions", st->name, st->id);
1049                 st->enabled = 0;
1050             }
1051         }
1052     }
1053 */
1054
1055     pthread_rwlock_unlock(&st->rwlock);
1056
1057     if(unlikely(pthread_setcancelstate(pthreadoldcancelstate, NULL) != 0))
1058         error("Cannot set pthread cancel state to RESTORE (%d).", pthreadoldcancelstate);
1059
1060     return(st->usec_since_last_update);
1061 }
1062