sqlite_functions.c 32 KB

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