sqlite_functions.c 91 KB

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