rrdengine.c 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #define NETDATA_RRD_INTERNALS
  3. #include "rrdengine.h"
  4. #include "pdc.h"
  5. rrdeng_stats_t global_io_errors = 0;
  6. rrdeng_stats_t global_fs_errors = 0;
  7. rrdeng_stats_t rrdeng_reserved_file_descriptors = 0;
  8. rrdeng_stats_t global_pg_cache_over_half_dirty_events = 0;
  9. rrdeng_stats_t global_flushing_pressure_page_deletions = 0;
  10. unsigned rrdeng_pages_per_extent = MAX_PAGES_PER_EXTENT;
  11. #if WORKER_UTILIZATION_MAX_JOB_TYPES < (RRDENG_OPCODE_MAX + 2)
  12. #error Please increase WORKER_UTILIZATION_MAX_JOB_TYPES to at least (RRDENG_MAX_OPCODE + 2)
  13. #endif
  14. struct rrdeng_cmd {
  15. struct rrdengine_instance *ctx;
  16. enum rrdeng_opcode opcode;
  17. void *data;
  18. struct completion *completion;
  19. enum storage_priority priority;
  20. dequeue_callback_t dequeue_cb;
  21. struct {
  22. struct rrdeng_cmd *prev;
  23. struct rrdeng_cmd *next;
  24. } queue;
  25. };
  26. static inline struct rrdeng_cmd rrdeng_deq_cmd(bool from_worker);
  27. static inline void worker_dispatch_extent_read(struct rrdeng_cmd cmd, bool from_worker);
  28. static inline void worker_dispatch_query_prep(struct rrdeng_cmd cmd, bool from_worker);
  29. struct rrdeng_main {
  30. uv_thread_t thread;
  31. uv_loop_t loop;
  32. uv_async_t async;
  33. uv_timer_t timer;
  34. pid_t tid;
  35. size_t flushes_running;
  36. size_t evictions_running;
  37. size_t cleanup_running;
  38. struct {
  39. ARAL *ar;
  40. struct {
  41. SPINLOCK spinlock;
  42. size_t waiting;
  43. struct rrdeng_cmd *waiting_items_by_priority[STORAGE_PRIORITY_INTERNAL_MAX_DONT_USE];
  44. size_t executed_by_priority[STORAGE_PRIORITY_INTERNAL_MAX_DONT_USE];
  45. } unsafe;
  46. } cmd_queue;
  47. struct {
  48. ARAL *ar;
  49. struct {
  50. size_t dispatched;
  51. size_t executing;
  52. } atomics;
  53. } work_cmd;
  54. struct {
  55. ARAL *ar;
  56. } handles;
  57. struct {
  58. ARAL *ar;
  59. } descriptors;
  60. struct {
  61. ARAL *ar;
  62. } xt_io_descr;
  63. } rrdeng_main = {
  64. .thread = 0,
  65. .loop = {},
  66. .async = {},
  67. .timer = {},
  68. .flushes_running = 0,
  69. .evictions_running = 0,
  70. .cleanup_running = 0,
  71. .cmd_queue = {
  72. .unsafe = {
  73. .spinlock = NETDATA_SPINLOCK_INITIALIZER,
  74. },
  75. }
  76. };
  77. static void sanity_check(void)
  78. {
  79. BUILD_BUG_ON(WORKER_UTILIZATION_MAX_JOB_TYPES < (RRDENG_OPCODE_MAX + 2));
  80. /* Magic numbers must fit in the super-blocks */
  81. BUILD_BUG_ON(strlen(RRDENG_DF_MAGIC) > RRDENG_MAGIC_SZ);
  82. BUILD_BUG_ON(strlen(RRDENG_JF_MAGIC) > RRDENG_MAGIC_SZ);
  83. /* Version strings must fit in the super-blocks */
  84. BUILD_BUG_ON(strlen(RRDENG_DF_VER) > RRDENG_VER_SZ);
  85. BUILD_BUG_ON(strlen(RRDENG_JF_VER) > RRDENG_VER_SZ);
  86. /* Data file super-block cannot be larger than RRDENG_BLOCK_SIZE */
  87. BUILD_BUG_ON(RRDENG_DF_SB_PADDING_SZ < 0);
  88. BUILD_BUG_ON(sizeof(uuid_t) != UUID_SZ); /* check UUID size */
  89. /* page count must fit in 8 bits */
  90. BUILD_BUG_ON(MAX_PAGES_PER_EXTENT > 255);
  91. /* extent cache count must fit in 32 bits */
  92. // BUILD_BUG_ON(MAX_CACHED_EXTENTS > 32);
  93. /* page info scratch space must be able to hold 2 32-bit integers */
  94. BUILD_BUG_ON(sizeof(((struct rrdeng_page_info *)0)->scratch) < 2 * sizeof(uint32_t));
  95. }
  96. // ----------------------------------------------------------------------------
  97. // work request cache
  98. typedef void *(*work_cb)(struct rrdengine_instance *ctx, void *data, struct completion *completion, uv_work_t* req);
  99. typedef void (*after_work_cb)(struct rrdengine_instance *ctx, void *data, struct completion *completion, uv_work_t* req, int status);
  100. struct rrdeng_work {
  101. uv_work_t req;
  102. struct rrdengine_instance *ctx;
  103. void *data;
  104. struct completion *completion;
  105. work_cb work_cb;
  106. after_work_cb after_work_cb;
  107. enum rrdeng_opcode opcode;
  108. };
  109. static void work_request_init(void) {
  110. rrdeng_main.work_cmd.ar = aral_create(
  111. "dbengine-work-cmd",
  112. sizeof(struct rrdeng_work),
  113. 0,
  114. 65536, NULL,
  115. NULL, NULL, false, false
  116. );
  117. }
  118. enum LIBUV_WORKERS_STATUS {
  119. LIBUV_WORKERS_RELAXED,
  120. LIBUV_WORKERS_STRESSED,
  121. LIBUV_WORKERS_CRITICAL,
  122. };
  123. static inline enum LIBUV_WORKERS_STATUS work_request_full(void) {
  124. size_t dispatched = __atomic_load_n(&rrdeng_main.work_cmd.atomics.dispatched, __ATOMIC_RELAXED);
  125. if(dispatched >= (size_t)(libuv_worker_threads))
  126. return LIBUV_WORKERS_CRITICAL;
  127. else if(dispatched >= (size_t)(libuv_worker_threads - RESERVED_LIBUV_WORKER_THREADS))
  128. return LIBUV_WORKERS_STRESSED;
  129. return LIBUV_WORKERS_RELAXED;
  130. }
  131. static inline void work_done(struct rrdeng_work *work_request) {
  132. aral_freez(rrdeng_main.work_cmd.ar, work_request);
  133. }
  134. static void work_standard_worker(uv_work_t *req) {
  135. __atomic_add_fetch(&rrdeng_main.work_cmd.atomics.executing, 1, __ATOMIC_RELAXED);
  136. register_libuv_worker_jobs();
  137. worker_is_busy(UV_EVENT_WORKER_INIT);
  138. struct rrdeng_work *work_request = req->data;
  139. work_request->data = work_request->work_cb(work_request->ctx, work_request->data, work_request->completion, req);
  140. worker_is_idle();
  141. if(work_request->opcode == RRDENG_OPCODE_EXTENT_READ || work_request->opcode == RRDENG_OPCODE_QUERY) {
  142. internal_fatal(work_request->after_work_cb != NULL, "DBENGINE: opcodes with a callback should not boosted");
  143. while(1) {
  144. struct rrdeng_cmd cmd = rrdeng_deq_cmd(true);
  145. if (cmd.opcode == RRDENG_OPCODE_NOOP)
  146. break;
  147. worker_is_busy(UV_EVENT_WORKER_INIT);
  148. switch (cmd.opcode) {
  149. case RRDENG_OPCODE_EXTENT_READ:
  150. worker_dispatch_extent_read(cmd, true);
  151. break;
  152. case RRDENG_OPCODE_QUERY:
  153. worker_dispatch_query_prep(cmd, true);
  154. break;
  155. default:
  156. fatal("DBENGINE: Opcode should not be executed synchronously");
  157. break;
  158. }
  159. worker_is_idle();
  160. }
  161. }
  162. __atomic_sub_fetch(&rrdeng_main.work_cmd.atomics.dispatched, 1, __ATOMIC_RELAXED);
  163. __atomic_sub_fetch(&rrdeng_main.work_cmd.atomics.executing, 1, __ATOMIC_RELAXED);
  164. // signal the event loop a worker is available
  165. fatal_assert(0 == uv_async_send(&rrdeng_main.async));
  166. }
  167. static void after_work_standard_callback(uv_work_t* req, int status) {
  168. struct rrdeng_work *work_request = req->data;
  169. worker_is_busy(RRDENG_OPCODE_MAX + work_request->opcode);
  170. if(work_request->after_work_cb)
  171. work_request->after_work_cb(work_request->ctx, work_request->data, work_request->completion, req, status);
  172. work_done(work_request);
  173. worker_is_idle();
  174. }
  175. static bool work_dispatch(struct rrdengine_instance *ctx, void *data, struct completion *completion, enum rrdeng_opcode opcode, work_cb work_cb, after_work_cb after_work_cb) {
  176. struct rrdeng_work *work_request = NULL;
  177. internal_fatal(rrdeng_main.tid != gettid(), "work_dispatch() can only be run from the event loop thread");
  178. work_request = aral_mallocz(rrdeng_main.work_cmd.ar);
  179. memset(work_request, 0, sizeof(struct rrdeng_work));
  180. work_request->req.data = work_request;
  181. work_request->ctx = ctx;
  182. work_request->data = data;
  183. work_request->completion = completion;
  184. work_request->work_cb = work_cb;
  185. work_request->after_work_cb = after_work_cb;
  186. work_request->opcode = opcode;
  187. if(uv_queue_work(&rrdeng_main.loop, &work_request->req, work_standard_worker, after_work_standard_callback)) {
  188. internal_fatal(true, "DBENGINE: cannot queue work");
  189. work_done(work_request);
  190. return false;
  191. }
  192. __atomic_add_fetch(&rrdeng_main.work_cmd.atomics.dispatched, 1, __ATOMIC_RELAXED);
  193. return true;
  194. }
  195. // ----------------------------------------------------------------------------
  196. // page descriptor cache
  197. void page_descriptors_init(void) {
  198. rrdeng_main.descriptors.ar = aral_create(
  199. "dbengine-descriptors",
  200. sizeof(struct page_descr_with_data),
  201. 0,
  202. 65536 * 4,
  203. NULL,
  204. NULL, NULL, false, false);
  205. }
  206. struct page_descr_with_data *page_descriptor_get(void) {
  207. struct page_descr_with_data *descr = aral_mallocz(rrdeng_main.descriptors.ar);
  208. memset(descr, 0, sizeof(struct page_descr_with_data));
  209. return descr;
  210. }
  211. static inline void page_descriptor_release(struct page_descr_with_data *descr) {
  212. aral_freez(rrdeng_main.descriptors.ar, descr);
  213. }
  214. // ----------------------------------------------------------------------------
  215. // extent io descriptor cache
  216. static void extent_io_descriptor_init(void) {
  217. rrdeng_main.xt_io_descr.ar = aral_create(
  218. "dbengine-extent-io",
  219. sizeof(struct extent_io_descriptor),
  220. 0,
  221. 65536,
  222. NULL,
  223. NULL, NULL, false, false
  224. );
  225. }
  226. static struct extent_io_descriptor *extent_io_descriptor_get(void) {
  227. struct extent_io_descriptor *xt_io_descr = aral_mallocz(rrdeng_main.xt_io_descr.ar);
  228. memset(xt_io_descr, 0, sizeof(struct extent_io_descriptor));
  229. return xt_io_descr;
  230. }
  231. static inline void extent_io_descriptor_release(struct extent_io_descriptor *xt_io_descr) {
  232. aral_freez(rrdeng_main.xt_io_descr.ar, xt_io_descr);
  233. }
  234. // ----------------------------------------------------------------------------
  235. // query handle cache
  236. void rrdeng_query_handle_init(void) {
  237. rrdeng_main.handles.ar = aral_create(
  238. "dbengine-query-handles",
  239. sizeof(struct rrdeng_query_handle),
  240. 0,
  241. 65536,
  242. NULL,
  243. NULL, NULL, false, false);
  244. }
  245. struct rrdeng_query_handle *rrdeng_query_handle_get(void) {
  246. struct rrdeng_query_handle *handle = aral_mallocz(rrdeng_main.handles.ar);
  247. memset(handle, 0, sizeof(struct rrdeng_query_handle));
  248. return handle;
  249. }
  250. void rrdeng_query_handle_release(struct rrdeng_query_handle *handle) {
  251. aral_freez(rrdeng_main.handles.ar, handle);
  252. }
  253. // ----------------------------------------------------------------------------
  254. // WAL cache
  255. static struct {
  256. struct {
  257. SPINLOCK spinlock;
  258. WAL *available_items;
  259. size_t available;
  260. } protected;
  261. struct {
  262. size_t allocated;
  263. } atomics;
  264. } wal_globals = {
  265. .protected = {
  266. .spinlock = NETDATA_SPINLOCK_INITIALIZER,
  267. .available_items = NULL,
  268. .available = 0,
  269. },
  270. .atomics = {
  271. .allocated = 0,
  272. },
  273. };
  274. static void wal_cleanup1(void) {
  275. WAL *wal = NULL;
  276. if(!spinlock_trylock(&wal_globals.protected.spinlock))
  277. return;
  278. if(wal_globals.protected.available_items && wal_globals.protected.available > storage_tiers) {
  279. wal = wal_globals.protected.available_items;
  280. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(wal_globals.protected.available_items, wal, cache.prev, cache.next);
  281. wal_globals.protected.available--;
  282. }
  283. spinlock_unlock(&wal_globals.protected.spinlock);
  284. if(wal) {
  285. posix_memfree(wal->buf);
  286. freez(wal);
  287. __atomic_sub_fetch(&wal_globals.atomics.allocated, 1, __ATOMIC_RELAXED);
  288. }
  289. }
  290. WAL *wal_get(struct rrdengine_instance *ctx, unsigned size) {
  291. if(!size || size > RRDENG_BLOCK_SIZE)
  292. fatal("DBENGINE: invalid WAL size requested");
  293. WAL *wal = NULL;
  294. spinlock_lock(&wal_globals.protected.spinlock);
  295. if(likely(wal_globals.protected.available_items)) {
  296. wal = wal_globals.protected.available_items;
  297. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(wal_globals.protected.available_items, wal, cache.prev, cache.next);
  298. wal_globals.protected.available--;
  299. }
  300. uint64_t transaction_id = __atomic_fetch_add(&ctx->atomic.transaction_id, 1, __ATOMIC_RELAXED);
  301. spinlock_unlock(&wal_globals.protected.spinlock);
  302. if(unlikely(!wal)) {
  303. wal = mallocz(sizeof(WAL));
  304. wal->buf_size = RRDENG_BLOCK_SIZE;
  305. int ret = posix_memalign((void *)&wal->buf, RRDFILE_ALIGNMENT, wal->buf_size);
  306. if (unlikely(ret))
  307. fatal("DBENGINE: posix_memalign:%s", strerror(ret));
  308. __atomic_add_fetch(&wal_globals.atomics.allocated, 1, __ATOMIC_RELAXED);
  309. }
  310. // these need to survive
  311. unsigned buf_size = wal->buf_size;
  312. void *buf = wal->buf;
  313. memset(wal, 0, sizeof(WAL));
  314. // put them back
  315. wal->buf_size = buf_size;
  316. wal->buf = buf;
  317. memset(wal->buf, 0, wal->buf_size);
  318. wal->transaction_id = transaction_id;
  319. wal->size = size;
  320. return wal;
  321. }
  322. void wal_release(WAL *wal) {
  323. if(unlikely(!wal)) return;
  324. spinlock_lock(&wal_globals.protected.spinlock);
  325. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(wal_globals.protected.available_items, wal, cache.prev, cache.next);
  326. wal_globals.protected.available++;
  327. spinlock_unlock(&wal_globals.protected.spinlock);
  328. }
  329. // ----------------------------------------------------------------------------
  330. // command queue cache
  331. static void rrdeng_cmd_queue_init(void) {
  332. rrdeng_main.cmd_queue.ar = aral_create("dbengine-opcodes",
  333. sizeof(struct rrdeng_cmd),
  334. 0,
  335. 65536,
  336. NULL,
  337. NULL, NULL, false, false);
  338. }
  339. static inline STORAGE_PRIORITY rrdeng_enq_cmd_map_opcode_to_priority(enum rrdeng_opcode opcode, STORAGE_PRIORITY priority) {
  340. if(unlikely(priority >= STORAGE_PRIORITY_INTERNAL_MAX_DONT_USE))
  341. priority = STORAGE_PRIORITY_BEST_EFFORT;
  342. switch(opcode) {
  343. case RRDENG_OPCODE_QUERY:
  344. priority = STORAGE_PRIORITY_INTERNAL_QUERY_PREP;
  345. break;
  346. default:
  347. break;
  348. }
  349. return priority;
  350. }
  351. void rrdeng_enqueue_epdl_cmd(struct rrdeng_cmd *cmd) {
  352. epdl_cmd_queued(cmd->data, cmd);
  353. }
  354. void rrdeng_dequeue_epdl_cmd(struct rrdeng_cmd *cmd) {
  355. epdl_cmd_dequeued(cmd->data);
  356. }
  357. void rrdeng_req_cmd(requeue_callback_t get_cmd_cb, void *data, STORAGE_PRIORITY priority) {
  358. spinlock_lock(&rrdeng_main.cmd_queue.unsafe.spinlock);
  359. struct rrdeng_cmd *cmd = get_cmd_cb(data);
  360. if(cmd) {
  361. priority = rrdeng_enq_cmd_map_opcode_to_priority(cmd->opcode, priority);
  362. if (cmd->priority > priority) {
  363. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(rrdeng_main.cmd_queue.unsafe.waiting_items_by_priority[cmd->priority], cmd, queue.prev, queue.next);
  364. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(rrdeng_main.cmd_queue.unsafe.waiting_items_by_priority[priority], cmd, queue.prev, queue.next);
  365. cmd->priority = priority;
  366. }
  367. }
  368. spinlock_unlock(&rrdeng_main.cmd_queue.unsafe.spinlock);
  369. }
  370. void rrdeng_enq_cmd(struct rrdengine_instance *ctx, enum rrdeng_opcode opcode, void *data, struct completion *completion,
  371. enum storage_priority priority, enqueue_callback_t enqueue_cb, dequeue_callback_t dequeue_cb) {
  372. priority = rrdeng_enq_cmd_map_opcode_to_priority(opcode, priority);
  373. struct rrdeng_cmd *cmd = aral_mallocz(rrdeng_main.cmd_queue.ar);
  374. memset(cmd, 0, sizeof(struct rrdeng_cmd));
  375. cmd->ctx = ctx;
  376. cmd->opcode = opcode;
  377. cmd->data = data;
  378. cmd->completion = completion;
  379. cmd->priority = priority;
  380. cmd->dequeue_cb = dequeue_cb;
  381. spinlock_lock(&rrdeng_main.cmd_queue.unsafe.spinlock);
  382. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(rrdeng_main.cmd_queue.unsafe.waiting_items_by_priority[priority], cmd, queue.prev, queue.next);
  383. rrdeng_main.cmd_queue.unsafe.waiting++;
  384. if(enqueue_cb)
  385. enqueue_cb(cmd);
  386. spinlock_unlock(&rrdeng_main.cmd_queue.unsafe.spinlock);
  387. fatal_assert(0 == uv_async_send(&rrdeng_main.async));
  388. }
  389. static inline bool rrdeng_cmd_has_waiting_opcodes_in_lower_priorities(STORAGE_PRIORITY priority, STORAGE_PRIORITY max_priority) {
  390. for(; priority <= max_priority ; priority++)
  391. if(rrdeng_main.cmd_queue.unsafe.waiting_items_by_priority[priority])
  392. return true;
  393. return false;
  394. }
  395. #define opcode_empty (struct rrdeng_cmd) { \
  396. .ctx = NULL, \
  397. .opcode = RRDENG_OPCODE_NOOP, \
  398. .priority = STORAGE_PRIORITY_BEST_EFFORT, \
  399. .completion = NULL, \
  400. .data = NULL, \
  401. }
  402. static inline struct rrdeng_cmd rrdeng_deq_cmd(bool from_worker) {
  403. struct rrdeng_cmd *cmd = NULL;
  404. enum LIBUV_WORKERS_STATUS status = work_request_full();
  405. STORAGE_PRIORITY min_priority, max_priority;
  406. min_priority = STORAGE_PRIORITY_INTERNAL_DBENGINE;
  407. max_priority = (status != LIBUV_WORKERS_RELAXED) ? STORAGE_PRIORITY_INTERNAL_DBENGINE : STORAGE_PRIORITY_INTERNAL_MAX_DONT_USE - 1;
  408. if(from_worker) {
  409. if(status == LIBUV_WORKERS_CRITICAL)
  410. return opcode_empty;
  411. min_priority = STORAGE_PRIORITY_INTERNAL_QUERY_PREP;
  412. max_priority = STORAGE_PRIORITY_BEST_EFFORT;
  413. }
  414. // find an opcode to execute from the queue
  415. spinlock_lock(&rrdeng_main.cmd_queue.unsafe.spinlock);
  416. for(STORAGE_PRIORITY priority = min_priority; priority <= max_priority ; priority++) {
  417. cmd = rrdeng_main.cmd_queue.unsafe.waiting_items_by_priority[priority];
  418. if(cmd) {
  419. // avoid starvation of lower priorities
  420. if(unlikely(priority >= STORAGE_PRIORITY_HIGH &&
  421. priority < STORAGE_PRIORITY_BEST_EFFORT &&
  422. ++rrdeng_main.cmd_queue.unsafe.executed_by_priority[priority] % 50 == 0 &&
  423. rrdeng_cmd_has_waiting_opcodes_in_lower_priorities(priority + 1, max_priority))) {
  424. // let the others run 2% of the requests
  425. cmd = NULL;
  426. continue;
  427. }
  428. // remove it from the queue
  429. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(rrdeng_main.cmd_queue.unsafe.waiting_items_by_priority[priority], cmd, queue.prev, queue.next);
  430. rrdeng_main.cmd_queue.unsafe.waiting--;
  431. break;
  432. }
  433. }
  434. if(cmd && cmd->dequeue_cb) {
  435. cmd->dequeue_cb(cmd);
  436. cmd->dequeue_cb = NULL;
  437. }
  438. spinlock_unlock(&rrdeng_main.cmd_queue.unsafe.spinlock);
  439. struct rrdeng_cmd ret;
  440. if(cmd) {
  441. // copy it, to return it
  442. ret = *cmd;
  443. aral_freez(rrdeng_main.cmd_queue.ar, cmd);
  444. }
  445. else
  446. ret = opcode_empty;
  447. return ret;
  448. }
  449. // ----------------------------------------------------------------------------
  450. struct {
  451. ARAL *aral[RRD_STORAGE_TIERS];
  452. } dbengine_page_alloc_globals = {};
  453. static inline ARAL *page_size_lookup(size_t size) {
  454. for(size_t tier = 0; tier < storage_tiers ;tier++)
  455. if(size == tier_page_size[tier])
  456. return dbengine_page_alloc_globals.aral[tier];
  457. return NULL;
  458. }
  459. static void dbengine_page_alloc_init(void) {
  460. for(size_t i = storage_tiers; i > 0 ;i--) {
  461. size_t tier = storage_tiers - i;
  462. char buf[20 + 1];
  463. snprintfz(buf, 20, "tier%zu-pages", tier);
  464. dbengine_page_alloc_globals.aral[tier] = aral_create(
  465. buf,
  466. tier_page_size[tier],
  467. 64,
  468. 512 * tier_page_size[tier],
  469. pgc_aral_statistics(),
  470. NULL, NULL, false, false);
  471. }
  472. }
  473. void *dbengine_page_alloc(size_t size) {
  474. ARAL *ar = page_size_lookup(size);
  475. if(ar) return aral_mallocz(ar);
  476. return mallocz(size);
  477. }
  478. void dbengine_page_free(void *page, size_t size __maybe_unused) {
  479. if(unlikely(!page || page == DBENGINE_EMPTY_PAGE))
  480. return;
  481. ARAL *ar = page_size_lookup(size);
  482. if(ar)
  483. aral_freez(ar, page);
  484. else
  485. freez(page);
  486. }
  487. // ----------------------------------------------------------------------------
  488. void *dbengine_extent_alloc(size_t size) {
  489. void *extent = mallocz(size);
  490. return extent;
  491. }
  492. void dbengine_extent_free(void *extent, size_t size __maybe_unused) {
  493. freez(extent);
  494. }
  495. static void journalfile_extent_build(struct rrdengine_instance *ctx, struct extent_io_descriptor *xt_io_descr) {
  496. unsigned count, payload_length, descr_size, size_bytes;
  497. void *buf;
  498. /* persistent structures */
  499. struct rrdeng_df_extent_header *df_header;
  500. struct rrdeng_jf_transaction_header *jf_header;
  501. struct rrdeng_jf_store_data *jf_metric_data;
  502. struct rrdeng_jf_transaction_trailer *jf_trailer;
  503. uLong crc;
  504. df_header = xt_io_descr->buf;
  505. count = df_header->number_of_pages;
  506. descr_size = sizeof(*jf_metric_data->descr) * count;
  507. payload_length = sizeof(*jf_metric_data) + descr_size;
  508. size_bytes = sizeof(*jf_header) + payload_length + sizeof(*jf_trailer);
  509. xt_io_descr->wal = wal_get(ctx, size_bytes);
  510. buf = xt_io_descr->wal->buf;
  511. jf_header = buf;
  512. jf_header->type = STORE_DATA;
  513. jf_header->reserved = 0;
  514. jf_header->id = xt_io_descr->wal->transaction_id;
  515. jf_header->payload_length = payload_length;
  516. jf_metric_data = buf + sizeof(*jf_header);
  517. jf_metric_data->extent_offset = xt_io_descr->pos;
  518. jf_metric_data->extent_size = xt_io_descr->bytes;
  519. jf_metric_data->number_of_pages = count;
  520. memcpy(jf_metric_data->descr, df_header->descr, descr_size);
  521. jf_trailer = buf + sizeof(*jf_header) + payload_length;
  522. crc = crc32(0L, Z_NULL, 0);
  523. crc = crc32(crc, buf, sizeof(*jf_header) + payload_length);
  524. crc32set(jf_trailer->checksum, crc);
  525. }
  526. static void after_extent_flushed_to_open(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t* req __maybe_unused, int status __maybe_unused) {
  527. if(completion)
  528. completion_mark_complete(completion);
  529. if(ctx_is_available_for_queries(ctx))
  530. rrdeng_enq_cmd(ctx, RRDENG_OPCODE_DATABASE_ROTATE, NULL, NULL, STORAGE_PRIORITY_INTERNAL_DBENGINE, NULL, NULL);
  531. }
  532. static void *extent_flushed_to_open_tp_worker(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t *uv_work_req __maybe_unused) {
  533. worker_is_busy(UV_EVENT_DBENGINE_FLUSHED_TO_OPEN);
  534. uv_fs_t *uv_fs_request = data;
  535. struct extent_io_descriptor *xt_io_descr = uv_fs_request->data;
  536. struct page_descr_with_data *descr;
  537. struct rrdengine_datafile *datafile;
  538. unsigned i;
  539. datafile = xt_io_descr->datafile;
  540. bool still_running = ctx_is_available_for_queries(ctx);
  541. for (i = 0 ; i < xt_io_descr->descr_count ; ++i) {
  542. descr = xt_io_descr->descr_array[i];
  543. if (likely(still_running))
  544. pgc_open_add_hot_page(
  545. (Word_t)ctx, descr->metric_id,
  546. (time_t) (descr->start_time_ut / USEC_PER_SEC),
  547. (time_t) (descr->end_time_ut / USEC_PER_SEC),
  548. descr->update_every_s,
  549. datafile,
  550. xt_io_descr->pos, xt_io_descr->bytes, descr->page_length);
  551. page_descriptor_release(descr);
  552. }
  553. uv_fs_req_cleanup(uv_fs_request);
  554. posix_memfree(xt_io_descr->buf);
  555. extent_io_descriptor_release(xt_io_descr);
  556. spinlock_lock(&datafile->writers.spinlock);
  557. datafile->writers.flushed_to_open_running--;
  558. spinlock_unlock(&datafile->writers.spinlock);
  559. if(datafile->fileno != ctx_last_fileno_get(ctx) && still_running)
  560. // we just finished a flushing on a datafile that is not the active one
  561. rrdeng_enq_cmd(ctx, RRDENG_OPCODE_JOURNAL_INDEX, datafile, NULL, STORAGE_PRIORITY_INTERNAL_DBENGINE, NULL, NULL);
  562. return data;
  563. }
  564. // Main event loop callback
  565. static void after_extent_write_datafile_io(uv_fs_t *uv_fs_request) {
  566. worker_is_busy(RRDENG_OPCODE_MAX + RRDENG_OPCODE_EXTENT_WRITE);
  567. struct extent_io_descriptor *xt_io_descr = uv_fs_request->data;
  568. struct rrdengine_datafile *datafile = xt_io_descr->datafile;
  569. struct rrdengine_instance *ctx = datafile->ctx;
  570. if (uv_fs_request->result < 0) {
  571. ctx_io_error(ctx);
  572. netdata_log_error("DBENGINE: %s: uv_fs_write(): %s", __func__, uv_strerror((int)uv_fs_request->result));
  573. }
  574. journalfile_v1_extent_write(ctx, xt_io_descr->datafile, xt_io_descr->wal, &rrdeng_main.loop);
  575. spinlock_lock(&datafile->writers.spinlock);
  576. datafile->writers.running--;
  577. datafile->writers.flushed_to_open_running++;
  578. spinlock_unlock(&datafile->writers.spinlock);
  579. rrdeng_enq_cmd(xt_io_descr->ctx,
  580. RRDENG_OPCODE_FLUSHED_TO_OPEN,
  581. uv_fs_request,
  582. xt_io_descr->completion,
  583. STORAGE_PRIORITY_INTERNAL_DBENGINE,
  584. NULL,
  585. NULL);
  586. worker_is_idle();
  587. }
  588. static bool datafile_is_full(struct rrdengine_instance *ctx, struct rrdengine_datafile *datafile) {
  589. bool ret = false;
  590. spinlock_lock(&datafile->writers.spinlock);
  591. if(ctx_is_available_for_queries(ctx) && datafile->pos > rrdeng_target_data_file_size(ctx))
  592. ret = true;
  593. spinlock_unlock(&datafile->writers.spinlock);
  594. return ret;
  595. }
  596. static struct rrdengine_datafile *get_datafile_to_write_extent(struct rrdengine_instance *ctx) {
  597. struct rrdengine_datafile *datafile;
  598. // get the latest datafile
  599. uv_rwlock_rdlock(&ctx->datafiles.rwlock);
  600. datafile = ctx->datafiles.first->prev;
  601. // become a writer on this datafile, to prevent it from vanishing
  602. spinlock_lock(&datafile->writers.spinlock);
  603. datafile->writers.running++;
  604. spinlock_unlock(&datafile->writers.spinlock);
  605. uv_rwlock_rdunlock(&ctx->datafiles.rwlock);
  606. if(datafile_is_full(ctx, datafile)) {
  607. // remember the datafile we have become writers to
  608. struct rrdengine_datafile *old_datafile = datafile;
  609. // only 1 datafile creation at a time
  610. static netdata_mutex_t mutex = NETDATA_MUTEX_INITIALIZER;
  611. netdata_mutex_lock(&mutex);
  612. // take the latest datafile again - without this, multiple threads may create multiple files
  613. uv_rwlock_rdlock(&ctx->datafiles.rwlock);
  614. datafile = ctx->datafiles.first->prev;
  615. uv_rwlock_rdunlock(&ctx->datafiles.rwlock);
  616. if(datafile_is_full(ctx, datafile) && create_new_datafile_pair(ctx, true) == 0)
  617. rrdeng_enq_cmd(ctx, RRDENG_OPCODE_JOURNAL_INDEX, datafile, NULL, STORAGE_PRIORITY_INTERNAL_DBENGINE, NULL,
  618. NULL);
  619. netdata_mutex_unlock(&mutex);
  620. // get the new latest datafile again, like above
  621. uv_rwlock_rdlock(&ctx->datafiles.rwlock);
  622. datafile = ctx->datafiles.first->prev;
  623. // become a writer on this datafile, to prevent it from vanishing
  624. spinlock_lock(&datafile->writers.spinlock);
  625. datafile->writers.running++;
  626. spinlock_unlock(&datafile->writers.spinlock);
  627. uv_rwlock_rdunlock(&ctx->datafiles.rwlock);
  628. // release the writers on the old datafile
  629. spinlock_lock(&old_datafile->writers.spinlock);
  630. old_datafile->writers.running--;
  631. spinlock_unlock(&old_datafile->writers.spinlock);
  632. }
  633. return datafile;
  634. }
  635. /*
  636. * Take a page list in a judy array and write them
  637. */
  638. static struct extent_io_descriptor *datafile_extent_build(struct rrdengine_instance *ctx, struct page_descr_with_data *base, struct completion *completion) {
  639. int ret;
  640. int compressed_size, max_compressed_size = 0;
  641. unsigned i, count, size_bytes, pos, real_io_size;
  642. uint32_t uncompressed_payload_length, payload_offset;
  643. struct page_descr_with_data *descr, *eligible_pages[MAX_PAGES_PER_EXTENT];
  644. struct extent_io_descriptor *xt_io_descr;
  645. struct extent_buffer *eb = NULL;
  646. void *compressed_buf = NULL;
  647. Word_t Index;
  648. uint8_t compression_algorithm = ctx->config.global_compress_alg;
  649. struct rrdengine_datafile *datafile;
  650. /* persistent structures */
  651. struct rrdeng_df_extent_header *header;
  652. struct rrdeng_df_extent_trailer *trailer;
  653. uLong crc;
  654. for(descr = base, Index = 0, count = 0, uncompressed_payload_length = 0;
  655. descr && count != rrdeng_pages_per_extent;
  656. descr = descr->link.next, Index++) {
  657. uncompressed_payload_length += descr->page_length;
  658. eligible_pages[count++] = descr;
  659. }
  660. if (!count) {
  661. if (completion)
  662. completion_mark_complete(completion);
  663. __atomic_sub_fetch(&ctx->atomic.extents_currently_being_flushed, 1, __ATOMIC_RELAXED);
  664. return NULL;
  665. }
  666. xt_io_descr = extent_io_descriptor_get();
  667. xt_io_descr->ctx = ctx;
  668. payload_offset = sizeof(*header) + count * sizeof(header->descr[0]);
  669. switch (compression_algorithm) {
  670. case RRD_NO_COMPRESSION:
  671. size_bytes = payload_offset + uncompressed_payload_length + sizeof(*trailer);
  672. break;
  673. default: /* Compress */
  674. fatal_assert(uncompressed_payload_length < LZ4_MAX_INPUT_SIZE);
  675. max_compressed_size = LZ4_compressBound(uncompressed_payload_length);
  676. eb = extent_buffer_get(max_compressed_size);
  677. compressed_buf = eb->data;
  678. size_bytes = payload_offset + MAX(uncompressed_payload_length, (unsigned)max_compressed_size) + sizeof(*trailer);
  679. break;
  680. }
  681. ret = posix_memalign((void *)&xt_io_descr->buf, RRDFILE_ALIGNMENT, ALIGN_BYTES_CEILING(size_bytes));
  682. if (unlikely(ret)) {
  683. fatal("DBENGINE: posix_memalign:%s", strerror(ret));
  684. /* freez(xt_io_descr);*/
  685. }
  686. memset(xt_io_descr->buf, 0, ALIGN_BYTES_CEILING(size_bytes));
  687. (void) memcpy(xt_io_descr->descr_array, eligible_pages, sizeof(struct page_descr_with_data *) * count);
  688. xt_io_descr->descr_count = count;
  689. pos = 0;
  690. header = xt_io_descr->buf;
  691. header->compression_algorithm = compression_algorithm;
  692. header->number_of_pages = count;
  693. pos += sizeof(*header);
  694. for (i = 0 ; i < count ; ++i) {
  695. descr = xt_io_descr->descr_array[i];
  696. header->descr[i].type = descr->type;
  697. uuid_copy(*(uuid_t *)header->descr[i].uuid, *descr->id);
  698. header->descr[i].page_length = descr->page_length;
  699. header->descr[i].start_time_ut = descr->start_time_ut;
  700. header->descr[i].end_time_ut = descr->end_time_ut;
  701. pos += sizeof(header->descr[i]);
  702. }
  703. for (i = 0 ; i < count ; ++i) {
  704. descr = xt_io_descr->descr_array[i];
  705. (void) memcpy(xt_io_descr->buf + pos, descr->page, descr->page_length);
  706. pos += descr->page_length;
  707. }
  708. if(likely(compression_algorithm == RRD_LZ4)) {
  709. compressed_size = LZ4_compress_default(
  710. xt_io_descr->buf + payload_offset,
  711. compressed_buf,
  712. (int)uncompressed_payload_length,
  713. max_compressed_size);
  714. __atomic_add_fetch(&ctx->stats.before_compress_bytes, uncompressed_payload_length, __ATOMIC_RELAXED);
  715. __atomic_add_fetch(&ctx->stats.after_compress_bytes, compressed_size, __ATOMIC_RELAXED);
  716. (void) memcpy(xt_io_descr->buf + payload_offset, compressed_buf, compressed_size);
  717. extent_buffer_release(eb);
  718. size_bytes = payload_offset + compressed_size + sizeof(*trailer);
  719. header->payload_length = compressed_size;
  720. }
  721. else { // RRD_NO_COMPRESSION
  722. header->payload_length = uncompressed_payload_length;
  723. }
  724. real_io_size = ALIGN_BYTES_CEILING(size_bytes);
  725. datafile = get_datafile_to_write_extent(ctx);
  726. spinlock_lock(&datafile->writers.spinlock);
  727. xt_io_descr->datafile = datafile;
  728. xt_io_descr->pos = datafile->pos;
  729. datafile->pos += real_io_size;
  730. spinlock_unlock(&datafile->writers.spinlock);
  731. xt_io_descr->bytes = size_bytes;
  732. xt_io_descr->uv_fs_request.data = xt_io_descr;
  733. xt_io_descr->completion = completion;
  734. trailer = xt_io_descr->buf + size_bytes - sizeof(*trailer);
  735. crc = crc32(0L, Z_NULL, 0);
  736. crc = crc32(crc, xt_io_descr->buf, size_bytes - sizeof(*trailer));
  737. crc32set(trailer->checksum, crc);
  738. xt_io_descr->iov = uv_buf_init((void *)xt_io_descr->buf, real_io_size);
  739. journalfile_extent_build(ctx, xt_io_descr);
  740. ctx_last_flush_fileno_set(ctx, datafile->fileno);
  741. ctx_current_disk_space_increase(ctx, real_io_size);
  742. ctx_io_write_op_bytes(ctx, real_io_size);
  743. return xt_io_descr;
  744. }
  745. static void after_extent_write(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t* uv_work_req __maybe_unused, int status __maybe_unused) {
  746. struct extent_io_descriptor *xt_io_descr = data;
  747. if(xt_io_descr) {
  748. int ret = uv_fs_write(&rrdeng_main.loop,
  749. &xt_io_descr->uv_fs_request,
  750. xt_io_descr->datafile->file,
  751. &xt_io_descr->iov,
  752. 1,
  753. (int64_t) xt_io_descr->pos,
  754. after_extent_write_datafile_io);
  755. fatal_assert(-1 != ret);
  756. }
  757. }
  758. static void *extent_write_tp_worker(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t *uv_work_req __maybe_unused) {
  759. worker_is_busy(UV_EVENT_DBENGINE_EXTENT_WRITE);
  760. struct page_descr_with_data *base = data;
  761. struct extent_io_descriptor *xt_io_descr = datafile_extent_build(ctx, base, completion);
  762. return xt_io_descr;
  763. }
  764. static void after_database_rotate(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t* req __maybe_unused, int status __maybe_unused) {
  765. __atomic_store_n(&ctx->atomic.now_deleting_files, false, __ATOMIC_RELAXED);
  766. }
  767. struct uuid_first_time_s {
  768. uuid_t *uuid;
  769. time_t first_time_s;
  770. METRIC *metric;
  771. size_t pages_found;
  772. size_t df_matched;
  773. size_t df_index_oldest;
  774. };
  775. struct rrdengine_datafile *datafile_release_and_acquire_next_for_retention(struct rrdengine_instance *ctx, struct rrdengine_datafile *datafile) {
  776. uv_rwlock_rdlock(&ctx->datafiles.rwlock);
  777. struct rrdengine_datafile *next_datafile = datafile->next;
  778. while(next_datafile && !datafile_acquire(next_datafile, DATAFILE_ACQUIRE_RETENTION))
  779. next_datafile = next_datafile->next;
  780. uv_rwlock_rdunlock(&ctx->datafiles.rwlock);
  781. datafile_release(datafile, DATAFILE_ACQUIRE_RETENTION);
  782. return next_datafile;
  783. }
  784. time_t find_uuid_first_time(
  785. struct rrdengine_instance *ctx,
  786. struct rrdengine_datafile *datafile,
  787. struct uuid_first_time_s *uuid_first_entry_list,
  788. size_t count)
  789. {
  790. time_t global_first_time_s = LONG_MAX;
  791. // acquire the datafile to work with it
  792. uv_rwlock_rdlock(&ctx->datafiles.rwlock);
  793. while(datafile && !datafile_acquire(datafile, DATAFILE_ACQUIRE_RETENTION))
  794. datafile = datafile->next;
  795. uv_rwlock_rdunlock(&ctx->datafiles.rwlock);
  796. if (unlikely(!datafile))
  797. return global_first_time_s;
  798. unsigned journalfile_count = 0;
  799. size_t binary_match = 0;
  800. size_t not_matching_bsearches = 0;
  801. while (datafile) {
  802. struct journal_v2_header *j2_header = journalfile_v2_data_acquire(datafile->journalfile, NULL, 0, 0);
  803. if (!j2_header) {
  804. datafile = datafile_release_and_acquire_next_for_retention(ctx, datafile);
  805. continue;
  806. }
  807. time_t journal_start_time_s = (time_t) (j2_header->start_time_ut / USEC_PER_SEC);
  808. if(journal_start_time_s < global_first_time_s)
  809. global_first_time_s = journal_start_time_s;
  810. struct journal_metric_list *uuid_list = (struct journal_metric_list *)((uint8_t *) j2_header + j2_header->metric_offset);
  811. struct uuid_first_time_s *uuid_original_entry;
  812. size_t journal_metric_count = j2_header->metric_count;
  813. for (size_t index = 0; index < count; ++index) {
  814. uuid_original_entry = &uuid_first_entry_list[index];
  815. // Check here if we should skip this
  816. if (uuid_original_entry->df_matched > 3 || uuid_original_entry->pages_found > 5)
  817. continue;
  818. struct journal_metric_list *live_entry =
  819. bsearch(uuid_original_entry->uuid,uuid_list,journal_metric_count,
  820. sizeof(*uuid_list), journal_metric_uuid_compare);
  821. if (!live_entry) {
  822. // Not found in this journal
  823. not_matching_bsearches++;
  824. continue;
  825. }
  826. uuid_original_entry->pages_found += live_entry->entries;
  827. uuid_original_entry->df_matched++;
  828. time_t old_first_time_s = uuid_original_entry->first_time_s;
  829. // Calculate first / last for this match
  830. time_t first_time_s = live_entry->delta_start_s + journal_start_time_s;
  831. uuid_original_entry->first_time_s = MIN(uuid_original_entry->first_time_s, first_time_s);
  832. if (uuid_original_entry->first_time_s != old_first_time_s)
  833. uuid_original_entry->df_index_oldest = uuid_original_entry->df_matched;
  834. binary_match++;
  835. }
  836. journalfile_count++;
  837. journalfile_v2_data_release(datafile->journalfile);
  838. datafile = datafile_release_and_acquire_next_for_retention(ctx, datafile);
  839. }
  840. // Let's scan the open cache for almost exact match
  841. size_t open_cache_count = 0;
  842. size_t df_index[10] = { 0 };
  843. size_t without_metric = 0;
  844. size_t open_cache_gave_first_time_s = 0;
  845. size_t metric_count = 0;
  846. size_t without_retention = 0;
  847. size_t not_needed_bsearches = 0;
  848. for (size_t index = 0; index < count; ++index) {
  849. struct uuid_first_time_s *uuid_first_t_entry = &uuid_first_entry_list[index];
  850. metric_count++;
  851. size_t idx = uuid_first_t_entry->df_index_oldest;
  852. if(idx >= 10)
  853. idx = 9;
  854. df_index[idx]++;
  855. not_needed_bsearches += uuid_first_t_entry->df_matched - uuid_first_t_entry->df_index_oldest;
  856. if (unlikely(!uuid_first_t_entry->metric)) {
  857. without_metric++;
  858. continue;
  859. }
  860. PGC_PAGE *page = pgc_page_get_and_acquire(
  861. open_cache, (Word_t)ctx,
  862. (Word_t)uuid_first_t_entry->metric, 0,
  863. PGC_SEARCH_FIRST);
  864. if (page) {
  865. time_t old_first_time_s = uuid_first_t_entry->first_time_s;
  866. time_t first_time_s = pgc_page_start_time_s(page);
  867. uuid_first_t_entry->first_time_s = MIN(uuid_first_t_entry->first_time_s, first_time_s);
  868. pgc_page_release(open_cache, page);
  869. open_cache_count++;
  870. if(uuid_first_t_entry->first_time_s != old_first_time_s) {
  871. open_cache_gave_first_time_s++;
  872. }
  873. }
  874. else {
  875. if(!uuid_first_t_entry->df_index_oldest)
  876. without_retention++;
  877. }
  878. }
  879. internal_error(true,
  880. "DBENGINE: analyzed the retention of %zu rotated metrics of tier %d, "
  881. "did %zu jv2 matching binary searches (%zu not matching, %zu overflown) in %u journal files, "
  882. "%zu metrics with entries in open cache, "
  883. "metrics first time found per datafile index ([not in jv2]:%zu, [1]:%zu, [2]:%zu, [3]:%zu, [4]:%zu, [5]:%zu, [6]:%zu, [7]:%zu, [8]:%zu, [bigger]: %zu), "
  884. "open cache found first time %zu, "
  885. "metrics without any remaining retention %zu, "
  886. "metrics not in MRG %zu",
  887. metric_count,
  888. ctx->config.tier,
  889. binary_match,
  890. not_matching_bsearches,
  891. not_needed_bsearches,
  892. journalfile_count,
  893. open_cache_count,
  894. df_index[0], df_index[1], df_index[2], df_index[3], df_index[4], df_index[5], df_index[6], df_index[7], df_index[8], df_index[9],
  895. open_cache_gave_first_time_s,
  896. without_retention,
  897. without_metric
  898. );
  899. return global_first_time_s;
  900. }
  901. static void update_metrics_first_time_s(struct rrdengine_instance *ctx, struct rrdengine_datafile *datafile_to_delete, struct rrdengine_datafile *first_datafile_remaining, bool worker) {
  902. time_t global_first_time_s = LONG_MAX;
  903. if(worker)
  904. worker_is_busy(UV_EVENT_DBENGINE_FIND_ROTATED_METRICS);
  905. struct rrdengine_journalfile *journalfile = datafile_to_delete->journalfile;
  906. struct journal_v2_header *j2_header = journalfile_v2_data_acquire(journalfile, NULL, 0, 0);
  907. if (unlikely(!j2_header)) {
  908. if (worker)
  909. worker_is_idle();
  910. return;
  911. }
  912. __atomic_add_fetch(&rrdeng_cache_efficiency_stats.metrics_retention_started, 1, __ATOMIC_RELAXED);
  913. struct journal_metric_list *uuid_list = (struct journal_metric_list *)((uint8_t *) j2_header + j2_header->metric_offset);
  914. size_t count = j2_header->metric_count;
  915. struct uuid_first_time_s *uuid_first_t_entry;
  916. struct uuid_first_time_s *uuid_first_entry_list = callocz(count, sizeof(struct uuid_first_time_s));
  917. size_t added = 0;
  918. for (size_t index = 0; index < count; ++index) {
  919. METRIC *metric = mrg_metric_get_and_acquire(main_mrg, &uuid_list[index].uuid, (Word_t) ctx);
  920. if (!metric)
  921. continue;
  922. uuid_first_entry_list[added].metric = metric;
  923. uuid_first_entry_list[added].first_time_s = LONG_MAX;
  924. uuid_first_entry_list[added].df_matched = 0;
  925. uuid_first_entry_list[added].df_index_oldest = 0;
  926. uuid_first_entry_list[added].uuid = mrg_metric_uuid(main_mrg, metric);
  927. added++;
  928. }
  929. netdata_log_info("DBENGINE: recalculating tier %d retention for %zu metrics starting with datafile %u",
  930. ctx->config.tier, count, first_datafile_remaining->fileno);
  931. journalfile_v2_data_release(journalfile);
  932. // Update the first time / last time for all metrics we plan to delete
  933. if(worker)
  934. worker_is_busy(UV_EVENT_DBENGINE_FIND_REMAINING_RETENTION);
  935. global_first_time_s = find_uuid_first_time(ctx, first_datafile_remaining, uuid_first_entry_list, added);
  936. if(worker)
  937. worker_is_busy(UV_EVENT_DBENGINE_POPULATE_MRG);
  938. netdata_log_info("DBENGINE: updating tier %d metrics registry retention for %zu metrics",
  939. ctx->config.tier, added);
  940. size_t deleted_metrics = 0, zero_retention_referenced = 0, zero_disk_retention = 0, zero_disk_but_live = 0;
  941. for (size_t index = 0; index < added; ++index) {
  942. uuid_first_t_entry = &uuid_first_entry_list[index];
  943. if (likely(uuid_first_t_entry->first_time_s != LONG_MAX)) {
  944. mrg_metric_set_first_time_s_if_bigger(main_mrg, uuid_first_t_entry->metric, uuid_first_t_entry->first_time_s);
  945. mrg_metric_release(main_mrg, uuid_first_t_entry->metric);
  946. }
  947. else {
  948. zero_disk_retention++;
  949. // there is no retention for this metric
  950. bool has_retention = mrg_metric_zero_disk_retention(main_mrg, uuid_first_t_entry->metric);
  951. if (!has_retention) {
  952. bool deleted = mrg_metric_release_and_delete(main_mrg, uuid_first_t_entry->metric);
  953. if(deleted)
  954. deleted_metrics++;
  955. else
  956. zero_retention_referenced++;
  957. }
  958. else {
  959. zero_disk_but_live++;
  960. mrg_metric_release(main_mrg, uuid_first_t_entry->metric);
  961. }
  962. }
  963. }
  964. freez(uuid_first_entry_list);
  965. internal_error(zero_disk_retention,
  966. "DBENGINE: deleted %zu metrics, zero retention but referenced %zu (out of %zu total, of which %zu have main cache retention) zero on-disk retention tier %d metrics from metrics registry",
  967. deleted_metrics, zero_retention_referenced, zero_disk_retention, zero_disk_but_live, ctx->config.tier);
  968. if(global_first_time_s != LONG_MAX)
  969. __atomic_store_n(&ctx->atomic.first_time_s, global_first_time_s, __ATOMIC_RELAXED);
  970. if(worker)
  971. worker_is_idle();
  972. }
  973. void datafile_delete(struct rrdengine_instance *ctx, struct rrdengine_datafile *datafile, bool update_retention, bool worker) {
  974. if(worker)
  975. worker_is_busy(UV_EVENT_DBENGINE_DATAFILE_DELETE_WAIT);
  976. bool datafile_got_for_deletion = datafile_acquire_for_deletion(datafile);
  977. if (update_retention)
  978. update_metrics_first_time_s(ctx, datafile, datafile->next, worker);
  979. while (!datafile_got_for_deletion) {
  980. if(worker)
  981. worker_is_busy(UV_EVENT_DBENGINE_DATAFILE_DELETE_WAIT);
  982. datafile_got_for_deletion = datafile_acquire_for_deletion(datafile);
  983. if (!datafile_got_for_deletion) {
  984. netdata_log_info("DBENGINE: waiting for data file '%s/"
  985. DATAFILE_PREFIX RRDENG_FILE_NUMBER_PRINT_TMPL DATAFILE_EXTENSION
  986. "' to be available for deletion, "
  987. "it is in use currently by %u users.",
  988. ctx->config.dbfiles_path, ctx->datafiles.first->tier, ctx->datafiles.first->fileno, datafile->users.lockers);
  989. __atomic_add_fetch(&rrdeng_cache_efficiency_stats.datafile_deletion_spin, 1, __ATOMIC_RELAXED);
  990. sleep_usec(1 * USEC_PER_SEC);
  991. }
  992. }
  993. __atomic_add_fetch(&rrdeng_cache_efficiency_stats.datafile_deletion_started, 1, __ATOMIC_RELAXED);
  994. netdata_log_info("DBENGINE: deleting data file '%s/"
  995. DATAFILE_PREFIX RRDENG_FILE_NUMBER_PRINT_TMPL DATAFILE_EXTENSION
  996. "'.",
  997. ctx->config.dbfiles_path, ctx->datafiles.first->tier, ctx->datafiles.first->fileno);
  998. if(worker)
  999. worker_is_busy(UV_EVENT_DBENGINE_DATAFILE_DELETE);
  1000. struct rrdengine_journalfile *journal_file;
  1001. unsigned deleted_bytes, journal_file_bytes, datafile_bytes;
  1002. int ret;
  1003. char path[RRDENG_PATH_MAX];
  1004. uv_rwlock_wrlock(&ctx->datafiles.rwlock);
  1005. datafile_list_delete_unsafe(ctx, datafile);
  1006. uv_rwlock_wrunlock(&ctx->datafiles.rwlock);
  1007. journal_file = datafile->journalfile;
  1008. datafile_bytes = datafile->pos;
  1009. journal_file_bytes = journalfile_current_size(journal_file);
  1010. deleted_bytes = journalfile_v2_data_size_get(journal_file);
  1011. netdata_log_info("DBENGINE: deleting data and journal files to maintain disk quota");
  1012. ret = journalfile_destroy_unsafe(journal_file, datafile);
  1013. if (!ret) {
  1014. journalfile_v1_generate_path(datafile, path, sizeof(path));
  1015. netdata_log_info("DBENGINE: deleted journal file \"%s\".", path);
  1016. journalfile_v2_generate_path(datafile, path, sizeof(path));
  1017. netdata_log_info("DBENGINE: deleted journal file \"%s\".", path);
  1018. deleted_bytes += journal_file_bytes;
  1019. }
  1020. ret = destroy_data_file_unsafe(datafile);
  1021. if (!ret) {
  1022. generate_datafilepath(datafile, path, sizeof(path));
  1023. netdata_log_info("DBENGINE: deleted data file \"%s\".", path);
  1024. deleted_bytes += datafile_bytes;
  1025. }
  1026. freez(journal_file);
  1027. freez(datafile);
  1028. ctx_current_disk_space_decrease(ctx, deleted_bytes);
  1029. netdata_log_info("DBENGINE: reclaimed %u bytes of disk space.", deleted_bytes);
  1030. }
  1031. static void *database_rotate_tp_worker(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t *uv_work_req __maybe_unused) {
  1032. datafile_delete(ctx, ctx->datafiles.first, ctx_is_available_for_queries(ctx), true);
  1033. if (rrdeng_ctx_exceeded_disk_quota(ctx))
  1034. rrdeng_enq_cmd(ctx, RRDENG_OPCODE_DATABASE_ROTATE, NULL, NULL, STORAGE_PRIORITY_INTERNAL_DBENGINE, NULL, NULL);
  1035. rrdcontext_db_rotation();
  1036. return data;
  1037. }
  1038. static void after_flush_all_hot_and_dirty_pages_of_section(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t* req __maybe_unused, int status __maybe_unused) {
  1039. ;
  1040. }
  1041. static void *flush_all_hot_and_dirty_pages_of_section_tp_worker(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t *uv_work_req __maybe_unused) {
  1042. worker_is_busy(UV_EVENT_DBENGINE_QUIESCE);
  1043. pgc_flush_all_hot_and_dirty_pages(main_cache, (Word_t)ctx);
  1044. completion_mark_complete(&ctx->quiesce.completion);
  1045. return data;
  1046. }
  1047. static void after_populate_mrg(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t* req __maybe_unused, int status __maybe_unused) {
  1048. ;
  1049. }
  1050. static void *populate_mrg_tp_worker(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t *uv_work_req __maybe_unused) {
  1051. worker_is_busy(UV_EVENT_DBENGINE_POPULATE_MRG);
  1052. do {
  1053. struct rrdengine_datafile *datafile = NULL;
  1054. // find a datafile to work
  1055. uv_rwlock_rdlock(&ctx->datafiles.rwlock);
  1056. for(datafile = ctx->datafiles.first; datafile ; datafile = datafile->next) {
  1057. if(!spinlock_trylock(&datafile->populate_mrg.spinlock))
  1058. continue;
  1059. if(datafile->populate_mrg.populated) {
  1060. spinlock_unlock(&datafile->populate_mrg.spinlock);
  1061. continue;
  1062. }
  1063. // we have the spinlock and it is not populated
  1064. break;
  1065. }
  1066. uv_rwlock_rdunlock(&ctx->datafiles.rwlock);
  1067. if(!datafile)
  1068. break;
  1069. journalfile_v2_populate_retention_to_mrg(ctx, datafile->journalfile);
  1070. datafile->populate_mrg.populated = true;
  1071. spinlock_unlock(&datafile->populate_mrg.spinlock);
  1072. } while(1);
  1073. completion_mark_complete(completion);
  1074. return data;
  1075. }
  1076. static void after_ctx_shutdown(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t* req __maybe_unused, int status __maybe_unused) {
  1077. ;
  1078. }
  1079. static void *ctx_shutdown_tp_worker(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t *uv_work_req __maybe_unused) {
  1080. worker_is_busy(UV_EVENT_DBENGINE_SHUTDOWN);
  1081. completion_wait_for(&ctx->quiesce.completion);
  1082. completion_destroy(&ctx->quiesce.completion);
  1083. bool logged = false;
  1084. while(__atomic_load_n(&ctx->atomic.extents_currently_being_flushed, __ATOMIC_RELAXED) ||
  1085. __atomic_load_n(&ctx->atomic.inflight_queries, __ATOMIC_RELAXED)) {
  1086. if(!logged) {
  1087. logged = true;
  1088. netdata_log_info("DBENGINE: waiting for %zu inflight queries to finish to shutdown tier %d...",
  1089. __atomic_load_n(&ctx->atomic.inflight_queries, __ATOMIC_RELAXED),
  1090. (ctx->config.legacy) ? -1 : ctx->config.tier);
  1091. }
  1092. sleep_usec(1 * USEC_PER_MS);
  1093. }
  1094. completion_mark_complete(completion);
  1095. return data;
  1096. }
  1097. static void *cache_flush_tp_worker(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t *uv_work_req __maybe_unused) {
  1098. if (!main_cache)
  1099. return data;
  1100. worker_is_busy(UV_EVENT_DBENGINE_FLUSH_MAIN_CACHE);
  1101. pgc_flush_pages(main_cache, 0);
  1102. return data;
  1103. }
  1104. static void *cache_evict_tp_worker(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t *req __maybe_unused) {
  1105. if (!main_cache)
  1106. return data;
  1107. worker_is_busy(UV_EVENT_DBENGINE_EVICT_MAIN_CACHE);
  1108. pgc_evict_pages(main_cache, 0, 0);
  1109. return data;
  1110. }
  1111. static void *query_prep_tp_worker(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t *req __maybe_unused) {
  1112. PDC *pdc = data;
  1113. rrdeng_prep_query(pdc, true);
  1114. return data;
  1115. }
  1116. unsigned rrdeng_target_data_file_size(struct rrdengine_instance *ctx) {
  1117. unsigned target_size = ctx->config.max_disk_space / TARGET_DATAFILES;
  1118. target_size = MIN(target_size, MAX_DATAFILE_SIZE);
  1119. target_size = MAX(target_size, MIN_DATAFILE_SIZE);
  1120. return target_size;
  1121. }
  1122. bool rrdeng_ctx_exceeded_disk_quota(struct rrdengine_instance *ctx)
  1123. {
  1124. uint64_t estimated_disk_space = ctx_current_disk_space_get(ctx) + rrdeng_target_data_file_size(ctx) -
  1125. (ctx->datafiles.first->prev ? ctx->datafiles.first->prev->pos : 0);
  1126. return estimated_disk_space > ctx->config.max_disk_space;
  1127. }
  1128. /* return 0 on success */
  1129. int init_rrd_files(struct rrdengine_instance *ctx)
  1130. {
  1131. return init_data_files(ctx);
  1132. }
  1133. void finalize_rrd_files(struct rrdengine_instance *ctx)
  1134. {
  1135. return finalize_data_files(ctx);
  1136. }
  1137. void async_cb(uv_async_t *handle)
  1138. {
  1139. uv_stop(handle->loop);
  1140. uv_update_time(handle->loop);
  1141. netdata_log_debug(D_RRDENGINE, "%s called, active=%d.", __func__, uv_is_active((uv_handle_t *)handle));
  1142. }
  1143. #define TIMER_PERIOD_MS (1000)
  1144. static void *extent_read_tp_worker(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t *uv_work_req __maybe_unused) {
  1145. EPDL *epdl = data;
  1146. epdl_find_extent_and_populate_pages(ctx, epdl, true);
  1147. return data;
  1148. }
  1149. static void epdl_populate_pages_asynchronously(struct rrdengine_instance *ctx, EPDL *epdl, STORAGE_PRIORITY priority) {
  1150. rrdeng_enq_cmd(ctx, RRDENG_OPCODE_EXTENT_READ, epdl, NULL, priority,
  1151. rrdeng_enqueue_epdl_cmd, rrdeng_dequeue_epdl_cmd);
  1152. }
  1153. void pdc_route_asynchronously(struct rrdengine_instance *ctx, struct page_details_control *pdc) {
  1154. pdc_to_epdl_router(ctx, pdc, epdl_populate_pages_asynchronously, epdl_populate_pages_asynchronously);
  1155. }
  1156. void epdl_populate_pages_synchronously(struct rrdengine_instance *ctx, EPDL *epdl, enum storage_priority priority __maybe_unused) {
  1157. epdl_find_extent_and_populate_pages(ctx, epdl, false);
  1158. }
  1159. void pdc_route_synchronously(struct rrdengine_instance *ctx, struct page_details_control *pdc) {
  1160. pdc_to_epdl_router(ctx, pdc, epdl_populate_pages_synchronously, epdl_populate_pages_synchronously);
  1161. }
  1162. #define MAX_RETRIES_TO_START_INDEX (100)
  1163. static void *journal_v2_indexing_tp_worker(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t *uv_work_req __maybe_unused) {
  1164. unsigned count = 0;
  1165. worker_is_busy(UV_EVENT_DBENGINE_JOURNAL_INDEX_WAIT);
  1166. while (__atomic_load_n(&ctx->atomic.now_deleting_files, __ATOMIC_RELAXED) && count++ < MAX_RETRIES_TO_START_INDEX)
  1167. sleep_usec(100 * USEC_PER_MS);
  1168. if (count == MAX_RETRIES_TO_START_INDEX) {
  1169. worker_is_idle();
  1170. return data;
  1171. }
  1172. struct rrdengine_datafile *datafile = ctx->datafiles.first;
  1173. worker_is_busy(UV_EVENT_DBENGINE_JOURNAL_INDEX);
  1174. count = 0;
  1175. while (datafile && datafile->fileno != ctx_last_fileno_get(ctx) && datafile->fileno != ctx_last_flush_fileno_get(ctx)) {
  1176. if(journalfile_v2_data_available(datafile->journalfile)) {
  1177. // journal file v2 is already there for this datafile
  1178. datafile = datafile->next;
  1179. continue;
  1180. }
  1181. spinlock_lock(&datafile->writers.spinlock);
  1182. bool available = (datafile->writers.running || datafile->writers.flushed_to_open_running) ? false : true;
  1183. spinlock_unlock(&datafile->writers.spinlock);
  1184. if(!available) {
  1185. netdata_log_info("DBENGINE: journal file %u needs to be indexed, but it has writers working on it - skipping it for now", datafile->fileno);
  1186. datafile = datafile->next;
  1187. continue;
  1188. }
  1189. netdata_log_info("DBENGINE: journal file %u is ready to be indexed", datafile->fileno);
  1190. pgc_open_cache_to_journal_v2(open_cache, (Word_t) ctx, (int) datafile->fileno, ctx->config.page_type,
  1191. journalfile_migrate_to_v2_callback, (void *) datafile->journalfile);
  1192. count++;
  1193. datafile = datafile->next;
  1194. if (unlikely(!ctx_is_available_for_queries(ctx)))
  1195. break;
  1196. }
  1197. errno = 0;
  1198. internal_error(count, "DBENGINE: journal indexing done; %u files processed", count);
  1199. worker_is_idle();
  1200. return data;
  1201. }
  1202. static void after_do_cache_flush(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t* req __maybe_unused, int status __maybe_unused) {
  1203. rrdeng_main.flushes_running--;
  1204. }
  1205. static void after_do_cache_evict(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t* req __maybe_unused, int status __maybe_unused) {
  1206. rrdeng_main.evictions_running--;
  1207. }
  1208. static void after_journal_v2_indexing(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t* req __maybe_unused, int status __maybe_unused) {
  1209. __atomic_store_n(&ctx->atomic.migration_to_v2_running, false, __ATOMIC_RELAXED);
  1210. rrdeng_enq_cmd(ctx, RRDENG_OPCODE_DATABASE_ROTATE, NULL, NULL, STORAGE_PRIORITY_INTERNAL_DBENGINE, NULL, NULL);
  1211. }
  1212. struct rrdeng_buffer_sizes rrdeng_get_buffer_sizes(void) {
  1213. return (struct rrdeng_buffer_sizes) {
  1214. .pgc = pgc_aral_overhead() + pgc_aral_structures(),
  1215. .mrg = mrg_aral_overhead() + mrg_aral_structures(),
  1216. .opcodes = aral_overhead(rrdeng_main.cmd_queue.ar) + aral_structures(rrdeng_main.cmd_queue.ar),
  1217. .handles = aral_overhead(rrdeng_main.handles.ar) + aral_structures(rrdeng_main.handles.ar),
  1218. .descriptors = aral_overhead(rrdeng_main.descriptors.ar) + aral_structures(rrdeng_main.descriptors.ar),
  1219. .wal = __atomic_load_n(&wal_globals.atomics.allocated, __ATOMIC_RELAXED) * (sizeof(WAL) + RRDENG_BLOCK_SIZE),
  1220. .workers = aral_overhead(rrdeng_main.work_cmd.ar),
  1221. .pdc = pdc_cache_size(),
  1222. .xt_io = aral_overhead(rrdeng_main.xt_io_descr.ar) + aral_structures(rrdeng_main.xt_io_descr.ar),
  1223. .xt_buf = extent_buffer_cache_size(),
  1224. .epdl = epdl_cache_size(),
  1225. .deol = deol_cache_size(),
  1226. .pd = pd_cache_size(),
  1227. #ifdef PDC_USE_JULYL
  1228. .julyl = julyl_cache_size(),
  1229. #endif
  1230. };
  1231. }
  1232. static void after_cleanup(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t* req __maybe_unused, int status __maybe_unused) {
  1233. rrdeng_main.cleanup_running--;
  1234. }
  1235. static void *cleanup_tp_worker(struct rrdengine_instance *ctx __maybe_unused, void *data __maybe_unused, struct completion *completion __maybe_unused, uv_work_t *uv_work_req __maybe_unused) {
  1236. worker_is_busy(UV_EVENT_DBENGINE_BUFFERS_CLEANUP);
  1237. wal_cleanup1();
  1238. extent_buffer_cleanup1();
  1239. {
  1240. static time_t last_run_s = 0;
  1241. time_t now_s = now_monotonic_sec();
  1242. if(now_s - last_run_s >= 10) {
  1243. last_run_s = now_s;
  1244. journalfile_v2_data_unmount_cleanup(now_s);
  1245. }
  1246. }
  1247. #ifdef PDC_USE_JULYL
  1248. julyl_cleanup1();
  1249. #endif
  1250. return data;
  1251. }
  1252. void timer_cb(uv_timer_t* handle) {
  1253. worker_is_busy(RRDENG_TIMER_CB);
  1254. uv_stop(handle->loop);
  1255. uv_update_time(handle->loop);
  1256. worker_set_metric(RRDENG_OPCODES_WAITING, (NETDATA_DOUBLE)rrdeng_main.cmd_queue.unsafe.waiting);
  1257. worker_set_metric(RRDENG_WORKS_DISPATCHED, (NETDATA_DOUBLE)__atomic_load_n(&rrdeng_main.work_cmd.atomics.dispatched, __ATOMIC_RELAXED));
  1258. worker_set_metric(RRDENG_WORKS_EXECUTING, (NETDATA_DOUBLE)__atomic_load_n(&rrdeng_main.work_cmd.atomics.executing, __ATOMIC_RELAXED));
  1259. rrdeng_enq_cmd(NULL, RRDENG_OPCODE_FLUSH_INIT, NULL, NULL, STORAGE_PRIORITY_INTERNAL_DBENGINE, NULL, NULL);
  1260. rrdeng_enq_cmd(NULL, RRDENG_OPCODE_EVICT_INIT, NULL, NULL, STORAGE_PRIORITY_INTERNAL_DBENGINE, NULL, NULL);
  1261. rrdeng_enq_cmd(NULL, RRDENG_OPCODE_CLEANUP, NULL, NULL, STORAGE_PRIORITY_INTERNAL_DBENGINE, NULL, NULL);
  1262. worker_is_idle();
  1263. }
  1264. static void dbengine_initialize_structures(void) {
  1265. pgc_and_mrg_initialize();
  1266. pdc_init();
  1267. page_details_init();
  1268. epdl_init();
  1269. deol_init();
  1270. rrdeng_cmd_queue_init();
  1271. work_request_init();
  1272. rrdeng_query_handle_init();
  1273. page_descriptors_init();
  1274. extent_buffer_init();
  1275. dbengine_page_alloc_init();
  1276. extent_io_descriptor_init();
  1277. }
  1278. bool rrdeng_dbengine_spawn(struct rrdengine_instance *ctx __maybe_unused) {
  1279. static bool spawned = false;
  1280. static SPINLOCK spinlock = NETDATA_SPINLOCK_INITIALIZER;
  1281. spinlock_lock(&spinlock);
  1282. if(!spawned) {
  1283. int ret;
  1284. ret = uv_loop_init(&rrdeng_main.loop);
  1285. if (ret) {
  1286. netdata_log_error("DBENGINE: uv_loop_init(): %s", uv_strerror(ret));
  1287. return false;
  1288. }
  1289. rrdeng_main.loop.data = &rrdeng_main;
  1290. ret = uv_async_init(&rrdeng_main.loop, &rrdeng_main.async, async_cb);
  1291. if (ret) {
  1292. netdata_log_error("DBENGINE: uv_async_init(): %s", uv_strerror(ret));
  1293. fatal_assert(0 == uv_loop_close(&rrdeng_main.loop));
  1294. return false;
  1295. }
  1296. rrdeng_main.async.data = &rrdeng_main;
  1297. ret = uv_timer_init(&rrdeng_main.loop, &rrdeng_main.timer);
  1298. if (ret) {
  1299. netdata_log_error("DBENGINE: uv_timer_init(): %s", uv_strerror(ret));
  1300. uv_close((uv_handle_t *)&rrdeng_main.async, NULL);
  1301. fatal_assert(0 == uv_loop_close(&rrdeng_main.loop));
  1302. return false;
  1303. }
  1304. rrdeng_main.timer.data = &rrdeng_main;
  1305. dbengine_initialize_structures();
  1306. fatal_assert(0 == uv_thread_create(&rrdeng_main.thread, dbengine_event_loop, &rrdeng_main));
  1307. spawned = true;
  1308. }
  1309. spinlock_unlock(&spinlock);
  1310. return true;
  1311. }
  1312. static inline void worker_dispatch_extent_read(struct rrdeng_cmd cmd, bool from_worker) {
  1313. struct rrdengine_instance *ctx = cmd.ctx;
  1314. EPDL *epdl = cmd.data;
  1315. if(from_worker)
  1316. epdl_find_extent_and_populate_pages(ctx, epdl, true);
  1317. else
  1318. work_dispatch(ctx, epdl, NULL, cmd.opcode, extent_read_tp_worker, NULL);
  1319. }
  1320. static inline void worker_dispatch_query_prep(struct rrdeng_cmd cmd, bool from_worker) {
  1321. struct rrdengine_instance *ctx = cmd.ctx;
  1322. PDC *pdc = cmd.data;
  1323. if(from_worker)
  1324. rrdeng_prep_query(pdc, true);
  1325. else
  1326. work_dispatch(ctx, pdc, NULL, cmd.opcode, query_prep_tp_worker, NULL);
  1327. }
  1328. void dbengine_event_loop(void* arg) {
  1329. sanity_check();
  1330. uv_thread_set_name_np(pthread_self(), "DBENGINE");
  1331. service_register(SERVICE_THREAD_TYPE_EVENT_LOOP, NULL, NULL, NULL, true);
  1332. worker_register("DBENGINE");
  1333. // opcode jobs
  1334. worker_register_job_name(RRDENG_OPCODE_NOOP, "noop");
  1335. worker_register_job_name(RRDENG_OPCODE_QUERY, "query");
  1336. worker_register_job_name(RRDENG_OPCODE_EXTENT_WRITE, "extent write");
  1337. worker_register_job_name(RRDENG_OPCODE_EXTENT_READ, "extent read");
  1338. worker_register_job_name(RRDENG_OPCODE_FLUSHED_TO_OPEN, "flushed to open");
  1339. worker_register_job_name(RRDENG_OPCODE_DATABASE_ROTATE, "db rotate");
  1340. worker_register_job_name(RRDENG_OPCODE_JOURNAL_INDEX, "journal index");
  1341. worker_register_job_name(RRDENG_OPCODE_FLUSH_INIT, "flush init");
  1342. worker_register_job_name(RRDENG_OPCODE_EVICT_INIT, "evict init");
  1343. worker_register_job_name(RRDENG_OPCODE_CTX_SHUTDOWN, "ctx shutdown");
  1344. worker_register_job_name(RRDENG_OPCODE_CTX_QUIESCE, "ctx quiesce");
  1345. worker_register_job_name(RRDENG_OPCODE_MAX, "get opcode");
  1346. worker_register_job_name(RRDENG_OPCODE_MAX + RRDENG_OPCODE_QUERY, "query cb");
  1347. worker_register_job_name(RRDENG_OPCODE_MAX + RRDENG_OPCODE_EXTENT_WRITE, "extent write cb");
  1348. worker_register_job_name(RRDENG_OPCODE_MAX + RRDENG_OPCODE_EXTENT_READ, "extent read cb");
  1349. worker_register_job_name(RRDENG_OPCODE_MAX + RRDENG_OPCODE_FLUSHED_TO_OPEN, "flushed to open cb");
  1350. worker_register_job_name(RRDENG_OPCODE_MAX + RRDENG_OPCODE_DATABASE_ROTATE, "db rotate cb");
  1351. worker_register_job_name(RRDENG_OPCODE_MAX + RRDENG_OPCODE_JOURNAL_INDEX, "journal index cb");
  1352. worker_register_job_name(RRDENG_OPCODE_MAX + RRDENG_OPCODE_FLUSH_INIT, "flush init cb");
  1353. worker_register_job_name(RRDENG_OPCODE_MAX + RRDENG_OPCODE_EVICT_INIT, "evict init cb");
  1354. worker_register_job_name(RRDENG_OPCODE_MAX + RRDENG_OPCODE_CTX_SHUTDOWN, "ctx shutdown cb");
  1355. worker_register_job_name(RRDENG_OPCODE_MAX + RRDENG_OPCODE_CTX_QUIESCE, "ctx quiesce cb");
  1356. // special jobs
  1357. worker_register_job_name(RRDENG_TIMER_CB, "timer");
  1358. worker_register_job_name(RRDENG_FLUSH_TRANSACTION_BUFFER_CB, "transaction buffer flush cb");
  1359. worker_register_job_custom_metric(RRDENG_OPCODES_WAITING, "opcodes waiting", "opcodes", WORKER_METRIC_ABSOLUTE);
  1360. worker_register_job_custom_metric(RRDENG_WORKS_DISPATCHED, "works dispatched", "works", WORKER_METRIC_ABSOLUTE);
  1361. worker_register_job_custom_metric(RRDENG_WORKS_EXECUTING, "works executing", "works", WORKER_METRIC_ABSOLUTE);
  1362. struct rrdeng_main *main = arg;
  1363. enum rrdeng_opcode opcode;
  1364. struct rrdeng_cmd cmd;
  1365. main->tid = gettid();
  1366. fatal_assert(0 == uv_timer_start(&main->timer, timer_cb, TIMER_PERIOD_MS, TIMER_PERIOD_MS));
  1367. bool shutdown = false;
  1368. while (likely(!shutdown)) {
  1369. worker_is_idle();
  1370. uv_run(&main->loop, UV_RUN_DEFAULT);
  1371. /* wait for commands */
  1372. do {
  1373. worker_is_busy(RRDENG_OPCODE_MAX);
  1374. cmd = rrdeng_deq_cmd(RRDENG_OPCODE_NOOP);
  1375. opcode = cmd.opcode;
  1376. worker_is_busy(opcode);
  1377. switch (opcode) {
  1378. case RRDENG_OPCODE_EXTENT_READ:
  1379. worker_dispatch_extent_read(cmd, false);
  1380. break;
  1381. case RRDENG_OPCODE_QUERY:
  1382. worker_dispatch_query_prep(cmd, false);
  1383. break;
  1384. case RRDENG_OPCODE_EXTENT_WRITE: {
  1385. struct rrdengine_instance *ctx = cmd.ctx;
  1386. struct page_descr_with_data *base = cmd.data;
  1387. struct completion *completion = cmd.completion; // optional
  1388. work_dispatch(ctx, base, completion, opcode, extent_write_tp_worker, after_extent_write);
  1389. break;
  1390. }
  1391. case RRDENG_OPCODE_FLUSHED_TO_OPEN: {
  1392. struct rrdengine_instance *ctx = cmd.ctx;
  1393. uv_fs_t *uv_fs_request = cmd.data;
  1394. struct extent_io_descriptor *xt_io_descr = uv_fs_request->data;
  1395. struct completion *completion = xt_io_descr->completion;
  1396. work_dispatch(ctx, uv_fs_request, completion, opcode, extent_flushed_to_open_tp_worker, after_extent_flushed_to_open);
  1397. break;
  1398. }
  1399. case RRDENG_OPCODE_FLUSH_INIT: {
  1400. if(rrdeng_main.flushes_running < (size_t)(libuv_worker_threads / 4)) {
  1401. rrdeng_main.flushes_running++;
  1402. work_dispatch(NULL, NULL, NULL, opcode, cache_flush_tp_worker, after_do_cache_flush);
  1403. }
  1404. break;
  1405. }
  1406. case RRDENG_OPCODE_EVICT_INIT: {
  1407. if(!rrdeng_main.evictions_running) {
  1408. rrdeng_main.evictions_running++;
  1409. work_dispatch(NULL, NULL, NULL, opcode, cache_evict_tp_worker, after_do_cache_evict);
  1410. }
  1411. break;
  1412. }
  1413. case RRDENG_OPCODE_CLEANUP: {
  1414. if(!rrdeng_main.cleanup_running) {
  1415. rrdeng_main.cleanup_running++;
  1416. work_dispatch(NULL, NULL, NULL, opcode, cleanup_tp_worker, after_cleanup);
  1417. }
  1418. break;
  1419. }
  1420. case RRDENG_OPCODE_JOURNAL_INDEX: {
  1421. struct rrdengine_instance *ctx = cmd.ctx;
  1422. struct rrdengine_datafile *datafile = cmd.data;
  1423. if(!__atomic_load_n(&ctx->atomic.migration_to_v2_running, __ATOMIC_RELAXED)) {
  1424. __atomic_store_n(&ctx->atomic.migration_to_v2_running, true, __ATOMIC_RELAXED);
  1425. work_dispatch(ctx, datafile, NULL, opcode, journal_v2_indexing_tp_worker, after_journal_v2_indexing);
  1426. }
  1427. break;
  1428. }
  1429. case RRDENG_OPCODE_DATABASE_ROTATE: {
  1430. struct rrdengine_instance *ctx = cmd.ctx;
  1431. if (!__atomic_load_n(&ctx->atomic.now_deleting_files, __ATOMIC_RELAXED) &&
  1432. ctx->datafiles.first->next != NULL &&
  1433. ctx->datafiles.first->next->next != NULL &&
  1434. rrdeng_ctx_exceeded_disk_quota(ctx)) {
  1435. __atomic_store_n(&ctx->atomic.now_deleting_files, true, __ATOMIC_RELAXED);
  1436. work_dispatch(ctx, NULL, NULL, opcode, database_rotate_tp_worker, after_database_rotate);
  1437. }
  1438. break;
  1439. }
  1440. case RRDENG_OPCODE_CTX_POPULATE_MRG: {
  1441. struct rrdengine_instance *ctx = cmd.ctx;
  1442. struct completion *completion = cmd.completion;
  1443. work_dispatch(ctx, NULL, completion, opcode, populate_mrg_tp_worker, after_populate_mrg);
  1444. break;
  1445. }
  1446. case RRDENG_OPCODE_CTX_QUIESCE: {
  1447. // a ctx will shutdown shortly
  1448. struct rrdengine_instance *ctx = cmd.ctx;
  1449. __atomic_store_n(&ctx->quiesce.enabled, true, __ATOMIC_RELEASE);
  1450. work_dispatch(ctx, NULL, NULL, opcode,
  1451. flush_all_hot_and_dirty_pages_of_section_tp_worker,
  1452. after_flush_all_hot_and_dirty_pages_of_section);
  1453. break;
  1454. }
  1455. case RRDENG_OPCODE_CTX_SHUTDOWN: {
  1456. // a ctx is shutting down
  1457. struct rrdengine_instance *ctx = cmd.ctx;
  1458. struct completion *completion = cmd.completion;
  1459. work_dispatch(ctx, NULL, completion, opcode, ctx_shutdown_tp_worker, after_ctx_shutdown);
  1460. break;
  1461. }
  1462. case RRDENG_OPCODE_NOOP: {
  1463. /* the command queue was empty, do nothing */
  1464. break;
  1465. }
  1466. // not opcodes
  1467. case RRDENG_OPCODE_MAX:
  1468. default: {
  1469. internal_fatal(true, "DBENGINE: unknown opcode");
  1470. break;
  1471. }
  1472. }
  1473. } while (opcode != RRDENG_OPCODE_NOOP);
  1474. }
  1475. /* cleanup operations of the event loop */
  1476. netdata_log_info("DBENGINE: shutting down dbengine thread");
  1477. /*
  1478. * uv_async_send after uv_close does not seem to crash in linux at the moment,
  1479. * it is however undocumented behaviour and we need to be aware if this becomes
  1480. * an issue in the future.
  1481. */
  1482. uv_close((uv_handle_t *)&main->async, NULL);
  1483. uv_timer_stop(&main->timer);
  1484. uv_close((uv_handle_t *)&main->timer, NULL);
  1485. uv_run(&main->loop, UV_RUN_DEFAULT);
  1486. uv_loop_close(&main->loop);
  1487. worker_unregister();
  1488. }