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