rrdset.c 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205
  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] = storage_engine_metrics_group_get(eng->backend, 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 pluginsd_rrdset_cleanup(RRDSET *st);
  147. void rrdset_finalize_collection(RRDSET *st, bool dimensions_too) {
  148. RRDHOST *host = st->rrdhost;
  149. rrdset_flag_set(st, RRDSET_FLAG_COLLECTION_FINISHED);
  150. if(dimensions_too) {
  151. RRDDIM *rd;
  152. rrddim_foreach_read(rd, st)
  153. rrddim_finalize_collection_and_check_retention(rd);
  154. rrddim_foreach_done(rd);
  155. }
  156. for(size_t tier = 0; tier < storage_tiers ; tier++) {
  157. STORAGE_ENGINE *eng = st->rrdhost->db[tier].eng;
  158. if(!eng) continue;
  159. if(st->storage_metrics_groups[tier]) {
  160. storage_engine_metrics_group_release(eng->backend, host->db[tier].instance, st->storage_metrics_groups[tier]);
  161. st->storage_metrics_groups[tier] = NULL;
  162. }
  163. }
  164. pluginsd_rrdset_cleanup(st);
  165. }
  166. // the destructor - the dictionary is write locked while this runs
  167. static void rrdset_delete_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rrdset, void *rrdhost) {
  168. RRDHOST *host = rrdhost;
  169. RRDSET *st = rrdset;
  170. rrdset_flag_clear(st, RRDSET_FLAG_INDEXED_ID);
  171. rrdset_finalize_collection(st, false);
  172. // remove it from the name index
  173. rrdset_index_del_name(host, st);
  174. // release the collector info
  175. dictionary_destroy(st->functions_view);
  176. rrdcalc_unlink_all_rrdset_alerts(st);
  177. // ------------------------------------------------------------------------
  178. // the order of destruction is important here
  179. // 1. delete RRDDIMVAR index - this will speed up the destruction of RRDDIMs
  180. // because each dimension loops to find its own variables in this index.
  181. // There are no references to the items on this index from the dimensions.
  182. // To find their own, they have to walk-through the dictionary.
  183. rrddimvar_index_destroy(st); // destroy the rrddimvar index
  184. // 2. delete RRDSETVAR index
  185. rrdsetvar_index_destroy(st); // destroy the rrdsetvar index
  186. // 3. delete RRDVAR index after the above, to avoid triggering its garbage collector (they have references on this)
  187. rrdvariables_destroy(st->rrdvars); // free all variables and destroy the rrdvar dictionary
  188. // 4. delete RRDFAMILY - this has to be last, because RRDDIMVAR and RRDSETVAR need the reference counter
  189. rrdfamily_release(host, st->rrdfamily); // release the acquired rrdfamily -- has to be after all variables
  190. // 5. delete RRDDIMs, now their variables are not existing, so this is fast
  191. rrddim_index_destroy(st); // free all the dimensions and destroy the dimensions index
  192. // 6. this has to be after the dimensions are freed, but before labels are freed (contexts need the labels)
  193. rrdcontext_removed_rrdset(st); // let contexts know
  194. // 7. destroy the chart labels
  195. rrdlabels_destroy(st->rrdlabels); // destroy the labels, after letting the contexts know
  196. // 8. destroy the ml handle
  197. ml_chart_delete(st);
  198. rrdset_memory_file_free(st); // remove files of db mode save and map
  199. // ------------------------------------------------------------------------
  200. // free it
  201. netdata_rwlock_destroy(&st->alerts.rwlock);
  202. string_freez(st->id);
  203. string_freez(st->name);
  204. string_freez(st->parts.id);
  205. string_freez(st->parts.type);
  206. string_freez(st->parts.name);
  207. string_freez(st->family);
  208. string_freez(st->title);
  209. string_freez(st->units);
  210. string_freez(st->context);
  211. string_freez(st->plugin_name);
  212. string_freez(st->module_name);
  213. freez(st->exporting_flags);
  214. freez(st->cache_dir);
  215. }
  216. // the item to be inserted, is already in the dictionary
  217. // this callback deals with the situation, migrating the existing object to the new values
  218. // the dictionary is write locked while this runs
  219. static bool rrdset_conflict_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rrdset, void *new_rrdset, void *constructor_data) {
  220. (void)new_rrdset; // it is NULL
  221. struct rrdset_constructor *ctr = constructor_data;
  222. RRDSET *st = rrdset;
  223. rrdset_isnot_obsolete(st);
  224. ctr->react_action = RRDSET_REACT_NONE;
  225. if (rrdset_flag_check(st, RRDSET_FLAG_ARCHIVED)) {
  226. rrdset_flag_clear(st, RRDSET_FLAG_ARCHIVED);
  227. ctr->react_action |= RRDSET_REACT_CHART_ACTIVATED;
  228. }
  229. if (rrdset_reset_name(st, (ctr->name && *ctr->name) ? ctr->name : ctr->id) == 2)
  230. ctr->react_action |= RRDSET_REACT_UPDATED;
  231. if (unlikely(st->priority != ctr->priority)) {
  232. st->priority = ctr->priority;
  233. ctr->react_action |= RRDSET_REACT_UPDATED;
  234. }
  235. if (unlikely(st->update_every != ctr->update_every)) {
  236. rrdset_set_update_every_s(st, ctr->update_every);
  237. ctr->react_action |= RRDSET_REACT_UPDATED;
  238. }
  239. if(ctr->plugin && *ctr->plugin) {
  240. STRING *old_plugin = st->plugin_name;
  241. st->plugin_name = rrd_string_strdupz(ctr->plugin);
  242. if (old_plugin != st->plugin_name)
  243. ctr->react_action |= RRDSET_REACT_PLUGIN_UPDATED;
  244. string_freez(old_plugin);
  245. }
  246. if(ctr->module && *ctr->module) {
  247. STRING *old_module = st->module_name;
  248. st->module_name = rrd_string_strdupz(ctr->module);
  249. if (old_module != st->module_name)
  250. ctr->react_action |= RRDSET_REACT_MODULE_UPDATED;
  251. string_freez(old_module);
  252. }
  253. if(ctr->title && *ctr->title) {
  254. STRING *old_title = st->title;
  255. st->title = rrd_string_strdupz(ctr->title);
  256. if(old_title != st->title)
  257. ctr->react_action |= RRDSET_REACT_UPDATED;
  258. string_freez(old_title);
  259. }
  260. if(ctr->units && *ctr->units) {
  261. STRING *old_units = st->units;
  262. st->units = rrd_string_strdupz(ctr->units);
  263. if(old_units != st->units)
  264. ctr->react_action |= RRDSET_REACT_UPDATED;
  265. string_freez(old_units);
  266. }
  267. if(ctr->family && *ctr->family) {
  268. STRING *old_family = st->family;
  269. st->family = rrd_string_strdupz(ctr->family);
  270. if(old_family != st->family)
  271. ctr->react_action |= RRDSET_REACT_UPDATED;
  272. string_freez(old_family);
  273. // TODO - we should rename RRDFAMILY variables
  274. }
  275. if(ctr->context && *ctr->context) {
  276. STRING *old_context = st->context;
  277. st->context = rrd_string_strdupz(ctr->context);
  278. if(old_context != st->context)
  279. ctr->react_action |= RRDSET_REACT_UPDATED;
  280. string_freez(old_context);
  281. }
  282. if(st->chart_type != ctr->chart_type) {
  283. st->chart_type = ctr->chart_type;
  284. ctr->react_action |= RRDSET_REACT_UPDATED;
  285. }
  286. rrdset_update_permanent_labels(st);
  287. rrdset_flag_set(st, RRDSET_FLAG_SYNC_CLOCK);
  288. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  289. return ctr->react_action != RRDSET_REACT_NONE;
  290. }
  291. // this is called after all insertions/conflicts, with the dictionary unlocked, with a reference to RRDSET
  292. // so, any actions requiring locks on other objects, should be placed here
  293. static void rrdset_react_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rrdset, void *constructor_data) {
  294. struct rrdset_constructor *ctr = constructor_data;
  295. RRDSET *st = rrdset;
  296. RRDHOST *host = st->rrdhost;
  297. st->last_accessed_time_s = now_realtime_sec();
  298. if(host->health.health_enabled && (ctr->react_action & (RRDSET_REACT_NEW | RRDSET_REACT_CHART_ACTIVATED))) {
  299. rrdset_flag_set(st, RRDSET_FLAG_PENDING_HEALTH_INITIALIZATION);
  300. rrdhost_flag_set(st->rrdhost, RRDHOST_FLAG_PENDING_HEALTH_INITIALIZATION);
  301. }
  302. if(ctr->react_action & (RRDSET_REACT_NEW | RRDSET_REACT_PLUGIN_UPDATED | RRDSET_REACT_MODULE_UPDATED)) {
  303. if (ctr->react_action & RRDSET_REACT_NEW) {
  304. if(unlikely(rrdcontext_find_chart_uuid(st, &st->chart_uuid)))
  305. uuid_generate(st->chart_uuid);
  306. }
  307. rrdset_flag_set(st, RRDSET_FLAG_METADATA_UPDATE);
  308. rrdhost_flag_set(st->rrdhost, RRDHOST_FLAG_METADATA_UPDATE);
  309. }
  310. rrdcontext_updated_rrdset(st);
  311. }
  312. void rrdset_index_init(RRDHOST *host) {
  313. if(!host->rrdset_root_index) {
  314. host->rrdset_root_index = dictionary_create_advanced(DICT_OPTION_DONT_OVERWRITE_VALUE | DICT_OPTION_FIXED_SIZE,
  315. &dictionary_stats_category_rrdset_rrddim, sizeof(RRDSET));
  316. dictionary_register_insert_callback(host->rrdset_root_index, rrdset_insert_callback, NULL);
  317. dictionary_register_conflict_callback(host->rrdset_root_index, rrdset_conflict_callback, NULL);
  318. dictionary_register_react_callback(host->rrdset_root_index, rrdset_react_callback, NULL);
  319. dictionary_register_delete_callback(host->rrdset_root_index, rrdset_delete_callback, host);
  320. }
  321. if(!host->rrdset_root_index_name) {
  322. host->rrdset_root_index_name = dictionary_create_advanced(
  323. DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE | DICT_OPTION_DONT_OVERWRITE_VALUE,
  324. &dictionary_stats_category_rrdset_rrddim, 0);
  325. dictionary_register_insert_callback(host->rrdset_root_index_name, rrdset_name_insert_callback, host);
  326. dictionary_register_delete_callback(host->rrdset_root_index_name, rrdset_name_delete_callback, host);
  327. }
  328. }
  329. void rrdset_index_destroy(RRDHOST *host) {
  330. // destroy the name index first
  331. dictionary_destroy(host->rrdset_root_index_name);
  332. host->rrdset_root_index_name = NULL;
  333. // destroy the id index last
  334. dictionary_destroy(host->rrdset_root_index);
  335. host->rrdset_root_index = NULL;
  336. }
  337. static inline RRDSET *rrdset_index_add(RRDHOST *host, const char *id, struct rrdset_constructor *st_ctr) {
  338. return dictionary_set_advanced(host->rrdset_root_index, id, -1, NULL, sizeof(RRDSET), st_ctr);
  339. }
  340. static inline void rrdset_index_del(RRDHOST *host, RRDSET *st) {
  341. if(rrdset_flag_check(st, RRDSET_FLAG_INDEXED_ID))
  342. dictionary_del(host->rrdset_root_index, rrdset_id(st));
  343. }
  344. static RRDSET *rrdset_index_find(RRDHOST *host, const char *id) {
  345. // TODO - the name index should have an acquired dictionary item, not just a pointer to RRDSET
  346. if (unlikely(!host->rrdset_root_index))
  347. return NULL;
  348. return dictionary_get(host->rrdset_root_index, id);
  349. }
  350. // ----------------------------------------------------------------------------
  351. // RRDSET - find charts
  352. inline RRDSET *rrdset_find(RRDHOST *host, const char *id) {
  353. debug(D_RRD_CALLS, "rrdset_find() for chart '%s' in host '%s'", id, rrdhost_hostname(host));
  354. RRDSET *st = rrdset_index_find(host, id);
  355. if(st)
  356. st->last_accessed_time_s = now_realtime_sec();
  357. return(st);
  358. }
  359. inline RRDSET *rrdset_find_bytype(RRDHOST *host, const char *type, const char *id) {
  360. debug(D_RRD_CALLS, "rrdset_find_bytype() for chart '%s.%s' in host '%s'", type, id, rrdhost_hostname(host));
  361. char buf[RRD_ID_LENGTH_MAX + 1];
  362. strncpyz(buf, type, RRD_ID_LENGTH_MAX - 1);
  363. strcat(buf, ".");
  364. int len = (int) strlen(buf);
  365. strncpyz(&buf[len], id, (size_t) (RRD_ID_LENGTH_MAX - len));
  366. return(rrdset_find(host, buf));
  367. }
  368. inline RRDSET *rrdset_find_byname(RRDHOST *host, const char *name) {
  369. debug(D_RRD_CALLS, "rrdset_find_byname() for chart '%s' in host '%s'", name, rrdhost_hostname(host));
  370. RRDSET *st = rrdset_index_find_name(host, name);
  371. return(st);
  372. }
  373. // ----------------------------------------------------------------------------
  374. // RRDSET - rename charts
  375. char *rrdset_strncpyz_name(char *to, const char *from, size_t length) {
  376. char c, *p = to;
  377. while (length-- && (c = *from++)) {
  378. if(c != '.' && c != '-' && !isalnum(c))
  379. c = '_';
  380. *p++ = c;
  381. }
  382. *p = '\0';
  383. return to;
  384. }
  385. int rrdset_reset_name(RRDSET *st, const char *name) {
  386. if(unlikely(!strcmp(rrdset_name(st), name)))
  387. return 1;
  388. RRDHOST *host = st->rrdhost;
  389. debug(D_RRD_CALLS, "rrdset_reset_name() old: '%s', new: '%s'", rrdset_name(st), name);
  390. STRING *name_string = rrdset_fix_name(host, rrdset_id(st), rrdset_parts_type(st), string2str(st->name), name);
  391. if(!name_string) return 0;
  392. if(st->name) {
  393. rrdset_index_del_name(host, st);
  394. string_freez(st->name);
  395. st->name = name_string;
  396. rrdsetvar_rename_all(st);
  397. }
  398. else
  399. st->name = name_string;
  400. RRDDIM *rd;
  401. rrddim_foreach_read(rd, st)
  402. rrddimvar_rename_all(rd);
  403. rrddim_foreach_done(rd);
  404. rrdset_index_add_name(host, st);
  405. rrdset_flag_clear(st, RRDSET_FLAG_EXPORTING_SEND);
  406. rrdset_flag_clear(st, RRDSET_FLAG_EXPORTING_IGNORE);
  407. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_SEND);
  408. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  409. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  410. rrdcontext_updated_rrdset_name(st);
  411. return 2;
  412. }
  413. // get the timestamp of the last entry in the round-robin database
  414. time_t rrdset_last_entry_s(RRDSET *st) {
  415. RRDDIM *rd;
  416. time_t last_entry_s = 0;
  417. rrddim_foreach_read(rd, st) {
  418. time_t t = rrddim_last_entry_s(rd);
  419. if(t > last_entry_s) last_entry_s = t;
  420. }
  421. rrddim_foreach_done(rd);
  422. return last_entry_s;
  423. }
  424. time_t rrdset_last_entry_s_of_tier(RRDSET *st, size_t tier) {
  425. RRDDIM *rd;
  426. time_t last_entry_s = 0;
  427. rrddim_foreach_read(rd, st) {
  428. time_t t = rrddim_last_entry_s_of_tier(rd, tier);
  429. if(t > last_entry_s) last_entry_s = t;
  430. }
  431. rrddim_foreach_done(rd);
  432. return last_entry_s;
  433. }
  434. // get the timestamp of first entry in the round-robin database
  435. time_t rrdset_first_entry_s(RRDSET *st) {
  436. RRDDIM *rd;
  437. time_t first_entry_s = LONG_MAX;
  438. rrddim_foreach_read(rd, st) {
  439. time_t t = rrddim_first_entry_s(rd);
  440. if(t < first_entry_s)
  441. first_entry_s = t;
  442. }
  443. rrddim_foreach_done(rd);
  444. if (unlikely(LONG_MAX == first_entry_s)) return 0;
  445. return first_entry_s;
  446. }
  447. time_t rrdset_first_entry_s_of_tier(RRDSET *st, size_t tier) {
  448. if(unlikely(tier > storage_tiers))
  449. return 0;
  450. RRDDIM *rd;
  451. time_t first_entry_s = LONG_MAX;
  452. rrddim_foreach_read(rd, st) {
  453. time_t t = rrddim_first_entry_s_of_tier(rd, tier);
  454. if(t && t < first_entry_s)
  455. first_entry_s = t;
  456. }
  457. rrddim_foreach_done(rd);
  458. if (unlikely(LONG_MAX == first_entry_s)) return 0;
  459. return first_entry_s;
  460. }
  461. 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) {
  462. if(!now_s)
  463. now_s = now_realtime_sec();
  464. time_t db_first_entry_s = rrdset_first_entry_s_of_tier(st, tier);
  465. time_t db_last_entry_s = st->last_updated.tv_sec; // we assume this is a collected RRDSET
  466. if(unlikely(!db_last_entry_s)) {
  467. db_last_entry_s = rrdset_last_entry_s_of_tier(st, tier);
  468. if (unlikely(!db_last_entry_s)) {
  469. // we assume this is a collected RRDSET
  470. db_first_entry_s = 0;
  471. db_last_entry_s = 0;
  472. }
  473. }
  474. if(unlikely(db_last_entry_s > now_s)) {
  475. internal_error(db_last_entry_s > now_s + 1,
  476. "RRDSET: 'host:%s/chart:%s' latest db time %ld is in the future, adjusting it to now %ld",
  477. rrdhost_hostname(st->rrdhost), rrdset_id(st),
  478. db_last_entry_s, now_s);
  479. db_last_entry_s = now_s;
  480. }
  481. if(unlikely(db_first_entry_s && db_last_entry_s && db_first_entry_s >= db_last_entry_s)) {
  482. internal_error(db_first_entry_s > db_last_entry_s,
  483. "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)",
  484. rrdhost_hostname(st->rrdhost), rrdset_id(st),
  485. db_first_entry_s, db_last_entry_s,
  486. db_last_entry_s, (time_t)st->update_every);
  487. db_first_entry_s = db_last_entry_s - st->update_every;
  488. }
  489. if(unlikely(!db_first_entry_s && db_last_entry_s))
  490. // this can be the case on the first data collection of a chart
  491. db_first_entry_s = db_last_entry_s - st->update_every;
  492. *first_time_s = db_first_entry_s;
  493. *last_time_s = db_last_entry_s;
  494. }
  495. inline void rrdset_is_obsolete(RRDSET *st) {
  496. if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_ARCHIVED))) {
  497. info("Cannot obsolete already archived chart %s", rrdset_name(st));
  498. return;
  499. }
  500. if(unlikely(!(rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE)))) {
  501. rrdset_flag_set(st, RRDSET_FLAG_OBSOLETE);
  502. rrdhost_flag_set(st->rrdhost, RRDHOST_FLAG_PENDING_OBSOLETE_CHARTS);
  503. st->last_accessed_time_s = now_realtime_sec();
  504. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  505. // the chart will not get more updates (data collection)
  506. // so, we have to push its definition now
  507. rrdset_push_chart_definition_now(st);
  508. rrdcontext_updated_rrdset_flags(st);
  509. }
  510. }
  511. inline void rrdset_isnot_obsolete(RRDSET *st) {
  512. if(unlikely((rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE)))) {
  513. rrdset_flag_clear(st, RRDSET_FLAG_OBSOLETE);
  514. st->last_accessed_time_s = now_realtime_sec();
  515. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  516. // the chart will be pushed upstream automatically
  517. // due to data collection
  518. rrdcontext_updated_rrdset_flags(st);
  519. }
  520. }
  521. inline void rrdset_update_heterogeneous_flag(RRDSET *st) {
  522. RRDHOST *host = st->rrdhost;
  523. (void)host;
  524. RRDDIM *rd;
  525. rrdset_flag_clear(st, RRDSET_FLAG_HOMOGENEOUS_CHECK);
  526. bool init = false, is_heterogeneous = false;
  527. RRD_ALGORITHM algorithm;
  528. collected_number multiplier;
  529. collected_number divisor;
  530. rrddim_foreach_read(rd, st) {
  531. if(!init) {
  532. algorithm = rd->algorithm;
  533. multiplier = rd->multiplier;
  534. divisor = ABS(rd->divisor);
  535. init = true;
  536. continue;
  537. }
  538. if(algorithm != rd->algorithm || multiplier != ABS(rd->multiplier) || divisor != ABS(rd->divisor)) {
  539. if(!rrdset_flag_check(st, RRDSET_FLAG_HETEROGENEOUS)) {
  540. #ifdef NETDATA_INTERNAL_CHECKS
  541. 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 ").",
  542. rrddim_name(rd),
  543. rrdset_name(st),
  544. rrdhost_hostname(host),
  545. rrd_algorithm_name(rd->algorithm), rrd_algorithm_name(algorithm),
  546. rd->multiplier, multiplier,
  547. rd->divisor, divisor
  548. );
  549. #endif
  550. rrdset_flag_set(st, RRDSET_FLAG_HETEROGENEOUS);
  551. }
  552. is_heterogeneous = true;
  553. break;
  554. }
  555. }
  556. rrddim_foreach_done(rd);
  557. if(!is_heterogeneous) {
  558. rrdset_flag_clear(st, RRDSET_FLAG_HETEROGENEOUS);
  559. rrdcontext_updated_rrdset_flags(st);
  560. }
  561. }
  562. // ----------------------------------------------------------------------------
  563. // RRDSET - reset a chart
  564. void rrdset_reset(RRDSET *st) {
  565. debug(D_RRD_CALLS, "rrdset_reset() %s", rrdset_name(st));
  566. st->last_collected_time.tv_sec = 0;
  567. st->last_collected_time.tv_usec = 0;
  568. st->last_updated.tv_sec = 0;
  569. st->last_updated.tv_usec = 0;
  570. st->current_entry = 0;
  571. st->counter = 0;
  572. st->counter_done = 0;
  573. RRDDIM *rd;
  574. rrddim_foreach_read(rd, st) {
  575. rd->last_collected_time.tv_sec = 0;
  576. rd->last_collected_time.tv_usec = 0;
  577. rd->collections_counter = 0;
  578. if(!rrddim_flag_check(rd, RRDDIM_FLAG_ARCHIVED)) {
  579. for(size_t tier = 0; tier < storage_tiers ;tier++)
  580. storage_engine_store_flush(rd->tiers[tier].db_collection_handle);
  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. storage_engine_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. storage_engine_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. storage_engine_store_metric(rd->tiers[0].db_collection_handle, point_end_time_ut,
  956. n, 0, 0,
  957. 1, 0, flags);
  958. rrdset_done_statistics_points_stored_per_tier[0]++;
  959. time_t now_s = (time_t)(point_end_time_ut / USEC_PER_SEC);
  960. STORAGE_POINT sp = {
  961. .start_time_s = now_s - rd->update_every,
  962. .end_time_s = now_s,
  963. .min = n,
  964. .max = n,
  965. .sum = n,
  966. .count = 1,
  967. .anomaly_count = (flags & SN_FLAG_NOT_ANOMALOUS) ? 0 : 1,
  968. .flags = flags
  969. };
  970. for(size_t tier = 1; tier < storage_tiers ;tier++) {
  971. if(unlikely(!rd->tiers[tier].db_metric_handle)) continue;
  972. struct rrddim_tier *t = &rd->tiers[tier];
  973. if(!rrddim_option_check(rd, RRDDIM_OPTION_BACKFILLED_HIGH_TIERS)) {
  974. // we have not collected this tier before
  975. // let's fill any gap that may exist
  976. rrdr_fill_tier_gap_from_smaller_tiers(rd, tier, now_s);
  977. rrddim_option_set(rd, RRDDIM_OPTION_BACKFILLED_HIGH_TIERS);
  978. }
  979. store_metric_at_tier(rd, tier, t, sp, point_end_time_ut);
  980. }
  981. rrdcontext_collected_rrddim(rd);
  982. }
  983. void store_metric_collection_completed() {
  984. global_statistics_rrdset_done_chart_collection_completed(rrdset_done_statistics_points_stored_per_tier);
  985. }
  986. // caching of dimensions rrdset_done() and rrdset_done_interpolate() loop through
  987. struct rda_item {
  988. const DICTIONARY_ITEM *item;
  989. RRDDIM *rd;
  990. };
  991. static __thread struct rda_item *thread_rda = NULL;
  992. static __thread size_t thread_rda_entries = 0;
  993. struct rda_item *rrdset_thread_rda_get(size_t *dimensions) {
  994. if(unlikely(!thread_rda || (*dimensions) > thread_rda_entries)) {
  995. size_t old_mem = thread_rda_entries * sizeof(struct rda_item);
  996. freez(thread_rda);
  997. thread_rda_entries = *dimensions;
  998. size_t new_mem = thread_rda_entries * sizeof(struct rda_item);
  999. thread_rda = mallocz(new_mem);
  1000. __atomic_add_fetch(&netdata_buffers_statistics.rrdset_done_rda_size, new_mem - old_mem, __ATOMIC_RELAXED);
  1001. }
  1002. *dimensions = thread_rda_entries;
  1003. return thread_rda;
  1004. }
  1005. void rrdset_thread_rda_free(void) {
  1006. __atomic_sub_fetch(&netdata_buffers_statistics.rrdset_done_rda_size, thread_rda_entries * sizeof(struct rda_item), __ATOMIC_RELAXED);
  1007. freez(thread_rda);
  1008. thread_rda = NULL;
  1009. thread_rda_entries = 0;
  1010. }
  1011. static inline size_t rrdset_done_interpolate(
  1012. RRDSET_STREAM_BUFFER *rsb
  1013. , RRDSET *st
  1014. , struct rda_item *rda_base
  1015. , size_t rda_slots
  1016. , usec_t update_every_ut
  1017. , usec_t last_stored_ut
  1018. , usec_t next_store_ut
  1019. , usec_t last_collect_ut
  1020. , usec_t now_collect_ut
  1021. , char store_this_entry
  1022. , uint32_t has_reset_value
  1023. ) {
  1024. RRDDIM *rd;
  1025. size_t stored_entries = 0; // the number of entries we have stored in the db, during this call to rrdset_done()
  1026. usec_t first_ut = last_stored_ut, last_ut = 0;
  1027. (void)first_ut;
  1028. ssize_t iterations = (ssize_t)((now_collect_ut - last_stored_ut) / (update_every_ut));
  1029. if((now_collect_ut % (update_every_ut)) == 0) iterations++;
  1030. size_t counter = st->counter;
  1031. long current_entry = st->current_entry;
  1032. SN_FLAGS storage_flags = SN_DEFAULT_FLAGS;
  1033. if (has_reset_value)
  1034. storage_flags |= SN_FLAG_RESET;
  1035. for( ; next_store_ut <= now_collect_ut ; last_collect_ut = next_store_ut, next_store_ut += update_every_ut, iterations-- ) {
  1036. internal_error(iterations < 0,
  1037. "RRDSET: '%s': iterations calculation wrapped! "
  1038. "first_ut = %llu, last_stored_ut = %llu, next_store_ut = %llu, now_collect_ut = %llu"
  1039. , rrdset_id(st)
  1040. , first_ut
  1041. , last_stored_ut
  1042. , next_store_ut
  1043. , now_collect_ut
  1044. );
  1045. rrdset_debug(st, "last_stored_ut = %0.3" NETDATA_DOUBLE_MODIFIER " (last updated time)", (NETDATA_DOUBLE)last_stored_ut/USEC_PER_SEC);
  1046. rrdset_debug(st, "next_store_ut = %0.3" NETDATA_DOUBLE_MODIFIER " (next interpolation point)", (NETDATA_DOUBLE)next_store_ut/USEC_PER_SEC);
  1047. last_ut = next_store_ut;
  1048. ml_chart_update_begin(st);
  1049. struct rda_item *rda;
  1050. size_t dim_id;
  1051. for(dim_id = 0, rda = rda_base ; dim_id < rda_slots ; ++dim_id, ++rda) {
  1052. rd = rda->rd;
  1053. if(unlikely(!rd)) continue;
  1054. NETDATA_DOUBLE new_value;
  1055. switch(rd->algorithm) {
  1056. case RRD_ALGORITHM_INCREMENTAL:
  1057. new_value = (NETDATA_DOUBLE)
  1058. ( rd->calculated_value
  1059. * (NETDATA_DOUBLE)(next_store_ut - last_collect_ut)
  1060. / (NETDATA_DOUBLE)(now_collect_ut - last_collect_ut)
  1061. );
  1062. rrdset_debug(st, "%s: CALC2 INC " NETDATA_DOUBLE_FORMAT " = "
  1063. NETDATA_DOUBLE_FORMAT
  1064. " * (%llu - %llu)"
  1065. " / (%llu - %llu)"
  1066. , rrddim_name(rd)
  1067. , new_value
  1068. , rd->calculated_value
  1069. , next_store_ut, last_collect_ut
  1070. , now_collect_ut, last_collect_ut
  1071. );
  1072. rd->calculated_value -= new_value;
  1073. new_value += rd->last_calculated_value;
  1074. rd->last_calculated_value = 0;
  1075. new_value /= (NETDATA_DOUBLE)st->update_every;
  1076. if(unlikely(next_store_ut - last_stored_ut < update_every_ut)) {
  1077. rrdset_debug(st, "%s: COLLECTION POINT IS SHORT " NETDATA_DOUBLE_FORMAT " - EXTRAPOLATING",
  1078. rrddim_name(rd)
  1079. , (NETDATA_DOUBLE)(next_store_ut - last_stored_ut)
  1080. );
  1081. new_value = new_value * (NETDATA_DOUBLE)(st->update_every * USEC_PER_SEC) / (NETDATA_DOUBLE)(next_store_ut - last_stored_ut);
  1082. }
  1083. break;
  1084. case RRD_ALGORITHM_ABSOLUTE:
  1085. case RRD_ALGORITHM_PCENT_OVER_ROW_TOTAL:
  1086. case RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL:
  1087. default:
  1088. if(iterations == 1) {
  1089. // this is the last iteration
  1090. // do not interpolate
  1091. // just show the calculated value
  1092. new_value = rd->calculated_value;
  1093. }
  1094. else {
  1095. // we have missed an update
  1096. // interpolate in the middle values
  1097. new_value = (NETDATA_DOUBLE)
  1098. ( ( (rd->calculated_value - rd->last_calculated_value)
  1099. * (NETDATA_DOUBLE)(next_store_ut - last_collect_ut)
  1100. / (NETDATA_DOUBLE)(now_collect_ut - last_collect_ut)
  1101. )
  1102. + rd->last_calculated_value
  1103. );
  1104. rrdset_debug(st, "%s: CALC2 DEF " NETDATA_DOUBLE_FORMAT " = ((("
  1105. "(" NETDATA_DOUBLE_FORMAT " - " NETDATA_DOUBLE_FORMAT ")"
  1106. " * %llu"
  1107. " / %llu) + " NETDATA_DOUBLE_FORMAT, rrddim_name(rd)
  1108. , new_value
  1109. , rd->calculated_value, rd->last_calculated_value
  1110. , (next_store_ut - first_ut)
  1111. , (now_collect_ut - first_ut), rd->last_calculated_value
  1112. );
  1113. }
  1114. break;
  1115. }
  1116. time_t current_time_s = (time_t) (next_store_ut / USEC_PER_SEC);
  1117. if(unlikely(!store_this_entry)) {
  1118. (void) ml_dimension_is_anomalous(rd, current_time_s, 0, false);
  1119. if(rsb->wb && rsb->v2)
  1120. rrddim_push_metrics_v2(rsb, rd, next_store_ut, NAN, SN_FLAG_NONE);
  1121. rrddim_store_metric(rd, next_store_ut, NAN, SN_FLAG_NONE);
  1122. continue;
  1123. }
  1124. if(likely(rd->updated && rd->collections_counter > 1 && iterations < gap_when_lost_iterations_above)) {
  1125. uint32_t dim_storage_flags = storage_flags;
  1126. if (ml_dimension_is_anomalous(rd, current_time_s, new_value, true)) {
  1127. // clear anomaly bit: 0 -> is anomalous, 1 -> not anomalous
  1128. dim_storage_flags &= ~((storage_number)SN_FLAG_NOT_ANOMALOUS);
  1129. }
  1130. if(rsb->wb && rsb->v2)
  1131. rrddim_push_metrics_v2(rsb, rd, next_store_ut, new_value, dim_storage_flags);
  1132. rrddim_store_metric(rd, next_store_ut, new_value, dim_storage_flags);
  1133. rd->last_stored_value = new_value;
  1134. }
  1135. else {
  1136. (void) ml_dimension_is_anomalous(rd, current_time_s, 0, false);
  1137. rrdset_debug(st, "%s: STORE[%ld] = NON EXISTING ", rrddim_name(rd), current_entry);
  1138. if(rsb->wb && rsb->v2)
  1139. rrddim_push_metrics_v2(rsb, rd, next_store_ut, NAN, SN_FLAG_NONE);
  1140. rrddim_store_metric(rd, next_store_ut, NAN, SN_FLAG_NONE);
  1141. rd->last_stored_value = NAN;
  1142. }
  1143. stored_entries++;
  1144. }
  1145. ml_chart_update_end(st);
  1146. // reset the storage flags for the next point, if any;
  1147. storage_flags = SN_DEFAULT_FLAGS;
  1148. st->counter = ++counter;
  1149. st->current_entry = current_entry = ((current_entry + 1) >= st->entries) ? 0 : current_entry + 1;
  1150. st->last_updated.tv_sec = (time_t) (last_ut / USEC_PER_SEC);
  1151. st->last_updated.tv_usec = 0;
  1152. last_stored_ut = next_store_ut;
  1153. }
  1154. /*
  1155. st->counter = counter;
  1156. st->current_entry = current_entry;
  1157. if(likely(last_ut)) {
  1158. st->last_updated.tv_sec = (time_t) (last_ut / USEC_PER_SEC);
  1159. st->last_updated.tv_usec = 0;
  1160. }
  1161. */
  1162. return stored_entries;
  1163. }
  1164. void rrdset_done(RRDSET *st) {
  1165. struct timeval now;
  1166. now_realtime_timeval(&now);
  1167. rrdset_timed_done(st, now, /* pending_rrdset_next = */ st->counter_done != 0);
  1168. }
  1169. void rrdset_timed_done(RRDSET *st, struct timeval now, bool pending_rrdset_next) {
  1170. if(unlikely(!service_running(SERVICE_COLLECTORS))) return;
  1171. RRDSET_STREAM_BUFFER stream_buffer = { .wb = NULL, };
  1172. if(unlikely(rrdhost_has_rrdpush_sender_enabled(st->rrdhost)))
  1173. stream_buffer = rrdset_push_metric_initialize(st, now.tv_sec);
  1174. netdata_spinlock_lock(&st->data_collection_lock);
  1175. if (pending_rrdset_next)
  1176. rrdset_timed_next(st, now, 0ULL);
  1177. debug(D_RRD_CALLS, "rrdset_done() for chart '%s'", rrdset_name(st));
  1178. RRDDIM *rd;
  1179. char
  1180. store_this_entry = 1, // boolean: 1 = store this entry, 0 = don't store this entry
  1181. first_entry = 0; // boolean: 1 = this is the first entry seen for this chart, 0 = all other entries
  1182. usec_t
  1183. last_collect_ut = 0, // the timestamp in microseconds, of the last collected value
  1184. now_collect_ut = 0, // the timestamp in microseconds, of this collected value (this is NOW)
  1185. last_stored_ut = 0, // the timestamp in microseconds, of the last stored entry in the db
  1186. next_store_ut = 0, // the timestamp in microseconds, of the next entry to store in the db
  1187. update_every_ut = st->update_every * USEC_PER_SEC; // st->update_every in microseconds
  1188. RRDSET_FLAGS rrdset_flags = rrdset_flag_check(st, ~0);
  1189. if(unlikely(rrdset_flags & RRDSET_FLAG_COLLECTION_FINISHED)) {
  1190. netdata_spinlock_unlock(&st->data_collection_lock);
  1191. return;
  1192. }
  1193. if (unlikely(rrdset_flags & RRDSET_FLAG_OBSOLETE)) {
  1194. error("Chart '%s' has the OBSOLETE flag set, but it is collected.", rrdset_id(st));
  1195. rrdset_isnot_obsolete(st);
  1196. }
  1197. // check if the chart has a long time to be updated
  1198. if(unlikely(st->usec_since_last_update > MAX(st->entries, 60) * update_every_ut)) {
  1199. info("host '%s', chart '%s': took too long to be updated (counter #%zu, update #%zu, %0.3" NETDATA_DOUBLE_MODIFIER
  1200. " 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);
  1201. rrdset_reset(st);
  1202. st->usec_since_last_update = update_every_ut;
  1203. store_this_entry = 0;
  1204. first_entry = 1;
  1205. }
  1206. rrdset_debug(st, "microseconds since last update: %llu", st->usec_since_last_update);
  1207. // set last_collected_time
  1208. if(unlikely(!st->last_collected_time.tv_sec)) {
  1209. // it is the first entry
  1210. // set the last_collected_time to now
  1211. last_collect_ut = rrdset_init_last_collected_time(st, now) - update_every_ut;
  1212. // the first entry should not be stored
  1213. store_this_entry = 0;
  1214. first_entry = 1;
  1215. }
  1216. else {
  1217. // it is not the first entry
  1218. // calculate the proper last_collected_time, using usec_since_last_update
  1219. last_collect_ut = rrdset_update_last_collected_time(st);
  1220. }
  1221. // if this set has not been updated in the past
  1222. // we fake the last_update time to be = now - usec_since_last_update
  1223. if(unlikely(!st->last_updated.tv_sec)) {
  1224. // it has never been updated before
  1225. // set a fake last_updated, in the past using usec_since_last_update
  1226. rrdset_init_last_updated_time(st);
  1227. // the first entry should not be stored
  1228. store_this_entry = 0;
  1229. first_entry = 1;
  1230. }
  1231. // check if we will re-write the entire data set
  1232. if(unlikely(dt_usec(&st->last_collected_time, &st->last_updated) > st->entries * update_every_ut &&
  1233. st->rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)) {
  1234. info(
  1235. "'%s': too old data (last updated at %"PRId64".%"PRId64", last collected at %"PRId64".%"PRId64"). "
  1236. "Resetting it. Will not store the next entry.",
  1237. rrdset_id(st),
  1238. (int64_t)st->last_updated.tv_sec,
  1239. (int64_t)st->last_updated.tv_usec,
  1240. (int64_t)st->last_collected_time.tv_sec,
  1241. (int64_t)st->last_collected_time.tv_usec);
  1242. rrdset_reset(st);
  1243. rrdset_init_last_updated_time(st);
  1244. st->usec_since_last_update = update_every_ut;
  1245. // the first entry should not be stored
  1246. store_this_entry = 0;
  1247. first_entry = 1;
  1248. }
  1249. // these are the 3 variables that will help us in interpolation
  1250. // last_stored_ut = the last time we added a value to the storage
  1251. // now_collect_ut = the time the current value has been collected
  1252. // next_store_ut = the time of the next interpolation point
  1253. now_collect_ut = st->last_collected_time.tv_sec * USEC_PER_SEC + st->last_collected_time.tv_usec;
  1254. last_stored_ut = st->last_updated.tv_sec * USEC_PER_SEC + st->last_updated.tv_usec;
  1255. next_store_ut = (st->last_updated.tv_sec + st->update_every) * USEC_PER_SEC;
  1256. if(unlikely(!st->counter_done)) {
  1257. // set a fake last_updated to jump to current time
  1258. rrdset_init_last_updated_time(st);
  1259. last_stored_ut = st->last_updated.tv_sec * USEC_PER_SEC + st->last_updated.tv_usec;
  1260. next_store_ut = (st->last_updated.tv_sec + st->update_every) * USEC_PER_SEC;
  1261. if(unlikely(rrdset_flags & RRDSET_FLAG_STORE_FIRST)) {
  1262. store_this_entry = 1;
  1263. last_collect_ut = next_store_ut - update_every_ut;
  1264. rrdset_debug(st, "Fixed first entry.");
  1265. }
  1266. else {
  1267. store_this_entry = 0;
  1268. rrdset_debug(st, "Will not store the next entry.");
  1269. }
  1270. }
  1271. st->counter_done++;
  1272. if(stream_buffer.wb && !stream_buffer.v2)
  1273. rrdset_push_metrics_v1(&stream_buffer, st);
  1274. uint32_t has_reset_value = 0;
  1275. size_t rda_slots = dictionary_entries(st->rrddim_root_index);
  1276. struct rda_item *rda_base = rrdset_thread_rda_get(&rda_slots);
  1277. size_t dim_id;
  1278. size_t dimensions = 0;
  1279. struct rda_item *rda = rda_base;
  1280. total_number collected_total = 0;
  1281. total_number last_collected_total = 0;
  1282. rrddim_foreach_read(rd, st) {
  1283. if(rd_dfe.counter >= rda_slots)
  1284. break;
  1285. rda = &rda_base[dimensions++];
  1286. if(rrddim_flag_check(rd, RRDDIM_FLAG_ARCHIVED)) {
  1287. rda->item = NULL;
  1288. rda->rd = NULL;
  1289. continue;
  1290. }
  1291. // store the dimension in the array
  1292. rda->item = dictionary_acquired_item_dup(st->rrddim_root_index, rd_dfe.item);
  1293. rda->rd = dictionary_acquired_item_value(rda->item);
  1294. // calculate totals
  1295. if(likely(rd->updated)) {
  1296. // if the new is smaller than the old (an overflow, or reset), set the old equal to the new
  1297. // to reset the calculation (it will give zero as the calculation for this second)
  1298. if(unlikely(rd->algorithm == RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL && rd->last_collected_value > rd->collected_value)) {
  1299. debug(D_RRD_STATS, "'%s' / '%s': RESET or OVERFLOW. Last collected value = " COLLECTED_NUMBER_FORMAT ", current = " COLLECTED_NUMBER_FORMAT
  1300. , rrdset_id(st)
  1301. , rrddim_name(rd)
  1302. , rd->last_collected_value
  1303. , rd->collected_value
  1304. );
  1305. if(!(rrddim_option_check(rd, RRDDIM_OPTION_DONT_DETECT_RESETS_OR_OVERFLOWS)))
  1306. has_reset_value = 1;
  1307. rd->last_collected_value = rd->collected_value;
  1308. }
  1309. last_collected_total += rd->last_collected_value;
  1310. collected_total += rd->collected_value;
  1311. if(unlikely(rrddim_flag_check(rd, RRDDIM_FLAG_OBSOLETE))) {
  1312. error("Dimension %s in chart '%s' has the OBSOLETE flag set, but it is collected.", rrddim_name(rd), rrdset_id(st));
  1313. rrddim_isnot_obsolete(st, rd);
  1314. }
  1315. }
  1316. }
  1317. rrddim_foreach_done(rd);
  1318. rda_slots = dimensions;
  1319. rrdset_debug(st, "last_collect_ut = %0.3" NETDATA_DOUBLE_MODIFIER " (last collection time)", (NETDATA_DOUBLE)last_collect_ut/USEC_PER_SEC);
  1320. rrdset_debug(st, "now_collect_ut = %0.3" NETDATA_DOUBLE_MODIFIER " (current collection time)", (NETDATA_DOUBLE)now_collect_ut/USEC_PER_SEC);
  1321. rrdset_debug(st, "last_stored_ut = %0.3" NETDATA_DOUBLE_MODIFIER " (last updated time)", (NETDATA_DOUBLE)last_stored_ut/USEC_PER_SEC);
  1322. rrdset_debug(st, "next_store_ut = %0.3" NETDATA_DOUBLE_MODIFIER " (next interpolation point)", (NETDATA_DOUBLE)next_store_ut/USEC_PER_SEC);
  1323. // process all dimensions to calculate their values
  1324. // based on the collected figures only
  1325. // at this stage we do not interpolate anything
  1326. for(dim_id = 0, rda = rda_base ; dim_id < rda_slots ; ++dim_id, ++rda) {
  1327. rd = rda->rd;
  1328. if(unlikely(!rd)) continue;
  1329. if(unlikely(!rd->updated)) {
  1330. rd->calculated_value = 0;
  1331. continue;
  1332. }
  1333. rrdset_debug(st, "%s: START "
  1334. " last_collected_value = " COLLECTED_NUMBER_FORMAT
  1335. " collected_value = " COLLECTED_NUMBER_FORMAT
  1336. " last_calculated_value = " NETDATA_DOUBLE_FORMAT
  1337. " calculated_value = " NETDATA_DOUBLE_FORMAT
  1338. , rrddim_name(rd)
  1339. , rd->last_collected_value
  1340. , rd->collected_value
  1341. , rd->last_calculated_value
  1342. , rd->calculated_value
  1343. );
  1344. switch(rd->algorithm) {
  1345. case RRD_ALGORITHM_ABSOLUTE:
  1346. rd->calculated_value = (NETDATA_DOUBLE)rd->collected_value
  1347. * (NETDATA_DOUBLE)rd->multiplier
  1348. / (NETDATA_DOUBLE)rd->divisor;
  1349. rrdset_debug(st, "%s: CALC ABS/ABS-NO-IN " NETDATA_DOUBLE_FORMAT " = "
  1350. COLLECTED_NUMBER_FORMAT
  1351. " * " NETDATA_DOUBLE_FORMAT
  1352. " / " NETDATA_DOUBLE_FORMAT
  1353. , rrddim_name(rd)
  1354. , rd->calculated_value
  1355. , rd->collected_value
  1356. , (NETDATA_DOUBLE)rd->multiplier
  1357. , (NETDATA_DOUBLE)rd->divisor
  1358. );
  1359. break;
  1360. case RRD_ALGORITHM_PCENT_OVER_ROW_TOTAL:
  1361. if(unlikely(!collected_total))
  1362. rd->calculated_value = 0;
  1363. else
  1364. // the percentage of the current value
  1365. // over the total of all dimensions
  1366. rd->calculated_value =
  1367. (NETDATA_DOUBLE)100
  1368. * (NETDATA_DOUBLE)rd->collected_value
  1369. / (NETDATA_DOUBLE)collected_total;
  1370. rrdset_debug(st, "%s: CALC PCENT-ROW " NETDATA_DOUBLE_FORMAT " = 100"
  1371. " * " COLLECTED_NUMBER_FORMAT
  1372. " / " COLLECTED_NUMBER_FORMAT
  1373. , rrddim_name(rd)
  1374. , rd->calculated_value
  1375. , rd->collected_value
  1376. , collected_total
  1377. );
  1378. break;
  1379. case RRD_ALGORITHM_INCREMENTAL:
  1380. if(unlikely(rd->collections_counter <= 1)) {
  1381. rd->calculated_value = 0;
  1382. continue;
  1383. }
  1384. // If the new is smaller than the old (an overflow, or reset), set the old equal to the new
  1385. // to reset the calculation (it will give zero as the calculation for this second).
  1386. // It is imperative to set the comparison to uint64_t since type collected_number is signed and
  1387. // produces wrong results as far as incremental counters are concerned.
  1388. if(unlikely((uint64_t)rd->last_collected_value > (uint64_t)rd->collected_value)) {
  1389. debug(D_RRD_STATS, "'%s' / '%s': RESET or OVERFLOW. Last collected value = " COLLECTED_NUMBER_FORMAT ", current = " COLLECTED_NUMBER_FORMAT
  1390. , rrdset_id(st)
  1391. , rrddim_name(rd)
  1392. , rd->last_collected_value
  1393. , rd->collected_value);
  1394. if(!(rrddim_option_check(rd, RRDDIM_OPTION_DONT_DETECT_RESETS_OR_OVERFLOWS)))
  1395. has_reset_value = 1;
  1396. uint64_t last = (uint64_t)rd->last_collected_value;
  1397. uint64_t new = (uint64_t)rd->collected_value;
  1398. uint64_t max = (uint64_t)rd->collected_value_max;
  1399. uint64_t cap = 0;
  1400. // Signed values are handled by exploiting two's complement which will produce positive deltas
  1401. if (max > 0x00000000FFFFFFFFULL)
  1402. cap = 0xFFFFFFFFFFFFFFFFULL; // handles signed and unsigned 64-bit counters
  1403. else
  1404. cap = 0x00000000FFFFFFFFULL; // handles signed and unsigned 32-bit counters
  1405. uint64_t delta = cap - last + new;
  1406. uint64_t max_acceptable_rate = (cap / 100) * MAX_INCREMENTAL_PERCENT_RATE;
  1407. // If the delta is less than the maximum acceptable rate and the previous value was near the cap
  1408. // then this is an overflow. There can be false positives such that a reset is detected as an
  1409. // overflow.
  1410. // TODO: remember recent history of rates and compare with current rate to reduce this chance.
  1411. if (delta < max_acceptable_rate) {
  1412. rd->calculated_value +=
  1413. (NETDATA_DOUBLE) delta
  1414. * (NETDATA_DOUBLE) rd->multiplier
  1415. / (NETDATA_DOUBLE) rd->divisor;
  1416. } else {
  1417. // This is a reset. Any overflow with a rate greater than MAX_INCREMENTAL_PERCENT_RATE will also
  1418. // be detected as a reset instead.
  1419. rd->calculated_value += (NETDATA_DOUBLE)0;
  1420. }
  1421. }
  1422. else {
  1423. rd->calculated_value +=
  1424. (NETDATA_DOUBLE) (rd->collected_value - rd->last_collected_value)
  1425. * (NETDATA_DOUBLE) rd->multiplier
  1426. / (NETDATA_DOUBLE) rd->divisor;
  1427. }
  1428. rrdset_debug(st, "%s: CALC INC PRE " NETDATA_DOUBLE_FORMAT " = ("
  1429. COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT
  1430. ")"
  1431. " * " NETDATA_DOUBLE_FORMAT
  1432. " / " NETDATA_DOUBLE_FORMAT
  1433. , rrddim_name(rd)
  1434. , rd->calculated_value
  1435. , rd->collected_value, rd->last_collected_value
  1436. , (NETDATA_DOUBLE)rd->multiplier
  1437. , (NETDATA_DOUBLE)rd->divisor
  1438. );
  1439. break;
  1440. case RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL:
  1441. if(unlikely(rd->collections_counter <= 1)) {
  1442. rd->calculated_value = 0;
  1443. continue;
  1444. }
  1445. // the percentage of the current increment
  1446. // over the increment of all dimensions together
  1447. if(unlikely(collected_total == last_collected_total))
  1448. rd->calculated_value = 0;
  1449. else
  1450. rd->calculated_value =
  1451. (NETDATA_DOUBLE)100
  1452. * (NETDATA_DOUBLE)(rd->collected_value - rd->last_collected_value)
  1453. / (NETDATA_DOUBLE)(collected_total - last_collected_total);
  1454. rrdset_debug(st, "%s: CALC PCENT-DIFF " NETDATA_DOUBLE_FORMAT " = 100"
  1455. " * (" COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT ")"
  1456. " / (" COLLECTED_NUMBER_FORMAT " - " COLLECTED_NUMBER_FORMAT ")"
  1457. , rrddim_name(rd)
  1458. , rd->calculated_value
  1459. , rd->collected_value, rd->last_collected_value
  1460. , collected_total, last_collected_total
  1461. );
  1462. break;
  1463. default:
  1464. // make the default zero, to make sure
  1465. // it gets noticed when we add new types
  1466. rd->calculated_value = 0;
  1467. rrdset_debug(st, "%s: CALC " NETDATA_DOUBLE_FORMAT " = 0"
  1468. , rrddim_name(rd)
  1469. , rd->calculated_value
  1470. );
  1471. break;
  1472. }
  1473. rrdset_debug(st, "%s: PHASE2 "
  1474. " last_collected_value = " COLLECTED_NUMBER_FORMAT
  1475. " collected_value = " COLLECTED_NUMBER_FORMAT
  1476. " last_calculated_value = " NETDATA_DOUBLE_FORMAT
  1477. " calculated_value = " NETDATA_DOUBLE_FORMAT
  1478. , rrddim_name(rd)
  1479. , rd->last_collected_value
  1480. , rd->collected_value
  1481. , rd->last_calculated_value
  1482. , rd->calculated_value
  1483. );
  1484. }
  1485. // at this point we have all the calculated values ready
  1486. // it is now time to interpolate values on a second boundary
  1487. // #ifdef NETDATA_INTERNAL_CHECKS
  1488. // if(unlikely(now_collect_ut < next_store_ut && st->counter_done > 1)) {
  1489. // // this is collected in the same interpolation point
  1490. // rrdset_debug(st, "THIS IS IN THE SAME INTERPOLATION POINT");
  1491. // 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);
  1492. // }
  1493. // #endif
  1494. rrdset_done_interpolate(
  1495. &stream_buffer
  1496. , st
  1497. , rda_base
  1498. , rda_slots
  1499. , update_every_ut
  1500. , last_stored_ut
  1501. , next_store_ut
  1502. , last_collect_ut
  1503. , now_collect_ut
  1504. , store_this_entry
  1505. , has_reset_value
  1506. );
  1507. for(dim_id = 0, rda = rda_base ; dim_id < rda_slots ; ++dim_id, ++rda) {
  1508. rd = rda->rd;
  1509. if(unlikely(!rd)) continue;
  1510. if(unlikely(!rd->updated))
  1511. continue;
  1512. 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);
  1513. rd->last_collected_value = rd->collected_value;
  1514. switch(rd->algorithm) {
  1515. case RRD_ALGORITHM_INCREMENTAL:
  1516. if(unlikely(!first_entry)) {
  1517. rrdset_debug(st, "%s: setting last_calculated_value (old: " NETDATA_DOUBLE_FORMAT ") to "
  1518. "last_calculated_value (new: " NETDATA_DOUBLE_FORMAT ")"
  1519. , rrddim_name(rd)
  1520. , rd->last_calculated_value + rd->calculated_value
  1521. , rd->calculated_value);
  1522. rd->last_calculated_value += rd->calculated_value;
  1523. }
  1524. else {
  1525. rrdset_debug(st, "THIS IS THE FIRST POINT");
  1526. }
  1527. break;
  1528. case RRD_ALGORITHM_ABSOLUTE:
  1529. case RRD_ALGORITHM_PCENT_OVER_ROW_TOTAL:
  1530. case RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL:
  1531. rrdset_debug(st, "%s: setting last_calculated_value (old: " NETDATA_DOUBLE_FORMAT ") to "
  1532. "last_calculated_value (new: " NETDATA_DOUBLE_FORMAT ")"
  1533. , rrddim_name(rd)
  1534. , rd->last_calculated_value
  1535. , rd->calculated_value);
  1536. rd->last_calculated_value = rd->calculated_value;
  1537. break;
  1538. }
  1539. rd->calculated_value = 0;
  1540. rd->collected_value = 0;
  1541. rd->updated = 0;
  1542. rrdset_debug(st, "%s: END "
  1543. " last_collected_value = " COLLECTED_NUMBER_FORMAT
  1544. " collected_value = " COLLECTED_NUMBER_FORMAT
  1545. " last_calculated_value = " NETDATA_DOUBLE_FORMAT
  1546. " calculated_value = " NETDATA_DOUBLE_FORMAT
  1547. , rrddim_name(rd)
  1548. , rd->last_collected_value
  1549. , rd->collected_value
  1550. , rd->last_calculated_value
  1551. , rd->calculated_value
  1552. );
  1553. }
  1554. netdata_spinlock_unlock(&st->data_collection_lock);
  1555. rrdset_push_metrics_finished(&stream_buffer, st);
  1556. // ALL DONE ABOUT THE DATA UPDATE
  1557. // --------------------------------------------------------------------
  1558. if(unlikely(st->rrd_memory_mode == RRD_MEMORY_MODE_MAP)) {
  1559. // update the memory mapped files with the latest values
  1560. rrdset_memory_file_update(st);
  1561. for(dim_id = 0, rda = rda_base; dim_id < rda_slots ; ++dim_id, ++rda) {
  1562. rd = rda->rd;
  1563. if(unlikely(!rd)) continue;
  1564. rrddim_memory_file_update(rd);
  1565. }
  1566. }
  1567. for(dim_id = 0, rda = rda_base; dim_id < rda_slots ; ++dim_id, ++rda) {
  1568. rd = rda->rd;
  1569. if(unlikely(!rd)) continue;
  1570. dictionary_acquired_item_release(st->rrddim_root_index, rda->item);
  1571. rda->item = NULL;
  1572. rda->rd = NULL;
  1573. }
  1574. rrdcontext_collected_rrdset(st);
  1575. store_metric_collection_completed();
  1576. }
  1577. time_t rrdset_set_update_every_s(RRDSET *st, time_t update_every_s) {
  1578. internal_error(true, "RRDSET '%s' switching update every from %d to %d",
  1579. rrdset_id(st), (int)st->update_every, (int)update_every_s);
  1580. time_t prev_update_every_s = (time_t) st->update_every;
  1581. st->update_every = (int) update_every_s;
  1582. // switch update every to the storage engine
  1583. RRDDIM *rd;
  1584. rrddim_foreach_read(rd, st) {
  1585. for (size_t tier = 0; tier < storage_tiers; tier++) {
  1586. if (rd->tiers[tier].db_collection_handle)
  1587. storage_engine_store_change_collection_frequency(
  1588. rd->tiers[tier].db_collection_handle,
  1589. (int)(st->rrdhost->db[tier].tier_grouping * st->update_every));
  1590. }
  1591. assert(rd->update_every == (int) prev_update_every_s &&
  1592. "chart's update every differs from the update every of its dimensions");
  1593. rd->update_every = st->update_every;
  1594. }
  1595. rrddim_foreach_done(rd);
  1596. return prev_update_every_s;
  1597. }
  1598. // ----------------------------------------------------------------------------
  1599. // compatibility layer for RRDSET files v019
  1600. #define RRDSET_MAGIC_V019 "NETDATA RRD SET FILE V019"
  1601. #define RRD_ID_LENGTH_MAX_V019 200
  1602. struct avl_element_v019 {
  1603. void *avl_link[2];
  1604. signed char avl_balance;
  1605. };
  1606. struct avl_tree_type_v019 {
  1607. void *root;
  1608. int (*compar)(void *a, void *b);
  1609. };
  1610. struct avl_tree_lock_v019 {
  1611. struct avl_tree_type_v019 avl_tree;
  1612. pthread_rwlock_t rwlock;
  1613. };
  1614. struct rrdset_map_save_v019 {
  1615. struct avl_element_v019 avl; // ignored
  1616. struct avl_element_v019 avlname; // ignored
  1617. char id[RRD_ID_LENGTH_MAX_V019 + 1]; // check to reset all - update on load
  1618. void *name; // ignored
  1619. void *unused_ptr; // ignored
  1620. void *type; // ignored
  1621. void *family; // ignored
  1622. void *title; // ignored
  1623. void *units; // ignored
  1624. void *context; // ignored
  1625. uint32_t hash_context; // ignored
  1626. uint32_t chart_type; // ignored
  1627. int update_every; // check to reset all - update on load
  1628. long entries; // check to reset all - update on load
  1629. long current_entry; // NEEDS TO BE UPDATED - FIXED ON LOAD
  1630. uint32_t flags; // ignored
  1631. void *exporting_flags; // ignored
  1632. int gap_when_lost_iterations_above; // ignored
  1633. long priority; // ignored
  1634. uint32_t rrd_memory_mode; // ignored
  1635. void *cache_dir; // ignored
  1636. char cache_filename[FILENAME_MAX+1]; // ignored - update on load
  1637. pthread_rwlock_t rrdset_rwlock; // ignored
  1638. size_t counter; // NEEDS TO BE UPDATED - maintained on load
  1639. size_t counter_done; // ignored
  1640. union { //
  1641. time_t last_accessed_time_s; // ignored
  1642. time_t last_entry_s; // ignored
  1643. }; //
  1644. time_t upstream_resync_time; // ignored
  1645. void *plugin_name; // ignored
  1646. void *module_name; // ignored
  1647. void *chart_uuid; // ignored
  1648. void *state; // ignored
  1649. size_t unused[3]; // ignored
  1650. size_t rrddim_page_alignment; // ignored
  1651. uint32_t hash; // ignored
  1652. uint32_t hash_name; // ignored
  1653. usec_t usec_since_last_update; // NEEDS TO BE UPDATED - maintained on load
  1654. struct timeval last_updated; // NEEDS TO BE UPDATED - check to reset all - fixed on load
  1655. struct timeval last_collected_time; // ignored
  1656. long long collected_total; // ignored
  1657. long long last_collected_total; // ignored
  1658. void *rrdfamily; // ignored
  1659. void *rrdhost; // ignored
  1660. void *next; // ignored
  1661. long double green; // ignored
  1662. long double red; // ignored
  1663. struct avl_tree_lock_v019 rrdvar_root_index; // ignored
  1664. void *variables; // ignored
  1665. void *alarms; // ignored
  1666. unsigned long memsize; // check to reset all - update on load
  1667. char magic[sizeof(RRDSET_MAGIC_V019) + 1]; // check to reset all - update on load
  1668. struct avl_tree_lock_v019 dimensions_index; // ignored
  1669. void *dimensions; // ignored
  1670. };
  1671. void rrdset_memory_file_update(RRDSET *st) {
  1672. if(!st->st_on_file) return;
  1673. struct rrdset_map_save_v019 *st_on_file = st->st_on_file;
  1674. st_on_file->current_entry = st->current_entry;
  1675. st_on_file->counter = st->counter;
  1676. st_on_file->usec_since_last_update = st->usec_since_last_update;
  1677. st_on_file->last_updated.tv_sec = st->last_updated.tv_sec;
  1678. st_on_file->last_updated.tv_usec = st->last_updated.tv_usec;
  1679. }
  1680. const char *rrdset_cache_filename(RRDSET *st) {
  1681. if(!st->st_on_file) return NULL;
  1682. struct rrdset_map_save_v019 *st_on_file = st->st_on_file;
  1683. return st_on_file->cache_filename;
  1684. }
  1685. const char *rrdset_cache_dir(RRDSET *st) {
  1686. if(!st->cache_dir)
  1687. st->cache_dir = rrdhost_cache_dir_for_rrdset_alloc(st->rrdhost, rrdset_id(st));
  1688. return st->cache_dir;
  1689. }
  1690. void rrdset_memory_file_free(RRDSET *st) {
  1691. if(!st->st_on_file) return;
  1692. // needed for memory mode map, to save the latest state
  1693. rrdset_memory_file_update(st);
  1694. struct rrdset_map_save_v019 *st_on_file = st->st_on_file;
  1695. __atomic_sub_fetch(&rrddim_db_memory_size, st_on_file->memsize, __ATOMIC_RELAXED);
  1696. netdata_munmap(st_on_file, st_on_file->memsize);
  1697. // remove the pointers from the RRDDIM
  1698. st->st_on_file = NULL;
  1699. }
  1700. void rrdset_memory_file_save(RRDSET *st) {
  1701. if(!st->st_on_file) return;
  1702. rrdset_memory_file_update(st);
  1703. struct rrdset_map_save_v019 *st_on_file = st->st_on_file;
  1704. if(st_on_file->rrd_memory_mode != RRD_MEMORY_MODE_SAVE) return;
  1705. memory_file_save(st_on_file->cache_filename, st->st_on_file, st_on_file->memsize);
  1706. }
  1707. bool rrdset_memory_load_or_create_map_save(RRDSET *st, RRD_MEMORY_MODE memory_mode) {
  1708. if(memory_mode != RRD_MEMORY_MODE_SAVE && memory_mode != RRD_MEMORY_MODE_MAP)
  1709. return false;
  1710. char fullfilename[FILENAME_MAX + 1];
  1711. snprintfz(fullfilename, FILENAME_MAX, "%s/main.db", rrdset_cache_dir(st));
  1712. unsigned long size = sizeof(struct rrdset_map_save_v019);
  1713. struct rrdset_map_save_v019 *st_on_file = (struct rrdset_map_save_v019 *)netdata_mmap(
  1714. fullfilename, size, ((memory_mode == RRD_MEMORY_MODE_MAP) ? MAP_SHARED : MAP_PRIVATE), 0, false, NULL);
  1715. if(!st_on_file) return false;
  1716. time_t now_s = now_realtime_sec();
  1717. st_on_file->magic[sizeof(RRDSET_MAGIC_V019)] = '\0';
  1718. if(strcmp(st_on_file->magic, RRDSET_MAGIC_V019) != 0) {
  1719. info("Initializing file '%s'.", fullfilename);
  1720. memset(st_on_file, 0, size);
  1721. }
  1722. else if(strncmp(st_on_file->id, rrdset_id(st), RRD_ID_LENGTH_MAX_V019) != 0) {
  1723. error("File '%s' contents are not for chart '%s'. Clearing it.", fullfilename, rrdset_id(st));
  1724. memset(st_on_file, 0, size);
  1725. }
  1726. else if(st_on_file->memsize != size || st_on_file->entries != st->entries) {
  1727. error("File '%s' does not have the desired size. Clearing it.", fullfilename);
  1728. memset(st_on_file, 0, size);
  1729. }
  1730. else if(st_on_file->update_every != st->update_every) {
  1731. error("File '%s' does not have the desired granularity. Clearing it.", fullfilename);
  1732. memset(st_on_file, 0, size);
  1733. }
  1734. else if((now_s - st_on_file->last_updated.tv_sec) > st->update_every * st->entries) {
  1735. info("File '%s' is too old. Clearing it.", fullfilename);
  1736. memset(st_on_file, 0, size);
  1737. }
  1738. else if(st_on_file->last_updated.tv_sec > now_s + st->update_every) {
  1739. 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));
  1740. st_on_file->last_updated.tv_sec = now_s;
  1741. }
  1742. if(st_on_file->current_entry >= st_on_file->entries)
  1743. st_on_file->current_entry = 0;
  1744. // make sure the database is aligned
  1745. bool align_last_updated = false;
  1746. if(st_on_file->last_updated.tv_sec) {
  1747. st_on_file->update_every = st->update_every;
  1748. align_last_updated = true;
  1749. }
  1750. // copy the useful values to st
  1751. st->current_entry = st_on_file->current_entry;
  1752. st->counter = st_on_file->counter;
  1753. st->usec_since_last_update = st_on_file->usec_since_last_update;
  1754. st->last_updated.tv_sec = st_on_file->last_updated.tv_sec;
  1755. st->last_updated.tv_usec = st_on_file->last_updated.tv_usec;
  1756. // link it to st
  1757. st->st_on_file = st_on_file;
  1758. // clear everything
  1759. memset(st_on_file, 0, size);
  1760. // set the values we need
  1761. strncpyz(st_on_file->id, rrdset_id(st), RRD_ID_LENGTH_MAX_V019 + 1);
  1762. strcpy(st_on_file->cache_filename, fullfilename);
  1763. strcpy(st_on_file->magic, RRDSET_MAGIC_V019);
  1764. st_on_file->memsize = size;
  1765. st_on_file->entries = st->entries;
  1766. st_on_file->update_every = st->update_every;
  1767. st_on_file->rrd_memory_mode = memory_mode;
  1768. if(align_last_updated)
  1769. last_updated_time_align(st);
  1770. // copy the useful values back to st_on_file
  1771. rrdset_memory_file_update(st);
  1772. __atomic_add_fetch(&rrddim_db_memory_size, st_on_file->memsize, __ATOMIC_RELAXED);
  1773. return true;
  1774. }