sqlite_functions.c 80 KB

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