rrdengineapi.c 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "rrdengine.h"
  3. /* Default global database instance */
  4. struct rrdengine_instance multidb_ctx_storage_tier0;
  5. struct rrdengine_instance multidb_ctx_storage_tier1;
  6. struct rrdengine_instance multidb_ctx_storage_tier2;
  7. struct rrdengine_instance multidb_ctx_storage_tier3;
  8. struct rrdengine_instance multidb_ctx_storage_tier4;
  9. #define mrg_metric_ctx(metric) (struct rrdengine_instance *)mrg_metric_section(main_mrg, metric)
  10. #if RRD_STORAGE_TIERS != 5
  11. #error RRD_STORAGE_TIERS is not 5 - you need to add allocations here
  12. #endif
  13. struct rrdengine_instance *multidb_ctx[RRD_STORAGE_TIERS];
  14. uint8_t tier_page_type[RRD_STORAGE_TIERS] = {PAGE_METRICS, PAGE_TIER, PAGE_TIER, PAGE_TIER, PAGE_TIER};
  15. #if defined(ENV32BIT)
  16. size_t tier_page_size[RRD_STORAGE_TIERS] = {2048, 1024, 192, 192, 192};
  17. #else
  18. size_t tier_page_size[RRD_STORAGE_TIERS] = {4096, 2048, 384, 384, 384};
  19. #endif
  20. #if PAGE_TYPE_MAX != 1
  21. #error PAGE_TYPE_MAX is not 1 - you need to add allocations here
  22. #endif
  23. size_t page_type_size[256] = {sizeof(storage_number), sizeof(storage_number_tier1_t)};
  24. __attribute__((constructor)) void initialize_multidb_ctx(void) {
  25. multidb_ctx[0] = &multidb_ctx_storage_tier0;
  26. multidb_ctx[1] = &multidb_ctx_storage_tier1;
  27. multidb_ctx[2] = &multidb_ctx_storage_tier2;
  28. multidb_ctx[3] = &multidb_ctx_storage_tier3;
  29. multidb_ctx[4] = &multidb_ctx_storage_tier4;
  30. }
  31. int default_rrdeng_page_fetch_timeout = 3;
  32. int default_rrdeng_page_fetch_retries = 3;
  33. int db_engine_journal_check = 0;
  34. int default_rrdeng_disk_quota_mb = 256;
  35. int default_multidb_disk_quota_mb = 256;
  36. #if defined(ENV32BIT)
  37. int default_rrdeng_page_cache_mb = 16;
  38. #else
  39. int default_rrdeng_page_cache_mb = 32;
  40. #endif
  41. // ----------------------------------------------------------------------------
  42. // metrics groups
  43. static inline void rrdeng_page_alignment_acquire(struct pg_alignment *pa) {
  44. if(unlikely(!pa)) return;
  45. __atomic_add_fetch(&pa->refcount, 1, __ATOMIC_SEQ_CST);
  46. }
  47. static inline bool rrdeng_page_alignment_release(struct pg_alignment *pa) {
  48. if(unlikely(!pa)) return true;
  49. if(__atomic_sub_fetch(&pa->refcount, 1, __ATOMIC_SEQ_CST) == 0) {
  50. freez(pa);
  51. return true;
  52. }
  53. return false;
  54. }
  55. // charts call this
  56. STORAGE_METRICS_GROUP *rrdeng_metrics_group_get(STORAGE_INSTANCE *db_instance __maybe_unused, uuid_t *uuid __maybe_unused) {
  57. struct pg_alignment *pa = callocz(1, sizeof(struct pg_alignment));
  58. rrdeng_page_alignment_acquire(pa);
  59. return (STORAGE_METRICS_GROUP *)pa;
  60. }
  61. // charts call this
  62. void rrdeng_metrics_group_release(STORAGE_INSTANCE *db_instance __maybe_unused, STORAGE_METRICS_GROUP *smg) {
  63. if(unlikely(!smg)) return;
  64. struct pg_alignment *pa = (struct pg_alignment *)smg;
  65. rrdeng_page_alignment_release(pa);
  66. }
  67. // ----------------------------------------------------------------------------
  68. // metric handle for legacy dbs
  69. /* This UUID is not unique across hosts */
  70. void rrdeng_generate_legacy_uuid(const char *dim_id, const char *chart_id, uuid_t *ret_uuid)
  71. {
  72. EVP_MD_CTX *evpctx;
  73. unsigned char hash_value[EVP_MAX_MD_SIZE];
  74. unsigned int hash_len;
  75. evpctx = EVP_MD_CTX_create();
  76. EVP_DigestInit_ex(evpctx, EVP_sha256(), NULL);
  77. EVP_DigestUpdate(evpctx, dim_id, strlen(dim_id));
  78. EVP_DigestUpdate(evpctx, chart_id, strlen(chart_id));
  79. EVP_DigestFinal_ex(evpctx, hash_value, &hash_len);
  80. EVP_MD_CTX_destroy(evpctx);
  81. fatal_assert(hash_len > sizeof(uuid_t));
  82. memcpy(ret_uuid, hash_value, sizeof(uuid_t));
  83. }
  84. static METRIC *rrdeng_metric_get_legacy(STORAGE_INSTANCE *db_instance, const char *rd_id, const char *st_id) {
  85. struct rrdengine_instance *ctx = (struct rrdengine_instance *)db_instance;
  86. uuid_t legacy_uuid;
  87. rrdeng_generate_legacy_uuid(rd_id, st_id, &legacy_uuid);
  88. return mrg_metric_get_and_acquire(main_mrg, &legacy_uuid, (Word_t) ctx);
  89. }
  90. // ----------------------------------------------------------------------------
  91. // metric handle
  92. void rrdeng_metric_release(STORAGE_METRIC_HANDLE *db_metric_handle) {
  93. METRIC *metric = (METRIC *)db_metric_handle;
  94. mrg_metric_release(main_mrg, metric);
  95. }
  96. STORAGE_METRIC_HANDLE *rrdeng_metric_dup(STORAGE_METRIC_HANDLE *db_metric_handle) {
  97. METRIC *metric = (METRIC *)db_metric_handle;
  98. return (STORAGE_METRIC_HANDLE *) mrg_metric_dup(main_mrg, metric);
  99. }
  100. STORAGE_METRIC_HANDLE *rrdeng_metric_get(STORAGE_INSTANCE *db_instance, uuid_t *uuid) {
  101. struct rrdengine_instance *ctx = (struct rrdengine_instance *)db_instance;
  102. return (STORAGE_METRIC_HANDLE *) mrg_metric_get_and_acquire(main_mrg, uuid, (Word_t) ctx);
  103. }
  104. static METRIC *rrdeng_metric_create(STORAGE_INSTANCE *db_instance, uuid_t *uuid) {
  105. internal_fatal(!db_instance, "DBENGINE: db_instance is NULL");
  106. struct rrdengine_instance *ctx = (struct rrdengine_instance *)db_instance;
  107. MRG_ENTRY entry = {
  108. .section = (Word_t)ctx,
  109. .first_time_s = 0,
  110. .last_time_s = 0,
  111. .latest_update_every_s = 0,
  112. };
  113. uuid_copy(entry.uuid, *uuid);
  114. METRIC *metric = mrg_metric_add_and_acquire(main_mrg, entry, NULL);
  115. return metric;
  116. }
  117. STORAGE_METRIC_HANDLE *rrdeng_metric_get_or_create(RRDDIM *rd, STORAGE_INSTANCE *db_instance) {
  118. struct rrdengine_instance *ctx = (struct rrdengine_instance *)db_instance;
  119. METRIC *metric;
  120. metric = mrg_metric_get_and_acquire(main_mrg, &rd->metric_uuid, (Word_t) ctx);
  121. if(unlikely(!metric)) {
  122. if(unlikely(ctx->config.legacy)) {
  123. // this is a single host database
  124. // generate uuid from the chart and dimensions ids
  125. // and overwrite the one supplied by rrddim
  126. metric = rrdeng_metric_get_legacy(db_instance, rrddim_id(rd), rrdset_id(rd->rrdset));
  127. if (metric)
  128. uuid_copy(rd->metric_uuid, *mrg_metric_uuid(main_mrg, metric));
  129. }
  130. if(likely(!metric))
  131. metric = rrdeng_metric_create(db_instance, &rd->metric_uuid);
  132. }
  133. #ifdef NETDATA_INTERNAL_CHECKS
  134. if(uuid_compare(rd->metric_uuid, *mrg_metric_uuid(main_mrg, metric)) != 0) {
  135. char uuid1[UUID_STR_LEN + 1];
  136. char uuid2[UUID_STR_LEN + 1];
  137. uuid_unparse(rd->metric_uuid, uuid1);
  138. uuid_unparse(*mrg_metric_uuid(main_mrg, metric), uuid2);
  139. fatal("DBENGINE: uuids do not match, asked for metric '%s', but got metric '%s'", uuid1, uuid2);
  140. }
  141. if(mrg_metric_ctx(metric) != ctx)
  142. fatal("DBENGINE: mixed up db instances, asked for metric from %p, got from %p",
  143. ctx, mrg_metric_ctx(metric));
  144. #endif
  145. return (STORAGE_METRIC_HANDLE *)metric;
  146. }
  147. // ----------------------------------------------------------------------------
  148. // collect ops
  149. static inline void check_and_fix_mrg_update_every(struct rrdeng_collect_handle *handle) {
  150. if(unlikely((time_t)(handle->update_every_ut / USEC_PER_SEC) != mrg_metric_get_update_every_s(main_mrg, handle->metric))) {
  151. internal_error(true, "DBENGINE: collection handle has update every %ld, but the metric registry has %ld. Fixing it.",
  152. (time_t)(handle->update_every_ut / USEC_PER_SEC), mrg_metric_get_update_every_s(main_mrg, handle->metric));
  153. if(unlikely(!handle->update_every_ut))
  154. handle->update_every_ut = (usec_t)mrg_metric_get_update_every_s(main_mrg, handle->metric) * USEC_PER_SEC;
  155. else
  156. mrg_metric_set_update_every(main_mrg, handle->metric, (time_t)(handle->update_every_ut / USEC_PER_SEC));
  157. }
  158. }
  159. static inline bool check_completed_page_consistency(struct rrdeng_collect_handle *handle __maybe_unused) {
  160. #ifdef NETDATA_INTERNAL_CHECKS
  161. if (unlikely(!handle->page || !handle->page_entries_max || !handle->page_position || !handle->page_end_time_ut))
  162. return false;
  163. struct rrdengine_instance *ctx = mrg_metric_ctx(handle->metric);
  164. uuid_t *uuid = mrg_metric_uuid(main_mrg, handle->metric);
  165. time_t start_time_s = pgc_page_start_time_s(handle->page);
  166. time_t end_time_s = pgc_page_end_time_s(handle->page);
  167. time_t update_every_s = pgc_page_update_every_s(handle->page);
  168. size_t page_length = handle->page_position * CTX_POINT_SIZE_BYTES(ctx);
  169. size_t entries = handle->page_position;
  170. time_t overwrite_zero_update_every_s = (time_t)(handle->update_every_ut / USEC_PER_SEC);
  171. if(end_time_s > max_acceptable_collected_time())
  172. handle->page_flags |= RRDENG_PAGE_COMPLETED_IN_FUTURE;
  173. VALIDATED_PAGE_DESCRIPTOR vd = validate_page(
  174. uuid,
  175. start_time_s,
  176. end_time_s,
  177. update_every_s,
  178. page_length,
  179. ctx->config.page_type,
  180. entries,
  181. 0, // do not check for future timestamps - we inherit the timestamps of the children
  182. overwrite_zero_update_every_s,
  183. false,
  184. "collected",
  185. handle->page_flags);
  186. return vd.is_valid;
  187. #else
  188. return true;
  189. #endif
  190. }
  191. /*
  192. * Gets a handle for storing metrics to the database.
  193. * The handle must be released with rrdeng_store_metric_final().
  194. */
  195. STORAGE_COLLECT_HANDLE *rrdeng_store_metric_init(STORAGE_METRIC_HANDLE *db_metric_handle, uint32_t update_every, STORAGE_METRICS_GROUP *smg) {
  196. METRIC *metric = (METRIC *)db_metric_handle;
  197. struct rrdengine_instance *ctx = mrg_metric_ctx(metric);
  198. bool is_1st_metric_writer = true;
  199. if(!mrg_metric_set_writer(main_mrg, metric)) {
  200. is_1st_metric_writer = false;
  201. char uuid[UUID_STR_LEN + 1];
  202. uuid_unparse(*mrg_metric_uuid(main_mrg, metric), uuid);
  203. error("DBENGINE: metric '%s' is already collected and should not be collected twice - expect gaps on the charts", uuid);
  204. }
  205. metric = mrg_metric_dup(main_mrg, metric);
  206. struct rrdeng_collect_handle *handle;
  207. handle = callocz(1, sizeof(struct rrdeng_collect_handle));
  208. handle->metric = metric;
  209. handle->page = NULL;
  210. handle->page_position = 0;
  211. handle->page_entries_max = 0;
  212. handle->update_every_ut = (usec_t)update_every * USEC_PER_SEC;
  213. handle->options = is_1st_metric_writer ? RRDENG_1ST_METRIC_WRITER : 0;
  214. __atomic_add_fetch(&ctx->atomic.collectors_running, 1, __ATOMIC_RELAXED);
  215. if(!is_1st_metric_writer)
  216. __atomic_add_fetch(&ctx->atomic.collectors_running_duplicate, 1, __ATOMIC_RELAXED);
  217. mrg_metric_set_update_every(main_mrg, metric, update_every);
  218. handle->alignment = (struct pg_alignment *)smg;
  219. rrdeng_page_alignment_acquire(handle->alignment);
  220. // this is important!
  221. // if we don't set the page_end_time_ut during the first collection
  222. // data collection may be able to go back in time and during the addition of new pages
  223. // clean pages may be found matching ours!
  224. time_t db_first_time_s, db_last_time_s, db_update_every_s;
  225. mrg_metric_get_retention(main_mrg, metric, &db_first_time_s, &db_last_time_s, &db_update_every_s);
  226. handle->page_end_time_ut = (usec_t)db_last_time_s * USEC_PER_SEC;
  227. return (STORAGE_COLLECT_HANDLE *)handle;
  228. }
  229. /* The page must be populated and referenced */
  230. static bool page_has_only_empty_metrics(struct rrdeng_collect_handle *handle) {
  231. switch(handle->type) {
  232. case PAGE_METRICS: {
  233. size_t slots = handle->page_position;
  234. storage_number *array = (storage_number *)pgc_page_data(handle->page);
  235. for (size_t i = 0 ; i < slots; ++i) {
  236. if(does_storage_number_exist(array[i]))
  237. return false;
  238. }
  239. }
  240. break;
  241. case PAGE_TIER: {
  242. size_t slots = handle->page_position;
  243. storage_number_tier1_t *array = (storage_number_tier1_t *)pgc_page_data(handle->page);
  244. for (size_t i = 0 ; i < slots; ++i) {
  245. if(fpclassify(array[i].sum_value) != FP_NAN)
  246. return false;
  247. }
  248. }
  249. break;
  250. default: {
  251. static bool logged = false;
  252. if(!logged) {
  253. error("DBENGINE: cannot check page for nulls on unknown page type id %d", (mrg_metric_ctx(handle->metric))->config.page_type);
  254. logged = true;
  255. }
  256. return false;
  257. }
  258. }
  259. return true;
  260. }
  261. void rrdeng_store_metric_flush_current_page(STORAGE_COLLECT_HANDLE *collection_handle) {
  262. struct rrdeng_collect_handle *handle = (struct rrdeng_collect_handle *)collection_handle;
  263. if (unlikely(!handle->page))
  264. return;
  265. if(!handle->page_position || page_has_only_empty_metrics(handle))
  266. pgc_page_to_clean_evict_or_release(main_cache, handle->page);
  267. else {
  268. check_completed_page_consistency(handle);
  269. mrg_metric_set_clean_latest_time_s(main_mrg, handle->metric, pgc_page_end_time_s(handle->page));
  270. pgc_page_hot_to_dirty_and_release(main_cache, handle->page);
  271. }
  272. mrg_metric_set_hot_latest_time_s(main_mrg, handle->metric, 0);
  273. handle->page = NULL;
  274. handle->page_flags = 0;
  275. handle->page_position = 0;
  276. handle->page_entries_max = 0;
  277. // important!
  278. // we should never zero page end time ut, because this will allow
  279. // collection to go back in time
  280. // handle->page_end_time_ut = 0;
  281. // handle->page_start_time_ut;
  282. check_and_fix_mrg_update_every(handle);
  283. }
  284. static void rrdeng_store_metric_create_new_page(struct rrdeng_collect_handle *handle,
  285. struct rrdengine_instance *ctx,
  286. usec_t point_in_time_ut,
  287. void *data,
  288. size_t data_size) {
  289. time_t point_in_time_s = (time_t)(point_in_time_ut / USEC_PER_SEC);
  290. const time_t update_every_s = (time_t)(handle->update_every_ut / USEC_PER_SEC);
  291. PGC_ENTRY page_entry = {
  292. .section = (Word_t) ctx,
  293. .metric_id = mrg_metric_id(main_mrg, handle->metric),
  294. .start_time_s = point_in_time_s,
  295. .end_time_s = point_in_time_s,
  296. .size = data_size,
  297. .data = data,
  298. .update_every_s = update_every_s,
  299. .hot = true
  300. };
  301. size_t conflicts = 0;
  302. bool added = true;
  303. PGC_PAGE *page = pgc_page_add_and_acquire(main_cache, page_entry, &added);
  304. while (unlikely(!added)) {
  305. conflicts++;
  306. char uuid[UUID_STR_LEN + 1];
  307. uuid_unparse(*mrg_metric_uuid(main_mrg, handle->metric), uuid);
  308. #ifdef NETDATA_INTERNAL_CHECKS
  309. internal_error(true,
  310. #else
  311. error_limit_static_global_var(erl, 1, 0);
  312. error_limit(&erl,
  313. #endif
  314. "DBENGINE: metric '%s' new page from %ld to %ld, update every %ld, has a conflict in main cache "
  315. "with existing %s%s page from %ld to %ld, update every %ld - "
  316. "is it collected more than once?",
  317. uuid,
  318. page_entry.start_time_s, page_entry.end_time_s, (time_t)page_entry.update_every_s,
  319. pgc_is_page_hot(page) ? "hot" : "not-hot",
  320. pgc_page_data(page) == DBENGINE_EMPTY_PAGE ? " gap" : "",
  321. pgc_page_start_time_s(page), pgc_page_end_time_s(page), pgc_page_update_every_s(page)
  322. );
  323. pgc_page_release(main_cache, page);
  324. point_in_time_ut -= handle->update_every_ut;
  325. point_in_time_s = (time_t)(point_in_time_ut / USEC_PER_SEC);
  326. page_entry.start_time_s = point_in_time_s;
  327. page_entry.end_time_s = point_in_time_s;
  328. page = pgc_page_add_and_acquire(main_cache, page_entry, &added);
  329. }
  330. handle->page_entries_max = data_size / CTX_POINT_SIZE_BYTES(ctx);
  331. handle->page_start_time_ut = point_in_time_ut;
  332. handle->page_end_time_ut = point_in_time_ut;
  333. handle->page_position = 1; // zero is already in our data
  334. handle->page = page;
  335. handle->page_flags = conflicts? RRDENG_PAGE_CONFLICT : 0;
  336. if(point_in_time_s > max_acceptable_collected_time())
  337. handle->page_flags |= RRDENG_PAGE_CREATED_IN_FUTURE;
  338. check_and_fix_mrg_update_every(handle);
  339. }
  340. static void *rrdeng_alloc_new_metric_data(struct rrdeng_collect_handle *handle, size_t *data_size, usec_t point_in_time_ut) {
  341. struct rrdengine_instance *ctx = mrg_metric_ctx(handle->metric);
  342. size_t size;
  343. if(handle->options & RRDENG_FIRST_PAGE_ALLOCATED) {
  344. // any page except the first
  345. size = tier_page_size[ctx->config.tier];
  346. }
  347. else {
  348. size_t final_slots = 0;
  349. // the first page
  350. handle->options |= RRDENG_FIRST_PAGE_ALLOCATED;
  351. size_t max_size = tier_page_size[ctx->config.tier];
  352. size_t max_slots = max_size / CTX_POINT_SIZE_BYTES(ctx);
  353. if(handle->alignment->initial_slots) {
  354. final_slots = handle->alignment->initial_slots;
  355. }
  356. else {
  357. max_slots -= 3;
  358. size_t smaller_slot = indexing_partition((Word_t)handle->alignment, max_slots);
  359. final_slots = smaller_slot;
  360. time_t now_s = (time_t)(point_in_time_ut / USEC_PER_SEC);
  361. size_t current_pos = (now_s % max_slots);
  362. if(current_pos > final_slots)
  363. final_slots += max_slots - current_pos;
  364. else if(current_pos < final_slots)
  365. final_slots -= current_pos;
  366. if(final_slots < 3) {
  367. final_slots += 3;
  368. smaller_slot += 3;
  369. if(smaller_slot >= max_slots)
  370. smaller_slot -= max_slots;
  371. }
  372. max_slots += 3;
  373. handle->alignment->initial_slots = smaller_slot + 3;
  374. internal_fatal(handle->alignment->initial_slots < 3 || handle->alignment->initial_slots >= max_slots, "ooops! wrong distribution of metrics across time");
  375. internal_fatal(final_slots < 3 || final_slots >= max_slots, "ooops! wrong distribution of metrics across time");
  376. }
  377. size = final_slots * CTX_POINT_SIZE_BYTES(ctx);
  378. }
  379. *data_size = size;
  380. return dbengine_page_alloc(size);
  381. }
  382. static void rrdeng_store_metric_append_point(STORAGE_COLLECT_HANDLE *collection_handle,
  383. const usec_t point_in_time_ut,
  384. const NETDATA_DOUBLE n,
  385. const NETDATA_DOUBLE min_value,
  386. const NETDATA_DOUBLE max_value,
  387. const uint16_t count,
  388. const uint16_t anomaly_count,
  389. const SN_FLAGS flags)
  390. {
  391. struct rrdeng_collect_handle *handle = (struct rrdeng_collect_handle *)collection_handle;
  392. struct rrdengine_instance *ctx = mrg_metric_ctx(handle->metric);
  393. bool perfect_page_alignment = false;
  394. void *data;
  395. size_t data_size;
  396. if(likely(handle->page)) {
  397. /* Make alignment decisions */
  398. if (handle->page_position == handle->alignment->page_position) {
  399. /* this is the leading dimension that defines chart alignment */
  400. perfect_page_alignment = true;
  401. }
  402. /* is the metric far enough out of alignment with the others? */
  403. if (unlikely(handle->page_position + 1 < handle->alignment->page_position))
  404. handle->options |= RRDENG_CHO_UNALIGNED;
  405. if (unlikely((handle->options & RRDENG_CHO_UNALIGNED) &&
  406. /* did the other metrics change page? */
  407. handle->alignment->page_position <= 1)) {
  408. handle->options &= ~RRDENG_CHO_UNALIGNED;
  409. handle->page_flags |= RRDENG_PAGE_UNALIGNED;
  410. rrdeng_store_metric_flush_current_page(collection_handle);
  411. data = rrdeng_alloc_new_metric_data(handle, &data_size, point_in_time_ut);
  412. }
  413. else {
  414. data = pgc_page_data(handle->page);
  415. data_size = pgc_page_data_size(main_cache, handle->page);
  416. }
  417. }
  418. else
  419. data = rrdeng_alloc_new_metric_data(handle, &data_size, point_in_time_ut);
  420. switch (ctx->config.page_type) {
  421. case PAGE_METRICS: {
  422. storage_number *tier0_metric_data = data;
  423. tier0_metric_data[handle->page_position] = pack_storage_number(n, flags);
  424. }
  425. break;
  426. case PAGE_TIER: {
  427. storage_number_tier1_t *tier12_metric_data = data;
  428. storage_number_tier1_t number_tier1;
  429. number_tier1.sum_value = (float)n;
  430. number_tier1.min_value = (float)min_value;
  431. number_tier1.max_value = (float)max_value;
  432. number_tier1.anomaly_count = anomaly_count;
  433. number_tier1.count = count;
  434. tier12_metric_data[handle->page_position] = number_tier1;
  435. }
  436. break;
  437. default: {
  438. static bool logged = false;
  439. if(!logged) {
  440. error("DBENGINE: cannot store metric on unknown page type id %d", ctx->config.page_type);
  441. logged = true;
  442. }
  443. }
  444. break;
  445. }
  446. if(unlikely(!handle->page)){
  447. rrdeng_store_metric_create_new_page(handle, ctx, point_in_time_ut, data, data_size);
  448. // handle->position is set to 1 already
  449. if (0 == handle->alignment->page_position) {
  450. /* this is the leading dimension that defines chart alignment */
  451. perfect_page_alignment = true;
  452. }
  453. }
  454. else {
  455. // update an existing page
  456. pgc_page_hot_set_end_time_s(main_cache, handle->page, (time_t) (point_in_time_ut / USEC_PER_SEC));
  457. handle->page_end_time_ut = point_in_time_ut;
  458. if(unlikely(++handle->page_position >= handle->page_entries_max)) {
  459. internal_fatal(handle->page_position > handle->page_entries_max, "DBENGINE: exceeded page max number of points");
  460. handle->page_flags |= RRDENG_PAGE_FULL;
  461. rrdeng_store_metric_flush_current_page(collection_handle);
  462. }
  463. }
  464. if (perfect_page_alignment)
  465. handle->alignment->page_position = handle->page_position;
  466. // update the metric information
  467. mrg_metric_set_hot_latest_time_s(main_mrg, handle->metric, (time_t) (point_in_time_ut / USEC_PER_SEC));
  468. }
  469. static void store_metric_next_error_log(struct rrdeng_collect_handle *handle, usec_t point_in_time_ut, const char *msg) {
  470. time_t point_in_time_s = (time_t)(point_in_time_ut / USEC_PER_SEC);
  471. char uuid[UUID_STR_LEN + 1];
  472. uuid_unparse(*mrg_metric_uuid(main_mrg, handle->metric), uuid);
  473. BUFFER *wb = NULL;
  474. if(handle->page && handle->page_flags) {
  475. wb = buffer_create(0, NULL);
  476. collect_page_flags_to_buffer(wb, handle->page_flags);
  477. }
  478. error_limit_static_global_var(erl, 1, 0);
  479. error_limit(&erl,
  480. "DBENGINE: metric '%s' collected point at %ld, %s last collection at %ld, "
  481. "update every %ld, %s page from %ld to %ld, position %u (of %u), flags: %s",
  482. uuid,
  483. point_in_time_s,
  484. msg,
  485. (time_t)(handle->page_end_time_ut / USEC_PER_SEC),
  486. (time_t)(handle->update_every_ut / USEC_PER_SEC),
  487. handle->page ? "current" : "*LAST*",
  488. (time_t)(handle->page_start_time_ut / USEC_PER_SEC),
  489. (time_t)(handle->page_end_time_ut / USEC_PER_SEC),
  490. handle->page_position, handle->page_entries_max,
  491. wb ? buffer_tostring(wb) : ""
  492. );
  493. buffer_free(wb);
  494. }
  495. void rrdeng_store_metric_next(STORAGE_COLLECT_HANDLE *collection_handle,
  496. const usec_t point_in_time_ut,
  497. const NETDATA_DOUBLE n,
  498. const NETDATA_DOUBLE min_value,
  499. const NETDATA_DOUBLE max_value,
  500. const uint16_t count,
  501. const uint16_t anomaly_count,
  502. const SN_FLAGS flags)
  503. {
  504. struct rrdeng_collect_handle *handle = (struct rrdeng_collect_handle *)collection_handle;
  505. #ifdef NETDATA_INTERNAL_CHECKS
  506. if(unlikely(point_in_time_ut > (usec_t)max_acceptable_collected_time() * USEC_PER_SEC))
  507. handle->page_flags |= RRDENG_PAGE_FUTURE_POINT;
  508. #endif
  509. if(likely(handle->page_end_time_ut + handle->update_every_ut == point_in_time_ut)) {
  510. // happy path
  511. ;
  512. }
  513. else if(unlikely(point_in_time_ut < handle->page_end_time_ut)) {
  514. handle->page_flags |= RRDENG_PAGE_PAST_COLLECTION;
  515. store_metric_next_error_log(handle, point_in_time_ut, "is older than the");
  516. return;
  517. }
  518. else if(unlikely(point_in_time_ut == handle->page_end_time_ut)) {
  519. handle->page_flags |= RRDENG_PAGE_REPEATED_COLLECTION;
  520. store_metric_next_error_log(handle, point_in_time_ut, "is at the same time as the");
  521. return;
  522. }
  523. else if(handle->page) {
  524. usec_t delta_ut = point_in_time_ut - handle->page_end_time_ut;
  525. if(unlikely(delta_ut < handle->update_every_ut)) {
  526. handle->page_flags |= RRDENG_PAGE_STEP_TOO_SMALL;
  527. rrdeng_store_metric_flush_current_page(collection_handle);
  528. }
  529. else if(unlikely(delta_ut % handle->update_every_ut)) {
  530. handle->page_flags |= RRDENG_PAGE_STEP_UNALIGNED;
  531. rrdeng_store_metric_flush_current_page(collection_handle);
  532. }
  533. else {
  534. size_t points_gap = delta_ut / handle->update_every_ut;
  535. size_t page_remaining_points = handle->page_entries_max - handle->page_position;
  536. if(points_gap >= page_remaining_points) {
  537. handle->page_flags |= RRDENG_PAGE_BIG_GAP;
  538. rrdeng_store_metric_flush_current_page(collection_handle);
  539. }
  540. else {
  541. // loop to fill the gap
  542. handle->page_flags |= RRDENG_PAGE_GAP;
  543. usec_t stop_ut = point_in_time_ut - handle->update_every_ut;
  544. for(usec_t this_ut = handle->page_end_time_ut + handle->update_every_ut;
  545. this_ut <= stop_ut ;
  546. this_ut = handle->page_end_time_ut + handle->update_every_ut) {
  547. rrdeng_store_metric_append_point(
  548. collection_handle,
  549. this_ut,
  550. NAN, NAN, NAN,
  551. 1, 0,
  552. SN_EMPTY_SLOT);
  553. }
  554. }
  555. }
  556. }
  557. rrdeng_store_metric_append_point(collection_handle,
  558. point_in_time_ut,
  559. n, min_value, max_value,
  560. count, anomaly_count,
  561. flags);
  562. }
  563. /*
  564. * Releases the database reference from the handle for storing metrics.
  565. * Returns 1 if it's safe to delete the dimension.
  566. */
  567. int rrdeng_store_metric_finalize(STORAGE_COLLECT_HANDLE *collection_handle) {
  568. struct rrdeng_collect_handle *handle = (struct rrdeng_collect_handle *)collection_handle;
  569. struct rrdengine_instance *ctx = mrg_metric_ctx(handle->metric);
  570. handle->page_flags |= RRDENG_PAGE_COLLECT_FINALIZE;
  571. rrdeng_store_metric_flush_current_page(collection_handle);
  572. rrdeng_page_alignment_release(handle->alignment);
  573. __atomic_sub_fetch(&ctx->atomic.collectors_running, 1, __ATOMIC_RELAXED);
  574. if(!(handle->options & RRDENG_1ST_METRIC_WRITER))
  575. __atomic_sub_fetch(&ctx->atomic.collectors_running_duplicate, 1, __ATOMIC_RELAXED);
  576. if((handle->options & RRDENG_1ST_METRIC_WRITER) && !mrg_metric_clear_writer(main_mrg, handle->metric))
  577. internal_fatal(true, "DBENGINE: metric is already released");
  578. time_t first_time_s, last_time_s, update_every_s;
  579. mrg_metric_get_retention(main_mrg, handle->metric, &first_time_s, &last_time_s, &update_every_s);
  580. mrg_metric_release(main_mrg, handle->metric);
  581. freez(handle);
  582. if(!first_time_s && !last_time_s)
  583. return 1;
  584. return 0;
  585. }
  586. void rrdeng_store_metric_change_collection_frequency(STORAGE_COLLECT_HANDLE *collection_handle, int update_every) {
  587. struct rrdeng_collect_handle *handle = (struct rrdeng_collect_handle *)collection_handle;
  588. check_and_fix_mrg_update_every(handle);
  589. METRIC *metric = handle->metric;
  590. usec_t update_every_ut = (usec_t)update_every * USEC_PER_SEC;
  591. if(update_every_ut == handle->update_every_ut)
  592. return;
  593. handle->page_flags |= RRDENG_PAGE_UPDATE_EVERY_CHANGE;
  594. rrdeng_store_metric_flush_current_page(collection_handle);
  595. mrg_metric_set_update_every(main_mrg, metric, update_every);
  596. handle->update_every_ut = update_every_ut;
  597. }
  598. // ----------------------------------------------------------------------------
  599. // query ops
  600. #ifdef NETDATA_INTERNAL_CHECKS
  601. SPINLOCK global_query_handle_spinlock = NETDATA_SPINLOCK_INITIALIZER;
  602. static struct rrdeng_query_handle *global_query_handle_ll = NULL;
  603. static void register_query_handle(struct rrdeng_query_handle *handle) {
  604. handle->query_pid = gettid();
  605. handle->started_time_s = now_realtime_sec();
  606. netdata_spinlock_lock(&global_query_handle_spinlock);
  607. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(global_query_handle_ll, handle, prev, next);
  608. netdata_spinlock_unlock(&global_query_handle_spinlock);
  609. }
  610. static void unregister_query_handle(struct rrdeng_query_handle *handle) {
  611. netdata_spinlock_lock(&global_query_handle_spinlock);
  612. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(global_query_handle_ll, handle, prev, next);
  613. netdata_spinlock_unlock(&global_query_handle_spinlock);
  614. }
  615. #else
  616. static void register_query_handle(struct rrdeng_query_handle *handle __maybe_unused) {
  617. ;
  618. }
  619. static void unregister_query_handle(struct rrdeng_query_handle *handle __maybe_unused) {
  620. ;
  621. }
  622. #endif
  623. /*
  624. * Gets a handle for loading metrics from the database.
  625. * The handle must be released with rrdeng_load_metric_final().
  626. */
  627. void rrdeng_load_metric_init(STORAGE_METRIC_HANDLE *db_metric_handle,
  628. struct storage_engine_query_handle *rrddim_handle,
  629. time_t start_time_s,
  630. time_t end_time_s,
  631. STORAGE_PRIORITY priority)
  632. {
  633. usec_t started_ut = now_monotonic_usec();
  634. netdata_thread_disable_cancelability();
  635. METRIC *metric = (METRIC *)db_metric_handle;
  636. struct rrdengine_instance *ctx = mrg_metric_ctx(metric);
  637. struct rrdeng_query_handle *handle;
  638. handle = rrdeng_query_handle_get();
  639. register_query_handle(handle);
  640. if(unlikely(priority < STORAGE_PRIORITY_HIGH))
  641. priority = STORAGE_PRIORITY_HIGH;
  642. else if(unlikely(priority > STORAGE_PRIORITY_BEST_EFFORT))
  643. priority = STORAGE_PRIORITY_BEST_EFFORT;
  644. handle->ctx = ctx;
  645. handle->metric = metric;
  646. handle->priority = priority;
  647. // IMPORTANT!
  648. // It is crucial not to exceed the db boundaries, because dbengine
  649. // now has gap caching, so when a gap is detected a negative page
  650. // is inserted into the main cache, to avoid scanning the journals
  651. // again for pages matching the gap.
  652. time_t db_first_time_s, db_last_time_s, db_update_every_s;
  653. mrg_metric_get_retention(main_mrg, metric, &db_first_time_s, &db_last_time_s, &db_update_every_s);
  654. if(is_page_in_time_range(start_time_s, end_time_s, db_first_time_s, db_last_time_s) == PAGE_IS_IN_RANGE) {
  655. handle->start_time_s = MAX(start_time_s, db_first_time_s);
  656. handle->end_time_s = MIN(end_time_s, db_last_time_s);
  657. handle->now_s = handle->start_time_s;
  658. handle->dt_s = db_update_every_s;
  659. if (!handle->dt_s) {
  660. handle->dt_s = default_rrd_update_every;
  661. mrg_metric_set_update_every_s_if_zero(main_mrg, metric, default_rrd_update_every);
  662. }
  663. rrddim_handle->handle = (STORAGE_QUERY_HANDLE *) handle;
  664. rrddim_handle->start_time_s = handle->start_time_s;
  665. rrddim_handle->end_time_s = handle->end_time_s;
  666. rrddim_handle->priority = priority;
  667. pg_cache_preload(handle);
  668. __atomic_add_fetch(&rrdeng_cache_efficiency_stats.query_time_init, now_monotonic_usec() - started_ut, __ATOMIC_RELAXED);
  669. }
  670. else {
  671. handle->start_time_s = start_time_s;
  672. handle->end_time_s = end_time_s;
  673. handle->now_s = start_time_s;
  674. handle->dt_s = db_update_every_s;
  675. rrddim_handle->handle = (STORAGE_QUERY_HANDLE *) handle;
  676. rrddim_handle->start_time_s = handle->start_time_s;
  677. rrddim_handle->end_time_s = 0;
  678. rrddim_handle->priority = priority;
  679. }
  680. }
  681. static bool rrdeng_load_page_next(struct storage_engine_query_handle *rrddim_handle, bool debug_this __maybe_unused) {
  682. struct rrdeng_query_handle *handle = (struct rrdeng_query_handle *)rrddim_handle->handle;
  683. struct rrdengine_instance *ctx = handle->ctx;
  684. if (likely(handle->page)) {
  685. // we have a page to release
  686. pgc_page_release(main_cache, handle->page);
  687. handle->page = NULL;
  688. }
  689. if (unlikely(handle->now_s > rrddim_handle->end_time_s))
  690. return false;
  691. size_t entries;
  692. handle->page = pg_cache_lookup_next(ctx, handle->pdc, handle->now_s, handle->dt_s, &entries);
  693. if (unlikely(!handle->page))
  694. return false;
  695. internal_fatal(pgc_page_data(handle->page) == DBENGINE_EMPTY_PAGE, "Empty page returned");
  696. time_t page_start_time_s = pgc_page_start_time_s(handle->page);
  697. time_t page_end_time_s = pgc_page_end_time_s(handle->page);
  698. time_t page_update_every_s = pgc_page_update_every_s(handle->page);
  699. unsigned position;
  700. if(likely(handle->now_s >= page_start_time_s && handle->now_s <= page_end_time_s)) {
  701. if(unlikely(entries == 1 || page_start_time_s == page_end_time_s || !page_update_every_s)) {
  702. position = 0;
  703. handle->now_s = page_start_time_s;
  704. }
  705. else {
  706. position = (handle->now_s - page_start_time_s) * (entries - 1) / (page_end_time_s - page_start_time_s);
  707. time_t point_end_time_s = page_start_time_s + position * page_update_every_s;
  708. while(point_end_time_s < handle->now_s && position + 1 < entries) {
  709. // https://github.com/netdata/netdata/issues/14411
  710. // we really need a while() here, because the delta may be
  711. // 2 points at higher tiers
  712. position++;
  713. point_end_time_s = page_start_time_s + position * page_update_every_s;
  714. }
  715. handle->now_s = point_end_time_s;
  716. }
  717. internal_fatal(position >= entries, "DBENGINE: wrong page position calculation");
  718. }
  719. else if(handle->now_s < page_start_time_s) {
  720. handle->now_s = page_start_time_s;
  721. position = 0;
  722. }
  723. else {
  724. internal_fatal(true, "DBENGINE: this page is entirely in our past and should not be accepted for this query in the first place");
  725. handle->now_s = page_end_time_s;
  726. position = entries - 1;
  727. }
  728. handle->entries = entries;
  729. handle->position = position;
  730. handle->metric_data = pgc_page_data((PGC_PAGE *)handle->page);
  731. handle->dt_s = page_update_every_s;
  732. return true;
  733. }
  734. // Returns the metric and sets its timestamp into current_time
  735. // IT IS REQUIRED TO **ALWAYS** SET ALL RETURN VALUES (current_time, end_time, flags)
  736. // IT IS REQUIRED TO **ALWAYS** KEEP TRACK OF TIME, EVEN OUTSIDE THE DATABASE BOUNDARIES
  737. STORAGE_POINT rrdeng_load_metric_next(struct storage_engine_query_handle *rrddim_handle) {
  738. struct rrdeng_query_handle *handle = (struct rrdeng_query_handle *)rrddim_handle->handle;
  739. STORAGE_POINT sp;
  740. if (unlikely(handle->now_s > rrddim_handle->end_time_s)) {
  741. storage_point_empty(sp, handle->now_s - handle->dt_s, handle->now_s);
  742. goto prepare_for_next_iteration;
  743. }
  744. if (unlikely(!handle->page || handle->position >= handle->entries)) {
  745. // We need to get a new page
  746. if (!rrdeng_load_page_next(rrddim_handle, false)) {
  747. storage_point_empty(sp, handle->now_s - handle->dt_s, handle->now_s);
  748. goto prepare_for_next_iteration;
  749. }
  750. }
  751. sp.start_time_s = handle->now_s - handle->dt_s;
  752. sp.end_time_s = handle->now_s;
  753. switch(handle->ctx->config.page_type) {
  754. case PAGE_METRICS: {
  755. storage_number n = handle->metric_data[handle->position];
  756. sp.min = sp.max = sp.sum = unpack_storage_number(n);
  757. sp.flags = n & SN_USER_FLAGS;
  758. sp.count = 1;
  759. sp.anomaly_count = is_storage_number_anomalous(n) ? 1 : 0;
  760. }
  761. break;
  762. case PAGE_TIER: {
  763. storage_number_tier1_t tier1_value = ((storage_number_tier1_t *)handle->metric_data)[handle->position];
  764. sp.flags = tier1_value.anomaly_count ? SN_FLAG_NONE : SN_FLAG_NOT_ANOMALOUS;
  765. sp.count = tier1_value.count;
  766. sp.anomaly_count = tier1_value.anomaly_count;
  767. sp.min = tier1_value.min_value;
  768. sp.max = tier1_value.max_value;
  769. sp.sum = tier1_value.sum_value;
  770. }
  771. break;
  772. // we don't know this page type
  773. default: {
  774. static bool logged = false;
  775. if(!logged) {
  776. error("DBENGINE: unknown page type %d found. Cannot decode it. Ignoring its metrics.", handle->ctx->config.page_type);
  777. logged = true;
  778. }
  779. storage_point_empty(sp, sp.start_time_s, sp.end_time_s);
  780. }
  781. break;
  782. }
  783. prepare_for_next_iteration:
  784. internal_fatal(sp.end_time_s < rrddim_handle->start_time_s, "DBENGINE: this point is too old for this query");
  785. internal_fatal(sp.end_time_s < handle->now_s, "DBENGINE: this point is too old for this point in time");
  786. handle->now_s += handle->dt_s;
  787. handle->position++;
  788. return sp;
  789. }
  790. int rrdeng_load_metric_is_finished(struct storage_engine_query_handle *rrddim_handle) {
  791. struct rrdeng_query_handle *handle = (struct rrdeng_query_handle *)rrddim_handle->handle;
  792. return (handle->now_s > rrddim_handle->end_time_s);
  793. }
  794. /*
  795. * Releases the database reference from the handle for loading metrics.
  796. */
  797. void rrdeng_load_metric_finalize(struct storage_engine_query_handle *rrddim_handle)
  798. {
  799. struct rrdeng_query_handle *handle = (struct rrdeng_query_handle *)rrddim_handle->handle;
  800. if (handle->page)
  801. pgc_page_release(main_cache, handle->page);
  802. if(!pdc_release_and_destroy_if_unreferenced(handle->pdc, false, false))
  803. __atomic_store_n(&handle->pdc->workers_should_stop, true, __ATOMIC_RELAXED);
  804. unregister_query_handle(handle);
  805. rrdeng_query_handle_release(handle);
  806. rrddim_handle->handle = NULL;
  807. netdata_thread_enable_cancelability();
  808. }
  809. time_t rrdeng_load_align_to_optimal_before(struct storage_engine_query_handle *rrddim_handle) {
  810. struct rrdeng_query_handle *handle = (struct rrdeng_query_handle *)rrddim_handle->handle;
  811. if(handle->pdc) {
  812. rrdeng_prep_wait(handle->pdc);
  813. if (handle->pdc->optimal_end_time_s > rrddim_handle->end_time_s)
  814. rrddim_handle->end_time_s = handle->pdc->optimal_end_time_s;
  815. }
  816. return rrddim_handle->end_time_s;
  817. }
  818. time_t rrdeng_metric_latest_time(STORAGE_METRIC_HANDLE *db_metric_handle) {
  819. METRIC *metric = (METRIC *)db_metric_handle;
  820. time_t latest_time_s = 0;
  821. if (metric)
  822. latest_time_s = mrg_metric_get_latest_time_s(main_mrg, metric);
  823. return latest_time_s;
  824. }
  825. time_t rrdeng_metric_oldest_time(STORAGE_METRIC_HANDLE *db_metric_handle) {
  826. METRIC *metric = (METRIC *)db_metric_handle;
  827. time_t oldest_time_s = 0;
  828. if (metric)
  829. oldest_time_s = mrg_metric_get_first_time_s(main_mrg, metric);
  830. return oldest_time_s;
  831. }
  832. bool rrdeng_metric_retention_by_uuid(STORAGE_INSTANCE *db_instance, uuid_t *dim_uuid, time_t *first_entry_s, time_t *last_entry_s)
  833. {
  834. struct rrdengine_instance *ctx = (struct rrdengine_instance *)db_instance;
  835. if (unlikely(!ctx)) {
  836. error("DBENGINE: invalid STORAGE INSTANCE to %s()", __FUNCTION__);
  837. return false;
  838. }
  839. METRIC *metric = mrg_metric_get_and_acquire(main_mrg, dim_uuid, (Word_t) ctx);
  840. if (unlikely(!metric))
  841. return false;
  842. time_t update_every_s;
  843. mrg_metric_get_retention(main_mrg, metric, first_entry_s, last_entry_s, &update_every_s);
  844. mrg_metric_release(main_mrg, metric);
  845. return true;
  846. }
  847. /*
  848. * Gathers Database Engine statistics.
  849. * Careful when modifying this function.
  850. * You must not change the indices of the statistics or user code will break.
  851. * You must not exceed RRDENG_NR_STATS or it will crash.
  852. */
  853. void rrdeng_get_37_statistics(struct rrdengine_instance *ctx, unsigned long long *array)
  854. {
  855. if (ctx == NULL)
  856. return;
  857. array[0] = (uint64_t)__atomic_load_n(&ctx->atomic.collectors_running, __ATOMIC_RELAXED); // API producers
  858. array[1] = (uint64_t)__atomic_load_n(&ctx->atomic.inflight_queries, __ATOMIC_RELAXED); // API consumers
  859. array[2] = 0;
  860. array[3] = 0;
  861. array[4] = 0;
  862. array[5] = 0; // (uint64_t)ctx->stats.pg_cache_insertions;
  863. array[6] = 0; // (uint64_t)ctx->stats.pg_cache_deletions;
  864. array[7] = 0; // (uint64_t)ctx->stats.pg_cache_hits;
  865. array[8] = 0; // (uint64_t)ctx->stats.pg_cache_misses;
  866. array[9] = 0; // (uint64_t)ctx->stats.pg_cache_backfills;
  867. array[10] = 0; // (uint64_t)ctx->stats.pg_cache_evictions;
  868. array[11] = (uint64_t)__atomic_load_n(&ctx->stats.before_compress_bytes, __ATOMIC_RELAXED); // used
  869. array[12] = (uint64_t)__atomic_load_n(&ctx->stats.after_compress_bytes, __ATOMIC_RELAXED); // used
  870. array[13] = (uint64_t)__atomic_load_n(&ctx->stats.before_decompress_bytes, __ATOMIC_RELAXED);
  871. array[14] = (uint64_t)__atomic_load_n(&ctx->stats.after_decompress_bytes, __ATOMIC_RELAXED);
  872. array[15] = (uint64_t)__atomic_load_n(&ctx->stats.io_write_bytes, __ATOMIC_RELAXED); // used
  873. array[16] = (uint64_t)__atomic_load_n(&ctx->stats.io_write_requests, __ATOMIC_RELAXED); // used
  874. array[17] = (uint64_t)__atomic_load_n(&ctx->stats.io_read_bytes, __ATOMIC_RELAXED);
  875. array[18] = (uint64_t)__atomic_load_n(&ctx->stats.io_read_requests, __ATOMIC_RELAXED); // used
  876. array[19] = 0; // (uint64_t)__atomic_load_n(&ctx->stats.io_write_extent_bytes, __ATOMIC_RELAXED);
  877. array[20] = 0; // (uint64_t)__atomic_load_n(&ctx->stats.io_write_extents, __ATOMIC_RELAXED);
  878. array[21] = 0; // (uint64_t)__atomic_load_n(&ctx->stats.io_read_extent_bytes, __ATOMIC_RELAXED);
  879. array[22] = 0; // (uint64_t)__atomic_load_n(&ctx->stats.io_read_extents, __ATOMIC_RELAXED);
  880. array[23] = (uint64_t)__atomic_load_n(&ctx->stats.datafile_creations, __ATOMIC_RELAXED);
  881. array[24] = (uint64_t)__atomic_load_n(&ctx->stats.datafile_deletions, __ATOMIC_RELAXED);
  882. array[25] = (uint64_t)__atomic_load_n(&ctx->stats.journalfile_creations, __ATOMIC_RELAXED);
  883. array[26] = (uint64_t)__atomic_load_n(&ctx->stats.journalfile_deletions, __ATOMIC_RELAXED);
  884. array[27] = 0; // (uint64_t)__atomic_load_n(&ctx->stats.page_cache_descriptors, __ATOMIC_RELAXED);
  885. array[28] = (uint64_t)__atomic_load_n(&ctx->stats.io_errors, __ATOMIC_RELAXED);
  886. array[29] = (uint64_t)__atomic_load_n(&ctx->stats.fs_errors, __ATOMIC_RELAXED);
  887. array[30] = (uint64_t)__atomic_load_n(&global_io_errors, __ATOMIC_RELAXED); // used
  888. array[31] = (uint64_t)__atomic_load_n(&global_fs_errors, __ATOMIC_RELAXED); // used
  889. array[32] = (uint64_t)__atomic_load_n(&rrdeng_reserved_file_descriptors, __ATOMIC_RELAXED); // used
  890. array[33] = 0; // (uint64_t)__atomic_load_n(&ctx->stats.pg_cache_over_half_dirty_events, __ATOMIC_RELAXED);
  891. array[34] = (uint64_t)__atomic_load_n(&global_pg_cache_over_half_dirty_events, __ATOMIC_RELAXED); // used
  892. array[35] = 0; // (uint64_t)__atomic_load_n(&ctx->stats.flushing_pressure_page_deletions, __ATOMIC_RELAXED);
  893. array[36] = (uint64_t)__atomic_load_n(&global_flushing_pressure_page_deletions, __ATOMIC_RELAXED); // used
  894. array[37] = 0; //(uint64_t)pg_cache->active_descriptors;
  895. fatal_assert(RRDENG_NR_STATS == 38);
  896. }
  897. static void rrdeng_populate_mrg(struct rrdengine_instance *ctx) {
  898. uv_rwlock_rdlock(&ctx->datafiles.rwlock);
  899. size_t datafiles = 0;
  900. for(struct rrdengine_datafile *df = ctx->datafiles.first; df ;df = df->next)
  901. datafiles++;
  902. uv_rwlock_rdunlock(&ctx->datafiles.rwlock);
  903. size_t cpus = get_netdata_cpus() / storage_tiers;
  904. if(cpus > datafiles)
  905. cpus = datafiles;
  906. if(cpus < 1)
  907. cpus = 1;
  908. if(cpus > (size_t)libuv_worker_threads)
  909. cpus = (size_t)libuv_worker_threads;
  910. if(cpus > MRG_PARTITIONS)
  911. cpus = MRG_PARTITIONS;
  912. info("DBENGINE: populating retention to MRG from %zu journal files of tier %d, using %zu threads...", datafiles, ctx->config.tier, cpus);
  913. if(datafiles > 2) {
  914. struct rrdengine_datafile *datafile;
  915. datafile = ctx->datafiles.first->prev;
  916. if(!(datafile->journalfile->v2.flags & JOURNALFILE_FLAG_IS_AVAILABLE))
  917. datafile = datafile->prev;
  918. if(datafile->journalfile->v2.flags & JOURNALFILE_FLAG_IS_AVAILABLE) {
  919. journalfile_v2_populate_retention_to_mrg(ctx, datafile->journalfile);
  920. datafile->populate_mrg.populated = true;
  921. }
  922. datafile = ctx->datafiles.first;
  923. if(datafile->journalfile->v2.flags & JOURNALFILE_FLAG_IS_AVAILABLE) {
  924. journalfile_v2_populate_retention_to_mrg(ctx, datafile->journalfile);
  925. datafile->populate_mrg.populated = true;
  926. }
  927. }
  928. ctx->loading.populate_mrg.size = cpus;
  929. ctx->loading.populate_mrg.array = callocz(ctx->loading.populate_mrg.size, sizeof(struct completion));
  930. for (size_t i = 0; i < ctx->loading.populate_mrg.size; i++) {
  931. completion_init(&ctx->loading.populate_mrg.array[i]);
  932. rrdeng_enq_cmd(ctx, RRDENG_OPCODE_CTX_POPULATE_MRG, NULL, &ctx->loading.populate_mrg.array[i],
  933. STORAGE_PRIORITY_INTERNAL_DBENGINE, NULL, NULL);
  934. }
  935. }
  936. void rrdeng_readiness_wait(struct rrdengine_instance *ctx) {
  937. for (size_t i = 0; i < ctx->loading.populate_mrg.size; i++) {
  938. completion_wait_for(&ctx->loading.populate_mrg.array[i]);
  939. completion_destroy(&ctx->loading.populate_mrg.array[i]);
  940. }
  941. freez(ctx->loading.populate_mrg.array);
  942. ctx->loading.populate_mrg.array = NULL;
  943. ctx->loading.populate_mrg.size = 0;
  944. info("DBENGINE: tier %d is ready for data collection and queries", ctx->config.tier);
  945. }
  946. bool rrdeng_is_legacy(STORAGE_INSTANCE *db_instance) {
  947. struct rrdengine_instance *ctx = (struct rrdengine_instance *)db_instance;
  948. return ctx->config.legacy;
  949. }
  950. void rrdeng_exit_mode(struct rrdengine_instance *ctx) {
  951. __atomic_store_n(&ctx->quiesce.exit_mode, true, __ATOMIC_RELAXED);
  952. }
  953. /*
  954. * Returns 0 on success, negative on error
  955. */
  956. int rrdeng_init(struct rrdengine_instance **ctxp, const char *dbfiles_path,
  957. unsigned disk_space_mb, size_t tier) {
  958. struct rrdengine_instance *ctx;
  959. uint32_t max_open_files;
  960. max_open_files = rlimit_nofile.rlim_cur / 4;
  961. /* reserve RRDENG_FD_BUDGET_PER_INSTANCE file descriptors for this instance */
  962. rrd_stat_atomic_add(&rrdeng_reserved_file_descriptors, RRDENG_FD_BUDGET_PER_INSTANCE);
  963. if (rrdeng_reserved_file_descriptors > max_open_files) {
  964. error(
  965. "Exceeded the budget of available file descriptors (%u/%u), cannot create new dbengine instance.",
  966. (unsigned)rrdeng_reserved_file_descriptors,
  967. (unsigned)max_open_files);
  968. rrd_stat_atomic_add(&global_fs_errors, 1);
  969. rrd_stat_atomic_add(&rrdeng_reserved_file_descriptors, -RRDENG_FD_BUDGET_PER_INSTANCE);
  970. return UV_EMFILE;
  971. }
  972. if(NULL == ctxp) {
  973. ctx = multidb_ctx[tier];
  974. memset(ctx, 0, sizeof(*ctx));
  975. ctx->config.legacy = false;
  976. }
  977. else {
  978. *ctxp = ctx = callocz(1, sizeof(*ctx));
  979. ctx->config.legacy = true;
  980. }
  981. ctx->config.tier = (int)tier;
  982. ctx->config.page_type = tier_page_type[tier];
  983. ctx->config.global_compress_alg = RRD_LZ4;
  984. if (disk_space_mb < RRDENG_MIN_DISK_SPACE_MB)
  985. disk_space_mb = RRDENG_MIN_DISK_SPACE_MB;
  986. ctx->config.max_disk_space = disk_space_mb * 1048576LLU;
  987. strncpyz(ctx->config.dbfiles_path, dbfiles_path, sizeof(ctx->config.dbfiles_path) - 1);
  988. ctx->config.dbfiles_path[sizeof(ctx->config.dbfiles_path) - 1] = '\0';
  989. ctx->atomic.transaction_id = 1;
  990. ctx->quiesce.enabled = false;
  991. if (rrdeng_dbengine_spawn(ctx) && !init_rrd_files(ctx)) {
  992. // success - we run this ctx too
  993. rrdeng_populate_mrg(ctx);
  994. return 0;
  995. }
  996. if (ctx->config.legacy) {
  997. freez(ctx);
  998. if (ctxp)
  999. *ctxp = NULL;
  1000. }
  1001. rrd_stat_atomic_add(&rrdeng_reserved_file_descriptors, -RRDENG_FD_BUDGET_PER_INSTANCE);
  1002. return UV_EIO;
  1003. }
  1004. size_t rrdeng_collectors_running(struct rrdengine_instance *ctx) {
  1005. return __atomic_load_n(&ctx->atomic.collectors_running, __ATOMIC_RELAXED);
  1006. }
  1007. /*
  1008. * Returns 0 on success, 1 on error
  1009. */
  1010. int rrdeng_exit(struct rrdengine_instance *ctx) {
  1011. if (NULL == ctx)
  1012. return 1;
  1013. // FIXME - ktsaou - properly cleanup ctx
  1014. // 1. make sure all collectors are stopped
  1015. // 2. make new queries will not be accepted (this is quiesce that has already run)
  1016. // 3. flush this section of the main cache
  1017. // 4. then wait for completion
  1018. bool logged = false;
  1019. while(__atomic_load_n(&ctx->atomic.collectors_running, __ATOMIC_RELAXED) && !unittest_running) {
  1020. if(!logged) {
  1021. info("DBENGINE: waiting for collectors to finish on tier %d...", (ctx->config.legacy) ? -1 : ctx->config.tier);
  1022. logged = true;
  1023. }
  1024. sleep_usec(100 * USEC_PER_MS);
  1025. }
  1026. info("DBENGINE: flushing main cache for tier %d", (ctx->config.legacy) ? -1 : ctx->config.tier);
  1027. pgc_flush_all_hot_and_dirty_pages(main_cache, (Word_t)ctx);
  1028. info("DBENGINE: shutting down tier %d", (ctx->config.legacy) ? -1 : ctx->config.tier);
  1029. struct completion completion = {};
  1030. completion_init(&completion);
  1031. rrdeng_enq_cmd(ctx, RRDENG_OPCODE_CTX_SHUTDOWN, NULL, &completion, STORAGE_PRIORITY_BEST_EFFORT, NULL, NULL);
  1032. completion_wait_for(&completion);
  1033. completion_destroy(&completion);
  1034. finalize_rrd_files(ctx);
  1035. if(ctx->config.legacy)
  1036. freez(ctx);
  1037. rrd_stat_atomic_add(&rrdeng_reserved_file_descriptors, -RRDENG_FD_BUDGET_PER_INSTANCE);
  1038. return 0;
  1039. }
  1040. void rrdeng_prepare_exit(struct rrdengine_instance *ctx) {
  1041. if (NULL == ctx)
  1042. return;
  1043. // FIXME - ktsaou - properly cleanup ctx
  1044. // 1. make sure all collectors are stopped
  1045. completion_init(&ctx->quiesce.completion);
  1046. rrdeng_enq_cmd(ctx, RRDENG_OPCODE_CTX_QUIESCE, NULL, NULL, STORAGE_PRIORITY_INTERNAL_DBENGINE, NULL, NULL);
  1047. }
  1048. static void populate_v2_statistics(struct rrdengine_datafile *datafile, RRDENG_SIZE_STATS *stats)
  1049. {
  1050. struct journal_v2_header *j2_header = journalfile_v2_data_acquire(datafile->journalfile, NULL, 0, 0);
  1051. void *data_start = (void *)j2_header;
  1052. if(unlikely(!j2_header))
  1053. return;
  1054. stats->extents += j2_header->extent_count;
  1055. unsigned entries;
  1056. struct journal_extent_list *extent_list = (void *) (data_start + j2_header->extent_offset);
  1057. for (entries = 0; entries < j2_header->extent_count; entries++) {
  1058. stats->extents_compressed_bytes += extent_list->datafile_size;
  1059. stats->extents_pages += extent_list->pages;
  1060. extent_list++;
  1061. }
  1062. struct journal_metric_list *metric = (void *) (data_start + j2_header->metric_offset);
  1063. time_t journal_start_time_s = (time_t) (j2_header->start_time_ut / USEC_PER_SEC);
  1064. stats->metrics += j2_header->metric_count;
  1065. for (entries = 0; entries < j2_header->metric_count; entries++) {
  1066. struct journal_page_header *metric_list_header = (void *) (data_start + metric->page_offset);
  1067. stats->metrics_pages += metric_list_header->entries;
  1068. struct journal_page_list *descr = (void *) (data_start + metric->page_offset + sizeof(struct journal_page_header));
  1069. for (uint32_t idx=0; idx < metric_list_header->entries; idx++) {
  1070. time_t update_every_s;
  1071. size_t points = descr->page_length / CTX_POINT_SIZE_BYTES(datafile->ctx);
  1072. time_t start_time_s = journal_start_time_s + descr->delta_start_s;
  1073. time_t end_time_s = journal_start_time_s + descr->delta_end_s;
  1074. if(likely(points > 1))
  1075. update_every_s = (time_t) ((end_time_s - start_time_s) / (points - 1));
  1076. else {
  1077. update_every_s = (time_t) (default_rrd_update_every * get_tier_grouping(datafile->ctx->config.tier));
  1078. stats->single_point_pages++;
  1079. }
  1080. time_t duration_s = (time_t)((end_time_s - start_time_s + update_every_s));
  1081. stats->pages_uncompressed_bytes += descr->page_length;
  1082. stats->pages_duration_secs += duration_s;
  1083. stats->points += points;
  1084. stats->page_types[descr->type].pages++;
  1085. stats->page_types[descr->type].pages_uncompressed_bytes += descr->page_length;
  1086. stats->page_types[descr->type].pages_duration_secs += duration_s;
  1087. stats->page_types[descr->type].points += points;
  1088. if(!stats->first_time_s || (start_time_s - update_every_s) < stats->first_time_s)
  1089. stats->first_time_s = (start_time_s - update_every_s);
  1090. if(!stats->last_time_s || end_time_s > stats->last_time_s)
  1091. stats->last_time_s = end_time_s;
  1092. descr++;
  1093. }
  1094. metric++;
  1095. }
  1096. journalfile_v2_data_release(datafile->journalfile);
  1097. }
  1098. RRDENG_SIZE_STATS rrdeng_size_statistics(struct rrdengine_instance *ctx) {
  1099. RRDENG_SIZE_STATS stats = { 0 };
  1100. uv_rwlock_rdlock(&ctx->datafiles.rwlock);
  1101. for(struct rrdengine_datafile *df = ctx->datafiles.first; df ;df = df->next) {
  1102. stats.datafiles++;
  1103. populate_v2_statistics(df, &stats);
  1104. }
  1105. uv_rwlock_rdunlock(&ctx->datafiles.rwlock);
  1106. stats.currently_collected_metrics = __atomic_load_n(&ctx->atomic.collectors_running, __ATOMIC_RELAXED);
  1107. internal_error(stats.metrics_pages != stats.extents_pages + stats.currently_collected_metrics,
  1108. "DBENGINE: metrics pages is %zu, but extents pages is %zu and API consumers is %zu",
  1109. stats.metrics_pages, stats.extents_pages, stats.currently_collected_metrics);
  1110. stats.disk_space = ctx_current_disk_space_get(ctx);
  1111. stats.max_disk_space = ctx->config.max_disk_space;
  1112. stats.database_retention_secs = (time_t)(stats.last_time_s - stats.first_time_s);
  1113. if(stats.extents_pages)
  1114. stats.average_page_size_bytes = (double)stats.pages_uncompressed_bytes / (double)stats.extents_pages;
  1115. if(stats.pages_uncompressed_bytes > 0)
  1116. stats.average_compression_savings = 100.0 - ((double)stats.extents_compressed_bytes * 100.0 / (double)stats.pages_uncompressed_bytes);
  1117. if(stats.points)
  1118. stats.average_point_duration_secs = (double)stats.pages_duration_secs / (double)stats.points;
  1119. if(stats.metrics) {
  1120. stats.average_metric_retention_secs = (double)stats.pages_duration_secs / (double)stats.metrics;
  1121. if(stats.database_retention_secs) {
  1122. double metric_coverage = stats.average_metric_retention_secs / (double)stats.database_retention_secs;
  1123. double db_retention_days = (double)stats.database_retention_secs / 86400.0;
  1124. stats.estimated_concurrently_collected_metrics = stats.metrics * metric_coverage;
  1125. stats.ephemeral_metrics_per_day_percent = ((double)stats.metrics * 100.0 / (double)stats.estimated_concurrently_collected_metrics - 100.0) / (double)db_retention_days;
  1126. }
  1127. }
  1128. // stats.sizeof_metric = 0;
  1129. stats.sizeof_datafile = struct_natural_alignment(sizeof(struct rrdengine_datafile)) + struct_natural_alignment(sizeof(struct rrdengine_journalfile));
  1130. stats.sizeof_page_in_cache = 0; // struct_natural_alignment(sizeof(struct page_cache_descr));
  1131. stats.sizeof_point_data = page_type_size[ctx->config.page_type];
  1132. stats.sizeof_page_data = tier_page_size[ctx->config.tier];
  1133. stats.pages_per_extent = rrdeng_pages_per_extent;
  1134. // stats.sizeof_metric_in_index = 40;
  1135. // stats.sizeof_page_in_index = 24;
  1136. stats.default_granularity_secs = (size_t)default_rrd_update_every * get_tier_grouping(ctx->config.tier);
  1137. return stats;
  1138. }
  1139. struct rrdeng_cache_efficiency_stats rrdeng_get_cache_efficiency_stats(void) {
  1140. // FIXME - make cache efficiency stats atomic
  1141. return rrdeng_cache_efficiency_stats;
  1142. }