sqlite_metadata.c 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
  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. nd_log(NDLS_DAEMON, NDLP_DEBUG, "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. nd_log(
  731. NDLS_DAEMON,
  732. NDLP_DEBUG,
  733. "Dimensions checked %u, deleted %u. Checks will %s in %lld seconds",
  734. total_checked,
  735. total_deleted,
  736. last_row_id ? "resume" : "restart",
  737. (long long)(next_execution_t - now));
  738. rc = sqlite3_finalize(res);
  739. if (unlikely(rc != SQLITE_OK))
  740. error_report("Failed to finalize the prepared statement to check dimensions");
  741. }
  742. static void check_chart_metadata(struct metadata_wc *wc)
  743. {
  744. static time_t next_execution_t = 0;
  745. static uint64_t last_row_id = 0;
  746. time_t now = now_realtime_sec();
  747. if (!next_execution_t)
  748. next_execution_t = now + METADATA_MAINTENANCE_FIRST_CHECK;
  749. if (next_execution_t && next_execution_t > now)
  750. return;
  751. sqlite3_stmt *res = NULL;
  752. int rc = sqlite3_prepare_v2(db_meta, SELECT_CHART_LIST, -1, &res, 0);
  753. if (unlikely(rc != SQLITE_OK)) {
  754. error_report("Failed to prepare statement to fetch charts");
  755. return;
  756. }
  757. uint32_t total_checked = 0;
  758. uint32_t total_deleted = 0;
  759. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Checking charts starting after row %" PRIu64, last_row_id);
  760. sqlite3_stmt *check_res = NULL;
  761. sqlite3_stmt *action_res = NULL;
  762. bool more_to_do = run_cleanup_loop(
  763. res,
  764. wc,
  765. chart_can_be_deleted,
  766. delete_chart_uuid,
  767. &total_checked,
  768. &total_deleted,
  769. &last_row_id,
  770. &check_res,
  771. &action_res,
  772. true,
  773. false);
  774. if (check_res)
  775. sqlite3_finalize(check_res);
  776. if (action_res)
  777. sqlite3_finalize(action_res);
  778. now = now_realtime_sec();
  779. if (more_to_do)
  780. next_execution_t = now + METADATA_MAINTENANCE_REPEAT;
  781. else {
  782. last_row_id = 0;
  783. next_execution_t = now + METADATA_CHART_CHECK_INTERVAL;
  784. }
  785. nd_log(
  786. NDLS_DAEMON,
  787. NDLP_DEBUG,
  788. "Charts checked %u, deleted %u. Checks will %s in %lld seconds",
  789. total_checked,
  790. total_deleted,
  791. last_row_id ? "resume" : "restart",
  792. (long long)(next_execution_t - now));
  793. rc = sqlite3_finalize(res);
  794. if (unlikely(rc != SQLITE_OK))
  795. error_report("Failed to finalize the prepared statement when reading charts");
  796. }
  797. static void check_label_metadata(struct metadata_wc *wc)
  798. {
  799. static time_t next_execution_t = 0;
  800. static uint64_t last_row_id = 0;
  801. time_t now = now_realtime_sec();
  802. if (!next_execution_t)
  803. next_execution_t = now + METADATA_MAINTENANCE_FIRST_CHECK;
  804. if (next_execution_t && next_execution_t > now)
  805. return;
  806. int rc;
  807. sqlite3_stmt *res = NULL;
  808. rc = sqlite3_prepare_v2(db_meta, SELECT_CHART_LABEL_LIST, -1, &res, 0);
  809. if (unlikely(rc != SQLITE_OK)) {
  810. error_report("Failed to prepare statement to fetch charts");
  811. return;
  812. }
  813. uint32_t total_checked = 0;
  814. uint32_t total_deleted = 0;
  815. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Checking charts labels starting after row %" PRIu64, last_row_id);
  816. sqlite3_stmt *check_res = NULL;
  817. sqlite3_stmt *action_res = NULL;
  818. bool more_to_do = run_cleanup_loop(
  819. res,
  820. wc,
  821. chart_can_be_deleted,
  822. delete_chart_uuid,
  823. &total_checked,
  824. &total_deleted,
  825. &last_row_id,
  826. &check_res,
  827. &action_res,
  828. false,
  829. true);
  830. if (check_res)
  831. sqlite3_finalize(check_res);
  832. if (action_res)
  833. sqlite3_finalize(action_res);
  834. now = now_realtime_sec();
  835. if (more_to_do)
  836. next_execution_t = now + METADATA_MAINTENANCE_REPEAT;
  837. else {
  838. last_row_id = 0;
  839. next_execution_t = now + METADATA_LABEL_CHECK_INTERVAL;
  840. }
  841. nd_log(
  842. NDLS_DAEMON,
  843. NDLP_DEBUG,
  844. "Chart labels checked %u, deleted %u. Checks will %s in %lld seconds",
  845. total_checked,
  846. total_deleted,
  847. last_row_id ? "resume" : "restart",
  848. (long long)(next_execution_t - now));
  849. rc = sqlite3_finalize(res);
  850. if (unlikely(rc != SQLITE_OK))
  851. error_report("Failed to finalize the prepared statement when checking charts");
  852. }
  853. static void cleanup_health_log(struct metadata_wc *wc)
  854. {
  855. static time_t next_execution_t = 0;
  856. time_t now = now_realtime_sec();
  857. if (!next_execution_t)
  858. next_execution_t = now + METADATA_MAINTENANCE_FIRST_CHECK;
  859. if (next_execution_t && next_execution_t > now)
  860. return;
  861. next_execution_t = now + METADATA_HEALTH_LOG_INTERVAL;
  862. RRDHOST *host;
  863. bool is_claimed = claimed();
  864. dfe_start_reentrant(rrdhost_root_index, host){
  865. if (rrdhost_flag_check(host, RRDHOST_FLAG_ARCHIVED))
  866. continue;
  867. sql_health_alarm_log_cleanup(host, is_claimed);
  868. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN)))
  869. break;
  870. }
  871. dfe_done(host);
  872. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN)))
  873. return;
  874. (void) db_execute(db_meta,"DELETE FROM health_log WHERE host_id NOT IN (SELECT host_id FROM host)");
  875. (void) db_execute(db_meta,"DELETE FROM health_log_detail WHERE health_log_id NOT IN (SELECT health_log_id FROM health_log)");
  876. }
  877. //
  878. // EVENT LOOP STARTS HERE
  879. //
  880. static void metadata_free_cmd_queue(struct metadata_wc *wc)
  881. {
  882. spinlock_lock(&wc->cmd_queue_lock);
  883. while(wc->cmd_base) {
  884. struct metadata_cmd *t = wc->cmd_base;
  885. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(wc->cmd_base, t, prev, next);
  886. freez(t);
  887. }
  888. spinlock_unlock(&wc->cmd_queue_lock);
  889. }
  890. static void metadata_enq_cmd(struct metadata_wc *wc, struct metadata_cmd *cmd)
  891. {
  892. if (cmd->opcode == METADATA_SYNC_SHUTDOWN) {
  893. metadata_flag_set(wc, METADATA_FLAG_SHUTDOWN);
  894. goto wakeup_event_loop;
  895. }
  896. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN)))
  897. goto wakeup_event_loop;
  898. struct metadata_cmd *t = mallocz(sizeof(*t));
  899. *t = *cmd;
  900. t->prev = t->next = NULL;
  901. spinlock_lock(&wc->cmd_queue_lock);
  902. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(wc->cmd_base, t, prev, next);
  903. spinlock_unlock(&wc->cmd_queue_lock);
  904. wakeup_event_loop:
  905. (void) uv_async_send(&wc->async);
  906. }
  907. static struct metadata_cmd metadata_deq_cmd(struct metadata_wc *wc)
  908. {
  909. struct metadata_cmd ret;
  910. spinlock_lock(&wc->cmd_queue_lock);
  911. if(wc->cmd_base) {
  912. struct metadata_cmd *t = wc->cmd_base;
  913. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(wc->cmd_base, t, prev, next);
  914. ret = *t;
  915. freez(t);
  916. }
  917. else {
  918. ret.opcode = METADATA_DATABASE_NOOP;
  919. ret.completion = NULL;
  920. }
  921. spinlock_unlock(&wc->cmd_queue_lock);
  922. return ret;
  923. }
  924. static void async_cb(uv_async_t *handle)
  925. {
  926. uv_stop(handle->loop);
  927. uv_update_time(handle->loop);
  928. }
  929. #define TIMER_INITIAL_PERIOD_MS (1000)
  930. #define TIMER_REPEAT_PERIOD_MS (1000)
  931. static void timer_cb(uv_timer_t* handle)
  932. {
  933. uv_stop(handle->loop);
  934. uv_update_time(handle->loop);
  935. struct metadata_wc *wc = handle->data;
  936. struct metadata_cmd cmd;
  937. memset(&cmd, 0, sizeof(cmd));
  938. if (wc->metadata_check_after < now_realtime_sec()) {
  939. cmd.opcode = METADATA_SCAN_HOSTS;
  940. metadata_enq_cmd(wc, &cmd);
  941. }
  942. }
  943. void vacuum_database(sqlite3 *database, const char *db_alias, int threshold, int vacuum_pc)
  944. {
  945. int free_pages = get_free_page_count(database);
  946. int total_pages = get_database_page_count(database);
  947. if (!threshold)
  948. threshold = DATABASE_FREE_PAGES_THRESHOLD_PC;
  949. if (!vacuum_pc)
  950. vacuum_pc = DATABASE_FREE_PAGES_VACUUM_PC;
  951. if (free_pages > (total_pages * threshold / 100)) {
  952. int do_free_pages = (int) (free_pages * vacuum_pc / 100);
  953. nd_log(NDLS_DAEMON, NDLP_DEBUG, "%s: Freeing %d database pages", db_alias, do_free_pages);
  954. char sql[128];
  955. snprintfz(sql, sizeof(sql) - 1, "PRAGMA incremental_vacuum(%d)", do_free_pages);
  956. (void) db_execute(database, sql);
  957. }
  958. }
  959. void run_metadata_cleanup(struct metadata_wc *wc)
  960. {
  961. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN)))
  962. return;
  963. check_dimension_metadata(wc);
  964. check_chart_metadata(wc);
  965. check_label_metadata(wc);
  966. cleanup_health_log(wc);
  967. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN)))
  968. return;
  969. vacuum_database(db_meta, "METADATA", DATABASE_FREE_PAGES_THRESHOLD_PC, DATABASE_FREE_PAGES_VACUUM_PC);
  970. (void) sqlite3_wal_checkpoint(db_meta, NULL);
  971. }
  972. struct scan_metadata_payload {
  973. uv_work_t request;
  974. struct metadata_wc *wc;
  975. void *data;
  976. BUFFER *work_buffer;
  977. uint32_t max_count;
  978. };
  979. struct host_context_load_thread {
  980. uv_thread_t thread;
  981. RRDHOST *host;
  982. bool busy;
  983. bool finished;
  984. };
  985. static void restore_host_context(void *arg)
  986. {
  987. struct host_context_load_thread *hclt = arg;
  988. RRDHOST *host = hclt->host;
  989. usec_t started_ut = now_monotonic_usec(); (void)started_ut;
  990. rrdhost_load_rrdcontext_data(host);
  991. usec_t ended_ut = now_monotonic_usec(); (void)ended_ut;
  992. rrdhost_flag_clear(host, RRDHOST_FLAG_PENDING_CONTEXT_LOAD);
  993. #ifdef ENABLE_ACLK
  994. aclk_queue_node_info(host, false);
  995. #endif
  996. nd_log(
  997. NDLS_DAEMON,
  998. NDLP_DEBUG,
  999. "Contexts for host %s loaded in %0.2f ms",
  1000. rrdhost_hostname(host),
  1001. (double)(ended_ut - started_ut) / USEC_PER_MS);
  1002. __atomic_store_n(&hclt->finished, true, __ATOMIC_RELEASE);
  1003. }
  1004. // Callback after scan of hosts is done
  1005. static void after_start_host_load_context(uv_work_t *req, int status __maybe_unused)
  1006. {
  1007. struct scan_metadata_payload *data = req->data;
  1008. freez(data);
  1009. }
  1010. #define MAX_FIND_THREAD_RETRIES (10)
  1011. static void cleanup_finished_threads(struct host_context_load_thread *hclt, size_t max_thread_slots, bool wait)
  1012. {
  1013. if (!hclt)
  1014. return;
  1015. for (size_t index = 0; index < max_thread_slots; index++) {
  1016. if (__atomic_load_n(&(hclt[index].finished), __ATOMIC_RELAXED)
  1017. || (wait && __atomic_load_n(&(hclt[index].busy), __ATOMIC_ACQUIRE))) {
  1018. int rc = uv_thread_join(&(hclt[index].thread));
  1019. if (rc)
  1020. nd_log(NDLS_DAEMON, NDLP_WARNING, "Failed to join thread, rc = %d", rc);
  1021. __atomic_store_n(&(hclt[index].busy), false, __ATOMIC_RELEASE);
  1022. __atomic_store_n(&(hclt[index].finished), false, __ATOMIC_RELEASE);
  1023. }
  1024. }
  1025. }
  1026. static size_t find_available_thread_slot(struct host_context_load_thread *hclt, size_t max_thread_slots, size_t *found_index)
  1027. {
  1028. size_t retries = MAX_FIND_THREAD_RETRIES;
  1029. while (retries--) {
  1030. size_t index = 0;
  1031. while (index < max_thread_slots) {
  1032. if (false == __atomic_load_n(&(hclt[index].busy), __ATOMIC_ACQUIRE)) {
  1033. *found_index = index;
  1034. return true;
  1035. }
  1036. index++;
  1037. }
  1038. sleep_usec(10 * USEC_PER_MS);
  1039. }
  1040. return false;
  1041. }
  1042. static void start_all_host_load_context(uv_work_t *req __maybe_unused)
  1043. {
  1044. register_libuv_worker_jobs();
  1045. struct scan_metadata_payload *data = req->data;
  1046. struct metadata_wc *wc = data->wc;
  1047. worker_is_busy(UV_EVENT_HOST_CONTEXT_LOAD);
  1048. usec_t started_ut = now_monotonic_usec(); (void)started_ut;
  1049. RRDHOST *host;
  1050. size_t max_threads = MIN(get_netdata_cpus() / 2, 6);
  1051. if (max_threads < 1)
  1052. max_threads = 1;
  1053. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Using %zu threads for context loading", max_threads);
  1054. struct host_context_load_thread *hclt = max_threads > 1 ? callocz(max_threads, sizeof(*hclt)) : NULL;
  1055. size_t thread_index = 0;
  1056. dfe_start_reentrant(rrdhost_root_index, host) {
  1057. if (!rrdhost_flag_check(host, RRDHOST_FLAG_PENDING_CONTEXT_LOAD))
  1058. continue;
  1059. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Loading context for host %s", rrdhost_hostname(host));
  1060. int rc = 0;
  1061. if (hclt) {
  1062. bool found_slot = false;
  1063. do {
  1064. if (metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN))
  1065. break;
  1066. cleanup_finished_threads(hclt, max_threads, false);
  1067. found_slot = find_available_thread_slot(hclt, max_threads, &thread_index);
  1068. } while (!found_slot);
  1069. if (metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN))
  1070. break;
  1071. __atomic_store_n(&hclt[thread_index].busy, true, __ATOMIC_RELAXED);
  1072. hclt[thread_index].host = host;
  1073. rc = uv_thread_create(&hclt[thread_index].thread, restore_host_context, &hclt[thread_index]);
  1074. }
  1075. // if single thread or thread creation failed
  1076. if (rc || !hclt) {
  1077. struct host_context_load_thread hclt_sync = {.host = host};
  1078. restore_host_context(&hclt_sync);
  1079. if (metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN))
  1080. break;
  1081. }
  1082. }
  1083. dfe_done(host);
  1084. cleanup_finished_threads(hclt, max_threads, true);
  1085. freez(hclt);
  1086. usec_t ended_ut = now_monotonic_usec(); (void)ended_ut;
  1087. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Host contexts loaded in %0.2f ms", (double)(ended_ut - started_ut) / USEC_PER_MS);
  1088. worker_is_idle();
  1089. }
  1090. // Callback after scan of hosts is done
  1091. static void after_metadata_hosts(uv_work_t *req, int status __maybe_unused)
  1092. {
  1093. struct scan_metadata_payload *data = req->data;
  1094. struct metadata_wc *wc = data->wc;
  1095. metadata_flag_clear(wc, METADATA_FLAG_PROCESSING);
  1096. if (unlikely(wc->scan_complete))
  1097. completion_mark_complete(wc->scan_complete);
  1098. freez(data);
  1099. }
  1100. static bool metadata_scan_host(RRDHOST *host, uint32_t max_count, bool use_transaction, BUFFER *work_buffer, size_t *query_counter) {
  1101. RRDSET *st;
  1102. int rc;
  1103. bool more_to_do = false;
  1104. uint32_t scan_count = 1;
  1105. sqlite3_stmt *ml_load_stmt = NULL;
  1106. bool load_ml_models = max_count;
  1107. if (use_transaction)
  1108. (void)db_execute(db_meta, "BEGIN TRANSACTION");
  1109. rrdset_foreach_reentrant(st, host) {
  1110. if (scan_count == max_count) {
  1111. more_to_do = true;
  1112. break;
  1113. }
  1114. if(rrdset_flag_check(st, RRDSET_FLAG_METADATA_UPDATE)) {
  1115. (*query_counter)++;
  1116. rrdset_flag_clear(st, RRDSET_FLAG_METADATA_UPDATE);
  1117. scan_count++;
  1118. buffer_flush(work_buffer);
  1119. rc = check_and_update_chart_labels(st, work_buffer, query_counter);
  1120. if (unlikely(rc))
  1121. error_report("METADATA: 'host:%s': Failed to update labels for chart %s", rrdhost_hostname(host), rrdset_name(st));
  1122. else
  1123. (*query_counter)++;
  1124. rc = store_chart_metadata(st);
  1125. if (unlikely(rc))
  1126. error_report("METADATA: 'host:%s': Failed to store metadata for chart %s", rrdhost_hostname(host), rrdset_name(st));
  1127. }
  1128. RRDDIM *rd;
  1129. rrddim_foreach_read(rd, st) {
  1130. if(rrddim_flag_check(rd, RRDDIM_FLAG_METADATA_UPDATE)) {
  1131. (*query_counter)++;
  1132. rrddim_flag_clear(rd, RRDDIM_FLAG_METADATA_UPDATE);
  1133. if (rrddim_option_check(rd, RRDDIM_OPTION_HIDDEN))
  1134. rrddim_flag_set(rd, RRDDIM_FLAG_META_HIDDEN);
  1135. else
  1136. rrddim_flag_clear(rd, RRDDIM_FLAG_META_HIDDEN);
  1137. rc = store_dimension_metadata(rd);
  1138. if (unlikely(rc))
  1139. error_report("METADATA: 'host:%s': Failed to dimension metadata for chart %s. dimension %s",
  1140. rrdhost_hostname(host), rrdset_name(st),
  1141. rrddim_name(rd));
  1142. }
  1143. if(rrddim_flag_check(rd, RRDDIM_FLAG_ML_MODEL_LOAD)) {
  1144. rrddim_flag_clear(rd, RRDDIM_FLAG_ML_MODEL_LOAD);
  1145. if (likely(load_ml_models))
  1146. (void) ml_dimension_load_models(rd, &ml_load_stmt);
  1147. }
  1148. worker_is_idle();
  1149. }
  1150. rrddim_foreach_done(rd);
  1151. }
  1152. rrdset_foreach_done(st);
  1153. if (use_transaction)
  1154. (void)db_execute(db_meta, "COMMIT TRANSACTION");
  1155. if (ml_load_stmt) {
  1156. sqlite3_finalize(ml_load_stmt);
  1157. ml_load_stmt = NULL;
  1158. }
  1159. return more_to_do;
  1160. }
  1161. static void store_host_and_system_info(RRDHOST *host, size_t *query_counter)
  1162. {
  1163. if (unlikely(store_host_systeminfo(host))) {
  1164. error_report("METADATA: 'host:%s': Failed to store host updated system information in the database", rrdhost_hostname(host));
  1165. rrdhost_flag_set(host, RRDHOST_FLAG_METADATA_INFO | RRDHOST_FLAG_METADATA_UPDATE);
  1166. }
  1167. else {
  1168. if (likely(query_counter))
  1169. (*query_counter)++;
  1170. }
  1171. if (unlikely(store_host_metadata(host))) {
  1172. error_report("METADATA: 'host:%s': Failed to store host info in the database", rrdhost_hostname(host));
  1173. rrdhost_flag_set(host, RRDHOST_FLAG_METADATA_INFO | RRDHOST_FLAG_METADATA_UPDATE);
  1174. }
  1175. else {
  1176. if (likely(query_counter))
  1177. (*query_counter)++;
  1178. }
  1179. }
  1180. struct host_chart_label_cleanup {
  1181. Pvoid_t JudyL;
  1182. Word_t count;
  1183. };
  1184. static void do_chart_label_cleanup(struct host_chart_label_cleanup *cl_cleanup_data)
  1185. {
  1186. if (!cl_cleanup_data)
  1187. return;
  1188. Word_t Index = 0;
  1189. bool first = true;
  1190. Pvoid_t *PValue;
  1191. while ((PValue = JudyLFirstThenNext(cl_cleanup_data->JudyL, &Index, &first))) {
  1192. char *machine_guid = *PValue;
  1193. RRDHOST *host = rrdhost_find_by_guid(machine_guid);
  1194. if (likely(!host)) {
  1195. uuid_t host_uuid;
  1196. if (!uuid_parse(machine_guid, host_uuid))
  1197. delete_host_chart_labels(&host_uuid);
  1198. }
  1199. freez(machine_guid);
  1200. }
  1201. JudyLFreeArray(&cl_cleanup_data->JudyL, PJE0);
  1202. freez(cl_cleanup_data);
  1203. }
  1204. // Worker thread to scan hosts for pending metadata to store
  1205. static void start_metadata_hosts(uv_work_t *req __maybe_unused)
  1206. {
  1207. register_libuv_worker_jobs();
  1208. RRDHOST *host;
  1209. int transaction_started = 0;
  1210. struct scan_metadata_payload *data = req->data;
  1211. struct metadata_wc *wc = data->wc;
  1212. BUFFER *work_buffer = data->work_buffer;
  1213. usec_t all_started_ut = now_monotonic_usec(); (void)all_started_ut;
  1214. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Checking all hosts started");
  1215. usec_t started_ut = now_monotonic_usec(); (void)started_ut;
  1216. do_chart_label_cleanup((struct host_chart_label_cleanup *) data->data);
  1217. bool run_again = false;
  1218. worker_is_busy(UV_EVENT_METADATA_STORE);
  1219. if (!data->max_count)
  1220. transaction_started = !db_execute(db_meta, "BEGIN TRANSACTION");
  1221. dfe_start_reentrant(rrdhost_root_index, host) {
  1222. if (rrdhost_flag_check(host, RRDHOST_FLAG_ARCHIVED) || !rrdhost_flag_check(host, RRDHOST_FLAG_METADATA_UPDATE))
  1223. continue;
  1224. size_t query_counter = 0; (void)query_counter;
  1225. rrdhost_flag_clear(host,RRDHOST_FLAG_METADATA_UPDATE);
  1226. if (unlikely(rrdhost_flag_check(host, RRDHOST_FLAG_METADATA_LABELS))) {
  1227. rrdhost_flag_clear(host, RRDHOST_FLAG_METADATA_LABELS);
  1228. int rc = exec_statement_with_uuid(SQL_DELETE_HOST_LABELS, &host->host_uuid);
  1229. if (likely(!rc)) {
  1230. query_counter++;
  1231. buffer_flush(work_buffer);
  1232. struct query_build tmp = {.sql = work_buffer, .count = 0};
  1233. uuid_unparse_lower(host->host_uuid, tmp.uuid_str);
  1234. rrdlabels_walkthrough_read(host->rrdlabels, host_label_store_to_sql_callback, &tmp);
  1235. 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()");
  1236. rc = db_execute(db_meta, buffer_tostring(work_buffer));
  1237. if (unlikely(rc)) {
  1238. error_report("METADATA: 'host:%s': failed to update metadata host labels", rrdhost_hostname(host));
  1239. rrdhost_flag_set(host, RRDHOST_FLAG_METADATA_LABELS | RRDHOST_FLAG_METADATA_UPDATE);
  1240. }
  1241. else
  1242. query_counter++;
  1243. } else {
  1244. error_report("METADATA: 'host:%s': failed to delete old host labels", rrdhost_hostname(host));
  1245. rrdhost_flag_set(host, RRDHOST_FLAG_METADATA_LABELS | RRDHOST_FLAG_METADATA_UPDATE);
  1246. }
  1247. }
  1248. if (unlikely(rrdhost_flag_check(host, RRDHOST_FLAG_METADATA_CLAIMID))) {
  1249. rrdhost_flag_clear(host, RRDHOST_FLAG_METADATA_CLAIMID);
  1250. uuid_t uuid;
  1251. int rc;
  1252. if (likely(host->aclk_state.claimed_id && !uuid_parse(host->aclk_state.claimed_id, uuid)))
  1253. rc = store_claim_id(&host->host_uuid, &uuid);
  1254. else
  1255. rc = store_claim_id(&host->host_uuid, NULL);
  1256. if (unlikely(rc))
  1257. rrdhost_flag_set(host, RRDHOST_FLAG_METADATA_CLAIMID | RRDHOST_FLAG_METADATA_UPDATE);
  1258. else
  1259. query_counter++;
  1260. }
  1261. if (unlikely(rrdhost_flag_check(host, RRDHOST_FLAG_METADATA_INFO))) {
  1262. rrdhost_flag_clear(host, RRDHOST_FLAG_METADATA_INFO);
  1263. store_host_and_system_info(host, &query_counter);
  1264. }
  1265. // For clarity
  1266. bool use_transaction = data->max_count;
  1267. if (unlikely(metadata_scan_host(host, data->max_count, use_transaction, work_buffer, &query_counter))) {
  1268. run_again = true;
  1269. rrdhost_flag_set(host,RRDHOST_FLAG_METADATA_UPDATE);
  1270. }
  1271. usec_t ended_ut = now_monotonic_usec(); (void)ended_ut;
  1272. nd_log(
  1273. NDLS_DAEMON,
  1274. NDLP_DEBUG,
  1275. "Host %s saved metadata with %zu SQL statements, in %0.2f ms",
  1276. rrdhost_hostname(host),
  1277. query_counter,
  1278. (double)(ended_ut - started_ut) / USEC_PER_MS);
  1279. }
  1280. dfe_done(host);
  1281. if (!data->max_count && transaction_started)
  1282. transaction_started = db_execute(db_meta, "COMMIT TRANSACTION");
  1283. usec_t all_ended_ut = now_monotonic_usec(); (void)all_ended_ut;
  1284. nd_log(
  1285. NDLS_DAEMON,
  1286. NDLP_DEBUG,
  1287. "Checking all hosts completed in %0.2f ms",
  1288. (double)(all_ended_ut - all_started_ut) / USEC_PER_MS);
  1289. if (unlikely(run_again))
  1290. wc->metadata_check_after = now_realtime_sec() + METADATA_HOST_CHECK_IMMEDIATE;
  1291. else {
  1292. wc->metadata_check_after = now_realtime_sec() + METADATA_HOST_CHECK_INTERVAL;
  1293. run_metadata_cleanup(wc);
  1294. }
  1295. worker_is_idle();
  1296. }
  1297. static void metadata_event_loop(void *arg)
  1298. {
  1299. worker_register("METASYNC");
  1300. worker_register_job_name(METADATA_DATABASE_NOOP, "noop");
  1301. worker_register_job_name(METADATA_DATABASE_TIMER, "timer");
  1302. worker_register_job_name(METADATA_DEL_DIMENSION, "delete dimension");
  1303. worker_register_job_name(METADATA_STORE_CLAIM_ID, "add claim id");
  1304. worker_register_job_name(METADATA_ADD_HOST_INFO, "add host info");
  1305. worker_register_job_name(METADATA_MAINTENANCE, "maintenance");
  1306. int ret;
  1307. uv_loop_t *loop;
  1308. unsigned cmd_batch_size;
  1309. struct metadata_wc *wc = arg;
  1310. enum metadata_opcode opcode;
  1311. uv_thread_set_name_np(wc->thread, "METASYNC");
  1312. loop = wc->loop = mallocz(sizeof(uv_loop_t));
  1313. ret = uv_loop_init(loop);
  1314. if (ret) {
  1315. netdata_log_error("uv_loop_init(): %s", uv_strerror(ret));
  1316. goto error_after_loop_init;
  1317. }
  1318. loop->data = wc;
  1319. ret = uv_async_init(wc->loop, &wc->async, async_cb);
  1320. if (ret) {
  1321. netdata_log_error("uv_async_init(): %s", uv_strerror(ret));
  1322. goto error_after_async_init;
  1323. }
  1324. wc->async.data = wc;
  1325. ret = uv_timer_init(loop, &wc->timer_req);
  1326. if (ret) {
  1327. netdata_log_error("uv_timer_init(): %s", uv_strerror(ret));
  1328. goto error_after_timer_init;
  1329. }
  1330. wc->timer_req.data = wc;
  1331. fatal_assert(0 == uv_timer_start(&wc->timer_req, timer_cb, TIMER_INITIAL_PERIOD_MS, TIMER_REPEAT_PERIOD_MS));
  1332. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Starting metadata sync thread");
  1333. struct metadata_cmd cmd;
  1334. memset(&cmd, 0, sizeof(cmd));
  1335. metadata_flag_clear(wc, METADATA_FLAG_PROCESSING);
  1336. wc->metadata_check_after = now_realtime_sec() + METADATA_HOST_CHECK_FIRST_CHECK;
  1337. int shutdown = 0;
  1338. completion_mark_complete(&wc->start_stop_complete);
  1339. BUFFER *work_buffer = buffer_create(1024, &netdata_buffers_statistics.buffers_sqlite);
  1340. struct scan_metadata_payload *data;
  1341. struct host_chart_label_cleanup *cl_cleanup_data = NULL;
  1342. while (shutdown == 0 || (wc->flags & METADATA_FLAG_PROCESSING)) {
  1343. uuid_t *uuid;
  1344. RRDHOST *host = NULL;
  1345. worker_is_idle();
  1346. uv_run(loop, UV_RUN_DEFAULT);
  1347. /* wait for commands */
  1348. cmd_batch_size = 0;
  1349. do {
  1350. if (unlikely(cmd_batch_size >= METADATA_MAX_BATCH_SIZE))
  1351. break;
  1352. cmd = metadata_deq_cmd(wc);
  1353. opcode = cmd.opcode;
  1354. if (unlikely(opcode == METADATA_DATABASE_NOOP && metadata_flag_check(wc, METADATA_FLAG_SHUTDOWN))) {
  1355. shutdown = 1;
  1356. continue;
  1357. }
  1358. ++cmd_batch_size;
  1359. if (likely(opcode != METADATA_DATABASE_NOOP))
  1360. worker_is_busy(opcode);
  1361. switch (opcode) {
  1362. case METADATA_DATABASE_NOOP:
  1363. case METADATA_DATABASE_TIMER:
  1364. break;
  1365. case METADATA_DEL_DIMENSION:
  1366. uuid = (uuid_t *) cmd.param[0];
  1367. if (likely(dimension_can_be_deleted(uuid, NULL, false)))
  1368. delete_dimension_uuid(uuid, NULL, false);
  1369. freez(uuid);
  1370. break;
  1371. case METADATA_STORE_CLAIM_ID:
  1372. store_claim_id((uuid_t *) cmd.param[0], (uuid_t *) cmd.param[1]);
  1373. freez((void *) cmd.param[0]);
  1374. freez((void *) cmd.param[1]);
  1375. break;
  1376. case METADATA_ADD_HOST_INFO:
  1377. host = (RRDHOST *) cmd.param[0];
  1378. store_host_and_system_info(host, NULL);
  1379. break;
  1380. case METADATA_SCAN_HOSTS:
  1381. if (unlikely(metadata_flag_check(wc, METADATA_FLAG_PROCESSING)))
  1382. break;
  1383. if (unittest_running)
  1384. break;
  1385. data = mallocz(sizeof(*data));
  1386. data->request.data = data;
  1387. data->wc = wc;
  1388. data->data = cl_cleanup_data;
  1389. data->work_buffer = work_buffer;
  1390. cl_cleanup_data = NULL;
  1391. if (unlikely(cmd.completion)) {
  1392. data->max_count = 0; // 0 will process all pending updates
  1393. cmd.completion = NULL; // Do not complete after launching worker (worker will do)
  1394. }
  1395. else
  1396. data->max_count = 5000;
  1397. metadata_flag_set(wc, METADATA_FLAG_PROCESSING);
  1398. if (unlikely(
  1399. uv_queue_work(loop,&data->request,
  1400. start_metadata_hosts,
  1401. after_metadata_hosts))) {
  1402. // Failed to launch worker -- let the event loop handle completion
  1403. cmd.completion = wc->scan_complete;
  1404. cl_cleanup_data = data->data;
  1405. freez(data);
  1406. metadata_flag_clear(wc, METADATA_FLAG_PROCESSING);
  1407. }
  1408. break;
  1409. case METADATA_LOAD_HOST_CONTEXT:;
  1410. if (unittest_running)
  1411. break;
  1412. data = callocz(1,sizeof(*data));
  1413. data->request.data = data;
  1414. data->wc = wc;
  1415. if (unlikely(
  1416. uv_queue_work(loop,&data->request, start_all_host_load_context,
  1417. after_start_host_load_context))) {
  1418. freez(data);
  1419. }
  1420. break;
  1421. case METADATA_DELETE_HOST_CHART_LABELS:;
  1422. if (!cl_cleanup_data)
  1423. cl_cleanup_data = callocz(1,sizeof(*cl_cleanup_data));
  1424. Pvoid_t *PValue = JudyLIns(&cl_cleanup_data->JudyL, (Word_t) ++cl_cleanup_data->count, PJE0);
  1425. if (PValue)
  1426. *PValue = (void *) cmd.param[0];
  1427. break;
  1428. case METADATA_UNITTEST:;
  1429. struct thread_unittest *tu = (struct thread_unittest *) cmd.param[0];
  1430. sleep_usec(1000); // processing takes 1ms
  1431. __atomic_fetch_add(&tu->processed, 1, __ATOMIC_SEQ_CST);
  1432. break;
  1433. default:
  1434. break;
  1435. }
  1436. if (cmd.completion)
  1437. completion_mark_complete(cmd.completion);
  1438. } while (opcode != METADATA_DATABASE_NOOP);
  1439. }
  1440. if (!uv_timer_stop(&wc->timer_req))
  1441. uv_close((uv_handle_t *)&wc->timer_req, NULL);
  1442. uv_close((uv_handle_t *)&wc->async, NULL);
  1443. int rc;
  1444. do {
  1445. rc = uv_loop_close(loop);
  1446. } while (rc != UV_EBUSY);
  1447. buffer_free(work_buffer);
  1448. freez(loop);
  1449. worker_unregister();
  1450. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Shutting down metadata thread");
  1451. completion_mark_complete(&wc->start_stop_complete);
  1452. if (wc->scan_complete) {
  1453. completion_destroy(wc->scan_complete);
  1454. freez(wc->scan_complete);
  1455. }
  1456. metadata_free_cmd_queue(wc);
  1457. return;
  1458. error_after_timer_init:
  1459. uv_close((uv_handle_t *)&wc->async, NULL);
  1460. error_after_async_init:
  1461. fatal_assert(0 == uv_loop_close(loop));
  1462. error_after_loop_init:
  1463. freez(loop);
  1464. worker_unregister();
  1465. }
  1466. void metadata_sync_shutdown(void)
  1467. {
  1468. completion_init(&metasync_worker.start_stop_complete);
  1469. struct metadata_cmd cmd;
  1470. memset(&cmd, 0, sizeof(cmd));
  1471. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Sending a shutdown command");
  1472. cmd.opcode = METADATA_SYNC_SHUTDOWN;
  1473. metadata_enq_cmd(&metasync_worker, &cmd);
  1474. /* wait for metadata thread to shut down */
  1475. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Waiting for shutdown ACK");
  1476. completion_wait_for(&metasync_worker.start_stop_complete);
  1477. completion_destroy(&metasync_worker.start_stop_complete);
  1478. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Shutdown complete");
  1479. }
  1480. void metadata_sync_shutdown_prepare(void)
  1481. {
  1482. if (unlikely(!metasync_worker.loop))
  1483. return;
  1484. struct metadata_cmd cmd;
  1485. memset(&cmd, 0, sizeof(cmd));
  1486. struct metadata_wc *wc = &metasync_worker;
  1487. struct completion *compl = mallocz(sizeof(*compl));
  1488. completion_init(compl);
  1489. __atomic_store_n(&wc->scan_complete, compl, __ATOMIC_RELAXED);
  1490. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Sending a scan host command");
  1491. uint32_t max_wait_iterations = 2000;
  1492. while (unlikely(metadata_flag_check(&metasync_worker, METADATA_FLAG_PROCESSING)) && max_wait_iterations--) {
  1493. if (max_wait_iterations == 1999)
  1494. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Current worker is running; waiting to finish");
  1495. sleep_usec(1000);
  1496. }
  1497. cmd.opcode = METADATA_SCAN_HOSTS;
  1498. metadata_enq_cmd(&metasync_worker, &cmd);
  1499. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Waiting for host scan completion");
  1500. completion_wait_for(wc->scan_complete);
  1501. nd_log(NDLS_DAEMON, NDLP_DEBUG, "METADATA: Host scan complete; can continue with shutdown");
  1502. }
  1503. // -------------------------------------------------------------
  1504. // Init function called on agent startup
  1505. void metadata_sync_init(void)
  1506. {
  1507. struct metadata_wc *wc = &metasync_worker;
  1508. memset(wc, 0, sizeof(*wc));
  1509. completion_init(&wc->start_stop_complete);
  1510. fatal_assert(0 == uv_thread_create(&(wc->thread), metadata_event_loop, wc));
  1511. completion_wait_for(&wc->start_stop_complete);
  1512. completion_destroy(&wc->start_stop_complete);
  1513. nd_log(NDLS_DAEMON, NDLP_DEBUG, "SQLite metadata sync initialization complete");
  1514. }
  1515. // Helpers
  1516. static inline void queue_metadata_cmd(enum metadata_opcode opcode, const void *param0, const void *param1)
  1517. {
  1518. struct metadata_cmd cmd;
  1519. cmd.opcode = opcode;
  1520. cmd.param[0] = param0;
  1521. cmd.param[1] = param1;
  1522. cmd.completion = NULL;
  1523. metadata_enq_cmd(&metasync_worker, &cmd);
  1524. }
  1525. // Public
  1526. void metaqueue_delete_dimension_uuid(uuid_t *uuid)
  1527. {
  1528. if (unlikely(!metasync_worker.loop))
  1529. return;
  1530. uuid_t *use_uuid = mallocz(sizeof(*uuid));
  1531. uuid_copy(*use_uuid, *uuid);
  1532. queue_metadata_cmd(METADATA_DEL_DIMENSION, use_uuid, NULL);
  1533. }
  1534. void metaqueue_store_claim_id(uuid_t *host_uuid, uuid_t *claim_uuid)
  1535. {
  1536. if (unlikely(!host_uuid))
  1537. return;
  1538. uuid_t *local_host_uuid = mallocz(sizeof(*host_uuid));
  1539. uuid_t *local_claim_uuid = NULL;
  1540. uuid_copy(*local_host_uuid, *host_uuid);
  1541. if (likely(claim_uuid)) {
  1542. local_claim_uuid = mallocz(sizeof(*claim_uuid));
  1543. uuid_copy(*local_claim_uuid, *claim_uuid);
  1544. }
  1545. queue_metadata_cmd(METADATA_STORE_CLAIM_ID, local_host_uuid, local_claim_uuid);
  1546. }
  1547. void metaqueue_host_update_info(RRDHOST *host)
  1548. {
  1549. if (unlikely(!metasync_worker.loop))
  1550. return;
  1551. queue_metadata_cmd(METADATA_ADD_HOST_INFO, host, NULL);
  1552. }
  1553. void metaqueue_ml_load_models(RRDDIM *rd)
  1554. {
  1555. rrddim_flag_set(rd, RRDDIM_FLAG_ML_MODEL_LOAD);
  1556. }
  1557. void metadata_queue_load_host_context(RRDHOST *host)
  1558. {
  1559. if (unlikely(!metasync_worker.loop))
  1560. return;
  1561. queue_metadata_cmd(METADATA_LOAD_HOST_CONTEXT, host, NULL);
  1562. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Queued command to load host contexts");
  1563. }
  1564. void metadata_delete_host_chart_labels(char *machine_guid)
  1565. {
  1566. if (unlikely(!metasync_worker.loop)) {
  1567. freez(machine_guid);
  1568. return;
  1569. }
  1570. // Node machine guid is already strdup-ed
  1571. queue_metadata_cmd(METADATA_DELETE_HOST_CHART_LABELS, machine_guid, NULL);
  1572. nd_log(NDLS_DAEMON, NDLP_DEBUG, "Queued command delete chart labels for host %s", machine_guid);
  1573. }
  1574. //
  1575. // unitests
  1576. //
  1577. static void *unittest_queue_metadata(void *arg) {
  1578. struct thread_unittest *tu = arg;
  1579. struct metadata_cmd cmd;
  1580. cmd.opcode = METADATA_UNITTEST;
  1581. cmd.param[0] = tu;
  1582. cmd.param[1] = NULL;
  1583. cmd.completion = NULL;
  1584. metadata_enq_cmd(&metasync_worker, &cmd);
  1585. do {
  1586. __atomic_fetch_add(&tu->added, 1, __ATOMIC_SEQ_CST);
  1587. metadata_enq_cmd(&metasync_worker, &cmd);
  1588. sleep_usec(10000);
  1589. } while (!__atomic_load_n(&tu->join, __ATOMIC_RELAXED));
  1590. return arg;
  1591. }
  1592. static void *metadata_unittest_threads(void)
  1593. {
  1594. unsigned done;
  1595. struct thread_unittest tu = {
  1596. .join = 0,
  1597. .added = 0,
  1598. .processed = 0,
  1599. .done = &done,
  1600. };
  1601. // Queue messages / Time it
  1602. time_t seconds_to_run = 5;
  1603. int threads_to_create = 4;
  1604. fprintf(
  1605. stderr,
  1606. "\nChecking metadata queue using %d threads for %lld seconds...\n",
  1607. threads_to_create,
  1608. (long long)seconds_to_run);
  1609. netdata_thread_t threads[threads_to_create];
  1610. tu.join = 0;
  1611. for (int i = 0; i < threads_to_create; i++) {
  1612. char buf[100 + 1];
  1613. snprintf(buf, sizeof(buf) - 1, "META[%d]", i);
  1614. netdata_thread_create(
  1615. &threads[i],
  1616. buf,
  1617. NETDATA_THREAD_OPTION_DONT_LOG | NETDATA_THREAD_OPTION_JOINABLE,
  1618. unittest_queue_metadata,
  1619. &tu);
  1620. }
  1621. (void) uv_async_send(&metasync_worker.async);
  1622. sleep_usec(seconds_to_run * USEC_PER_SEC);
  1623. __atomic_store_n(&tu.join, 1, __ATOMIC_RELAXED);
  1624. for (int i = 0; i < threads_to_create; i++) {
  1625. void *retval;
  1626. netdata_thread_join(threads[i], &retval);
  1627. }
  1628. sleep_usec(5 * USEC_PER_SEC);
  1629. fprintf(stderr, "Added %u elements, processed %u\n", tu.added, tu.processed);
  1630. return 0;
  1631. }
  1632. int metadata_unittest(void)
  1633. {
  1634. metadata_sync_init();
  1635. // Queue items for a specific period of time
  1636. metadata_unittest_threads();
  1637. metadata_sync_shutdown();
  1638. return 0;
  1639. }