sqlite_functions.c 70 KB

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