web_api_v1.c 59 KB

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