sqlite_functions.c 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "sqlite_functions.h"
  3. #define DB_METADATA_VERSION "1"
  4. const char *database_config[] = {
  5. "CREATE TABLE IF NOT EXISTS host(host_id blob PRIMARY KEY, hostname text, "
  6. "registry_hostname text, update_every int, os text, timezone text, tags text);",
  7. "CREATE TABLE IF NOT EXISTS chart(chart_id blob PRIMARY KEY, host_id blob, type text, id text, name text, "
  8. "family text, context text, title text, unit text, plugin text, module text, priority int, update_every int, "
  9. "chart_type int, memory_mode int, history_entries);",
  10. "CREATE TABLE IF NOT EXISTS dimension(dim_id blob PRIMARY KEY, chart_id blob, id text, name text, "
  11. "multiplier int, divisor int , algorithm int, options text);",
  12. "DROP TABLE IF EXISTS chart_active;",
  13. "DROP TABLE IF EXISTS dimension_active;",
  14. "CREATE TABLE IF NOT EXISTS chart_active(chart_id blob PRIMARY KEY, date_created int);",
  15. "CREATE TABLE IF NOT EXISTS dimension_active(dim_id blob primary key, date_created int);",
  16. "CREATE TABLE IF NOT EXISTS metadata_migration(filename text, file_size, date_created int);",
  17. "CREATE INDEX IF NOT EXISTS ind_d1 on dimension (chart_id, id, name);",
  18. "CREATE INDEX IF NOT EXISTS ind_c1 on chart (host_id, id, type, name);",
  19. "CREATE TABLE IF NOT EXISTS chart_label(chart_id blob, source_type int, label_key text, "
  20. "label_value text, date_created int, PRIMARY KEY (chart_id, label_key));",
  21. "CREATE TABLE IF NOT EXISTS node_instance (host_id blob PRIMARY KEY, claim_id, node_id, date_created);",
  22. "CREATE TABLE IF NOT EXISTS alert_hash(hash_id blob PRIMARY KEY, date_updated int, alarm text, template text, "
  23. "on_key text, class text, component text, type text, os text, hosts text, lookup text, "
  24. "every text, units text, calc text, families text, plugin text, module text, charts text, green text, "
  25. "red text, warn text, crit text, exec text, to_key text, info text, delay text, options text, "
  26. "repeat text, host_labels text, p_db_lookup_dimensions text, p_db_lookup_method text, p_db_lookup_options int, "
  27. "p_db_lookup_after int, p_db_lookup_before int, p_update_every int);",
  28. "CREATE TABLE IF NOT EXISTS chart_hash_map(chart_id blob , hash_id blob, UNIQUE (chart_id, hash_id));",
  29. "CREATE TABLE IF NOT EXISTS chart_hash(hash_id blob PRIMARY KEY,type text, id text, name text, "
  30. "family text, context text, title text, unit text, plugin text, "
  31. "module text, priority integer, chart_type, last_used);",
  32. "CREATE VIEW IF NOT EXISTS v_chart_hash as SELECT ch.*, chm.chart_id FROM chart_hash ch, chart_hash_map chm "
  33. "WHERE ch.hash_id = chm.hash_id;",
  34. "CREATE TRIGGER IF NOT EXISTS ins_host AFTER INSERT ON host BEGIN INSERT INTO node_instance (host_id, date_created)"
  35. " SELECT new.host_id, strftime(\"%s\") WHERE new.host_id NOT IN (SELECT host_id FROM node_instance); END;",
  36. "CREATE TRIGGER IF NOT EXISTS tr_v_chart_hash INSTEAD OF INSERT on v_chart_hash BEGIN "
  37. "INSERT INTO chart_hash (hash_id, type, id, name, family, context, title, unit, plugin, "
  38. "module, priority, chart_type, last_used) "
  39. "values (new.hash_id, new.type, new.id, new.name, new.family, new.context, new.title, new.unit, new.plugin, "
  40. "new.module, new.priority, new.chart_type, strftime('%s')) "
  41. "ON CONFLICT (hash_id) DO UPDATE SET last_used = strftime('%s'); "
  42. "INSERT INTO chart_hash_map (chart_id, hash_id) values (new.chart_id, new.hash_id) "
  43. "on conflict (chart_id, hash_id) do nothing; END; ",
  44. "PRAGMA user_version="DB_METADATA_VERSION";",
  45. NULL
  46. };
  47. const char *database_cleanup[] = {
  48. "delete from chart where chart_id not in (select chart_id from dimension);",
  49. "delete from host where host_id not in (select host_id from chart);",
  50. "delete from chart_label where chart_id not in (select chart_id from chart);",
  51. "DELETE FROM chart_hash_map WHERE chart_id NOT IN (SELECT chart_id FROM chart);",
  52. "DELETE FROM chart_hash WHERE hash_id NOT IN (SELECT hash_id FROM chart_hash_map);",
  53. "DELETE FROM node_instance WHERE host_id NOT IN (SELECT host_id FROM host);",
  54. NULL
  55. };
  56. sqlite3 *db_meta = NULL;
  57. static uv_mutex_t sqlite_transaction_lock;
  58. int execute_insert(sqlite3_stmt *res)
  59. {
  60. int rc;
  61. int cnt = 0;
  62. while ((rc = sqlite3_step(res)) != SQLITE_DONE && ++cnt < SQL_MAX_RETRY && likely(!netdata_exit)) {
  63. if (likely(rc == SQLITE_BUSY || rc == SQLITE_LOCKED)) {
  64. usleep(SQLITE_INSERT_DELAY * USEC_PER_MS);
  65. error_report("Failed to insert/update, rc = %d -- attempt %d", rc, cnt);
  66. }
  67. else {
  68. error_report("SQLite error %d", rc);
  69. break;
  70. }
  71. }
  72. return rc;
  73. }
  74. #define MAX_OPEN_STATEMENTS (512)
  75. static void add_stmt_to_list(sqlite3_stmt *res)
  76. {
  77. static int idx = 0;
  78. static sqlite3_stmt *statements[MAX_OPEN_STATEMENTS];
  79. if (unlikely(!res)) {
  80. while (idx > 0) {
  81. int rc;
  82. rc = sqlite3_finalize(statements[--idx]);
  83. if (unlikely(rc != SQLITE_OK))
  84. error_report("Failed to finalize statement during shutdown, rc = %d", rc);
  85. }
  86. return;
  87. }
  88. if (unlikely(idx == MAX_OPEN_STATEMENTS))
  89. return;
  90. statements[idx++] = res;
  91. }
  92. int prepare_statement(sqlite3 *database, char *query, sqlite3_stmt **statement) {
  93. int rc = sqlite3_prepare_v2(database, query, -1, statement, 0);
  94. if (likely(rc == SQLITE_OK))
  95. add_stmt_to_list(*statement);
  96. return rc;
  97. }
  98. /*
  99. * Store a chart or dimension UUID in chart_active or dimension_active
  100. * The statement that will be prepared determines that
  101. */
  102. static int store_active_uuid_object(sqlite3_stmt **res, char *statement, uuid_t *uuid)
  103. {
  104. int rc;
  105. // Check if we should need to prepare the statement
  106. if (!*res) {
  107. rc = prepare_statement(db_meta, statement, res);
  108. if (unlikely(rc != SQLITE_OK)) {
  109. error_report("Failed to prepare statement to store active object, rc = %d", rc);
  110. return rc;
  111. }
  112. }
  113. rc = sqlite3_bind_blob(*res, 1, uuid, sizeof(*uuid), SQLITE_STATIC);
  114. if (unlikely(rc != SQLITE_OK))
  115. error_report("Failed to bind input parameter to store active object, rc = %d", rc);
  116. else
  117. rc = execute_insert(*res);
  118. return rc;
  119. }
  120. /*
  121. * Marks a chart with UUID as active
  122. * Input: UUID
  123. */
  124. void store_active_chart(uuid_t *chart_uuid)
  125. {
  126. static __thread sqlite3_stmt *res = NULL;
  127. int rc;
  128. if (unlikely(!db_meta)) {
  129. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  130. error_report("Database has not been initialized");
  131. return;
  132. }
  133. if (unlikely(!chart_uuid))
  134. return;
  135. rc = store_active_uuid_object(&res, SQL_STORE_ACTIVE_CHART, chart_uuid);
  136. if (rc != SQLITE_DONE)
  137. error_report("Failed to store active chart, rc = %d", rc);
  138. rc = sqlite3_reset(res);
  139. if (unlikely(rc != SQLITE_OK))
  140. error_report("Failed to finalize statement in store active chart, rc = %d", rc);
  141. return;
  142. }
  143. /*
  144. * Marks a dimension with UUID as active
  145. * Input: UUID
  146. */
  147. void store_active_dimension(uuid_t *dimension_uuid)
  148. {
  149. static __thread sqlite3_stmt *res = NULL;
  150. int rc;
  151. if (unlikely(!db_meta)) {
  152. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  153. error_report("Database has not been initialized");
  154. return;
  155. }
  156. if (unlikely(!dimension_uuid))
  157. return;
  158. rc = store_active_uuid_object(&res, SQL_STORE_ACTIVE_DIMENSION, dimension_uuid);
  159. if (rc != SQLITE_DONE)
  160. error_report("Failed to store active dimension, rc = %d", rc);
  161. rc = sqlite3_reset(res);
  162. if (unlikely(rc != SQLITE_OK))
  163. error_report("Failed to finalize statement in store active dimension, rc = %d", rc);
  164. return;
  165. }
  166. static int check_table_integrity_cb(void *data, int argc, char **argv, char **column)
  167. {
  168. int *status = data;
  169. UNUSED(argc);
  170. UNUSED(column);
  171. info("---> %s", argv[0]);
  172. *status = (strcmp(argv[0], "ok") != 0);
  173. return 0;
  174. }
  175. static int check_table_integrity(char *table)
  176. {
  177. int status = 0;
  178. char *err_msg = NULL;
  179. char wstr[255];
  180. if (table) {
  181. info("Checking table %s", table);
  182. snprintfz(wstr, 254, "PRAGMA integrity_check(%s);", table);
  183. }
  184. else {
  185. info("Checking entire database");
  186. strcpy(wstr,"PRAGMA integrity_check;");
  187. }
  188. int rc = sqlite3_exec(db_meta, wstr, check_table_integrity_cb, (void *) &status, &err_msg);
  189. if (rc != SQLITE_OK) {
  190. error_report("SQLite error during database integrity check for %s, rc = %d (%s)",
  191. table ? table : "the entire database", rc, err_msg);
  192. sqlite3_free(err_msg);
  193. }
  194. return status;
  195. }
  196. const char *rebuild_chart_commands[] = {
  197. "BEGIN TRANSACTION; ",
  198. "DROP INDEX IF EXISTS ind_c1;" ,
  199. "DROP TABLE IF EXISTS chart_backup; " ,
  200. "CREATE TABLE chart_backup AS SELECT * FROM chart; " ,
  201. "DROP TABLE chart; ",
  202. "CREATE TABLE IF NOT EXISTS chart(chart_id blob PRIMARY KEY, host_id blob, type text, id text, "
  203. "name text, family text, context text, title text, unit text, plugin text, "
  204. "module text, priority int, update_every int, chart_type int, memory_mode int, history_entries); ",
  205. "INSERT INTO chart SELECT DISTINCT * FROM chart_backup; ",
  206. "DROP TABLE chart_backup; " ,
  207. "CREATE INDEX IF NOT EXISTS ind_c1 on chart (host_id, id, type, name);",
  208. "COMMIT TRANSACTION;",
  209. NULL
  210. };
  211. static void rebuild_chart()
  212. {
  213. int rc;
  214. char *err_msg = NULL;
  215. info("Rebuilding chart table");
  216. for (int i = 0; rebuild_chart_commands[i]; i++) {
  217. info("Executing %s", rebuild_chart_commands[i]);
  218. rc = sqlite3_exec(db_meta, rebuild_chart_commands[i], 0, 0, &err_msg);
  219. if (rc != SQLITE_OK) {
  220. error_report("SQLite error during database setup, rc = %d (%s)", rc, err_msg);
  221. error_report("SQLite failed statement %s", rebuild_chart_commands[i]);
  222. sqlite3_free(err_msg);
  223. }
  224. }
  225. return;
  226. }
  227. const char *rebuild_dimension_commands[] = {
  228. "BEGIN TRANSACTION; ",
  229. "DROP INDEX IF EXISTS ind_d1;" ,
  230. "DROP TABLE IF EXISTS dimension_backup; " ,
  231. "CREATE TABLE dimension_backup AS SELECT * FROM dimension; " ,
  232. "DROP TABLE dimension; " ,
  233. "CREATE TABLE IF NOT EXISTS dimension(dim_id blob PRIMARY KEY, chart_id blob, id text, name text, "
  234. "multiplier int, divisor int , algorithm int, options text);" ,
  235. "INSERT INTO dimension SELECT distinct * FROM dimension_backup; " ,
  236. "DROP TABLE dimension_backup; " ,
  237. "CREATE INDEX IF NOT EXISTS ind_d1 on dimension (chart_id, id, name);",
  238. "COMMIT TRANSACTION;",
  239. NULL
  240. };
  241. void rebuild_dimension()
  242. {
  243. int rc;
  244. char *err_msg = NULL;
  245. info("Rebuilding dimension table");
  246. for (int i = 0; rebuild_dimension_commands[i]; i++) {
  247. info("Executing %s", rebuild_dimension_commands[i]);
  248. rc = sqlite3_exec(db_meta, rebuild_dimension_commands[i], 0, 0, &err_msg);
  249. if (rc != SQLITE_OK) {
  250. error_report("SQLite error during database setup, rc = %d (%s)", rc, err_msg);
  251. error_report("SQLite failed statement %s", rebuild_dimension_commands[i]);
  252. sqlite3_free(err_msg);
  253. }
  254. }
  255. return;
  256. }
  257. static int attempt_database_fix()
  258. {
  259. info("Closing database and attempting to fix it");
  260. int rc = sqlite3_close(db_meta);
  261. if (rc != SQLITE_OK)
  262. error_report("Failed to close database, rc = %d", rc);
  263. info("Attempting to fix database");
  264. db_meta = NULL;
  265. return sql_init_database(DB_CHECK_FIX_DB | DB_CHECK_CONT, 0);
  266. }
  267. static int init_database_batch(int rebuild, int init_type, const char *batch[])
  268. {
  269. int rc;
  270. char *err_msg = NULL;
  271. for (int i = 0; batch[i]; i++) {
  272. debug(D_METADATALOG, "Executing %s", batch[i]);
  273. rc = sqlite3_exec(db_meta, batch[i], 0, 0, &err_msg);
  274. if (rc != SQLITE_OK) {
  275. error_report("SQLite error during database %s, rc = %d (%s)", init_type ? "cleanup" : "setup", rc, err_msg);
  276. error_report("SQLite failed statement %s", batch[i]);
  277. sqlite3_free(err_msg);
  278. if (SQLITE_CORRUPT == rc) {
  279. if (!rebuild)
  280. return attempt_database_fix();
  281. rc = check_table_integrity(NULL);
  282. if (rc)
  283. error_report("Databse integrity errors reported");
  284. }
  285. return 1;
  286. }
  287. }
  288. return 0;
  289. }
  290. /*
  291. * Initialize the SQLite database
  292. * Return 0 on success
  293. */
  294. int sql_init_database(db_check_action_type_t rebuild, int memory)
  295. {
  296. char *err_msg = NULL;
  297. char sqlite_database[FILENAME_MAX + 1];
  298. int rc;
  299. if (likely(!memory))
  300. snprintfz(sqlite_database, FILENAME_MAX, "%s/netdata-meta.db", netdata_configured_cache_dir);
  301. else
  302. strcpy(sqlite_database, ":memory:");
  303. rc = sqlite3_open(sqlite_database, &db_meta);
  304. if (rc != SQLITE_OK) {
  305. error_report("Failed to initialize database at %s, due to \"%s\"", sqlite_database, sqlite3_errstr(rc));
  306. sqlite3_close(db_meta);
  307. db_meta = NULL;
  308. return 1;
  309. }
  310. if (rebuild & (DB_CHECK_INTEGRITY | DB_CHECK_FIX_DB)) {
  311. int errors_detected = 0;
  312. if (!(rebuild & DB_CHECK_CONT))
  313. info("Running database check on %s", sqlite_database);
  314. if (check_table_integrity("chart")) {
  315. errors_detected++;
  316. if (rebuild & DB_CHECK_FIX_DB)
  317. rebuild_chart();
  318. else
  319. error_report("Errors reported -- run with -W sqlite-fix");
  320. }
  321. if (check_table_integrity("dimension")) {
  322. errors_detected++;
  323. if (rebuild & DB_CHECK_FIX_DB)
  324. rebuild_dimension();
  325. else
  326. error_report("Errors reported -- run with -W sqlite-fix");
  327. }
  328. if (!errors_detected) {
  329. if (check_table_integrity(NULL))
  330. error_report("Errors reported");
  331. }
  332. }
  333. if (rebuild & DB_CHECK_RECLAIM_SPACE) {
  334. if (!(rebuild & DB_CHECK_CONT))
  335. info("Reclaiming space of %s", sqlite_database);
  336. rc = sqlite3_exec(db_meta, "VACUUM;", 0, 0, &err_msg);
  337. if (rc != SQLITE_OK) {
  338. error_report("Failed to execute VACUUM rc = %d (%s)", rc, err_msg);
  339. sqlite3_free(err_msg);
  340. }
  341. }
  342. if (rebuild && !(rebuild & DB_CHECK_CONT))
  343. return 1;
  344. info("SQLite database %s initialization", sqlite_database);
  345. char buf[1024 + 1] = "";
  346. const char *list[2] = { buf, NULL };
  347. // https://www.sqlite.org/pragma.html#pragma_auto_vacuum
  348. // PRAGMA schema.auto_vacuum = 0 | NONE | 1 | FULL | 2 | INCREMENTAL;
  349. snprintfz(buf, 1024, "PRAGMA auto_vacuum=%s;", config_get(CONFIG_SECTION_SQLITE, "auto vacuum", "INCREMENTAL"));
  350. if(init_database_batch(rebuild, 0, list)) return 1;
  351. // https://www.sqlite.org/pragma.html#pragma_synchronous
  352. // PRAGMA schema.synchronous = 0 | OFF | 1 | NORMAL | 2 | FULL | 3 | EXTRA;
  353. snprintfz(buf, 1024, "PRAGMA synchronous=%s;", config_get(CONFIG_SECTION_SQLITE, "synchronous", "NORMAL"));
  354. if(init_database_batch(rebuild, 0, list)) return 1;
  355. // https://www.sqlite.org/pragma.html#pragma_journal_mode
  356. // PRAGMA schema.journal_mode = DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF
  357. snprintfz(buf, 1024, "PRAGMA journal_mode=%s;", config_get(CONFIG_SECTION_SQLITE, "journal mode", "WAL"));
  358. if(init_database_batch(rebuild, 0, list)) return 1;
  359. // https://www.sqlite.org/pragma.html#pragma_temp_store
  360. // PRAGMA temp_store = 0 | DEFAULT | 1 | FILE | 2 | MEMORY;
  361. snprintfz(buf, 1024, "PRAGMA temp_store=%s;", config_get(CONFIG_SECTION_SQLITE, "temp store", "MEMORY"));
  362. if(init_database_batch(rebuild, 0, list)) return 1;
  363. // https://www.sqlite.org/pragma.html#pragma_journal_size_limit
  364. // PRAGMA schema.journal_size_limit = N ;
  365. snprintfz(buf, 1024, "PRAGMA journal_size_limit=%lld;", config_get_number(CONFIG_SECTION_SQLITE, "journal size limit", 16777216));
  366. if(init_database_batch(rebuild, 0, list)) return 1;
  367. // https://www.sqlite.org/pragma.html#pragma_cache_size
  368. // PRAGMA schema.cache_size = pages;
  369. // PRAGMA schema.cache_size = -kibibytes;
  370. snprintfz(buf, 1024, "PRAGMA cache_size=%lld;", config_get_number(CONFIG_SECTION_SQLITE, "cache size", -2000));
  371. if(init_database_batch(rebuild, 0, list)) return 1;
  372. if (init_database_batch(rebuild, 0, &database_config[0]))
  373. return 1;
  374. if (init_database_batch(rebuild, 0, &database_cleanup[0]))
  375. return 1;
  376. fatal_assert(0 == uv_mutex_init(&sqlite_transaction_lock));
  377. info("SQLite database initialization completed");
  378. return 0;
  379. }
  380. /*
  381. * Close the sqlite database
  382. */
  383. void sql_close_database(void)
  384. {
  385. int rc;
  386. if (unlikely(!db_meta))
  387. return;
  388. info("Closing SQLite database");
  389. add_stmt_to_list(NULL);
  390. rc = sqlite3_close_v2(db_meta);
  391. if (unlikely(rc != SQLITE_OK))
  392. error_report("Error %d while closing the SQLite database, %s", rc, sqlite3_errstr(rc));
  393. return;
  394. }
  395. #define FIND_UUID_TYPE "select 1 from host where host_id = @uuid union select 2 from chart where chart_id = @uuid union select 3 from dimension where dim_id = @uuid;"
  396. int find_uuid_type(uuid_t *uuid)
  397. {
  398. static __thread sqlite3_stmt *res = NULL;
  399. int rc;
  400. int uuid_type = 3;
  401. if (unlikely(!res)) {
  402. rc = prepare_statement(db_meta, FIND_UUID_TYPE, &res);
  403. if (rc != SQLITE_OK) {
  404. error_report("Failed to bind prepare statement to find UUID type in the database");
  405. return 0;
  406. }
  407. }
  408. rc = sqlite3_bind_blob(res, 1, uuid, sizeof(*uuid), SQLITE_STATIC);
  409. if (unlikely(rc != SQLITE_OK))
  410. goto bind_fail;
  411. rc = sqlite3_step(res);
  412. if (likely(rc == SQLITE_ROW))
  413. uuid_type = sqlite3_column_int(res, 0);
  414. rc = sqlite3_reset(res);
  415. if (unlikely(rc != SQLITE_OK))
  416. error_report("Failed to reset statement during find uuid type, rc = %d", rc);
  417. return uuid_type;
  418. bind_fail:
  419. return 0;
  420. }
  421. int find_dimension_uuid(RRDSET *st, RRDDIM *rd, uuid_t *store_uuid)
  422. {
  423. static __thread sqlite3_stmt *res = NULL;
  424. int rc;
  425. int status = 1;
  426. if (unlikely(!db_meta) && default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)
  427. return 1;
  428. if (unlikely(!res)) {
  429. rc = prepare_statement(db_meta, SQL_FIND_DIMENSION_UUID, &res);
  430. if (rc != SQLITE_OK) {
  431. error_report("Failed to bind prepare statement to lookup dimension UUID in the database");
  432. return 1;
  433. }
  434. }
  435. rc = sqlite3_bind_blob(res, 1, st->chart_uuid, sizeof(*st->chart_uuid), SQLITE_STATIC);
  436. if (unlikely(rc != SQLITE_OK))
  437. goto bind_fail;
  438. rc = sqlite3_bind_text(res, 2, rd->id, -1, SQLITE_STATIC);
  439. if (unlikely(rc != SQLITE_OK))
  440. goto bind_fail;
  441. rc = sqlite3_bind_text(res, 3, rd->name, -1, SQLITE_STATIC);
  442. if (unlikely(rc != SQLITE_OK))
  443. goto bind_fail;
  444. rc = sqlite3_step(res);
  445. if (likely(rc == SQLITE_ROW)) {
  446. uuid_copy(*store_uuid, *((uuid_t *) sqlite3_column_blob(res, 0)));
  447. status = 0;
  448. }
  449. else {
  450. uuid_generate(*store_uuid);
  451. status = sql_store_dimension(store_uuid, st->chart_uuid, rd->id, rd->name, rd->multiplier, rd->divisor, rd->algorithm);
  452. if (unlikely(status))
  453. error_report("Failed to store dimension metadata in the database");
  454. }
  455. rc = sqlite3_reset(res);
  456. if (unlikely(rc != SQLITE_OK))
  457. error_report("Failed to reset statement find dimension uuid, rc = %d", rc);
  458. return status;
  459. bind_fail:
  460. error_report("Failed to bind input parameter to perform dimension UUID database lookup, rc = %d", rc);
  461. return 1;
  462. }
  463. #define DELETE_DIMENSION_UUID "delete from dimension where dim_id = @uuid;"
  464. void delete_dimension_uuid(uuid_t *dimension_uuid)
  465. {
  466. static __thread sqlite3_stmt *res = NULL;
  467. int rc;
  468. #ifdef NETDATA_INTERNAL_CHECKS
  469. char uuid_str[GUID_LEN + 1];
  470. uuid_unparse_lower(*dimension_uuid, uuid_str);
  471. debug(D_METADATALOG,"Deleting dimension uuid %s", uuid_str);
  472. #endif
  473. if (unlikely(!res)) {
  474. rc = prepare_statement(db_meta, DELETE_DIMENSION_UUID, &res);
  475. if (rc != SQLITE_OK) {
  476. error_report("Failed to prepare statement to delete a dimension uuid");
  477. return;
  478. }
  479. }
  480. rc = sqlite3_bind_blob(res, 1, dimension_uuid, sizeof(*dimension_uuid), SQLITE_STATIC);
  481. if (unlikely(rc != SQLITE_OK))
  482. goto bind_fail;
  483. rc = sqlite3_step(res);
  484. if (unlikely(rc != SQLITE_DONE))
  485. error_report("Failed to delete dimension uuid, rc = %d", rc);
  486. bind_fail:
  487. rc = sqlite3_reset(res);
  488. if (unlikely(rc != SQLITE_OK))
  489. error_report("Failed to reset statement when deleting dimension UUID, rc = %d", rc);
  490. return;
  491. }
  492. /*
  493. * Do a database lookup to find the UUID of a chart
  494. *
  495. */
  496. uuid_t *find_chart_uuid(RRDHOST *host, const char *type, const char *id, const char *name)
  497. {
  498. static __thread sqlite3_stmt *res = NULL;
  499. uuid_t *uuid = NULL;
  500. int rc;
  501. if (unlikely(!db_meta) && default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)
  502. return NULL;
  503. if (unlikely(!res)) {
  504. rc = prepare_statement(db_meta, SQL_FIND_CHART_UUID, &res);
  505. if (rc != SQLITE_OK) {
  506. error_report("Failed to prepare statement to lookup chart UUID in the database");
  507. return NULL;
  508. }
  509. }
  510. rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
  511. if (unlikely(rc != SQLITE_OK))
  512. goto bind_fail;
  513. rc = sqlite3_bind_text(res, 2, type, -1, SQLITE_STATIC);
  514. if (unlikely(rc != SQLITE_OK))
  515. goto bind_fail;
  516. rc = sqlite3_bind_text(res, 3, id, -1, SQLITE_STATIC);
  517. if (unlikely(rc != SQLITE_OK))
  518. goto bind_fail;
  519. rc = sqlite3_bind_text(res, 4, name ? name : id, -1, SQLITE_STATIC);
  520. if (unlikely(rc != SQLITE_OK))
  521. goto bind_fail;
  522. rc = sqlite3_step(res);
  523. if (likely(rc == SQLITE_ROW)) {
  524. uuid = mallocz(sizeof(uuid_t));
  525. uuid_copy(*uuid, sqlite3_column_blob(res, 0));
  526. }
  527. rc = sqlite3_reset(res);
  528. if (unlikely(rc != SQLITE_OK))
  529. error_report("Failed to reset statement when searching for a chart UUID, rc = %d", rc);
  530. #ifdef NETDATA_INTERNAL_CHECKS
  531. char uuid_str[GUID_LEN + 1];
  532. if (likely(uuid)) {
  533. uuid_unparse_lower(*uuid, uuid_str);
  534. debug(D_METADATALOG, "Found UUID %s for chart %s.%s", uuid_str, type, name ? name : id);
  535. }
  536. else
  537. debug(D_METADATALOG, "UUID not found for chart %s.%s", type, name ? name : id);
  538. #endif
  539. return uuid;
  540. bind_fail:
  541. error_report("Failed to bind input parameter to perform chart UUID database lookup, rc = %d", rc);
  542. rc = sqlite3_reset(res);
  543. if (unlikely(rc != SQLITE_OK))
  544. error_report("Failed to reset statement when searching for a chart UUID, rc = %d", rc);
  545. return NULL;
  546. }
  547. int update_chart_metadata(uuid_t *chart_uuid, RRDSET *st, const char *id, const char *name)
  548. {
  549. int rc;
  550. if (unlikely(!db_meta) && default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)
  551. return 0;
  552. rc = sql_store_chart(
  553. chart_uuid, &st->rrdhost->host_uuid, st->type, id, name, st->family, st->context, st->title, st->units, st->plugin_name,
  554. st->module_name, st->priority, st->update_every, st->chart_type, st->rrd_memory_mode, st->entries);
  555. return rc;
  556. }
  557. uuid_t *create_chart_uuid(RRDSET *st, const char *id, const char *name)
  558. {
  559. uuid_t *uuid = NULL;
  560. int rc;
  561. uuid = mallocz(sizeof(uuid_t));
  562. uuid_generate(*uuid);
  563. #ifdef NETDATA_INTERNAL_CHECKS
  564. char uuid_str[GUID_LEN + 1];
  565. uuid_unparse_lower(*uuid, uuid_str);
  566. debug(D_METADATALOG,"Generating uuid [%s] for chart %s under host %s", uuid_str, st->id, st->rrdhost->hostname);
  567. #endif
  568. rc = update_chart_metadata(uuid, st, id, name);
  569. if (unlikely(rc))
  570. error_report("Failed to store chart metadata in the database");
  571. return uuid;
  572. }
  573. // Functions to create host, chart, dimension in the database
  574. int sql_store_host(
  575. uuid_t *host_uuid, const char *hostname, const char *registry_hostname, int update_every, const char *os,
  576. const char *tzone, const char *tags)
  577. {
  578. static __thread sqlite3_stmt *res = NULL;
  579. int rc;
  580. if (unlikely(!db_meta)) {
  581. if (default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)
  582. return 0;
  583. error_report("Database has not been initialized");
  584. return 1;
  585. }
  586. if (unlikely((!res))) {
  587. rc = prepare_statement(db_meta, SQL_STORE_HOST, &res);
  588. if (unlikely(rc != SQLITE_OK)) {
  589. error_report("Failed to prepare statement to store host, rc = %d", rc);
  590. return 1;
  591. }
  592. }
  593. rc = sqlite3_bind_blob(res, 1, host_uuid, sizeof(*host_uuid), SQLITE_STATIC);
  594. if (unlikely(rc != SQLITE_OK))
  595. goto bind_fail;
  596. rc = sqlite3_bind_text(res, 2, hostname, -1, SQLITE_STATIC);
  597. if (unlikely(rc != SQLITE_OK))
  598. goto bind_fail;
  599. rc = sqlite3_bind_text(res, 3, registry_hostname, -1, SQLITE_STATIC);
  600. if (unlikely(rc != SQLITE_OK))
  601. goto bind_fail;
  602. rc = sqlite3_bind_int(res, 4, update_every);
  603. if (unlikely(rc != SQLITE_OK))
  604. goto bind_fail;
  605. rc = sqlite3_bind_text(res, 5, os, -1, SQLITE_STATIC);
  606. if (unlikely(rc != SQLITE_OK))
  607. goto bind_fail;
  608. rc = sqlite3_bind_text(res, 6, tzone, -1, SQLITE_STATIC);
  609. if (unlikely(rc != SQLITE_OK))
  610. goto bind_fail;
  611. rc = sqlite3_bind_text(res, 7, tags, -1, SQLITE_STATIC);
  612. if (unlikely(rc != SQLITE_OK))
  613. goto bind_fail;
  614. int store_rc = sqlite3_step(res);
  615. if (unlikely(store_rc != SQLITE_DONE))
  616. error_report("Failed to store host %s, rc = %d", hostname, rc);
  617. rc = sqlite3_reset(res);
  618. if (unlikely(rc != SQLITE_OK))
  619. error_report("Failed to reset statement to store host %s, rc = %d", hostname, rc);
  620. return !(store_rc == SQLITE_DONE);
  621. bind_fail:
  622. error_report("Failed to bind parameter to store host %s, rc = %d", hostname, rc);
  623. rc = sqlite3_reset(res);
  624. if (unlikely(rc != SQLITE_OK))
  625. error_report("Failed to reset statement to store host %s, rc = %d", hostname, rc);
  626. return 1;
  627. }
  628. /*
  629. * Store a chart in the database
  630. */
  631. int sql_store_chart(
  632. uuid_t *chart_uuid, uuid_t *host_uuid, const char *type, const char *id, const char *name, const char *family,
  633. const char *context, const char *title, const char *units, const char *plugin, const char *module, long priority,
  634. int update_every, int chart_type, int memory_mode, long history_entries)
  635. {
  636. static __thread sqlite3_stmt *res = NULL;
  637. int rc, param = 0;
  638. if (unlikely(!db_meta)) {
  639. if (default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)
  640. return 0;
  641. error_report("Database has not been initialized");
  642. return 1;
  643. }
  644. if (unlikely(!res)) {
  645. rc = prepare_statement(db_meta, SQL_STORE_CHART, &res);
  646. if (unlikely(rc != SQLITE_OK)) {
  647. error_report("Failed to prepare statement to store chart, rc = %d", rc);
  648. return 1;
  649. }
  650. }
  651. param++;
  652. rc = sqlite3_bind_blob(res, 1, chart_uuid, sizeof(*chart_uuid), SQLITE_STATIC);
  653. if (unlikely(rc != SQLITE_OK))
  654. goto bind_fail;
  655. param++;
  656. rc = sqlite3_bind_blob(res, 2, host_uuid, sizeof(*host_uuid), SQLITE_STATIC);
  657. if (unlikely(rc != SQLITE_OK))
  658. goto bind_fail;
  659. param++;
  660. rc = sqlite3_bind_text(res, 3, type, -1, SQLITE_STATIC);
  661. if (unlikely(rc != SQLITE_OK))
  662. goto bind_fail;
  663. param++;
  664. rc = sqlite3_bind_text(res, 4, id, -1, SQLITE_STATIC);
  665. if (unlikely(rc != SQLITE_OK))
  666. goto bind_fail;
  667. param++;
  668. if (name && *name)
  669. rc = sqlite3_bind_text(res, 5, name, -1, SQLITE_STATIC);
  670. else
  671. rc = sqlite3_bind_null(res, 5);
  672. if (unlikely(rc != SQLITE_OK))
  673. goto bind_fail;
  674. param++;
  675. rc = sqlite3_bind_text(res, 6, family, -1, SQLITE_STATIC);
  676. if (unlikely(rc != SQLITE_OK))
  677. goto bind_fail;
  678. param++;
  679. rc = sqlite3_bind_text(res, 7, context, -1, SQLITE_STATIC);
  680. if (unlikely(rc != SQLITE_OK))
  681. goto bind_fail;
  682. param++;
  683. rc = sqlite3_bind_text(res, 8, title, -1, SQLITE_STATIC);
  684. if (unlikely(rc != SQLITE_OK))
  685. goto bind_fail;
  686. param++;
  687. rc = sqlite3_bind_text(res, 9, units, -1, SQLITE_STATIC);
  688. if (unlikely(rc != SQLITE_OK))
  689. goto bind_fail;
  690. param++;
  691. rc = sqlite3_bind_text(res, 10, plugin, -1, SQLITE_STATIC);
  692. if (unlikely(rc != SQLITE_OK))
  693. goto bind_fail;
  694. param++;
  695. rc = sqlite3_bind_text(res, 11, module, -1, SQLITE_STATIC);
  696. if (unlikely(rc != SQLITE_OK))
  697. goto bind_fail;
  698. param++;
  699. rc = sqlite3_bind_int(res, 12, priority);
  700. if (unlikely(rc != SQLITE_OK))
  701. goto bind_fail;
  702. param++;
  703. rc = sqlite3_bind_int(res, 13, update_every);
  704. if (unlikely(rc != SQLITE_OK))
  705. goto bind_fail;
  706. param++;
  707. rc = sqlite3_bind_int(res, 14, chart_type);
  708. if (unlikely(rc != SQLITE_OK))
  709. goto bind_fail;
  710. param++;
  711. rc = sqlite3_bind_int(res, 15, memory_mode);
  712. if (unlikely(rc != SQLITE_OK))
  713. goto bind_fail;
  714. param++;
  715. rc = sqlite3_bind_int(res, 16, history_entries);
  716. if (unlikely(rc != SQLITE_OK))
  717. goto bind_fail;
  718. rc = execute_insert(res);
  719. if (unlikely(rc != SQLITE_DONE))
  720. error_report("Failed to store chart, rc = %d", rc);
  721. rc = sqlite3_reset(res);
  722. if (unlikely(rc != SQLITE_OK))
  723. error_report("Failed to reset statement in chart store function, rc = %d", rc);
  724. return 0;
  725. bind_fail:
  726. error_report("Failed to bind parameter %d to store chart, rc = %d", param, rc);
  727. rc = sqlite3_reset(res);
  728. if (unlikely(rc != SQLITE_OK))
  729. error_report("Failed to reset statement in chart store function, rc = %d", rc);
  730. return 1;
  731. }
  732. /*
  733. * Store a dimension
  734. */
  735. int sql_store_dimension(
  736. uuid_t *dim_uuid, uuid_t *chart_uuid, const char *id, const char *name, collected_number multiplier,
  737. collected_number divisor, int algorithm)
  738. {
  739. static __thread sqlite3_stmt *res = NULL;
  740. int rc;
  741. if (unlikely(!db_meta)) {
  742. if (default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)
  743. return 0;
  744. error_report("Database has not been initialized");
  745. return 1;
  746. }
  747. if (unlikely(!res)) {
  748. rc = prepare_statement(db_meta, SQL_STORE_DIMENSION, &res);
  749. if (unlikely(rc != SQLITE_OK)) {
  750. error_report("Failed to prepare statement to store dimension, rc = %d", rc);
  751. return 1;
  752. }
  753. }
  754. rc = sqlite3_bind_blob(res, 1, dim_uuid, sizeof(*dim_uuid), SQLITE_STATIC);
  755. if (unlikely(rc != SQLITE_OK))
  756. goto bind_fail;
  757. rc = sqlite3_bind_blob(res, 2, chart_uuid, sizeof(*chart_uuid), SQLITE_STATIC);
  758. if (unlikely(rc != SQLITE_OK))
  759. goto bind_fail;
  760. rc = sqlite3_bind_text(res, 3, id, -1, SQLITE_STATIC);
  761. if (unlikely(rc != SQLITE_OK))
  762. goto bind_fail;
  763. rc = sqlite3_bind_text(res, 4, name, -1, SQLITE_STATIC);
  764. if (unlikely(rc != SQLITE_OK))
  765. goto bind_fail;
  766. rc = sqlite3_bind_int(res, 5, multiplier);
  767. if (unlikely(rc != SQLITE_OK))
  768. goto bind_fail;
  769. rc = sqlite3_bind_int(res, 6, divisor);
  770. if (unlikely(rc != SQLITE_OK))
  771. goto bind_fail;
  772. rc = sqlite3_bind_int(res, 7, algorithm);
  773. if (unlikely(rc != SQLITE_OK))
  774. goto bind_fail;
  775. rc = execute_insert(res);
  776. if (unlikely(rc != SQLITE_DONE))
  777. error_report("Failed to store dimension, rc = %d", rc);
  778. rc = sqlite3_reset(res);
  779. if (unlikely(rc != SQLITE_OK))
  780. error_report("Failed to reset statement in store dimension, rc = %d", rc);
  781. return 0;
  782. bind_fail:
  783. error_report("Failed to bind parameter to store dimension, rc = %d", rc);
  784. rc = sqlite3_reset(res);
  785. if (unlikely(rc != SQLITE_OK))
  786. error_report("Failed to reset statement in store dimension, rc = %d", rc);
  787. return 1;
  788. }
  789. /*
  790. * Store set option for a dimension
  791. */
  792. int sql_set_dimension_option(uuid_t *dim_uuid, char *option)
  793. {
  794. sqlite3_stmt *res = NULL;
  795. int rc;
  796. if (unlikely(!db_meta)) {
  797. if (default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)
  798. return 0;
  799. error_report("Database has not been initialized");
  800. return 1;
  801. }
  802. rc = sqlite3_prepare_v2(db_meta, "UPDATE dimension SET options = @options WHERE dim_id = @dim_id", -1, &res, 0);
  803. if (unlikely(rc != SQLITE_OK)) {
  804. error_report("Failed to prepare statement to update dimension options");
  805. return 0;
  806. };
  807. rc = sqlite3_bind_blob(res, 2, dim_uuid, sizeof(*dim_uuid), SQLITE_STATIC);
  808. if (unlikely(rc != SQLITE_OK))
  809. goto bind_fail;
  810. if (!option || !strcmp(option,"unhide"))
  811. rc = sqlite3_bind_null(res, 1);
  812. else
  813. rc = sqlite3_bind_text(res, 1, option, -1, SQLITE_STATIC);
  814. if (unlikely(rc != SQLITE_OK))
  815. goto bind_fail;
  816. rc = execute_insert(res);
  817. if (unlikely(rc != SQLITE_DONE))
  818. error_report("Failed to update dimension option, rc = %d", rc);
  819. bind_fail:
  820. rc = sqlite3_finalize(res);
  821. if (unlikely(rc != SQLITE_OK))
  822. error_report("Failed to finalize statement in update dimension options, rc = %d", rc);
  823. return 0;
  824. }
  825. //
  826. // Support for archived charts
  827. //
  828. #define SELECT_DIMENSION "select d.id, d.name from dimension d where d.chart_id = @chart_uuid;"
  829. void sql_rrdim2json(sqlite3_stmt *res_dim, uuid_t *chart_uuid, BUFFER *wb, size_t *dimensions_count)
  830. {
  831. int rc;
  832. rc = sqlite3_bind_blob(res_dim, 1, chart_uuid, sizeof(*chart_uuid), SQLITE_STATIC);
  833. if (rc != SQLITE_OK)
  834. return;
  835. int dimensions = 0;
  836. buffer_sprintf(wb, "\t\t\t\"dimensions\": {\n");
  837. while (sqlite3_step(res_dim) == SQLITE_ROW) {
  838. if (dimensions)
  839. buffer_strcat(wb, ",\n\t\t\t\t\"");
  840. else
  841. buffer_strcat(wb, "\t\t\t\t\"");
  842. buffer_strcat_jsonescape(wb, (const char *) sqlite3_column_text(res_dim, 0));
  843. buffer_strcat(wb, "\": { \"name\": \"");
  844. buffer_strcat_jsonescape(wb, (const char *) sqlite3_column_text(res_dim, 1));
  845. buffer_strcat(wb, "\" }");
  846. dimensions++;
  847. }
  848. *dimensions_count += dimensions;
  849. buffer_sprintf(wb, "\n\t\t\t}");
  850. }
  851. #define SELECT_CHART "select chart_id, id, name, type, family, context, title, priority, plugin, " \
  852. "module, unit, chart_type, update_every from chart " \
  853. "where host_id = @host_uuid and chart_id not in (select chart_id from chart_active) order by chart_id asc;"
  854. void sql_rrdset2json(RRDHOST *host, BUFFER *wb)
  855. {
  856. // time_t first_entry_t = 0; //= rrdset_first_entry_t(st);
  857. // time_t last_entry_t = 0; //rrdset_last_entry_t(st);
  858. static char *custom_dashboard_info_js_filename = NULL;
  859. int rc;
  860. sqlite3_stmt *res_chart = NULL;
  861. sqlite3_stmt *res_dim = NULL;
  862. time_t now = now_realtime_sec();
  863. rc = sqlite3_prepare_v2(db_meta, SELECT_CHART, -1, &res_chart, 0);
  864. if (unlikely(rc != SQLITE_OK)) {
  865. error_report("Failed to prepare statement to fetch host archived charts");
  866. return;
  867. }
  868. rc = sqlite3_bind_blob(res_chart, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
  869. if (unlikely(rc != SQLITE_OK)) {
  870. error_report("Failed to bind host parameter to fetch archived charts");
  871. goto failed;
  872. }
  873. rc = sqlite3_prepare_v2(db_meta, SELECT_DIMENSION, -1, &res_dim, 0);
  874. if (unlikely(rc != SQLITE_OK)) {
  875. error_report("Failed to prepare statement to fetch chart archived dimensions");
  876. goto failed;
  877. };
  878. if(unlikely(!custom_dashboard_info_js_filename))
  879. custom_dashboard_info_js_filename = config_get(CONFIG_SECTION_WEB, "custom dashboard_info.js", "");
  880. buffer_sprintf(wb, "{\n"
  881. "\t\"hostname\": \"%s\""
  882. ",\n\t\"version\": \"%s\""
  883. ",\n\t\"release_channel\": \"%s\""
  884. ",\n\t\"os\": \"%s\""
  885. ",\n\t\"timezone\": \"%s\""
  886. ",\n\t\"update_every\": %d"
  887. ",\n\t\"history\": %ld"
  888. ",\n\t\"memory_mode\": \"%s\""
  889. ",\n\t\"custom_info\": \"%s\""
  890. ",\n\t\"charts\": {"
  891. , host->hostname
  892. , host->program_version
  893. , get_release_channel()
  894. , host->os
  895. , host->timezone
  896. , host->rrd_update_every
  897. , host->rrd_history_entries
  898. , rrd_memory_mode_name(host->rrd_memory_mode)
  899. , custom_dashboard_info_js_filename
  900. );
  901. size_t c = 0;
  902. size_t dimensions = 0;
  903. while (sqlite3_step(res_chart) == SQLITE_ROW) {
  904. char id[512];
  905. sprintf(id, "%s.%s", sqlite3_column_text(res_chart, 3), sqlite3_column_text(res_chart, 1));
  906. RRDSET *st = rrdset_find(host, id);
  907. if (st && !rrdset_flag_check(st, RRDSET_FLAG_ARCHIVED))
  908. continue;
  909. if (c)
  910. buffer_strcat(wb, ",\n\t\t\"");
  911. else
  912. buffer_strcat(wb, "\n\t\t\"");
  913. c++;
  914. buffer_strcat(wb, id);
  915. buffer_strcat(wb, "\": ");
  916. buffer_sprintf(
  917. wb,
  918. "\t\t{\n"
  919. "\t\t\t\"id\": \"%s\",\n"
  920. "\t\t\t\"name\": \"%s\",\n"
  921. "\t\t\t\"type\": \"%s\",\n"
  922. "\t\t\t\"family\": \"%s\",\n"
  923. "\t\t\t\"context\": \"%s\",\n"
  924. "\t\t\t\"title\": \"%s (%s)\",\n"
  925. "\t\t\t\"priority\": %ld,\n"
  926. "\t\t\t\"plugin\": \"%s\",\n"
  927. "\t\t\t\"module\": \"%s\",\n"
  928. "\t\t\t\"enabled\": %s,\n"
  929. "\t\t\t\"units\": \"%s\",\n"
  930. "\t\t\t\"data_url\": \"/api/v1/data?chart=%s\",\n"
  931. "\t\t\t\"chart_type\": \"%s\",\n",
  932. id //sqlite3_column_text(res_chart, 1)
  933. ,
  934. id // sqlite3_column_text(res_chart, 2)
  935. ,
  936. sqlite3_column_text(res_chart, 3), sqlite3_column_text(res_chart, 4), sqlite3_column_text(res_chart, 5),
  937. sqlite3_column_text(res_chart, 6), id //sqlite3_column_text(res_chart, 2)
  938. ,
  939. (long ) sqlite3_column_int(res_chart, 7),
  940. (const char *) sqlite3_column_text(res_chart, 8) ? (const char *) sqlite3_column_text(res_chart, 8) : (char *) "",
  941. (const char *) sqlite3_column_text(res_chart, 9) ? (const char *) sqlite3_column_text(res_chart, 9) : (char *) "", (char *) "false",
  942. (const char *) sqlite3_column_text(res_chart, 10), id //sqlite3_column_text(res_chart, 2)
  943. ,
  944. rrdset_type_name(sqlite3_column_int(res_chart, 11)));
  945. sql_rrdim2json(res_dim, (uuid_t *) sqlite3_column_blob(res_chart, 0), wb, &dimensions);
  946. rc = sqlite3_reset(res_dim);
  947. if (unlikely(rc != SQLITE_OK))
  948. error_report("Failed to reset the prepared statement when reading archived chart dimensions");
  949. buffer_strcat(wb, "\n\t\t}");
  950. }
  951. buffer_sprintf(wb
  952. , "\n\t}"
  953. ",\n\t\"charts_count\": %zu"
  954. ",\n\t\"dimensions_count\": %zu"
  955. ",\n\t\"alarms_count\": %zu"
  956. ",\n\t\"rrd_memory_bytes\": %zu"
  957. ",\n\t\"hosts_count\": %zu"
  958. ",\n\t\"hosts\": ["
  959. , c
  960. , dimensions
  961. , (size_t) 0
  962. , (size_t) 0
  963. , rrd_hosts_available
  964. );
  965. if(unlikely(rrd_hosts_available > 1)) {
  966. rrd_rdlock();
  967. size_t found = 0;
  968. RRDHOST *h;
  969. rrdhost_foreach_read(h) {
  970. if(!rrdhost_should_be_removed(h, host, now) && !rrdhost_flag_check(h, RRDHOST_FLAG_ARCHIVED)) {
  971. buffer_sprintf(wb
  972. , "%s\n\t\t{"
  973. "\n\t\t\t\"hostname\": \"%s\""
  974. "\n\t\t}"
  975. , (found > 0) ? "," : ""
  976. , h->hostname
  977. );
  978. found++;
  979. }
  980. }
  981. rrd_unlock();
  982. }
  983. else {
  984. buffer_sprintf(wb
  985. , "\n\t\t{"
  986. "\n\t\t\t\"hostname\": \"%s\""
  987. "\n\t\t}"
  988. , host->hostname
  989. );
  990. }
  991. buffer_sprintf(wb, "\n\t]\n}\n");
  992. rc = sqlite3_finalize(res_dim);
  993. if (unlikely(rc != SQLITE_OK))
  994. error_report("Failed to finalize the prepared statement when reading archived chart dimensions");
  995. failed:
  996. rc = sqlite3_finalize(res_chart);
  997. if (unlikely(rc != SQLITE_OK))
  998. error_report("Failed to finalize the prepared statement when reading archived charts");
  999. return;
  1000. }
  1001. void free_temporary_host(RRDHOST *host)
  1002. {
  1003. if (host) {
  1004. freez(host->hostname);
  1005. freez((char *)host->os);
  1006. freez((char *)host->tags);
  1007. freez((char *)host->timezone);
  1008. freez(host->program_name);
  1009. freez(host->program_version);
  1010. freez(host->registry_hostname);
  1011. freez(host->system_info);
  1012. freez(host);
  1013. }
  1014. }
  1015. #define SELECT_HOST "select host_id, registry_hostname, update_every, os, timezone, tags from host where hostname = @hostname order by rowid desc;"
  1016. #define SELECT_HOST_BY_UUID "select h.host_id, h.registry_hostname, h.update_every, h.os, h.timezone, h.tags from host h, node_instance ni " \
  1017. "where (ni.host_id = @host_id or ni.node_id = @host_id) AND ni.host_id = h.host_id;"
  1018. RRDHOST *sql_create_host_by_uuid(char *hostname)
  1019. {
  1020. int rc;
  1021. RRDHOST *host = NULL;
  1022. uuid_t host_uuid;
  1023. sqlite3_stmt *res = NULL;
  1024. rc = uuid_parse(hostname, host_uuid);
  1025. if (!rc) {
  1026. rc = sqlite3_prepare_v2(db_meta, SELECT_HOST_BY_UUID, -1, &res, 0);
  1027. if (unlikely(rc != SQLITE_OK)) {
  1028. error_report("Failed to prepare statement to fetch host by uuid");
  1029. return NULL;
  1030. }
  1031. rc = sqlite3_bind_blob(res, 1, &host_uuid, sizeof(host_uuid), SQLITE_STATIC);
  1032. if (unlikely(rc != SQLITE_OK)) {
  1033. error_report("Failed to bind host_id parameter to fetch host information");
  1034. goto failed;
  1035. }
  1036. }
  1037. else {
  1038. rc = sqlite3_prepare_v2(db_meta, SELECT_HOST, -1, &res, 0);
  1039. if (unlikely(rc != SQLITE_OK)) {
  1040. error_report("Failed to prepare statement to fetch host by hostname");
  1041. return NULL;
  1042. }
  1043. rc = sqlite3_bind_text(res, 1, hostname, -1, SQLITE_STATIC);
  1044. if (unlikely(rc != SQLITE_OK)) {
  1045. error_report("Failed to bind hostname parameter to fetch host information");
  1046. goto failed;
  1047. }
  1048. }
  1049. rc = sqlite3_step(res);
  1050. if (unlikely(rc != SQLITE_ROW)) {
  1051. error_report("Failed to find hostname %s", hostname);
  1052. goto failed;
  1053. }
  1054. char uuid_str[GUID_LEN + 1];
  1055. uuid_unparse_lower(*((uuid_t *) sqlite3_column_blob(res, 0)), uuid_str);
  1056. host = callocz(1, sizeof(RRDHOST));
  1057. set_host_properties(host, sqlite3_column_int(res, 2), RRD_MEMORY_MODE_DBENGINE, hostname,
  1058. (char *) sqlite3_column_text(res, 1), (const char *) uuid_str,
  1059. (char *) sqlite3_column_text(res, 3), (char *) sqlite3_column_text(res, 5),
  1060. (char *) sqlite3_column_text(res, 4), NULL, 0, NULL, NULL);
  1061. uuid_copy(host->host_uuid, *((uuid_t *) sqlite3_column_blob(res, 0)));
  1062. host->system_info = callocz(1, sizeof(*host->system_info));;
  1063. rrdhost_flag_set(host, RRDHOST_FLAG_ARCHIVED);
  1064. #ifdef ENABLE_DBENGINE
  1065. host->rrdeng_ctx = &multidb_ctx;
  1066. #endif
  1067. failed:
  1068. rc = sqlite3_finalize(res);
  1069. if (unlikely(rc != SQLITE_OK))
  1070. error_report("Failed to finalize the prepared statement when reading host information");
  1071. return host;
  1072. }
  1073. void db_execute(const char *cmd)
  1074. {
  1075. int rc;
  1076. int cnt = 0;
  1077. while (cnt < SQL_MAX_RETRY) {
  1078. char *err_msg;
  1079. rc = sqlite3_exec(db_meta, cmd, 0, 0, &err_msg);
  1080. if (rc != SQLITE_OK) {
  1081. error_report("Failed to execute '%s', rc = %d (%s) -- attempt %d", cmd, rc, err_msg, cnt);
  1082. sqlite3_free(err_msg);
  1083. if (likely(rc == SQLITE_BUSY || rc == SQLITE_LOCKED)) {
  1084. usleep(SQLITE_INSERT_DELAY * USEC_PER_MS);
  1085. }
  1086. else break;
  1087. }
  1088. else
  1089. break;
  1090. ++cnt;
  1091. }
  1092. return;
  1093. }
  1094. void db_lock(void)
  1095. {
  1096. uv_mutex_lock(&sqlite_transaction_lock);
  1097. return;
  1098. }
  1099. void db_unlock(void)
  1100. {
  1101. uv_mutex_unlock(&sqlite_transaction_lock);
  1102. return;
  1103. }
  1104. #define SELECT_MIGRATED_FILE "select 1 from metadata_migration where filename = @path;"
  1105. int file_is_migrated(char *path)
  1106. {
  1107. sqlite3_stmt *res = NULL;
  1108. int rc;
  1109. rc = sqlite3_prepare_v2(db_meta, SELECT_MIGRATED_FILE, -1, &res, 0);
  1110. if (unlikely(rc != SQLITE_OK)) {
  1111. error_report("Failed to prepare statement to fetch host");
  1112. return 0;
  1113. }
  1114. rc = sqlite3_bind_text(res, 1, path, -1, SQLITE_STATIC);
  1115. if (unlikely(rc != SQLITE_OK)) {
  1116. error_report("Failed to bind filename parameter to check migration");
  1117. return 0;
  1118. }
  1119. rc = sqlite3_step(res);
  1120. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  1121. error_report("Failed to finalize the prepared statement when checking if metadata file is migrated");
  1122. return (rc == SQLITE_ROW);
  1123. }
  1124. #define STORE_MIGRATED_FILE "insert or replace into metadata_migration (filename, file_size, date_created) " \
  1125. "values (@file, @size, strftime('%s'));"
  1126. void add_migrated_file(char *path, uint64_t file_size)
  1127. {
  1128. sqlite3_stmt *res = NULL;
  1129. int rc;
  1130. rc = sqlite3_prepare_v2(db_meta, STORE_MIGRATED_FILE, -1, &res, 0);
  1131. if (unlikely(rc != SQLITE_OK)) {
  1132. error_report("Failed to prepare statement to fetch host");
  1133. return;
  1134. }
  1135. rc = sqlite3_bind_text(res, 1, path, -1, SQLITE_STATIC);
  1136. if (unlikely(rc != SQLITE_OK)) {
  1137. error_report("Failed to bind filename parameter to store migration information");
  1138. return;
  1139. }
  1140. rc = sqlite3_bind_int64(res, 2, file_size);
  1141. if (unlikely(rc != SQLITE_OK)) {
  1142. error_report("Failed to bind size parameter to store migration information");
  1143. return;
  1144. }
  1145. rc = execute_insert(res);
  1146. if (unlikely(rc != SQLITE_DONE))
  1147. error_report("Failed to store migrated file, rc = %d", rc);
  1148. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  1149. error_report("Failed to finalize the prepared statement when checking if metadata file is migrated");
  1150. return;
  1151. }
  1152. #define SQL_INS_CHART_LABEL "insert or replace into chart_label " \
  1153. "(chart_id, source_type, label_key, label_value, date_created) " \
  1154. "values (@chart, @source, @label, @value, strftime('%s'));"
  1155. void sql_store_chart_label(uuid_t *chart_uuid, int source_type, char *label, char *value)
  1156. {
  1157. static __thread sqlite3_stmt *res = NULL;
  1158. int rc;
  1159. if (unlikely(!db_meta)) {
  1160. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  1161. error_report("Database has not been initialized");
  1162. return;
  1163. }
  1164. if (unlikely(!res)) {
  1165. rc = prepare_statement(db_meta, SQL_INS_CHART_LABEL, &res);
  1166. if (unlikely(rc != SQLITE_OK)) {
  1167. error_report("Failed to prepare statement store chart labels");
  1168. return;
  1169. }
  1170. }
  1171. rc = sqlite3_bind_blob(res, 1, chart_uuid, sizeof(*chart_uuid), SQLITE_STATIC);
  1172. if (unlikely(rc != SQLITE_OK)) {
  1173. error_report("Failed to bind chart_id parameter to store label information");
  1174. goto failed;
  1175. }
  1176. rc = sqlite3_bind_int(res, 2, source_type);
  1177. if (unlikely(rc != SQLITE_OK)) {
  1178. error_report("Failed to bind type parameter to store label information");
  1179. goto failed;
  1180. }
  1181. rc = sqlite3_bind_text(res, 3, label, -1, SQLITE_STATIC);
  1182. if (unlikely(rc != SQLITE_OK)) {
  1183. error_report("Failed to bind label parameter to store label information");
  1184. goto failed;
  1185. }
  1186. rc = sqlite3_bind_text(res, 4, value, -1, SQLITE_STATIC);
  1187. if (unlikely(rc != SQLITE_OK)) {
  1188. error_report("Failed to bind value parameter to store label information");
  1189. goto failed;
  1190. }
  1191. rc = execute_insert(res);
  1192. if (unlikely(rc != SQLITE_DONE))
  1193. error_report("Failed to store chart label entry, rc = %d", rc);
  1194. failed:
  1195. if (unlikely(sqlite3_reset(res) != SQLITE_OK))
  1196. error_report("Failed to reset the prepared statement when storing chart label information");
  1197. return;
  1198. }
  1199. int find_dimension_first_last_t(char *machine_guid, char *chart_id, char *dim_id,
  1200. uuid_t *uuid, time_t *first_entry_t, time_t *last_entry_t, uuid_t *rrdeng_uuid)
  1201. {
  1202. #ifdef ENABLE_DBENGINE
  1203. int rc;
  1204. uuid_t legacy_uuid;
  1205. uuid_t multihost_legacy_uuid;
  1206. time_t dim_first_entry_t, dim_last_entry_t;
  1207. rc = rrdeng_metric_latest_time_by_uuid(uuid, &dim_first_entry_t, &dim_last_entry_t);
  1208. if (unlikely(rc)) {
  1209. rrdeng_generate_legacy_uuid(dim_id, chart_id, &legacy_uuid);
  1210. rc = rrdeng_metric_latest_time_by_uuid(&legacy_uuid, &dim_first_entry_t, &dim_last_entry_t);
  1211. if (likely(rc)) {
  1212. rrdeng_convert_legacy_uuid_to_multihost(machine_guid, &legacy_uuid, &multihost_legacy_uuid);
  1213. rc = rrdeng_metric_latest_time_by_uuid(&multihost_legacy_uuid, &dim_first_entry_t, &dim_last_entry_t);
  1214. if (likely(!rc))
  1215. uuid_copy(*rrdeng_uuid, multihost_legacy_uuid);
  1216. }
  1217. else
  1218. uuid_copy(*rrdeng_uuid, legacy_uuid);
  1219. }
  1220. else
  1221. uuid_copy(*rrdeng_uuid, *uuid);
  1222. if (likely(!rc)) {
  1223. *first_entry_t = MIN(*first_entry_t, dim_first_entry_t);
  1224. *last_entry_t = MAX(*last_entry_t, dim_last_entry_t);
  1225. }
  1226. return rc;
  1227. #else
  1228. UNUSED(machine_guid);
  1229. UNUSED(chart_id);
  1230. UNUSED(dim_id);
  1231. UNUSED(uuid);
  1232. UNUSED(first_entry_t);
  1233. UNUSED(last_entry_t);
  1234. UNUSED(rrdeng_uuid);
  1235. return 1;
  1236. #endif
  1237. }
  1238. #ifdef ENABLE_DBENGINE
  1239. static RRDDIM *create_rrdim_entry(ONEWAYALLOC *owa, RRDSET *st, char *id, char *name, uuid_t *metric_uuid)
  1240. {
  1241. RRDDIM *rd = onewayalloc_callocz(owa, 1, sizeof(*rd));
  1242. rd->rrdset = st;
  1243. rd->last_stored_value = NAN;
  1244. rrddim_flag_set(rd, RRDDIM_FLAG_NONE);
  1245. rd->state = onewayalloc_mallocz(owa, sizeof(*rd->state));
  1246. rd->rrd_memory_mode = RRD_MEMORY_MODE_DBENGINE;
  1247. rd->state->query_ops.init = rrdeng_load_metric_init;
  1248. rd->state->query_ops.next_metric = rrdeng_load_metric_next;
  1249. rd->state->query_ops.is_finished = rrdeng_load_metric_is_finished;
  1250. rd->state->query_ops.finalize = rrdeng_load_metric_finalize;
  1251. rd->state->query_ops.latest_time = rrdeng_metric_latest_time;
  1252. rd->state->query_ops.oldest_time = rrdeng_metric_oldest_time;
  1253. rd->state->rrdeng_uuid = onewayalloc_mallocz(owa, sizeof(uuid_t));
  1254. uuid_copy(*rd->state->rrdeng_uuid, *metric_uuid);
  1255. uuid_copy(rd->state->metric_uuid, *metric_uuid);
  1256. rd->id = onewayalloc_strdupz(owa, id);
  1257. rd->name = onewayalloc_strdupz(owa, name);
  1258. return rd;
  1259. }
  1260. #endif
  1261. #define SELECT_CHART_CONTEXT "select d.dim_id, d.id, d.name, c.id, c.type, c.name, c.update_every, c.chart_id, " \
  1262. "c.context, CASE WHEN d.options = 'hidden' THEN 1 else 0 END from chart c, " \
  1263. "dimension d, host h " \
  1264. "where d.chart_id = c.chart_id and c.host_id = h.host_id and c.host_id = @host_id and c.context = @context " \
  1265. "order by c.chart_id asc, c.type||c.id desc;"
  1266. #define SELECT_CHART_SINGLE "select d.dim_id, d.id, d.name, c.id, c.type, c.name, c.update_every, c.chart_id, " \
  1267. "c.context, CASE WHEN d.options = 'hidden' THEN 1 else 0 END from chart c, " \
  1268. "dimension d, host h " \
  1269. "where d.chart_id = c.chart_id and c.host_id = h.host_id and c.host_id = @host_id and c.type||'.'||c.id = @chart " \
  1270. "order by c.chart_id asc, c.type||'.'||c.id desc;"
  1271. void sql_build_context_param_list(ONEWAYALLOC *owa, struct context_param **param_list, RRDHOST *host, char *context, char *chart)
  1272. {
  1273. #ifdef ENABLE_DBENGINE
  1274. int rc;
  1275. if (unlikely(!param_list) || host->rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)
  1276. return;
  1277. if (unlikely(!(*param_list))) {
  1278. *param_list = onewayalloc_mallocz(owa, sizeof(struct context_param));
  1279. (*param_list)->first_entry_t = LONG_MAX;
  1280. (*param_list)->last_entry_t = 0;
  1281. (*param_list)->rd = NULL;
  1282. (*param_list)->flags = CONTEXT_FLAGS_ARCHIVE;
  1283. if (chart)
  1284. (*param_list)->flags |= CONTEXT_FLAGS_CHART;
  1285. else
  1286. (*param_list)->flags |= CONTEXT_FLAGS_CONTEXT;
  1287. }
  1288. sqlite3_stmt *res = NULL;
  1289. if (context)
  1290. rc = sqlite3_prepare_v2(db_meta, SELECT_CHART_CONTEXT, -1, &res, 0);
  1291. else
  1292. rc = sqlite3_prepare_v2(db_meta, SELECT_CHART_SINGLE, -1, &res, 0);
  1293. if (unlikely(rc != SQLITE_OK)) {
  1294. error_report("Failed to prepare statement to fetch host archived charts");
  1295. return;
  1296. }
  1297. rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
  1298. if (unlikely(rc != SQLITE_OK)) {
  1299. error_report("Failed to bind host parameter to fetch archived charts");
  1300. goto failed;
  1301. }
  1302. if (context)
  1303. rc = sqlite3_bind_text(res, 2, context, -1, SQLITE_STATIC);
  1304. else
  1305. rc = sqlite3_bind_text(res, 2, chart, -1, SQLITE_STATIC);
  1306. if (unlikely(rc != SQLITE_OK)) {
  1307. error_report("Failed to bind host parameter to fetch archived charts");
  1308. goto failed;
  1309. }
  1310. RRDSET *st = NULL;
  1311. char machine_guid[GUID_LEN + 1];
  1312. uuid_unparse_lower(host->host_uuid, machine_guid);
  1313. uuid_t rrdeng_uuid;
  1314. uuid_t chart_id;
  1315. while (sqlite3_step(res) == SQLITE_ROW) {
  1316. char id[512];
  1317. sprintf(id, "%s.%s", sqlite3_column_text(res, 3), sqlite3_column_text(res, 1));
  1318. if (!st || uuid_compare(*(uuid_t *)sqlite3_column_blob(res, 7), chart_id)) {
  1319. if (unlikely(st && !st->counter)) {
  1320. onewayalloc_freez(owa, st->context);
  1321. onewayalloc_freez(owa, (char *) st->name);
  1322. onewayalloc_freez(owa, st);
  1323. }
  1324. st = onewayalloc_callocz(owa, 1, sizeof(*st));
  1325. char n[RRD_ID_LENGTH_MAX + 1];
  1326. snprintfz(
  1327. n, RRD_ID_LENGTH_MAX, "%s.%s", (char *)sqlite3_column_text(res, 4),
  1328. (char *)sqlite3_column_text(res, 3));
  1329. st->name = onewayalloc_strdupz(owa, n);
  1330. st->update_every = sqlite3_column_int(res, 6);
  1331. st->counter = 0;
  1332. if (chart) {
  1333. st->context = onewayalloc_strdupz(owa, (char *)sqlite3_column_text(res, 8));
  1334. strncpyz(st->id, chart, RRD_ID_LENGTH_MAX);
  1335. }
  1336. uuid_copy(chart_id, *(uuid_t *)sqlite3_column_blob(res, 7));
  1337. st->last_entry_t = 0;
  1338. st->rrdhost = host;
  1339. }
  1340. if (unlikely(find_dimension_first_last_t(machine_guid, (char *)st->name, (char *)sqlite3_column_text(res, 1),
  1341. (uuid_t *)sqlite3_column_blob(res, 0), &(*param_list)->first_entry_t, &(*param_list)->last_entry_t,
  1342. &rrdeng_uuid)))
  1343. continue;
  1344. st->counter++;
  1345. st->last_entry_t = MAX(st->last_entry_t, (*param_list)->last_entry_t);
  1346. RRDDIM *rd = create_rrdim_entry(owa, st, (char *)sqlite3_column_text(res, 1), (char *)sqlite3_column_text(res, 2), &rrdeng_uuid);
  1347. if (sqlite3_column_int(res, 9) == 1)
  1348. rrddim_flag_set(rd, RRDDIM_FLAG_HIDDEN);
  1349. rd->next = (*param_list)->rd;
  1350. (*param_list)->rd = rd;
  1351. }
  1352. if (st) {
  1353. if (!st->counter) {
  1354. onewayalloc_freez(owa,st->context);
  1355. onewayalloc_freez(owa,(char *)st->name);
  1356. onewayalloc_freez(owa,st);
  1357. }
  1358. else
  1359. if (!st->context && context)
  1360. st->context = onewayalloc_strdupz(owa,context);
  1361. }
  1362. failed:
  1363. rc = sqlite3_finalize(res);
  1364. if (unlikely(rc != SQLITE_OK))
  1365. error_report("Failed to finalize the prepared statement when reading archived charts");
  1366. #else
  1367. UNUSED(param_list);
  1368. UNUSED(host);
  1369. UNUSED(context);
  1370. UNUSED(chart);
  1371. #endif
  1372. return;
  1373. }
  1374. /*
  1375. * Store a chart hash in the database
  1376. */
  1377. #define SQL_STORE_CHART_HASH "insert into v_chart_hash (hash_id, type, id, " \
  1378. "name, family, context, title, unit, plugin, module, priority, chart_type, last_used, chart_id) " \
  1379. "values (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11, ?12, strftime('%s'), ?13);"
  1380. int sql_store_chart_hash(
  1381. uuid_t *hash_id, uuid_t *chart_id, const char *type, const char *id, const char *name, const char *family,
  1382. const char *context, const char *title, const char *units, const char *plugin, const char *module, long priority,
  1383. RRDSET_TYPE chart_type)
  1384. {
  1385. static __thread sqlite3_stmt *res = NULL;
  1386. int rc, param = 0;
  1387. if (unlikely(!db_meta)) {
  1388. if (default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)
  1389. return 0;
  1390. error_report("Database has not been initialized");
  1391. return 1;
  1392. }
  1393. if (unlikely(!res)) {
  1394. rc = prepare_statement(db_meta, SQL_STORE_CHART_HASH, &res);
  1395. if (unlikely(rc != SQLITE_OK)) {
  1396. error_report("Failed to prepare statement to store chart, rc = %d", rc);
  1397. return 1;
  1398. }
  1399. }
  1400. param++;
  1401. rc = sqlite3_bind_blob(res, 1, hash_id, sizeof(*hash_id), SQLITE_STATIC);
  1402. if (unlikely(rc != SQLITE_OK))
  1403. goto bind_fail;
  1404. param++;
  1405. rc = sqlite3_bind_text(res, 2, type, -1, SQLITE_STATIC);
  1406. if (unlikely(rc != SQLITE_OK))
  1407. goto bind_fail;
  1408. param++;
  1409. rc = sqlite3_bind_text(res, 3, id, -1, SQLITE_STATIC);
  1410. if (unlikely(rc != SQLITE_OK))
  1411. goto bind_fail;
  1412. param++;
  1413. if (name && *name)
  1414. rc = sqlite3_bind_text(res, 4, name, -1, SQLITE_STATIC);
  1415. else
  1416. rc = sqlite3_bind_null(res, 4);
  1417. if (unlikely(rc != SQLITE_OK))
  1418. goto bind_fail;
  1419. param++;
  1420. rc = sqlite3_bind_text(res, 5, family, -1, SQLITE_STATIC);
  1421. if (unlikely(rc != SQLITE_OK))
  1422. goto bind_fail;
  1423. param++;
  1424. rc = sqlite3_bind_text(res, 6, context, -1, SQLITE_STATIC);
  1425. if (unlikely(rc != SQLITE_OK))
  1426. goto bind_fail;
  1427. param++;
  1428. rc = sqlite3_bind_text(res, 7, title, -1, SQLITE_STATIC);
  1429. if (unlikely(rc != SQLITE_OK))
  1430. goto bind_fail;
  1431. param++;
  1432. rc = sqlite3_bind_text(res, 8, units, -1, SQLITE_STATIC);
  1433. if (unlikely(rc != SQLITE_OK))
  1434. goto bind_fail;
  1435. param++;
  1436. rc = sqlite3_bind_text(res, 9, plugin, -1, SQLITE_STATIC);
  1437. if (unlikely(rc != SQLITE_OK))
  1438. goto bind_fail;
  1439. param++;
  1440. rc = sqlite3_bind_text(res, 10, module, -1, SQLITE_STATIC);
  1441. if (unlikely(rc != SQLITE_OK))
  1442. goto bind_fail;
  1443. param++;
  1444. rc = sqlite3_bind_int(res, 11, (int) priority);
  1445. if (unlikely(rc != SQLITE_OK))
  1446. goto bind_fail;
  1447. param++;
  1448. rc = sqlite3_bind_int(res, 12, chart_type);
  1449. if (unlikely(rc != SQLITE_OK))
  1450. goto bind_fail;
  1451. param++;
  1452. rc = sqlite3_bind_blob(res, 13, chart_id, sizeof(*chart_id), SQLITE_STATIC);
  1453. if (unlikely(rc != SQLITE_OK))
  1454. goto bind_fail;
  1455. rc = execute_insert(res);
  1456. if (unlikely(rc != SQLITE_DONE))
  1457. error_report("Failed to store chart hash_id, rc = %d", rc);
  1458. rc = sqlite3_reset(res);
  1459. if (unlikely(rc != SQLITE_OK))
  1460. error_report("Failed to reset statement in chart hash_id store function, rc = %d", rc);
  1461. return 0;
  1462. bind_fail:
  1463. error_report("Failed to bind parameter %d to store chart hash_id, rc = %d", param, rc);
  1464. rc = sqlite3_reset(res);
  1465. if (unlikely(rc != SQLITE_OK))
  1466. error_report("Failed to reset statement in chart hash_id store function, rc = %d", rc);
  1467. return 1;
  1468. }
  1469. /*
  1470. chart hashes are used for cloud communication.
  1471. if cloud is disabled or openssl is not available (which will prevent cloud connectivity)
  1472. skip hash calculations
  1473. */
  1474. void compute_chart_hash(RRDSET *st)
  1475. {
  1476. #if !defined DISABLE_CLOUD && defined ENABLE_HTTPS
  1477. EVP_MD_CTX *evpctx;
  1478. unsigned char hash_value[EVP_MAX_MD_SIZE];
  1479. unsigned int hash_len;
  1480. char priority_str[32];
  1481. sprintf(priority_str, "%ld", st->priority);
  1482. evpctx = EVP_MD_CTX_create();
  1483. EVP_DigestInit_ex(evpctx, EVP_sha256(), NULL);
  1484. //EVP_DigestUpdate(evpctx, st->type, strlen(st->type));
  1485. EVP_DigestUpdate(evpctx, st->id, strlen(st->id));
  1486. EVP_DigestUpdate(evpctx, st->name, strlen(st->name));
  1487. EVP_DigestUpdate(evpctx, st->family, strlen(st->family));
  1488. EVP_DigestUpdate(evpctx, st->context, strlen(st->context));
  1489. EVP_DigestUpdate(evpctx, st->title, strlen(st->title));
  1490. EVP_DigestUpdate(evpctx, st->units, strlen(st->units));
  1491. EVP_DigestUpdate(evpctx, st->plugin_name, strlen(st->plugin_name));
  1492. if (st->module_name)
  1493. EVP_DigestUpdate(evpctx, st->module_name, strlen(st->module_name));
  1494. // EVP_DigestUpdate(evpctx, priority_str, strlen(priority_str));
  1495. EVP_DigestUpdate(evpctx, &st->priority, sizeof(st->priority));
  1496. EVP_DigestUpdate(evpctx, &st->chart_type, sizeof(st->chart_type));
  1497. EVP_DigestFinal_ex(evpctx, hash_value, &hash_len);
  1498. EVP_MD_CTX_destroy(evpctx);
  1499. fatal_assert(hash_len > sizeof(uuid_t));
  1500. char uuid_str[GUID_LEN + 1];
  1501. uuid_unparse_lower(*((uuid_t *) &hash_value), uuid_str);
  1502. //info("Calculating HASH %s for chart %s", uuid_str, st->name);
  1503. uuid_copy(st->state->hash_id, *((uuid_t *) &hash_value));
  1504. (void)sql_store_chart_hash(
  1505. (uuid_t *)&hash_value,
  1506. st->chart_uuid,
  1507. st->type,
  1508. st->id,
  1509. st->name,
  1510. st->family,
  1511. st->context,
  1512. st->title,
  1513. st->units,
  1514. st->plugin_name,
  1515. st->module_name,
  1516. st->priority,
  1517. st->chart_type);
  1518. #else
  1519. UNUSED(st);
  1520. #endif
  1521. return;
  1522. }
  1523. #define SQL_STORE_CLAIM_ID "insert into node_instance " \
  1524. "(host_id, claim_id, date_created) values (@host_id, @claim_id, strftime('%s')) " \
  1525. "on conflict(host_id) do update set claim_id = excluded.claim_id;"
  1526. void store_claim_id(uuid_t *host_id, uuid_t *claim_id)
  1527. {
  1528. sqlite3_stmt *res = NULL;
  1529. int rc;
  1530. if (unlikely(!db_meta)) {
  1531. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  1532. error_report("Database has not been initialized");
  1533. return;
  1534. }
  1535. rc = sqlite3_prepare_v2(db_meta, SQL_STORE_CLAIM_ID, -1, &res, 0);
  1536. if (unlikely(rc != SQLITE_OK)) {
  1537. error_report("Failed to prepare statement store chart labels");
  1538. return;
  1539. }
  1540. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  1541. if (unlikely(rc != SQLITE_OK)) {
  1542. error_report("Failed to bind host_id parameter to store node instance information");
  1543. goto failed;
  1544. }
  1545. if (claim_id)
  1546. rc = sqlite3_bind_blob(res, 2, claim_id, sizeof(*claim_id), SQLITE_STATIC);
  1547. else
  1548. rc = sqlite3_bind_null(res, 2);
  1549. if (unlikely(rc != SQLITE_OK)) {
  1550. error_report("Failed to bind claim_id parameter to store node instance information");
  1551. goto failed;
  1552. }
  1553. rc = execute_insert(res);
  1554. if (unlikely(rc != SQLITE_DONE))
  1555. error_report("Failed to store node instance information, rc = %d", rc);
  1556. failed:
  1557. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  1558. error_report("Failed to finalize the prepared statement when storing node instance information");
  1559. return;
  1560. }
  1561. static inline void set_host_node_id(RRDHOST *host, uuid_t *node_id)
  1562. {
  1563. if (unlikely(!host))
  1564. return;
  1565. if (unlikely(!node_id)) {
  1566. freez(host->node_id);
  1567. host->node_id = NULL;
  1568. return;
  1569. }
  1570. struct aclk_database_worker_config *wc = host->dbsync_worker;
  1571. if (unlikely(!host->node_id))
  1572. host->node_id = mallocz(sizeof(*host->node_id));
  1573. uuid_copy(*(host->node_id), *node_id);
  1574. if (unlikely(!wc))
  1575. sql_create_aclk_table(host, &host->host_uuid, node_id);
  1576. else
  1577. uuid_unparse_lower(*node_id, wc->node_id);
  1578. return;
  1579. }
  1580. #define SQL_UPDATE_NODE_ID "update node_instance set node_id = @node_id where host_id = @host_id;"
  1581. int update_node_id(uuid_t *host_id, uuid_t *node_id)
  1582. {
  1583. sqlite3_stmt *res = NULL;
  1584. RRDHOST *host = NULL;
  1585. int rc = 2;
  1586. if (unlikely(!db_meta)) {
  1587. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  1588. error_report("Database has not been initialized");
  1589. return 1;
  1590. }
  1591. rc = sqlite3_prepare_v2(db_meta, SQL_UPDATE_NODE_ID, -1, &res, 0);
  1592. if (unlikely(rc != SQLITE_OK)) {
  1593. error_report("Failed to prepare statement to store node instance information");
  1594. return 1;
  1595. }
  1596. rc = sqlite3_bind_blob(res, 1, node_id, sizeof(*node_id), SQLITE_STATIC);
  1597. if (unlikely(rc != SQLITE_OK)) {
  1598. error_report("Failed to bind host_id parameter to store node instance information");
  1599. goto failed;
  1600. }
  1601. rc = sqlite3_bind_blob(res, 2, host_id, sizeof(*host_id), SQLITE_STATIC);
  1602. if (unlikely(rc != SQLITE_OK)) {
  1603. error_report("Failed to bind host_id parameter to store node instance information");
  1604. goto failed;
  1605. }
  1606. rc = execute_insert(res);
  1607. if (unlikely(rc != SQLITE_DONE))
  1608. error_report("Failed to store node instance information, rc = %d", rc);
  1609. rc = sqlite3_changes(db_meta);
  1610. char host_guid[GUID_LEN + 1];
  1611. uuid_unparse_lower(*host_id, host_guid);
  1612. rrd_wrlock();
  1613. host = rrdhost_find_by_guid(host_guid, 0);
  1614. if (likely(host))
  1615. set_host_node_id(host, node_id);
  1616. rrd_unlock();
  1617. failed:
  1618. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  1619. error_report("Failed to finalize the prepared statement when storing node instance information");
  1620. return rc - 1;
  1621. }
  1622. #define SQL_SELECT_HOSTNAME_BY_NODE_ID "SELECT h.hostname FROM node_instance ni, " \
  1623. "host h WHERE ni.host_id = h.host_id AND ni.node_id = @node_id;"
  1624. char *get_hostname_by_node_id(char *node)
  1625. {
  1626. sqlite3_stmt *res = NULL;
  1627. char *hostname = NULL;
  1628. int rc;
  1629. rrd_rdlock();
  1630. RRDHOST *host = find_host_by_node_id(node);
  1631. rrd_unlock();
  1632. if (host)
  1633. return strdupz(host->hostname);
  1634. if (unlikely(!db_meta)) {
  1635. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  1636. error_report("Database has not been initialized");
  1637. return NULL;
  1638. }
  1639. uuid_t node_id;
  1640. if (uuid_parse(node, node_id))
  1641. return NULL;
  1642. rc = sqlite3_prepare_v2(db_meta, SQL_SELECT_HOSTNAME_BY_NODE_ID, -1, &res, 0);
  1643. if (unlikely(rc != SQLITE_OK)) {
  1644. error_report("Failed to prepare statement to fetch hostname by node id");
  1645. return NULL;
  1646. }
  1647. rc = sqlite3_bind_blob(res, 1, &node_id, sizeof(node_id), SQLITE_STATIC);
  1648. if (unlikely(rc != SQLITE_OK)) {
  1649. error_report("Failed to bind host_id parameter to select node instance information");
  1650. goto failed;
  1651. }
  1652. rc = sqlite3_step(res);
  1653. if (likely(rc == SQLITE_ROW))
  1654. hostname = strdupz((char *)sqlite3_column_text(res, 0));
  1655. failed:
  1656. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  1657. error_report("Failed to finalize the prepared statement when search for hostname by node id");
  1658. return hostname;
  1659. }
  1660. #define SQL_SELECT_HOST_BY_NODE_ID "select host_id from node_instance where node_id = @node_id;"
  1661. int get_host_id(uuid_t *node_id, uuid_t *host_id)
  1662. {
  1663. static __thread sqlite3_stmt *res = NULL;
  1664. int rc;
  1665. if (unlikely(!db_meta)) {
  1666. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  1667. error_report("Database has not been initialized");
  1668. return 1;
  1669. }
  1670. if (unlikely(!res)) {
  1671. rc = prepare_statement(db_meta, SQL_SELECT_HOST_BY_NODE_ID, &res);
  1672. if (unlikely(rc != SQLITE_OK)) {
  1673. error_report("Failed to prepare statement to select node instance information for a node");
  1674. return 1;
  1675. }
  1676. }
  1677. rc = sqlite3_bind_blob(res, 1, node_id, sizeof(*node_id), SQLITE_STATIC);
  1678. if (unlikely(rc != SQLITE_OK)) {
  1679. error_report("Failed to bind host_id parameter to select node instance information");
  1680. goto failed;
  1681. }
  1682. rc = sqlite3_step(res);
  1683. if (likely(rc == SQLITE_ROW && host_id))
  1684. uuid_copy(*host_id, *((uuid_t *) sqlite3_column_blob(res, 0)));
  1685. failed:
  1686. if (unlikely(sqlite3_reset(res) != SQLITE_OK))
  1687. error_report("Failed to reset the prepared statement when selecting node instance information");
  1688. return (rc == SQLITE_ROW) ? 0 : -1;
  1689. }
  1690. #define SQL_SELECT_NODE_ID "select node_id from node_instance where host_id = @host_id and node_id not null;"
  1691. int get_node_id(uuid_t *host_id, uuid_t *node_id)
  1692. {
  1693. sqlite3_stmt *res = NULL;
  1694. int rc;
  1695. if (unlikely(!db_meta)) {
  1696. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  1697. error_report("Database has not been initialized");
  1698. return 1;
  1699. }
  1700. rc = sqlite3_prepare_v2(db_meta, SQL_SELECT_NODE_ID, -1, &res, 0);
  1701. if (unlikely(rc != SQLITE_OK)) {
  1702. error_report("Failed to prepare statement to select node instance information for a host");
  1703. return 1;
  1704. }
  1705. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  1706. if (unlikely(rc != SQLITE_OK)) {
  1707. error_report("Failed to bind host_id parameter to select node instance information");
  1708. goto failed;
  1709. }
  1710. rc = sqlite3_step(res);
  1711. if (likely(rc == SQLITE_ROW && node_id))
  1712. uuid_copy(*node_id, *((uuid_t *) sqlite3_column_blob(res, 0)));
  1713. failed:
  1714. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  1715. error_report("Failed to finalize the prepared statement when selecting node instance information");
  1716. return (rc == SQLITE_ROW) ? 0 : -1;
  1717. }
  1718. #define SQL_INVALIDATE_NODE_INSTANCES "update node_instance set node_id = NULL where exists " \
  1719. "(select host_id from node_instance where host_id = @host_id and (@claim_id is null or claim_id <> @claim_id));"
  1720. void invalidate_node_instances(uuid_t *host_id, uuid_t *claim_id)
  1721. {
  1722. sqlite3_stmt *res = NULL;
  1723. int rc;
  1724. if (unlikely(!db_meta)) {
  1725. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  1726. error_report("Database has not been initialized");
  1727. return;
  1728. }
  1729. rc = sqlite3_prepare_v2(db_meta, SQL_INVALIDATE_NODE_INSTANCES, -1, &res, 0);
  1730. if (unlikely(rc != SQLITE_OK)) {
  1731. error_report("Failed to prepare statement to invalidate node instance ids");
  1732. return;
  1733. }
  1734. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  1735. if (unlikely(rc != SQLITE_OK)) {
  1736. error_report("Failed to bind host_id parameter to invalidate node instance information");
  1737. goto failed;
  1738. }
  1739. if (claim_id)
  1740. rc = sqlite3_bind_blob(res, 2, claim_id, sizeof(*claim_id), SQLITE_STATIC);
  1741. else
  1742. rc = sqlite3_bind_null(res, 2);
  1743. if (unlikely(rc != SQLITE_OK)) {
  1744. error_report("Failed to bind claim_id parameter to invalidate node instance information");
  1745. goto failed;
  1746. }
  1747. rc = execute_insert(res);
  1748. if (unlikely(rc != SQLITE_DONE))
  1749. error_report("Failed to invalidate node instance information, rc = %d", rc);
  1750. failed:
  1751. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  1752. error_report("Failed to finalize the prepared statement when invalidating node instance information");
  1753. }
  1754. #define SQL_GET_NODE_INSTANCE_LIST "select ni.node_id, ni.host_id, h.hostname " \
  1755. "from node_instance ni, host h where ni.host_id = h.host_id;"
  1756. struct node_instance_list *get_node_list(void)
  1757. {
  1758. struct node_instance_list *node_list = NULL;
  1759. sqlite3_stmt *res = NULL;
  1760. int rc;
  1761. if (unlikely(!db_meta)) {
  1762. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  1763. error_report("Database has not been initialized");
  1764. return NULL;
  1765. }
  1766. rc = sqlite3_prepare_v2(db_meta, SQL_GET_NODE_INSTANCE_LIST, -1, &res, 0);
  1767. if (unlikely(rc != SQLITE_OK)) {
  1768. error_report("Failed to prepare statement to get node instance information");
  1769. return NULL;
  1770. };
  1771. int row = 0;
  1772. char host_guid[37];
  1773. while (sqlite3_step(res) == SQLITE_ROW)
  1774. row++;
  1775. if (sqlite3_reset(res) != SQLITE_OK) {
  1776. error_report("Failed to reset the prepared statement while fetching node instance information");
  1777. goto failed;
  1778. }
  1779. node_list = callocz(row + 1, sizeof(*node_list));
  1780. int max_rows = row;
  1781. row = 0;
  1782. rrd_rdlock();
  1783. while (sqlite3_step(res) == SQLITE_ROW) {
  1784. if (sqlite3_column_bytes(res, 0) == sizeof(uuid_t))
  1785. uuid_copy(node_list[row].node_id, *((uuid_t *)sqlite3_column_blob(res, 0)));
  1786. if (sqlite3_column_bytes(res, 1) == sizeof(uuid_t)) {
  1787. uuid_t *host_id = (uuid_t *)sqlite3_column_blob(res, 1);
  1788. uuid_copy(node_list[row].host_id, *host_id);
  1789. node_list[row].queryable = 1;
  1790. uuid_unparse_lower(*host_id, host_guid);
  1791. RRDHOST *host = rrdhost_find_by_guid(host_guid, 0);
  1792. node_list[row].live = host && (host == localhost || host->receiver) ? 1 : 0;
  1793. node_list[row].hops = (host && host->system_info) ? host->system_info->hops :
  1794. uuid_compare(*host_id, localhost->host_uuid) ? 1 : 0;
  1795. node_list[row].hostname =
  1796. sqlite3_column_bytes(res, 2) ? strdupz((char *)sqlite3_column_text(res, 2)) : NULL;
  1797. }
  1798. row++;
  1799. if (row == max_rows)
  1800. break;
  1801. }
  1802. rrd_unlock();
  1803. failed:
  1804. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  1805. error_report("Failed to finalize the prepared statement when fetching node instance information");
  1806. return node_list;
  1807. };
  1808. #define SQL_GET_HOST_NODE_ID "select node_id from node_instance where host_id = @host_id;"
  1809. void sql_load_node_id(RRDHOST *host)
  1810. {
  1811. static __thread sqlite3_stmt *res = NULL;
  1812. int rc;
  1813. if (unlikely(!db_meta)) {
  1814. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  1815. error_report("Database has not been initialized");
  1816. return;
  1817. }
  1818. if (unlikely(!res)) {
  1819. rc = prepare_statement(db_meta, SQL_GET_HOST_NODE_ID, &res);
  1820. if (unlikely(rc != SQLITE_OK)) {
  1821. error_report("Failed to prepare statement to fetch node id");
  1822. return;
  1823. };
  1824. }
  1825. rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
  1826. if (unlikely(rc != SQLITE_OK)) {
  1827. error_report("Failed to bind host_id parameter to load node instance information");
  1828. goto failed;
  1829. }
  1830. rc = sqlite3_step(res);
  1831. if (likely(rc == SQLITE_ROW)) {
  1832. if (likely(sqlite3_column_bytes(res, 0) == sizeof(uuid_t)))
  1833. set_host_node_id(host, (uuid_t *)sqlite3_column_blob(res, 0));
  1834. else
  1835. set_host_node_id(host, NULL);
  1836. }
  1837. failed:
  1838. if (unlikely(sqlite3_reset(res) != SQLITE_OK))
  1839. error_report("Failed to reset the prepared statement when loading node instance information");
  1840. return;
  1841. };