rrdset.c 84 KB

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