sqlite_functions.c 33 KB

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