rrdengineapi.c 55 KB

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