sqlite_functions.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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 14
  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(rc == SQLITE_DONE, 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)
  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, 1024, "PRAGMA auto_vacuum=%s;", config_get(CONFIG_SECTION_SQLITE, "auto vacuum", "INCREMENTAL"));
  171. if (init_database_batch(database, list))
  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, 1024, "PRAGMA synchronous=%s;", config_get(CONFIG_SECTION_SQLITE, "synchronous", "NORMAL"));
  176. if (init_database_batch(database, list))
  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, 1024, "PRAGMA journal_mode=%s;", config_get(CONFIG_SECTION_SQLITE, "journal mode", "WAL"));
  181. if (init_database_batch(database, list))
  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, 1024, "PRAGMA temp_store=%s;", config_get(CONFIG_SECTION_SQLITE, "temp store", "MEMORY"));
  186. if (init_database_batch(database, list))
  187. return 1;
  188. // https://www.sqlite.org/pragma.html#pragma_journal_size_limit
  189. // PRAGMA schema.journal_size_limit = N ;
  190. snprintfz(buf, 1024, "PRAGMA journal_size_limit=%lld;", config_get_number(CONFIG_SECTION_SQLITE, "journal size limit", 16777216));
  191. if (init_database_batch(database, list))
  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, 1024, "PRAGMA cache_size=%lld;", config_get_number(CONFIG_SECTION_SQLITE, "cache size", -2000));
  197. if (init_database_batch(database, list))
  198. return 1;
  199. snprintfz(buf, 1024, "PRAGMA user_version=%d;", target_version);
  200. if (init_database_batch(database, list))
  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. int init_database_batch(sqlite3 *database, const char *batch[])
  260. {
  261. int rc;
  262. char *err_msg = NULL;
  263. for (int i = 0; batch[i]; i++) {
  264. rc = sqlite3_exec_monitored(database, batch[i], 0, 0, &err_msg);
  265. if (rc != SQLITE_OK) {
  266. error_report("SQLite error during database initialization, rc = %d (%s)", rc, err_msg);
  267. error_report("SQLite failed statement %s", batch[i]);
  268. analytics_set_data_str(&analytics_data.netdata_fail_reason, sqlite3_errstr(sqlite3_extended_errcode(database)));
  269. sqlite3_free(err_msg);
  270. if (SQLITE_CORRUPT == rc) {
  271. if (mark_database_to_recover(NULL, database))
  272. error_report("Database is corrupted will attempt to fix");
  273. return SQLITE_CORRUPT;
  274. }
  275. return 1;
  276. }
  277. }
  278. return 0;
  279. }
  280. static void sqlite_uuid_parse(sqlite3_context *context, int argc, sqlite3_value **argv)
  281. {
  282. uuid_t uuid;
  283. if ( argc != 1 ){
  284. sqlite3_result_null(context);
  285. return ;
  286. }
  287. int rc = uuid_parse((const char *) sqlite3_value_text(argv[0]), uuid);
  288. if (rc == -1) {
  289. sqlite3_result_null(context);
  290. return ;
  291. }
  292. sqlite3_result_blob(context, &uuid, sizeof(uuid_t), SQLITE_TRANSIENT);
  293. }
  294. void sqlite_now_usec(sqlite3_context *context, int argc, sqlite3_value **argv)
  295. {
  296. if (argc != 1 ){
  297. sqlite3_result_null(context);
  298. return ;
  299. }
  300. if (sqlite3_value_int(argv[0]) != 0) {
  301. struct timespec req = {.tv_sec = 0, .tv_nsec = 1};
  302. nanosleep(&req, NULL);
  303. }
  304. sqlite3_result_int64(context, (sqlite_int64) now_realtime_usec());
  305. }
  306. void sqlite_uuid_random(sqlite3_context *context, int argc, sqlite3_value **argv)
  307. {
  308. (void)argc;
  309. (void)argv;
  310. uuid_t uuid;
  311. uuid_generate_random(uuid);
  312. sqlite3_result_blob(context, &uuid, sizeof(uuid_t), SQLITE_TRANSIENT);
  313. }
  314. /*
  315. * Initialize the SQLite database
  316. * Return 0 on success
  317. */
  318. int sql_init_database(db_check_action_type_t rebuild, int memory)
  319. {
  320. char *err_msg = NULL;
  321. char sqlite_database[FILENAME_MAX + 1];
  322. int rc;
  323. if (likely(!memory)) {
  324. snprintfz(sqlite_database, FILENAME_MAX, "%s/.netdata-meta.db.recover", netdata_configured_cache_dir);
  325. rc = unlink(sqlite_database);
  326. snprintfz(sqlite_database, FILENAME_MAX, "%s/netdata-meta.db", netdata_configured_cache_dir);
  327. if (rc == 0 || (rebuild & DB_CHECK_RECOVER)) {
  328. char new_sqlite_database[FILENAME_MAX + 1];
  329. snprintfz(new_sqlite_database, FILENAME_MAX, "%s/netdata-meta-recover.db", netdata_configured_cache_dir);
  330. recover_database(sqlite_database, new_sqlite_database);
  331. if (rebuild & DB_CHECK_RECOVER)
  332. return 0;
  333. }
  334. }
  335. else
  336. strcpy(sqlite_database, ":memory:");
  337. rc = sqlite3_open(sqlite_database, &db_meta);
  338. if (rc != SQLITE_OK) {
  339. error_report("Failed to initialize database at %s, due to \"%s\"", sqlite_database, sqlite3_errstr(rc));
  340. analytics_set_data_str(&analytics_data.netdata_fail_reason, sqlite3_errstr(sqlite3_extended_errcode(db_meta)));
  341. sqlite3_close(db_meta);
  342. db_meta = NULL;
  343. return 1;
  344. }
  345. if (rebuild & DB_CHECK_RECLAIM_SPACE) {
  346. netdata_log_info("Reclaiming space of %s", sqlite_database);
  347. rc = sqlite3_exec_monitored(db_meta, "VACUUM;", 0, 0, &err_msg);
  348. if (rc != SQLITE_OK) {
  349. error_report("Failed to execute VACUUM rc = %d (%s)", rc, err_msg);
  350. sqlite3_free(err_msg);
  351. }
  352. else {
  353. (void) db_execute(db_meta, "select count(*) from sqlite_master limit 0");
  354. (void) sqlite3_close(db_meta);
  355. }
  356. return 1;
  357. }
  358. netdata_log_info("SQLite database %s initialization", sqlite_database);
  359. rc = sqlite3_create_function(db_meta, "u2h", 1, SQLITE_ANY | SQLITE_DETERMINISTIC, 0, sqlite_uuid_parse, 0, 0);
  360. if (unlikely(rc != SQLITE_OK))
  361. error_report("Failed to register internal u2h function");
  362. rc = sqlite3_create_function(db_meta, "now_usec", 1, SQLITE_ANY, 0, sqlite_now_usec, 0, 0);
  363. if (unlikely(rc != SQLITE_OK))
  364. error_report("Failed to register internal now_usec function");
  365. rc = sqlite3_create_function(db_meta, "uuid_random", 0, SQLITE_ANY, 0, sqlite_uuid_random, 0, 0);
  366. if (unlikely(rc != SQLITE_OK))
  367. error_report("Failed to register internal uuid_random function");
  368. int target_version = DB_METADATA_VERSION;
  369. if (likely(!memory))
  370. target_version = perform_database_migration(db_meta, DB_METADATA_VERSION);
  371. if (configure_sqlite_database(db_meta, target_version))
  372. return 1;
  373. if (init_database_batch(db_meta, &database_config[0]))
  374. return 1;
  375. if (init_database_batch(db_meta, &database_cleanup[0]))
  376. return 1;
  377. netdata_log_info("SQLite database initialization completed");
  378. initialize_thread_key_pool();
  379. return 0;
  380. }
  381. /*
  382. * Close the sqlite database
  383. */
  384. void sql_close_database(void)
  385. {
  386. int rc;
  387. if (unlikely(!db_meta))
  388. return;
  389. netdata_log_info("Closing SQLite database");
  390. add_stmt_to_list(NULL);
  391. rc = sqlite3_close_v2(db_meta);
  392. if (unlikely(rc != SQLITE_OK))
  393. error_report("Error %d while closing the SQLite database, %s", rc, sqlite3_errstr(rc));
  394. }
  395. int exec_statement_with_uuid(const char *sql, uuid_t *uuid)
  396. {
  397. int rc, result = 1;
  398. sqlite3_stmt *res = NULL;
  399. rc = sqlite3_prepare_v2(db_meta, sql, -1, &res, 0);
  400. if (unlikely(rc != SQLITE_OK)) {
  401. error_report("Failed to prepare statement %s, rc = %d", sql, rc);
  402. return 1;
  403. }
  404. rc = sqlite3_bind_blob(res, 1, uuid, sizeof(*uuid), SQLITE_STATIC);
  405. if (unlikely(rc != SQLITE_OK)) {
  406. error_report("Failed to bind UUID parameter to %s, rc = %d", sql, rc);
  407. goto skip;
  408. }
  409. rc = execute_insert(res);
  410. if (likely(rc == SQLITE_DONE))
  411. result = SQLITE_OK;
  412. else
  413. error_report("Failed to execute %s, rc = %d", sql, rc);
  414. skip:
  415. rc = sqlite3_finalize(res);
  416. if (unlikely(rc != SQLITE_OK))
  417. error_report("Failed to finalize statement %s, rc = %d", sql, rc);
  418. return result;
  419. }
  420. // Return 0 OK
  421. // Return 1 Failed
  422. int db_execute(sqlite3 *db, const char *cmd)
  423. {
  424. int rc;
  425. int cnt = 0;
  426. while (cnt < SQL_MAX_RETRY) {
  427. char *err_msg;
  428. rc = sqlite3_exec_monitored(db, cmd, 0, 0, &err_msg);
  429. if (rc != SQLITE_OK) {
  430. error_report("Failed to execute '%s', rc = %d (%s) -- attempt %d", cmd, rc, err_msg, cnt);
  431. sqlite3_free(err_msg);
  432. if (likely(rc == SQLITE_BUSY || rc == SQLITE_LOCKED)) {
  433. usleep(SQLITE_INSERT_DELAY * USEC_PER_MS);
  434. }
  435. else
  436. break;
  437. }
  438. else
  439. break;
  440. ++cnt;
  441. }
  442. return (rc != SQLITE_OK);
  443. }
  444. static inline void set_host_node_id(RRDHOST *host, uuid_t *node_id)
  445. {
  446. if (unlikely(!host))
  447. return;
  448. if (unlikely(!node_id)) {
  449. freez(host->node_id);
  450. __atomic_store_n(&host->node_id, NULL, __ATOMIC_RELAXED);
  451. return;
  452. }
  453. struct aclk_sync_host_config *wc = host->aclk_sync_host_config;
  454. if (unlikely(!host->node_id)) {
  455. uuid_t *t = mallocz(sizeof(*host->node_id));
  456. uuid_copy(*t, *node_id);
  457. __atomic_store_n(&host->node_id, t, __ATOMIC_RELAXED);
  458. }
  459. else {
  460. uuid_copy(*(host->node_id), *node_id);
  461. }
  462. if (unlikely(!wc))
  463. sql_create_aclk_table(host, &host->host_uuid, node_id);
  464. else
  465. uuid_unparse_lower(*node_id, wc->node_id);
  466. }
  467. #define SQL_UPDATE_NODE_ID "update node_instance set node_id = @node_id where host_id = @host_id;"
  468. int update_node_id(uuid_t *host_id, uuid_t *node_id)
  469. {
  470. sqlite3_stmt *res = NULL;
  471. RRDHOST *host = NULL;
  472. int rc = 2;
  473. char host_guid[GUID_LEN + 1];
  474. uuid_unparse_lower(*host_id, host_guid);
  475. rrd_wrlock();
  476. host = rrdhost_find_by_guid(host_guid);
  477. if (likely(host))
  478. set_host_node_id(host, node_id);
  479. rrd_unlock();
  480. if (unlikely(!db_meta)) {
  481. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  482. error_report("Database has not been initialized");
  483. return 1;
  484. }
  485. rc = sqlite3_prepare_v2(db_meta, SQL_UPDATE_NODE_ID, -1, &res, 0);
  486. if (unlikely(rc != SQLITE_OK)) {
  487. error_report("Failed to prepare statement to store node instance information");
  488. return 1;
  489. }
  490. rc = sqlite3_bind_blob(res, 1, node_id, sizeof(*node_id), SQLITE_STATIC);
  491. if (unlikely(rc != SQLITE_OK)) {
  492. error_report("Failed to bind host_id parameter to store node instance information");
  493. goto failed;
  494. }
  495. rc = sqlite3_bind_blob(res, 2, host_id, sizeof(*host_id), SQLITE_STATIC);
  496. if (unlikely(rc != SQLITE_OK)) {
  497. error_report("Failed to bind host_id parameter to store node instance information");
  498. goto failed;
  499. }
  500. rc = execute_insert(res);
  501. if (unlikely(rc != SQLITE_DONE))
  502. error_report("Failed to store node instance information, rc = %d", rc);
  503. rc = sqlite3_changes(db_meta);
  504. failed:
  505. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  506. error_report("Failed to finalize the prepared statement when storing node instance information");
  507. return rc - 1;
  508. }
  509. #define SQL_SELECT_NODE_ID "SELECT node_id FROM node_instance WHERE host_id = @host_id AND node_id IS NOT NULL;"
  510. int get_node_id(uuid_t *host_id, uuid_t *node_id)
  511. {
  512. sqlite3_stmt *res = NULL;
  513. int rc;
  514. if (unlikely(!db_meta)) {
  515. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  516. error_report("Database has not been initialized");
  517. return 1;
  518. }
  519. rc = sqlite3_prepare_v2(db_meta, SQL_SELECT_NODE_ID, -1, &res, 0);
  520. if (unlikely(rc != SQLITE_OK)) {
  521. error_report("Failed to prepare statement to select node instance information for a host");
  522. return 1;
  523. }
  524. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  525. if (unlikely(rc != SQLITE_OK)) {
  526. error_report("Failed to bind host_id parameter to select node instance information");
  527. goto failed;
  528. }
  529. rc = sqlite3_step_monitored(res);
  530. if (likely(rc == SQLITE_ROW && node_id))
  531. uuid_copy(*node_id, *((uuid_t *) sqlite3_column_blob(res, 0)));
  532. failed:
  533. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  534. error_report("Failed to finalize the prepared statement when selecting node instance information");
  535. return (rc == SQLITE_ROW) ? 0 : -1;
  536. }
  537. #define SQL_INVALIDATE_NODE_INSTANCES "UPDATE node_instance SET node_id = NULL WHERE EXISTS " \
  538. "(SELECT host_id FROM node_instance WHERE host_id = @host_id AND (@claim_id IS NULL OR claim_id <> @claim_id));"
  539. void invalidate_node_instances(uuid_t *host_id, uuid_t *claim_id)
  540. {
  541. sqlite3_stmt *res = NULL;
  542. int rc;
  543. if (unlikely(!db_meta)) {
  544. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  545. error_report("Database has not been initialized");
  546. return;
  547. }
  548. rc = sqlite3_prepare_v2(db_meta, SQL_INVALIDATE_NODE_INSTANCES, -1, &res, 0);
  549. if (unlikely(rc != SQLITE_OK)) {
  550. error_report("Failed to prepare statement to invalidate node instance ids");
  551. return;
  552. }
  553. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  554. if (unlikely(rc != SQLITE_OK)) {
  555. error_report("Failed to bind host_id parameter to invalidate node instance information");
  556. goto failed;
  557. }
  558. if (claim_id)
  559. rc = sqlite3_bind_blob(res, 2, claim_id, sizeof(*claim_id), SQLITE_STATIC);
  560. else
  561. rc = sqlite3_bind_null(res, 2);
  562. if (unlikely(rc != SQLITE_OK)) {
  563. error_report("Failed to bind claim_id parameter to invalidate node instance information");
  564. goto failed;
  565. }
  566. rc = execute_insert(res);
  567. if (unlikely(rc != SQLITE_DONE))
  568. error_report("Failed to invalidate node instance information, rc = %d", rc);
  569. failed:
  570. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  571. error_report("Failed to finalize the prepared statement when invalidating node instance information");
  572. }
  573. #define SQL_GET_NODE_INSTANCE_LIST "SELECT ni.node_id, ni.host_id, h.hostname " \
  574. "FROM node_instance ni, host h WHERE ni.host_id = h.host_id AND h.hops >=0;"
  575. struct node_instance_list *get_node_list(void)
  576. {
  577. struct node_instance_list *node_list = NULL;
  578. sqlite3_stmt *res = NULL;
  579. int rc;
  580. if (unlikely(!db_meta)) {
  581. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  582. error_report("Database has not been initialized");
  583. return NULL;
  584. }
  585. rc = sqlite3_prepare_v2(db_meta, SQL_GET_NODE_INSTANCE_LIST, -1, &res, 0);
  586. if (unlikely(rc != SQLITE_OK)) {
  587. error_report("Failed to prepare statement to get node instance information");
  588. return NULL;
  589. };
  590. int row = 0;
  591. char host_guid[37];
  592. while (sqlite3_step_monitored(res) == SQLITE_ROW)
  593. row++;
  594. if (sqlite3_reset(res) != SQLITE_OK) {
  595. error_report("Failed to reset the prepared statement while fetching node instance information");
  596. goto failed;
  597. }
  598. node_list = callocz(row + 1, sizeof(*node_list));
  599. int max_rows = row;
  600. row = 0;
  601. // TODO: Check to remove lock
  602. rrd_rdlock();
  603. while (sqlite3_step_monitored(res) == SQLITE_ROW) {
  604. if (sqlite3_column_bytes(res, 0) == sizeof(uuid_t))
  605. uuid_copy(node_list[row].node_id, *((uuid_t *)sqlite3_column_blob(res, 0)));
  606. if (sqlite3_column_bytes(res, 1) == sizeof(uuid_t)) {
  607. uuid_t *host_id = (uuid_t *)sqlite3_column_blob(res, 1);
  608. uuid_unparse_lower(*host_id, host_guid);
  609. RRDHOST *host = rrdhost_find_by_guid(host_guid);
  610. if (!host)
  611. continue;
  612. if (rrdhost_flag_check(host, RRDHOST_FLAG_PENDING_CONTEXT_LOAD)) {
  613. netdata_log_info("ACLK: 'host:%s' skipping get node list because context is initializing", rrdhost_hostname(host));
  614. continue;
  615. }
  616. uuid_copy(node_list[row].host_id, *host_id);
  617. node_list[row].queryable = 1;
  618. node_list[row].live = (host && (host == localhost || host->receiver
  619. || !(rrdhost_flag_check(host, RRDHOST_FLAG_ORPHAN)))) ? 1 : 0;
  620. node_list[row].hops = (host && host->system_info) ? host->system_info->hops :
  621. uuid_memcmp(host_id, &localhost->host_uuid) ? 1 : 0;
  622. node_list[row].hostname =
  623. sqlite3_column_bytes(res, 2) ? strdupz((char *)sqlite3_column_text(res, 2)) : NULL;
  624. }
  625. row++;
  626. if (row == max_rows)
  627. break;
  628. }
  629. rrd_unlock();
  630. failed:
  631. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  632. error_report("Failed to finalize the prepared statement when fetching node instance information");
  633. return node_list;
  634. };
  635. #define SQL_GET_HOST_NODE_ID "select node_id from node_instance where host_id = @host_id;"
  636. void sql_load_node_id(RRDHOST *host)
  637. {
  638. sqlite3_stmt *res = NULL;
  639. int rc;
  640. if (unlikely(!db_meta)) {
  641. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  642. error_report("Database has not been initialized");
  643. return;
  644. }
  645. rc = sqlite3_prepare_v2(db_meta, SQL_GET_HOST_NODE_ID, -1, &res, 0);
  646. if (unlikely(rc != SQLITE_OK)) {
  647. error_report("Failed to prepare statement to fetch node id");
  648. return;
  649. };
  650. rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
  651. if (unlikely(rc != SQLITE_OK)) {
  652. error_report("Failed to bind host_id parameter to load node instance information");
  653. goto failed;
  654. }
  655. rc = sqlite3_step_monitored(res);
  656. if (likely(rc == SQLITE_ROW)) {
  657. if (likely(sqlite3_column_bytes(res, 0) == sizeof(uuid_t)))
  658. set_host_node_id(host, (uuid_t *)sqlite3_column_blob(res, 0));
  659. else
  660. set_host_node_id(host, NULL);
  661. }
  662. failed:
  663. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  664. error_report("Failed to finalize the prepared statement when loading node instance information");
  665. };
  666. #define SELECT_HOST_INFO "SELECT system_key, system_value FROM host_info WHERE host_id = @host_id;"
  667. void sql_build_host_system_info(uuid_t *host_id, struct rrdhost_system_info *system_info)
  668. {
  669. int rc;
  670. sqlite3_stmt *res = NULL;
  671. rc = sqlite3_prepare_v2(db_meta, SELECT_HOST_INFO, -1, &res, 0);
  672. if (unlikely(rc != SQLITE_OK)) {
  673. error_report("Failed to prepare statement to read host information");
  674. return;
  675. }
  676. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  677. if (unlikely(rc != SQLITE_OK)) {
  678. error_report("Failed to bind host parameter host information");
  679. goto skip;
  680. }
  681. while (sqlite3_step_monitored(res) == SQLITE_ROW) {
  682. rrdhost_set_system_info_variable(system_info, (char *) sqlite3_column_text(res, 0),
  683. (char *) sqlite3_column_text(res, 1));
  684. }
  685. skip:
  686. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  687. error_report("Failed to finalize the prepared statement when reading host information");
  688. }
  689. #define SELECT_HOST_LABELS "SELECT label_key, label_value, source_type FROM host_label WHERE host_id = @host_id " \
  690. "AND label_key IS NOT NULL AND label_value IS NOT NULL;"
  691. RRDLABELS *sql_load_host_labels(uuid_t *host_id)
  692. {
  693. int rc;
  694. RRDLABELS *labels = NULL;
  695. sqlite3_stmt *res = NULL;
  696. rc = sqlite3_prepare_v2(db_meta, SELECT_HOST_LABELS, -1, &res, 0);
  697. if (unlikely(rc != SQLITE_OK)) {
  698. error_report("Failed to prepare statement to read host information");
  699. return NULL;
  700. }
  701. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  702. if (unlikely(rc != SQLITE_OK)) {
  703. error_report("Failed to bind host parameter host information");
  704. goto skip;
  705. }
  706. labels = rrdlabels_create();
  707. while (sqlite3_step_monitored(res) == SQLITE_ROW) {
  708. rrdlabels_add(labels, (const char *)sqlite3_column_text(res, 0), (const char *)sqlite3_column_text(res, 1), sqlite3_column_int(res, 2));
  709. }
  710. skip:
  711. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  712. error_report("Failed to finalize the prepared statement when reading host information");
  713. return labels;
  714. }
  715. // Utils
  716. int bind_text_null(sqlite3_stmt *res, int position, const char *text, bool can_be_null)
  717. {
  718. if (likely(text))
  719. return sqlite3_bind_text(res, position, text, -1, SQLITE_STATIC);
  720. if (!can_be_null)
  721. return 1;
  722. return sqlite3_bind_null(res, position);
  723. }
  724. int sql_metadata_cache_stats(int op)
  725. {
  726. int count, dummy;
  727. if (unlikely(!db_meta))
  728. return 0;
  729. netdata_thread_disable_cancelability();
  730. sqlite3_db_status(db_meta, op, &count, &dummy, 0);
  731. netdata_thread_enable_cancelability();
  732. return count;
  733. }
  734. #define SQL_DROP_TABLE "DROP table %s;"
  735. void sql_drop_table(const char *table)
  736. {
  737. if (!table)
  738. return;
  739. char wstr[255];
  740. snprintfz(wstr, 254, SQL_DROP_TABLE, table);
  741. int rc = sqlite3_exec_monitored(db_meta, wstr, 0, 0, NULL);
  742. if (rc != SQLITE_OK) {
  743. error_report("DES SQLite error during drop table operation for %s, rc = %d", table, rc);
  744. }
  745. }