web_api_v1.c 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "web_api_v1.h"
  3. char *api_secret;
  4. static struct {
  5. const char *name;
  6. uint32_t hash;
  7. RRDR_OPTIONS value;
  8. } api_v1_data_options[] = {
  9. { "nonzero" , 0 , RRDR_OPTION_NONZERO}
  10. , {"flip" , 0 , RRDR_OPTION_REVERSED}
  11. , {"reversed" , 0 , RRDR_OPTION_REVERSED}
  12. , {"reverse" , 0 , RRDR_OPTION_REVERSED}
  13. , {"jsonwrap" , 0 , RRDR_OPTION_JSON_WRAP}
  14. , {"min2max" , 0 , RRDR_OPTION_MIN2MAX}
  15. , {"ms" , 0 , RRDR_OPTION_MILLISECONDS}
  16. , {"milliseconds" , 0 , RRDR_OPTION_MILLISECONDS}
  17. , {"abs" , 0 , RRDR_OPTION_ABSOLUTE}
  18. , {"absolute" , 0 , RRDR_OPTION_ABSOLUTE}
  19. , {"absolute_sum" , 0 , RRDR_OPTION_ABSOLUTE}
  20. , {"absolute-sum" , 0 , RRDR_OPTION_ABSOLUTE}
  21. , {"display_absolute" , 0 , RRDR_OPTION_DISPLAY_ABS}
  22. , {"display-absolute" , 0 , RRDR_OPTION_DISPLAY_ABS}
  23. , {"seconds" , 0 , RRDR_OPTION_SECONDS}
  24. , {"null2zero" , 0 , RRDR_OPTION_NULL2ZERO}
  25. , {"objectrows" , 0 , RRDR_OPTION_OBJECTSROWS}
  26. , {"google_json" , 0 , RRDR_OPTION_GOOGLE_JSON}
  27. , {"google-json" , 0 , RRDR_OPTION_GOOGLE_JSON}
  28. , {"percentage" , 0 , RRDR_OPTION_PERCENTAGE}
  29. , {"unaligned" , 0 , RRDR_OPTION_NOT_ALIGNED}
  30. , {"match_ids" , 0 , RRDR_OPTION_MATCH_IDS}
  31. , {"match-ids" , 0 , RRDR_OPTION_MATCH_IDS}
  32. , {"match_names" , 0 , RRDR_OPTION_MATCH_NAMES}
  33. , {"match-names" , 0 , RRDR_OPTION_MATCH_NAMES}
  34. , {"anomaly-bit" , 0 , RRDR_OPTION_ANOMALY_BIT}
  35. , {"selected-tier" , 0 , RRDR_OPTION_SELECTED_TIER}
  36. , {"raw" , 0 , RRDR_OPTION_RETURN_RAW}
  37. , {"jw-anomaly-rates" , 0 , RRDR_OPTION_RETURN_JWAR}
  38. , {"natural-points" , 0 , RRDR_OPTION_NATURAL_POINTS}
  39. , {"virtual-points" , 0 , RRDR_OPTION_VIRTUAL_POINTS}
  40. , {"all-dimensions" , 0 , RRDR_OPTION_ALL_DIMENSIONS}
  41. , {"details" , 0 , RRDR_OPTION_SHOW_DETAILS}
  42. , {"debug" , 0 , RRDR_OPTION_DEBUG}
  43. , {"plan" , 0 , RRDR_OPTION_DEBUG}
  44. , {"minify" , 0 , RRDR_OPTION_MINIFY}
  45. , {"group-by-labels" , 0 , RRDR_OPTION_GROUP_BY_LABELS}
  46. , {"label-quotes" , 0 , RRDR_OPTION_LABEL_QUOTES}
  47. , {NULL , 0 , 0}
  48. };
  49. static struct {
  50. const char *name;
  51. uint32_t hash;
  52. CONTEXTS_V2_OPTIONS value;
  53. } contexts_v2_options[] = {
  54. {"minify" , 0 , CONTEXT_V2_OPTION_MINIFY}
  55. , {"debug" , 0 , CONTEXT_V2_OPTION_DEBUG}
  56. , {"config" , 0 , CONTEXT_V2_OPTION_ALERTS_WITH_CONFIGURATIONS}
  57. , {"instances" , 0 , CONTEXT_V2_OPTION_ALERTS_WITH_INSTANCES}
  58. , {"values" , 0 , CONTEXT_V2_OPTION_ALERTS_WITH_VALUES}
  59. , {"summary" , 0 , CONTEXT_V2_OPTION_ALERTS_WITH_SUMMARY}
  60. , {NULL , 0 , 0}
  61. };
  62. static struct {
  63. const char *name;
  64. uint32_t hash;
  65. CONTEXTS_V2_ALERT_STATUS value;
  66. } contexts_v2_alert_status[] = {
  67. {"uninitialized" , 0 , CONTEXT_V2_ALERT_UNINITIALIZED}
  68. , {"undefined" , 0 , CONTEXT_V2_ALERT_UNDEFINED}
  69. , {"clear" , 0 , CONTEXT_V2_ALERT_CLEAR}
  70. , {"raised" , 0 , CONTEXT_V2_ALERT_RAISED}
  71. , {"active" , 0 , CONTEXT_V2_ALERT_RAISED}
  72. , {"warning" , 0 , CONTEXT_V2_ALERT_WARNING}
  73. , {"critical" , 0 , CONTEXT_V2_ALERT_CRITICAL}
  74. , {NULL , 0 , 0}
  75. };
  76. static struct {
  77. const char *name;
  78. uint32_t hash;
  79. DATASOURCE_FORMAT value;
  80. } api_v1_data_formats[] = {
  81. { DATASOURCE_FORMAT_DATATABLE_JSON , 0 , DATASOURCE_DATATABLE_JSON}
  82. , {DATASOURCE_FORMAT_DATATABLE_JSONP, 0 , DATASOURCE_DATATABLE_JSONP}
  83. , {DATASOURCE_FORMAT_JSON , 0 , DATASOURCE_JSON}
  84. , {DATASOURCE_FORMAT_JSON2 , 0 , DATASOURCE_JSON2}
  85. , {DATASOURCE_FORMAT_JSONP , 0 , DATASOURCE_JSONP}
  86. , {DATASOURCE_FORMAT_SSV , 0 , DATASOURCE_SSV}
  87. , {DATASOURCE_FORMAT_CSV , 0 , DATASOURCE_CSV}
  88. , {DATASOURCE_FORMAT_TSV , 0 , DATASOURCE_TSV}
  89. , {"tsv-excel" , 0 , DATASOURCE_TSV}
  90. , {DATASOURCE_FORMAT_HTML , 0 , DATASOURCE_HTML}
  91. , {DATASOURCE_FORMAT_JS_ARRAY , 0 , DATASOURCE_JS_ARRAY}
  92. , {DATASOURCE_FORMAT_SSV_COMMA , 0 , DATASOURCE_SSV_COMMA}
  93. , {DATASOURCE_FORMAT_CSV_JSON_ARRAY , 0 , DATASOURCE_CSV_JSON_ARRAY}
  94. , {DATASOURCE_FORMAT_CSV_MARKDOWN , 0 , DATASOURCE_CSV_MARKDOWN}
  95. // terminator
  96. , {NULL, 0, 0}
  97. };
  98. static struct {
  99. const char *name;
  100. uint32_t hash;
  101. DATASOURCE_FORMAT value;
  102. } api_v1_data_google_formats[] = {
  103. // this is not an error - when Google requests json, it expects javascript
  104. // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source#responseformat
  105. {"json", 0, DATASOURCE_DATATABLE_JSONP}
  106. , {"html", 0, DATASOURCE_HTML}
  107. , {"csv", 0, DATASOURCE_CSV}
  108. , {"tsv-excel", 0, DATASOURCE_TSV}
  109. // terminator
  110. , {NULL, 0, 0}
  111. };
  112. void web_client_api_v1_init(void) {
  113. int i;
  114. for(i = 0; contexts_v2_alert_status[i].name ; i++)
  115. contexts_v2_alert_status[i].hash = simple_hash(contexts_v2_alert_status[i].name);
  116. for(i = 0; api_v1_data_options[i].name ; i++)
  117. api_v1_data_options[i].hash = simple_hash(api_v1_data_options[i].name);
  118. for(i = 0; contexts_v2_options[i].name ; i++)
  119. contexts_v2_options[i].hash = simple_hash(contexts_v2_options[i].name);
  120. for(i = 0; api_v1_data_formats[i].name ; i++)
  121. api_v1_data_formats[i].hash = simple_hash(api_v1_data_formats[i].name);
  122. for(i = 0; api_v1_data_google_formats[i].name ; i++)
  123. api_v1_data_google_formats[i].hash = simple_hash(api_v1_data_google_formats[i].name);
  124. time_grouping_init();
  125. uuid_t uuid;
  126. // generate
  127. uuid_generate(uuid);
  128. // unparse (to string)
  129. char uuid_str[37];
  130. uuid_unparse_lower(uuid, uuid_str);
  131. }
  132. char *get_mgmt_api_key(void) {
  133. char filename[FILENAME_MAX + 1];
  134. snprintfz(filename, FILENAME_MAX, "%s/netdata.api.key", netdata_configured_varlib_dir);
  135. char *api_key_filename=config_get(CONFIG_SECTION_REGISTRY, "netdata management api key file", filename);
  136. static char guid[GUID_LEN + 1] = "";
  137. if(likely(guid[0]))
  138. return guid;
  139. // read it from disk
  140. int fd = open(api_key_filename, O_RDONLY);
  141. if(fd != -1) {
  142. char buf[GUID_LEN + 1];
  143. if(read(fd, buf, GUID_LEN) != GUID_LEN)
  144. netdata_log_error("Failed to read management API key from '%s'", api_key_filename);
  145. else {
  146. buf[GUID_LEN] = '\0';
  147. if(regenerate_guid(buf, guid) == -1) {
  148. netdata_log_error("Failed to validate management API key '%s' from '%s'.",
  149. buf, api_key_filename);
  150. guid[0] = '\0';
  151. }
  152. }
  153. close(fd);
  154. }
  155. // generate a new one?
  156. if(!guid[0]) {
  157. uuid_t uuid;
  158. uuid_generate_time(uuid);
  159. uuid_unparse_lower(uuid, guid);
  160. guid[GUID_LEN] = '\0';
  161. // save it
  162. fd = open(api_key_filename, O_WRONLY|O_CREAT|O_TRUNC, 444);
  163. if(fd == -1) {
  164. netdata_log_error("Cannot create unique management API key file '%s'. Please adjust config parameter 'netdata management api key file' to a proper path and file.", api_key_filename);
  165. goto temp_key;
  166. }
  167. if(write(fd, guid, GUID_LEN) != GUID_LEN) {
  168. netdata_log_error("Cannot write the unique management API key file '%s'. Please adjust config parameter 'netdata management api key file' to a proper path and file with enough space left.", api_key_filename);
  169. close(fd);
  170. goto temp_key;
  171. }
  172. close(fd);
  173. }
  174. return guid;
  175. temp_key:
  176. netdata_log_info("You can still continue to use the alarm management API using the authorization token %s during this Netdata session only.", guid);
  177. return guid;
  178. }
  179. void web_client_api_v1_management_init(void) {
  180. api_secret = get_mgmt_api_key();
  181. }
  182. inline RRDR_OPTIONS web_client_api_request_v1_data_options(char *o) {
  183. RRDR_OPTIONS ret = 0;
  184. char *tok;
  185. while(o && *o && (tok = strsep_skip_consecutive_separators(&o, ", |"))) {
  186. if(!*tok) continue;
  187. uint32_t hash = simple_hash(tok);
  188. int i;
  189. for(i = 0; api_v1_data_options[i].name ; i++) {
  190. if (unlikely(hash == api_v1_data_options[i].hash && !strcmp(tok, api_v1_data_options[i].name))) {
  191. ret |= api_v1_data_options[i].value;
  192. break;
  193. }
  194. }
  195. }
  196. return ret;
  197. }
  198. inline CONTEXTS_V2_OPTIONS web_client_api_request_v2_context_options(char *o) {
  199. CONTEXTS_V2_OPTIONS ret = 0;
  200. char *tok;
  201. while(o && *o && (tok = strsep_skip_consecutive_separators(&o, ", |"))) {
  202. if(!*tok) continue;
  203. uint32_t hash = simple_hash(tok);
  204. int i;
  205. for(i = 0; contexts_v2_options[i].name ; i++) {
  206. if (unlikely(hash == contexts_v2_options[i].hash && !strcmp(tok, contexts_v2_options[i].name))) {
  207. ret |= contexts_v2_options[i].value;
  208. break;
  209. }
  210. }
  211. }
  212. return ret;
  213. }
  214. inline CONTEXTS_V2_ALERT_STATUS web_client_api_request_v2_alert_status(char *o) {
  215. CONTEXTS_V2_ALERT_STATUS ret = 0;
  216. char *tok;
  217. while(o && *o && (tok = strsep_skip_consecutive_separators(&o, ", |"))) {
  218. if(!*tok) continue;
  219. uint32_t hash = simple_hash(tok);
  220. int i;
  221. for(i = 0; contexts_v2_alert_status[i].name ; i++) {
  222. if (unlikely(hash == contexts_v2_alert_status[i].hash && !strcmp(tok, contexts_v2_alert_status[i].name))) {
  223. ret |= contexts_v2_alert_status[i].value;
  224. break;
  225. }
  226. }
  227. }
  228. return ret;
  229. }
  230. void web_client_api_request_v2_contexts_alerts_status_to_buffer_json_array(BUFFER *wb, const char *key, CONTEXTS_V2_ALERT_STATUS options) {
  231. buffer_json_member_add_array(wb, key);
  232. RRDR_OPTIONS used = 0; // to prevent adding duplicates
  233. for(int i = 0; contexts_v2_alert_status[i].name ; i++) {
  234. if (unlikely((contexts_v2_alert_status[i].value & options) && !(contexts_v2_alert_status[i].value & used))) {
  235. const char *name = contexts_v2_alert_status[i].name;
  236. used |= contexts_v2_alert_status[i].value;
  237. buffer_json_add_array_item_string(wb, name);
  238. }
  239. }
  240. buffer_json_array_close(wb);
  241. }
  242. void web_client_api_request_v2_contexts_options_to_buffer_json_array(BUFFER *wb, const char *key, CONTEXTS_V2_OPTIONS options) {
  243. buffer_json_member_add_array(wb, key);
  244. RRDR_OPTIONS used = 0; // to prevent adding duplicates
  245. for(int i = 0; contexts_v2_options[i].name ; i++) {
  246. if (unlikely((contexts_v2_options[i].value & options) && !(contexts_v2_options[i].value & used))) {
  247. const char *name = contexts_v2_options[i].name;
  248. used |= contexts_v2_options[i].value;
  249. buffer_json_add_array_item_string(wb, name);
  250. }
  251. }
  252. buffer_json_array_close(wb);
  253. }
  254. void web_client_api_request_v1_data_options_to_buffer_json_array(BUFFER *wb, const char *key, RRDR_OPTIONS options) {
  255. buffer_json_member_add_array(wb, key);
  256. RRDR_OPTIONS used = 0; // to prevent adding duplicates
  257. for(int i = 0; api_v1_data_options[i].name ; i++) {
  258. if (unlikely((api_v1_data_options[i].value & options) && !(api_v1_data_options[i].value & used))) {
  259. const char *name = api_v1_data_options[i].name;
  260. used |= api_v1_data_options[i].value;
  261. buffer_json_add_array_item_string(wb, name);
  262. }
  263. }
  264. buffer_json_array_close(wb);
  265. }
  266. void web_client_api_request_v1_data_options_to_string(char *buf, size_t size, RRDR_OPTIONS options) {
  267. char *write = buf;
  268. char *end = &buf[size - 1];
  269. RRDR_OPTIONS used = 0; // to prevent adding duplicates
  270. int added = 0;
  271. for(int i = 0; api_v1_data_options[i].name ; i++) {
  272. if (unlikely((api_v1_data_options[i].value & options) && !(api_v1_data_options[i].value & used))) {
  273. const char *name = api_v1_data_options[i].name;
  274. used |= api_v1_data_options[i].value;
  275. if(added && write < end)
  276. *write++ = ',';
  277. while(*name && write < end)
  278. *write++ = *name++;
  279. added++;
  280. }
  281. }
  282. *write = *end = '\0';
  283. }
  284. inline uint32_t web_client_api_request_v1_data_format(char *name) {
  285. uint32_t hash = simple_hash(name);
  286. int i;
  287. for(i = 0; api_v1_data_formats[i].name ; i++) {
  288. if (unlikely(hash == api_v1_data_formats[i].hash && !strcmp(name, api_v1_data_formats[i].name))) {
  289. return api_v1_data_formats[i].value;
  290. }
  291. }
  292. return DATASOURCE_JSON;
  293. }
  294. inline uint32_t web_client_api_request_v1_data_google_format(char *name) {
  295. uint32_t hash = simple_hash(name);
  296. int i;
  297. for(i = 0; api_v1_data_google_formats[i].name ; i++) {
  298. if (unlikely(hash == api_v1_data_google_formats[i].hash && !strcmp(name, api_v1_data_google_formats[i].name))) {
  299. return api_v1_data_google_formats[i].value;
  300. }
  301. }
  302. return DATASOURCE_JSON;
  303. }
  304. int web_client_api_request_v1_alarms_select (char *url) {
  305. int all = 0;
  306. while(url) {
  307. char *value = strsep_skip_consecutive_separators(&url, "&");
  308. if (!value || !*value) continue;
  309. if(!strcmp(value, "all") || !strcmp(value, "all=true")) all = 1;
  310. else if(!strcmp(value, "active") || !strcmp(value, "active=true")) all = 0;
  311. }
  312. return all;
  313. }
  314. inline int web_client_api_request_v1_alarms(RRDHOST *host, struct web_client *w, char *url) {
  315. int all = web_client_api_request_v1_alarms_select(url);
  316. buffer_flush(w->response.data);
  317. w->response.data->content_type = CT_APPLICATION_JSON;
  318. health_alarms2json(host, w->response.data, all);
  319. buffer_no_cacheable(w->response.data);
  320. return HTTP_RESP_OK;
  321. }
  322. inline int web_client_api_request_v1_alarms_values(RRDHOST *host, struct web_client *w, char *url) {
  323. int all = web_client_api_request_v1_alarms_select(url);
  324. buffer_flush(w->response.data);
  325. w->response.data->content_type = CT_APPLICATION_JSON;
  326. health_alarms_values2json(host, w->response.data, all);
  327. buffer_no_cacheable(w->response.data);
  328. return HTTP_RESP_OK;
  329. }
  330. inline int web_client_api_request_v1_alarm_count(RRDHOST *host, struct web_client *w, char *url) {
  331. RRDCALC_STATUS status = RRDCALC_STATUS_RAISED;
  332. BUFFER *contexts = NULL;
  333. buffer_flush(w->response.data);
  334. buffer_sprintf(w->response.data, "[");
  335. while(url) {
  336. char *value = strsep_skip_consecutive_separators(&url, "&");
  337. if(!value || !*value) continue;
  338. char *name = strsep_skip_consecutive_separators(&value, "=");
  339. if(!name || !*name) continue;
  340. if(!value || !*value) continue;
  341. netdata_log_debug(D_WEB_CLIENT, "%llu: API v1 alarm_count query param '%s' with value '%s'", w->id, name, value);
  342. char* p = value;
  343. if(!strcmp(name, "status")) {
  344. while ((*p = toupper(*p))) p++;
  345. if (!strcmp("CRITICAL", value)) status = RRDCALC_STATUS_CRITICAL;
  346. else if (!strcmp("WARNING", value)) status = RRDCALC_STATUS_WARNING;
  347. else if (!strcmp("UNINITIALIZED", value)) status = RRDCALC_STATUS_UNINITIALIZED;
  348. else if (!strcmp("UNDEFINED", value)) status = RRDCALC_STATUS_UNDEFINED;
  349. else if (!strcmp("REMOVED", value)) status = RRDCALC_STATUS_REMOVED;
  350. else if (!strcmp("CLEAR", value)) status = RRDCALC_STATUS_CLEAR;
  351. }
  352. else if(!strcmp(name, "context") || !strcmp(name, "ctx")) {
  353. if(!contexts) contexts = buffer_create(255, &netdata_buffers_statistics.buffers_api);
  354. buffer_strcat(contexts, "|");
  355. buffer_strcat(contexts, value);
  356. }
  357. }
  358. health_aggregate_alarms(host, w->response.data, contexts, status);
  359. buffer_sprintf(w->response.data, "]\n");
  360. w->response.data->content_type = CT_APPLICATION_JSON;
  361. buffer_no_cacheable(w->response.data);
  362. buffer_free(contexts);
  363. return 200;
  364. }
  365. inline int web_client_api_request_v1_alarm_log(RRDHOST *host, struct web_client *w, char *url) {
  366. time_t after = 0;
  367. char *chart = NULL;
  368. while(url) {
  369. char *value = strsep_skip_consecutive_separators(&url, "&");
  370. if (!value || !*value) continue;
  371. char *name = strsep_skip_consecutive_separators(&value, "=");
  372. if(!name || !*name) continue;
  373. if(!value || !*value) continue;
  374. if (!strcmp(name, "after")) after = (time_t) strtoul(value, NULL, 0);
  375. else if (!strcmp(name, "chart")) chart = value;
  376. }
  377. buffer_flush(w->response.data);
  378. w->response.data->content_type = CT_APPLICATION_JSON;
  379. sql_health_alarm_log2json(host, w->response.data, after, chart);
  380. return HTTP_RESP_OK;
  381. }
  382. inline int web_client_api_request_single_chart(RRDHOST *host, struct web_client *w, char *url, void callback(RRDSET *st, BUFFER *buf)) {
  383. int ret = HTTP_RESP_BAD_REQUEST;
  384. char *chart = NULL;
  385. buffer_flush(w->response.data);
  386. while(url) {
  387. char *value = strsep_skip_consecutive_separators(&url, "&");
  388. if(!value || !*value) continue;
  389. char *name = strsep_skip_consecutive_separators(&value, "=");
  390. if(!name || !*name) continue;
  391. if(!value || !*value) continue;
  392. // name and value are now the parameters
  393. // they are not null and not empty
  394. if(!strcmp(name, "chart")) chart = value;
  395. //else {
  396. /// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
  397. // goto cleanup;
  398. //}
  399. }
  400. if(!chart || !*chart) {
  401. buffer_sprintf(w->response.data, "No chart id is given at the request.");
  402. goto cleanup;
  403. }
  404. RRDSET *st = rrdset_find(host, chart);
  405. if(!st) st = rrdset_find_byname(host, chart);
  406. if(!st) {
  407. buffer_strcat(w->response.data, "Chart is not found: ");
  408. buffer_strcat_htmlescape(w->response.data, chart);
  409. ret = HTTP_RESP_NOT_FOUND;
  410. goto cleanup;
  411. }
  412. w->response.data->content_type = CT_APPLICATION_JSON;
  413. st->last_accessed_time_s = now_realtime_sec();
  414. callback(st, w->response.data);
  415. return HTTP_RESP_OK;
  416. cleanup:
  417. return ret;
  418. }
  419. inline int web_client_api_request_v1_alarm_variables(RRDHOST *host, struct web_client *w, char *url) {
  420. return web_client_api_request_single_chart(host, w, url, health_api_v1_chart_variables2json);
  421. }
  422. static int web_client_api_request_v1_context(RRDHOST *host, struct web_client *w, char *url) {
  423. char *context = NULL;
  424. RRDCONTEXT_TO_JSON_OPTIONS options = RRDCONTEXT_OPTION_NONE;
  425. time_t after = 0, before = 0;
  426. const char *chart_label_key = NULL, *chart_labels_filter = NULL;
  427. BUFFER *dimensions = NULL;
  428. buffer_flush(w->response.data);
  429. while(url) {
  430. char *value = strsep_skip_consecutive_separators(&url, "&");
  431. if(!value || !*value) continue;
  432. char *name = strsep_skip_consecutive_separators(&value, "=");
  433. if(!name || !*name) continue;
  434. if(!value || !*value) continue;
  435. // name and value are now the parameters
  436. // they are not null and not empty
  437. if(!strcmp(name, "context") || !strcmp(name, "ctx")) context = value;
  438. else if(!strcmp(name, "after")) after = str2l(value);
  439. else if(!strcmp(name, "before")) before = str2l(value);
  440. else if(!strcmp(name, "options")) options = rrdcontext_to_json_parse_options(value);
  441. else if(!strcmp(name, "chart_label_key")) chart_label_key = value;
  442. else if(!strcmp(name, "chart_labels_filter")) chart_labels_filter = value;
  443. else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
  444. if(!dimensions) dimensions = buffer_create(100, &netdata_buffers_statistics.buffers_api);
  445. buffer_strcat(dimensions, "|");
  446. buffer_strcat(dimensions, value);
  447. }
  448. }
  449. if(!context || !*context) {
  450. buffer_sprintf(w->response.data, "No context is given at the request.");
  451. return HTTP_RESP_BAD_REQUEST;
  452. }
  453. SIMPLE_PATTERN *chart_label_key_pattern = NULL;
  454. SIMPLE_PATTERN *chart_labels_filter_pattern = NULL;
  455. SIMPLE_PATTERN *chart_dimensions_pattern = NULL;
  456. if(chart_label_key)
  457. chart_label_key_pattern = simple_pattern_create(chart_label_key, ",|\t\r\n\f\v", SIMPLE_PATTERN_EXACT, true);
  458. if(chart_labels_filter)
  459. chart_labels_filter_pattern = simple_pattern_create(chart_labels_filter, ",|\t\r\n\f\v", SIMPLE_PATTERN_EXACT,
  460. true);
  461. if(dimensions) {
  462. chart_dimensions_pattern = simple_pattern_create(buffer_tostring(dimensions), ",|\t\r\n\f\v",
  463. SIMPLE_PATTERN_EXACT, true);
  464. buffer_free(dimensions);
  465. }
  466. w->response.data->content_type = CT_APPLICATION_JSON;
  467. int ret = rrdcontext_to_json(host, w->response.data, after, before, options, context, chart_label_key_pattern, chart_labels_filter_pattern, chart_dimensions_pattern);
  468. simple_pattern_free(chart_label_key_pattern);
  469. simple_pattern_free(chart_labels_filter_pattern);
  470. simple_pattern_free(chart_dimensions_pattern);
  471. return ret;
  472. }
  473. static int web_client_api_request_v1_contexts(RRDHOST *host, struct web_client *w, char *url) {
  474. RRDCONTEXT_TO_JSON_OPTIONS options = RRDCONTEXT_OPTION_NONE;
  475. time_t after = 0, before = 0;
  476. const char *chart_label_key = NULL, *chart_labels_filter = NULL;
  477. BUFFER *dimensions = NULL;
  478. buffer_flush(w->response.data);
  479. while(url) {
  480. char *value = strsep_skip_consecutive_separators(&url, "&");
  481. if(!value || !*value) continue;
  482. char *name = strsep_skip_consecutive_separators(&value, "=");
  483. if(!name || !*name) continue;
  484. if(!value || !*value) continue;
  485. // name and value are now the parameters
  486. // they are not null and not empty
  487. if(!strcmp(name, "after")) after = str2l(value);
  488. else if(!strcmp(name, "before")) before = str2l(value);
  489. else if(!strcmp(name, "options")) options = rrdcontext_to_json_parse_options(value);
  490. else if(!strcmp(name, "chart_label_key")) chart_label_key = value;
  491. else if(!strcmp(name, "chart_labels_filter")) chart_labels_filter = value;
  492. else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
  493. if(!dimensions) dimensions = buffer_create(100, &netdata_buffers_statistics.buffers_api);
  494. buffer_strcat(dimensions, "|");
  495. buffer_strcat(dimensions, value);
  496. }
  497. }
  498. SIMPLE_PATTERN *chart_label_key_pattern = NULL;
  499. SIMPLE_PATTERN *chart_labels_filter_pattern = NULL;
  500. SIMPLE_PATTERN *chart_dimensions_pattern = NULL;
  501. if(chart_label_key)
  502. chart_label_key_pattern = simple_pattern_create(chart_label_key, ",|\t\r\n\f\v", SIMPLE_PATTERN_EXACT, true);
  503. if(chart_labels_filter)
  504. chart_labels_filter_pattern = simple_pattern_create(chart_labels_filter, ",|\t\r\n\f\v", SIMPLE_PATTERN_EXACT,
  505. true);
  506. if(dimensions) {
  507. chart_dimensions_pattern = simple_pattern_create(buffer_tostring(dimensions), ",|\t\r\n\f\v",
  508. SIMPLE_PATTERN_EXACT, true);
  509. buffer_free(dimensions);
  510. }
  511. w->response.data->content_type = CT_APPLICATION_JSON;
  512. int ret = rrdcontexts_to_json(host, w->response.data, after, before, options, chart_label_key_pattern, chart_labels_filter_pattern, chart_dimensions_pattern);
  513. simple_pattern_free(chart_label_key_pattern);
  514. simple_pattern_free(chart_labels_filter_pattern);
  515. simple_pattern_free(chart_dimensions_pattern);
  516. return ret;
  517. }
  518. inline int web_client_api_request_v1_charts(RRDHOST *host, struct web_client *w, char *url) {
  519. (void)url;
  520. buffer_flush(w->response.data);
  521. w->response.data->content_type = CT_APPLICATION_JSON;
  522. charts2json(host, w->response.data);
  523. return HTTP_RESP_OK;
  524. }
  525. inline int web_client_api_request_v1_chart(RRDHOST *host, struct web_client *w, char *url) {
  526. return web_client_api_request_single_chart(host, w, url, rrd_stats_api_v1_chart);
  527. }
  528. // returns the HTTP code
  529. static inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url) {
  530. netdata_log_debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
  531. int ret = HTTP_RESP_BAD_REQUEST;
  532. BUFFER *dimensions = NULL;
  533. buffer_flush(w->response.data);
  534. char *google_version = "0.6",
  535. *google_reqId = "0",
  536. *google_sig = "0",
  537. *google_out = "json",
  538. *responseHandler = NULL,
  539. *outFileName = NULL;
  540. time_t last_timestamp_in_data = 0, google_timestamp = 0;
  541. char *chart = NULL;
  542. char *before_str = NULL;
  543. char *after_str = NULL;
  544. char *group_time_str = NULL;
  545. char *points_str = NULL;
  546. char *timeout_str = NULL;
  547. char *context = NULL;
  548. char *chart_label_key = NULL;
  549. char *chart_labels_filter = NULL;
  550. char *group_options = NULL;
  551. size_t tier = 0;
  552. RRDR_TIME_GROUPING group = RRDR_GROUPING_AVERAGE;
  553. DATASOURCE_FORMAT format = DATASOURCE_JSON;
  554. RRDR_OPTIONS options = 0;
  555. while(url) {
  556. char *value = strsep_skip_consecutive_separators(&url, "&");
  557. if(!value || !*value) continue;
  558. char *name = strsep_skip_consecutive_separators(&value, "=");
  559. if(!name || !*name) continue;
  560. if(!value || !*value) continue;
  561. netdata_log_debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
  562. // name and value are now the parameters
  563. // they are not null and not empty
  564. if(!strcmp(name, "context")) context = value;
  565. else if(!strcmp(name, "chart_label_key")) chart_label_key = value;
  566. else if(!strcmp(name, "chart_labels_filter")) chart_labels_filter = value;
  567. else if(!strcmp(name, "chart")) chart = value;
  568. else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
  569. if(!dimensions) dimensions = buffer_create(100, &netdata_buffers_statistics.buffers_api);
  570. buffer_strcat(dimensions, "|");
  571. buffer_strcat(dimensions, value);
  572. }
  573. else if(!strcmp(name, "show_dimensions")) options |= RRDR_OPTION_ALL_DIMENSIONS;
  574. else if(!strcmp(name, "after")) after_str = value;
  575. else if(!strcmp(name, "before")) before_str = value;
  576. else if(!strcmp(name, "points")) points_str = value;
  577. else if(!strcmp(name, "timeout")) timeout_str = value;
  578. else if(!strcmp(name, "gtime")) group_time_str = value;
  579. else if(!strcmp(name, "group_options")) group_options = value;
  580. else if(!strcmp(name, "group")) {
  581. group = time_grouping_parse(value, RRDR_GROUPING_AVERAGE);
  582. }
  583. else if(!strcmp(name, "format")) {
  584. format = web_client_api_request_v1_data_format(value);
  585. }
  586. else if(!strcmp(name, "options")) {
  587. options |= web_client_api_request_v1_data_options(value);
  588. }
  589. else if(!strcmp(name, "callback")) {
  590. responseHandler = value;
  591. }
  592. else if(!strcmp(name, "filename")) {
  593. outFileName = value;
  594. }
  595. else if(!strcmp(name, "tqx")) {
  596. // parse Google Visualization API options
  597. // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
  598. char *tqx_name, *tqx_value;
  599. while(value) {
  600. tqx_value = strsep_skip_consecutive_separators(&value, ";");
  601. if(!tqx_value || !*tqx_value) continue;
  602. tqx_name = strsep_skip_consecutive_separators(&tqx_value, ":");
  603. if(!tqx_name || !*tqx_name) continue;
  604. if(!tqx_value || !*tqx_value) continue;
  605. if(!strcmp(tqx_name, "version"))
  606. google_version = tqx_value;
  607. else if(!strcmp(tqx_name, "reqId"))
  608. google_reqId = tqx_value;
  609. else if(!strcmp(tqx_name, "sig")) {
  610. google_sig = tqx_value;
  611. google_timestamp = strtoul(google_sig, NULL, 0);
  612. }
  613. else if(!strcmp(tqx_name, "out")) {
  614. google_out = tqx_value;
  615. format = web_client_api_request_v1_data_google_format(google_out);
  616. }
  617. else if(!strcmp(tqx_name, "responseHandler"))
  618. responseHandler = tqx_value;
  619. else if(!strcmp(tqx_name, "outFileName"))
  620. outFileName = tqx_value;
  621. }
  622. }
  623. else if(!strcmp(name, "tier")) {
  624. tier = str2ul(value);
  625. if(tier < storage_tiers)
  626. options |= RRDR_OPTION_SELECTED_TIER;
  627. else
  628. tier = 0;
  629. }
  630. }
  631. // validate the google parameters given
  632. fix_google_param(google_out);
  633. fix_google_param(google_sig);
  634. fix_google_param(google_reqId);
  635. fix_google_param(google_version);
  636. fix_google_param(responseHandler);
  637. fix_google_param(outFileName);
  638. RRDSET *st = NULL;
  639. ONEWAYALLOC *owa = onewayalloc_create(0);
  640. QUERY_TARGET *qt = NULL;
  641. if(!is_valid_sp(chart) && !is_valid_sp(context)) {
  642. buffer_sprintf(w->response.data, "No chart or context is given.");
  643. goto cleanup;
  644. }
  645. if(chart && !context) {
  646. // check if this is a specific chart
  647. st = rrdset_find(host, chart);
  648. if (!st) st = rrdset_find_byname(host, chart);
  649. }
  650. long long before = (before_str && *before_str)?str2l(before_str):0;
  651. long long after = (after_str && *after_str) ?str2l(after_str):-600;
  652. int points = (points_str && *points_str)?str2i(points_str):0;
  653. int timeout = (timeout_str && *timeout_str)?str2i(timeout_str): 0;
  654. long group_time = (group_time_str && *group_time_str)?str2l(group_time_str):0;
  655. QUERY_TARGET_REQUEST qtr = {
  656. .version = 1,
  657. .after = after,
  658. .before = before,
  659. .host = host,
  660. .st = st,
  661. .nodes = NULL,
  662. .contexts = context,
  663. .instances = chart,
  664. .dimensions = (dimensions)?buffer_tostring(dimensions):NULL,
  665. .timeout_ms = timeout,
  666. .points = points,
  667. .format = format,
  668. .options = options,
  669. .time_group_method = group,
  670. .time_group_options = group_options,
  671. .resampling_time = group_time,
  672. .tier = tier,
  673. .chart_label_key = chart_label_key,
  674. .labels = chart_labels_filter,
  675. .query_source = QUERY_SOURCE_API_DATA,
  676. .priority = STORAGE_PRIORITY_NORMAL,
  677. .interrupt_callback = web_client_interrupt_callback,
  678. .interrupt_callback_data = w,
  679. .transaction = &w->transaction,
  680. };
  681. qt = query_target_create(&qtr);
  682. if(!qt || !qt->query.used) {
  683. buffer_sprintf(w->response.data, "No metrics where matched to query.");
  684. ret = HTTP_RESP_NOT_FOUND;
  685. goto cleanup;
  686. }
  687. web_client_timeout_checkpoint_set(w, timeout);
  688. if(web_client_timeout_checkpoint_and_check(w, NULL)) {
  689. ret = w->response.code;
  690. goto cleanup;
  691. }
  692. if(outFileName && *outFileName) {
  693. buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
  694. netdata_log_debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName);
  695. }
  696. if(format == DATASOURCE_DATATABLE_JSONP) {
  697. if(responseHandler == NULL)
  698. responseHandler = "google.visualization.Query.setResponse";
  699. netdata_log_debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
  700. w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
  701. );
  702. buffer_sprintf(
  703. w->response.data,
  704. "%s({version:'%s',reqId:'%s',status:'ok',sig:'%"PRId64"',table:",
  705. responseHandler,
  706. google_version,
  707. google_reqId,
  708. (int64_t)(st ? st->last_updated.tv_sec : 0));
  709. }
  710. else if(format == DATASOURCE_JSONP) {
  711. if(responseHandler == NULL)
  712. responseHandler = "callback";
  713. buffer_strcat(w->response.data, responseHandler);
  714. buffer_strcat(w->response.data, "(");
  715. }
  716. ret = data_query_execute(owa, w->response.data, qt, &last_timestamp_in_data);
  717. if(format == DATASOURCE_DATATABLE_JSONP) {
  718. if(google_timestamp < last_timestamp_in_data)
  719. buffer_strcat(w->response.data, "});");
  720. else {
  721. // the client already has the latest data
  722. buffer_flush(w->response.data);
  723. buffer_sprintf(w->response.data,
  724. "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
  725. responseHandler, google_version, google_reqId);
  726. }
  727. }
  728. else if(format == DATASOURCE_JSONP)
  729. buffer_strcat(w->response.data, ");");
  730. if(qt->internal.relative)
  731. buffer_no_cacheable(w->response.data);
  732. else
  733. buffer_cacheable(w->response.data);
  734. cleanup:
  735. query_target_release(qt);
  736. onewayalloc_destroy(owa);
  737. buffer_free(dimensions);
  738. return ret;
  739. }
  740. // Pings a netdata server:
  741. // /api/v1/registry?action=hello
  742. //
  743. // Access to a netdata registry:
  744. // /api/v1/registry?action=access&machine=${machine_guid}&name=${hostname}&url=${url}
  745. //
  746. // Delete from a netdata registry:
  747. // /api/v1/registry?action=delete&machine=${machine_guid}&name=${hostname}&url=${url}&delete_url=${delete_url}
  748. //
  749. // Search for the URLs of a machine:
  750. // /api/v1/registry?action=search&for=${machine_guid}
  751. //
  752. // Impersonate:
  753. // /api/v1/registry?action=switch&machine=${machine_guid}&name=${hostname}&url=${url}&to=${new_person_guid}
  754. inline int web_client_api_request_v1_registry(RRDHOST *host, struct web_client *w, char *url) {
  755. static uint32_t hash_action = 0, hash_access = 0, hash_hello = 0, hash_delete = 0, hash_search = 0,
  756. hash_switch = 0, hash_machine = 0, hash_url = 0, hash_name = 0, hash_delete_url = 0, hash_for = 0,
  757. hash_to = 0 /*, hash_redirects = 0 */;
  758. if(unlikely(!hash_action)) {
  759. hash_action = simple_hash("action");
  760. hash_access = simple_hash("access");
  761. hash_hello = simple_hash("hello");
  762. hash_delete = simple_hash("delete");
  763. hash_search = simple_hash("search");
  764. hash_switch = simple_hash("switch");
  765. hash_machine = simple_hash("machine");
  766. hash_url = simple_hash("url");
  767. hash_name = simple_hash("name");
  768. hash_delete_url = simple_hash("delete_url");
  769. hash_for = simple_hash("for");
  770. hash_to = simple_hash("to");
  771. /*
  772. hash_redirects = simple_hash("redirects");
  773. */
  774. }
  775. netdata_log_debug(D_WEB_CLIENT, "%llu: API v1 registry with URL '%s'", w->id, url);
  776. // TODO
  777. // The browser may send multiple cookies with our id
  778. char person_guid[UUID_STR_LEN] = "";
  779. char *cookie = strstr(w->response.data->buffer, NETDATA_REGISTRY_COOKIE_NAME "=");
  780. if(cookie)
  781. strncpyz(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME)], UUID_STR_LEN - 1);
  782. else if(!extract_bearer_token_from_request(w, person_guid, sizeof(person_guid)))
  783. person_guid[0] = '\0';
  784. char action = '\0';
  785. char *machine_guid = NULL,
  786. *machine_url = NULL,
  787. *url_name = NULL,
  788. *search_machine_guid = NULL,
  789. *delete_url = NULL,
  790. *to_person_guid = NULL;
  791. /*
  792. int redirects = 0;
  793. */
  794. // Don't cache registry responses
  795. buffer_no_cacheable(w->response.data);
  796. while(url) {
  797. char *value = strsep_skip_consecutive_separators(&url, "&");
  798. if (!value || !*value) continue;
  799. char *name = strsep_skip_consecutive_separators(&value, "=");
  800. if (!name || !*name) continue;
  801. if (!value || !*value) continue;
  802. netdata_log_debug(D_WEB_CLIENT, "%llu: API v1 registry query param '%s' with value '%s'", w->id, name, value);
  803. uint32_t hash = simple_hash(name);
  804. if(hash == hash_action && !strcmp(name, "action")) {
  805. uint32_t vhash = simple_hash(value);
  806. if(vhash == hash_access && !strcmp(value, "access")) action = 'A';
  807. else if(vhash == hash_hello && !strcmp(value, "hello")) action = 'H';
  808. else if(vhash == hash_delete && !strcmp(value, "delete")) action = 'D';
  809. else if(vhash == hash_search && !strcmp(value, "search")) action = 'S';
  810. else if(vhash == hash_switch && !strcmp(value, "switch")) action = 'W';
  811. #ifdef NETDATA_INTERNAL_CHECKS
  812. else netdata_log_error("unknown registry action '%s'", value);
  813. #endif /* NETDATA_INTERNAL_CHECKS */
  814. }
  815. /*
  816. else if(hash == hash_redirects && !strcmp(name, "redirects"))
  817. redirects = atoi(value);
  818. */
  819. else if(hash == hash_machine && !strcmp(name, "machine"))
  820. machine_guid = value;
  821. else if(hash == hash_url && !strcmp(name, "url"))
  822. machine_url = value;
  823. else if(action == 'A') {
  824. if(hash == hash_name && !strcmp(name, "name"))
  825. url_name = value;
  826. }
  827. else if(action == 'D') {
  828. if(hash == hash_delete_url && !strcmp(name, "delete_url"))
  829. delete_url = value;
  830. }
  831. else if(action == 'S') {
  832. if(hash == hash_for && !strcmp(name, "for"))
  833. search_machine_guid = value;
  834. }
  835. else if(action == 'W') {
  836. if(hash == hash_to && !strcmp(name, "to"))
  837. to_person_guid = value;
  838. }
  839. #ifdef NETDATA_INTERNAL_CHECKS
  840. else netdata_log_error("unused registry URL parameter '%s' with value '%s'", name, value);
  841. #endif /* NETDATA_INTERNAL_CHECKS */
  842. }
  843. bool do_not_track = respect_web_browser_do_not_track_policy && web_client_has_donottrack(w);
  844. if(unlikely(action == 'H')) {
  845. // HELLO request, dashboard ACL
  846. analytics_log_dashboard();
  847. if(unlikely(!http_can_access_dashboard(w)))
  848. return web_client_permission_denied(w);
  849. }
  850. else {
  851. // everything else, registry ACL
  852. if(unlikely(!http_can_access_registry(w)))
  853. return web_client_permission_denied(w);
  854. if(unlikely(do_not_track)) {
  855. buffer_flush(w->response.data);
  856. buffer_sprintf(w->response.data, "Your web browser is sending 'DNT: 1' (Do Not Track). The registry requires persistent cookies on your browser to work.");
  857. return HTTP_RESP_BAD_REQUEST;
  858. }
  859. }
  860. buffer_no_cacheable(w->response.data);
  861. switch(action) {
  862. case 'A':
  863. if(unlikely(!machine_guid || !machine_url || !url_name)) {
  864. netdata_log_error("Invalid registry request - access requires these parameters: machine ('%s'), url ('%s'), name ('%s')", machine_guid ? machine_guid : "UNSET", machine_url ? machine_url : "UNSET", url_name ? url_name : "UNSET");
  865. buffer_flush(w->response.data);
  866. buffer_strcat(w->response.data, "Invalid registry Access request.");
  867. return HTTP_RESP_BAD_REQUEST;
  868. }
  869. web_client_enable_tracking_required(w);
  870. return registry_request_access_json(host, w, person_guid, machine_guid, machine_url, url_name, now_realtime_sec());
  871. case 'D':
  872. if(unlikely(!machine_guid || !machine_url || !delete_url)) {
  873. netdata_log_error("Invalid registry request - delete requires these parameters: machine ('%s'), url ('%s'), delete_url ('%s')", machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", delete_url?delete_url:"UNSET");
  874. buffer_flush(w->response.data);
  875. buffer_strcat(w->response.data, "Invalid registry Delete request.");
  876. return HTTP_RESP_BAD_REQUEST;
  877. }
  878. web_client_enable_tracking_required(w);
  879. return registry_request_delete_json(host, w, person_guid, machine_guid, machine_url, delete_url, now_realtime_sec());
  880. case 'S':
  881. if(unlikely(!search_machine_guid)) {
  882. netdata_log_error("Invalid registry request - search requires these parameters: for ('%s')", search_machine_guid?search_machine_guid:"UNSET");
  883. buffer_flush(w->response.data);
  884. buffer_strcat(w->response.data, "Invalid registry Search request.");
  885. return HTTP_RESP_BAD_REQUEST;
  886. }
  887. web_client_enable_tracking_required(w);
  888. return registry_request_search_json(host, w, person_guid, search_machine_guid);
  889. case 'W':
  890. if(unlikely(!machine_guid || !machine_url || !to_person_guid)) {
  891. netdata_log_error("Invalid registry request - switching identity requires these parameters: machine ('%s'), url ('%s'), to ('%s')", machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", to_person_guid?to_person_guid:"UNSET");
  892. buffer_flush(w->response.data);
  893. buffer_strcat(w->response.data, "Invalid registry Switch request.");
  894. return HTTP_RESP_BAD_REQUEST;
  895. }
  896. web_client_enable_tracking_required(w);
  897. return registry_request_switch_json(host, w, person_guid, machine_guid, machine_url, to_person_guid, now_realtime_sec());
  898. case 'H':
  899. return registry_request_hello_json(host, w, do_not_track);
  900. default:
  901. buffer_flush(w->response.data);
  902. buffer_strcat(w->response.data, "Invalid registry request - you need to set an action: hello, access, delete, search");
  903. return HTTP_RESP_BAD_REQUEST;
  904. }
  905. }
  906. void web_client_api_request_v1_info_summary_alarm_statuses(RRDHOST *host, BUFFER *wb, const char *key) {
  907. buffer_json_member_add_object(wb, key);
  908. size_t normal = 0, warning = 0, critical = 0;
  909. RRDCALC *rc;
  910. foreach_rrdcalc_in_rrdhost_read(host, rc) {
  911. if(unlikely(!rc->rrdset || !rc->rrdset->last_collected_time.tv_sec))
  912. continue;
  913. switch(rc->status) {
  914. case RRDCALC_STATUS_WARNING:
  915. warning++;
  916. break;
  917. case RRDCALC_STATUS_CRITICAL:
  918. critical++;
  919. break;
  920. default:
  921. normal++;
  922. }
  923. }
  924. foreach_rrdcalc_in_rrdhost_done(rc);
  925. buffer_json_member_add_uint64(wb, "normal", normal);
  926. buffer_json_member_add_uint64(wb, "warning", warning);
  927. buffer_json_member_add_uint64(wb, "critical", critical);
  928. buffer_json_object_close(wb);
  929. }
  930. static inline void web_client_api_request_v1_info_mirrored_hosts_status(BUFFER *wb, RRDHOST *host) {
  931. buffer_json_add_array_item_object(wb);
  932. buffer_json_member_add_string(wb, "hostname", rrdhost_hostname(host));
  933. buffer_json_member_add_uint64(wb, "hops", host->system_info ? host->system_info->hops : (host == localhost) ? 0 : 1);
  934. buffer_json_member_add_boolean(wb, "reachable", (host == localhost || !rrdhost_flag_check(host, RRDHOST_FLAG_ORPHAN)));
  935. buffer_json_member_add_string(wb, "guid", host->machine_guid);
  936. buffer_json_member_add_uuid(wb, "node_id", host->node_id);
  937. rrdhost_aclk_state_lock(host);
  938. buffer_json_member_add_string(wb, "claim_id", host->aclk_state.claimed_id);
  939. rrdhost_aclk_state_unlock(host);
  940. buffer_json_object_close(wb);
  941. }
  942. static inline void web_client_api_request_v1_info_mirrored_hosts(BUFFER *wb) {
  943. RRDHOST *host;
  944. rrd_rdlock();
  945. buffer_json_member_add_array(wb, "mirrored_hosts");
  946. rrdhost_foreach_read(host)
  947. buffer_json_add_array_item_string(wb, rrdhost_hostname(host));
  948. buffer_json_array_close(wb);
  949. buffer_json_member_add_array(wb, "mirrored_hosts_status");
  950. rrdhost_foreach_read(host) {
  951. if ((host == localhost || !rrdhost_flag_check(host, RRDHOST_FLAG_ORPHAN))) {
  952. web_client_api_request_v1_info_mirrored_hosts_status(wb, host);
  953. }
  954. }
  955. rrdhost_foreach_read(host) {
  956. if ((host != localhost && rrdhost_flag_check(host, RRDHOST_FLAG_ORPHAN))) {
  957. web_client_api_request_v1_info_mirrored_hosts_status(wb, host);
  958. }
  959. }
  960. buffer_json_array_close(wb);
  961. rrd_unlock();
  962. }
  963. void host_labels2json(RRDHOST *host, BUFFER *wb, const char *key) {
  964. buffer_json_member_add_object(wb, key);
  965. rrdlabels_to_buffer_json_members(host->rrdlabels, wb);
  966. buffer_json_object_close(wb);
  967. }
  968. static void host_collectors(RRDHOST *host, BUFFER *wb) {
  969. buffer_json_member_add_array(wb, "collectors");
  970. DICTIONARY *dict = dictionary_create(DICT_OPTION_SINGLE_THREADED|DICT_OPTION_DONT_OVERWRITE_VALUE);
  971. RRDSET *st;
  972. char name[500];
  973. time_t now = now_realtime_sec();
  974. rrdset_foreach_read(st, host) {
  975. if (!rrdset_is_available_for_viewers(st))
  976. continue;
  977. sprintf(name, "%s:%s", rrdset_plugin_name(st), rrdset_module_name(st));
  978. bool old = 0;
  979. bool *set = dictionary_set(dict, name, &old, sizeof(bool));
  980. if(!*set) {
  981. *set = true;
  982. st->last_accessed_time_s = now;
  983. buffer_json_add_array_item_object(wb);
  984. buffer_json_member_add_string(wb, "plugin", rrdset_plugin_name(st));
  985. buffer_json_member_add_string(wb, "module", rrdset_module_name(st));
  986. buffer_json_object_close(wb);
  987. }
  988. }
  989. rrdset_foreach_done(st);
  990. dictionary_destroy(dict);
  991. buffer_json_array_close(wb);
  992. }
  993. extern int aclk_connected;
  994. inline int web_client_api_request_v1_info_fill_buffer(RRDHOST *host, BUFFER *wb) {
  995. buffer_json_initialize(wb, "\"", "\"", 0, true, BUFFER_JSON_OPTIONS_DEFAULT);
  996. buffer_json_member_add_string(wb, "version", rrdhost_program_version(host));
  997. buffer_json_member_add_string(wb, "uid", host->machine_guid);
  998. buffer_json_member_add_uint64(wb, "hosts-available", rrdhost_hosts_available());
  999. web_client_api_request_v1_info_mirrored_hosts(wb);
  1000. web_client_api_request_v1_info_summary_alarm_statuses(host, wb, "alarms");
  1001. buffer_json_member_add_string_or_empty(wb, "os_name", host->system_info->host_os_name);
  1002. buffer_json_member_add_string_or_empty(wb, "os_id", host->system_info->host_os_id);
  1003. buffer_json_member_add_string_or_empty(wb, "os_id_like", host->system_info->host_os_id_like);
  1004. buffer_json_member_add_string_or_empty(wb, "os_version", host->system_info->host_os_version);
  1005. buffer_json_member_add_string_or_empty(wb, "os_version_id", host->system_info->host_os_version_id);
  1006. buffer_json_member_add_string_or_empty(wb, "os_detection", host->system_info->host_os_detection);
  1007. buffer_json_member_add_string_or_empty(wb, "cores_total", host->system_info->host_cores);
  1008. buffer_json_member_add_string_or_empty(wb, "total_disk_space", host->system_info->host_disk_space);
  1009. buffer_json_member_add_string_or_empty(wb, "cpu_freq", host->system_info->host_cpu_freq);
  1010. buffer_json_member_add_string_or_empty(wb, "ram_total", host->system_info->host_ram_total);
  1011. buffer_json_member_add_string_or_omit(wb, "container_os_name", host->system_info->container_os_name);
  1012. buffer_json_member_add_string_or_omit(wb, "container_os_id", host->system_info->container_os_id);
  1013. buffer_json_member_add_string_or_omit(wb, "container_os_id_like", host->system_info->container_os_id_like);
  1014. buffer_json_member_add_string_or_omit(wb, "container_os_version", host->system_info->container_os_version);
  1015. buffer_json_member_add_string_or_omit(wb, "container_os_version_id", host->system_info->container_os_version_id);
  1016. buffer_json_member_add_string_or_omit(wb, "container_os_detection", host->system_info->container_os_detection);
  1017. buffer_json_member_add_string_or_omit(wb, "is_k8s_node", host->system_info->is_k8s_node);
  1018. buffer_json_member_add_string_or_empty(wb, "kernel_name", host->system_info->kernel_name);
  1019. buffer_json_member_add_string_or_empty(wb, "kernel_version", host->system_info->kernel_version);
  1020. buffer_json_member_add_string_or_empty(wb, "architecture", host->system_info->architecture);
  1021. buffer_json_member_add_string_or_empty(wb, "virtualization", host->system_info->virtualization);
  1022. buffer_json_member_add_string_or_empty(wb, "virt_detection", host->system_info->virt_detection);
  1023. buffer_json_member_add_string_or_empty(wb, "container", host->system_info->container);
  1024. buffer_json_member_add_string_or_empty(wb, "container_detection", host->system_info->container_detection);
  1025. buffer_json_member_add_string_or_omit(wb, "cloud_provider_type", host->system_info->cloud_provider_type);
  1026. buffer_json_member_add_string_or_omit(wb, "cloud_instance_type", host->system_info->cloud_instance_type);
  1027. buffer_json_member_add_string_or_omit(wb, "cloud_instance_region", host->system_info->cloud_instance_region);
  1028. host_labels2json(host, wb, "host_labels");
  1029. host_functions2json(host, wb);
  1030. host_collectors(host, wb);
  1031. buffer_json_member_add_boolean(wb, "cloud-enabled", netdata_cloud_enabled);
  1032. #ifdef ENABLE_ACLK
  1033. buffer_json_member_add_boolean(wb, "cloud-available", true);
  1034. #else
  1035. buffer_json_member_add_boolean(wb, "cloud-available", false);
  1036. #endif
  1037. char *agent_id = get_agent_claimid();
  1038. buffer_json_member_add_boolean(wb, "agent-claimed", agent_id != NULL);
  1039. freez(agent_id);
  1040. #ifdef ENABLE_ACLK
  1041. buffer_json_member_add_boolean(wb, "aclk-available", aclk_connected);
  1042. #else
  1043. buffer_json_member_add_boolean(wb, "aclk-available", false);
  1044. #endif
  1045. buffer_json_member_add_string(wb, "memory-mode", rrd_memory_mode_name(host->rrd_memory_mode));
  1046. #ifdef ENABLE_DBENGINE
  1047. buffer_json_member_add_uint64(wb, "multidb-disk-quota", default_multidb_disk_quota_mb);
  1048. buffer_json_member_add_uint64(wb, "page-cache-size", default_rrdeng_page_cache_mb);
  1049. #endif // ENABLE_DBENGINE
  1050. buffer_json_member_add_boolean(wb, "web-enabled", web_server_mode != WEB_SERVER_MODE_NONE);
  1051. buffer_json_member_add_boolean(wb, "stream-enabled", default_rrdpush_enabled);
  1052. buffer_json_member_add_boolean(wb, "stream-compression",
  1053. host->sender && host->sender->compressor.initialized);
  1054. #ifdef ENABLE_HTTPS
  1055. buffer_json_member_add_boolean(wb, "https-enabled", true);
  1056. #else
  1057. buffer_json_member_add_boolean(wb, "https-enabled", false);
  1058. #endif
  1059. buffer_json_member_add_quoted_string(wb, "buildinfo", analytics_data.netdata_buildinfo);
  1060. buffer_json_member_add_quoted_string(wb, "release-channel", analytics_data.netdata_config_release_channel);
  1061. buffer_json_member_add_quoted_string(wb, "notification-methods", analytics_data.netdata_notification_methods);
  1062. buffer_json_member_add_boolean(wb, "exporting-enabled", analytics_data.exporting_enabled);
  1063. buffer_json_member_add_quoted_string(wb, "exporting-connectors", analytics_data.netdata_exporting_connectors);
  1064. buffer_json_member_add_uint64(wb, "allmetrics-prometheus-used", analytics_data.prometheus_hits);
  1065. buffer_json_member_add_uint64(wb, "allmetrics-shell-used", analytics_data.shell_hits);
  1066. buffer_json_member_add_uint64(wb, "allmetrics-json-used", analytics_data.json_hits);
  1067. buffer_json_member_add_uint64(wb, "dashboard-used", analytics_data.dashboard_hits);
  1068. buffer_json_member_add_uint64(wb, "charts-count", analytics_data.charts_count);
  1069. buffer_json_member_add_uint64(wb, "metrics-count", analytics_data.metrics_count);
  1070. #if defined(ENABLE_ML)
  1071. buffer_json_member_add_object(wb, "ml-info");
  1072. ml_host_get_info(host, wb);
  1073. buffer_json_object_close(wb);
  1074. #endif
  1075. buffer_json_finalize(wb);
  1076. return 0;
  1077. }
  1078. #if defined(ENABLE_ML)
  1079. int web_client_api_request_v1_ml_info(RRDHOST *host, struct web_client *w, char *url) {
  1080. (void) url;
  1081. if (!netdata_ready)
  1082. return HTTP_RESP_SERVICE_UNAVAILABLE;
  1083. BUFFER *wb = w->response.data;
  1084. buffer_flush(wb);
  1085. wb->content_type = CT_APPLICATION_JSON;
  1086. buffer_json_initialize(wb, "\"", "\"", 0, true, BUFFER_JSON_OPTIONS_DEFAULT);
  1087. ml_host_get_detection_info(host, wb);
  1088. buffer_json_finalize(wb);
  1089. buffer_no_cacheable(wb);
  1090. return HTTP_RESP_OK;
  1091. }
  1092. int web_client_api_request_v1_ml_models(RRDHOST *host, struct web_client *w, char *url) {
  1093. (void) url;
  1094. if (!netdata_ready)
  1095. return HTTP_RESP_SERVICE_UNAVAILABLE;
  1096. BUFFER *wb = w->response.data;
  1097. buffer_flush(wb);
  1098. wb->content_type = CT_APPLICATION_JSON;
  1099. ml_host_get_models(host, wb);
  1100. buffer_no_cacheable(wb);
  1101. return HTTP_RESP_OK;
  1102. }
  1103. #endif // ENABLE_ML
  1104. inline int web_client_api_request_v1_info(RRDHOST *host, struct web_client *w, char *url) {
  1105. (void)url;
  1106. if (!netdata_ready) return HTTP_RESP_SERVICE_UNAVAILABLE;
  1107. BUFFER *wb = w->response.data;
  1108. buffer_flush(wb);
  1109. wb->content_type = CT_APPLICATION_JSON;
  1110. web_client_api_request_v1_info_fill_buffer(host, wb);
  1111. buffer_no_cacheable(wb);
  1112. return HTTP_RESP_OK;
  1113. }
  1114. static int web_client_api_request_v1_aclk_state(RRDHOST *host, struct web_client *w, char *url) {
  1115. UNUSED(url);
  1116. UNUSED(host);
  1117. if (!netdata_ready) return HTTP_RESP_SERVICE_UNAVAILABLE;
  1118. BUFFER *wb = w->response.data;
  1119. buffer_flush(wb);
  1120. char *str = aclk_state_json();
  1121. buffer_strcat(wb, str);
  1122. freez(str);
  1123. wb->content_type = CT_APPLICATION_JSON;
  1124. buffer_no_cacheable(wb);
  1125. return HTTP_RESP_OK;
  1126. }
  1127. int web_client_api_request_v1_metric_correlations(RRDHOST *host, struct web_client *w, char *url) {
  1128. return web_client_api_request_weights(host, w, url, default_metric_correlations_method, WEIGHTS_FORMAT_CHARTS, 1);
  1129. }
  1130. int web_client_api_request_v1_weights(RRDHOST *host, struct web_client *w, char *url) {
  1131. return web_client_api_request_weights(host, w, url, WEIGHTS_METHOD_ANOMALY_RATE, WEIGHTS_FORMAT_CONTEXTS, 1);
  1132. }
  1133. static void web_client_progress_functions_update(void *data, size_t done, size_t all) {
  1134. // handle progress updates from the plugin
  1135. struct web_client *w = data;
  1136. query_progress_functions_update(&w->transaction, done, all);
  1137. }
  1138. int web_client_api_request_v1_function(RRDHOST *host, struct web_client *w, char *url) {
  1139. if (!netdata_ready)
  1140. return HTTP_RESP_SERVICE_UNAVAILABLE;
  1141. int timeout = 0;
  1142. const char *function = NULL;
  1143. while (url) {
  1144. char *value = strsep_skip_consecutive_separators(&url, "&");
  1145. if (!value || !*value)
  1146. continue;
  1147. char *name = strsep_skip_consecutive_separators(&value, "=");
  1148. if (!name || !*name)
  1149. continue;
  1150. if (!strcmp(name, "function"))
  1151. function = value;
  1152. else if (!strcmp(name, "timeout"))
  1153. timeout = (int) strtoul(value, NULL, 0);
  1154. }
  1155. BUFFER *wb = w->response.data;
  1156. buffer_flush(wb);
  1157. wb->content_type = CT_APPLICATION_JSON;
  1158. buffer_no_cacheable(wb);
  1159. char transaction[UUID_COMPACT_STR_LEN];
  1160. uuid_unparse_lower_compact(w->transaction, transaction);
  1161. CLEAN_BUFFER *source = buffer_create(100, NULL);
  1162. web_client_source2buffer(w, source);
  1163. return rrd_function_run(host, wb, timeout, w->access, function, true, transaction,
  1164. NULL, NULL,
  1165. web_client_progress_functions_update, w,
  1166. web_client_interrupt_callback, w, NULL,
  1167. buffer_tostring(source));
  1168. }
  1169. int web_client_api_request_v1_functions(RRDHOST *host, struct web_client *w, char *url __maybe_unused) {
  1170. if (!netdata_ready)
  1171. return HTTP_RESP_SERVICE_UNAVAILABLE;
  1172. BUFFER *wb = w->response.data;
  1173. buffer_flush(wb);
  1174. wb->content_type = CT_APPLICATION_JSON;
  1175. buffer_no_cacheable(wb);
  1176. buffer_json_initialize(wb, "\"", "\"", 0, true, BUFFER_JSON_OPTIONS_DEFAULT);
  1177. host_functions2json(host, wb);
  1178. buffer_json_finalize(wb);
  1179. return HTTP_RESP_OK;
  1180. }
  1181. void web_client_source2buffer(struct web_client *w, BUFFER *source) {
  1182. if(web_client_flag_check(w, WEB_CLIENT_FLAG_AUTH_CLOUD))
  1183. buffer_sprintf(source, "method=NC");
  1184. else if(web_client_flag_check(w, WEB_CLIENT_FLAG_AUTH_BEARER))
  1185. buffer_sprintf(source, "method=api-bearer");
  1186. else
  1187. buffer_sprintf(source, "method=api");
  1188. if(web_client_flag_check(w, WEB_CLIENT_FLAG_AUTH_CLOUD) || web_client_flag_check(w, WEB_CLIENT_FLAG_AUTH_BEARER)) {
  1189. buffer_sprintf(source, ",role=%s", http_id2access(w->access));
  1190. char uuid_str[UUID_COMPACT_STR_LEN];
  1191. uuid_unparse_lower_compact(w->auth.cloud_account_id, uuid_str);
  1192. buffer_sprintf(source, ",user=%s,account=%s", w->auth.client_name, uuid_str);
  1193. }
  1194. else if(web_client_flag_check(w, WEB_CLIENT_FLAG_AUTH_GOD))
  1195. buffer_strcat(source, ",role=god");
  1196. else
  1197. buffer_sprintf(source, ",role=%s", http_id2access(w->access));
  1198. if(w->client_ip[0])
  1199. buffer_sprintf(source, ",ip=%s", w->client_ip);
  1200. if(w->forwarded_for)
  1201. buffer_sprintf(source, ",forwarded_for=%s", w->forwarded_for);
  1202. }
  1203. static int web_client_api_request_v1_config(RRDHOST *host, struct web_client *w, char *url __maybe_unused) {
  1204. char *action = "tree";
  1205. char *path = "/";
  1206. char *id = NULL;
  1207. char *add_name = NULL;
  1208. int timeout = 120;
  1209. while(url) {
  1210. char *value = strsep_skip_consecutive_separators(&url, "&");
  1211. if(!value || !*value) continue;
  1212. char *name = strsep_skip_consecutive_separators(&value, "=");
  1213. if(!name || !*name) continue;
  1214. if(!value || !*value) continue;
  1215. // name and value are now the parameters
  1216. // they are not null and not empty
  1217. if(!strcmp(name, "action"))
  1218. action = value;
  1219. else if(!strcmp(name, "path"))
  1220. path = value;
  1221. else if(!strcmp(name, "id"))
  1222. id = value;
  1223. else if(!strcmp(name, "name"))
  1224. add_name = value;
  1225. else if(!strcmp(name, "timeout")) {
  1226. timeout = (int)strtol(value, NULL, 10);
  1227. if(timeout < 10)
  1228. timeout = 10;
  1229. }
  1230. }
  1231. char transaction[UUID_COMPACT_STR_LEN];
  1232. uuid_unparse_lower_compact(w->transaction, transaction);
  1233. size_t len = strlen(action) + (id ? strlen(id) : 0) + strlen(path) + (add_name ? strlen(add_name) : 0) + 100;
  1234. char cmd[len];
  1235. if(strcmp(action, "tree") == 0)
  1236. snprintfz(cmd, sizeof(cmd), PLUGINSD_FUNCTION_CONFIG " tree '%s' '%s'", path, id?id:"");
  1237. else {
  1238. DYNCFG_CMDS c = dyncfg_cmds2id(action);
  1239. if(!id || !*id || !dyncfg_is_valid_id(id)) {
  1240. rrd_call_function_error(w->response.data, "invalid id given", HTTP_RESP_BAD_REQUEST);
  1241. return HTTP_RESP_BAD_REQUEST;
  1242. }
  1243. if(c == DYNCFG_CMD_NONE) {
  1244. rrd_call_function_error(w->response.data, "invalid action given", HTTP_RESP_BAD_REQUEST);
  1245. return HTTP_RESP_BAD_REQUEST;
  1246. }
  1247. else if(c == DYNCFG_CMD_ADD) {
  1248. if(!add_name || !*add_name || !dyncfg_is_valid_id(add_name)) {
  1249. rrd_call_function_error(w->response.data, "invalid name given", HTTP_RESP_BAD_REQUEST);
  1250. return HTTP_RESP_BAD_REQUEST;
  1251. }
  1252. snprintfz(cmd, sizeof(cmd), PLUGINSD_FUNCTION_CONFIG " %s %s %s", id, dyncfg_id2cmd_one(c), add_name);
  1253. }
  1254. else
  1255. snprintfz(cmd, sizeof(cmd), PLUGINSD_FUNCTION_CONFIG " %s %s", id, dyncfg_id2cmd_one(c));
  1256. }
  1257. CLEAN_BUFFER *source = buffer_create(100, NULL);
  1258. web_client_source2buffer(w, source);
  1259. buffer_flush(w->response.data);
  1260. int code = rrd_function_run(host, w->response.data, timeout, w->access, cmd,
  1261. true, transaction,
  1262. NULL, NULL,
  1263. web_client_progress_functions_update, w,
  1264. web_client_interrupt_callback, w,
  1265. w->payload, buffer_tostring(source));
  1266. return code;
  1267. }
  1268. #ifndef ENABLE_DBENGINE
  1269. int web_client_api_request_v1_dbengine_stats(RRDHOST *host __maybe_unused, struct web_client *w __maybe_unused, char *url __maybe_unused) {
  1270. return HTTP_RESP_NOT_FOUND;
  1271. }
  1272. #else
  1273. static void web_client_api_v1_dbengine_stats_for_tier(BUFFER *wb, size_t tier) {
  1274. RRDENG_SIZE_STATS stats = rrdeng_size_statistics(multidb_ctx[tier]);
  1275. buffer_sprintf(wb,
  1276. "\n\t\t\"default_granularity_secs\":%zu"
  1277. ",\n\t\t\"sizeof_datafile\":%zu"
  1278. ",\n\t\t\"sizeof_page_in_cache\":%zu"
  1279. ",\n\t\t\"sizeof_point_data\":%zu"
  1280. ",\n\t\t\"sizeof_page_data\":%zu"
  1281. ",\n\t\t\"pages_per_extent\":%zu"
  1282. ",\n\t\t\"datafiles\":%zu"
  1283. ",\n\t\t\"extents\":%zu"
  1284. ",\n\t\t\"extents_pages\":%zu"
  1285. ",\n\t\t\"points\":%zu"
  1286. ",\n\t\t\"metrics\":%zu"
  1287. ",\n\t\t\"metrics_pages\":%zu"
  1288. ",\n\t\t\"extents_compressed_bytes\":%zu"
  1289. ",\n\t\t\"pages_uncompressed_bytes\":%zu"
  1290. ",\n\t\t\"pages_duration_secs\":%lld"
  1291. ",\n\t\t\"single_point_pages\":%zu"
  1292. ",\n\t\t\"first_t\":%ld"
  1293. ",\n\t\t\"last_t\":%ld"
  1294. ",\n\t\t\"database_retention_secs\":%lld"
  1295. ",\n\t\t\"average_compression_savings\":%0.2f"
  1296. ",\n\t\t\"average_point_duration_secs\":%0.2f"
  1297. ",\n\t\t\"average_metric_retention_secs\":%0.2f"
  1298. ",\n\t\t\"ephemeral_metrics_per_day_percent\":%0.2f"
  1299. ",\n\t\t\"average_page_size_bytes\":%0.2f"
  1300. ",\n\t\t\"estimated_concurrently_collected_metrics\":%zu"
  1301. ",\n\t\t\"currently_collected_metrics\":%zu"
  1302. ",\n\t\t\"disk_space\":%zu"
  1303. ",\n\t\t\"max_disk_space\":%zu"
  1304. , stats.default_granularity_secs
  1305. , stats.sizeof_datafile
  1306. , stats.sizeof_page_in_cache
  1307. , stats.sizeof_point_data
  1308. , stats.sizeof_page_data
  1309. , stats.pages_per_extent
  1310. , stats.datafiles
  1311. , stats.extents
  1312. , stats.extents_pages
  1313. , stats.points
  1314. , stats.metrics
  1315. , stats.metrics_pages
  1316. , stats.extents_compressed_bytes
  1317. , stats.pages_uncompressed_bytes
  1318. , (long long)stats.pages_duration_secs
  1319. , stats.single_point_pages
  1320. , stats.first_time_s
  1321. , stats.last_time_s
  1322. , (long long)stats.database_retention_secs
  1323. , stats.average_compression_savings
  1324. , stats.average_point_duration_secs
  1325. , stats.average_metric_retention_secs
  1326. , stats.ephemeral_metrics_per_day_percent
  1327. , stats.average_page_size_bytes
  1328. , stats.estimated_concurrently_collected_metrics
  1329. , stats.currently_collected_metrics
  1330. , stats.disk_space
  1331. , stats.max_disk_space
  1332. );
  1333. }
  1334. int web_client_api_request_v1_dbengine_stats(RRDHOST *host __maybe_unused, struct web_client *w, char *url __maybe_unused) {
  1335. if (!netdata_ready)
  1336. return HTTP_RESP_SERVICE_UNAVAILABLE;
  1337. BUFFER *wb = w->response.data;
  1338. buffer_flush(wb);
  1339. if(!dbengine_enabled) {
  1340. buffer_strcat(wb, "dbengine is not enabled");
  1341. return HTTP_RESP_NOT_FOUND;
  1342. }
  1343. wb->content_type = CT_APPLICATION_JSON;
  1344. buffer_no_cacheable(wb);
  1345. buffer_strcat(wb, "{");
  1346. for(size_t tier = 0; tier < storage_tiers ;tier++) {
  1347. buffer_sprintf(wb, "%s\n\t\"tier%zu\": {", tier?",":"", tier);
  1348. web_client_api_v1_dbengine_stats_for_tier(wb, tier);
  1349. buffer_strcat(wb, "\n\t}");
  1350. }
  1351. buffer_strcat(wb, "\n}");
  1352. return HTTP_RESP_OK;
  1353. }
  1354. #endif
  1355. #define HLT_MGM "manage/health"
  1356. int web_client_api_request_v1_mgmt(RRDHOST *host, struct web_client *w, char *url) {
  1357. const char *haystack = buffer_tostring(w->url_path_decoded);
  1358. char *needle;
  1359. buffer_flush(w->response.data);
  1360. if ((needle = strstr(haystack, HLT_MGM)) == NULL) {
  1361. buffer_strcat(w->response.data, "Invalid management request. Curently only 'health' is supported.");
  1362. return HTTP_RESP_NOT_FOUND;
  1363. }
  1364. needle += strlen(HLT_MGM);
  1365. if (*needle != '\0') {
  1366. buffer_strcat(w->response.data, "Invalid management request. Curently only 'health' is supported.");
  1367. return HTTP_RESP_NOT_FOUND;
  1368. }
  1369. return web_client_api_request_v1_mgmt_health(host, w, url);
  1370. }
  1371. static struct web_api_command api_commands_v1[] = {
  1372. {"info", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_info, 0 },
  1373. {"data", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_data, 0 },
  1374. {"chart", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_chart, 0 },
  1375. {"charts", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_charts, 0 },
  1376. {"context", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_context, 0 },
  1377. {"contexts", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_contexts, 0 },
  1378. // registry checks the ACL by itself, so we allow everything
  1379. {"registry", 0, HTTP_ACL_NOCHECK, web_client_api_request_v1_registry, 0 },
  1380. // badges can be fetched with both dashboard and badge permissions
  1381. {"badge.svg", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC | HTTP_ACL_BADGE, web_client_api_request_v1_badge, 0 },
  1382. {"alarms", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_alarms, 0 },
  1383. {"alarms_values", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_alarms_values, 0 },
  1384. {"alarm_log", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_alarm_log, 0 },
  1385. {"alarm_variables", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_alarm_variables, 0 },
  1386. {"alarm_count", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_alarm_count, 0 },
  1387. {"allmetrics", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_allmetrics, 0 },
  1388. #if defined(ENABLE_ML)
  1389. {"ml_info", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_ml_info, 0 },
  1390. // { "ml_models", 0, HTTP_ACL_DASHBOARD, web_client_api_request_v1_ml_models },
  1391. #endif
  1392. {"manage", 0, HTTP_ACL_MGMT | HTTP_ACL_ACLK, web_client_api_request_v1_mgmt, 1 },
  1393. {"aclk", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_aclk_state, 0 },
  1394. {"metric_correlations", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_metric_correlations, 0 },
  1395. {"weights", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_weights, 0 },
  1396. {"function", 0, HTTP_ACL_ACLK_WEBRTC_DASHBOARD_WITH_OPTIONAL_BEARER | ACL_DEV_OPEN_ACCESS, web_client_api_request_v1_function, 0 },
  1397. {"functions", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC | ACL_DEV_OPEN_ACCESS, web_client_api_request_v1_functions, 0 },
  1398. {"config", 0, HTTP_ACL_ACLK_WEBRTC_DASHBOARD_WITH_OPTIONAL_BEARER | ACL_DEV_OPEN_ACCESS, web_client_api_request_v1_config, 0 },
  1399. {"dbengine_stats", 0, HTTP_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v1_dbengine_stats, 0 },
  1400. // terminator
  1401. {NULL, 0, HTTP_ACL_NONE, NULL, 0 },
  1402. };
  1403. inline int web_client_api_request_v1(RRDHOST *host, struct web_client *w, char *url_path_endpoint) {
  1404. static int initialized = 0;
  1405. if(unlikely(initialized == 0)) {
  1406. initialized = 1;
  1407. for(int i = 0; api_commands_v1[i].command ; i++)
  1408. api_commands_v1[i].hash = simple_hash(api_commands_v1[i].command);
  1409. }
  1410. return web_client_api_request_vX(host, w, url_path_endpoint, api_commands_v1);
  1411. }