prometheus.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #define EXPORTINGS_INTERNALS
  3. #include "prometheus.h"
  4. // ----------------------------------------------------------------------------
  5. // PROMETHEUS
  6. // /api/v1/allmetrics?format=prometheus and /api/v1/allmetrics?format=prometheus_all_hosts
  7. static int is_matches_rrdset(struct instance *instance, RRDSET *st, SIMPLE_PATTERN *filter) {
  8. if (instance->config.options & EXPORTING_OPTION_SEND_NAMES) {
  9. return simple_pattern_matches_string(filter, st->name);
  10. }
  11. return simple_pattern_matches_string(filter, st->id);
  12. }
  13. /**
  14. * Check if a chart can be sent to Prometheus
  15. *
  16. * @param instance an instance data structure.
  17. * @param st a chart.
  18. * @param filter a simple pattern to match against.
  19. * @return Returns 1 if the chart can be sent, 0 otherwise.
  20. */
  21. inline int can_send_rrdset(struct instance *instance, RRDSET *st, SIMPLE_PATTERN *filter)
  22. {
  23. #ifdef NETDATA_INTERNAL_CHECKS
  24. RRDHOST *host = st->rrdhost;
  25. #endif
  26. if (unlikely(rrdset_flag_check(st, RRDSET_FLAG_EXPORTING_IGNORE)))
  27. return 0;
  28. if (filter) {
  29. if (!is_matches_rrdset(instance, st, filter)) {
  30. return 0;
  31. }
  32. } else if (unlikely(!rrdset_flag_check(st, RRDSET_FLAG_EXPORTING_SEND))) {
  33. // we have not checked this chart
  34. if (is_matches_rrdset(instance, st, instance->config.charts_pattern)) {
  35. rrdset_flag_set(st, RRDSET_FLAG_EXPORTING_SEND);
  36. } else {
  37. rrdset_flag_set(st, RRDSET_FLAG_EXPORTING_IGNORE);
  38. netdata_log_debug(
  39. D_EXPORTING,
  40. "EXPORTING: not sending chart '%s' of host '%s', because it is disabled for exporting.",
  41. rrdset_id(st),
  42. rrdhost_hostname(host));
  43. return 0;
  44. }
  45. }
  46. if (unlikely(!rrdset_is_available_for_exporting_and_alarms(st))) {
  47. netdata_log_debug(
  48. D_EXPORTING,
  49. "EXPORTING: not sending chart '%s' of host '%s', because it is not available for exporting.",
  50. rrdset_id(st),
  51. rrdhost_hostname(host));
  52. return 0;
  53. }
  54. if (unlikely(
  55. st->rrd_memory_mode == RRD_MEMORY_MODE_NONE &&
  56. !(EXPORTING_OPTIONS_DATA_SOURCE(instance->config.options) == EXPORTING_SOURCE_DATA_AS_COLLECTED))) {
  57. netdata_log_debug(
  58. D_EXPORTING,
  59. "EXPORTING: not sending chart '%s' of host '%s' because its memory mode is '%s' and the exporting connector requires database access.",
  60. rrdset_id(st),
  61. rrdhost_hostname(host),
  62. rrd_memory_mode_name(host->rrd_memory_mode));
  63. return 0;
  64. }
  65. return 1;
  66. }
  67. static struct prometheus_server {
  68. const char *server;
  69. uint32_t hash;
  70. RRDHOST *host;
  71. time_t last_access;
  72. struct prometheus_server *next;
  73. } *prometheus_server_root = NULL;
  74. static netdata_mutex_t prometheus_server_root_mutex = NETDATA_MUTEX_INITIALIZER;
  75. /**
  76. * Clean server root local structure
  77. */
  78. void prometheus_clean_server_root()
  79. {
  80. if (prometheus_server_root) {
  81. netdata_mutex_lock(&prometheus_server_root_mutex);
  82. struct prometheus_server *ps;
  83. for (ps = prometheus_server_root; ps; ) {
  84. struct prometheus_server *current = ps;
  85. ps = ps->next;
  86. if(current->server)
  87. freez((void *)current->server);
  88. freez(current);
  89. }
  90. prometheus_server_root = NULL;
  91. netdata_mutex_unlock(&prometheus_server_root_mutex);
  92. }
  93. }
  94. /**
  95. * Get the last time when a Prometheus server scraped the Netdata Prometheus exporter.
  96. *
  97. * @param server the name of the Prometheus server.
  98. * @param host a data collecting host.
  99. * @param now actual time.
  100. * @return Returns the last time when the server accessed Netdata, or 0 if it is the first occurrence.
  101. */
  102. static inline time_t prometheus_server_last_access(const char *server, RRDHOST *host, time_t now)
  103. {
  104. #ifdef UNIT_TESTING
  105. return 0;
  106. #endif
  107. uint32_t hash = simple_hash(server);
  108. netdata_mutex_lock(&prometheus_server_root_mutex);
  109. struct prometheus_server *ps;
  110. for (ps = prometheus_server_root; ps; ps = ps->next) {
  111. if (host == ps->host && hash == ps->hash && !strcmp(server, ps->server)) {
  112. time_t last = ps->last_access;
  113. ps->last_access = now;
  114. netdata_mutex_unlock(&prometheus_server_root_mutex);
  115. return last;
  116. }
  117. }
  118. ps = callocz(1, sizeof(struct prometheus_server));
  119. ps->server = strdupz(server);
  120. ps->hash = hash;
  121. ps->host = host;
  122. ps->last_access = now;
  123. ps->next = prometheus_server_root;
  124. prometheus_server_root = ps;
  125. netdata_mutex_unlock(&prometheus_server_root_mutex);
  126. return 0;
  127. }
  128. /**
  129. * Copy and sanitize name.
  130. *
  131. * @param d a destination string.
  132. * @param s a source string.
  133. * @param usable the number of characters to copy.
  134. * @return Returns the length of the copied string.
  135. */
  136. inline size_t prometheus_name_copy(char *d, const char *s, size_t usable)
  137. {
  138. size_t n;
  139. for (n = 0; *s && n < usable; d++, s++, n++) {
  140. register char c = *s;
  141. if (!isalnum(c))
  142. *d = '_';
  143. else
  144. *d = c;
  145. }
  146. *d = '\0';
  147. return n;
  148. }
  149. /**
  150. * Copy and sanitize label.
  151. *
  152. * @param d a destination string.
  153. * @param s a source string.
  154. * @param usable the number of characters to copy.
  155. * @return Returns the length of the copied string.
  156. */
  157. inline size_t prometheus_label_copy(char *d, const char *s, size_t usable)
  158. {
  159. size_t n;
  160. // make sure we can escape one character without overflowing the buffer
  161. usable--;
  162. for (n = 0; *s && n < usable; d++, s++, n++) {
  163. register char c = *s;
  164. if (unlikely(c == '"' || c == '\\' || c == '\n')) {
  165. *d++ = '\\';
  166. n++;
  167. }
  168. *d = c;
  169. }
  170. *d = '\0';
  171. return n;
  172. }
  173. /**
  174. * Copy and sanitize units.
  175. *
  176. * @param d a destination string.
  177. * @param s a source string.
  178. * @param usable the number of characters to copy.
  179. * @param showoldunits set this flag to 1 to show old (before v1.12) units.
  180. * @return Returns the destination string.
  181. */
  182. inline char *prometheus_units_copy(char *d, const char *s, size_t usable, int showoldunits)
  183. {
  184. const char *sorig = s;
  185. char *ret = d;
  186. size_t n;
  187. // Fix for issue 5227
  188. if (unlikely(showoldunits)) {
  189. static struct {
  190. const char *newunit;
  191. uint32_t hash;
  192. const char *oldunit;
  193. } units[] = { { "KiB/s", 0, "kilobytes/s" },
  194. { "MiB/s", 0, "MB/s" },
  195. { "GiB/s", 0, "GB/s" },
  196. { "KiB", 0, "KB" },
  197. { "MiB", 0, "MB" },
  198. { "GiB", 0, "GB" },
  199. { "inodes", 0, "Inodes" },
  200. { "percentage", 0, "percent" },
  201. { "faults/s", 0, "page faults/s" },
  202. { "KiB/operation", 0, "kilobytes per operation" },
  203. { "milliseconds/operation", 0, "ms per operation" },
  204. { NULL, 0, NULL } };
  205. static int initialized = 0;
  206. int i;
  207. if (unlikely(!initialized)) {
  208. for (i = 0; units[i].newunit; i++)
  209. units[i].hash = simple_hash(units[i].newunit);
  210. initialized = 1;
  211. }
  212. uint32_t hash = simple_hash(s);
  213. for (i = 0; units[i].newunit; i++) {
  214. if (unlikely(hash == units[i].hash && !strcmp(s, units[i].newunit))) {
  215. // netdata_log_info("matched extension for filename '%s': '%s'", filename, last_dot);
  216. s = units[i].oldunit;
  217. sorig = s;
  218. break;
  219. }
  220. }
  221. }
  222. *d++ = '_';
  223. for (n = 1; *s && n < usable; d++, s++, n++) {
  224. register char c = *s;
  225. if (!isalnum(c))
  226. *d = '_';
  227. else
  228. *d = c;
  229. }
  230. if (n == 2 && sorig[0] == '%') {
  231. n = 0;
  232. d = ret;
  233. s = "_percent";
  234. for (; *s && n < usable; n++)
  235. *d++ = *s++;
  236. } else if (n > 3 && sorig[n - 3] == '/' && sorig[n - 2] == 's') {
  237. n = n - 2;
  238. d -= 2;
  239. s = "_persec";
  240. for (; *s && n < usable; n++)
  241. *d++ = *s++;
  242. }
  243. *d = '\0';
  244. return ret;
  245. }
  246. /**
  247. * Format host labels for the Prometheus exporter
  248. *
  249. * @param instance an instance data structure.
  250. * @param host a data collecting host.
  251. */
  252. struct format_prometheus_label_callback {
  253. struct instance *instance;
  254. size_t count;
  255. };
  256. static int format_prometheus_label_callback(const char *name, const char *value, RRDLABEL_SRC ls __maybe_unused, void *data) {
  257. struct format_prometheus_label_callback *d = (struct format_prometheus_label_callback *)data;
  258. if (!should_send_label(d->instance, ls)) return 0;
  259. char k[PROMETHEUS_ELEMENT_MAX + 1];
  260. char v[PROMETHEUS_ELEMENT_MAX + 1];
  261. prometheus_name_copy(k, name, PROMETHEUS_ELEMENT_MAX);
  262. prometheus_label_copy(v, value, PROMETHEUS_ELEMENT_MAX);
  263. if (*k && *v) {
  264. if (d->count > 0) buffer_strcat(d->instance->labels_buffer, ",");
  265. buffer_sprintf(d->instance->labels_buffer, "%s=\"%s\"", k, v);
  266. d->count++;
  267. }
  268. return 1;
  269. }
  270. void format_host_labels_prometheus(struct instance *instance, RRDHOST *host)
  271. {
  272. if (unlikely(!sending_labels_configured(instance)))
  273. return;
  274. if (!instance->labels_buffer)
  275. instance->labels_buffer = buffer_create(1024, &netdata_buffers_statistics.buffers_exporters);
  276. struct format_prometheus_label_callback tmp = {
  277. .instance = instance,
  278. .count = 0
  279. };
  280. rrdlabels_walkthrough_read(host->rrdlabels, format_prometheus_label_callback, &tmp);
  281. }
  282. /**
  283. * Format host labels for the Prometheus exporter
  284. * We are using a structure instead a direct buffer to expand options quickly.
  285. *
  286. * @param data is the buffer used to add labels.
  287. */
  288. static int format_prometheus_chart_label_callback(const char *name, const char *value, RRDLABEL_SRC ls __maybe_unused, void *data) {
  289. BUFFER *wb = data;
  290. if (name[0] == '_' )
  291. return 1;
  292. char k[PROMETHEUS_ELEMENT_MAX + 1];
  293. char v[PROMETHEUS_ELEMENT_MAX + 1];
  294. prometheus_name_copy(k, name, PROMETHEUS_ELEMENT_MAX);
  295. prometheus_label_copy(v, value, PROMETHEUS_ELEMENT_MAX);
  296. if (*k && *v)
  297. buffer_sprintf(wb, ",%s=\"%s\"", k, v);
  298. return 1;
  299. }
  300. struct host_variables_callback_options {
  301. RRDHOST *host;
  302. BUFFER *wb;
  303. EXPORTING_OPTIONS exporting_options;
  304. PROMETHEUS_OUTPUT_OPTIONS output_options;
  305. const char *prefix;
  306. const char *labels;
  307. time_t now;
  308. int host_header_printed;
  309. char name[PROMETHEUS_VARIABLE_MAX + 1];
  310. };
  311. /**
  312. * Print host variables.
  313. *
  314. * @param rv a variable.
  315. * @param data callback options.
  316. * @return Returns 1 if the chart can be sent, 0 otherwise.
  317. */
  318. static int print_host_variables_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rv_ptr __maybe_unused, void *data) {
  319. const RRDVAR_ACQUIRED *rv = (const RRDVAR_ACQUIRED *)item;
  320. struct host_variables_callback_options *opts = data;
  321. if (rrdvar_flags(rv) & (RRDVAR_FLAG_CUSTOM_HOST_VAR | RRDVAR_FLAG_CUSTOM_CHART_VAR)) {
  322. if (!opts->host_header_printed) {
  323. opts->host_header_printed = 1;
  324. if (opts->output_options & PROMETHEUS_OUTPUT_HELP) {
  325. buffer_sprintf(opts->wb, "\n# COMMENT global host and chart variables\n");
  326. }
  327. }
  328. NETDATA_DOUBLE value = rrdvar2number(rv);
  329. if (isnan(value) || isinf(value)) {
  330. if (opts->output_options & PROMETHEUS_OUTPUT_HELP)
  331. buffer_sprintf(
  332. opts->wb, "# COMMENT variable \"%s\" is %s. Skipped.\n", rrdvar_name(rv), (isnan(value)) ? "NAN" : "INF");
  333. return 0;
  334. }
  335. char *label_pre = "";
  336. char *label_post = "";
  337. if (opts->labels && *opts->labels) {
  338. label_pre = "{";
  339. label_post = "}";
  340. }
  341. prometheus_name_copy(opts->name, rrdvar_name(rv), sizeof(opts->name));
  342. if (opts->output_options & PROMETHEUS_OUTPUT_TIMESTAMPS)
  343. buffer_sprintf(
  344. opts->wb,
  345. "%s_%s%s%s%s " NETDATA_DOUBLE_FORMAT " %llu\n",
  346. opts->prefix,
  347. opts->name,
  348. label_pre,
  349. opts->labels,
  350. label_post,
  351. value,
  352. opts->now * 1000ULL);
  353. else
  354. buffer_sprintf(
  355. opts->wb,
  356. "%s_%s%s%s%s " NETDATA_DOUBLE_FORMAT "\n",
  357. opts->prefix,
  358. opts->name,
  359. label_pre,
  360. opts->labels,
  361. label_post,
  362. value);
  363. return 1;
  364. }
  365. return 0;
  366. }
  367. struct gen_parameters {
  368. const char *prefix;
  369. const char *labels_prefix;
  370. char *context;
  371. char *suffix;
  372. char *chart;
  373. char *dimension;
  374. char *family;
  375. char *labels;
  376. PROMETHEUS_OUTPUT_OPTIONS output_options;
  377. RRDSET *st;
  378. RRDDIM *rd;
  379. const char *relation;
  380. const char *type;
  381. };
  382. /**
  383. * Write an as-collected help comment to a buffer.
  384. *
  385. * @param wb the buffer to write the comment to.
  386. * @param p parameters for generating the comment string.
  387. * @param homogeneous a flag for homogeneous charts.
  388. * @param prometheus_collector a flag for metrics from prometheus collector.
  389. */
  390. static void generate_as_collected_prom_help(BUFFER *wb, struct gen_parameters *p, int homogeneous, int prometheus_collector)
  391. {
  392. buffer_sprintf(wb, "# COMMENT %s_%s", p->prefix, p->context);
  393. if (!homogeneous)
  394. buffer_sprintf(wb, "_%s", p->dimension);
  395. buffer_sprintf(
  396. wb,
  397. "%s: chart \"%s\", context \"%s\", family \"%s\", dimension \"%s\", value * ",
  398. p->suffix,
  399. (p->output_options & PROMETHEUS_OUTPUT_NAMES && p->st->name) ? rrdset_name(p->st) : rrdset_id(p->st),
  400. rrdset_context(p->st),
  401. rrdset_family(p->st),
  402. (p->output_options & PROMETHEUS_OUTPUT_NAMES && p->rd->name) ? rrddim_name(p->rd) : rrddim_id(p->rd));
  403. if (prometheus_collector)
  404. buffer_sprintf(wb, "1 / 1");
  405. else
  406. buffer_sprintf(wb, "%d / %d", p->rd->multiplier, p->rd->divisor);
  407. buffer_sprintf(wb, " %s %s (%s)\n", p->relation, rrdset_units(p->st), p->type);
  408. }
  409. /**
  410. * Write an as-collected metric to a buffer.
  411. *
  412. * @param wb the buffer to write the metric to.
  413. * @param p parameters for generating the metric string.
  414. * @param homogeneous a flag for homogeneous charts.
  415. * @param prometheus_collector a flag for metrics from prometheus collector.
  416. * @param chart_labels the dictionary with chart labels
  417. */
  418. static void generate_as_collected_prom_metric(BUFFER *wb,
  419. struct gen_parameters *p,
  420. int homogeneous,
  421. int prometheus_collector,
  422. RRDLABELS *chart_labels)
  423. {
  424. buffer_sprintf(wb, "%s_%s", p->prefix, p->context);
  425. if (!homogeneous)
  426. buffer_sprintf(wb, "_%s", p->dimension);
  427. buffer_sprintf(wb, "%s{%schart=\"%s\"", p->suffix, p->labels_prefix, p->chart);
  428. if (homogeneous)
  429. buffer_sprintf(wb, ",%sdimension=\"%s\"", p->labels_prefix, p->dimension);
  430. buffer_sprintf(wb, ",%sfamily=\"%s\"", p->labels_prefix, p->family);
  431. rrdlabels_walkthrough_read(chart_labels, format_prometheus_chart_label_callback, wb);
  432. buffer_sprintf(wb, "%s} ", p->labels);
  433. if (prometheus_collector)
  434. buffer_sprintf(
  435. wb,
  436. NETDATA_DOUBLE_FORMAT,
  437. (NETDATA_DOUBLE)p->rd->collector.last_collected_value * (NETDATA_DOUBLE)p->rd->multiplier /
  438. (NETDATA_DOUBLE)p->rd->divisor);
  439. else
  440. buffer_sprintf(wb, COLLECTED_NUMBER_FORMAT, p->rd->collector.last_collected_value);
  441. if (p->output_options & PROMETHEUS_OUTPUT_TIMESTAMPS)
  442. buffer_sprintf(wb, " %"PRIu64"\n", timeval_msec(&p->rd->collector.last_collected_time));
  443. else
  444. buffer_sprintf(wb, "\n");
  445. }
  446. /**
  447. * Write metrics in Prometheus format to a buffer.
  448. *
  449. * @param instance an instance data structure.
  450. * @param host a data collecting host.
  451. * @param filter_string a simple pattern filter.
  452. * @param wb the buffer to fill with metrics.
  453. * @param prefix a prefix for every metric.
  454. * @param exporting_options options to configure what data is exported.
  455. * @param allhosts set to 1 if host instance should be in the output for tags.
  456. * @param output_options options to configure the format of the output.
  457. */
  458. static void rrd_stats_api_v1_charts_allmetrics_prometheus(
  459. struct instance *instance,
  460. RRDHOST *host,
  461. const char *filter_string,
  462. BUFFER *wb,
  463. const char *prefix,
  464. EXPORTING_OPTIONS exporting_options,
  465. int allhosts,
  466. PROMETHEUS_OUTPUT_OPTIONS output_options)
  467. {
  468. SIMPLE_PATTERN *filter = simple_pattern_create(filter_string, NULL, SIMPLE_PATTERN_EXACT, true);
  469. char hostname[PROMETHEUS_ELEMENT_MAX + 1];
  470. prometheus_label_copy(hostname, rrdhost_hostname(host), PROMETHEUS_ELEMENT_MAX);
  471. format_host_labels_prometheus(instance, host);
  472. buffer_sprintf(
  473. wb,
  474. "netdata_info{instance=\"%s\",application=\"%s\",version=\"%s\"",
  475. hostname,
  476. rrdhost_program_name(host),
  477. rrdhost_program_version(host));
  478. if (instance->labels_buffer && *buffer_tostring(instance->labels_buffer)) {
  479. buffer_sprintf(wb, ",%s", buffer_tostring(instance->labels_buffer));
  480. }
  481. if (output_options & PROMETHEUS_OUTPUT_TIMESTAMPS)
  482. buffer_sprintf(wb, "} 1 %llu\n", now_realtime_usec() / USEC_PER_MS);
  483. else
  484. buffer_sprintf(wb, "} 1\n");
  485. char labels[PROMETHEUS_LABELS_MAX + 1] = "";
  486. if (allhosts) {
  487. snprintfz(labels, PROMETHEUS_LABELS_MAX, ",%sinstance=\"%s\"", instance->config.label_prefix, hostname);
  488. }
  489. if (instance->labels_buffer)
  490. buffer_flush(instance->labels_buffer);
  491. // send custom variables set for the host
  492. if (output_options & PROMETHEUS_OUTPUT_VARIABLES) {
  493. struct host_variables_callback_options opts = {
  494. .host = host,
  495. .wb = wb,
  496. .labels = (labels[0] == ',') ? &labels[1] : labels,
  497. .exporting_options = exporting_options,
  498. .output_options = output_options,
  499. .prefix = prefix,
  500. .now = now_realtime_sec(),
  501. .host_header_printed = 0
  502. };
  503. rrdvar_walkthrough_read(host->rrdvars, print_host_variables_callback, &opts);
  504. }
  505. // for each chart
  506. RRDSET *st;
  507. BUFFER *plabels_buffer = buffer_create(0, NULL);
  508. const char *plabels_prefix = instance->config.label_prefix;
  509. STRING *prometheus = string_strdupz("prometheus");
  510. rrdset_foreach_read(st, host) {
  511. if (likely(can_send_rrdset(instance, st, filter))) {
  512. char chart[PROMETHEUS_ELEMENT_MAX + 1];
  513. char context[PROMETHEUS_ELEMENT_MAX + 1];
  514. char family[PROMETHEUS_ELEMENT_MAX + 1];
  515. char units[PROMETHEUS_ELEMENT_MAX + 1] = "";
  516. prometheus_label_copy(chart, (output_options & PROMETHEUS_OUTPUT_NAMES && st->name) ? rrdset_name(st) : rrdset_id(st), PROMETHEUS_ELEMENT_MAX);
  517. prometheus_label_copy(family, rrdset_family(st), PROMETHEUS_ELEMENT_MAX);
  518. prometheus_name_copy(context, rrdset_context(st), PROMETHEUS_ELEMENT_MAX);
  519. int as_collected = (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_AS_COLLECTED);
  520. int homogeneous = 1;
  521. int prometheus_collector = 0;
  522. RRDSET_FLAGS flags = rrdset_flag_get(st);
  523. if (as_collected) {
  524. if (flags & RRDSET_FLAG_HOMOGENEOUS_CHECK)
  525. rrdset_update_heterogeneous_flag(st);
  526. if (flags & RRDSET_FLAG_HETEROGENEOUS)
  527. homogeneous = 0;
  528. if (st->module_name == prometheus)
  529. prometheus_collector = 1;
  530. }
  531. else {
  532. if (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_AVERAGE &&
  533. !(output_options & PROMETHEUS_OUTPUT_HIDEUNITS))
  534. prometheus_units_copy(
  535. units, rrdset_units(st), PROMETHEUS_ELEMENT_MAX, output_options & PROMETHEUS_OUTPUT_OLDUNITS);
  536. }
  537. if (unlikely(output_options & PROMETHEUS_OUTPUT_HELP))
  538. buffer_sprintf(
  539. wb,
  540. "\n# COMMENT %s chart \"%s\", context \"%s\", family \"%s\", units \"%s\"\n",
  541. (homogeneous) ? "homogeneous" : "heterogeneous",
  542. (output_options & PROMETHEUS_OUTPUT_NAMES && st->name) ? rrdset_name(st) : rrdset_id(st),
  543. rrdset_context(st),
  544. rrdset_family(st),
  545. rrdset_units(st));
  546. // for each dimension
  547. RRDDIM *rd;
  548. rrddim_foreach_read(rd, st) {
  549. if (rd->collector.counter && !rrddim_flag_check(rd, RRDDIM_FLAG_OBSOLETE)) {
  550. char dimension[PROMETHEUS_ELEMENT_MAX + 1];
  551. char *suffix = "";
  552. if (as_collected) {
  553. // we need as-collected / raw data
  554. struct gen_parameters p;
  555. p.prefix = prefix;
  556. p.labels_prefix = instance->config.label_prefix;
  557. p.context = context;
  558. p.suffix = suffix;
  559. p.chart = chart;
  560. p.dimension = dimension;
  561. p.family = family;
  562. p.labels = labels;
  563. p.output_options = output_options;
  564. p.st = st;
  565. p.rd = rd;
  566. if (unlikely(rd->collector.last_collected_time.tv_sec < instance->after))
  567. continue;
  568. p.type = "gauge";
  569. p.relation = "gives";
  570. if (rd->algorithm == RRD_ALGORITHM_INCREMENTAL ||
  571. rd->algorithm == RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL) {
  572. p.type = "counter";
  573. p.relation = "delta gives";
  574. if (!prometheus_collector)
  575. p.suffix = "_total";
  576. }
  577. if (homogeneous) {
  578. // all the dimensions of the chart, has the same algorithm, multiplier and divisor
  579. // we add all dimensions as labels
  580. prometheus_label_copy(
  581. dimension,
  582. (output_options & PROMETHEUS_OUTPUT_NAMES && rd->name) ? rrddim_name(rd) : rrddim_id(rd),
  583. PROMETHEUS_ELEMENT_MAX);
  584. if (unlikely(output_options & PROMETHEUS_OUTPUT_HELP))
  585. generate_as_collected_prom_help(wb, &p, homogeneous, prometheus_collector);
  586. if (unlikely(output_options & PROMETHEUS_OUTPUT_TYPES))
  587. buffer_sprintf(wb, "# TYPE %s_%s%s %s\n", prefix, context, suffix, p.type);
  588. generate_as_collected_prom_metric(wb, &p, homogeneous, prometheus_collector, st->rrdlabels);
  589. }
  590. else {
  591. // the dimensions of the chart, do not have the same algorithm, multiplier or divisor
  592. // we create a metric per dimension
  593. prometheus_name_copy(
  594. dimension,
  595. (output_options & PROMETHEUS_OUTPUT_NAMES && rd->name) ? rrddim_name(rd) : rrddim_id(rd),
  596. PROMETHEUS_ELEMENT_MAX);
  597. if (unlikely(output_options & PROMETHEUS_OUTPUT_HELP))
  598. generate_as_collected_prom_help(wb, &p, homogeneous, prometheus_collector);
  599. if (unlikely(output_options & PROMETHEUS_OUTPUT_TYPES))
  600. buffer_sprintf(
  601. wb, "# TYPE %s_%s_%s%s %s\n", prefix, context, dimension, suffix, p.type);
  602. generate_as_collected_prom_metric(wb, &p, homogeneous, prometheus_collector, st->rrdlabels);
  603. }
  604. }
  605. else {
  606. // we need average or sum of the data
  607. time_t first_time = instance->after;
  608. time_t last_time = instance->before;
  609. NETDATA_DOUBLE value = exporting_calculate_value_from_stored_data(instance, rd, &last_time);
  610. if (!isnan(value) && !isinf(value)) {
  611. if (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_AVERAGE)
  612. suffix = "_average";
  613. else if (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_SUM)
  614. suffix = "_sum";
  615. prometheus_label_copy(
  616. dimension,
  617. (output_options & PROMETHEUS_OUTPUT_NAMES && rd->name) ? rrddim_name(rd) : rrddim_id(rd),
  618. PROMETHEUS_ELEMENT_MAX);
  619. buffer_flush(plabels_buffer);
  620. buffer_sprintf(plabels_buffer, "%1$schart=\"%2$s\",%1$sdimension=\"%3$s\",%1$sfamily=\"%4$s\"", plabels_prefix, chart, dimension, family);
  621. rrdlabels_walkthrough_read(st->rrdlabels, format_prometheus_chart_label_callback, plabels_buffer);
  622. if (unlikely(output_options & PROMETHEUS_OUTPUT_HELP))
  623. buffer_sprintf(
  624. wb,
  625. "# COMMENT %s_%s%s%s: dimension \"%s\", value is %s, gauge, dt %llu to %llu inclusive\n",
  626. prefix,
  627. context,
  628. units,
  629. suffix,
  630. (output_options & PROMETHEUS_OUTPUT_NAMES && rd->name) ? rrddim_name(rd) : rrddim_id(rd),
  631. rrdset_units(st),
  632. (unsigned long long)first_time,
  633. (unsigned long long)last_time);
  634. if (unlikely(output_options & PROMETHEUS_OUTPUT_TYPES))
  635. buffer_sprintf(wb, "# TYPE %s_%s%s%s gauge\n", prefix, context, units, suffix);
  636. if (output_options & PROMETHEUS_OUTPUT_TIMESTAMPS)
  637. buffer_sprintf(
  638. wb,
  639. "%s_%s%s%s{%s%s} " NETDATA_DOUBLE_FORMAT
  640. " %llu\n",
  641. prefix,
  642. context,
  643. units,
  644. suffix,
  645. buffer_tostring(plabels_buffer),
  646. labels,
  647. value,
  648. last_time * MSEC_PER_SEC);
  649. else
  650. buffer_sprintf(
  651. wb,
  652. "%s_%s%s%s{%s%s} " NETDATA_DOUBLE_FORMAT
  653. "\n",
  654. prefix,
  655. context,
  656. units,
  657. suffix,
  658. buffer_tostring(plabels_buffer),
  659. labels,
  660. value);
  661. }
  662. }
  663. }
  664. }
  665. rrddim_foreach_done(rd);
  666. }
  667. }
  668. rrdset_foreach_done(st);
  669. buffer_free(plabels_buffer);
  670. simple_pattern_free(filter);
  671. }
  672. /**
  673. * Get the last time time when a server accessed Netdata. Write information about an API request to a buffer.
  674. *
  675. * @param instance an instance data structure.
  676. * @param host a data collecting host.
  677. * @param wb the buffer to write to.
  678. * @param exporting_options options to configure what data is exported.
  679. * @param server the name of a Prometheus server..
  680. * @param now actual time.
  681. * @param output_options options to configure the format of the output.
  682. * @return Returns the last time when the server accessed Netdata.
  683. */
  684. static inline time_t prometheus_preparation(
  685. struct instance *instance,
  686. RRDHOST *host,
  687. BUFFER *wb,
  688. EXPORTING_OPTIONS exporting_options,
  689. const char *server,
  690. time_t now,
  691. PROMETHEUS_OUTPUT_OPTIONS output_options)
  692. {
  693. #ifndef UNIT_TESTING
  694. analytics_log_prometheus();
  695. #endif
  696. if (!server || !*server)
  697. server = "default";
  698. time_t after = prometheus_server_last_access(server, host, now);
  699. int first_seen = 0;
  700. if (!after) {
  701. after = now - instance->config.update_every;
  702. first_seen = 1;
  703. }
  704. if (after > now) {
  705. // oops! this should never happen
  706. after = now - instance->config.update_every;
  707. }
  708. if (output_options & PROMETHEUS_OUTPUT_HELP) {
  709. char *mode;
  710. if (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_AS_COLLECTED)
  711. mode = "as collected";
  712. else if (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_AVERAGE)
  713. mode = "average";
  714. else if (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_SUM)
  715. mode = "sum";
  716. else
  717. mode = "unknown";
  718. buffer_sprintf(
  719. wb,
  720. "# COMMENT netdata \"%s\" to %sprometheus \"%s\", source \"%s\", last seen %lu %s, time range %lu to %lu\n\n",
  721. rrdhost_hostname(host),
  722. (first_seen) ? "FIRST SEEN " : "",
  723. server,
  724. mode,
  725. (unsigned long)((first_seen) ? 0 : (now - after)),
  726. (first_seen) ? "never" : "seconds ago",
  727. (unsigned long)after,
  728. (unsigned long)now);
  729. }
  730. return after;
  731. }
  732. /**
  733. * Write metrics and auxiliary information for one host to a buffer.
  734. *
  735. * @param host a data collecting host.
  736. * @param filter_string a simple pattern filter.
  737. * @param wb the buffer to write to.
  738. * @param server the name of a Prometheus server.
  739. * @param prefix a prefix for every metric.
  740. * @param exporting_options options to configure what data is exported.
  741. * @param output_options options to configure the format of the output.
  742. */
  743. void rrd_stats_api_v1_charts_allmetrics_prometheus_single_host(
  744. RRDHOST *host,
  745. const char *filter_string,
  746. BUFFER *wb,
  747. const char *server,
  748. const char *prefix,
  749. EXPORTING_OPTIONS exporting_options,
  750. PROMETHEUS_OUTPUT_OPTIONS output_options)
  751. {
  752. if (unlikely(!prometheus_exporter_instance || !prometheus_exporter_instance->config.initialized))
  753. return;
  754. prometheus_exporter_instance->before = now_realtime_sec();
  755. // we start at the point we had stopped before
  756. prometheus_exporter_instance->after = prometheus_preparation(
  757. prometheus_exporter_instance,
  758. host,
  759. wb,
  760. exporting_options,
  761. server,
  762. prometheus_exporter_instance->before,
  763. output_options);
  764. rrd_stats_api_v1_charts_allmetrics_prometheus(
  765. prometheus_exporter_instance, host, filter_string, wb, prefix, exporting_options, 0, output_options);
  766. }
  767. /**
  768. * Write metrics and auxiliary information for all hosts to a buffer.
  769. *
  770. * @param host a data collecting host.
  771. * @param filter_string a simple pattern filter.
  772. * @param wb the buffer to write to.
  773. * @param server the name of a Prometheus server.
  774. * @param prefix a prefix for every metric.
  775. * @param exporting_options options to configure what data is exported.
  776. * @param output_options options to configure the format of the output.
  777. */
  778. void rrd_stats_api_v1_charts_allmetrics_prometheus_all_hosts(
  779. RRDHOST *host,
  780. const char *filter_string,
  781. BUFFER *wb,
  782. const char *server,
  783. const char *prefix,
  784. EXPORTING_OPTIONS exporting_options,
  785. PROMETHEUS_OUTPUT_OPTIONS output_options)
  786. {
  787. if (unlikely(!prometheus_exporter_instance || !prometheus_exporter_instance->config.initialized))
  788. return;
  789. prometheus_exporter_instance->before = now_realtime_sec();
  790. // we start at the point we had stopped before
  791. prometheus_exporter_instance->after = prometheus_preparation(
  792. prometheus_exporter_instance,
  793. host,
  794. wb,
  795. exporting_options,
  796. server,
  797. prometheus_exporter_instance->before,
  798. output_options);
  799. dfe_start_reentrant(rrdhost_root_index, host)
  800. {
  801. rrd_stats_api_v1_charts_allmetrics_prometheus(
  802. prometheus_exporter_instance, host, filter_string, wb, prefix, exporting_options, 1, output_options);
  803. }
  804. dfe_done(host);
  805. }