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