sqlite_functions.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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 (!host)
  694. continue;
  695. if (rrdhost_flag_check(host, RRDHOST_FLAG_PENDING_CONTEXT_LOAD)) {
  696. netdata_log_info("ACLK: 'host:%s' skipping get node list because context is initializing", rrdhost_hostname(host));
  697. continue;
  698. }
  699. uuid_copy(node_list[row].host_id, *host_id);
  700. node_list[row].queryable = 1;
  701. node_list[row].live = (host && (host == localhost || host->receiver
  702. || !(rrdhost_flag_check(host, RRDHOST_FLAG_ORPHAN)))) ? 1 : 0;
  703. node_list[row].hops = (host && host->system_info) ? host->system_info->hops :
  704. uuid_memcmp(host_id, &localhost->host_uuid) ? 1 : 0;
  705. node_list[row].hostname =
  706. sqlite3_column_bytes(res, 2) ? strdupz((char *)sqlite3_column_text(res, 2)) : NULL;
  707. }
  708. row++;
  709. if (row == max_rows)
  710. break;
  711. }
  712. rrd_unlock();
  713. failed:
  714. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  715. error_report("Failed to finalize the prepared statement when fetching node instance information");
  716. return node_list;
  717. };
  718. #define SQL_GET_HOST_NODE_ID "select node_id from node_instance where host_id = @host_id;"
  719. void sql_load_node_id(RRDHOST *host)
  720. {
  721. static __thread sqlite3_stmt *res = NULL;
  722. int rc;
  723. if (unlikely(!db_meta)) {
  724. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  725. error_report("Database has not been initialized");
  726. return;
  727. }
  728. if (unlikely(!res)) {
  729. rc = prepare_statement(db_meta, SQL_GET_HOST_NODE_ID, &res);
  730. if (unlikely(rc != SQLITE_OK)) {
  731. error_report("Failed to prepare statement to fetch node id");
  732. return;
  733. };
  734. }
  735. rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
  736. if (unlikely(rc != SQLITE_OK)) {
  737. error_report("Failed to bind host_id parameter to load node instance information");
  738. goto failed;
  739. }
  740. rc = sqlite3_step_monitored(res);
  741. if (likely(rc == SQLITE_ROW)) {
  742. if (likely(sqlite3_column_bytes(res, 0) == sizeof(uuid_t)))
  743. set_host_node_id(host, (uuid_t *)sqlite3_column_blob(res, 0));
  744. else
  745. set_host_node_id(host, NULL);
  746. }
  747. failed:
  748. if (unlikely(sqlite3_reset(res) != SQLITE_OK))
  749. error_report("Failed to reset the prepared statement when loading node instance information");
  750. };
  751. #define SELECT_HOST_INFO "SELECT system_key, system_value FROM host_info WHERE host_id = @host_id;"
  752. void sql_build_host_system_info(uuid_t *host_id, struct rrdhost_system_info *system_info)
  753. {
  754. int rc;
  755. sqlite3_stmt *res = NULL;
  756. rc = sqlite3_prepare_v2(db_meta, SELECT_HOST_INFO, -1, &res, 0);
  757. if (unlikely(rc != SQLITE_OK)) {
  758. error_report("Failed to prepare statement to read host information");
  759. return;
  760. }
  761. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  762. if (unlikely(rc != SQLITE_OK)) {
  763. error_report("Failed to bind host parameter host information");
  764. goto skip;
  765. }
  766. while (sqlite3_step_monitored(res) == SQLITE_ROW) {
  767. rrdhost_set_system_info_variable(system_info, (char *) sqlite3_column_text(res, 0),
  768. (char *) sqlite3_column_text(res, 1));
  769. }
  770. skip:
  771. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  772. error_report("Failed to finalize the prepared statement when reading host information");
  773. }
  774. #define SELECT_HOST_LABELS "SELECT label_key, label_value, source_type FROM host_label WHERE host_id = @host_id " \
  775. "AND label_key IS NOT NULL AND label_value IS NOT NULL;"
  776. DICTIONARY *sql_load_host_labels(uuid_t *host_id)
  777. {
  778. int rc;
  779. DICTIONARY *labels = NULL;
  780. sqlite3_stmt *res = NULL;
  781. rc = sqlite3_prepare_v2(db_meta, SELECT_HOST_LABELS, -1, &res, 0);
  782. if (unlikely(rc != SQLITE_OK)) {
  783. error_report("Failed to prepare statement to read host information");
  784. return NULL;
  785. }
  786. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  787. if (unlikely(rc != SQLITE_OK)) {
  788. error_report("Failed to bind host parameter host information");
  789. goto skip;
  790. }
  791. labels = rrdlabels_create();
  792. while (sqlite3_step_monitored(res) == SQLITE_ROW) {
  793. rrdlabels_add(
  794. labels,
  795. (const char *)sqlite3_column_text(res, 0),
  796. (const char *)sqlite3_column_text(res, 1),
  797. sqlite3_column_int(res, 2));
  798. }
  799. skip:
  800. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  801. error_report("Failed to finalize the prepared statement when reading host information");
  802. return labels;
  803. }
  804. // Utils
  805. int bind_text_null(sqlite3_stmt *res, int position, const char *text, bool can_be_null)
  806. {
  807. if (likely(text))
  808. return sqlite3_bind_text(res, position, text, -1, SQLITE_STATIC);
  809. if (!can_be_null)
  810. return 1;
  811. return sqlite3_bind_null(res, position);
  812. }
  813. int sql_metadata_cache_stats(int op)
  814. {
  815. int count, dummy;
  816. if (unlikely(!db_meta))
  817. return 0;
  818. netdata_thread_disable_cancelability();
  819. sqlite3_db_status(db_meta, op, &count, &dummy, 0);
  820. netdata_thread_enable_cancelability();
  821. return count;
  822. }
  823. #define SQL_DROP_TABLE "DROP table %s;"
  824. void sql_drop_table(const char *table)
  825. {
  826. if (!table)
  827. return;
  828. char wstr[255];
  829. snprintfz(wstr, 254, SQL_DROP_TABLE, table);
  830. int rc = sqlite3_exec_monitored(db_meta, wstr, 0, 0, NULL);
  831. if (rc != SQLITE_OK) {
  832. error_report("DES SQLite error during drop table operation for %s, rc = %d", table, rc);
  833. }
  834. }