rrdset.c 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #define NETDATA_RRD_INTERNALS
  3. #include "rrd.h"
  4. #include <sched.h>
  5. #include "storage_engine.h"
  6. // ----------------------------------------------------------------------------
  7. // RRDSET name index
  8. static void rrdset_name_insert_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rrdset, void *rrdhost __maybe_unused) {
  9. RRDSET *st = rrdset;
  10. rrdset_flag_set(st, RRDSET_FLAG_INDEXED_NAME);
  11. }
  12. static void rrdset_name_delete_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rrdset, void *rrdhost __maybe_unused) {
  13. RRDSET *st = rrdset;
  14. rrdset_flag_clear(st, RRDSET_FLAG_INDEXED_NAME);
  15. }
  16. static inline void rrdset_index_add_name(RRDHOST *host, RRDSET *st) {
  17. if(!st->name) return;
  18. dictionary_set(host->rrdset_root_index_name, rrdset_name(st), st, sizeof(RRDSET));
  19. }
  20. static inline void rrdset_index_del_name(RRDHOST *host, RRDSET *st) {
  21. if(rrdset_flag_check(st, RRDSET_FLAG_INDEXED_NAME))
  22. dictionary_del(host->rrdset_root_index_name, rrdset_name(st));
  23. }
  24. static inline RRDSET *rrdset_index_find_name(RRDHOST *host, const char *name) {
  25. if (unlikely(!host->rrdset_root_index_name))
  26. return NULL;
  27. return dictionary_get(host->rrdset_root_index_name, name);
  28. }
  29. // ----------------------------------------------------------------------------
  30. // RRDSET index
  31. static inline void rrdset_update_permanent_labels(RRDSET *st) {
  32. if(!st->rrdlabels) return;
  33. rrdlabels_add(st->rrdlabels, "_collect_plugin", rrdset_plugin_name(st), RRDLABEL_SRC_AUTO| RRDLABEL_FLAG_PERMANENT);
  34. rrdlabels_add(st->rrdlabels, "_collect_module", rrdset_module_name(st), RRDLABEL_SRC_AUTO| RRDLABEL_FLAG_PERMANENT);
  35. }
  36. static STRING *rrdset_fix_name(RRDHOST *host, const char *chart_full_id, const char *type, const char *current_name, const char *name) {
  37. if(!name || !*name) return NULL;
  38. char full_name[RRD_ID_LENGTH_MAX + 1];
  39. char sanitized_name[CONFIG_MAX_VALUE + 1];
  40. char new_name[CONFIG_MAX_VALUE + 1];
  41. snprintfz(full_name, RRD_ID_LENGTH_MAX, "%s.%s", type, name);
  42. rrdset_strncpyz_name(sanitized_name, full_name, CONFIG_MAX_VALUE);
  43. strncpyz(new_name, sanitized_name, CONFIG_MAX_VALUE);
  44. if(rrdset_index_find_name(host, new_name)) {
  45. debug(D_RRD_CALLS, "RRDSET: chart name '%s' on host '%s' already exists.", new_name, rrdhost_hostname(host));
  46. if(!strcmp(chart_full_id, full_name) && (!current_name || !*current_name)) {
  47. unsigned i = 1;
  48. do {
  49. snprintfz(new_name, CONFIG_MAX_VALUE, "%s_%u", sanitized_name, i);
  50. i++;
  51. } while (rrdset_index_find_name(host, new_name));
  52. info("RRDSET: using name '%s' for chart '%s' on host '%s'.", new_name, full_name, rrdhost_hostname(host));
  53. }
  54. else
  55. return NULL;
  56. }
  57. return string_strdupz(new_name);
  58. }
  59. struct rrdset_constructor {
  60. RRDHOST *host;
  61. const char *type;
  62. const char *id;
  63. const char *name;
  64. const char *family;
  65. const char *context;
  66. const char *title;
  67. const char *units;
  68. const char *plugin;
  69. const char *module;
  70. long priority;
  71. int update_every;
  72. RRDSET_TYPE chart_type;
  73. RRD_MEMORY_MODE memory_mode;
  74. long history_entries;
  75. enum {
  76. RRDSET_REACT_NONE = 0,
  77. RRDSET_REACT_NEW = (1 << 0),
  78. RRDSET_REACT_UPDATED = (1 << 1),
  79. RRDSET_REACT_PLUGIN_UPDATED = (1 << 2),
  80. RRDSET_REACT_MODULE_UPDATED = (1 << 3),
  81. RRDSET_REACT_CHART_ACTIVATED = (1 << 4),
  82. } react_action;
  83. };
  84. // the constructor - the dictionary is write locked while this runs
  85. static void rrdset_insert_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rrdset, void *constructor_data) {
  86. struct rrdset_constructor *ctr = constructor_data;
  87. RRDHOST *host = ctr->host;
  88. RRDSET *st = rrdset;
  89. const char *chart_full_id = dictionary_acquired_item_name(item);
  90. st->id = string_strdupz(chart_full_id);
  91. st->name = rrdset_fix_name(host, chart_full_id, ctr->type, NULL, ctr->name);
  92. if(!st->name)
  93. st->name = rrdset_fix_name(host, chart_full_id, ctr->type, NULL, ctr->id);
  94. rrdset_index_add_name(host, st);
  95. st->parts.id = string_strdupz(ctr->id);
  96. st->parts.type = string_strdupz(ctr->type);
  97. st->parts.name = string_strdupz(ctr->name);
  98. st->family = (ctr->family && *ctr->family) ? rrd_string_strdupz(ctr->family) : rrd_string_strdupz(ctr->type);
  99. st->context = (ctr->context && *ctr->context) ? rrd_string_strdupz(ctr->context) : rrd_string_strdupz(chart_full_id);
  100. st->units = rrd_string_strdupz(ctr->units);
  101. st->title = rrd_string_strdupz(ctr->title);
  102. st->plugin_name = rrd_string_strdupz(ctr->plugin);
  103. st->module_name = rrd_string_strdupz(ctr->module);
  104. st->priority = ctr->priority;
  105. st->entries = (ctr->memory_mode != RRD_MEMORY_MODE_DBENGINE) ? align_entries_to_pagesize(ctr->memory_mode, ctr->history_entries) : 5;
  106. st->update_every = ctr->update_every;
  107. st->rrd_memory_mode = ctr->memory_mode;
  108. st->chart_type = ctr->chart_type;
  109. st->rrdhost = host;
  110. netdata_spinlock_init(&st->data_collection_lock);
  111. st->flags = RRDSET_FLAG_SYNC_CLOCK
  112. | RRDSET_FLAG_INDEXED_ID
  113. | RRDSET_FLAG_RECEIVER_REPLICATION_FINISHED
  114. | RRDSET_FLAG_SENDER_REPLICATION_FINISHED
  115. ;
  116. netdata_rwlock_init(&st->alerts.rwlock);
  117. if(st->rrd_memory_mode == RRD_MEMORY_MODE_SAVE || st->rrd_memory_mode == RRD_MEMORY_MODE_MAP) {
  118. if(!rrdset_memory_load_or_create_map_save(st, st->rrd_memory_mode)) {
  119. info("Failed to use db mode %s for chart '%s', falling back to ram mode.", (st->rrd_memory_mode == RRD_MEMORY_MODE_MAP)?"map":"save", rrdset_name(st));
  120. st->rrd_memory_mode = RRD_MEMORY_MODE_RAM;
  121. }
  122. }
  123. // initialize the db tiers
  124. {
  125. for(size_t tier = 0; tier < storage_tiers ; tier++) {
  126. STORAGE_ENGINE *eng = st->rrdhost->db[tier].eng;
  127. if(!eng) continue;
  128. st->storage_metrics_groups[tier] = eng->api.collect_ops.metrics_group_get(host->db[tier].instance, &st->chart_uuid);
  129. }
  130. }
  131. rrddim_index_init(st);
  132. // chart variables - we need this for data collection to work (collector given chart variables) - not only health
  133. rrdsetvar_index_init(st);
  134. if (host->health.health_enabled) {
  135. st->rrdfamily = rrdfamily_add_and_acquire(host, rrdset_family(st));
  136. st->rrdvars = rrdvariables_create();
  137. rrddimvar_index_init(st);
  138. }
  139. st->rrdlabels = rrdlabels_create();
  140. rrdset_update_permanent_labels(st);
  141. st->green = NAN;
  142. st->red = NAN;
  143. ctr->react_action = RRDSET_REACT_NEW;
  144. ml_chart_new(st);
  145. }
  146. void rrdset_finalize_collection(RRDSET *st, bool dimensions_too) {
  147. RRDHOST *host = st->rrdhost;
  148. rrdset_flag_set(st, RRDSET_FLAG_COLLECTION_FINISHED);
  149. if(dimensions_too) {
  150. RRDDIM *rd;
  151. rrddim_foreach_read(rd, st)
  152. rrddim_finalize_collection_and_check_retention(rd);
  153. rrddim_foreach_done(rd);
  154. }
  155. for(size_t tier = 0; tier < storage_tiers ; tier++) {
  156. STORAGE_ENGINE *eng = st->rrdhost->db[tier].eng;
  157. if(!eng) continue;
  158. if(st->storage_metrics_groups[tier]) {
  159. eng->api.collect_ops.metrics_group_release(host->db[tier].instance, st->storage_metrics_groups[tier]);
  160. st->storage_metrics_groups[tier] = NULL;
  161. }
  162. }
  163. }
  164. // the destructor - the dictionary is write locked while this runs
  165. static void rrdset_delete_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rrdset, void *rrdhost) {
  166. RRDHOST *host = rrdhost;
  167. RRDSET *st = rrdset;
  168. rrdset_flag_clear(st, RRDSET_FLAG_INDEXED_ID);
  169. rrdset_finalize_collection(st, false);
  170. // remove it from the name index
  171. rrdset_index_del_name(host, st);
  172. // release the collector info
  173. dictionary_destroy(st->functions_view);
  174. rrdcalc_unlink_all_rrdset_alerts(st);
  175. // ------------------------------------------------------------------------
  176. // the order of destruction is important here
  177. // 1. delete RRDDIMVAR index - this will speed up the destruction of RRDDIMs
  178. // because each dimension loops to find its own variables in this index.
  179. // There are no references to the items on this index from the dimensions.
  180. // To find their own, they have to walk-through the dictionary.
  181. rrddimvar_index_destroy(st); // destroy the rrddimvar index
  182. // 2. delete RRDSETVAR index
  183. rrdsetvar_index_destroy(st); // destroy the rrdsetvar index
  184. // 3. delete RRDVAR index after the above, to avoid triggering its garbage collector (they have references on this)
  185. rrdvariables_destroy(st->rrdvars); // free all variables and destroy the rrdvar dictionary
  186. // 4. delete RRDFAMILY - this has to be last, because RRDDIMVAR and RRDSETVAR need the reference counter
  187. rrdfamily_release(host, st->rrdfamily); // release the acquired rrdfamily -- has to be after all variables
  188. // 5. delete RRDDIMs, now their variables are not existing, so this is fast
  189. rrddim_index_destroy(st); // free all the dimensions and destroy the dimensions index
  190. // 6. this has to be after the dimensions are freed, but before labels are freed (contexts need the labels)
  191. rrdcontext_removed_rrdset(st); // let contexts know
  192. // 7. destroy the chart labels
  193. rrdlabels_destroy(st->rrdlabels); // destroy the labels, after letting the contexts know
  194. // 8. destroy the ml handle
  195. ml_chart_delete(st);
  196. rrdset_memory_file_free(st); // remove files of db mode save and map
  197. // ------------------------------------------------------------------------
  198. // free it
  199. netdata_rwlock_destroy(&st->alerts.rwlock);
  200. string_freez(st->id);
  201. string_freez(st->name);
  202. string_freez(st->parts.id);
  203. string_freez(st->parts.type);
  204. string_freez(st->parts.name);
  205. string_freez(st->family);
  206. string_freez(st->title);
  207. string_freez(st->units);
  208. string_freez(st->context);
  209. string_freez(st->plugin_name);
  210. string_freez(st->module_name);
  211. freez(st->exporting_flags);
  212. freez(st->cache_dir);
  213. }
  214. // the item to be inserted, is already in the dictionary
  215. // this callback deals with the situation, migrating the existing object to the new values
  216. // the dictionary is write locked while this runs
  217. static bool rrdset_conflict_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rrdset, void *new_rrdset, void *constructor_data) {
  218. (void)new_rrdset; // it is NULL
  219. struct rrdset_constructor *ctr = constructor_data;
  220. RRDSET *st = rrdset;
  221. rrdset_isnot_obsolete(st);
  222. ctr->react_action = RRDSET_REACT_NONE;
  223. if (rrdset_flag_check(st, RRDSET_FLAG_ARCHIVED)) {
  224. rrdset_flag_clear(st, RRDSET_FLAG_ARCHIVED);
  225. ctr->react_action |= RRDSET_REACT_CHART_ACTIVATED;
  226. }
  227. if (rrdset_reset_name(st, (ctr->name && *ctr->name) ? ctr->name : ctr->id) == 2)
  228. ctr->react_action |= RRDSET_REACT_UPDATED;
  229. if (unlikely(st->priority != ctr->priority)) {
  230. st->priority = ctr->priority;
  231. ctr->react_action |= RRDSET_REACT_UPDATED;
  232. }
  233. if (unlikely(st->update_every != ctr->update_every)) {
  234. rrdset_set_update_every_s(st, ctr->update_every);
  235. ctr->react_action |= RRDSET_REACT_UPDATED;
  236. }
  237. if(ctr->plugin && *ctr->plugin) {
  238. STRING *old_plugin = st->plugin_name;
  239. st->plugin_name = rrd_string_strdupz(ctr->plugin);
  240. if (old_plugin != st->plugin_name)
  241. ctr->react_action |= RRDSET_REACT_PLUGIN_UPDATED;
  242. string_freez(old_plugin);
  243. }
  244. if(ctr->module && *ctr->module) {
  245. STRING *old_module = st->module_name;
  246. st->module_name = rrd_string_strdupz(ctr->module);
  247. if (old_module != st->module_name)
  248. ctr->react_action |= RRDSET_REACT_MODULE_UPDATED;
  249. string_freez(old_module);
  250. }
  251. if(ctr->title && *ctr->title) {
  252. STRING *old_title = st->title;
  253. st->title = rrd_string_strdupz(ctr->title);
  254. if(old_title != st->title)
  255. ctr->react_action |= RRDSET_REACT_UPDATED;
  256. string_freez(old_title);
  257. }
  258. if(ctr->units && *ctr->units) {
  259. STRING *old_units = st->units;
  260. st->units = rrd_string_strdupz(ctr->units);
  261. if(old_units != st->units)
  262. ctr->react_action |= RRDSET_REACT_UPDATED;
  263. string_freez(old_units);
  264. }
  265. if(ctr->family && *ctr->family) {
  266. STRING *old_family = st->family;
  267. st->family = rrd_string_strdupz(ctr->family);
  268. if(old_family != st->family)
  269. ctr->react_action |= RRDSET_REACT_UPDATED;
  270. string_freez(old_family);
  271. // TODO - we should rename RRDFAMILY variables
  272. }
  273. if(ctr->context && *ctr->context) {
  274. STRING *old_context = st->context;
  275. st->context = rrd_string_strdupz(ctr->context);
  276. if(old_context != st->context)
  277. ctr->react_action |= RRDSET_REACT_UPDATED;
  278. string_freez(old_context);
  279. }
  280. if(st->chart_type != ctr->chart_type) {
  281. st->chart_type = ctr->chart_type;
  282. ctr->react_action |= RRDSET_REACT_UPDATED;
  283. }
  284. rrdset_update_permanent_labels(st);
  285. rrdset_flag_set(st, RRDSET_FLAG_SYNC_CLOCK);
  286. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  287. return ctr->react_action != RRDSET_REACT_NONE;
  288. }
  289. // this is called after all insertions/conflicts, with the dictionary unlocked, with a reference to RRDSET
  290. // so, any actions requiring locks on other objects, should be placed here
  291. static void rrdset_react_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rrdset, void *constructor_data) {
  292. struct rrdset_constructor *ctr = constructor_data;
  293. RRDSET *st = rrdset;
  294. RRDHOST *host = st->rrdhost;
  295. st->last_accessed_time_s = now_realtime_sec();
  296. if(host->health.health_enabled && (ctr->react_action & (RRDSET_REACT_NEW | RRDSET_REACT_CHART_ACTIVATED))) {
  297. rrdset_flag_set(st, RRDSET_FLAG_PENDING_HEALTH_INITIALIZATION);
  298. rrdhost_flag_set(st->rrdhost, RRDHOST_FLAG_PENDING_HEALTH_INITIALIZATION);
  299. }
  300. if(ctr->react_action & (RRDSET_REACT_NEW | RRDSET_REACT_PLUGIN_UPDATED | RRDSET_REACT_MODULE_UPDATED)) {
  301. if (ctr->react_action & RRDSET_REACT_NEW) {
  302. if(unlikely(rrdcontext_find_chart_uuid(st, &st->chart_uuid)))
  303. uuid_generate(st->chart_uuid);
  304. }
  305. rrdset_flag_set(st, RRDSET_FLAG_METADATA_UPDATE);
  306. rrdhost_flag_set(st->rrdhost, RRDHOST_FLAG_METADATA_UPDATE);
  307. }
  308. rrdcontext_updated_rrdset(st);
  309. }
  310. void rrdset_index_init(RRDHOST *host) {
  311. if(!host->rrdset_root_index) {
  312. host->rrdset_root_index = dictionary_create_advanced(DICT_OPTION_DONT_OVERWRITE_VALUE | DICT_OPTION_FIXED_SIZE,
  313. &dictionary_stats_category_rrdset_rrddim, sizeof(RRDSET));
  314. dictionary_register_insert_callback(host->rrdset_root_index, rrdset_insert_callback, NULL);
  315. dictionary_register_conflict_callback(host->rrdset_root_index, rrdset_conflict_callback, NULL);
  316. dictionary_register_react_callback(host->rrdset_root_index, rrdset_react_callback, NULL);
  317. dictionary_register_delete_callback(host->rrdset_root_index, rrdset_delete_callback, host);
  318. }
  319. if(!host->rrdset_root_index_name) {
  320. host->rrdset_root_index_name = dictionary_create_advanced(
  321. DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE | DICT_OPTION_DONT_OVERWRITE_VALUE,
  322. &dictionary_stats_category_rrdset_rrddim, 0);
  323. dictionary_register_insert_callback(host->rrdset_root_index_name, rrdset_name_insert_callback, host);
  324. dictionary_register_delete_callback(host->rrdset_root_index_name, rrdset_name_delete_callback, host);
  325. }
  326. }
  327. void rrdset_index_destroy(RRDHOST *host) {
  328. // destroy the name index first
  329. dictionary_destroy(host->rrdset_root_index_name);
  330. host->rrdset_root_index_name = NULL;
  331. // destroy the id index last
  332. dictionary_destroy(host->rrdset_root_index);
  333. host->rrdset_root_index = NULL;
  334. }
  335. static inline RRDSET *rrdset_index_add(RRDHOST *host, const char *id, struct rrdset_constructor *st_ctr) {
  336. return dictionary_set_advanced(host->rrdset_root_index, id, -1, NULL, sizeof(RRDSET), st_ctr);
  337. }
  338. static inline void rrdset_index_del(RRDHOST *host, RRDSET *st) {
  339. if(rrdset_flag_check(st, RRDSET_FLAG_INDEXED_ID))
  340. dictionary_del(host->rrdset_root_index, rrdset_id(st));
  341. }
  342. static RRDSET *rrdset_index_find(RRDHOST *host, const char *id) {
  343. // TODO - the name index should have an acquired dictionary item, not just a pointer to RRDSET
  344. if (unlikely(!host->rrdset_root_index))
  345. return NULL;
  346. return dictionary_get(host->rrdset_root_index, id);
  347. }
  348. // ----------------------------------------------------------------------------
  349. // RRDSET - find charts
  350. inline RRDSET *rrdset_find(RRDHOST *host, const char *id) {
  351. debug(D_RRD_CALLS, "rrdset_find() for chart '%s' in host '%s'", id, rrdhost_hostname(host));
  352. RRDSET *st = rrdset_index_find(host, id);
  353. if(st)
  354. st->last_accessed_time_s = now_realtime_sec();
  355. return(st);
  356. }
  357. inline RRDSET *rrdset_find_bytype(RRDHOST *host, const char *type, const char *id) {
  358. debug(D_RRD_CALLS, "rrdset_find_bytype() for chart '%s.%s' in host '%s'", type, id, rrdhost_hostname(host));
  359. char buf[RRD_ID_LENGTH_MAX + 1];
  360. strncpyz(buf, type, RRD_ID_LENGTH_MAX - 1);
  361. strcat(buf, ".");
  362. int len = (int) strlen(buf);
  363. strncpyz(&buf[len], id, (size_t) (RRD_ID_LENGTH_MAX - len));
  364. return(rrdset_find(host, buf));
  365. }
  366. inline RRDSET *rrdset_find_byname(RRDHOST *host, const char *name) {
  367. debug(D_RRD_CALLS, "rrdset_find_byname() for chart '%s' in host '%s'", name, rrdhost_hostname(host));
  368. RRDSET *st = rrdset_index_find_name(host, name);
  369. return(st);
  370. }
  371. // ----------------------------------------------------------------------------
  372. // RRDSET - rename charts
  373. char *rrdset_strncpyz_name(char *to, const char *from, size_t length) {
  374. char c, *p = to;
  375. while (length-- && (c = *from++)) {
  376. if(c != '.' && c != '-' && !isalnum(c))
  377. c = '_';
  378. *p++ = c;
  379. }
  380. *p = '\0';
  381. return to;
  382. }
  383. int rrdset_reset_name(RRDSET *st, const char *name) {
  384. if(unlikely(!strcmp(rrdset_name(st), name)))
  385. return 1;
  386. RRDHOST *host = st->rrdhost;
  387. debug(D_RRD_CALLS, "rrdset_reset_name() old: '%s', new: '%s'", rrdset_name(st), name);
  388. STRING *name_string = rrdset_fix_name(host, rrdset_id(st), rrdset_parts_type(st), string2str(st->name), name);
  389. if(!name_string) return 0;
  390. if(st->name) {
  391. rrdset_index_del_name(host, st);
  392. string_freez(st->name);
  393. st->name = name_string;
  394. rrdsetvar_rename_all(st);
  395. }
  396. else
  397. st->name = name_string;
  398. RRDDIM *rd;
  399. rrddim_foreach_read(rd, st)
  400. rrddimvar_rename_all(rd);
  401. rrddim_foreach_done(rd);
  402. rrdset_index_add_name(host, st);
  403. rrdset_flag_clear(st, RRDSET_FLAG_EXPORTING_SEND);
  404. rrdset_flag_clear(st, RRDSET_FLAG_EXPORTING_IGNORE);
  405. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_SEND);
  406. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  407. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  408. rrdcontext_updated_rrdset_name(st);
  409. return 2;
  410. }
  411. // get the timestamp of the last entry in the round-robin database
  412. time_t rrdset_last_entry_s(RRDSET *st) {
  413. RRDDIM *rd;
  414. time_t last_entry_s = 0;
  415. rrddim_foreach_read(rd, st) {
  416. time_t t = rrddim_last_entry_s(rd);
  417. if(t > last_entry_s) last_entry_s = t;
  418. }
  419. rrddim_foreach_done(rd);
  420. return last_entry_s;
  421. }
  422. time_t rrdset_last_entry_s_of_tier(RRDSET *st, size_t tier) {
  423. RRDDIM *rd;
  424. time_t last_entry_s = 0;
  425. rrddim_foreach_read(rd, st) {
  426. time_t t = rrddim_last_entry_s_of_tier(rd, tier);
  427. if(t > last_entry_s) last_entry_s = t;
  428. }
  429. rrddim_foreach_done(rd);
  430. return last_entry_s;
  431. }
  432. // get the timestamp of first entry in the round-robin database
  433. time_t rrdset_first_entry_s(RRDSET *st) {
  434. RRDDIM *rd;
  435. time_t first_entry_s = LONG_MAX;
  436. rrddim_foreach_read(rd, st) {
  437. time_t t = rrddim_first_entry_s(rd);
  438. if(t < first_entry_s)
  439. first_entry_s = t;
  440. }
  441. rrddim_foreach_done(rd);
  442. if (unlikely(LONG_MAX == first_entry_s)) return 0;
  443. return first_entry_s;
  444. }
  445. time_t rrdset_first_entry_s_of_tier(RRDSET *st, size_t tier) {
  446. if(unlikely(tier > storage_tiers))
  447. return 0;
  448. RRDDIM *rd;
  449. time_t first_entry_s = LONG_MAX;
  450. rrddim_foreach_read(rd, st) {
  451. time_t t = rrddim_first_entry_s_of_tier(rd, tier);
  452. if(t && t < first_entry_s)
  453. first_entry_s = t;
  454. }
  455. rrddim_foreach_done(rd);
  456. if (unlikely(LONG_MAX == first_entry_s)) return 0;
  457. return first_entry_s;
  458. }
  459. void rrdset_get_retention_of_tier_for_collected_chart(RRDSET *st, time_t *first_time_s, time_t *last_time_s, time_t now_s, size_t tier) {
  460. if(!now_s)
  461. now_s = now_realtime_sec();
  462. time_t db_first_entry_s = rrdset_first_entry_s_of_tier(st, tier);
  463. time_t db_last_entry_s = st->last_updated.tv_sec; // we assume this is a collected RRDSET
  464. if(unlikely(!db_last_entry_s)) {
  465. db_last_entry_s = rrdset_last_entry_s_of_tier(st, tier);
  466. if (unlikely(!db_last_entry_s)) {
  467. // we assume this is a collected RRDSET
  468. db_first_entry_s = 0;
  469. db_last_entry_s = 0;
  470. }
  471. }
  472. if(unlikely(db_last_entry_s > now_s)) {
  473. internal_error(db_last_entry_s > now_s + 1,
  474. "RRDSET: 'host:%s/chart:%s' latest db time %ld is in the future, adjusting it to now %ld",
  475. rrdhost_hostname(st->rrdhost), rrdset_id(st),
  476. db_last_entry_s, now_s);
  477. db_last_entry_s = now_s;
  478. }
  479. if(unlikely(db_first_entry_s && db_last_entry_s && db_first_entry_s >= db_last_entry_s)) {
  480. internal_error(db_first_entry_s > db_last_entry_s,
  481. "RRDSET: 'host:%s/chart:%s' oldest db time %ld is bigger than latest db time %ld, adjusting it to (latest time %ld - update every %ld)",
  482. rrdhost_hostname(st->rrdhost), rrdset_id(st),
  483. db_first_entry_s, db_last_entry_s,
  484. db_last_entry_s, (time_t)st->update_every);
  485. db_first_entry_s = db_last_entry_s - st->update_every;
  486. }
  487. if(unlikely(!db_first_entry_s && db_last_entry_s))
  488. // this can be the case on the first data collection of a chart
  489. db_first_entry_s = db_last_entry_s - st->update_every;
  490. *first_time_s = db_first_entry_s;
  491. *last_time_s = db_last_entry_s;
  492. }
  493. inline void rrdset_is_obsolete(RRDSET *st) {
  494. if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_ARCHIVED))) {
  495. info("Cannot obsolete already archived chart %s", rrdset_name(st));
  496. return;
  497. }
  498. if(unlikely(!(rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE)))) {
  499. rrdset_flag_set(st, RRDSET_FLAG_OBSOLETE);
  500. rrdhost_flag_set(st->rrdhost, RRDHOST_FLAG_PENDING_OBSOLETE_CHARTS);
  501. st->last_accessed_time_s = now_realtime_sec();
  502. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  503. // the chart will not get more updates (data collection)
  504. // so, we have to push its definition now
  505. rrdset_push_chart_definition_now(st);
  506. rrdcontext_updated_rrdset_flags(st);
  507. }
  508. }
  509. inline void rrdset_isnot_obsolete(RRDSET *st) {
  510. if(unlikely((rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE)))) {
  511. rrdset_flag_clear(st, RRDSET_FLAG_OBSOLETE);
  512. st->last_accessed_time_s = now_realtime_sec();
  513. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  514. // the chart will be pushed upstream automatically
  515. // due to data collection
  516. rrdcontext_updated_rrdset_flags(st);
  517. }
  518. }
  519. inline void rrdset_update_heterogeneous_flag(RRDSET *st) {
  520. RRDHOST *host = st->rrdhost;
  521. (void)host;
  522. RRDDIM *rd;
  523. rrdset_flag_clear(st, RRDSET_FLAG_HOMOGENEOUS_CHECK);
  524. bool init = false, is_heterogeneous = false;
  525. RRD_ALGORITHM algorithm;
  526. collected_number multiplier;
  527. collected_number divisor;
  528. rrddim_foreach_read(rd, st) {
  529. if(!init) {
  530. algorithm = rd->algorithm;
  531. multiplier = rd->multiplier;
  532. divisor = ABS(rd->divisor);
  533. init = true;
  534. continue;
  535. }
  536. if(algorithm != rd->algorithm || multiplier != ABS(rd->multiplier) || divisor != ABS(rd->divisor)) {
  537. if(!rrdset_flag_check(st, RRDSET_FLAG_HETEROGENEOUS)) {
  538. #ifdef NETDATA_INTERNAL_CHECKS
  539. info("Dimension '%s' added on chart '%s' of host '%s' is not homogeneous to other dimensions already present (algorithm is '%s' vs '%s', multiplier is " COLLECTED_NUMBER_FORMAT " vs " COLLECTED_NUMBER_FORMAT ", divisor is " COLLECTED_NUMBER_FORMAT " vs " COLLECTED_NUMBER_FORMAT ").",
  540. rrddim_name(rd),
  541. rrdset_name(st),
  542. rrdhost_hostname(host),
  543. rrd_algorithm_name(rd->algorithm), rrd_algorithm_name(algorithm),
  544. rd->multiplier, multiplier,
  545. rd->divisor, divisor
  546. );
  547. #endif
  548. rrdset_flag_set(st, RRDSET_FLAG_HETEROGENEOUS);
  549. }
  550. is_heterogeneous = true;
  551. break;
  552. }
  553. }
  554. rrddim_foreach_done(rd);
  555. if(!is_heterogeneous) {
  556. rrdset_flag_clear(st, RRDSET_FLAG_HETEROGENEOUS);
  557. rrdcontext_updated_rrdset_flags(st);
  558. }
  559. }
  560. // ----------------------------------------------------------------------------
  561. // RRDSET - reset a chart
  562. void rrdset_reset(RRDSET *st) {
  563. debug(D_RRD_CALLS, "rrdset_reset() %s", rrdset_name(st));
  564. st->last_collected_time.tv_sec = 0;
  565. st->last_collected_time.tv_usec = 0;
  566. st->last_updated.tv_sec = 0;
  567. st->last_updated.tv_usec = 0;
  568. st->current_entry = 0;
  569. st->counter = 0;
  570. st->counter_done = 0;
  571. RRDDIM *rd;
  572. rrddim_foreach_read(rd, st) {
  573. rd->last_collected_time.tv_sec = 0;
  574. rd->last_collected_time.tv_usec = 0;
  575. rd->collections_counter = 0;
  576. if(!rrddim_flag_check(rd, RRDDIM_FLAG_ARCHIVED)) {
  577. for(size_t tier = 0; tier < storage_tiers ;tier++) {
  578. if(rd->tiers[tier].db_collection_handle)
  579. rd->tiers[tier].collect_ops->flush(rd->tiers[tier].db_collection_handle);
  580. }
  581. }
  582. }
  583. rrddim_foreach_done(rd);
  584. }
  585. // ----------------------------------------------------------------------------
  586. // RRDSET - helpers for rrdset_create()
  587. inline long align_entries_to_pagesize(RRD_MEMORY_MODE mode, long entries) {
  588. if(mode == RRD_MEMORY_MODE_DBENGINE) return 0;
  589. if(mode == RRD_MEMORY_MODE_NONE) return 5;
  590. if(entries < 5) entries = 5;
  591. if(entries > RRD_HISTORY_ENTRIES_MAX) entries = RRD_HISTORY_ENTRIES_MAX;
  592. if(mode == RRD_MEMORY_MODE_MAP || mode == RRD_MEMORY_MODE_SAVE || mode == RRD_MEMORY_MODE_RAM) {
  593. long header_size = 0;
  594. if(mode == RRD_MEMORY_MODE_MAP || mode == RRD_MEMORY_MODE_SAVE)
  595. header_size = (long)rrddim_memory_file_header_size();
  596. long page = (long)sysconf(_SC_PAGESIZE);
  597. long size = (long)(header_size + entries * sizeof(storage_number));
  598. if (unlikely(size % page)) {
  599. size -= (size % page);
  600. size += page;
  601. long n = (long)((size - header_size) / sizeof(storage_number));
  602. return n;
  603. }
  604. }
  605. return entries;
  606. }
  607. static inline void last_collected_time_align(RRDSET *st) {
  608. st->last_collected_time.tv_sec -= st->last_collected_time.tv_sec % st->update_every;
  609. if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_STORE_FIRST)))
  610. st->last_collected_time.tv_usec = 0;
  611. else
  612. st->last_collected_time.tv_usec = 500000;
  613. }
  614. static inline void last_updated_time_align(RRDSET *st) {
  615. st->last_updated.tv_sec -= st->last_updated.tv_sec % st->update_every;
  616. st->last_updated.tv_usec = 0;
  617. }
  618. // ----------------------------------------------------------------------------
  619. // RRDSET - free a chart
  620. void rrdset_free(RRDSET *st) {
  621. if(unlikely(!st)) return;
  622. rrdset_index_del(st->rrdhost, st);
  623. }
  624. void rrdset_save(RRDSET *st) {
  625. rrdset_memory_file_save(st);
  626. RRDDIM *rd;
  627. rrddim_foreach_read(rd, st)
  628. rrddim_memory_file_save(rd);
  629. rrddim_foreach_done(rd);
  630. }
  631. void rrdset_delete_files(RRDSET *st) {
  632. RRDDIM *rd;
  633. info("Deleting chart '%s' ('%s') from disk...", rrdset_id(st), rrdset_name(st));
  634. if(st->rrd_memory_mode == RRD_MEMORY_MODE_SAVE || st->rrd_memory_mode == RRD_MEMORY_MODE_MAP) {
  635. const char *cache_filename = rrdset_cache_filename(st);
  636. if(cache_filename) {
  637. info("Deleting chart header file '%s'.", cache_filename);
  638. if (unlikely(unlink(cache_filename) == -1))
  639. error("Cannot delete chart header file '%s'", cache_filename);
  640. }
  641. else
  642. error("Cannot find the cache filename of chart '%s'", rrdset_id(st));
  643. }
  644. rrddim_foreach_read(rd, st) {
  645. const char *cache_filename = rrddim_cache_filename(rd);
  646. if(!cache_filename) continue;
  647. info("Deleting dimension file '%s'.", cache_filename);
  648. if(unlikely(unlink(cache_filename) == -1))
  649. error("Cannot delete dimension file '%s'", cache_filename);
  650. }
  651. rrddim_foreach_done(rd);
  652. if(st->cache_dir)
  653. recursively_delete_dir(st->cache_dir, "left-over chart");
  654. }
  655. void rrdset_delete_obsolete_dimensions(RRDSET *st) {
  656. RRDDIM *rd;
  657. info("Deleting dimensions of chart '%s' ('%s') from disk...", rrdset_id(st), rrdset_name(st));
  658. rrddim_foreach_read(rd, st) {
  659. if(rrddim_flag_check(rd, RRDDIM_FLAG_OBSOLETE)) {
  660. const char *cache_filename = rrddim_cache_filename(rd);
  661. if(!cache_filename) continue;
  662. info("Deleting dimension file '%s'.", cache_filename);
  663. if(unlikely(unlink(cache_filename) == -1))
  664. error("Cannot delete dimension file '%s'", cache_filename);
  665. }
  666. }
  667. rrddim_foreach_done(rd);
  668. }
  669. // ----------------------------------------------------------------------------
  670. // RRDSET - create a chart
  671. RRDSET *rrdset_create_custom(
  672. RRDHOST *host
  673. , const char *type
  674. , const char *id
  675. , const char *name
  676. , const char *family
  677. , const char *context
  678. , const char *title
  679. , const char *units
  680. , const char *plugin
  681. , const char *module
  682. , long priority
  683. , int update_every
  684. , RRDSET_TYPE chart_type
  685. , RRD_MEMORY_MODE memory_mode
  686. , long history_entries
  687. ) {
  688. if (host != localhost)
  689. host->child_last_chart_command = now_realtime_sec();
  690. if(!type || !type[0])
  691. fatal("Cannot create rrd stats without a type: id '%s', name '%s', family '%s', context '%s', title '%s', units '%s', plugin '%s', module '%s'."
  692. , (id && *id)?id:"<unset>"
  693. , (name && *name)?name:"<unset>"
  694. , (family && *family)?family:"<unset>"
  695. , (context && *context)?context:"<unset>"
  696. , (title && *title)?title:"<unset>"
  697. , (units && *units)?units:"<unset>"
  698. , (plugin && *plugin)?plugin:"<unset>"
  699. , (module && *module)?module:"<unset>"
  700. );
  701. if(!id || !id[0])
  702. fatal("Cannot create rrd stats without an id: type '%s', name '%s', family '%s', context '%s', title '%s', units '%s', plugin '%s', module '%s'."
  703. , type
  704. , (name && *name)?name:"<unset>"
  705. , (family && *family)?family:"<unset>"
  706. , (context && *context)?context:"<unset>"
  707. , (title && *title)?title:"<unset>"
  708. , (units && *units)?units:"<unset>"
  709. , (plugin && *plugin)?plugin:"<unset>"
  710. , (module && *module)?module:"<unset>"
  711. );
  712. // ------------------------------------------------------------------------
  713. // check if it already exists
  714. char full_id[RRD_ID_LENGTH_MAX + 1];
  715. snprintfz(full_id, RRD_ID_LENGTH_MAX, "%s.%s", type, id);
  716. // ------------------------------------------------------------------------
  717. // allocate it
  718. debug(D_RRD_CALLS, "Creating RRD_STATS for '%s.%s'.", type, id);
  719. struct rrdset_constructor tmp = {
  720. .host = host,
  721. .type = type,
  722. .id = id,
  723. .name = name,
  724. .family = family,
  725. .context = context,
  726. .title = title,
  727. .units = units,
  728. .plugin = plugin,
  729. .module = module,
  730. .priority = priority,
  731. .update_every = update_every,
  732. .chart_type = chart_type,
  733. .memory_mode = memory_mode,
  734. .history_entries = history_entries,
  735. };
  736. RRDSET *st = rrdset_index_add(host, full_id, &tmp);
  737. return(st);
  738. }
  739. // ----------------------------------------------------------------------------
  740. // RRDSET - data collection iteration control
  741. void rrdset_timed_next(RRDSET *st, struct timeval now, usec_t duration_since_last_update) {
  742. #ifdef NETDATA_INTERNAL_CHECKS
  743. char *discard_reason = NULL;
  744. usec_t discarded = duration_since_last_update;
  745. #endif
  746. if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_SYNC_CLOCK))) {
  747. // the chart needs to be re-synced to current time
  748. rrdset_flag_clear(st, RRDSET_FLAG_SYNC_CLOCK);
  749. // discard the duration supplied
  750. duration_since_last_update = 0;
  751. #ifdef NETDATA_INTERNAL_CHECKS
  752. if(!discard_reason) discard_reason = "SYNC CLOCK FLAG";
  753. #endif
  754. }
  755. if(unlikely(!st->last_collected_time.tv_sec)) {
  756. // the first entry
  757. duration_since_last_update = st->update_every * USEC_PER_SEC;
  758. #ifdef NETDATA_INTERNAL_CHECKS
  759. if(!discard_reason) discard_reason = "FIRST DATA COLLECTION";
  760. #endif
  761. }
  762. else if(unlikely(!duration_since_last_update)) {
  763. // no dt given by the plugin
  764. duration_since_last_update = dt_usec(&now, &st->last_collected_time);
  765. #ifdef NETDATA_INTERNAL_CHECKS
  766. if(!discard_reason) discard_reason = "NO USEC GIVEN BY COLLECTOR";
  767. #endif
  768. }
  769. else {
  770. // microseconds has the time since the last collection
  771. susec_t since_last_usec = dt_usec_signed(&now, &st->last_collected_time);
  772. if(unlikely(since_last_usec < 0)) {
  773. // oops! the database is in the future
  774. #ifdef NETDATA_INTERNAL_CHECKS
  775. info("RRD database for chart '%s' on host '%s' is %0.5" NETDATA_DOUBLE_MODIFIER
  776. " secs in the future (counter #%zu, update #%zu). Adjusting it to current time."
  777. , rrdset_id(st)
  778. , rrdhost_hostname(st->rrdhost)
  779. , (NETDATA_DOUBLE)-since_last_usec / USEC_PER_SEC
  780. , st->counter
  781. , st->counter_done
  782. );
  783. #endif
  784. duration_since_last_update = 0;
  785. #ifdef NETDATA_INTERNAL_CHECKS
  786. if(!discard_reason) discard_reason = "COLLECTION TIME IN FUTURE";
  787. #endif
  788. }
  789. else if(unlikely((usec_t)since_last_usec > (usec_t)(st->update_every * 5 * USEC_PER_SEC))) {
  790. // oops! the database is too far behind
  791. #ifdef NETDATA_INTERNAL_CHECKS
  792. info("RRD database for chart '%s' on host '%s' is %0.5" NETDATA_DOUBLE_MODIFIER
  793. " secs in the past (counter #%zu, update #%zu). Adjusting it to current time.", rrdset_id(st), rrdhost_hostname(st->rrdhost), (NETDATA_DOUBLE)since_last_usec / USEC_PER_SEC, st->counter, st->counter_done);
  794. #endif
  795. duration_since_last_update = (usec_t)since_last_usec;
  796. #ifdef NETDATA_INTERNAL_CHECKS
  797. if(!discard_reason) discard_reason = "COLLECTION TIME TOO FAR IN THE PAST";
  798. #endif
  799. }
  800. #ifdef NETDATA_INTERNAL_CHECKS
  801. if(since_last_usec > 0 && (susec_t) duration_since_last_update < since_last_usec) {
  802. static __thread susec_t min_delta = USEC_PER_SEC * 3600, permanent_min_delta = 0;
  803. static __thread time_t last_time_s = 0;
  804. // the first time initialize it so that it will make the check later
  805. if(last_time_s == 0) last_time_s = now.tv_sec + 60;
  806. susec_t delta = since_last_usec - (susec_t) duration_since_last_update;
  807. if(delta < min_delta) min_delta = delta;
  808. if(now.tv_sec >= last_time_s + 60) {
  809. last_time_s = now.tv_sec;
  810. if(min_delta > permanent_min_delta) {
  811. info("MINIMUM MICROSECONDS DELTA of thread %d increased from %lld to %lld (+%lld)", gettid(), permanent_min_delta, min_delta, min_delta - permanent_min_delta);
  812. permanent_min_delta = min_delta;
  813. }
  814. min_delta = USEC_PER_SEC * 3600;
  815. }
  816. }
  817. #endif
  818. }
  819. debug(D_RRD_CALLS, "rrdset_timed_next() for chart %s with duration since last update %llu usec", rrdset_name(st), duration_since_last_update);
  820. rrdset_debug(st, "NEXT: %llu microseconds", duration_since_last_update);
  821. internal_error(discarded && discarded != duration_since_last_update,
  822. "host '%s', chart '%s': discarded data collection time of %llu usec, "
  823. "replaced with %llu usec, reason: '%s'"
  824. , rrdhost_hostname(st->rrdhost)
  825. , rrdset_id(st)
  826. , discarded
  827. , duration_since_last_update
  828. , discard_reason?discard_reason:"UNDEFINED"
  829. );
  830. st->usec_since_last_update = duration_since_last_update;
  831. }
  832. inline void rrdset_next_usec_unfiltered(RRDSET *st, usec_t duration_since_last_update) {
  833. if(unlikely(!st->last_collected_time.tv_sec || !duration_since_last_update || (rrdset_flag_check(st, RRDSET_FLAG_SYNC_CLOCK)))) {
  834. // call the full next_usec() function
  835. rrdset_next_usec(st, duration_since_last_update);
  836. return;
  837. }
  838. st->usec_since_last_update = duration_since_last_update;
  839. }
  840. inline void rrdset_next_usec(RRDSET *st, usec_t duration_since_last_update) {
  841. struct timeval now;
  842. now_realtime_timeval(&now);
  843. rrdset_timed_next(st, now, duration_since_last_update);
  844. }
  845. // ----------------------------------------------------------------------------
  846. // RRDSET - process the collected values for all dimensions of a chart
  847. static inline usec_t rrdset_init_last_collected_time(RRDSET *st, struct timeval now) {
  848. st->last_collected_time = now;
  849. last_collected_time_align(st);
  850. usec_t last_collect_ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec;
  851. rrdset_debug(st, "initialized last collected time to %0.3" NETDATA_DOUBLE_MODIFIER, (NETDATA_DOUBLE)last_collect_ut / USEC_PER_SEC);
  852. return last_collect_ut;
  853. }
  854. static inline usec_t rrdset_update_last_collected_time(RRDSET *st) {
  855. usec_t last_collect_ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec;
  856. usec_t ut = last_collect_ut + st->usec_since_last_update;
  857. st->last_collected_time.tv_sec = (time_t) (ut / USEC_PER_SEC);
  858. st->last_collected_time.tv_usec = (suseconds_t) (ut % USEC_PER_SEC);
  859. rrdset_debug(st, "updated last collected time to %0.3" NETDATA_DOUBLE_MODIFIER, (NETDATA_DOUBLE)last_collect_ut / USEC_PER_SEC);
  860. return last_collect_ut;
  861. }
  862. static inline void rrdset_init_last_updated_time(RRDSET *st) {
  863. // copy the last collected time to last updated time
  864. st->last_updated.tv_sec = st->last_collected_time.tv_sec;
  865. st->last_updated.tv_usec = st->last_collected_time.tv_usec;
  866. if(rrdset_flag_check(st, RRDSET_FLAG_STORE_FIRST))
  867. st->last_updated.tv_sec -= st->update_every;
  868. last_updated_time_align(st);
  869. }
  870. static __thread size_t rrdset_done_statistics_points_stored_per_tier[RRD_STORAGE_TIERS];
  871. static inline time_t tier_next_point_time_s(RRDDIM *rd, struct rrddim_tier *t, time_t now_s) {
  872. time_t loop = (time_t)rd->update_every * (time_t)t->tier_grouping;
  873. return now_s + loop - ((now_s + loop) % loop);
  874. }
  875. void store_metric_at_tier(RRDDIM *rd, size_t tier, struct rrddim_tier *t, STORAGE_POINT sp, usec_t now_ut __maybe_unused) {
  876. if (unlikely(!t->next_point_end_time_s))
  877. t->next_point_end_time_s = tier_next_point_time_s(rd, t, sp.end_time_s);
  878. if(unlikely(sp.start_time_s >= t->next_point_end_time_s)) {
  879. // flush the virtual point, it is done
  880. if (likely(!storage_point_is_unset(t->virtual_point))) {
  881. t->collect_ops->store_metric(
  882. t->db_collection_handle,
  883. t->next_point_end_time_s * USEC_PER_SEC,
  884. t->virtual_point.sum,
  885. t->virtual_point.min,
  886. t->virtual_point.max,
  887. t->virtual_point.count,
  888. t->virtual_point.anomaly_count,
  889. t->virtual_point.flags);
  890. }
  891. else {
  892. t->collect_ops->store_metric(
  893. t->db_collection_handle,
  894. t->next_point_end_time_s * USEC_PER_SEC,
  895. NAN,
  896. NAN,
  897. NAN,
  898. 0,
  899. 0, SN_FLAG_NONE);
  900. }
  901. rrdset_done_statistics_points_stored_per_tier[tier]++;
  902. t->virtual_point.count = 0; // make the point unset
  903. t->next_point_end_time_s = tier_next_point_time_s(rd, t, sp.end_time_s);
  904. }
  905. // merge the dates into our virtual point
  906. if (unlikely(sp.start_time_s < t->virtual_point.start_time_s))
  907. t->virtual_point.start_time_s = sp.start_time_s;
  908. if (likely(sp.end_time_s > t->virtual_point.end_time_s))
  909. t->virtual_point.end_time_s = sp.end_time_s;
  910. // merge the values into our virtual point
  911. if (likely(!storage_point_is_gap(sp))) {
  912. // we aggregate only non NULLs into higher tiers
  913. if (likely(!storage_point_is_unset(t->virtual_point))) {
  914. // merge the collected point to our virtual one
  915. t->virtual_point.sum += sp.sum;
  916. t->virtual_point.min = MIN(t->virtual_point.min, sp.min);
  917. t->virtual_point.max = MAX(t->virtual_point.max, sp.max);
  918. t->virtual_point.count += sp.count;
  919. t->virtual_point.anomaly_count += sp.anomaly_count;
  920. t->virtual_point.flags |= sp.flags;
  921. }
  922. else {
  923. // reset our virtual point to this one
  924. t->virtual_point = sp;
  925. }
  926. }
  927. }
  928. #ifdef NETDATA_LOG_COLLECTION_ERRORS
  929. void rrddim_store_metric_with_trace(RRDDIM *rd, usec_t point_end_time_ut, NETDATA_DOUBLE n, SN_FLAGS flags, const char *function) {
  930. #else // !NETDATA_LOG_COLLECTION_ERRORS
  931. void rrddim_store_metric(RRDDIM *rd, usec_t point_end_time_ut, NETDATA_DOUBLE n, SN_FLAGS flags) {
  932. #endif // !NETDATA_LOG_COLLECTION_ERRORS
  933. #ifdef NETDATA_LOG_COLLECTION_ERRORS
  934. rd->rrddim_store_metric_count++;
  935. if(likely(rd->rrddim_store_metric_count > 1)) {
  936. usec_t expected = rd->rrddim_store_metric_last_ut + rd->update_every * USEC_PER_SEC;
  937. if(point_end_time_ut != rd->rrddim_store_metric_last_ut) {
  938. internal_error(true,
  939. "%s COLLECTION: 'host:%s/chart:%s/dim:%s' granularity %d, collection %zu, expected to store at tier 0 a value at %llu, but it gave %llu [%s%llu usec] (called from %s(), previously by %s())",
  940. (point_end_time_ut < rd->rrddim_store_metric_last_ut) ? "**PAST**" : "GAP",
  941. rrdhost_hostname(rd->rrdset->rrdhost), rrdset_id(rd->rrdset), rrddim_id(rd),
  942. rd->update_every,
  943. rd->rrddim_store_metric_count,
  944. expected, point_end_time_ut,
  945. (point_end_time_ut < rd->rrddim_store_metric_last_ut)?"by -" : "gap ",
  946. expected - point_end_time_ut,
  947. function,
  948. rd->rrddim_store_metric_last_caller?rd->rrddim_store_metric_last_caller:"none");
  949. }
  950. }
  951. rd->rrddim_store_metric_last_ut = point_end_time_ut;
  952. rd->rrddim_store_metric_last_caller = function;
  953. #endif // NETDATA_LOG_COLLECTION_ERRORS
  954. // store the metric on tier 0
  955. rd->tiers[0].collect_ops->store_metric(rd->tiers[0].db_collection_handle, point_end_time_ut, n, 0, 0, 1, 0, flags);
  956. rrdset_done_statistics_points_stored_per_tier[0]++;
  957. time_t now_s = (time_t)(point_end_time_ut / USEC_PER_SEC);
  958. STORAGE_POINT sp = {
  959. .start_time_s = now_s - rd->update_every,
  960. .end_time_s = now_s,
  961. .min = n,
  962. .max = n,
  963. .sum = n,
  964. .count = 1,
  965. .anomaly_count = (flags & SN_FLAG_NOT_ANOMALOUS) ? 0 : 1,
  966. .flags = flags
  967. };
  968. for(size_t tier = 1; tier < storage_tiers ;tier++) {
  969. if(unlikely(!rd->tiers[tier].db_metric_handle)) continue;
  970. struct rrddim_tier *t = &rd->tiers[tier];
  971. if(!rrddim_option_check(rd, RRDDIM_OPTION_BACKFILLED_HIGH_TIERS)) {
  972. // we have not collected this tier before
  973. // let's fill any gap that may exist
  974. rrdr_fill_tier_gap_from_smaller_tiers(rd, tier, now_s);
  975. rrddim_option_set(rd, RRDDIM_OPTION_BACKFILLED_HIGH_TIERS);
  976. }
  977. store_metric_at_tier(rd, tier, t, sp, point_end_time_ut);
  978. }
  979. }
  980. void store_metric_collection_completed() {
  981. global_statistics_rrdset_done_chart_collection_completed(rrdset_done_statistics_points_stored_per_tier);
  982. }
  983. // caching of dimensions rrdset_done() and rrdset_done_interpolate() loop through
  984. struct rda_item {
  985. const DICTIONARY_ITEM *item;
  986. RRDDIM *rd;
  987. };
  988. static __thread struct rda_item *thread_rda = NULL;
  989. static __thread size_t thread_rda_entries = 0;
  990. struct rda_item *rrdset_thread_rda_get(size_t *dimensions) {
  991. if(unlikely(!thread_rda || (*dimensions) > thread_rda_entries)) {
  992. size_t old_mem = thread_rda_entries * sizeof(struct rda_item);
  993. freez(thread_rda);
  994. thread_rda_entries = *dimensions;
  995. size_t new_mem = thread_rda_entries * sizeof(struct rda_item);
  996. thread_rda = mallocz(new_mem);
  997. __atomic_add_fetch(&netdata_buffers_statistics.rrdset_done_rda_size, new_mem - old_mem, __ATOMIC_RELAXED);
  998. }
  999. *dimensions = thread_rda_entries;
  1000. return thread_rda;
  1001. }
  1002. void rrdset_thread_rda_free(void) {
  1003. __atomic_sub_fetch(&netdata_buffers_statistics.rrdset_done_rda_size, thread_rda_entries * sizeof(struct rda_item), __ATOMIC_RELAXED);
  1004. freez(thread_rda);
  1005. thread_rda = NULL;
  1006. thread_rda_entries = 0;
  1007. }
  1008. static inline size_t rrdset_done_interpolate(
  1009. RRDSET *st
  1010. , struct rda_item *rda_base
  1011. , size_t rda_slots
  1012. , usec_t update_every_ut
  1013. , usec_t last_stored_ut
  1014. , usec_t next_store_ut
  1015. , usec_t last_collect_ut
  1016. , usec_t now_collect_ut
  1017. , char store_this_entry
  1018. , uint32_t has_reset_value
  1019. ) {
  1020. RRDDIM *rd;
  1021. size_t stored_entries = 0; // the number of entries we have stored in the db, during this call to rrdset_done()
  1022. usec_t first_ut = last_stored_ut, last_ut = 0;
  1023. (void)first_ut;
  1024. ssize_t iterations = (ssize_t)((now_collect_ut - last_stored_ut) / (update_every_ut));
  1025. if((now_collect_ut % (update_every_ut)) == 0) iterations++;
  1026. size_t counter = st->counter;
  1027. long current_entry = st->current_entry;
  1028. SN_FLAGS storage_flags = SN_DEFAULT_FLAGS;
  1029. if (has_reset_value)
  1030. storage_flags |= SN_FLAG_RESET;
  1031. for( ; next_store_ut <= now_collect_ut ; last_collect_ut = next_store_ut, next_store_ut += update_every_ut, iterations-- ) {
  1032. internal_error(iterations < 0,
  1033. "RRDSET: '%s': iterations calculation wrapped! "
  1034. "first_ut = %llu, last_stored_ut = %llu, next_store_ut = %llu, now_collect_ut = %llu"
  1035. , rrdset_id(st)
  1036. , first_ut
  1037. , last_stored_ut
  1038. , next_store_ut
  1039. , now_collect_ut
  1040. );
  1041. rrdset_debug(st, "last_stored_ut = %0.3" NETDATA_DOUBLE_MODIFIER " (last updated time)", (NETDATA_DOUBLE)last_stored_ut/USEC_PER_SEC);
  1042. rrdset_debug(st, "next_store_ut = %0.3" NETDATA_DOUBLE_MODIFIER " (next interpolation point)", (NETDATA_DOUBLE)next_store_ut/USEC_PER_SEC);
  1043. last_ut = next_store_ut;
  1044. ml_chart_update_begin(st);
  1045. struct rda_item *rda;
  1046. size_t dim_id;
  1047. for(dim_id = 0, rda = rda_base ; dim_id < rda_slots ; ++dim_id, ++rda) {
  1048. rd = rda->rd;
  1049. if(unlikely(!rd)) continue;
  1050. NETDATA_DOUBLE new_value;
  1051. switch(rd->algorithm) {
  1052. case RRD_ALGORITHM_INCREMENTAL:
  1053. new_value = (NETDATA_DOUBLE)
  1054. ( rd->calculated_value
  1055. * (NETDATA_DOUBLE)(next_store_ut - last_collect_ut)
  1056. / (NETDATA_DOUBLE)(now_collect_ut - last_collect_ut)
  1057. );
  1058. rrdset_debug(st, "%s: CALC2 INC " NETDATA_DOUBLE_FORMAT " = "
  1059. NETDATA_DOUBLE_FORMAT
  1060. " * (%llu - %llu)"
  1061. " / (%llu - %llu)"
  1062. , rrddim_name(rd)
  1063. , new_value
  1064. , rd->calculated_value
  1065. , next_store_ut, last_collect_ut
  1066. , now_collect_ut, last_collect_ut
  1067. );
  1068. rd->calculated_value -= new_value;
  1069. new_value += rd->last_calculated_value;
  1070. rd->last_calculated_value = 0;
  1071. new_value /= (NETDATA_DOUBLE)st->update_every;
  1072. if(unlikely(next_store_ut - last_stored_ut < update_every_ut)) {
  1073. rrdset_debug(st, "%s: COLLECTION POINT IS SHORT " NETDATA_DOUBLE_FORMAT " - EXTRAPOLATING",
  1074. rrddim_name(rd)
  1075. , (NETDATA_DOUBLE)(next_store_ut - last_stored_ut)
  1076. );
  1077. new_value = new_value * (NETDATA_DOUBLE)(st->update_every * USEC_PER_SEC) / (NETDATA_DOUBLE)(next_store_ut - last_stored_ut);
  1078. }
  1079. break;
  1080. case RRD_ALGORITHM_ABSOLUTE:
  1081. case RRD_ALGORITHM_PCENT_OVER_ROW_TOTAL:
  1082. case RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL:
  1083. default:
  1084. if(iterations == 1) {
  1085. // this is the last iteration
  1086. // do not interpolate
  1087. // just show the calculated value
  1088. new_value = rd->calculated_value;
  1089. }
  1090. else {
  1091. // we have missed an update
  1092. // interpolate in the middle values
  1093. new_value = (NETDATA_DOUBLE)
  1094. ( ( (rd->calculated_value - rd->last_calculated_value)
  1095. * (NETDATA_DOUBLE)(next_store_ut - last_collect_ut)
  1096. / (NETDATA_DOUBLE)(now_collect_ut - last_collect_ut)
  1097. )
  1098. + rd->last_calculated_value
  1099. );
  1100. rrdset_debug(st, "%s: CALC2 DEF " NETDATA_DOUBLE_FORMAT " = ((("
  1101. "(" NETDATA_DOUBLE_FORMAT " - " NETDATA_DOUBLE_FORMAT ")"
  1102. " * %llu"
  1103. " / %llu) + " NETDATA_DOUBLE_FORMAT, rrddim_name(rd)
  1104. , new_value
  1105. , rd->calculated_value, rd->last_calculated_value
  1106. , (next_store_ut - first_ut)
  1107. , (now_collect_ut - first_ut), rd->last_calculated_value
  1108. );
  1109. }
  1110. break;
  1111. }
  1112. time_t current_time_s = (time_t) (next_store_ut / USEC_PER_SEC);
  1113. if(unlikely(!store_this_entry)) {
  1114. (void) ml_is_anomalous(rd, current_time_s, 0, false);
  1115. rrddim_store_metric(rd, next_store_ut, NAN, SN_FLAG_NONE);
  1116. rrdcontext_collected_rrddim(rd);
  1117. continue;
  1118. }
  1119. if(likely(rd->updated && rd->collections_counter > 1 && iterations < gap_when_lost_iterations_above)) {
  1120. uint32_t dim_storage_flags = storage_flags;
  1121. if (ml_is_anomalous(rd, current_time_s, new_value, true)) {
  1122. // clear anomaly bit: 0 -> is anomalous, 1 -> not anomalous
  1123. dim_storage_flags &= ~((storage_number)SN_FLAG_NOT_ANOMALOUS);
  1124. }
  1125. rrddim_store_metric(rd, next_store_ut, new_value, dim_storage_flags);
  1126. rrdcontext_collected_rrddim(rd);
  1127. rd->last_stored_value = new_value;
  1128. }
  1129. else {
  1130. (void) ml_is_anomalous(rd, current_time_s, 0, false);
  1131. rrdset_debug(st, "%s: STORE[%ld] = NON EXISTING ", rrddim_name(rd), current_entry);
  1132. rrddim_store_metric(rd, next_store_ut, NAN, SN_FLAG_NONE);
  1133. rrdcontext_collected_rrddim(rd);
  1134. rd->last_stored_value = NAN;
  1135. }
  1136. stored_entries++;
  1137. }
  1138. ml_chart_update_end(st);
  1139. // reset the storage flags for the next point, if any;
  1140. storage_flags = SN_DEFAULT_FLAGS;
  1141. st->counter = ++counter;
  1142. st->current_entry = current_entry = ((current_entry + 1) >= st->entries) ? 0 : current_entry + 1;
  1143. st->last_updated.tv_sec = (time_t) (last_ut / USEC_PER_SEC);
  1144. st->last_updated.tv_usec = 0;
  1145. last_stored_ut = next_store_ut;
  1146. }
  1147. /*
  1148. st->counter = counter;
  1149. st->current_entry = current_entry;
  1150. if(likely(last_ut)) {
  1151. st->last_updated.tv_sec = (time_t) (last_ut / USEC_PER_SEC);
  1152. st->last_updated.tv_usec = 0;
  1153. }
  1154. */
  1155. return stored_entries;
  1156. }
  1157. void rrdset_done(RRDSET *st) {
  1158. struct timeval now;
  1159. now_realtime_timeval(&now);
  1160. rrdset_timed_done(st, now, /* pending_rrdset_next = */ st->counter_done != 0);
  1161. }
  1162. void rrdset_timed_done(RRDSET *st, struct timeval now, bool pending_rrdset_next) {
  1163. if(unlikely(!service_running(SERVICE_COLLECTORS))) return;
  1164. netdata_spinlock_lock(&st->data_collection_lock);
  1165. if (pending_rrdset_next)
  1166. rrdset_timed_next(st, now, 0ULL);
  1167. debug(D_RRD_CALLS, "rrdset_done() for chart '%s'", rrdset_name(st));
  1168. RRDDIM *rd;
  1169. char
  1170. store_this_entry = 1, // boolean: 1 = store this entry, 0 = don't store this entry
  1171. first_entry = 0; // boolean: 1 = this is the first entry seen for this chart, 0 = all other entries
  1172. usec_t
  1173. last_collect_ut = 0, // the timestamp in microseconds, of the last collected value
  1174. now_collect_ut = 0, // the timestamp in microseconds, of this collected value (this is NOW)
  1175. last_stored_ut = 0, // the timestamp in microseconds, of the last stored entry in the db
  1176. next_store_ut = 0, // the timestamp in microseconds, of the next entry to store in the db
  1177. update_every_ut = st->update_every * USEC_PER_SEC; // st->update_every in microseconds
  1178. RRDSET_FLAGS rrdset_flags = rrdset_flag_check(st, ~0);
  1179. if(unlikely(rrdset_flags & RRDSET_FLAG_COLLECTION_FINISHED))
  1180. return;
  1181. netdata_thread_disable_cancelability();
  1182. if (unlikely(rrdset_flags & RRDSET_FLAG_OBSOLETE)) {
  1183. error("Chart '%s' has the OBSOLETE flag set, but it is collected.", rrdset_id(st));
  1184. rrdset_isnot_obsolete(st);
  1185. }
  1186. // check if the chart has a long time to be updated
  1187. if(unlikely(st->usec_since_last_update > st->entries * update_every_ut &&
  1188. st->rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE && st->rrd_memory_mode != RRD_MEMORY_MODE_NONE)) {
  1189. info("host '%s', chart '%s': took too long to be updated (counter #%zu, update #%zu, %0.3" NETDATA_DOUBLE_MODIFIER
  1190. " secs). Resetting it.", rrdhost_hostname(st->rrdhost), rrdset_id(st), st->counter, st->counter_done, (NETDATA_DOUBLE)st->usec_since_last_update / USEC_PER_SEC);
  1191. rrdset_reset(st);
  1192. st->usec_since_last_update = update_every_ut;
  1193. store_this_entry = 0;
  1194. first_entry = 1;
  1195. }
  1196. rrdset_debug(st, "microseconds since last update: %llu", st->usec_since_last_update);
  1197. // set last_collected_time
  1198. if(unlikely(!st->last_collected_time.tv_sec)) {
  1199. // it is the first entry
  1200. // set the last_collected_time to now
  1201. last_collect_ut = rrdset_init_last_collected_time(st, now) - update_every_ut;
  1202. // the first entry should not be stored
  1203. store_this_entry = 0;
  1204. first_entry = 1;
  1205. }
  1206. else {
  1207. // it is not the first entry
  1208. // calculate the proper last_collected_time, using usec_since_last_update
  1209. last_collect_ut = rrdset_update_last_collected_time(st);
  1210. }
  1211. if (unlikely(st->rrd_memory_mode == RRD_MEMORY_MODE_NONE)) {
  1212. goto after_first_database_work;
  1213. }
  1214. // if this set has not been updated in the past
  1215. // we fake the last_update time to be = now - usec_since_last_update
  1216. if(unlikely(!st->last_updated.tv_sec)) {
  1217. // it has never been updated before
  1218. // set a fake last_updated, in the past using usec_since_last_update
  1219. rrdset_init_last_updated_time(st);
  1220. // the first entry should not be stored
  1221. store_this_entry = 0;
  1222. first_entry = 1;
  1223. }
  1224. // check if we will re-write the entire data set
  1225. if(unlikely(dt_usec(&st->last_collected_time, &st->last_updated) > st->entries * update_every_ut &&
  1226. st->rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)) {
  1227. info(
  1228. "'%s': too old data (last updated at %"PRId64".%"PRId64", last collected at %"PRId64".%"PRId64"). "
  1229. "Resetting it. Will not store the next entry.",
  1230. rrdset_id(st),
  1231. (int64_t)st->last_updated.tv_sec,
  1232. (int64_t)st->last_updated.tv_usec,
  1233. (int64_t)st->last_collected_time.tv_sec,
  1234. (int64_t)st->last_collected_time.tv_usec);
  1235. rrdset_reset(st);
  1236. rrdset_init_last_updated_time(st);
  1237. st->usec_since_last_update = update_every_ut;
  1238. // the first entry should not be stored
  1239. store_this_entry = 0;
  1240. first_entry = 1;
  1241. }
  1242. // these are the 3 variables that will help us in interpolation
  1243. // last_stored_ut = the last time we added a value to the storage
  1244. // now_collect_ut = the time the current value has been collected
  1245. // next_store_ut = the time of the next interpolation point
  1246. now_collect_ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec;
  1247. last_stored_ut = st->last_updated.tv_sec * USEC_PER_SEC + st->last_updated.tv_usec;
  1248. next_store_ut = (st->last_updated.tv_sec + st->update_every) * USEC_PER_SEC;
  1249. if(unlikely(!st->counter_done)) {
  1250. // set a fake last_updated to jump to current time
  1251. rrdset_init_last_updated_time(st);
  1252. last_stored_ut = st->last_updated.tv_sec * USEC_PER_SEC + st->last_updated.tv_usec;
  1253. next_store_ut = (st->last_updated.tv_sec + st->update_every) * USEC_PER_SEC;
  1254. if(unlikely(rrdset_flags & RRDSET_FLAG_STORE_FIRST)) {
  1255. store_this_entry = 1;
  1256. last_collect_ut = next_store_ut - update_every_ut;
  1257. rrdset_debug(st, "Fixed first entry.");
  1258. }
  1259. else {
  1260. store_this_entry = 0;
  1261. rrdset_debug(st, "Will not store the next entry.");
  1262. }
  1263. }
  1264. after_first_database_work:
  1265. st->counter_done++;
  1266. if(unlikely(rrdhost_has_rrdpush_sender_enabled(st->rrdhost)))
  1267. rrdset_done_push(st);
  1268. uint32_t has_reset_value = 0;
  1269. size_t rda_slots = dictionary_entries(st->rrddim_root_index);
  1270. struct rda_item *rda_base = rrdset_thread_rda_get(&rda_slots);
  1271. size_t dim_id;
  1272. size_t dimensions = 0;
  1273. struct rda_item *rda = rda_base;
  1274. total_number collected_total = 0;
  1275. total_number last_collected_total = 0;
  1276. rrddim_foreach_read(rd, st) {
  1277. if(rd_dfe.counter >= rda_slots)
  1278. break;
  1279. rda = &rda_base[dimensions++];
  1280. if(rrddim_flag_check(rd, RRDDIM_FLAG_ARCHIVED)) {
  1281. rda->item = NULL;
  1282. rda->rd = NULL;
  1283. continue;
  1284. }
  1285. // store the dimension in the array
  1286. rda->item = dictionary_acquired_item_dup(st->rrddim_root_index, rd_dfe.item);
  1287. rda->rd = dictionary_acquired_item_value(rda->item);
  1288. // calculate totals
  1289. if(likely(rd->updated)) {
  1290. // if the new is smaller than the old (an overflow, or reset), set the old equal to the new
  1291. // to reset the calculation (it will give zero as the calculation for this second)
  1292. if(unlikely(rd->algorithm == RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL && rd->last_collected_value > rd->collected_value)) {
  1293. debug(D_RRD_STATS, "'%s' / '%s': RESET or OVERFLOW. Last collected value = " COLLECTED_NUMBER_FORMAT ", current = " COLLECTED_NUMBER_FORMAT
  1294. , rrdset_id(st)
  1295. , rrddim_name(rd)
  1296. , rd->last_collected_value
  1297. , rd->collected_value
  1298. );
  1299. if(!(rrddim_option_check(rd, RRDDIM_OPTION_DONT_DETECT_RESETS_OR_OVERFLOWS)))
  1300. has_reset_value = 1;
  1301. rd->last_collected_value = rd->collected_value;
  1302. }
  1303. last_collected_total += rd->last_collected_value;
  1304. collected_total += rd->collected_value;
  1305. if(unlikely(rrddim_flag_check(rd, RRDDIM_FLAG_OBSOLETE))) {
  1306. error("Dimension %s in chart '%s' has the OBSOLETE flag set, but it is collected.", rrddim_name(rd), rrdset_id(st));
  1307. rrddim_isnot_obsolete(st, rd);
  1308. }
  1309. }
  1310. }
  1311. rrddim_foreach_done(rd);
  1312. rda_slots = dimensions;
  1313. if (unlikely(st->rrd_memory_mode == RRD_MEMORY_MODE_NONE))
  1314. goto after_second_database_work;
  1315. rrdset_debug(st, "last_collect_ut = %0.3" NETDATA_DOUBLE_MODIFIER " (last collection time)", (NETDATA_DOUBLE)last_collect_ut/USEC_PER_SEC);
  1316. rrdset_debug(st, "now_collect_ut = %0.3" NETDATA_DOUBLE_MODIFIER " (current collection time)", (NETDATA_DOUBLE)now_collect_ut/USEC_PER_SEC);
  1317. rrdset_debug(st, "last_stored_ut = %0.3" NETDATA_DOUBLE_MODIFIER " (last updated time)", (NETDATA_DOUBLE)last_stored_ut/USEC_PER_SEC);
  1318. rrdset_debug(st, "next_store_ut = %0.3" NETDATA_DOUBLE_MODIFIER " (next interpolation point)", (NETDATA_DOUBLE)next_store_ut/USEC_PER_SEC);
  1319. // process all dimensions to calculate their values
  1320. // based on the collected figures only
  1321. // at this stage we do not interpolate anything
  1322. for(dim_id = 0, rda = rda_base ; dim_id < rda_slots ; ++dim_id, ++rda) {
  1323. rd = rda->rd;
  1324. if(unlikely(!rd)) continue;
  1325. if(unlikely(!rd->updated)) {
  1326. rd->calculated_value = 0;
  1327. continue;
  1328. }
  1329. rrdset_debug(st, "%s: START "
  1330. " last_collected_value = " COLLECTED_NUMBER_FORMAT
  1331. " collected_value = " COLLECTED_NUMBER_FORMAT
  1332. " last_calculated_value = " NETDATA_DOUBLE_FORMAT
  1333. " calculated_value = " NETDATA_DOUBLE_FORMAT
  1334. , rrddim_name(rd)
  1335. , rd->last_collected_value
  1336. , rd->collected_value
  1337. , rd->last_calculated_value
  1338. , rd->calculated_value
  1339. );
  1340. switch(rd->algorithm) {
  1341. case RRD_ALGORITHM_ABSOLUTE:
  1342. rd->calculated_value = (NETDATA_DOUBLE)rd->collected_value
  1343. * (NETDATA_DOUBLE)rd->multiplier
  1344. / (NETDATA_DOUBLE)rd->divisor;
  1345. rrdset_debug(st, "%s: CALC ABS/ABS-NO-IN " NETDATA_DOUBLE_FORMAT " = "
  1346. COLLECTED_NUMBER_FORMAT
  1347. " * " NETDATA_DOUBLE_FORMAT
  1348. " / " NETDATA_DOUBLE_FORMAT
  1349. , rrddim_name(rd)
  1350. , rd->calculated_value
  1351. , rd->collected_value
  1352. , (NETDATA_DOUBLE)rd->multiplier
  1353. , (NETDATA_DOUBLE)rd->divisor
  1354. );
  1355. break;
  1356. case RRD_ALGORITHM_PCENT_OVER_ROW_TOTAL:
  1357. if(unlikely(!collected_total))
  1358. rd->calculated_value = 0;
  1359. else
  1360. // the percentage of the current value
  1361. // over the total of all dimensions
  1362. rd->calculated_value =
  1363. (NETDATA_DOUBLE)100
  1364. * (NETDATA_DOUBLE)rd->collected_value
  1365. / (NETDATA_DOUBLE)collected_total;
  1366. rrdset_debug(st, "%s: CALC PCENT-ROW " NETDATA_DOUBLE_FORMAT " = 100"
  1367. " * " COLLECTED_NUMBER_FORMAT
  1368. " / " COLLECTED_NUMBER_FORMAT
  1369. , rrddim_name(rd)
  1370. , rd->calculated_value
  1371. , rd->collected_value
  1372. , collected_total
  1373. );
  1374. break;
  1375. case RRD_ALGORITHM_INCREMENTAL:
  1376. if(unlikely(rd->collections_counter <= 1)) {
  1377. rd->calculated_value = 0;
  1378. continue;
  1379. }
  1380. // If the new is smaller than the old (an overflow, or reset), set the old equal to the new
  1381. // to reset the calculation (it will give zero as the calculation for this second).
  1382. // It is imperative to set the comparison to uint64_t since type collected_number is signed and
  1383. // produces wrong results as far as incremental counters are concerned.
  1384. if(unlikely((uint64_t)rd->last_collected_value > (uint64_t)rd->collected_value)) {
  1385. debug(D_RRD_STATS, "'%s' / '%s': RESET or OVERFLOW. Last collected value = " COLLECTED_NUMBER_FORMAT ", current = " COLLECTED_NUMBER_FORMAT
  1386. , rrdset_id(st)
  1387. , rrddim_name(rd)
  1388. , rd->last_collected_value
  1389. , rd->collected_value);
  1390. if(!(rrddim_option_check(rd, RRDDIM_OPTION_DONT_DETECT_RESETS_OR_OVERFLOWS)))
  1391. has_reset_value = 1;
  1392. uint64_t last = (uint64_t)rd->last_collected_value;
  1393. uint64_t new = (uint64_t)rd->collected_value;
  1394. uint64_t max = (uint64_t)rd->collected_value_max;
  1395. uint64_t cap = 0;
  1396. // Signed values are handled by exploiting two's complement which will produce positive deltas
  1397. if (max > 0x00000000FFFFFFFFULL)
  1398. cap = 0xFFFFFFFFFFFFFFFFULL; // handles signed and unsigned 64-bit counters
  1399. else
  1400. cap = 0x00000000FFFFFFFFULL; // handles signed and unsigned 32-bit counters
  1401. uint64_t delta = cap - last + new;
  1402. uint64_t max_acceptable_rate = (cap / 100) * MAX_INCREMENTAL_PERCENT_RATE;
  1403. // If the delta is less than the maximum acceptable rate and the previous value was near the cap
  1404. // then this is an overflow. There can be false positives such that a reset is detected as an
  1405. // overflow.
  1406. // TODO: remember recent history of rates and compare with current rate to reduce this chance.
  1407. if (delta < max_acceptable_rate) {
  1408. rd->calculated_value +=
  1409. (NETDATA_DOUBLE) delta
  1410. * (NETDATA_DOUBLE) rd->multiplier
  1411. / (NETDATA_DOUBLE) rd->divisor;
  1412. } else {
  1413. // This is a reset. Any overflow with a rate greater than MAX_INCREMENTAL_PERCENT_RATE will also
  1414. // be detected as a reset instead.
  1415. rd->calculated_value += (NETDATA_DOUBLE)0;
  1416. }
  1417. }
  1418. else {
  1419. rd->calculated_value +=
  1420. (NETDATA_DOUBLE) (rd->collected_value - rd->last_collected_value)
  1421. * (NETDATA_DOUBLE) rd->multiplier
  1422. / (NETDATA_DOUBLE) rd->divisor;
  1423. }
  1424. rrdset_debug(st, "%s: CALC INC PRE " NETDATA_DOUBLE_FORMAT " = ("
  1425. COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT
  1426. ")"
  1427. " * " NETDATA_DOUBLE_FORMAT
  1428. " / " NETDATA_DOUBLE_FORMAT
  1429. , rrddim_name(rd)
  1430. , rd->calculated_value
  1431. , rd->collected_value, rd->last_collected_value
  1432. , (NETDATA_DOUBLE)rd->multiplier
  1433. , (NETDATA_DOUBLE)rd->divisor
  1434. );
  1435. break;
  1436. case RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL:
  1437. if(unlikely(rd->collections_counter <= 1)) {
  1438. rd->calculated_value = 0;
  1439. continue;
  1440. }
  1441. // the percentage of the current increment
  1442. // over the increment of all dimensions together
  1443. if(unlikely(collected_total == last_collected_total))
  1444. rd->calculated_value = 0;
  1445. else
  1446. rd->calculated_value =
  1447. (NETDATA_DOUBLE)100
  1448. * (NETDATA_DOUBLE)(rd->collected_value - rd->last_collected_value)
  1449. / (NETDATA_DOUBLE)(collected_total - last_collected_total);
  1450. rrdset_debug(st, "%s: CALC PCENT-DIFF " NETDATA_DOUBLE_FORMAT " = 100"
  1451. " * (" COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT ")"
  1452. " / (" COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT ")"
  1453. , rrddim_name(rd)
  1454. , rd->calculated_value
  1455. , rd->collected_value, rd->last_collected_value
  1456. , collected_total, last_collected_total
  1457. );
  1458. break;
  1459. default:
  1460. // make the default zero, to make sure
  1461. // it gets noticed when we add new types
  1462. rd->calculated_value = 0;
  1463. rrdset_debug(st, "%s: CALC " NETDATA_DOUBLE_FORMAT " = 0"
  1464. , rrddim_name(rd)
  1465. , rd->calculated_value
  1466. );
  1467. break;
  1468. }
  1469. rrdset_debug(st, "%s: PHASE2 "
  1470. " last_collected_value = " COLLECTED_NUMBER_FORMAT
  1471. " collected_value = " COLLECTED_NUMBER_FORMAT
  1472. " last_calculated_value = " NETDATA_DOUBLE_FORMAT
  1473. " calculated_value = " NETDATA_DOUBLE_FORMAT
  1474. , rrddim_name(rd)
  1475. , rd->last_collected_value
  1476. , rd->collected_value
  1477. , rd->last_calculated_value
  1478. , rd->calculated_value
  1479. );
  1480. }
  1481. // at this point we have all the calculated values ready
  1482. // it is now time to interpolate values on a second boundary
  1483. // #ifdef NETDATA_INTERNAL_CHECKS
  1484. // if(unlikely(now_collect_ut < next_store_ut && st->counter_done > 1)) {
  1485. // // this is collected in the same interpolation point
  1486. // rrdset_debug(st, "THIS IS IN THE SAME INTERPOLATION POINT");
  1487. // info("INTERNAL CHECK: host '%s', chart '%s' collection %zu is in the same interpolation point: short by %llu microseconds", st->rrdhost->hostname, rrdset_name(st), st->counter_done, next_store_ut - now_collect_ut);
  1488. // }
  1489. // #endif
  1490. rrdset_done_interpolate(
  1491. st
  1492. , rda_base
  1493. , rda_slots
  1494. , update_every_ut
  1495. , last_stored_ut
  1496. , next_store_ut
  1497. , last_collect_ut
  1498. , now_collect_ut
  1499. , store_this_entry
  1500. , has_reset_value
  1501. );
  1502. after_second_database_work:
  1503. for(dim_id = 0, rda = rda_base ; dim_id < rda_slots ; ++dim_id, ++rda) {
  1504. rd = rda->rd;
  1505. if(unlikely(!rd)) continue;
  1506. if(unlikely(!rd->updated))
  1507. continue;
  1508. rrdset_debug(st, "%s: setting last_collected_value (old: " COLLECTED_NUMBER_FORMAT ") to last_collected_value (new: " COLLECTED_NUMBER_FORMAT ")", rrddim_name(rd), rd->last_collected_value, rd->collected_value);
  1509. rd->last_collected_value = rd->collected_value;
  1510. switch(rd->algorithm) {
  1511. case RRD_ALGORITHM_INCREMENTAL:
  1512. if(unlikely(!first_entry)) {
  1513. rrdset_debug(st, "%s: setting last_calculated_value (old: " NETDATA_DOUBLE_FORMAT ") to "
  1514. "last_calculated_value (new: " NETDATA_DOUBLE_FORMAT ")"
  1515. , rrddim_name(rd)
  1516. , rd->last_calculated_value + rd->calculated_value
  1517. , rd->calculated_value);
  1518. rd->last_calculated_value += rd->calculated_value;
  1519. }
  1520. else {
  1521. rrdset_debug(st, "THIS IS THE FIRST POINT");
  1522. }
  1523. break;
  1524. case RRD_ALGORITHM_ABSOLUTE:
  1525. case RRD_ALGORITHM_PCENT_OVER_ROW_TOTAL:
  1526. case RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL:
  1527. rrdset_debug(st, "%s: setting last_calculated_value (old: " NETDATA_DOUBLE_FORMAT ") to "
  1528. "last_calculated_value (new: " NETDATA_DOUBLE_FORMAT ")"
  1529. , rrddim_name(rd)
  1530. , rd->last_calculated_value
  1531. , rd->calculated_value);
  1532. rd->last_calculated_value = rd->calculated_value;
  1533. break;
  1534. }
  1535. rd->calculated_value = 0;
  1536. rd->collected_value = 0;
  1537. rd->updated = 0;
  1538. rrdset_debug(st, "%s: END "
  1539. " last_collected_value = " COLLECTED_NUMBER_FORMAT
  1540. " collected_value = " COLLECTED_NUMBER_FORMAT
  1541. " last_calculated_value = " NETDATA_DOUBLE_FORMAT
  1542. " calculated_value = " NETDATA_DOUBLE_FORMAT
  1543. , rrddim_name(rd)
  1544. , rd->last_collected_value
  1545. , rd->collected_value
  1546. , rd->last_calculated_value
  1547. , rd->calculated_value
  1548. );
  1549. }
  1550. netdata_spinlock_unlock(&st->data_collection_lock);
  1551. // ALL DONE ABOUT THE DATA UPDATE
  1552. // --------------------------------------------------------------------
  1553. if(unlikely(st->rrd_memory_mode == RRD_MEMORY_MODE_MAP)) {
  1554. // update the memory mapped files with the latest values
  1555. rrdset_memory_file_update(st);
  1556. for(dim_id = 0, rda = rda_base; dim_id < rda_slots ; ++dim_id, ++rda) {
  1557. rd = rda->rd;
  1558. if(unlikely(!rd)) continue;
  1559. rrddim_memory_file_update(rd);
  1560. }
  1561. }
  1562. for(dim_id = 0, rda = rda_base; dim_id < rda_slots ; ++dim_id, ++rda) {
  1563. rd = rda->rd;
  1564. if(unlikely(!rd)) continue;
  1565. dictionary_acquired_item_release(st->rrddim_root_index, rda->item);
  1566. rda->item = NULL;
  1567. rda->rd = NULL;
  1568. }
  1569. rrdcontext_collected_rrdset(st);
  1570. netdata_thread_enable_cancelability();
  1571. store_metric_collection_completed();
  1572. }
  1573. time_t rrdset_set_update_every_s(RRDSET *st, time_t update_every_s) {
  1574. internal_error(true, "RRDSET '%s' switching update every from %d to %d",
  1575. rrdset_id(st), (int)st->update_every, (int)update_every_s);
  1576. time_t prev_update_every_s = st->update_every;
  1577. st->update_every = update_every_s;
  1578. // switch update every to the storage engine
  1579. RRDDIM *rd;
  1580. rrddim_foreach_read(rd, st) {
  1581. for (size_t tier = 0; tier < storage_tiers; tier++) {
  1582. if (rd->tiers[tier].db_collection_handle)
  1583. rd->tiers[tier].collect_ops->change_collection_frequency(rd->tiers[tier].db_collection_handle, (int)(st->rrdhost->db[tier].tier_grouping * st->update_every));
  1584. }
  1585. assert(rd->update_every == prev_update_every_s &&
  1586. "chart's update every differs from the update every of its dimensions");
  1587. rd->update_every = st->update_every;
  1588. }
  1589. rrddim_foreach_done(rd);
  1590. return prev_update_every_s;
  1591. }
  1592. // ----------------------------------------------------------------------------
  1593. // compatibility layer for RRDSET files v019
  1594. #define RRDSET_MAGIC_V019 "NETDATA RRD SET FILE V019"
  1595. #define RRD_ID_LENGTH_MAX_V019 200
  1596. struct avl_element_v019 {
  1597. void *avl_link[2];
  1598. signed char avl_balance;
  1599. };
  1600. struct avl_tree_type_v019 {
  1601. void *root;
  1602. int (*compar)(void *a, void *b);
  1603. };
  1604. struct avl_tree_lock_v019 {
  1605. struct avl_tree_type_v019 avl_tree;
  1606. pthread_rwlock_t rwlock;
  1607. };
  1608. struct rrdset_map_save_v019 {
  1609. struct avl_element_v019 avl; // ignored
  1610. struct avl_element_v019 avlname; // ignored
  1611. char id[RRD_ID_LENGTH_MAX_V019 + 1]; // check to reset all - update on load
  1612. void *name; // ignored
  1613. void *unused_ptr; // ignored
  1614. void *type; // ignored
  1615. void *family; // ignored
  1616. void *title; // ignored
  1617. void *units; // ignored
  1618. void *context; // ignored
  1619. uint32_t hash_context; // ignored
  1620. uint32_t chart_type; // ignored
  1621. int update_every; // check to reset all - update on load
  1622. long entries; // check to reset all - update on load
  1623. long current_entry; // NEEDS TO BE UPDATED - FIXED ON LOAD
  1624. uint32_t flags; // ignored
  1625. void *exporting_flags; // ignored
  1626. int gap_when_lost_iterations_above; // ignored
  1627. long priority; // ignored
  1628. uint32_t rrd_memory_mode; // ignored
  1629. void *cache_dir; // ignored
  1630. char cache_filename[FILENAME_MAX+1]; // ignored - update on load
  1631. pthread_rwlock_t rrdset_rwlock; // ignored
  1632. size_t counter; // NEEDS TO BE UPDATED - maintained on load
  1633. size_t counter_done; // ignored
  1634. union { //
  1635. time_t last_accessed_time_s; // ignored
  1636. time_t last_entry_s; // ignored
  1637. }; //
  1638. time_t upstream_resync_time; // ignored
  1639. void *plugin_name; // ignored
  1640. void *module_name; // ignored
  1641. void *chart_uuid; // ignored
  1642. void *state; // ignored
  1643. size_t unused[3]; // ignored
  1644. size_t rrddim_page_alignment; // ignored
  1645. uint32_t hash; // ignored
  1646. uint32_t hash_name; // ignored
  1647. usec_t usec_since_last_update; // NEEDS TO BE UPDATED - maintained on load
  1648. struct timeval last_updated; // NEEDS TO BE UPDATED - check to reset all - fixed on load
  1649. struct timeval last_collected_time; // ignored
  1650. long long collected_total; // ignored
  1651. long long last_collected_total; // ignored
  1652. void *rrdfamily; // ignored
  1653. void *rrdhost; // ignored
  1654. void *next; // ignored
  1655. long double green; // ignored
  1656. long double red; // ignored
  1657. struct avl_tree_lock_v019 rrdvar_root_index; // ignored
  1658. void *variables; // ignored
  1659. void *alarms; // ignored
  1660. unsigned long memsize; // check to reset all - update on load
  1661. char magic[sizeof(RRDSET_MAGIC_V019) + 1]; // check to reset all - update on load
  1662. struct avl_tree_lock_v019 dimensions_index; // ignored
  1663. void *dimensions; // ignored
  1664. };
  1665. void rrdset_memory_file_update(RRDSET *st) {
  1666. if(!st->st_on_file) return;
  1667. struct rrdset_map_save_v019 *st_on_file = st->st_on_file;
  1668. st_on_file->current_entry = st->current_entry;
  1669. st_on_file->counter = st->counter;
  1670. st_on_file->usec_since_last_update = st->usec_since_last_update;
  1671. st_on_file->last_updated.tv_sec = st->last_updated.tv_sec;
  1672. st_on_file->last_updated.tv_usec = st->last_updated.tv_usec;
  1673. }
  1674. const char *rrdset_cache_filename(RRDSET *st) {
  1675. if(!st->st_on_file) return NULL;
  1676. struct rrdset_map_save_v019 *st_on_file = st->st_on_file;
  1677. return st_on_file->cache_filename;
  1678. }
  1679. const char *rrdset_cache_dir(RRDSET *st) {
  1680. if(!st->cache_dir)
  1681. st->cache_dir = rrdhost_cache_dir_for_rrdset_alloc(st->rrdhost, rrdset_id(st));
  1682. return st->cache_dir;
  1683. }
  1684. void rrdset_memory_file_free(RRDSET *st) {
  1685. if(!st->st_on_file) return;
  1686. // needed for memory mode map, to save the latest state
  1687. rrdset_memory_file_update(st);
  1688. struct rrdset_map_save_v019 *st_on_file = st->st_on_file;
  1689. __atomic_sub_fetch(&rrddim_db_memory_size, st_on_file->memsize, __ATOMIC_RELAXED);
  1690. netdata_munmap(st_on_file, st_on_file->memsize);
  1691. // remove the pointers from the RRDDIM
  1692. st->st_on_file = NULL;
  1693. }
  1694. void rrdset_memory_file_save(RRDSET *st) {
  1695. if(!st->st_on_file) return;
  1696. rrdset_memory_file_update(st);
  1697. struct rrdset_map_save_v019 *st_on_file = st->st_on_file;
  1698. if(st_on_file->rrd_memory_mode != RRD_MEMORY_MODE_SAVE) return;
  1699. memory_file_save(st_on_file->cache_filename, st->st_on_file, st_on_file->memsize);
  1700. }
  1701. bool rrdset_memory_load_or_create_map_save(RRDSET *st, RRD_MEMORY_MODE memory_mode) {
  1702. if(memory_mode != RRD_MEMORY_MODE_SAVE && memory_mode != RRD_MEMORY_MODE_MAP)
  1703. return false;
  1704. char fullfilename[FILENAME_MAX + 1];
  1705. snprintfz(fullfilename, FILENAME_MAX, "%s/main.db", rrdset_cache_dir(st));
  1706. unsigned long size = sizeof(struct rrdset_map_save_v019);
  1707. struct rrdset_map_save_v019 *st_on_file = (struct rrdset_map_save_v019 *)netdata_mmap(
  1708. fullfilename, size, ((memory_mode == RRD_MEMORY_MODE_MAP) ? MAP_SHARED : MAP_PRIVATE), 0, false, NULL);
  1709. if(!st_on_file) return false;
  1710. time_t now_s = now_realtime_sec();
  1711. st_on_file->magic[sizeof(RRDSET_MAGIC_V019)] = '\0';
  1712. if(strcmp(st_on_file->magic, RRDSET_MAGIC_V019) != 0) {
  1713. info("Initializing file '%s'.", fullfilename);
  1714. memset(st_on_file, 0, size);
  1715. }
  1716. else if(strncmp(st_on_file->id, rrdset_id(st), RRD_ID_LENGTH_MAX_V019) != 0) {
  1717. error("File '%s' contents are not for chart '%s'. Clearing it.", fullfilename, rrdset_id(st));
  1718. memset(st_on_file, 0, size);
  1719. }
  1720. else if(st_on_file->memsize != size || st_on_file->entries != st->entries) {
  1721. error("File '%s' does not have the desired size. Clearing it.", fullfilename);
  1722. memset(st_on_file, 0, size);
  1723. }
  1724. else if(st_on_file->update_every != st->update_every) {
  1725. error("File '%s' does not have the desired granularity. Clearing it.", fullfilename);
  1726. memset(st_on_file, 0, size);
  1727. }
  1728. else if((now_s - st_on_file->last_updated.tv_sec) > st->update_every * st->entries) {
  1729. info("File '%s' is too old. Clearing it.", fullfilename);
  1730. memset(st_on_file, 0, size);
  1731. }
  1732. else if(st_on_file->last_updated.tv_sec > now_s + st->update_every) {
  1733. error("File '%s' refers to the future by %zd secs. Resetting it to now.", fullfilename, (ssize_t)(st_on_file->last_updated.tv_sec - now_s));
  1734. st_on_file->last_updated.tv_sec = now_s;
  1735. }
  1736. if(st_on_file->current_entry >= st_on_file->entries)
  1737. st_on_file->current_entry = 0;
  1738. // make sure the database is aligned
  1739. bool align_last_updated = false;
  1740. if(st_on_file->last_updated.tv_sec) {
  1741. st_on_file->update_every = st->update_every;
  1742. align_last_updated = true;
  1743. }
  1744. // copy the useful values to st
  1745. st->current_entry = st_on_file->current_entry;
  1746. st->counter = st_on_file->counter;
  1747. st->usec_since_last_update = st_on_file->usec_since_last_update;
  1748. st->last_updated.tv_sec = st_on_file->last_updated.tv_sec;
  1749. st->last_updated.tv_usec = st_on_file->last_updated.tv_usec;
  1750. // link it to st
  1751. st->st_on_file = st_on_file;
  1752. // clear everything
  1753. memset(st_on_file, 0, size);
  1754. // set the values we need
  1755. strncpyz(st_on_file->id, rrdset_id(st), RRD_ID_LENGTH_MAX_V019 + 1);
  1756. strcpy(st_on_file->cache_filename, fullfilename);
  1757. strcpy(st_on_file->magic, RRDSET_MAGIC_V019);
  1758. st_on_file->memsize = size;
  1759. st_on_file->entries = st->entries;
  1760. st_on_file->update_every = st->update_every;
  1761. st_on_file->rrd_memory_mode = memory_mode;
  1762. if(align_last_updated)
  1763. last_updated_time_align(st);
  1764. // copy the useful values back to st_on_file
  1765. rrdset_memory_file_update(st);
  1766. __atomic_add_fetch(&rrddim_db_memory_size, st_on_file->memsize, __ATOMIC_RELAXED);
  1767. return true;
  1768. }