sqlite_metadata.c 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "sqlite_metadata.h"
  3. // SQL statements
  4. #define SQL_STORE_CLAIM_ID \
  5. "INSERT INTO node_instance " \
  6. "(host_id, claim_id, date_created) VALUES (@host_id, @claim_id, UNIXEPOCH()) " \
  7. "ON CONFLICT(host_id) DO UPDATE SET claim_id = excluded.claim_id"
  8. #define SQL_DELETE_HOST_LABELS "DELETE FROM host_label WHERE host_id = @uuid"
  9. #define STORE_HOST_LABEL \
  10. "INSERT INTO host_label (host_id, source_type, label_key, label_value, date_created) VALUES "
  11. #define STORE_CHART_LABEL \
  12. "INSERT INTO chart_label (chart_id, source_type, label_key, label_value, date_created) VALUES "
  13. #define STORE_HOST_OR_CHART_LABEL_VALUE "(u2h('%s'), %d,'%s','%s', unixepoch())"
  14. #define DELETE_DIMENSION_UUID "DELETE FROM dimension WHERE dim_id = @uuid"
  15. #define SQL_STORE_HOST_INFO \
  16. "INSERT OR REPLACE INTO host (host_id, hostname, registry_hostname, update_every, os, timezone, tags, hops, " \
  17. "memory_mode, abbrev_timezone, utc_offset, program_name, program_version, entries, health_enabled, last_connected) " \
  18. "VALUES (@host_id, @hostname, @registry_hostname, @update_every, @os, @timezone, @tags, @hops, " \
  19. "@memory_mode, @abbrev_tz, @utc_offset, @prog_name, @prog_version, @entries, @health_enabled, @last_connected)"
  20. #define SQL_STORE_CHART \
  21. "INSERT INTO chart (chart_id, host_id, type, id, name, family, context, title, unit, plugin, module, priority, " \
  22. "update_every, chart_type, memory_mode, history_entries) " \
  23. "values (@chart_id, @host_id, @type, @id, @name, @family, @context, @title, @unit, @plugin, @module, @priority, " \
  24. "@update_every, @chart_type, @memory_mode, @history_entries) " \
  25. "ON CONFLICT(chart_id) DO UPDATE SET type=excluded.type, id=excluded.id, name=excluded.name, " \
  26. "family=excluded.family, context=excluded.context, title=excluded.title, unit=excluded.unit, " \
  27. "plugin=excluded.plugin, module=excluded.module, priority=excluded.priority, update_every=excluded.update_every, " \
  28. "chart_type=excluded.chart_type, memory_mode = excluded.memory_mode, history_entries = excluded.history_entries"
  29. #define SQL_STORE_DIMENSION \
  30. "INSERT INTO dimension (dim_id, chart_id, id, name, multiplier, divisor , algorithm, options) " \
  31. "VALUES (@dim_id, @chart_id, @id, @name, @multiplier, @divisor, @algorithm, @options) " \
  32. "ON CONFLICT(dim_id) DO UPDATE SET id=excluded.id, name=excluded.name, multiplier=excluded.multiplier, " \
  33. "divisor=excluded.divisor, algorithm=excluded.algorithm, options=excluded.options"
  34. #define SELECT_DIMENSION_LIST "SELECT dim_id, rowid FROM dimension WHERE rowid > @row_id"
  35. #define SELECT_CHART_LIST "SELECT chart_id, rowid FROM chart WHERE rowid > @row_id"
  36. #define SELECT_CHART_LABEL_LIST "SELECT chart_id, rowid FROM chart_label WHERE rowid > @row_id"
  37. #define SQL_STORE_HOST_SYSTEM_INFO_VALUES \
  38. "INSERT OR REPLACE INTO host_info (host_id, system_key, system_value, date_created) VALUES " \
  39. "(@uuid, @name, @value, UNIXEPOCH())"
  40. #define MIGRATE_LOCALHOST_TO_NEW_MACHINE_GUID \
  41. "UPDATE chart SET host_id = @host_id WHERE host_id in (SELECT host_id FROM host where host_id <> @host_id and hops = 0)"
  42. #define DELETE_NON_EXISTING_LOCALHOST "DELETE FROM host WHERE hops = 0 AND host_id <> @host_id"
  43. #define DELETE_MISSING_NODE_INSTANCES "DELETE FROM node_instance WHERE host_id NOT IN (SELECT host_id FROM host)"
  44. #define METADATA_MAINTENANCE_FIRST_CHECK (1800) // Maintenance first run after agent startup in seconds
  45. #define METADATA_MAINTENANCE_REPEAT (60) // Repeat if last run for dimensions, charts, labels needs more work
  46. #define METADATA_HEALTH_LOG_INTERVAL (3600) // Repeat maintenance for health
  47. #define METADATA_DIM_CHECK_INTERVAL (3600) // Repeat maintenance for dimensions
  48. #define METADATA_CHART_CHECK_INTERVAL (3600) // Repeat maintenance for charts
  49. #define METADATA_LABEL_CHECK_INTERVAL (3600) // Repeat maintenance for labels
  50. #define METADATA_RUNTIME_THRESHOLD (5) // Run time threshold for cleanup task
  51. #define METADATA_HOST_CHECK_FIRST_CHECK (5) // First check for pending metadata
  52. #define METADATA_HOST_CHECK_INTERVAL (30) // Repeat check for pending metadata
  53. #define METADATA_HOST_CHECK_IMMEDIATE (5) // Repeat immediate run because we have more metadata to write
  54. #define MAX_METADATA_CLEANUP (500) // Maximum metadata write operations (e.g deletes before retrying)
  55. #define METADATA_MAX_BATCH_SIZE (512) // Maximum commands to execute before running the event loop
  56. #define DATABASE_FREE_PAGES_THRESHOLD_PC (5) // Percentage of free pages to trigger vacuum
  57. #define DATABASE_FREE_PAGES_VACUUM_PC (10) // Percentage of free pages to vacuum
  58. enum metadata_opcode {
  59. METADATA_DATABASE_NOOP = 0,
  60. METADATA_DATABASE_TIMER,
  61. METADATA_DEL_DIMENSION,
  62. METADATA_STORE_CLAIM_ID,
  63. METADATA_ADD_HOST_INFO,
  64. METADATA_SCAN_HOSTS,
  65. METADATA_LOAD_HOST_CONTEXT,
  66. METADATA_DELETE_HOST_CHART_LABELS,
  67. METADATA_MAINTENANCE,
  68. METADATA_SYNC_SHUTDOWN,
  69. METADATA_UNITTEST,
  70. // leave this last
  71. // we need it to check for worker utilization
  72. METADATA_MAX_ENUMERATIONS_DEFINED
  73. };
  74. #define MAX_PARAM_LIST (2)
  75. struct metadata_cmd {
  76. enum metadata_opcode opcode;
  77. struct completion *completion;
  78. const void *param[MAX_PARAM_LIST];
  79. struct metadata_cmd *prev, *next;
  80. };
  81. typedef enum {
  82. METADATA_FLAG_PROCESSING = (1 << 0), // store or cleanup
  83. METADATA_FLAG_SHUTDOWN = (1 << 1), // Shutting down
  84. } METADATA_FLAG;
  85. struct metadata_wc {
  86. uv_thread_t thread;
  87. uv_loop_t *loop;
  88. uv_async_t async;
  89. uv_timer_t timer_req;
  90. time_t metadata_check_after;
  91. METADATA_FLAG flags;
  92. struct completion start_stop_complete;
  93. struct completion *scan_complete;
  94. /* FIFO command queue */
  95. SPINLOCK cmd_queue_lock;
  96. struct metadata_cmd *cmd_base;
  97. };
  98. #define metadata_flag_check(target_flags, flag) (__atomic_load_n(&((target_flags)->flags), __ATOMIC_SEQ_CST) & (flag))
  99. #define metadata_flag_set(target_flags, flag) __atomic_or_fetch(&((target_flags)->flags), (flag), __ATOMIC_SEQ_CST)
  100. #define metadata_flag_clear(target_flags, flag) __atomic_and_fetch(&((target_flags)->flags), ~(flag), __ATOMIC_SEQ_CST)
  101. struct metadata_wc metasync_worker = {.loop = NULL};
  102. //
  103. // For unittest
  104. //
  105. struct thread_unittest {
  106. int join;
  107. unsigned added;
  108. unsigned processed;
  109. unsigned *done;
  110. };
  111. // Metadata functions
  112. struct query_build {
  113. BUFFER *sql;
  114. int count;
  115. char uuid_str[UUID_STR_LEN];
  116. };
  117. #define SQL_DELETE_CHART_LABELS_BY_HOST \
  118. "DELETE FROM chart_label WHERE chart_id in (SELECT chart_id FROM chart WHERE host_id = @host_id)"
  119. static void delete_host_chart_labels(uuid_t *host_uuid)
  120. {
  121. sqlite3_stmt *res = NULL;
  122. int rc = sqlite3_prepare_v2(db_meta, SQL_DELETE_CHART_LABELS_BY_HOST, -1, &res, 0);
  123. if (unlikely(rc != SQLITE_OK)) {
  124. error_report("Failed to prepare statement to delete chart labels by host");
  125. return;
  126. }
  127. rc = sqlite3_bind_blob(res, 1, host_uuid, sizeof(*host_uuid), SQLITE_STATIC);
  128. if (unlikely(rc != SQLITE_OK)) {
  129. error_report("Failed to bind host_id parameter to host chart labels");
  130. goto failed;
  131. }
  132. rc = sqlite3_step_monitored(res);
  133. if (unlikely(rc != SQLITE_DONE))
  134. error_report("Failed to execute command to remove host chart labels");
  135. failed:
  136. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  137. error_report("Failed to finalize statement to remove host chart labels");
  138. }
  139. static int host_label_store_to_sql_callback(const char *name, const char *value, RRDLABEL_SRC ls, void *data) {
  140. struct query_build *lb = data;
  141. if (unlikely(!lb->count))
  142. buffer_sprintf(lb->sql, STORE_HOST_LABEL);
  143. else
  144. buffer_strcat(lb->sql, ", ");
  145. buffer_sprintf(lb->sql, STORE_HOST_OR_CHART_LABEL_VALUE, lb->uuid_str, (int) (ls & ~(RRDLABEL_FLAG_INTERNAL)), name, value);
  146. lb->count++;
  147. return 1;
  148. }
  149. static int chart_label_store_to_sql_callback(const char *name, const char *value, RRDLABEL_SRC ls, void *data) {
  150. struct query_build *lb = data;
  151. if (unlikely(!lb->count))
  152. buffer_sprintf(lb->sql, STORE_CHART_LABEL);
  153. else
  154. buffer_strcat(lb->sql, ", ");
  155. buffer_sprintf(lb->sql, STORE_HOST_OR_CHART_LABEL_VALUE, lb->uuid_str, (int) (ls & ~(RRDLABEL_FLAG_INTERNAL)), name, value);
  156. lb->count++;
  157. return 1;
  158. }
  159. #define SQL_DELETE_CHART_LABEL "DELETE FROM chart_label WHERE chart_id = @chart_id"
  160. #define SQL_DELETE_CHART_LABEL_HISTORY "DELETE FROM chart_label WHERE date_created < %ld AND chart_id = @chart_id"
  161. static void clean_old_chart_labels(RRDSET *st)
  162. {
  163. char sql[512];
  164. time_t first_time_s = rrdset_first_entry_s(st);
  165. if (unlikely(!first_time_s))
  166. snprintfz(sql, sizeof(sql) - 1, SQL_DELETE_CHART_LABEL);
  167. else
  168. snprintfz(sql, sizeof(sql) - 1, SQL_DELETE_CHART_LABEL_HISTORY, first_time_s);
  169. int rc = exec_statement_with_uuid(sql, &st->chart_uuid);
  170. if (unlikely(rc))
  171. error_report("METADATA: 'host:%s' Failed to clean old labels for chart %s", rrdhost_hostname(st->rrdhost), rrdset_name(st));
  172. }
  173. static int check_and_update_chart_labels(RRDSET *st, BUFFER *work_buffer, size_t *query_counter)
  174. {
  175. size_t old_version = st->rrdlabels_last_saved_version;
  176. size_t new_version = rrdlabels_version(st->rrdlabels);
  177. if (new_version == old_version)
  178. return 0;
  179. struct query_build tmp = {.sql = work_buffer, .count = 0};
  180. uuid_unparse_lower(st->chart_uuid, tmp.uuid_str);
  181. rrdlabels_walkthrough_read(st->rrdlabels, chart_label_store_to_sql_callback, &tmp);
  182. buffer_strcat(work_buffer, " ON CONFLICT (chart_id, label_key) DO UPDATE SET source_type = excluded.source_type, label_value=excluded.label_value, date_created=UNIXEPOCH()");
  183. int rc = db_execute(db_meta, buffer_tostring(work_buffer));
  184. if (likely(!rc)) {
  185. st->rrdlabels_last_saved_version = new_version;
  186. (*query_counter)++;
  187. }
  188. clean_old_chart_labels(st);
  189. return rc;
  190. }
  191. // Migrate all hosts with hops zero to this host_uuid
  192. void migrate_localhost(uuid_t *host_uuid)
  193. {
  194. int rc;
  195. rc = exec_statement_with_uuid(MIGRATE_LOCALHOST_TO_NEW_MACHINE_GUID, host_uuid);
  196. if (!rc)
  197. rc = exec_statement_with_uuid(DELETE_NON_EXISTING_LOCALHOST, host_uuid);
  198. if (!rc) {
  199. if (unlikely(db_execute(db_meta, DELETE_MISSING_NODE_INSTANCES)))
  200. error_report("Failed to remove deleted hosts from node instances");
  201. }
  202. }
  203. static int store_claim_id(uuid_t *host_id, uuid_t *claim_id)
  204. {
  205. sqlite3_stmt *res = NULL;
  206. int rc;
  207. if (unlikely(!db_meta)) {
  208. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  209. error_report("Database has not been initialized");
  210. return 1;
  211. }
  212. rc = sqlite3_prepare_v2(db_meta, SQL_STORE_CLAIM_ID, -1, &res, 0);
  213. if (unlikely(rc != SQLITE_OK)) {
  214. error_report("Failed to prepare statement to store host claim id");
  215. return 1;
  216. }
  217. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  218. if (unlikely(rc != SQLITE_OK)) {
  219. error_report("Failed to bind host_id parameter to store claim id");
  220. goto failed;
  221. }
  222. if (claim_id)
  223. rc = sqlite3_bind_blob(res, 2, claim_id, sizeof(*claim_id), SQLITE_STATIC);
  224. else
  225. rc = sqlite3_bind_null(res, 2);
  226. if (unlikely(rc != SQLITE_OK)) {
  227. error_report("Failed to bind claim_id parameter to host claim id");
  228. goto failed;
  229. }
  230. rc = execute_insert(res);
  231. if (unlikely(rc != SQLITE_DONE))
  232. error_report("Failed to store host claim id rc = %d", rc);
  233. failed:
  234. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  235. error_report("Failed to finalize the prepared statement when storing a host claim id");
  236. return rc != SQLITE_DONE;
  237. }
  238. static void delete_dimension_uuid(uuid_t *dimension_uuid, sqlite3_stmt **action_res __maybe_unused, bool flag __maybe_unused)
  239. {
  240. static __thread sqlite3_stmt *res = NULL;
  241. int rc;
  242. if (unlikely(!res)) {
  243. rc = prepare_statement(db_meta, DELETE_DIMENSION_UUID, &res);
  244. if (rc != SQLITE_OK) {
  245. error_report("Failed to prepare statement to delete a dimension uuid");
  246. return;
  247. }
  248. }
  249. rc = sqlite3_bind_blob(res, 1, dimension_uuid, sizeof(*dimension_uuid), SQLITE_STATIC);
  250. if (unlikely(rc != SQLITE_OK))
  251. goto skip_execution;
  252. rc = sqlite3_step_monitored(res);
  253. if (unlikely(rc != SQLITE_DONE))
  254. error_report("Failed to delete dimension uuid, rc = %d", rc);
  255. skip_execution:
  256. rc = sqlite3_reset(res);
  257. if (unlikely(rc != SQLITE_OK))
  258. error_report("Failed to reset statement when deleting dimension UUID, rc = %d", rc);
  259. }
  260. //
  261. // Store host and host system info information in the database
  262. static int store_host_metadata(RRDHOST *host)
  263. {
  264. static __thread sqlite3_stmt *res = NULL;
  265. int rc, param = 0;
  266. if (unlikely((!res))) {
  267. rc = prepare_statement(db_meta, SQL_STORE_HOST_INFO, &res);
  268. if (unlikely(rc != SQLITE_OK)) {
  269. error_report("Failed to prepare statement to store host, rc = %d", rc);
  270. return 1;
  271. }
  272. }
  273. rc = sqlite3_bind_blob(res, ++param, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
  274. if (unlikely(rc != SQLITE_OK))
  275. goto bind_fail;
  276. rc = bind_text_null(res, ++param, rrdhost_hostname(host), 0);
  277. if (unlikely(rc != SQLITE_OK))
  278. goto bind_fail;
  279. rc = bind_text_null(res, ++param, rrdhost_registry_hostname(host), 1);
  280. if (unlikely(rc != SQLITE_OK))
  281. goto bind_fail;
  282. rc = sqlite3_bind_int(res, ++param, host->rrd_update_every);
  283. if (unlikely(rc != SQLITE_OK))
  284. goto bind_fail;
  285. rc = bind_text_null(res, ++param, rrdhost_os(host), 1);
  286. if (unlikely(rc != SQLITE_OK))
  287. goto bind_fail;
  288. rc = bind_text_null(res, ++param, rrdhost_timezone(host), 1);
  289. if (unlikely(rc != SQLITE_OK))
  290. goto bind_fail;
  291. rc = bind_text_null(res, ++param, rrdhost_tags(host), 1);
  292. if (unlikely(rc != SQLITE_OK))
  293. goto bind_fail;
  294. rc = sqlite3_bind_int(res, ++param, host->system_info ? host->system_info->hops : 0);
  295. if (unlikely(rc != SQLITE_OK))
  296. goto bind_fail;
  297. rc = sqlite3_bind_int(res, ++param, host->rrd_memory_mode);
  298. if (unlikely(rc != SQLITE_OK))
  299. goto bind_fail;
  300. rc = bind_text_null(res, ++param, rrdhost_abbrev_timezone(host), 1);
  301. if (unlikely(rc != SQLITE_OK))
  302. goto bind_fail;
  303. rc = sqlite3_bind_int(res, ++param, host->utc_offset);
  304. if (unlikely(rc != SQLITE_OK))
  305. goto bind_fail;
  306. rc = bind_text_null(res, ++param, rrdhost_program_name(host), 1);
  307. if (unlikely(rc != SQLITE_OK))
  308. goto bind_fail;
  309. rc = bind_text_null(res, ++param, rrdhost_program_version(host), 1);
  310. if (unlikely(rc != SQLITE_OK))
  311. goto bind_fail;
  312. rc = sqlite3_bind_int64(res, ++param, host->rrd_history_entries);
  313. if (unlikely(rc != SQLITE_OK))
  314. goto bind_fail;
  315. rc = sqlite3_bind_int(res, ++param, (int ) host->health.health_enabled);
  316. if (unlikely(rc != SQLITE_OK))
  317. goto bind_fail;
  318. rc = sqlite3_bind_int64(res, ++param, (sqlite3_int64) host->last_connected);
  319. if (unlikely(rc != SQLITE_OK))
  320. goto bind_fail;
  321. int store_rc = sqlite3_step_monitored(res);
  322. if (unlikely(store_rc != SQLITE_DONE))
  323. error_report("Failed to store host %s, rc = %d", rrdhost_hostname(host), rc);
  324. rc = sqlite3_reset(res);
  325. if (unlikely(rc != SQLITE_OK))
  326. error_report("Failed to reset statement to store host %s, rc = %d", rrdhost_hostname(host), rc);
  327. return store_rc != SQLITE_DONE;
  328. bind_fail:
  329. error_report("Failed to bind %d parameter to store host %s, rc = %d", param, rrdhost_hostname(host), rc);
  330. rc = sqlite3_reset(res);
  331. if (unlikely(rc != SQLITE_OK))
  332. error_report("Failed to reset statement to store host %s, rc = %d", rrdhost_hostname(host), rc);
  333. return 1;
  334. }
  335. static int add_host_sysinfo_key_value(const char *name, const char *value, uuid_t *uuid)
  336. {
  337. static __thread sqlite3_stmt *res = NULL;
  338. int rc, param = 0;
  339. if (unlikely(!db_meta)) {
  340. if (default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)
  341. return 0;
  342. error_report("Database has not been initialized");
  343. return 0;
  344. }
  345. if (unlikely((!res))) {
  346. rc = prepare_statement(db_meta, SQL_STORE_HOST_SYSTEM_INFO_VALUES, &res);
  347. if (unlikely(rc != SQLITE_OK)) {
  348. error_report("Failed to prepare statement to store host info values, rc = %d", rc);
  349. return 0;
  350. }
  351. }
  352. rc = sqlite3_bind_blob(res, ++param, uuid, sizeof(*uuid), SQLITE_STATIC);
  353. if (unlikely(rc != SQLITE_OK))
  354. goto bind_fail;
  355. rc = bind_text_null(res, ++param, name, 0);
  356. if (unlikely(rc != SQLITE_OK))
  357. goto bind_fail;
  358. rc = bind_text_null(res, ++param, value ? value : "unknown", 0);
  359. if (unlikely(rc != SQLITE_OK))
  360. goto bind_fail;
  361. int store_rc = sqlite3_step_monitored(res);
  362. if (unlikely(store_rc != SQLITE_DONE))
  363. error_report("Failed to store host info value %s, rc = %d", name, rc);
  364. rc = sqlite3_reset(res);
  365. if (unlikely(rc != SQLITE_OK))
  366. error_report("Failed to reset statement to store host info value %s, rc = %d", name, rc);
  367. return store_rc == SQLITE_DONE;
  368. bind_fail:
  369. error_report("Failed to bind %d parameter to store host info values %s, rc = %d", param, name, rc);
  370. rc = sqlite3_reset(res);
  371. if (unlikely(rc != SQLITE_OK))
  372. error_report("Failed to reset statement to store host info values %s, rc = %d", name, rc);
  373. return 0;
  374. }
  375. static bool store_host_systeminfo(RRDHOST *host)
  376. {
  377. struct rrdhost_system_info *system_info = host->system_info;
  378. if (unlikely(!system_info))
  379. return false;
  380. int ret = 0;
  381. ret += add_host_sysinfo_key_value("NETDATA_CONTAINER_OS_NAME", system_info->container_os_name, &host->host_uuid);
  382. ret += add_host_sysinfo_key_value("NETDATA_CONTAINER_OS_ID", system_info->container_os_id, &host->host_uuid);
  383. ret += add_host_sysinfo_key_value("NETDATA_CONTAINER_OS_ID_LIKE", system_info->container_os_id_like, &host->host_uuid);
  384. ret += add_host_sysinfo_key_value("NETDATA_CONTAINER_OS_VERSION", system_info->container_os_version, &host->host_uuid);
  385. ret += add_host_sysinfo_key_value("NETDATA_CONTAINER_OS_VERSION_ID", system_info->container_os_version_id, &host->host_uuid);
  386. ret += add_host_sysinfo_key_value("NETDATA_CONTAINER_OS_DETECTION", system_info->host_os_detection, &host->host_uuid);
  387. ret += add_host_sysinfo_key_value("NETDATA_HOST_OS_NAME", system_info->host_os_name, &host->host_uuid);
  388. ret += add_host_sysinfo_key_value("NETDATA_HOST_OS_ID", system_info->host_os_id, &host->host_uuid);
  389. ret += add_host_sysinfo_key_value("NETDATA_HOST_OS_ID_LIKE", system_info->host_os_id_like, &host->host_uuid);
  390. ret += add_host_sysinfo_key_value("NETDATA_HOST_OS_VERSION", system_info->host_os_version, &host->host_uuid);
  391. ret += add_host_sysinfo_key_value("NETDATA_HOST_OS_VERSION_ID", system_info->host_os_version_id, &host->host_uuid);
  392. ret += add_host_sysinfo_key_value("NETDATA_HOST_OS_DETECTION", system_info->host_os_detection, &host->host_uuid);
  393. ret += add_host_sysinfo_key_value("NETDATA_SYSTEM_KERNEL_NAME", system_info->kernel_name, &host->host_uuid);
  394. ret += add_host_sysinfo_key_value("NETDATA_SYSTEM_CPU_LOGICAL_CPU_COUNT", system_info->host_cores, &host->host_uuid);
  395. ret += add_host_sysinfo_key_value("NETDATA_SYSTEM_CPU_FREQ", system_info->host_cpu_freq, &host->host_uuid);
  396. ret += add_host_sysinfo_key_value("NETDATA_SYSTEM_TOTAL_RAM", system_info->host_ram_total, &host->host_uuid);
  397. ret += add_host_sysinfo_key_value("NETDATA_SYSTEM_TOTAL_DISK_SIZE", system_info->host_disk_space, &host->host_uuid);
  398. ret += add_host_sysinfo_key_value("NETDATA_SYSTEM_KERNEL_VERSION", system_info->kernel_version, &host->host_uuid);
  399. ret += add_host_sysinfo_key_value("NETDATA_SYSTEM_ARCHITECTURE", system_info->architecture, &host->host_uuid);
  400. ret += add_host_sysinfo_key_value("NETDATA_SYSTEM_VIRTUALIZATION", system_info->virtualization, &host->host_uuid);
  401. ret += add_host_sysinfo_key_value("NETDATA_SYSTEM_VIRT_DETECTION", system_info->virt_detection, &host->host_uuid);
  402. ret += add_host_sysinfo_key_value("NETDATA_SYSTEM_CONTAINER", system_info->container, &host->host_uuid);
  403. ret += add_host_sysinfo_key_value("NETDATA_SYSTEM_CONTAINER_DETECTION", system_info->container_detection, &host->host_uuid);
  404. ret += add_host_sysinfo_key_value("NETDATA_HOST_IS_K8S_NODE", system_info->is_k8s_node, &host->host_uuid);
  405. return !(24 == ret);
  406. }
  407. /*
  408. * Store a chart in the database
  409. */
  410. static int store_chart_metadata(RRDSET *st)
  411. {
  412. static __thread sqlite3_stmt *res = NULL;
  413. int rc, param = 0, store_rc = 0;
  414. if (unlikely(!res)) {
  415. rc = prepare_statement(db_meta, SQL_STORE_CHART, &res);
  416. if (unlikely(rc != SQLITE_OK)) {
  417. error_report("Failed to prepare statement to store chart, rc = %d", rc);
  418. return 1;
  419. }
  420. }
  421. rc = sqlite3_bind_blob(res, ++param, &st->chart_uuid, sizeof(st->chart_uuid), SQLITE_STATIC);
  422. if (unlikely(rc != SQLITE_OK))
  423. goto bind_fail;
  424. rc = sqlite3_bind_blob(res, ++param, &st->rrdhost->host_uuid, sizeof(st->rrdhost->host_uuid), SQLITE_STATIC);
  425. if (unlikely(rc != SQLITE_OK))
  426. goto bind_fail;
  427. rc = sqlite3_bind_text(res, ++param, string2str(st->parts.type), -1, SQLITE_STATIC);
  428. if (unlikely(rc != SQLITE_OK))
  429. goto bind_fail;
  430. rc = sqlite3_bind_text(res, ++param, string2str(st->parts.id), -1, SQLITE_STATIC);
  431. if (unlikely(rc != SQLITE_OK))
  432. goto bind_fail;
  433. const char *name = string2str(st->parts.name);
  434. if (name && *name)
  435. rc = sqlite3_bind_text(res, ++param, name, -1, SQLITE_STATIC);
  436. else
  437. rc = sqlite3_bind_null(res, ++param);
  438. if (unlikely(rc != SQLITE_OK))
  439. goto bind_fail;
  440. rc = sqlite3_bind_text(res, ++param, rrdset_family(st), -1, SQLITE_STATIC);
  441. if (unlikely(rc != SQLITE_OK))
  442. goto bind_fail;
  443. rc = sqlite3_bind_text(res, ++param, rrdset_context(st), -1, SQLITE_STATIC);
  444. if (unlikely(rc != SQLITE_OK))
  445. goto bind_fail;
  446. rc = sqlite3_bind_text(res, ++param, rrdset_title(st), -1, SQLITE_STATIC);
  447. if (unlikely(rc != SQLITE_OK))
  448. goto bind_fail;
  449. rc = sqlite3_bind_text(res, ++param, rrdset_units(st), -1, SQLITE_STATIC);
  450. if (unlikely(rc != SQLITE_OK))
  451. goto bind_fail;
  452. rc = sqlite3_bind_text(res, ++param, rrdset_plugin_name(st), -1, SQLITE_STATIC);
  453. if (unlikely(rc != SQLITE_OK))
  454. goto bind_fail;
  455. rc = sqlite3_bind_text(res, ++param, rrdset_module_name(st), -1, SQLITE_STATIC);
  456. if (unlikely(rc != SQLITE_OK))
  457. goto bind_fail;
  458. rc = sqlite3_bind_int(res, ++param, (int) st->priority);
  459. if (unlikely(rc != SQLITE_OK))
  460. goto bind_fail;
  461. rc = sqlite3_bind_int(res, ++param, st->update_every);
  462. if (unlikely(rc != SQLITE_OK))
  463. goto bind_fail;
  464. rc = sqlite3_bind_int(res, ++param, st->chart_type);
  465. if (unlikely(rc != SQLITE_OK))
  466. goto bind_fail;
  467. rc = sqlite3_bind_int(res, ++param, st->rrd_memory_mode);
  468. if (unlikely(rc != SQLITE_OK))
  469. goto bind_fail;
  470. rc = sqlite3_bind_int(res, ++param, (int) st->db.entries);
  471. if (unlikely(rc != SQLITE_OK))
  472. goto bind_fail;
  473. store_rc = execute_insert(res);
  474. if (unlikely(store_rc != SQLITE_DONE))
  475. error_report("Failed to store chart, rc = %d", store_rc);
  476. rc = sqlite3_reset(res);
  477. if (unlikely(rc != SQLITE_OK))
  478. error_report("Failed to reset statement in chart store function, rc = %d", rc);
  479. return store_rc != SQLITE_DONE;
  480. bind_fail:
  481. error_report("Failed to bind parameter %d to store chart, rc = %d", param, rc);
  482. rc = sqlite3_reset(res);
  483. if (unlikely(rc != SQLITE_OK))
  484. error_report("Failed to reset statement in chart store function, rc = %d", rc);
  485. return 1;
  486. }
  487. /*
  488. * Store a dimension
  489. */
  490. static int store_dimension_metadata(RRDDIM *rd)
  491. {
  492. static __thread sqlite3_stmt *res = NULL;
  493. int rc, param = 0;
  494. if (unlikely(!res)) {
  495. rc = prepare_statement(db_meta, SQL_STORE_DIMENSION, &res);
  496. if (unlikely(rc != SQLITE_OK)) {
  497. error_report("Failed to prepare statement to store dimension, rc = %d", rc);
  498. return 1;
  499. }
  500. }
  501. rc = sqlite3_bind_blob(res, ++param, &rd->metric_uuid, sizeof(rd->metric_uuid), SQLITE_STATIC);
  502. if (unlikely(rc != SQLITE_OK))
  503. goto bind_fail;
  504. rc = sqlite3_bind_blob(res, ++param, &rd->rrdset->chart_uuid, sizeof(rd->rrdset->chart_uuid), SQLITE_STATIC);
  505. if (unlikely(rc != SQLITE_OK))
  506. goto bind_fail;
  507. rc = sqlite3_bind_text(res, ++param, string2str(rd->id), -1, SQLITE_STATIC);
  508. if (unlikely(rc != SQLITE_OK))
  509. goto bind_fail;
  510. rc = sqlite3_bind_text(res, ++param, string2str(rd->name), -1, SQLITE_STATIC);
  511. if (unlikely(rc != SQLITE_OK))
  512. goto bind_fail;
  513. rc = sqlite3_bind_int(res, ++param, (int) rd->multiplier);
  514. if (unlikely(rc != SQLITE_OK))
  515. goto bind_fail;
  516. rc = sqlite3_bind_int(res, ++param, (int ) rd->divisor);
  517. if (unlikely(rc != SQLITE_OK))
  518. goto bind_fail;
  519. rc = sqlite3_bind_int(res, ++param, rd->algorithm);
  520. if (unlikely(rc != SQLITE_OK))
  521. goto bind_fail;
  522. if (rrddim_option_check(rd, RRDDIM_OPTION_HIDDEN))
  523. rc = sqlite3_bind_text(res, ++param, "hidden", -1, SQLITE_STATIC);
  524. else
  525. rc = sqlite3_bind_null(res, ++param);
  526. if (unlikely(rc != SQLITE_OK))
  527. goto bind_fail;
  528. rc = execute_insert(res);
  529. if (unlikely(rc != SQLITE_DONE))
  530. error_report("Failed to store dimension, rc = %d", rc);
  531. rc = sqlite3_reset(res);
  532. if (unlikely(rc != SQLITE_OK))
  533. error_report("Failed to reset statement in store dimension, rc = %d", rc);
  534. return 0;
  535. bind_fail:
  536. error_report("Failed to bind parameter %d to store dimension, rc = %d", param, rc);
  537. rc = sqlite3_reset(res);
  538. if (unlikely(rc != SQLITE_OK))
  539. error_report("Failed to reset statement in store dimension, rc = %d", rc);
  540. return 1;
  541. }
  542. static bool dimension_can_be_deleted(uuid_t *dim_uuid __maybe_unused, sqlite3_stmt **res __maybe_unused, bool flag __maybe_unused)
  543. {
  544. #ifdef ENABLE_DBENGINE
  545. if(dbengine_enabled) {
  546. bool no_retention = true;
  547. for (size_t tier = 0; tier < storage_tiers; tier++) {
  548. if (!multidb_ctx[tier])
  549. continue;
  550. time_t first_time_t = 0, last_time_t = 0;
  551. if (rrdeng_metric_retention_by_uuid((void *) multidb_ctx[tier], dim_uuid, &first_time_t, &last_time_t)) {
  552. if (first_time_t > 0) {
  553. no_retention = false;
  554. break;
  555. }
  556. }
  557. }
  558. return no_retention;
  559. }
  560. else
  561. return false;
  562. #else
  563. return false;
  564. #endif
  565. }
  566. int get_pragma_value(sqlite3 *database, const char *sql)
  567. {
  568. sqlite3_stmt *res = NULL;
  569. int rc = sqlite3_prepare_v2(database, sql, -1, &res, 0);
  570. if (unlikely(rc != SQLITE_OK))
  571. return -1;
  572. int result = -1;
  573. rc = sqlite3_step_monitored(res);
  574. if (likely(rc == SQLITE_ROW))
  575. result = sqlite3_column_int(res, 0);
  576. rc = sqlite3_finalize(res);
  577. (void) rc;
  578. return result;
  579. }
  580. int get_free_page_count(sqlite3 *database)
  581. {
  582. return get_pragma_value(database, "PRAGMA freelist_count");
  583. }
  584. int get_database_page_count(sqlite3 *database)
  585. {
  586. return get_pragma_value(database, "PRAGMA page_count");
  587. }
  588. static bool run_cleanup_loop(
  589. sqlite3_stmt *res,
  590. struct metadata_wc *wc,
  591. bool (*check_cb)(uuid_t *, sqlite3_stmt **, bool),
  592. void (*action_cb)(uuid_t *, sqlite3_stmt **, bool),
  593. uint32_t *total_checked,
  594. uint32_t *total_deleted,
  595. uint64_t *row_id,
  596. sqlite3_stmt **check_stmt,
  597. sqlite3_stmt **action_stmt,
  598. bool check_flag,
  599. bool action_flag)
  600. {
  601. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN)))
  602. return true;
  603. int rc = sqlite3_bind_int64(res, 1, (sqlite3_int64) *row_id);
  604. if (unlikely(rc != SQLITE_OK))
  605. return true;
  606. time_t start_running = now_monotonic_sec();
  607. bool time_expired = false;
  608. while (!time_expired && sqlite3_step_monitored(res) == SQLITE_ROW &&
  609. (*total_deleted < MAX_METADATA_CLEANUP && *total_checked < MAX_METADATA_CLEANUP)) {
  610. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN)))
  611. break;
  612. *row_id = sqlite3_column_int64(res, 1);
  613. rc = check_cb((uuid_t *)sqlite3_column_blob(res, 0), check_stmt, check_flag);
  614. if (rc == true) {
  615. action_cb((uuid_t *)sqlite3_column_blob(res, 0), action_stmt, action_flag);
  616. (*total_deleted)++;
  617. }
  618. (*total_checked)++;
  619. time_expired = ((now_monotonic_sec() - start_running) > METADATA_RUNTIME_THRESHOLD);
  620. }
  621. return time_expired || (*total_checked == MAX_METADATA_CLEANUP) || (*total_deleted == MAX_METADATA_CLEANUP);
  622. }
  623. #define SQL_CHECK_CHART_EXISTENCE_IN_DIMENSION "SELECT count(1) FROM dimension WHERE chart_id = @chart_id"
  624. #define SQL_CHECK_CHART_EXISTENCE_IN_CHART "SELECT count(1) FROM chart WHERE chart_id = @chart_id"
  625. static bool chart_can_be_deleted(uuid_t *chart_uuid, sqlite3_stmt **check_res, bool check_in_dimension)
  626. {
  627. int rc, result = 1;
  628. sqlite3_stmt *res = check_res ? *check_res : NULL;
  629. if (!res) {
  630. if (check_in_dimension)
  631. rc = sqlite3_prepare_v2(db_meta, SQL_CHECK_CHART_EXISTENCE_IN_DIMENSION, -1, &res, 0);
  632. else
  633. rc = sqlite3_prepare_v2(db_meta, SQL_CHECK_CHART_EXISTENCE_IN_CHART, -1, &res, 0);
  634. if (unlikely(rc != SQLITE_OK)) {
  635. error_report("Failed to prepare statement to check for chart existence, rc = %d", rc);
  636. return 0;
  637. }
  638. if (check_res)
  639. *check_res = res;
  640. }
  641. rc = sqlite3_bind_blob(res, 1, chart_uuid, sizeof(*chart_uuid), SQLITE_STATIC);
  642. if (unlikely(rc != SQLITE_OK)) {
  643. error_report("Failed to bind chart uuid parameter, rc = %d", rc);
  644. goto skip;
  645. }
  646. rc = sqlite3_step_monitored(res);
  647. if (likely(rc == SQLITE_ROW))
  648. result = sqlite3_column_int(res, 0);
  649. skip:
  650. if (check_res)
  651. rc = sqlite3_reset(res);
  652. else
  653. rc = sqlite3_finalize(res);
  654. if (unlikely(rc != SQLITE_OK))
  655. error_report("Failed to %s statement that checks chart uuid existence rc = %d", check_res ? "reset" : "finalize", rc);
  656. return result == 0;
  657. }
  658. #define SQL_DELETE_CHART_BY_UUID "DELETE FROM chart WHERE chart_id = @chart_id"
  659. #define SQL_DELETE_CHART_LABEL_BY_UUID "DELETE FROM chart_label WHERE chart_id = @chart_id"
  660. static void delete_chart_uuid(uuid_t *chart_uuid, sqlite3_stmt **action_res, bool label_only)
  661. {
  662. int rc;
  663. sqlite3_stmt *res = action_res ? *action_res : NULL;
  664. if (!res) {
  665. if (label_only)
  666. rc = sqlite3_prepare_v2(db_meta, SQL_DELETE_CHART_LABEL_BY_UUID, -1, &res, 0);
  667. else
  668. rc = sqlite3_prepare_v2(db_meta, SQL_DELETE_CHART_BY_UUID, -1, &res, 0);
  669. if (unlikely(rc != SQLITE_OK)) {
  670. error_report("Failed to prepare statement to check for chart existence, rc = %d", rc);
  671. return;
  672. }
  673. if (action_res)
  674. *action_res = res;
  675. }
  676. rc = sqlite3_bind_blob(res, 1, chart_uuid, sizeof(*chart_uuid), SQLITE_STATIC);
  677. if (unlikely(rc != SQLITE_OK)) {
  678. error_report("Failed to bind chart uuid parameter, rc = %d", rc);
  679. goto skip;
  680. }
  681. rc = sqlite3_step_monitored(res);
  682. if (unlikely(rc != SQLITE_DONE))
  683. error_report("Failed to delete a chart uuid from the %s table, rc = %d", label_only ? "labels" : "chart", rc);
  684. skip:
  685. if (action_res)
  686. rc = sqlite3_reset(res);
  687. else
  688. rc = sqlite3_finalize(res);
  689. if (unlikely(rc != SQLITE_OK))
  690. error_report("Failed to %s statement that deletes a chart uuid rc = %d", action_res ? "reset" : "finalize", rc);
  691. }
  692. static void check_dimension_metadata(struct metadata_wc *wc)
  693. {
  694. static time_t next_execution_t = 0;
  695. static uint64_t last_row_id = 0;
  696. time_t now = now_realtime_sec();
  697. if (!next_execution_t)
  698. next_execution_t = now + METADATA_MAINTENANCE_FIRST_CHECK;
  699. if (next_execution_t && next_execution_t > now)
  700. return;
  701. int rc;
  702. sqlite3_stmt *res = NULL;
  703. rc = sqlite3_prepare_v2(db_meta, SELECT_DIMENSION_LIST, -1, &res, 0);
  704. if (unlikely(rc != SQLITE_OK)) {
  705. error_report("Failed to prepare statement to fetch host dimensions");
  706. return;
  707. }
  708. uint32_t total_checked = 0;
  709. uint32_t total_deleted = 0;
  710. internal_error(true, "METADATA: Checking dimensions starting after row %"PRIu64, last_row_id);
  711. bool more_to_do = run_cleanup_loop(
  712. res,
  713. wc,
  714. dimension_can_be_deleted,
  715. delete_dimension_uuid,
  716. &total_checked,
  717. &total_deleted,
  718. &last_row_id,
  719. NULL,
  720. NULL,
  721. false,
  722. false);
  723. now = now_realtime_sec();
  724. if (more_to_do)
  725. next_execution_t = now + METADATA_MAINTENANCE_REPEAT;
  726. else {
  727. last_row_id = 0;
  728. next_execution_t = now + METADATA_DIM_CHECK_INTERVAL;
  729. }
  730. internal_error(true,
  731. "METADATA: Dimensions checked %u, deleted %u. Checks will %s in %lld seconds",
  732. total_checked,
  733. total_deleted,
  734. last_row_id ? "resume" : "restart",
  735. (long long)(next_execution_t - now));
  736. rc = sqlite3_finalize(res);
  737. if (unlikely(rc != SQLITE_OK))
  738. error_report("Failed to finalize the prepared statement to check dimensions");
  739. }
  740. static void check_chart_metadata(struct metadata_wc *wc)
  741. {
  742. static time_t next_execution_t = 0;
  743. static uint64_t last_row_id = 0;
  744. time_t now = now_realtime_sec();
  745. if (!next_execution_t)
  746. next_execution_t = now + METADATA_MAINTENANCE_FIRST_CHECK;
  747. if (next_execution_t && next_execution_t > now)
  748. return;
  749. sqlite3_stmt *res = NULL;
  750. int rc = sqlite3_prepare_v2(db_meta, SELECT_CHART_LIST, -1, &res, 0);
  751. if (unlikely(rc != SQLITE_OK)) {
  752. error_report("Failed to prepare statement to fetch charts");
  753. return;
  754. }
  755. uint32_t total_checked = 0;
  756. uint32_t total_deleted = 0;
  757. internal_error(true, "METADATA: Checking charts starting after row %"PRIu64, last_row_id);
  758. sqlite3_stmt *check_res = NULL;
  759. sqlite3_stmt *action_res = NULL;
  760. bool more_to_do = run_cleanup_loop(
  761. res,
  762. wc,
  763. chart_can_be_deleted,
  764. delete_chart_uuid,
  765. &total_checked,
  766. &total_deleted,
  767. &last_row_id,
  768. &check_res,
  769. &action_res,
  770. true,
  771. false);
  772. if (check_res)
  773. sqlite3_finalize(check_res);
  774. if (action_res)
  775. sqlite3_finalize(action_res);
  776. now = now_realtime_sec();
  777. if (more_to_do)
  778. next_execution_t = now + METADATA_MAINTENANCE_REPEAT;
  779. else {
  780. last_row_id = 0;
  781. next_execution_t = now + METADATA_CHART_CHECK_INTERVAL;
  782. }
  783. internal_error(true,
  784. "METADATA: Charts checked %u, deleted %u. Checks will %s in %lld seconds",
  785. total_checked,
  786. total_deleted,
  787. last_row_id ? "resume" : "restart",
  788. (long long)(next_execution_t - now));
  789. rc = sqlite3_finalize(res);
  790. if (unlikely(rc != SQLITE_OK))
  791. error_report("Failed to finalize the prepared statement when reading charts");
  792. }
  793. static void check_label_metadata(struct metadata_wc *wc)
  794. {
  795. static time_t next_execution_t = 0;
  796. static uint64_t last_row_id = 0;
  797. time_t now = now_realtime_sec();
  798. if (!next_execution_t)
  799. next_execution_t = now + METADATA_MAINTENANCE_FIRST_CHECK;
  800. if (next_execution_t && next_execution_t > now)
  801. return;
  802. int rc;
  803. sqlite3_stmt *res = NULL;
  804. rc = sqlite3_prepare_v2(db_meta, SELECT_CHART_LABEL_LIST, -1, &res, 0);
  805. if (unlikely(rc != SQLITE_OK)) {
  806. error_report("Failed to prepare statement to fetch charts");
  807. return;
  808. }
  809. uint32_t total_checked = 0;
  810. uint32_t total_deleted = 0;
  811. internal_error(true,"METADATA: Checking charts labels starting after row %"PRIu64, last_row_id);
  812. sqlite3_stmt *check_res = NULL;
  813. sqlite3_stmt *action_res = NULL;
  814. bool more_to_do = run_cleanup_loop(
  815. res,
  816. wc,
  817. chart_can_be_deleted,
  818. delete_chart_uuid,
  819. &total_checked,
  820. &total_deleted,
  821. &last_row_id,
  822. &check_res,
  823. &action_res,
  824. false,
  825. true);
  826. if (check_res)
  827. sqlite3_finalize(check_res);
  828. if (action_res)
  829. sqlite3_finalize(action_res);
  830. now = now_realtime_sec();
  831. if (more_to_do)
  832. next_execution_t = now + METADATA_MAINTENANCE_REPEAT;
  833. else {
  834. last_row_id = 0;
  835. next_execution_t = now + METADATA_LABEL_CHECK_INTERVAL;
  836. }
  837. internal_error(true,
  838. "METADATA: Chart labels checked %u, deleted %u. Checks will %s in %lld seconds",
  839. total_checked,
  840. total_deleted,
  841. last_row_id ? "resume" : "restart",
  842. (long long)(next_execution_t - now));
  843. rc = sqlite3_finalize(res);
  844. if (unlikely(rc != SQLITE_OK))
  845. error_report("Failed to finalize the prepared statement when checking charts");
  846. }
  847. static void cleanup_health_log(struct metadata_wc *wc)
  848. {
  849. static time_t next_execution_t = 0;
  850. time_t now = now_realtime_sec();
  851. if (!next_execution_t)
  852. next_execution_t = now + METADATA_MAINTENANCE_FIRST_CHECK;
  853. if (next_execution_t && next_execution_t > now)
  854. return;
  855. next_execution_t = now + METADATA_HEALTH_LOG_INTERVAL;
  856. RRDHOST *host;
  857. bool is_claimed = claimed();
  858. dfe_start_reentrant(rrdhost_root_index, host){
  859. if (rrdhost_flag_check(host, RRDHOST_FLAG_ARCHIVED))
  860. continue;
  861. sql_health_alarm_log_cleanup(host, is_claimed);
  862. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN)))
  863. break;
  864. }
  865. dfe_done(host);
  866. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN)))
  867. return;
  868. (void) db_execute(db_meta,"DELETE FROM health_log WHERE host_id NOT IN (SELECT host_id FROM host)");
  869. (void) db_execute(db_meta,"DELETE FROM health_log_detail WHERE health_log_id NOT IN (SELECT health_log_id FROM health_log)");
  870. }
  871. //
  872. // EVENT LOOP STARTS HERE
  873. //
  874. static void metadata_free_cmd_queue(struct metadata_wc *wc)
  875. {
  876. spinlock_lock(&wc->cmd_queue_lock);
  877. while(wc->cmd_base) {
  878. struct metadata_cmd *t = wc->cmd_base;
  879. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(wc->cmd_base, t, prev, next);
  880. freez(t);
  881. }
  882. spinlock_unlock(&wc->cmd_queue_lock);
  883. }
  884. static void metadata_enq_cmd(struct metadata_wc *wc, struct metadata_cmd *cmd)
  885. {
  886. if (cmd->opcode == METADATA_SYNC_SHUTDOWN) {
  887. metadata_flag_set(wc, METADATA_FLAG_SHUTDOWN);
  888. goto wakeup_event_loop;
  889. }
  890. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN)))
  891. goto wakeup_event_loop;
  892. struct metadata_cmd *t = mallocz(sizeof(*t));
  893. *t = *cmd;
  894. t->prev = t->next = NULL;
  895. spinlock_lock(&wc->cmd_queue_lock);
  896. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(wc->cmd_base, t, prev, next);
  897. spinlock_unlock(&wc->cmd_queue_lock);
  898. wakeup_event_loop:
  899. (void) uv_async_send(&wc->async);
  900. }
  901. static struct metadata_cmd metadata_deq_cmd(struct metadata_wc *wc)
  902. {
  903. struct metadata_cmd ret;
  904. spinlock_lock(&wc->cmd_queue_lock);
  905. if(wc->cmd_base) {
  906. struct metadata_cmd *t = wc->cmd_base;
  907. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(wc->cmd_base, t, prev, next);
  908. ret = *t;
  909. freez(t);
  910. }
  911. else {
  912. ret.opcode = METADATA_DATABASE_NOOP;
  913. ret.completion = NULL;
  914. }
  915. spinlock_unlock(&wc->cmd_queue_lock);
  916. return ret;
  917. }
  918. static void async_cb(uv_async_t *handle)
  919. {
  920. uv_stop(handle->loop);
  921. uv_update_time(handle->loop);
  922. }
  923. #define TIMER_INITIAL_PERIOD_MS (1000)
  924. #define TIMER_REPEAT_PERIOD_MS (1000)
  925. static void timer_cb(uv_timer_t* handle)
  926. {
  927. uv_stop(handle->loop);
  928. uv_update_time(handle->loop);
  929. struct metadata_wc *wc = handle->data;
  930. struct metadata_cmd cmd;
  931. memset(&cmd, 0, sizeof(cmd));
  932. if (wc->metadata_check_after < now_realtime_sec()) {
  933. cmd.opcode = METADATA_SCAN_HOSTS;
  934. metadata_enq_cmd(wc, &cmd);
  935. }
  936. }
  937. void vacuum_database(sqlite3 *database, const char *db_alias, int threshold, int vacuum_pc)
  938. {
  939. int free_pages = get_free_page_count(database);
  940. int total_pages = get_database_page_count(database);
  941. if (!threshold)
  942. threshold = DATABASE_FREE_PAGES_THRESHOLD_PC;
  943. if (!vacuum_pc)
  944. vacuum_pc = DATABASE_FREE_PAGES_VACUUM_PC;
  945. if (free_pages > (total_pages * threshold / 100)) {
  946. int do_free_pages = (int) (free_pages * vacuum_pc / 100);
  947. nd_log(NDLS_DAEMON, NDLP_DEBUG, "%s: Freeing %d database pages", db_alias, do_free_pages);
  948. char sql[128];
  949. snprintfz(sql, sizeof(sql) - 1, "PRAGMA incremental_vacuum(%d)", do_free_pages);
  950. (void) db_execute(database, sql);
  951. }
  952. }
  953. void run_metadata_cleanup(struct metadata_wc *wc)
  954. {
  955. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN)))
  956. return;
  957. check_dimension_metadata(wc);
  958. check_chart_metadata(wc);
  959. check_label_metadata(wc);
  960. cleanup_health_log(wc);
  961. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN)))
  962. return;
  963. vacuum_database(db_meta, "METADATA", DATABASE_FREE_PAGES_THRESHOLD_PC, DATABASE_FREE_PAGES_VACUUM_PC);
  964. (void) sqlite3_wal_checkpoint(db_meta, NULL);
  965. }
  966. struct scan_metadata_payload {
  967. uv_work_t request;
  968. struct metadata_wc *wc;
  969. void *data;
  970. BUFFER *work_buffer;
  971. uint32_t max_count;
  972. };
  973. struct host_context_load_thread {
  974. uv_thread_t thread;
  975. RRDHOST *host;
  976. bool busy;
  977. bool finished;
  978. };
  979. static void restore_host_context(void *arg)
  980. {
  981. struct host_context_load_thread *hclt = arg;
  982. RRDHOST *host = hclt->host;
  983. usec_t started_ut = now_monotonic_usec(); (void)started_ut;
  984. rrdhost_load_rrdcontext_data(host);
  985. usec_t ended_ut = now_monotonic_usec(); (void)ended_ut;
  986. rrdhost_flag_clear(host, RRDHOST_FLAG_PENDING_CONTEXT_LOAD | RRDHOST_FLAG_CONTEXT_LOAD_IN_PROGRESS);
  987. #ifdef ENABLE_ACLK
  988. aclk_queue_node_info(host, false);
  989. #endif
  990. internal_error(true, "METADATA: 'host:%s' context load in %0.2f ms", rrdhost_hostname(host),
  991. (double)(ended_ut - started_ut) / USEC_PER_MS);
  992. __atomic_store_n(&hclt->finished, true, __ATOMIC_RELEASE);
  993. }
  994. // Callback after scan of hosts is done
  995. static void after_start_host_load_context(uv_work_t *req, int status __maybe_unused)
  996. {
  997. struct scan_metadata_payload *data = req->data;
  998. freez(data);
  999. }
  1000. #define MAX_FIND_THREAD_RETRIES (10)
  1001. static void cleanup_finished_threads(struct host_context_load_thread *hclt, size_t max_thread_slots, bool wait)
  1002. {
  1003. for (size_t index = 0; index < max_thread_slots; index++) {
  1004. if (__atomic_load_n(&(hclt[index].finished), __ATOMIC_RELAXED)
  1005. || (wait && __atomic_load_n(&(hclt[index].busy), __ATOMIC_ACQUIRE))) {
  1006. int rc = uv_thread_join(&(hclt[index].thread));
  1007. if (rc)
  1008. netdata_log_error("Failed to join thread, rc = %d",rc);
  1009. __atomic_store_n(&(hclt[index].busy), false, __ATOMIC_RELEASE);
  1010. __atomic_store_n(&(hclt[index].finished), false, __ATOMIC_RELEASE);
  1011. }
  1012. }
  1013. }
  1014. static size_t find_available_thread_slot(struct host_context_load_thread *hclt, size_t max_thread_slots, size_t *found_index)
  1015. {
  1016. size_t retries = MAX_FIND_THREAD_RETRIES;
  1017. while (retries--) {
  1018. size_t index = 0;
  1019. while (index < max_thread_slots) {
  1020. if (false == __atomic_load_n(&(hclt[index].busy), __ATOMIC_ACQUIRE)) {
  1021. *found_index = index;
  1022. return true;
  1023. }
  1024. index++;
  1025. }
  1026. sleep_usec(10 * USEC_PER_MS);
  1027. }
  1028. return false;
  1029. }
  1030. static void start_all_host_load_context(uv_work_t *req __maybe_unused)
  1031. {
  1032. register_libuv_worker_jobs();
  1033. struct scan_metadata_payload *data = req->data;
  1034. struct metadata_wc *wc = data->wc;
  1035. worker_is_busy(UV_EVENT_HOST_CONTEXT_LOAD);
  1036. usec_t started_ut = now_monotonic_usec(); (void)started_ut;
  1037. RRDHOST *host;
  1038. size_t max_threads = MIN(get_netdata_cpus() / 2, 6);
  1039. if (max_threads < 1)
  1040. max_threads = 1;
  1041. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Using %zu threads for context loading", max_threads);
  1042. struct host_context_load_thread *hclt = callocz(max_threads, sizeof(*hclt));
  1043. size_t thread_index;
  1044. dfe_start_reentrant(rrdhost_root_index, host) {
  1045. if (rrdhost_flag_check(host, RRDHOST_FLAG_CONTEXT_LOAD_IN_PROGRESS) ||
  1046. !rrdhost_flag_check(host, RRDHOST_FLAG_PENDING_CONTEXT_LOAD))
  1047. continue;
  1048. rrdhost_flag_set(host, RRDHOST_FLAG_CONTEXT_LOAD_IN_PROGRESS);
  1049. internal_error(true, "METADATA: 'host:%s' loading context", rrdhost_hostname(host));
  1050. bool found_slot = false;
  1051. do {
  1052. if (metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN))
  1053. break;
  1054. cleanup_finished_threads(hclt, max_threads, false);
  1055. found_slot = find_available_thread_slot(hclt, max_threads, &thread_index);
  1056. } while (!found_slot);
  1057. if (metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN))
  1058. break;
  1059. __atomic_store_n(&hclt[thread_index].busy, true, __ATOMIC_RELAXED);
  1060. hclt[thread_index].host = host;
  1061. fatal_assert(0 == uv_thread_create(&hclt[thread_index].thread, restore_host_context, &hclt[thread_index]));
  1062. }
  1063. dfe_done(host);
  1064. cleanup_finished_threads(hclt, max_threads, true);
  1065. freez(hclt);
  1066. usec_t ended_ut = now_monotonic_usec(); (void)ended_ut;
  1067. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: host contexts loaded in %0.2f ms", (double)(ended_ut - started_ut) / USEC_PER_MS);
  1068. worker_is_idle();
  1069. }
  1070. // Callback after scan of hosts is done
  1071. static void after_metadata_hosts(uv_work_t *req, int status __maybe_unused)
  1072. {
  1073. struct scan_metadata_payload *data = req->data;
  1074. struct metadata_wc *wc = data->wc;
  1075. metadata_flag_clear(wc, METADATA_FLAG_PROCESSING);
  1076. internal_error(true, "METADATA: scanning hosts complete");
  1077. if (unlikely(wc->scan_complete)) {
  1078. completion_mark_complete(wc->scan_complete);
  1079. internal_error(true, "METADATA: Sending completion done");
  1080. }
  1081. freez(data);
  1082. }
  1083. static bool metadata_scan_host(RRDHOST *host, uint32_t max_count, bool use_transaction, BUFFER *work_buffer, size_t *query_counter) {
  1084. RRDSET *st;
  1085. int rc;
  1086. bool more_to_do = false;
  1087. uint32_t scan_count = 1;
  1088. sqlite3_stmt *ml_load_stmt = NULL;
  1089. bool load_ml_models = max_count;
  1090. if (use_transaction)
  1091. (void)db_execute(db_meta, "BEGIN TRANSACTION");
  1092. rrdset_foreach_reentrant(st, host) {
  1093. if (scan_count == max_count) {
  1094. more_to_do = true;
  1095. break;
  1096. }
  1097. if(rrdset_flag_check(st, RRDSET_FLAG_METADATA_UPDATE)) {
  1098. (*query_counter)++;
  1099. rrdset_flag_clear(st, RRDSET_FLAG_METADATA_UPDATE);
  1100. scan_count++;
  1101. buffer_flush(work_buffer);
  1102. rc = check_and_update_chart_labels(st, work_buffer, query_counter);
  1103. if (unlikely(rc))
  1104. error_report("METADATA: 'host:%s': Failed to update labels for chart %s", rrdhost_hostname(host), rrdset_name(st));
  1105. else
  1106. (*query_counter)++;
  1107. rc = store_chart_metadata(st);
  1108. if (unlikely(rc))
  1109. error_report("METADATA: 'host:%s': Failed to store metadata for chart %s", rrdhost_hostname(host), rrdset_name(st));
  1110. }
  1111. RRDDIM *rd;
  1112. rrddim_foreach_read(rd, st) {
  1113. if(rrddim_flag_check(rd, RRDDIM_FLAG_METADATA_UPDATE)) {
  1114. (*query_counter)++;
  1115. rrddim_flag_clear(rd, RRDDIM_FLAG_METADATA_UPDATE);
  1116. if (rrddim_option_check(rd, RRDDIM_OPTION_HIDDEN))
  1117. rrddim_flag_set(rd, RRDDIM_FLAG_META_HIDDEN);
  1118. else
  1119. rrddim_flag_clear(rd, RRDDIM_FLAG_META_HIDDEN);
  1120. rc = store_dimension_metadata(rd);
  1121. if (unlikely(rc))
  1122. error_report("METADATA: 'host:%s': Failed to dimension metadata for chart %s. dimension %s",
  1123. rrdhost_hostname(host), rrdset_name(st),
  1124. rrddim_name(rd));
  1125. }
  1126. if(rrddim_flag_check(rd, RRDDIM_FLAG_ML_MODEL_LOAD)) {
  1127. rrddim_flag_clear(rd, RRDDIM_FLAG_ML_MODEL_LOAD);
  1128. if (likely(load_ml_models))
  1129. (void) ml_dimension_load_models(rd, &ml_load_stmt);
  1130. }
  1131. worker_is_idle();
  1132. }
  1133. rrddim_foreach_done(rd);
  1134. }
  1135. rrdset_foreach_done(st);
  1136. if (use_transaction)
  1137. (void)db_execute(db_meta, "COMMIT TRANSACTION");
  1138. if (ml_load_stmt) {
  1139. sqlite3_finalize(ml_load_stmt);
  1140. ml_load_stmt = NULL;
  1141. }
  1142. return more_to_do;
  1143. }
  1144. static void store_host_and_system_info(RRDHOST *host, size_t *query_counter)
  1145. {
  1146. if (unlikely(store_host_systeminfo(host))) {
  1147. error_report("METADATA: 'host:%s': Failed to store host updated system information in the database", rrdhost_hostname(host));
  1148. rrdhost_flag_set(host, RRDHOST_FLAG_METADATA_INFO | RRDHOST_FLAG_METADATA_UPDATE);
  1149. }
  1150. else {
  1151. if (likely(query_counter))
  1152. (*query_counter)++;
  1153. }
  1154. if (unlikely(store_host_metadata(host))) {
  1155. error_report("METADATA: 'host:%s': Failed to store host info in the database", rrdhost_hostname(host));
  1156. rrdhost_flag_set(host, RRDHOST_FLAG_METADATA_INFO | RRDHOST_FLAG_METADATA_UPDATE);
  1157. }
  1158. else {
  1159. if (likely(query_counter))
  1160. (*query_counter)++;
  1161. }
  1162. }
  1163. struct host_chart_label_cleanup {
  1164. Pvoid_t JudyL;
  1165. Word_t count;
  1166. };
  1167. // Worker thread to scan hosts for pending metadata to store
  1168. static void start_metadata_hosts(uv_work_t *req __maybe_unused)
  1169. {
  1170. register_libuv_worker_jobs();
  1171. RRDHOST *host;
  1172. int transaction_started = 0;
  1173. struct scan_metadata_payload *data = req->data;
  1174. struct metadata_wc *wc = data->wc;
  1175. BUFFER *work_buffer = data->work_buffer;
  1176. usec_t all_started_ut = now_monotonic_usec(); (void)all_started_ut;
  1177. internal_error(true, "METADATA: checking all hosts...");
  1178. usec_t started_ut = now_monotonic_usec(); (void)started_ut;
  1179. struct host_chart_label_cleanup *cl_cleanup_data = data->data;
  1180. if (cl_cleanup_data) {
  1181. Word_t Index = 0;
  1182. bool first = true;
  1183. Pvoid_t *PValue;
  1184. while ((PValue = JudyLFirstThenNext(cl_cleanup_data->JudyL, &Index, &first))) {
  1185. char *machine_guid = *PValue;
  1186. host = rrdhost_find_by_guid(machine_guid);
  1187. if (likely(!host)) {
  1188. uuid_t host_uuid;
  1189. if (!uuid_parse(machine_guid, host_uuid))
  1190. delete_host_chart_labels(&host_uuid);
  1191. }
  1192. freez(machine_guid);
  1193. }
  1194. JudyLFreeArray(&cl_cleanup_data->JudyL, PJE0);
  1195. freez(cl_cleanup_data);
  1196. }
  1197. bool run_again = false;
  1198. worker_is_busy(UV_EVENT_METADATA_STORE);
  1199. if (!data->max_count)
  1200. transaction_started = !db_execute(db_meta, "BEGIN TRANSACTION");
  1201. dfe_start_reentrant(rrdhost_root_index, host) {
  1202. if (rrdhost_flag_check(host, RRDHOST_FLAG_ARCHIVED) || !rrdhost_flag_check(host, RRDHOST_FLAG_METADATA_UPDATE))
  1203. continue;
  1204. size_t query_counter = 0; (void)query_counter;
  1205. rrdhost_flag_clear(host,RRDHOST_FLAG_METADATA_UPDATE);
  1206. if (unlikely(rrdhost_flag_check(host, RRDHOST_FLAG_METADATA_LABELS))) {
  1207. rrdhost_flag_clear(host, RRDHOST_FLAG_METADATA_LABELS);
  1208. int rc = exec_statement_with_uuid(SQL_DELETE_HOST_LABELS, &host->host_uuid);
  1209. if (likely(!rc)) {
  1210. query_counter++;
  1211. buffer_flush(work_buffer);
  1212. struct query_build tmp = {.sql = work_buffer, .count = 0};
  1213. uuid_unparse_lower(host->host_uuid, tmp.uuid_str);
  1214. rrdlabels_walkthrough_read(host->rrdlabels, host_label_store_to_sql_callback, &tmp);
  1215. buffer_strcat(work_buffer, " ON CONFLICT (host_id, label_key) DO UPDATE SET source_type = excluded.source_type, label_value=excluded.label_value, date_created=UNIXEPOCH()");
  1216. rc = db_execute(db_meta, buffer_tostring(work_buffer));
  1217. if (unlikely(rc)) {
  1218. error_report("METADATA: 'host:%s': failed to update metadata host labels", rrdhost_hostname(host));
  1219. rrdhost_flag_set(host, RRDHOST_FLAG_METADATA_LABELS | RRDHOST_FLAG_METADATA_UPDATE);
  1220. }
  1221. else
  1222. query_counter++;
  1223. } else {
  1224. error_report("METADATA: 'host:%s': failed to delete old host labels", rrdhost_hostname(host));
  1225. rrdhost_flag_set(host, RRDHOST_FLAG_METADATA_LABELS | RRDHOST_FLAG_METADATA_UPDATE);
  1226. }
  1227. }
  1228. if (unlikely(rrdhost_flag_check(host, RRDHOST_FLAG_METADATA_CLAIMID))) {
  1229. rrdhost_flag_clear(host, RRDHOST_FLAG_METADATA_CLAIMID);
  1230. uuid_t uuid;
  1231. int rc;
  1232. if (likely(host->aclk_state.claimed_id && !uuid_parse(host->aclk_state.claimed_id, uuid)))
  1233. rc = store_claim_id(&host->host_uuid, &uuid);
  1234. else
  1235. rc = store_claim_id(&host->host_uuid, NULL);
  1236. if (unlikely(rc))
  1237. rrdhost_flag_set(host, RRDHOST_FLAG_METADATA_CLAIMID | RRDHOST_FLAG_METADATA_UPDATE);
  1238. else
  1239. query_counter++;
  1240. }
  1241. if (unlikely(rrdhost_flag_check(host, RRDHOST_FLAG_METADATA_INFO))) {
  1242. rrdhost_flag_clear(host, RRDHOST_FLAG_METADATA_INFO);
  1243. store_host_and_system_info(host, &query_counter);
  1244. }
  1245. // For clarity
  1246. bool use_transaction = data->max_count;
  1247. if (unlikely(metadata_scan_host(host, data->max_count, use_transaction, work_buffer, &query_counter))) {
  1248. run_again = true;
  1249. rrdhost_flag_set(host,RRDHOST_FLAG_METADATA_UPDATE);
  1250. internal_error(true,"METADATA: 'host:%s': scheduling another run, more charts to store", rrdhost_hostname(host));
  1251. }
  1252. usec_t ended_ut = now_monotonic_usec(); (void)ended_ut;
  1253. internal_error(true, "METADATA: 'host:%s': saved metadata with %zu SQL statements, in %0.2f ms",
  1254. rrdhost_hostname(host), query_counter,
  1255. (double)(ended_ut - started_ut) / USEC_PER_MS);
  1256. }
  1257. dfe_done(host);
  1258. if (!data->max_count && transaction_started)
  1259. transaction_started = db_execute(db_meta, "COMMIT TRANSACTION");
  1260. usec_t all_ended_ut = now_monotonic_usec(); (void)all_ended_ut;
  1261. internal_error(true, "METADATA: checking all hosts completed in %0.2f ms",
  1262. (double)(all_ended_ut - all_started_ut) / USEC_PER_MS);
  1263. if (unlikely(run_again))
  1264. wc->metadata_check_after = now_realtime_sec() + METADATA_HOST_CHECK_IMMEDIATE;
  1265. else {
  1266. wc->metadata_check_after = now_realtime_sec() + METADATA_HOST_CHECK_INTERVAL;
  1267. run_metadata_cleanup(wc);
  1268. }
  1269. worker_is_idle();
  1270. }
  1271. static void metadata_event_loop(void *arg)
  1272. {
  1273. worker_register("METASYNC");
  1274. worker_register_job_name(METADATA_DATABASE_NOOP, "noop");
  1275. worker_register_job_name(METADATA_DATABASE_TIMER, "timer");
  1276. worker_register_job_name(METADATA_DEL_DIMENSION, "delete dimension");
  1277. worker_register_job_name(METADATA_STORE_CLAIM_ID, "add claim id");
  1278. worker_register_job_name(METADATA_ADD_HOST_INFO, "add host info");
  1279. worker_register_job_name(METADATA_MAINTENANCE, "maintenance");
  1280. int ret;
  1281. uv_loop_t *loop;
  1282. unsigned cmd_batch_size;
  1283. struct metadata_wc *wc = arg;
  1284. enum metadata_opcode opcode;
  1285. uv_thread_set_name_np(wc->thread, "METASYNC");
  1286. loop = wc->loop = mallocz(sizeof(uv_loop_t));
  1287. ret = uv_loop_init(loop);
  1288. if (ret) {
  1289. netdata_log_error("uv_loop_init(): %s", uv_strerror(ret));
  1290. goto error_after_loop_init;
  1291. }
  1292. loop->data = wc;
  1293. ret = uv_async_init(wc->loop, &wc->async, async_cb);
  1294. if (ret) {
  1295. netdata_log_error("uv_async_init(): %s", uv_strerror(ret));
  1296. goto error_after_async_init;
  1297. }
  1298. wc->async.data = wc;
  1299. ret = uv_timer_init(loop, &wc->timer_req);
  1300. if (ret) {
  1301. netdata_log_error("uv_timer_init(): %s", uv_strerror(ret));
  1302. goto error_after_timer_init;
  1303. }
  1304. wc->timer_req.data = wc;
  1305. fatal_assert(0 == uv_timer_start(&wc->timer_req, timer_cb, TIMER_INITIAL_PERIOD_MS, TIMER_REPEAT_PERIOD_MS));
  1306. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Starting metadata sync thread");
  1307. struct metadata_cmd cmd;
  1308. memset(&cmd, 0, sizeof(cmd));
  1309. metadata_flag_clear(wc, METADATA_FLAG_PROCESSING);
  1310. wc->metadata_check_after = now_realtime_sec() + METADATA_HOST_CHECK_FIRST_CHECK;
  1311. int shutdown = 0;
  1312. completion_mark_complete(&wc->start_stop_complete);
  1313. BUFFER *work_buffer = buffer_create(1024, &netdata_buffers_statistics.buffers_sqlite);
  1314. struct scan_metadata_payload *data;
  1315. struct host_chart_label_cleanup *cl_cleanup_data = NULL;
  1316. while (shutdown == 0 || (wc->flags & METADATA_FLAG_PROCESSING)) {
  1317. uuid_t *uuid;
  1318. RRDHOST *host = NULL;
  1319. worker_is_idle();
  1320. uv_run(loop, UV_RUN_DEFAULT);
  1321. /* wait for commands */
  1322. cmd_batch_size = 0;
  1323. do {
  1324. if (unlikely(cmd_batch_size >= METADATA_MAX_BATCH_SIZE))
  1325. break;
  1326. cmd = metadata_deq_cmd(wc);
  1327. opcode = cmd.opcode;
  1328. if (unlikely(opcode == METADATA_DATABASE_NOOP && metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN))) {
  1329. shutdown = 1;
  1330. continue;
  1331. }
  1332. ++cmd_batch_size;
  1333. if (likely(opcode != METADATA_DATABASE_NOOP))
  1334. worker_is_busy(opcode);
  1335. switch (opcode) {
  1336. case METADATA_DATABASE_NOOP:
  1337. case METADATA_DATABASE_TIMER:
  1338. break;
  1339. case METADATA_DEL_DIMENSION:
  1340. uuid = (uuid_t *) cmd.param[0];
  1341. if (likely(dimension_can_be_deleted(uuid, NULL, false)))
  1342. delete_dimension_uuid(uuid, NULL, false);
  1343. freez(uuid);
  1344. break;
  1345. case METADATA_STORE_CLAIM_ID:
  1346. store_claim_id((uuid_t *) cmd.param[0], (uuid_t *) cmd.param[1]);
  1347. freez((void *) cmd.param[0]);
  1348. freez((void *) cmd.param[1]);
  1349. break;
  1350. case METADATA_ADD_HOST_INFO:
  1351. host = (RRDHOST *) cmd.param[0];
  1352. store_host_and_system_info(host, NULL);
  1353. break;
  1354. case METADATA_SCAN_HOSTS:
  1355. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_PROCESSING)))
  1356. break;
  1357. if (unittest_running)
  1358. break;
  1359. data = mallocz(sizeof(*data));
  1360. data->request.data = data;
  1361. data->wc = wc;
  1362. data->data = cl_cleanup_data;
  1363. data->work_buffer = work_buffer;
  1364. cl_cleanup_data = NULL;
  1365. if (unlikely(cmd.completion)) {
  1366. data->max_count = 0; // 0 will process all pending updates
  1367. cmd.completion = NULL; // Do not complete after launching worker (worker will do)
  1368. }
  1369. else
  1370. data->max_count = 5000;
  1371. metadata_flag_set(wc, METADATA_FLAG_PROCESSING);
  1372. if (unlikely(
  1373. uv_queue_work(loop,&data->request,
  1374. start_metadata_hosts,
  1375. after_metadata_hosts))) {
  1376. // Failed to launch worker -- let the event loop handle completion
  1377. cmd.completion = wc->scan_complete;
  1378. cl_cleanup_data = data->data;
  1379. freez(data);
  1380. metadata_flag_clear(wc, METADATA_FLAG_PROCESSING);
  1381. }
  1382. break;
  1383. case METADATA_LOAD_HOST_CONTEXT:;
  1384. if (unittest_running)
  1385. break;
  1386. data = callocz(1,sizeof(*data));
  1387. data->request.data = data;
  1388. data->wc = wc;
  1389. if (unlikely(
  1390. uv_queue_work(loop,&data->request, start_all_host_load_context,
  1391. after_start_host_load_context))) {
  1392. freez(data);
  1393. }
  1394. break;
  1395. case METADATA_DELETE_HOST_CHART_LABELS:;
  1396. if (!cl_cleanup_data)
  1397. cl_cleanup_data = callocz(1,sizeof(*cl_cleanup_data));
  1398. Pvoid_t *PValue = JudyLIns(&cl_cleanup_data->JudyL, (Word_t) ++cl_cleanup_data->count, PJE0);
  1399. if (PValue)
  1400. *PValue = (void *) cmd.param[0];
  1401. break;
  1402. case METADATA_UNITTEST:;
  1403. struct thread_unittest *tu = (struct thread_unittest *) cmd.param[0];
  1404. sleep_usec(1000); // processing takes 1ms
  1405. __atomic_fetch_add(&tu->processed, 1, __ATOMIC_SEQ_CST);
  1406. break;
  1407. default:
  1408. break;
  1409. }
  1410. if (cmd.completion)
  1411. completion_mark_complete(cmd.completion);
  1412. } while (opcode != METADATA_DATABASE_NOOP);
  1413. }
  1414. if (!uv_timer_stop(&wc->timer_req))
  1415. uv_close((uv_handle_t *)&wc->timer_req, NULL);
  1416. uv_close((uv_handle_t *)&wc->async, NULL);
  1417. int rc;
  1418. do {
  1419. rc = uv_loop_close(loop);
  1420. } while (rc != UV_EBUSY);
  1421. buffer_free(work_buffer);
  1422. freez(loop);
  1423. worker_unregister();
  1424. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Shutting down metadata thread");
  1425. completion_mark_complete(&wc->start_stop_complete);
  1426. if (wc->scan_complete) {
  1427. completion_destroy(wc->scan_complete);
  1428. freez(wc->scan_complete);
  1429. }
  1430. metadata_free_cmd_queue(wc);
  1431. return;
  1432. error_after_timer_init:
  1433. uv_close((uv_handle_t *)&wc->async, NULL);
  1434. error_after_async_init:
  1435. fatal_assert(0 == uv_loop_close(loop));
  1436. error_after_loop_init:
  1437. freez(loop);
  1438. worker_unregister();
  1439. }
  1440. void metadata_sync_shutdown(void)
  1441. {
  1442. completion_init(&metasync_worker.start_stop_complete);
  1443. struct metadata_cmd cmd;
  1444. memset(&cmd, 0, sizeof(cmd));
  1445. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Sending a shutdown command");
  1446. cmd.opcode = METADATA_SYNC_SHUTDOWN;
  1447. metadata_enq_cmd(&metasync_worker, &cmd);
  1448. /* wait for metadata thread to shut down */
  1449. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Waiting for shutdown ACK");
  1450. completion_wait_for(&metasync_worker.start_stop_complete);
  1451. completion_destroy(&metasync_worker.start_stop_complete);
  1452. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Shutdown complete");
  1453. }
  1454. void metadata_sync_shutdown_prepare(void)
  1455. {
  1456. if (unlikely(!metasync_worker.loop))
  1457. return;
  1458. struct metadata_cmd cmd;
  1459. memset(&cmd, 0, sizeof(cmd));
  1460. struct metadata_wc *wc = &metasync_worker;
  1461. struct completion *compl = mallocz(sizeof(*compl));
  1462. completion_init(compl);
  1463. __atomic_store_n(&wc->scan_complete, compl, __ATOMIC_RELAXED);
  1464. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Sending a scan host command");
  1465. uint32_t max_wait_iterations = 2000;
  1466. while (unlikely(metadata_flag_check(&metasync_worker, METADATA_FLAG_PROCESSING)) && max_wait_iterations--) {
  1467. if (max_wait_iterations == 1999)
  1468. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Current worker is running; waiting to finish");
  1469. sleep_usec(1000);
  1470. }
  1471. cmd.opcode = METADATA_SCAN_HOSTS;
  1472. metadata_enq_cmd(&metasync_worker, &cmd);
  1473. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Waiting for host scan completion");
  1474. completion_wait_for(wc->scan_complete);
  1475. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Host scan complete; can continue with shutdown");
  1476. }
  1477. // -------------------------------------------------------------
  1478. // Init function called on agent startup
  1479. void metadata_sync_init(void)
  1480. {
  1481. struct metadata_wc *wc = &metasync_worker;
  1482. memset(wc, 0, sizeof(*wc));
  1483. completion_init(&wc->start_stop_complete);
  1484. fatal_assert(0 == uv_thread_create(&(wc->thread), metadata_event_loop, wc));
  1485. completion_wait_for(&wc->start_stop_complete);
  1486. completion_destroy(&wc->start_stop_complete);
  1487. nd_log(NDLS_DAEMON, NDLP_DEBUG, "SQLite metadata sync initialization complete");
  1488. }
  1489. // Helpers
  1490. static inline void queue_metadata_cmd(enum metadata_opcode opcode, const void *param0, const void *param1)
  1491. {
  1492. struct metadata_cmd cmd;
  1493. cmd.opcode = opcode;
  1494. cmd.param[0] = param0;
  1495. cmd.param[1] = param1;
  1496. cmd.completion = NULL;
  1497. metadata_enq_cmd(&metasync_worker, &cmd);
  1498. }
  1499. // Public
  1500. void metaqueue_delete_dimension_uuid(uuid_t *uuid)
  1501. {
  1502. if (unlikely(!metasync_worker.loop))
  1503. return;
  1504. uuid_t *use_uuid = mallocz(sizeof(*uuid));
  1505. uuid_copy(*use_uuid, *uuid);
  1506. queue_metadata_cmd(METADATA_DEL_DIMENSION, use_uuid, NULL);
  1507. }
  1508. void metaqueue_store_claim_id(uuid_t *host_uuid, uuid_t *claim_uuid)
  1509. {
  1510. if (unlikely(!host_uuid))
  1511. return;
  1512. uuid_t *local_host_uuid = mallocz(sizeof(*host_uuid));
  1513. uuid_t *local_claim_uuid = NULL;
  1514. uuid_copy(*local_host_uuid, *host_uuid);
  1515. if (likely(claim_uuid)) {
  1516. local_claim_uuid = mallocz(sizeof(*claim_uuid));
  1517. uuid_copy(*local_claim_uuid, *claim_uuid);
  1518. }
  1519. queue_metadata_cmd(METADATA_STORE_CLAIM_ID, local_host_uuid, local_claim_uuid);
  1520. }
  1521. void metaqueue_host_update_info(RRDHOST *host)
  1522. {
  1523. if (unlikely(!metasync_worker.loop))
  1524. return;
  1525. queue_metadata_cmd(METADATA_ADD_HOST_INFO, host, NULL);
  1526. }
  1527. void metaqueue_ml_load_models(RRDDIM *rd)
  1528. {
  1529. rrddim_flag_set(rd, RRDDIM_FLAG_ML_MODEL_LOAD);
  1530. }
  1531. void metadata_queue_load_host_context(RRDHOST *host)
  1532. {
  1533. if (unlikely(!metasync_worker.loop))
  1534. return;
  1535. queue_metadata_cmd(METADATA_LOAD_HOST_CONTEXT, host, NULL);
  1536. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Queued command to load host contexts");
  1537. }
  1538. void metadata_delete_host_chart_labels(char *machine_guid)
  1539. {
  1540. if (unlikely(!metasync_worker.loop)) {
  1541. freez(machine_guid);
  1542. return;
  1543. }
  1544. // Node machine guid is already strdup-ed
  1545. queue_metadata_cmd(METADATA_DELETE_HOST_CHART_LABELS, machine_guid, NULL);
  1546. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Queued command delete chart labels for host %s", machine_guid);
  1547. }
  1548. //
  1549. // unitests
  1550. //
  1551. static void *unittest_queue_metadata(void *arg) {
  1552. struct thread_unittest *tu = arg;
  1553. struct metadata_cmd cmd;
  1554. cmd.opcode = METADATA_UNITTEST;
  1555. cmd.param[0] = tu;
  1556. cmd.param[1] = NULL;
  1557. cmd.completion = NULL;
  1558. metadata_enq_cmd(&metasync_worker, &cmd);
  1559. do {
  1560. __atomic_fetch_add(&tu->added, 1, __ATOMIC_SEQ_CST);
  1561. metadata_enq_cmd(&metasync_worker, &cmd);
  1562. sleep_usec(10000);
  1563. } while (!__atomic_load_n(&tu->join, __ATOMIC_RELAXED));
  1564. return arg;
  1565. }
  1566. static void *metadata_unittest_threads(void)
  1567. {
  1568. unsigned done;
  1569. struct thread_unittest tu = {
  1570. .join = 0,
  1571. .added = 0,
  1572. .processed = 0,
  1573. .done = &done,
  1574. };
  1575. // Queue messages / Time it
  1576. time_t seconds_to_run = 5;
  1577. int threads_to_create = 4;
  1578. fprintf(
  1579. stderr,
  1580. "\nChecking metadata queue using %d threads for %lld seconds...\n",
  1581. threads_to_create,
  1582. (long long)seconds_to_run);
  1583. netdata_thread_t threads[threads_to_create];
  1584. tu.join = 0;
  1585. for (int i = 0; i < threads_to_create; i++) {
  1586. char buf[100 + 1];
  1587. snprintf(buf, sizeof(buf) - 1, "META[%d]", i);
  1588. netdata_thread_create(
  1589. &threads[i],
  1590. buf,
  1591. NETDATA_THREAD_OPTION_DONT_LOG | NETDATA_THREAD_OPTION_JOINABLE,
  1592. unittest_queue_metadata,
  1593. &tu);
  1594. }
  1595. (void) uv_async_send(&metasync_worker.async);
  1596. sleep_usec(seconds_to_run * USEC_PER_SEC);
  1597. __atomic_store_n(&tu.join, 1, __ATOMIC_RELAXED);
  1598. for (int i = 0; i < threads_to_create; i++) {
  1599. void *retval;
  1600. netdata_thread_join(threads[i], &retval);
  1601. }
  1602. sleep_usec(5 * USEC_PER_SEC);
  1603. fprintf(stderr, "Added %u elements, processed %u\n", tu.added, tu.processed);
  1604. return 0;
  1605. }
  1606. int metadata_unittest(void)
  1607. {
  1608. metadata_sync_init();
  1609. // Queue items for a specific period of time
  1610. metadata_unittest_threads();
  1611. metadata_sync_shutdown();
  1612. return 0;
  1613. }