sqlite_functions.c 33 KB

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