sqlite_functions.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "sqlite_functions.h"
  3. #include "sqlite_db_migration.h"
  4. #define DB_METADATA_VERSION 11
  5. const char *database_config[] = {
  6. "CREATE TABLE IF NOT EXISTS host(host_id BLOB PRIMARY KEY, hostname TEXT NOT NULL, "
  7. "registry_hostname TEXT NOT NULL default 'unknown', update_every INT NOT NULL default 1, "
  8. "os TEXT NOT NULL default 'unknown', timezone TEXT NOT NULL default 'unknown', tags TEXT NOT NULL default '',"
  9. "hops INT NOT NULL DEFAULT 0,"
  10. "memory_mode INT DEFAULT 0, abbrev_timezone TEXT DEFAULT '', utc_offset INT NOT NULL DEFAULT 0,"
  11. "program_name TEXT NOT NULL DEFAULT 'unknown', program_version TEXT NOT NULL DEFAULT 'unknown', "
  12. "entries INT NOT NULL DEFAULT 0,"
  13. "health_enabled INT NOT NULL DEFAULT 0);",
  14. "CREATE TABLE IF NOT EXISTS chart(chart_id blob PRIMARY KEY, host_id blob, type text, id text, name text, "
  15. "family text, context text, title text, unit text, plugin text, module text, priority int, update_every int, "
  16. "chart_type int, memory_mode int, history_entries);",
  17. "CREATE TABLE IF NOT EXISTS dimension(dim_id blob PRIMARY KEY, chart_id blob, id text, name text, "
  18. "multiplier int, divisor int , algorithm int, options text);",
  19. "CREATE TABLE IF NOT EXISTS metadata_migration(filename text, file_size, date_created int);",
  20. "CREATE INDEX IF NOT EXISTS ind_d2 on dimension (chart_id);",
  21. "CREATE INDEX IF NOT EXISTS ind_c3 on chart (host_id);",
  22. "CREATE TABLE IF NOT EXISTS chart_label(chart_id blob, source_type int, label_key text, "
  23. "label_value text, date_created int, PRIMARY KEY (chart_id, label_key));",
  24. "CREATE TABLE IF NOT EXISTS node_instance (host_id blob PRIMARY KEY, claim_id, node_id, date_created);",
  25. "CREATE TABLE IF NOT EXISTS alert_hash(hash_id blob PRIMARY KEY, date_updated int, alarm text, template text, "
  26. "on_key text, class text, component text, type text, os text, hosts text, lookup text, "
  27. "every text, units text, calc text, families text, plugin text, module text, charts text, green text, "
  28. "red text, warn text, crit text, exec text, to_key text, info text, delay text, options text, "
  29. "repeat text, host_labels text, p_db_lookup_dimensions text, p_db_lookup_method text, p_db_lookup_options int, "
  30. "p_db_lookup_after int, p_db_lookup_before int, p_update_every int, source text, chart_labels text);",
  31. "CREATE TABLE IF NOT EXISTS host_info(host_id blob, system_key text NOT NULL, system_value text NOT NULL, "
  32. "date_created INT, PRIMARY KEY(host_id, system_key));",
  33. "CREATE TABLE IF NOT EXISTS host_label(host_id blob, source_type int, label_key text NOT NULL, "
  34. "label_value text NOT NULL, date_created INT, PRIMARY KEY (host_id, label_key));",
  35. "CREATE TRIGGER IF NOT EXISTS ins_host AFTER INSERT ON host BEGIN INSERT INTO node_instance (host_id, date_created)"
  36. " SELECT new.host_id, unixepoch() WHERE new.host_id NOT IN (SELECT host_id FROM node_instance); END;",
  37. "CREATE TABLE IF NOT EXISTS health_log (health_log_id INTEGER PRIMARY KEY, host_id blob, alarm_id int, "
  38. "config_hash_id blob, name text, chart text, family text, recipient text, units text, exec text, "
  39. "chart_context text, last_transition_id blob, chart_name text, UNIQUE (host_id, alarm_id)) ;",
  40. "CREATE INDEX IF NOT EXISTS health_log_ind_1 ON health_log (host_id);",
  41. "CREATE TABLE IF NOT EXISTS health_log_detail (health_log_id int, unique_id int, alarm_id int, alarm_event_id int, "
  42. "updated_by_id int, updates_id int, when_key int, duration int, non_clear_duration int, "
  43. "flags int, exec_run_timestamp int, delay_up_to_timestamp int, "
  44. "info text, exec_code int, new_status real, old_status real, delay int, "
  45. "new_value double, old_value double, last_repeat int, transition_id blob, global_id int);",
  46. "CREATE INDEX IF NOT EXISTS health_log_d_ind_1 ON health_log_detail (unique_id);",
  47. "CREATE INDEX IF NOT EXISTS health_log_d_ind_2 ON health_log_detail (global_id);",
  48. "CREATE INDEX IF NOT EXISTS health_log_d_ind_3 ON health_log_detail (transition_id);",
  49. "CREATE INDEX IF NOT EXISTS health_log_d_ind_4 ON health_log_detail (health_log_id);",
  50. NULL
  51. };
  52. const char *database_cleanup[] = {
  53. "DELETE FROM chart WHERE chart_id NOT IN (SELECT chart_id FROM dimension);",
  54. "DELETE FROM host WHERE host_id NOT IN (SELECT host_id FROM chart);",
  55. "DELETE FROM node_instance WHERE host_id NOT IN (SELECT host_id FROM host);",
  56. "DELETE FROM host_info WHERE host_id NOT IN (SELECT host_id FROM host);",
  57. "DELETE FROM host_label WHERE host_id NOT IN (SELECT host_id FROM host);",
  58. "DROP TRIGGER IF EXISTS tr_dim_del;",
  59. "DROP INDEX IF EXISTS ind_d1;",
  60. "DROP INDEX IF EXISTS ind_c1;",
  61. "DROP INDEX IF EXISTS ind_c2;",
  62. "DROP INDEX IF EXISTS alert_hash_index;",
  63. NULL
  64. };
  65. sqlite3 *db_meta = NULL;
  66. #define MAX_PREPARED_STATEMENTS (32)
  67. pthread_key_t key_pool[MAX_PREPARED_STATEMENTS];
  68. SQLITE_API int sqlite3_exec_monitored(
  69. sqlite3 *db, /* An open database */
  70. const char *sql, /* SQL to be evaluated */
  71. int (*callback)(void*,int,char**,char**), /* Callback function */
  72. void *data, /* 1st argument to callback */
  73. char **errmsg /* Error msg written here */
  74. ) {
  75. int rc = sqlite3_exec(db, sql, callback, data, errmsg);
  76. global_statistics_sqlite3_query_completed(rc == SQLITE_OK, rc == SQLITE_BUSY, rc == SQLITE_LOCKED);
  77. return rc;
  78. }
  79. SQLITE_API int sqlite3_step_monitored(sqlite3_stmt *stmt) {
  80. int rc;
  81. int cnt = 0;
  82. while (cnt++ < SQL_MAX_RETRY) {
  83. rc = sqlite3_step(stmt);
  84. switch (rc) {
  85. case SQLITE_DONE:
  86. global_statistics_sqlite3_query_completed(1, 0, 0);
  87. break;
  88. case SQLITE_ROW:
  89. global_statistics_sqlite3_row_completed();
  90. break;
  91. case SQLITE_BUSY:
  92. case SQLITE_LOCKED:
  93. global_statistics_sqlite3_query_completed(rc == SQLITE_DONE, rc == SQLITE_BUSY, rc == SQLITE_LOCKED);
  94. usleep(SQLITE_INSERT_DELAY * USEC_PER_MS);
  95. continue;
  96. default:
  97. break;
  98. }
  99. break;
  100. }
  101. return rc;
  102. }
  103. int execute_insert(sqlite3_stmt *res)
  104. {
  105. int rc;
  106. int cnt = 0;
  107. while ((rc = sqlite3_step_monitored(res)) != SQLITE_DONE && ++cnt < SQL_MAX_RETRY && likely(!netdata_exit)) {
  108. if (likely(rc == SQLITE_BUSY || rc == SQLITE_LOCKED)) {
  109. usleep(SQLITE_INSERT_DELAY * USEC_PER_MS);
  110. error_report("Failed to insert/update, rc = %d -- attempt %d", rc, cnt);
  111. }
  112. else {
  113. error_report("SQLite error %d", rc);
  114. break;
  115. }
  116. }
  117. return rc;
  118. }
  119. #define MAX_OPEN_STATEMENTS (512)
  120. static void add_stmt_to_list(sqlite3_stmt *res)
  121. {
  122. static int idx = 0;
  123. static sqlite3_stmt *statements[MAX_OPEN_STATEMENTS];
  124. if (unlikely(!res)) {
  125. if (idx)
  126. netdata_log_info("Finilizing %d statements", idx);
  127. else
  128. netdata_log_info("No statements pending to finalize");
  129. while (idx > 0) {
  130. int rc;
  131. rc = sqlite3_finalize(statements[--idx]);
  132. if (unlikely(rc != SQLITE_OK))
  133. error_report("Failed to finalize statement during shutdown, rc = %d", rc);
  134. }
  135. return;
  136. }
  137. if (unlikely(idx == MAX_OPEN_STATEMENTS))
  138. return;
  139. }
  140. static void release_statement(void *statement)
  141. {
  142. int rc;
  143. #ifdef NETDATA_DEV_MODE
  144. netdata_log_info("Thread %d: Cleaning prepared statement on %p", gettid(), statement);
  145. #endif
  146. if (unlikely(rc = sqlite3_finalize((sqlite3_stmt *) statement) != SQLITE_OK))
  147. error_report("Failed to finalize statement, rc = %d", rc);
  148. }
  149. void initialize_thread_key_pool(void)
  150. {
  151. for (int i = 0; i < MAX_PREPARED_STATEMENTS; i++)
  152. (void)pthread_key_create(&key_pool[i], release_statement);
  153. }
  154. int prepare_statement(sqlite3 *database, const char *query, sqlite3_stmt **statement)
  155. {
  156. static __thread uint32_t keys_used = 0;
  157. pthread_key_t *key = NULL;
  158. int ret = 1;
  159. if (likely(keys_used < MAX_PREPARED_STATEMENTS))
  160. key = &key_pool[keys_used++];
  161. int rc = sqlite3_prepare_v2(database, query, -1, statement, 0);
  162. if (likely(rc == SQLITE_OK)) {
  163. if (likely(key)) {
  164. ret = pthread_setspecific(*key, *statement);
  165. #ifdef NETDATA_DEV_MODE
  166. netdata_log_info("Thread %d: Using key %u on statement %p", gettid(), keys_used, *statement);
  167. #endif
  168. }
  169. if (ret)
  170. add_stmt_to_list(*statement);
  171. }
  172. return rc;
  173. }
  174. static int check_table_integrity_cb(void *data, int argc, char **argv, char **column)
  175. {
  176. int *status = data;
  177. UNUSED(argc);
  178. UNUSED(column);
  179. netdata_log_info("---> %s", argv[0]);
  180. *status = (strcmp(argv[0], "ok") != 0);
  181. return 0;
  182. }
  183. static int check_table_integrity(char *table)
  184. {
  185. int status = 0;
  186. char *err_msg = NULL;
  187. char wstr[255];
  188. if (table) {
  189. netdata_log_info("Checking table %s", table);
  190. snprintfz(wstr, 254, "PRAGMA integrity_check(%s);", table);
  191. }
  192. else {
  193. netdata_log_info("Checking entire database");
  194. strcpy(wstr,"PRAGMA integrity_check;");
  195. }
  196. int rc = sqlite3_exec_monitored(db_meta, wstr, check_table_integrity_cb, (void *) &status, &err_msg);
  197. if (rc != SQLITE_OK) {
  198. error_report("SQLite error during database integrity check for %s, rc = %d (%s)",
  199. table ? table : "the entire database", rc, err_msg);
  200. sqlite3_free(err_msg);
  201. }
  202. return status;
  203. }
  204. const char *rebuild_chart_commands[] = {
  205. "BEGIN TRANSACTION; ",
  206. "DROP INDEX IF EXISTS ind_c1;" ,
  207. "DROP TABLE IF EXISTS chart_backup; " ,
  208. "CREATE TABLE chart_backup AS SELECT * FROM chart; " ,
  209. "DROP TABLE chart; ",
  210. "CREATE TABLE IF NOT EXISTS chart(chart_id blob PRIMARY KEY, host_id blob, type text, id text, "
  211. "name text, family text, context text, title text, unit text, plugin text, "
  212. "module text, priority int, update_every int, chart_type int, memory_mode int, history_entries); ",
  213. "INSERT INTO chart SELECT DISTINCT * FROM chart_backup; ",
  214. "DROP TABLE chart_backup; " ,
  215. "CREATE INDEX IF NOT EXISTS ind_c1 on chart (host_id, id, type, name);",
  216. "COMMIT TRANSACTION;",
  217. NULL
  218. };
  219. static void rebuild_chart()
  220. {
  221. int rc;
  222. char *err_msg = NULL;
  223. netdata_log_info("Rebuilding chart table");
  224. for (int i = 0; rebuild_chart_commands[i]; i++) {
  225. netdata_log_info("Executing %s", rebuild_chart_commands[i]);
  226. rc = sqlite3_exec_monitored(db_meta, rebuild_chart_commands[i], 0, 0, &err_msg);
  227. if (rc != SQLITE_OK) {
  228. error_report("SQLite error during database setup, rc = %d (%s)", rc, err_msg);
  229. error_report("SQLite failed statement %s", rebuild_chart_commands[i]);
  230. sqlite3_free(err_msg);
  231. }
  232. }
  233. }
  234. const char *rebuild_dimension_commands[] = {
  235. "BEGIN TRANSACTION; ",
  236. "DROP INDEX IF EXISTS ind_d1;" ,
  237. "DROP TABLE IF EXISTS dimension_backup; " ,
  238. "CREATE TABLE dimension_backup AS SELECT * FROM dimension; " ,
  239. "DROP TABLE dimension; " ,
  240. "CREATE TABLE IF NOT EXISTS dimension(dim_id blob PRIMARY KEY, chart_id blob, id text, name text, "
  241. "multiplier int, divisor int , algorithm int, options text);" ,
  242. "INSERT INTO dimension SELECT distinct * FROM dimension_backup; " ,
  243. "DROP TABLE dimension_backup; " ,
  244. "CREATE INDEX IF NOT EXISTS ind_d1 on dimension (chart_id, id, name);",
  245. "COMMIT TRANSACTION;",
  246. NULL
  247. };
  248. void rebuild_dimension()
  249. {
  250. int rc;
  251. char *err_msg = NULL;
  252. netdata_log_info("Rebuilding dimension table");
  253. for (int i = 0; rebuild_dimension_commands[i]; i++) {
  254. netdata_log_info("Executing %s", rebuild_dimension_commands[i]);
  255. rc = sqlite3_exec_monitored(db_meta, rebuild_dimension_commands[i], 0, 0, &err_msg);
  256. if (rc != SQLITE_OK) {
  257. error_report("SQLite error during database setup, rc = %d (%s)", rc, err_msg);
  258. error_report("SQLite failed statement %s", rebuild_dimension_commands[i]);
  259. sqlite3_free(err_msg);
  260. }
  261. }
  262. }
  263. static int attempt_database_fix()
  264. {
  265. netdata_log_info("Closing database and attempting to fix it");
  266. int rc = sqlite3_close(db_meta);
  267. if (rc != SQLITE_OK)
  268. error_report("Failed to close database, rc = %d", rc);
  269. netdata_log_info("Attempting to fix database");
  270. db_meta = NULL;
  271. return sql_init_database(DB_CHECK_FIX_DB | DB_CHECK_CONT, 0);
  272. }
  273. int init_database_batch(sqlite3 *database, int rebuild, int init_type, const char *batch[])
  274. {
  275. int rc;
  276. char *err_msg = NULL;
  277. for (int i = 0; batch[i]; i++) {
  278. netdata_log_debug(D_METADATALOG, "Executing %s", batch[i]);
  279. rc = sqlite3_exec_monitored(database, batch[i], 0, 0, &err_msg);
  280. if (rc != SQLITE_OK) {
  281. error_report("SQLite error during database %s, rc = %d (%s)", init_type ? "cleanup" : "setup", rc, err_msg);
  282. error_report("SQLite failed statement %s", batch[i]);
  283. sqlite3_free(err_msg);
  284. if (SQLITE_CORRUPT == rc) {
  285. if (!rebuild)
  286. return attempt_database_fix();
  287. rc = check_table_integrity(NULL);
  288. if (rc)
  289. error_report("Databse integrity errors reported");
  290. }
  291. return 1;
  292. }
  293. }
  294. return 0;
  295. }
  296. static void sqlite_uuid_parse(sqlite3_context *context, int argc, sqlite3_value **argv)
  297. {
  298. uuid_t uuid;
  299. if ( argc != 1 ){
  300. sqlite3_result_null(context);
  301. return ;
  302. }
  303. int rc = uuid_parse((const char *) sqlite3_value_text(argv[0]), uuid);
  304. if (rc == -1) {
  305. sqlite3_result_null(context);
  306. return ;
  307. }
  308. sqlite3_result_blob(context, &uuid, sizeof(uuid_t), SQLITE_TRANSIENT);
  309. }
  310. void sqlite_now_usec(sqlite3_context *context, int argc, sqlite3_value **argv)
  311. {
  312. if (argc != 1 ){
  313. sqlite3_result_null(context);
  314. return ;
  315. }
  316. if (sqlite3_value_int(argv[0]) != 0) {
  317. struct timespec req = {.tv_sec = 0, .tv_nsec = 1};
  318. nanosleep(&req, NULL);
  319. }
  320. sqlite3_result_int64(context, (sqlite_int64) now_realtime_usec());
  321. }
  322. void sqlite_uuid_random(sqlite3_context *context, int argc, sqlite3_value **argv)
  323. {
  324. (void)argc;
  325. (void)argv;
  326. uuid_t uuid;
  327. uuid_generate_random(uuid);
  328. sqlite3_result_blob(context, &uuid, sizeof(uuid_t), SQLITE_TRANSIENT);
  329. }
  330. /*
  331. * Initialize the SQLite database
  332. * Return 0 on success
  333. */
  334. int sql_init_database(db_check_action_type_t rebuild, int memory)
  335. {
  336. char *err_msg = NULL;
  337. char sqlite_database[FILENAME_MAX + 1];
  338. int rc;
  339. if (likely(!memory))
  340. snprintfz(sqlite_database, FILENAME_MAX, "%s/netdata-meta.db", netdata_configured_cache_dir);
  341. else
  342. strcpy(sqlite_database, ":memory:");
  343. rc = sqlite3_open(sqlite_database, &db_meta);
  344. if (rc != SQLITE_OK) {
  345. error_report("Failed to initialize database at %s, due to \"%s\"", sqlite_database, sqlite3_errstr(rc));
  346. sqlite3_close(db_meta);
  347. db_meta = NULL;
  348. return 1;
  349. }
  350. if (rebuild & (DB_CHECK_INTEGRITY | DB_CHECK_FIX_DB)) {
  351. int errors_detected = 0;
  352. if (!(rebuild & DB_CHECK_CONT))
  353. netdata_log_info("Running database check on %s", sqlite_database);
  354. if (check_table_integrity("chart")) {
  355. errors_detected++;
  356. if (rebuild & DB_CHECK_FIX_DB)
  357. rebuild_chart();
  358. else
  359. error_report("Errors reported -- run with -W sqlite-fix");
  360. }
  361. if (check_table_integrity("dimension")) {
  362. errors_detected++;
  363. if (rebuild & DB_CHECK_FIX_DB)
  364. rebuild_dimension();
  365. else
  366. error_report("Errors reported -- run with -W sqlite-fix");
  367. }
  368. if (!errors_detected) {
  369. if (check_table_integrity(NULL))
  370. error_report("Errors reported");
  371. }
  372. }
  373. if (rebuild & DB_CHECK_RECLAIM_SPACE) {
  374. if (!(rebuild & DB_CHECK_CONT))
  375. netdata_log_info("Reclaiming space of %s", sqlite_database);
  376. rc = sqlite3_exec_monitored(db_meta, "VACUUM;", 0, 0, &err_msg);
  377. if (rc != SQLITE_OK) {
  378. error_report("Failed to execute VACUUM rc = %d (%s)", rc, err_msg);
  379. sqlite3_free(err_msg);
  380. }
  381. }
  382. if (rebuild && !(rebuild & DB_CHECK_CONT))
  383. return 1;
  384. netdata_log_info("SQLite database %s initialization", sqlite_database);
  385. char buf[1024 + 1] = "";
  386. const char *list[2] = { buf, NULL };
  387. rc = sqlite3_create_function(db_meta, "u2h", 1, SQLITE_ANY | SQLITE_DETERMINISTIC, 0, sqlite_uuid_parse, 0, 0);
  388. if (unlikely(rc != SQLITE_OK))
  389. error_report("Failed to register internal u2h function");
  390. rc = sqlite3_create_function(db_meta, "now_usec", 1, SQLITE_ANY, 0, sqlite_now_usec, 0, 0);
  391. if (unlikely(rc != SQLITE_OK))
  392. error_report("Failed to register internal now_usec function");
  393. rc = sqlite3_create_function(db_meta, "uuid_random", 0, SQLITE_ANY, 0, sqlite_uuid_random, 0, 0);
  394. if (unlikely(rc != SQLITE_OK))
  395. error_report("Failed to register internal uuid_random function");
  396. int target_version = DB_METADATA_VERSION;
  397. if (likely(!memory))
  398. target_version = perform_database_migration(db_meta, DB_METADATA_VERSION);
  399. // https://www.sqlite.org/pragma.html#pragma_auto_vacuum
  400. // PRAGMA schema.auto_vacuum = 0 | NONE | 1 | FULL | 2 | INCREMENTAL;
  401. snprintfz(buf, 1024, "PRAGMA auto_vacuum=%s;", config_get(CONFIG_SECTION_SQLITE, "auto vacuum", "INCREMENTAL"));
  402. if(init_database_batch(db_meta, rebuild, 0, list)) return 1;
  403. // https://www.sqlite.org/pragma.html#pragma_synchronous
  404. // PRAGMA schema.synchronous = 0 | OFF | 1 | NORMAL | 2 | FULL | 3 | EXTRA;
  405. snprintfz(buf, 1024, "PRAGMA synchronous=%s;", config_get(CONFIG_SECTION_SQLITE, "synchronous", "NORMAL"));
  406. if(init_database_batch(db_meta, rebuild, 0, list)) return 1;
  407. // https://www.sqlite.org/pragma.html#pragma_journal_mode
  408. // PRAGMA schema.journal_mode = DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF
  409. snprintfz(buf, 1024, "PRAGMA journal_mode=%s;", config_get(CONFIG_SECTION_SQLITE, "journal mode", "WAL"));
  410. if(init_database_batch(db_meta, rebuild, 0, list)) return 1;
  411. // https://www.sqlite.org/pragma.html#pragma_temp_store
  412. // PRAGMA temp_store = 0 | DEFAULT | 1 | FILE | 2 | MEMORY;
  413. snprintfz(buf, 1024, "PRAGMA temp_store=%s;", config_get(CONFIG_SECTION_SQLITE, "temp store", "MEMORY"));
  414. if(init_database_batch(db_meta, rebuild, 0, list)) return 1;
  415. // https://www.sqlite.org/pragma.html#pragma_journal_size_limit
  416. // PRAGMA schema.journal_size_limit = N ;
  417. snprintfz(buf, 1024, "PRAGMA journal_size_limit=%lld;", config_get_number(CONFIG_SECTION_SQLITE, "journal size limit", 16777216));
  418. if(init_database_batch(db_meta, rebuild, 0, list)) return 1;
  419. // https://www.sqlite.org/pragma.html#pragma_cache_size
  420. // PRAGMA schema.cache_size = pages;
  421. // PRAGMA schema.cache_size = -kibibytes;
  422. snprintfz(buf, 1024, "PRAGMA cache_size=%lld;", config_get_number(CONFIG_SECTION_SQLITE, "cache size", -2000));
  423. if(init_database_batch(db_meta, rebuild, 0, list)) return 1;
  424. snprintfz(buf, 1024, "PRAGMA user_version=%d;", target_version);
  425. if(init_database_batch(db_meta, rebuild, 0, list)) return 1;
  426. if (init_database_batch(db_meta, rebuild, 0, &database_config[0]))
  427. return 1;
  428. if (init_database_batch(db_meta, rebuild, 0, &database_cleanup[0]))
  429. return 1;
  430. netdata_log_info("SQLite database initialization completed");
  431. initialize_thread_key_pool();
  432. return 0;
  433. }
  434. /*
  435. * Close the sqlite database
  436. */
  437. void sql_close_database(void)
  438. {
  439. int rc;
  440. if (unlikely(!db_meta))
  441. return;
  442. netdata_log_info("Closing SQLite database");
  443. add_stmt_to_list(NULL);
  444. rc = sqlite3_close_v2(db_meta);
  445. if (unlikely(rc != SQLITE_OK))
  446. error_report("Error %d while closing the SQLite database, %s", rc, sqlite3_errstr(rc));
  447. }
  448. int exec_statement_with_uuid(const char *sql, uuid_t *uuid)
  449. {
  450. int rc, result = 1;
  451. sqlite3_stmt *res = NULL;
  452. rc = sqlite3_prepare_v2(db_meta, sql, -1, &res, 0);
  453. if (unlikely(rc != SQLITE_OK)) {
  454. error_report("Failed to prepare statement %s, rc = %d", sql, rc);
  455. return 1;
  456. }
  457. rc = sqlite3_bind_blob(res, 1, uuid, sizeof(*uuid), SQLITE_STATIC);
  458. if (unlikely(rc != SQLITE_OK)) {
  459. error_report("Failed to bind host parameter to %s, rc = %d", sql, rc);
  460. goto skip;
  461. }
  462. rc = execute_insert(res);
  463. if (likely(rc == SQLITE_DONE))
  464. result = SQLITE_OK;
  465. else
  466. error_report("Failed to execute %s, rc = %d", sql, rc);
  467. skip:
  468. rc = sqlite3_finalize(res);
  469. if (unlikely(rc != SQLITE_OK))
  470. error_report("Failed to finalize statement %s, rc = %d", sql, rc);
  471. return result;
  472. }
  473. // Return 0 OK
  474. // Return 1 Failed
  475. int db_execute(sqlite3 *db, const char *cmd)
  476. {
  477. int rc;
  478. int cnt = 0;
  479. while (cnt < SQL_MAX_RETRY) {
  480. char *err_msg;
  481. rc = sqlite3_exec_monitored(db, cmd, 0, 0, &err_msg);
  482. if (rc != SQLITE_OK) {
  483. error_report("Failed to execute '%s', rc = %d (%s) -- attempt %d", cmd, rc, err_msg, cnt);
  484. sqlite3_free(err_msg);
  485. if (likely(rc == SQLITE_BUSY || rc == SQLITE_LOCKED)) {
  486. usleep(SQLITE_INSERT_DELAY * USEC_PER_MS);
  487. }
  488. else
  489. break;
  490. }
  491. else
  492. break;
  493. ++cnt;
  494. }
  495. return (rc != SQLITE_OK);
  496. }
  497. static inline void set_host_node_id(RRDHOST *host, uuid_t *node_id)
  498. {
  499. if (unlikely(!host))
  500. return;
  501. if (unlikely(!node_id)) {
  502. freez(host->node_id);
  503. __atomic_store_n(&host->node_id, NULL, __ATOMIC_RELAXED);
  504. return;
  505. }
  506. struct aclk_sync_host_config *wc = host->aclk_sync_host_config;
  507. if (unlikely(!host->node_id)) {
  508. uuid_t *t = mallocz(sizeof(*host->node_id));
  509. uuid_copy(*t, *node_id);
  510. __atomic_store_n(&host->node_id, t, __ATOMIC_RELAXED);
  511. }
  512. else {
  513. uuid_copy(*(host->node_id), *node_id);
  514. }
  515. if (unlikely(!wc))
  516. sql_create_aclk_table(host, &host->host_uuid, node_id);
  517. else
  518. uuid_unparse_lower(*node_id, wc->node_id);
  519. }
  520. #define SQL_UPDATE_NODE_ID "update node_instance set node_id = @node_id where host_id = @host_id;"
  521. int update_node_id(uuid_t *host_id, uuid_t *node_id)
  522. {
  523. sqlite3_stmt *res = NULL;
  524. RRDHOST *host = NULL;
  525. int rc = 2;
  526. char host_guid[GUID_LEN + 1];
  527. uuid_unparse_lower(*host_id, host_guid);
  528. rrd_wrlock();
  529. host = rrdhost_find_by_guid(host_guid);
  530. if (likely(host))
  531. set_host_node_id(host, node_id);
  532. rrd_unlock();
  533. if (unlikely(!db_meta)) {
  534. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  535. error_report("Database has not been initialized");
  536. return 1;
  537. }
  538. rc = sqlite3_prepare_v2(db_meta, SQL_UPDATE_NODE_ID, -1, &res, 0);
  539. if (unlikely(rc != SQLITE_OK)) {
  540. error_report("Failed to prepare statement to store node instance information");
  541. return 1;
  542. }
  543. rc = sqlite3_bind_blob(res, 1, node_id, sizeof(*node_id), SQLITE_STATIC);
  544. if (unlikely(rc != SQLITE_OK)) {
  545. error_report("Failed to bind host_id parameter to store node instance information");
  546. goto failed;
  547. }
  548. rc = sqlite3_bind_blob(res, 2, host_id, sizeof(*host_id), SQLITE_STATIC);
  549. if (unlikely(rc != SQLITE_OK)) {
  550. error_report("Failed to bind host_id parameter to store node instance information");
  551. goto failed;
  552. }
  553. rc = execute_insert(res);
  554. if (unlikely(rc != SQLITE_DONE))
  555. error_report("Failed to store node instance information, rc = %d", rc);
  556. rc = sqlite3_changes(db_meta);
  557. failed:
  558. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  559. error_report("Failed to finalize the prepared statement when storing node instance information");
  560. return rc - 1;
  561. }
  562. #define SQL_SELECT_HOST_BY_NODE_ID "select host_id from node_instance where node_id = @node_id;"
  563. int get_host_id(uuid_t *node_id, uuid_t *host_id)
  564. {
  565. static __thread sqlite3_stmt *res = NULL;
  566. int rc;
  567. if (unlikely(!db_meta)) {
  568. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  569. error_report("Database has not been initialized");
  570. return 1;
  571. }
  572. if (unlikely(!res)) {
  573. rc = prepare_statement(db_meta, SQL_SELECT_HOST_BY_NODE_ID, &res);
  574. if (unlikely(rc != SQLITE_OK)) {
  575. error_report("Failed to prepare statement to select node instance information for a node");
  576. return 1;
  577. }
  578. }
  579. rc = sqlite3_bind_blob(res, 1, node_id, sizeof(*node_id), SQLITE_STATIC);
  580. if (unlikely(rc != SQLITE_OK)) {
  581. error_report("Failed to bind host_id parameter to select node instance information");
  582. goto failed;
  583. }
  584. rc = sqlite3_step_monitored(res);
  585. if (likely(rc == SQLITE_ROW && host_id))
  586. uuid_copy(*host_id, *((uuid_t *) sqlite3_column_blob(res, 0)));
  587. failed:
  588. if (unlikely(sqlite3_reset(res) != SQLITE_OK))
  589. error_report("Failed to reset the prepared statement when selecting node instance information");
  590. return (rc == SQLITE_ROW) ? 0 : -1;
  591. }
  592. #define SQL_SELECT_NODE_ID "SELECT node_id FROM node_instance WHERE host_id = @host_id AND node_id IS NOT NULL;"
  593. int get_node_id(uuid_t *host_id, uuid_t *node_id)
  594. {
  595. sqlite3_stmt *res = NULL;
  596. int rc;
  597. if (unlikely(!db_meta)) {
  598. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  599. error_report("Database has not been initialized");
  600. return 1;
  601. }
  602. rc = sqlite3_prepare_v2(db_meta, SQL_SELECT_NODE_ID, -1, &res, 0);
  603. if (unlikely(rc != SQLITE_OK)) {
  604. error_report("Failed to prepare statement to select node instance information for a host");
  605. return 1;
  606. }
  607. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  608. if (unlikely(rc != SQLITE_OK)) {
  609. error_report("Failed to bind host_id parameter to select node instance information");
  610. goto failed;
  611. }
  612. rc = sqlite3_step_monitored(res);
  613. if (likely(rc == SQLITE_ROW && node_id))
  614. uuid_copy(*node_id, *((uuid_t *) sqlite3_column_blob(res, 0)));
  615. failed:
  616. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  617. error_report("Failed to finalize the prepared statement when selecting node instance information");
  618. return (rc == SQLITE_ROW) ? 0 : -1;
  619. }
  620. #define SQL_INVALIDATE_NODE_INSTANCES "UPDATE node_instance SET node_id = NULL WHERE EXISTS " \
  621. "(SELECT host_id FROM node_instance WHERE host_id = @host_id AND (@claim_id IS NULL OR claim_id <> @claim_id));"
  622. void invalidate_node_instances(uuid_t *host_id, uuid_t *claim_id)
  623. {
  624. sqlite3_stmt *res = NULL;
  625. int rc;
  626. if (unlikely(!db_meta)) {
  627. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  628. error_report("Database has not been initialized");
  629. return;
  630. }
  631. rc = sqlite3_prepare_v2(db_meta, SQL_INVALIDATE_NODE_INSTANCES, -1, &res, 0);
  632. if (unlikely(rc != SQLITE_OK)) {
  633. error_report("Failed to prepare statement to invalidate node instance ids");
  634. return;
  635. }
  636. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  637. if (unlikely(rc != SQLITE_OK)) {
  638. error_report("Failed to bind host_id parameter to invalidate node instance information");
  639. goto failed;
  640. }
  641. if (claim_id)
  642. rc = sqlite3_bind_blob(res, 2, claim_id, sizeof(*claim_id), SQLITE_STATIC);
  643. else
  644. rc = sqlite3_bind_null(res, 2);
  645. if (unlikely(rc != SQLITE_OK)) {
  646. error_report("Failed to bind claim_id parameter to invalidate node instance information");
  647. goto failed;
  648. }
  649. rc = execute_insert(res);
  650. if (unlikely(rc != SQLITE_DONE))
  651. error_report("Failed to invalidate node instance information, rc = %d", rc);
  652. failed:
  653. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  654. error_report("Failed to finalize the prepared statement when invalidating node instance information");
  655. }
  656. #define SQL_GET_NODE_INSTANCE_LIST "SELECT ni.node_id, ni.host_id, h.hostname " \
  657. "FROM node_instance ni, host h WHERE ni.host_id = h.host_id AND h.hops >=0;"
  658. struct node_instance_list *get_node_list(void)
  659. {
  660. struct node_instance_list *node_list = NULL;
  661. sqlite3_stmt *res = NULL;
  662. int rc;
  663. if (unlikely(!db_meta)) {
  664. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  665. error_report("Database has not been initialized");
  666. return NULL;
  667. }
  668. rc = sqlite3_prepare_v2(db_meta, SQL_GET_NODE_INSTANCE_LIST, -1, &res, 0);
  669. if (unlikely(rc != SQLITE_OK)) {
  670. error_report("Failed to prepare statement to get node instance information");
  671. return NULL;
  672. };
  673. int row = 0;
  674. char host_guid[37];
  675. while (sqlite3_step_monitored(res) == SQLITE_ROW)
  676. row++;
  677. if (sqlite3_reset(res) != SQLITE_OK) {
  678. error_report("Failed to reset the prepared statement while fetching node instance information");
  679. goto failed;
  680. }
  681. node_list = callocz(row + 1, sizeof(*node_list));
  682. int max_rows = row;
  683. row = 0;
  684. // TODO: Check to remove lock
  685. rrd_rdlock();
  686. while (sqlite3_step_monitored(res) == SQLITE_ROW) {
  687. if (sqlite3_column_bytes(res, 0) == sizeof(uuid_t))
  688. uuid_copy(node_list[row].node_id, *((uuid_t *)sqlite3_column_blob(res, 0)));
  689. if (sqlite3_column_bytes(res, 1) == sizeof(uuid_t)) {
  690. uuid_t *host_id = (uuid_t *)sqlite3_column_blob(res, 1);
  691. uuid_unparse_lower(*host_id, host_guid);
  692. RRDHOST *host = rrdhost_find_by_guid(host_guid);
  693. if (rrdhost_flag_check(host, RRDHOST_FLAG_PENDING_CONTEXT_LOAD)) {
  694. netdata_log_info("ACLK: 'host:%s' skipping get node list because context is initializing", rrdhost_hostname(host));
  695. continue;
  696. }
  697. uuid_copy(node_list[row].host_id, *host_id);
  698. node_list[row].queryable = 1;
  699. node_list[row].live = (host && (host == localhost || host->receiver
  700. || !(rrdhost_flag_check(host, RRDHOST_FLAG_ORPHAN)))) ? 1 : 0;
  701. node_list[row].hops = (host && host->system_info) ? host->system_info->hops :
  702. uuid_memcmp(host_id, &localhost->host_uuid) ? 1 : 0;
  703. node_list[row].hostname =
  704. sqlite3_column_bytes(res, 2) ? strdupz((char *)sqlite3_column_text(res, 2)) : NULL;
  705. }
  706. row++;
  707. if (row == max_rows)
  708. break;
  709. }
  710. rrd_unlock();
  711. failed:
  712. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  713. error_report("Failed to finalize the prepared statement when fetching node instance information");
  714. return node_list;
  715. };
  716. #define SQL_GET_HOST_NODE_ID "select node_id from node_instance where host_id = @host_id;"
  717. void sql_load_node_id(RRDHOST *host)
  718. {
  719. static __thread sqlite3_stmt *res = NULL;
  720. int rc;
  721. if (unlikely(!db_meta)) {
  722. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  723. error_report("Database has not been initialized");
  724. return;
  725. }
  726. if (unlikely(!res)) {
  727. rc = prepare_statement(db_meta, SQL_GET_HOST_NODE_ID, &res);
  728. if (unlikely(rc != SQLITE_OK)) {
  729. error_report("Failed to prepare statement to fetch node id");
  730. return;
  731. };
  732. }
  733. rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
  734. if (unlikely(rc != SQLITE_OK)) {
  735. error_report("Failed to bind host_id parameter to load node instance information");
  736. goto failed;
  737. }
  738. rc = sqlite3_step_monitored(res);
  739. if (likely(rc == SQLITE_ROW)) {
  740. if (likely(sqlite3_column_bytes(res, 0) == sizeof(uuid_t)))
  741. set_host_node_id(host, (uuid_t *)sqlite3_column_blob(res, 0));
  742. else
  743. set_host_node_id(host, NULL);
  744. }
  745. failed:
  746. if (unlikely(sqlite3_reset(res) != SQLITE_OK))
  747. error_report("Failed to reset the prepared statement when loading node instance information");
  748. };
  749. #define SELECT_HOST_INFO "SELECT system_key, system_value FROM host_info WHERE host_id = @host_id;"
  750. void sql_build_host_system_info(uuid_t *host_id, struct rrdhost_system_info *system_info)
  751. {
  752. int rc;
  753. sqlite3_stmt *res = NULL;
  754. rc = sqlite3_prepare_v2(db_meta, SELECT_HOST_INFO, -1, &res, 0);
  755. if (unlikely(rc != SQLITE_OK)) {
  756. error_report("Failed to prepare statement to read host information");
  757. return;
  758. }
  759. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  760. if (unlikely(rc != SQLITE_OK)) {
  761. error_report("Failed to bind host parameter host information");
  762. goto skip;
  763. }
  764. while (sqlite3_step_monitored(res) == SQLITE_ROW) {
  765. rrdhost_set_system_info_variable(system_info, (char *) sqlite3_column_text(res, 0),
  766. (char *) sqlite3_column_text(res, 1));
  767. }
  768. skip:
  769. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  770. error_report("Failed to finalize the prepared statement when reading host information");
  771. }
  772. #define SELECT_HOST_LABELS "SELECT label_key, label_value, source_type FROM host_label WHERE host_id = @host_id " \
  773. "AND label_key IS NOT NULL AND label_value IS NOT NULL;"
  774. DICTIONARY *sql_load_host_labels(uuid_t *host_id)
  775. {
  776. int rc;
  777. DICTIONARY *labels = NULL;
  778. sqlite3_stmt *res = NULL;
  779. rc = sqlite3_prepare_v2(db_meta, SELECT_HOST_LABELS, -1, &res, 0);
  780. if (unlikely(rc != SQLITE_OK)) {
  781. error_report("Failed to prepare statement to read host information");
  782. return NULL;
  783. }
  784. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  785. if (unlikely(rc != SQLITE_OK)) {
  786. error_report("Failed to bind host parameter host information");
  787. goto skip;
  788. }
  789. labels = rrdlabels_create();
  790. while (sqlite3_step_monitored(res) == SQLITE_ROW) {
  791. rrdlabels_add(
  792. labels,
  793. (const char *)sqlite3_column_text(res, 0),
  794. (const char *)sqlite3_column_text(res, 1),
  795. sqlite3_column_int(res, 2));
  796. }
  797. skip:
  798. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  799. error_report("Failed to finalize the prepared statement when reading host information");
  800. return labels;
  801. }
  802. // Utils
  803. int bind_text_null(sqlite3_stmt *res, int position, const char *text, bool can_be_null)
  804. {
  805. if (likely(text))
  806. return sqlite3_bind_text(res, position, text, -1, SQLITE_STATIC);
  807. if (!can_be_null)
  808. return 1;
  809. return sqlite3_bind_null(res, position);
  810. }
  811. int sql_metadata_cache_stats(int op)
  812. {
  813. int count, dummy;
  814. if (unlikely(!db_meta))
  815. return 0;
  816. netdata_thread_disable_cancelability();
  817. sqlite3_db_status(db_meta, op, &count, &dummy, 0);
  818. netdata_thread_enable_cancelability();
  819. return count;
  820. }
  821. #define SQL_DROP_TABLE "DROP table %s;"
  822. void sql_drop_table(const char *table)
  823. {
  824. if (!table)
  825. return;
  826. char wstr[255];
  827. snprintfz(wstr, 254, SQL_DROP_TABLE, table);
  828. int rc = sqlite3_exec_monitored(db_meta, wstr, 0, 0, NULL);
  829. if (rc != SQLITE_OK) {
  830. error_report("DES SQLite error during drop table operation for %s, rc = %d", table, rc);
  831. }
  832. }