sqlite_functions.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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 10
  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 INDEX IF NOT EXISTS alert_hash_index ON alert_hash (hash_id);",
  32. "CREATE TABLE IF NOT EXISTS host_info(host_id blob, system_key text NOT NULL, system_value text NOT NULL, "
  33. "date_created INT, PRIMARY KEY(host_id, system_key));",
  34. "CREATE TABLE IF NOT EXISTS host_label(host_id blob, source_type int, label_key text NOT NULL, "
  35. "label_value text NOT NULL, date_created INT, PRIMARY KEY (host_id, label_key));",
  36. "CREATE TRIGGER IF NOT EXISTS ins_host AFTER INSERT ON host BEGIN INSERT INTO node_instance (host_id, date_created)"
  37. " SELECT new.host_id, unixepoch() WHERE new.host_id NOT IN (SELECT host_id FROM node_instance); END;",
  38. "CREATE TABLE IF NOT EXISTS health_log (health_log_id INTEGER PRIMARY KEY, host_id blob, alarm_id int, "
  39. "config_hash_id blob, name text, chart text, family text, recipient text, units text, exec text, "
  40. "chart_context text, last_transition_id blob, UNIQUE (host_id, alarm_id)) ;",
  41. "CREATE INDEX IF NOT EXISTS health_log_ind_1 ON health_log (host_id);",
  42. "CREATE TABLE IF NOT EXISTS health_log_detail (health_log_id int, unique_id int, alarm_id int, alarm_event_id int, "
  43. "updated_by_id int, updates_id int, when_key int, duration int, non_clear_duration int, "
  44. "flags int, exec_run_timestamp int, delay_up_to_timestamp int, "
  45. "info text, exec_code int, new_status real, old_status real, delay int, "
  46. "new_value double, old_value double, last_repeat int, transition_id blob, global_id int);",
  47. "CREATE INDEX IF NOT EXISTS health_log_d_ind_1 ON health_log_detail (unique_id);",
  48. "CREATE INDEX IF NOT EXISTS health_log_d_ind_2 ON health_log_detail (global_id);",
  49. "CREATE INDEX IF NOT EXISTS health_log_d_ind_3 ON health_log_detail (transition_id);",
  50. "CREATE INDEX IF NOT EXISTS health_log_d_ind_4 ON health_log_detail (health_log_id);",
  51. NULL
  52. };
  53. const char *database_cleanup[] = {
  54. "DELETE FROM chart WHERE chart_id NOT IN (SELECT chart_id FROM dimension);",
  55. "DELETE FROM host WHERE host_id NOT IN (SELECT host_id FROM chart);",
  56. "DELETE FROM node_instance WHERE host_id NOT IN (SELECT host_id FROM host);",
  57. "DELETE FROM host_info WHERE host_id NOT IN (SELECT host_id FROM host);",
  58. "DELETE FROM host_label WHERE host_id NOT IN (SELECT host_id FROM host);",
  59. "DROP TRIGGER IF EXISTS tr_dim_del;",
  60. "DROP INDEX IF EXISTS ind_d1;",
  61. "DROP INDEX IF EXISTS ind_c1;",
  62. "DROP INDEX IF EXISTS ind_c2;",
  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. host->node_id = NULL;
  504. return;
  505. }
  506. struct aclk_sync_host_config *wc = host->aclk_sync_host_config;
  507. if (unlikely(!host->node_id))
  508. host->node_id = mallocz(sizeof(*host->node_id));
  509. uuid_copy(*(host->node_id), *node_id);
  510. if (unlikely(!wc))
  511. sql_create_aclk_table(host, &host->host_uuid, node_id);
  512. else
  513. uuid_unparse_lower(*node_id, wc->node_id);
  514. }
  515. #define SQL_UPDATE_NODE_ID "update node_instance set node_id = @node_id where host_id = @host_id;"
  516. int update_node_id(uuid_t *host_id, uuid_t *node_id)
  517. {
  518. sqlite3_stmt *res = NULL;
  519. RRDHOST *host = NULL;
  520. int rc = 2;
  521. if (unlikely(!db_meta)) {
  522. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  523. error_report("Database has not been initialized");
  524. return 1;
  525. }
  526. rc = sqlite3_prepare_v2(db_meta, SQL_UPDATE_NODE_ID, -1, &res, 0);
  527. if (unlikely(rc != SQLITE_OK)) {
  528. error_report("Failed to prepare statement to store node instance information");
  529. return 1;
  530. }
  531. rc = sqlite3_bind_blob(res, 1, node_id, sizeof(*node_id), SQLITE_STATIC);
  532. if (unlikely(rc != SQLITE_OK)) {
  533. error_report("Failed to bind host_id parameter to store node instance information");
  534. goto failed;
  535. }
  536. rc = sqlite3_bind_blob(res, 2, host_id, sizeof(*host_id), SQLITE_STATIC);
  537. if (unlikely(rc != SQLITE_OK)) {
  538. error_report("Failed to bind host_id parameter to store node instance information");
  539. goto failed;
  540. }
  541. rc = execute_insert(res);
  542. if (unlikely(rc != SQLITE_DONE))
  543. error_report("Failed to store node instance information, rc = %d", rc);
  544. rc = sqlite3_changes(db_meta);
  545. char host_guid[GUID_LEN + 1];
  546. uuid_unparse_lower(*host_id, host_guid);
  547. rrd_wrlock();
  548. host = rrdhost_find_by_guid(host_guid);
  549. if (likely(host))
  550. set_host_node_id(host, node_id);
  551. rrd_unlock();
  552. failed:
  553. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  554. error_report("Failed to finalize the prepared statement when storing node instance information");
  555. return rc - 1;
  556. }
  557. #define SQL_SELECT_HOST_BY_NODE_ID "select host_id from node_instance where node_id = @node_id;"
  558. int get_host_id(uuid_t *node_id, uuid_t *host_id)
  559. {
  560. static __thread sqlite3_stmt *res = NULL;
  561. int rc;
  562. if (unlikely(!db_meta)) {
  563. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  564. error_report("Database has not been initialized");
  565. return 1;
  566. }
  567. if (unlikely(!res)) {
  568. rc = prepare_statement(db_meta, SQL_SELECT_HOST_BY_NODE_ID, &res);
  569. if (unlikely(rc != SQLITE_OK)) {
  570. error_report("Failed to prepare statement to select node instance information for a node");
  571. return 1;
  572. }
  573. }
  574. rc = sqlite3_bind_blob(res, 1, node_id, sizeof(*node_id), SQLITE_STATIC);
  575. if (unlikely(rc != SQLITE_OK)) {
  576. error_report("Failed to bind host_id parameter to select node instance information");
  577. goto failed;
  578. }
  579. rc = sqlite3_step_monitored(res);
  580. if (likely(rc == SQLITE_ROW && host_id))
  581. uuid_copy(*host_id, *((uuid_t *) sqlite3_column_blob(res, 0)));
  582. failed:
  583. if (unlikely(sqlite3_reset(res) != SQLITE_OK))
  584. error_report("Failed to reset the prepared statement when selecting node instance information");
  585. return (rc == SQLITE_ROW) ? 0 : -1;
  586. }
  587. #define SQL_SELECT_NODE_ID "SELECT node_id FROM node_instance WHERE host_id = @host_id AND node_id IS NOT NULL;"
  588. int get_node_id(uuid_t *host_id, uuid_t *node_id)
  589. {
  590. sqlite3_stmt *res = NULL;
  591. int rc;
  592. if (unlikely(!db_meta)) {
  593. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  594. error_report("Database has not been initialized");
  595. return 1;
  596. }
  597. rc = sqlite3_prepare_v2(db_meta, SQL_SELECT_NODE_ID, -1, &res, 0);
  598. if (unlikely(rc != SQLITE_OK)) {
  599. error_report("Failed to prepare statement to select node instance information for a host");
  600. return 1;
  601. }
  602. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  603. if (unlikely(rc != SQLITE_OK)) {
  604. error_report("Failed to bind host_id parameter to select node instance information");
  605. goto failed;
  606. }
  607. rc = sqlite3_step_monitored(res);
  608. if (likely(rc == SQLITE_ROW && node_id))
  609. uuid_copy(*node_id, *((uuid_t *) sqlite3_column_blob(res, 0)));
  610. failed:
  611. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  612. error_report("Failed to finalize the prepared statement when selecting node instance information");
  613. return (rc == SQLITE_ROW) ? 0 : -1;
  614. }
  615. #define SQL_INVALIDATE_NODE_INSTANCES "UPDATE node_instance SET node_id = NULL WHERE EXISTS " \
  616. "(SELECT host_id FROM node_instance WHERE host_id = @host_id AND (@claim_id IS NULL OR claim_id <> @claim_id));"
  617. void invalidate_node_instances(uuid_t *host_id, uuid_t *claim_id)
  618. {
  619. sqlite3_stmt *res = NULL;
  620. int rc;
  621. if (unlikely(!db_meta)) {
  622. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  623. error_report("Database has not been initialized");
  624. return;
  625. }
  626. rc = sqlite3_prepare_v2(db_meta, SQL_INVALIDATE_NODE_INSTANCES, -1, &res, 0);
  627. if (unlikely(rc != SQLITE_OK)) {
  628. error_report("Failed to prepare statement to invalidate node instance ids");
  629. return;
  630. }
  631. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  632. if (unlikely(rc != SQLITE_OK)) {
  633. error_report("Failed to bind host_id parameter to invalidate node instance information");
  634. goto failed;
  635. }
  636. if (claim_id)
  637. rc = sqlite3_bind_blob(res, 2, claim_id, sizeof(*claim_id), SQLITE_STATIC);
  638. else
  639. rc = sqlite3_bind_null(res, 2);
  640. if (unlikely(rc != SQLITE_OK)) {
  641. error_report("Failed to bind claim_id parameter to invalidate node instance information");
  642. goto failed;
  643. }
  644. rc = execute_insert(res);
  645. if (unlikely(rc != SQLITE_DONE))
  646. error_report("Failed to invalidate node instance information, rc = %d", rc);
  647. failed:
  648. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  649. error_report("Failed to finalize the prepared statement when invalidating node instance information");
  650. }
  651. #define SQL_GET_NODE_INSTANCE_LIST "SELECT ni.node_id, ni.host_id, h.hostname " \
  652. "FROM node_instance ni, host h WHERE ni.host_id = h.host_id AND h.hops >=0;"
  653. struct node_instance_list *get_node_list(void)
  654. {
  655. struct node_instance_list *node_list = NULL;
  656. sqlite3_stmt *res = NULL;
  657. int rc;
  658. if (unlikely(!db_meta)) {
  659. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  660. error_report("Database has not been initialized");
  661. return NULL;
  662. }
  663. rc = sqlite3_prepare_v2(db_meta, SQL_GET_NODE_INSTANCE_LIST, -1, &res, 0);
  664. if (unlikely(rc != SQLITE_OK)) {
  665. error_report("Failed to prepare statement to get node instance information");
  666. return NULL;
  667. };
  668. int row = 0;
  669. char host_guid[37];
  670. while (sqlite3_step_monitored(res) == SQLITE_ROW)
  671. row++;
  672. if (sqlite3_reset(res) != SQLITE_OK) {
  673. error_report("Failed to reset the prepared statement while fetching node instance information");
  674. goto failed;
  675. }
  676. node_list = callocz(row + 1, sizeof(*node_list));
  677. int max_rows = row;
  678. row = 0;
  679. // TODO: Check to remove lock
  680. rrd_rdlock();
  681. while (sqlite3_step_monitored(res) == SQLITE_ROW) {
  682. if (sqlite3_column_bytes(res, 0) == sizeof(uuid_t))
  683. uuid_copy(node_list[row].node_id, *((uuid_t *)sqlite3_column_blob(res, 0)));
  684. if (sqlite3_column_bytes(res, 1) == sizeof(uuid_t)) {
  685. uuid_t *host_id = (uuid_t *)sqlite3_column_blob(res, 1);
  686. uuid_unparse_lower(*host_id, host_guid);
  687. RRDHOST *host = rrdhost_find_by_guid(host_guid);
  688. if (rrdhost_flag_check(host, RRDHOST_FLAG_PENDING_CONTEXT_LOAD)) {
  689. netdata_log_info("ACLK: 'host:%s' skipping get node list because context is initializing", rrdhost_hostname(host));
  690. continue;
  691. }
  692. uuid_copy(node_list[row].host_id, *host_id);
  693. node_list[row].queryable = 1;
  694. node_list[row].live = (host && (host == localhost || host->receiver
  695. || !(rrdhost_flag_check(host, RRDHOST_FLAG_ORPHAN)))) ? 1 : 0;
  696. node_list[row].hops = (host && host->system_info) ? host->system_info->hops :
  697. uuid_memcmp(host_id, &localhost->host_uuid) ? 1 : 0;
  698. node_list[row].hostname =
  699. sqlite3_column_bytes(res, 2) ? strdupz((char *)sqlite3_column_text(res, 2)) : NULL;
  700. }
  701. row++;
  702. if (row == max_rows)
  703. break;
  704. }
  705. rrd_unlock();
  706. failed:
  707. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  708. error_report("Failed to finalize the prepared statement when fetching node instance information");
  709. return node_list;
  710. };
  711. #define SQL_GET_HOST_NODE_ID "select node_id from node_instance where host_id = @host_id;"
  712. void sql_load_node_id(RRDHOST *host)
  713. {
  714. static __thread sqlite3_stmt *res = NULL;
  715. int rc;
  716. if (unlikely(!db_meta)) {
  717. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  718. error_report("Database has not been initialized");
  719. return;
  720. }
  721. if (unlikely(!res)) {
  722. rc = prepare_statement(db_meta, SQL_GET_HOST_NODE_ID, &res);
  723. if (unlikely(rc != SQLITE_OK)) {
  724. error_report("Failed to prepare statement to fetch node id");
  725. return;
  726. };
  727. }
  728. rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
  729. if (unlikely(rc != SQLITE_OK)) {
  730. error_report("Failed to bind host_id parameter to load node instance information");
  731. goto failed;
  732. }
  733. rc = sqlite3_step_monitored(res);
  734. if (likely(rc == SQLITE_ROW)) {
  735. if (likely(sqlite3_column_bytes(res, 0) == sizeof(uuid_t)))
  736. set_host_node_id(host, (uuid_t *)sqlite3_column_blob(res, 0));
  737. else
  738. set_host_node_id(host, NULL);
  739. }
  740. failed:
  741. if (unlikely(sqlite3_reset(res) != SQLITE_OK))
  742. error_report("Failed to reset the prepared statement when loading node instance information");
  743. };
  744. #define SELECT_HOST_INFO "SELECT system_key, system_value FROM host_info WHERE host_id = @host_id;"
  745. void sql_build_host_system_info(uuid_t *host_id, struct rrdhost_system_info *system_info)
  746. {
  747. int rc;
  748. sqlite3_stmt *res = NULL;
  749. rc = sqlite3_prepare_v2(db_meta, SELECT_HOST_INFO, -1, &res, 0);
  750. if (unlikely(rc != SQLITE_OK)) {
  751. error_report("Failed to prepare statement to read host information");
  752. return;
  753. }
  754. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  755. if (unlikely(rc != SQLITE_OK)) {
  756. error_report("Failed to bind host parameter host information");
  757. goto skip;
  758. }
  759. while (sqlite3_step_monitored(res) == SQLITE_ROW) {
  760. rrdhost_set_system_info_variable(system_info, (char *) sqlite3_column_text(res, 0),
  761. (char *) sqlite3_column_text(res, 1));
  762. }
  763. skip:
  764. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  765. error_report("Failed to finalize the prepared statement when reading host information");
  766. }
  767. #define SELECT_HOST_LABELS "SELECT label_key, label_value, source_type FROM host_label WHERE host_id = @host_id " \
  768. "AND label_key IS NOT NULL AND label_value IS NOT NULL;"
  769. DICTIONARY *sql_load_host_labels(uuid_t *host_id)
  770. {
  771. int rc;
  772. DICTIONARY *labels = NULL;
  773. sqlite3_stmt *res = NULL;
  774. rc = sqlite3_prepare_v2(db_meta, SELECT_HOST_LABELS, -1, &res, 0);
  775. if (unlikely(rc != SQLITE_OK)) {
  776. error_report("Failed to prepare statement to read host information");
  777. return NULL;
  778. }
  779. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  780. if (unlikely(rc != SQLITE_OK)) {
  781. error_report("Failed to bind host parameter host information");
  782. goto skip;
  783. }
  784. labels = rrdlabels_create();
  785. while (sqlite3_step_monitored(res) == SQLITE_ROW) {
  786. rrdlabels_add(
  787. labels,
  788. (const char *)sqlite3_column_text(res, 0),
  789. (const char *)sqlite3_column_text(res, 1),
  790. sqlite3_column_int(res, 2));
  791. }
  792. skip:
  793. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  794. error_report("Failed to finalize the prepared statement when reading host information");
  795. return labels;
  796. }
  797. // Utils
  798. int bind_text_null(sqlite3_stmt *res, int position, const char *text, bool can_be_null)
  799. {
  800. if (likely(text))
  801. return sqlite3_bind_text(res, position, text, -1, SQLITE_STATIC);
  802. if (!can_be_null)
  803. return 1;
  804. return sqlite3_bind_null(res, position);
  805. }
  806. int sql_metadata_cache_stats(int op)
  807. {
  808. int count, dummy;
  809. if (unlikely(!db_meta))
  810. return 0;
  811. netdata_thread_disable_cancelability();
  812. sqlite3_db_status(db_meta, op, &count, &dummy, 0);
  813. netdata_thread_enable_cancelability();
  814. return count;
  815. }
  816. #define SQL_DROP_TABLE "DROP table %s;"
  817. void sql_drop_table(const char *table)
  818. {
  819. if (!table)
  820. return;
  821. char wstr[255];
  822. snprintfz(wstr, 254, SQL_DROP_TABLE, table);
  823. int rc = sqlite3_exec_monitored(db_meta, wstr, 0, 0, NULL);
  824. if (rc != SQLITE_OK) {
  825. error_report("DES SQLite error during drop table operation for %s, rc = %d", table, rc);
  826. }
  827. }