prometheus.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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, 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, void *data) {
  289. BUFFER *wb = data;
  290. (void)ls;
  291. if (name[0] == '_' )
  292. return 1;
  293. char k[PROMETHEUS_ELEMENT_MAX + 1];
  294. char v[PROMETHEUS_ELEMENT_MAX + 1];
  295. prometheus_name_copy(k, name, PROMETHEUS_ELEMENT_MAX);
  296. prometheus_label_copy(v, value, PROMETHEUS_ELEMENT_MAX);
  297. if (*k && *v)
  298. buffer_sprintf(wb, ",%s=\"%s\"", k, v);
  299. return 1;
  300. }
  301. struct host_variables_callback_options {
  302. RRDHOST *host;
  303. BUFFER *wb;
  304. EXPORTING_OPTIONS exporting_options;
  305. PROMETHEUS_OUTPUT_OPTIONS output_options;
  306. const char *prefix;
  307. const char *labels;
  308. time_t now;
  309. int host_header_printed;
  310. char name[PROMETHEUS_VARIABLE_MAX + 1];
  311. };
  312. /**
  313. * Print host variables.
  314. *
  315. * @param rv a variable.
  316. * @param data callback options.
  317. * @return Returns 1 if the chart can be sent, 0 otherwise.
  318. */
  319. static int print_host_variables_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rv_ptr __maybe_unused, void *data) {
  320. const RRDVAR_ACQUIRED *rv = (const RRDVAR_ACQUIRED *)item;
  321. struct host_variables_callback_options *opts = data;
  322. if (rrdvar_flags(rv) & (RRDVAR_FLAG_CUSTOM_HOST_VAR | RRDVAR_FLAG_CUSTOM_CHART_VAR)) {
  323. if (!opts->host_header_printed) {
  324. opts->host_header_printed = 1;
  325. if (opts->output_options & PROMETHEUS_OUTPUT_HELP) {
  326. buffer_sprintf(opts->wb, "\n# COMMENT global host and chart variables\n");
  327. }
  328. }
  329. NETDATA_DOUBLE value = rrdvar2number(rv);
  330. if (isnan(value) || isinf(value)) {
  331. if (opts->output_options & PROMETHEUS_OUTPUT_HELP)
  332. buffer_sprintf(
  333. opts->wb, "# COMMENT variable \"%s\" is %s. Skipped.\n", rrdvar_name(rv), (isnan(value)) ? "NAN" : "INF");
  334. return 0;
  335. }
  336. char *label_pre = "";
  337. char *label_post = "";
  338. if (opts->labels && *opts->labels) {
  339. label_pre = "{";
  340. label_post = "}";
  341. }
  342. prometheus_name_copy(opts->name, rrdvar_name(rv), sizeof(opts->name));
  343. if (opts->output_options & PROMETHEUS_OUTPUT_TIMESTAMPS)
  344. buffer_sprintf(
  345. opts->wb,
  346. "%s_%s%s%s%s " NETDATA_DOUBLE_FORMAT " %llu\n",
  347. opts->prefix,
  348. opts->name,
  349. label_pre,
  350. opts->labels,
  351. label_post,
  352. value,
  353. opts->now * 1000ULL);
  354. else
  355. buffer_sprintf(
  356. opts->wb,
  357. "%s_%s%s%s%s " NETDATA_DOUBLE_FORMAT "\n",
  358. opts->prefix,
  359. opts->name,
  360. label_pre,
  361. opts->labels,
  362. label_post,
  363. value);
  364. return 1;
  365. }
  366. return 0;
  367. }
  368. struct gen_parameters {
  369. const char *prefix;
  370. const char *labels_prefix;
  371. char *context;
  372. char *suffix;
  373. char *chart;
  374. char *dimension;
  375. char *family;
  376. char *labels;
  377. PROMETHEUS_OUTPUT_OPTIONS output_options;
  378. RRDSET *st;
  379. RRDDIM *rd;
  380. const char *relation;
  381. const char *type;
  382. };
  383. /**
  384. * Write an as-collected help comment to a buffer.
  385. *
  386. * @param wb the buffer to write the comment to.
  387. * @param p parameters for generating the comment string.
  388. * @param homogeneous a flag for homogeneous charts.
  389. * @param prometheus_collector a flag for metrics from prometheus collector.
  390. */
  391. static void generate_as_collected_prom_help(BUFFER *wb, struct gen_parameters *p, int homogeneous, int prometheus_collector)
  392. {
  393. buffer_sprintf(wb, "# COMMENT %s_%s", p->prefix, p->context);
  394. if (!homogeneous)
  395. buffer_sprintf(wb, "_%s", p->dimension);
  396. buffer_sprintf(
  397. wb,
  398. "%s: chart \"%s\", context \"%s\", family \"%s\", dimension \"%s\", value * ",
  399. p->suffix,
  400. (p->output_options & PROMETHEUS_OUTPUT_NAMES && p->st->name) ? rrdset_name(p->st) : rrdset_id(p->st),
  401. rrdset_context(p->st),
  402. rrdset_family(p->st),
  403. (p->output_options & PROMETHEUS_OUTPUT_NAMES && p->rd->name) ? rrddim_name(p->rd) : rrddim_id(p->rd));
  404. if (prometheus_collector)
  405. buffer_sprintf(wb, "1 / 1");
  406. else
  407. buffer_sprintf(wb, "%d / %d", p->rd->multiplier, p->rd->divisor);
  408. buffer_sprintf(wb, " %s %s (%s)\n", p->relation, rrdset_units(p->st), p->type);
  409. }
  410. /**
  411. * Write an as-collected metric to a buffer.
  412. *
  413. * @param wb the buffer to write the metric to.
  414. * @param p parameters for generating the metric string.
  415. * @param homogeneous a flag for homogeneous charts.
  416. * @param prometheus_collector a flag for metrics from prometheus collector.
  417. * @param chart_labels the dictionary with chart labels
  418. */
  419. static void generate_as_collected_prom_metric(BUFFER *wb,
  420. struct gen_parameters *p,
  421. int homogeneous,
  422. int prometheus_collector,
  423. DICTIONARY *chart_labels)
  424. {
  425. buffer_sprintf(wb, "%s_%s", p->prefix, p->context);
  426. if (!homogeneous)
  427. buffer_sprintf(wb, "_%s", p->dimension);
  428. buffer_sprintf(wb, "%s{%schart=\"%s\"", p->suffix, p->labels_prefix, p->chart);
  429. if (homogeneous)
  430. buffer_sprintf(wb, ",%sdimension=\"%s\"", p->labels_prefix, p->dimension);
  431. buffer_sprintf(wb, ",%sfamily=\"%s\"", p->labels_prefix, p->family);
  432. rrdlabels_walkthrough_read(chart_labels, format_prometheus_chart_label_callback, wb);
  433. buffer_sprintf(wb, "%s} ", p->labels);
  434. if (prometheus_collector)
  435. buffer_sprintf(
  436. wb,
  437. NETDATA_DOUBLE_FORMAT,
  438. (NETDATA_DOUBLE)p->rd->collector.last_collected_value * (NETDATA_DOUBLE)p->rd->multiplier /
  439. (NETDATA_DOUBLE)p->rd->divisor);
  440. else
  441. buffer_sprintf(wb, COLLECTED_NUMBER_FORMAT, p->rd->collector.last_collected_value);
  442. if (p->output_options & PROMETHEUS_OUTPUT_TIMESTAMPS)
  443. buffer_sprintf(wb, " %llu\n", timeval_msec(&p->rd->collector.last_collected_time));
  444. else
  445. buffer_sprintf(wb, "\n");
  446. }
  447. /**
  448. * Write metrics in Prometheus format to a buffer.
  449. *
  450. * @param instance an instance data structure.
  451. * @param host a data collecting host.
  452. * @param filter_string a simple pattern filter.
  453. * @param wb the buffer to fill with metrics.
  454. * @param prefix a prefix for every metric.
  455. * @param exporting_options options to configure what data is exported.
  456. * @param allhosts set to 1 if host instance should be in the output for tags.
  457. * @param output_options options to configure the format of the output.
  458. */
  459. static void rrd_stats_api_v1_charts_allmetrics_prometheus(
  460. struct instance *instance,
  461. RRDHOST *host,
  462. const char *filter_string,
  463. BUFFER *wb,
  464. const char *prefix,
  465. EXPORTING_OPTIONS exporting_options,
  466. int allhosts,
  467. PROMETHEUS_OUTPUT_OPTIONS output_options)
  468. {
  469. SIMPLE_PATTERN *filter = simple_pattern_create(filter_string, NULL, SIMPLE_PATTERN_EXACT, true);
  470. char hostname[PROMETHEUS_ELEMENT_MAX + 1];
  471. prometheus_label_copy(hostname, rrdhost_hostname(host), PROMETHEUS_ELEMENT_MAX);
  472. format_host_labels_prometheus(instance, host);
  473. buffer_sprintf(
  474. wb,
  475. "netdata_info{instance=\"%s\",application=\"%s\",version=\"%s\"",
  476. hostname,
  477. rrdhost_program_name(host),
  478. rrdhost_program_version(host));
  479. if (instance->labels_buffer && *buffer_tostring(instance->labels_buffer)) {
  480. buffer_sprintf(wb, ",%s", buffer_tostring(instance->labels_buffer));
  481. }
  482. if (output_options & PROMETHEUS_OUTPUT_TIMESTAMPS)
  483. buffer_sprintf(wb, "} 1 %llu\n", now_realtime_usec() / USEC_PER_MS);
  484. else
  485. buffer_sprintf(wb, "} 1\n");
  486. char labels[PROMETHEUS_LABELS_MAX + 1] = "";
  487. if (allhosts) {
  488. snprintfz(labels, PROMETHEUS_LABELS_MAX, ",%sinstance=\"%s\"", instance->config.label_prefix, hostname);
  489. }
  490. if (instance->labels_buffer)
  491. buffer_flush(instance->labels_buffer);
  492. // send custom variables set for the host
  493. if (output_options & PROMETHEUS_OUTPUT_VARIABLES) {
  494. struct host_variables_callback_options opts = {
  495. .host = host,
  496. .wb = wb,
  497. .labels = (labels[0] == ',') ? &labels[1] : labels,
  498. .exporting_options = exporting_options,
  499. .output_options = output_options,
  500. .prefix = prefix,
  501. .now = now_realtime_sec(),
  502. .host_header_printed = 0
  503. };
  504. rrdvar_walkthrough_read(host->rrdvars, print_host_variables_callback, &opts);
  505. }
  506. // for each chart
  507. RRDSET *st;
  508. BUFFER *plabels_buffer = buffer_create(0, NULL);
  509. const char *plabels_prefix = instance->config.label_prefix;
  510. STRING *prometheus = string_strdupz("prometheus");
  511. rrdset_foreach_read(st, host) {
  512. if (likely(can_send_rrdset(instance, st, filter))) {
  513. char chart[PROMETHEUS_ELEMENT_MAX + 1];
  514. char context[PROMETHEUS_ELEMENT_MAX + 1];
  515. char family[PROMETHEUS_ELEMENT_MAX + 1];
  516. char units[PROMETHEUS_ELEMENT_MAX + 1] = "";
  517. prometheus_label_copy(chart, (output_options & PROMETHEUS_OUTPUT_NAMES && st->name) ? rrdset_name(st) : rrdset_id(st), PROMETHEUS_ELEMENT_MAX);
  518. prometheus_label_copy(family, rrdset_family(st), PROMETHEUS_ELEMENT_MAX);
  519. prometheus_name_copy(context, rrdset_context(st), PROMETHEUS_ELEMENT_MAX);
  520. int as_collected = (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_AS_COLLECTED);
  521. int homogeneous = 1;
  522. int prometheus_collector = 0;
  523. RRDSET_FLAGS flags = __atomic_load_n(&st->flags, __ATOMIC_RELAXED);
  524. if (as_collected) {
  525. if (flags & RRDSET_FLAG_HOMOGENEOUS_CHECK)
  526. rrdset_update_heterogeneous_flag(st);
  527. if (flags & RRDSET_FLAG_HETEROGENEOUS)
  528. homogeneous = 0;
  529. if (st->module_name == prometheus)
  530. prometheus_collector = 1;
  531. }
  532. else {
  533. if (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_AVERAGE &&
  534. !(output_options & PROMETHEUS_OUTPUT_HIDEUNITS))
  535. prometheus_units_copy(
  536. units, rrdset_units(st), PROMETHEUS_ELEMENT_MAX, output_options & PROMETHEUS_OUTPUT_OLDUNITS);
  537. }
  538. if (unlikely(output_options & PROMETHEUS_OUTPUT_HELP))
  539. buffer_sprintf(
  540. wb,
  541. "\n# COMMENT %s chart \"%s\", context \"%s\", family \"%s\", units \"%s\"\n",
  542. (homogeneous) ? "homogeneous" : "heterogeneous",
  543. (output_options & PROMETHEUS_OUTPUT_NAMES && st->name) ? rrdset_name(st) : rrdset_id(st),
  544. rrdset_context(st),
  545. rrdset_family(st),
  546. rrdset_units(st));
  547. // for each dimension
  548. RRDDIM *rd;
  549. rrddim_foreach_read(rd, st) {
  550. if (rd->collector.counter && !rrddim_flag_check(rd, RRDDIM_FLAG_OBSOLETE)) {
  551. char dimension[PROMETHEUS_ELEMENT_MAX + 1];
  552. char *suffix = "";
  553. if (as_collected) {
  554. // we need as-collected / raw data
  555. struct gen_parameters p;
  556. p.prefix = prefix;
  557. p.labels_prefix = instance->config.label_prefix;
  558. p.context = context;
  559. p.suffix = suffix;
  560. p.chart = chart;
  561. p.dimension = dimension;
  562. p.family = family;
  563. p.labels = labels;
  564. p.output_options = output_options;
  565. p.st = st;
  566. p.rd = rd;
  567. if (unlikely(rd->collector.last_collected_time.tv_sec < instance->after))
  568. continue;
  569. p.type = "gauge";
  570. p.relation = "gives";
  571. if (rd->algorithm == RRD_ALGORITHM_INCREMENTAL ||
  572. rd->algorithm == RRD_ALGORITHM_PCENT_OVER_DIFF_TOTAL) {
  573. p.type = "counter";
  574. p.relation = "delta gives";
  575. if (!prometheus_collector)
  576. p.suffix = "_total";
  577. }
  578. if (homogeneous) {
  579. // all the dimensions of the chart, has the same algorithm, multiplier and divisor
  580. // we add all dimensions as labels
  581. prometheus_label_copy(
  582. dimension,
  583. (output_options & PROMETHEUS_OUTPUT_NAMES && rd->name) ? rrddim_name(rd) : rrddim_id(rd),
  584. PROMETHEUS_ELEMENT_MAX);
  585. if (unlikely(output_options & PROMETHEUS_OUTPUT_HELP))
  586. generate_as_collected_prom_help(wb, &p, homogeneous, prometheus_collector);
  587. if (unlikely(output_options & PROMETHEUS_OUTPUT_TYPES))
  588. buffer_sprintf(wb, "# TYPE %s_%s%s %s\n", prefix, context, suffix, p.type);
  589. generate_as_collected_prom_metric(wb, &p, homogeneous, prometheus_collector, st->rrdlabels);
  590. }
  591. else {
  592. // the dimensions of the chart, do not have the same algorithm, multiplier or divisor
  593. // we create a metric per dimension
  594. prometheus_name_copy(
  595. dimension,
  596. (output_options & PROMETHEUS_OUTPUT_NAMES && rd->name) ? rrddim_name(rd) : rrddim_id(rd),
  597. PROMETHEUS_ELEMENT_MAX);
  598. if (unlikely(output_options & PROMETHEUS_OUTPUT_HELP))
  599. generate_as_collected_prom_help(wb, &p, homogeneous, prometheus_collector);
  600. if (unlikely(output_options & PROMETHEUS_OUTPUT_TYPES))
  601. buffer_sprintf(
  602. wb, "# TYPE %s_%s_%s%s %s\n", prefix, context, dimension, suffix, p.type);
  603. generate_as_collected_prom_metric(wb, &p, homogeneous, prometheus_collector, st->rrdlabels);
  604. }
  605. }
  606. else {
  607. // we need average or sum of the data
  608. time_t first_time = instance->after;
  609. time_t last_time = instance->before;
  610. NETDATA_DOUBLE value = exporting_calculate_value_from_stored_data(instance, rd, &last_time);
  611. if (!isnan(value) && !isinf(value)) {
  612. if (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_AVERAGE)
  613. suffix = "_average";
  614. else if (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_SUM)
  615. suffix = "_sum";
  616. prometheus_label_copy(
  617. dimension,
  618. (output_options & PROMETHEUS_OUTPUT_NAMES && rd->name) ? rrddim_name(rd) : rrddim_id(rd),
  619. PROMETHEUS_ELEMENT_MAX);
  620. buffer_flush(plabels_buffer);
  621. buffer_sprintf(plabels_buffer, "%1$schart=\"%2$s\",%1$sdimension=\"%3$s\",%1$sfamily=\"%4$s\"", plabels_prefix, chart, dimension, family);
  622. rrdlabels_walkthrough_read(st->rrdlabels, format_prometheus_chart_label_callback, plabels_buffer);
  623. if (unlikely(output_options & PROMETHEUS_OUTPUT_HELP))
  624. buffer_sprintf(
  625. wb,
  626. "# COMMENT %s_%s%s%s: dimension \"%s\", value is %s, gauge, dt %llu to %llu inclusive\n",
  627. prefix,
  628. context,
  629. units,
  630. suffix,
  631. (output_options & PROMETHEUS_OUTPUT_NAMES && rd->name) ? rrddim_name(rd) : rrddim_id(rd),
  632. rrdset_units(st),
  633. (unsigned long long)first_time,
  634. (unsigned long long)last_time);
  635. if (unlikely(output_options & PROMETHEUS_OUTPUT_TYPES))
  636. buffer_sprintf(wb, "# TYPE %s_%s%s%s gauge\n", prefix, context, units, suffix);
  637. if (output_options & PROMETHEUS_OUTPUT_TIMESTAMPS)
  638. buffer_sprintf(
  639. wb,
  640. "%s_%s%s%s{%s%s} " NETDATA_DOUBLE_FORMAT
  641. " %llu\n",
  642. prefix,
  643. context,
  644. units,
  645. suffix,
  646. buffer_tostring(plabels_buffer),
  647. labels,
  648. value,
  649. last_time * MSEC_PER_SEC);
  650. else
  651. buffer_sprintf(
  652. wb,
  653. "%s_%s%s%s{%s%s} " NETDATA_DOUBLE_FORMAT
  654. "\n",
  655. prefix,
  656. context,
  657. units,
  658. suffix,
  659. buffer_tostring(plabels_buffer),
  660. labels,
  661. value);
  662. }
  663. }
  664. }
  665. }
  666. rrddim_foreach_done(rd);
  667. }
  668. }
  669. rrdset_foreach_done(st);
  670. buffer_free(plabels_buffer);
  671. simple_pattern_free(filter);
  672. }
  673. /**
  674. * Get the last time time when a server accessed Netdata. Write information about an API request to a buffer.
  675. *
  676. * @param instance an instance data structure.
  677. * @param host a data collecting host.
  678. * @param wb the buffer to write to.
  679. * @param exporting_options options to configure what data is exported.
  680. * @param server the name of a Prometheus server..
  681. * @param now actual time.
  682. * @param output_options options to configure the format of the output.
  683. * @return Returns the last time when the server accessed Netdata.
  684. */
  685. static inline time_t prometheus_preparation(
  686. struct instance *instance,
  687. RRDHOST *host,
  688. BUFFER *wb,
  689. EXPORTING_OPTIONS exporting_options,
  690. const char *server,
  691. time_t now,
  692. PROMETHEUS_OUTPUT_OPTIONS output_options)
  693. {
  694. #ifndef UNIT_TESTING
  695. analytics_log_prometheus();
  696. #endif
  697. if (!server || !*server)
  698. server = "default";
  699. time_t after = prometheus_server_last_access(server, host, now);
  700. int first_seen = 0;
  701. if (!after) {
  702. after = now - instance->config.update_every;
  703. first_seen = 1;
  704. }
  705. if (after > now) {
  706. // oops! this should never happen
  707. after = now - instance->config.update_every;
  708. }
  709. if (output_options & PROMETHEUS_OUTPUT_HELP) {
  710. char *mode;
  711. if (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_AS_COLLECTED)
  712. mode = "as collected";
  713. else if (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_AVERAGE)
  714. mode = "average";
  715. else if (EXPORTING_OPTIONS_DATA_SOURCE(exporting_options) == EXPORTING_SOURCE_DATA_SUM)
  716. mode = "sum";
  717. else
  718. mode = "unknown";
  719. buffer_sprintf(
  720. wb,
  721. "# COMMENT netdata \"%s\" to %sprometheus \"%s\", source \"%s\", last seen %lu %s, time range %lu to %lu\n\n",
  722. rrdhost_hostname(host),
  723. (first_seen) ? "FIRST SEEN " : "",
  724. server,
  725. mode,
  726. (unsigned long)((first_seen) ? 0 : (now - after)),
  727. (first_seen) ? "never" : "seconds ago",
  728. (unsigned long)after,
  729. (unsigned long)now);
  730. }
  731. return after;
  732. }
  733. /**
  734. * Write metrics and auxiliary information for one host to a buffer.
  735. *
  736. * @param host a data collecting host.
  737. * @param filter_string a simple pattern filter.
  738. * @param wb the buffer to write to.
  739. * @param server the name of a Prometheus server.
  740. * @param prefix a prefix for every metric.
  741. * @param exporting_options options to configure what data is exported.
  742. * @param output_options options to configure the format of the output.
  743. */
  744. void rrd_stats_api_v1_charts_allmetrics_prometheus_single_host(
  745. RRDHOST *host,
  746. const char *filter_string,
  747. BUFFER *wb,
  748. const char *server,
  749. const char *prefix,
  750. EXPORTING_OPTIONS exporting_options,
  751. PROMETHEUS_OUTPUT_OPTIONS output_options)
  752. {
  753. if (unlikely(!prometheus_exporter_instance || !prometheus_exporter_instance->config.initialized))
  754. return;
  755. prometheus_exporter_instance->before = now_realtime_sec();
  756. // we start at the point we had stopped before
  757. prometheus_exporter_instance->after = prometheus_preparation(
  758. prometheus_exporter_instance,
  759. host,
  760. wb,
  761. exporting_options,
  762. server,
  763. prometheus_exporter_instance->before,
  764. output_options);
  765. rrd_stats_api_v1_charts_allmetrics_prometheus(
  766. prometheus_exporter_instance, host, filter_string, wb, prefix, exporting_options, 0, output_options);
  767. }
  768. /**
  769. * Write metrics and auxiliary information for all hosts to a buffer.
  770. *
  771. * @param host a data collecting host.
  772. * @param filter_string a simple pattern filter.
  773. * @param wb the buffer to write to.
  774. * @param server the name of a Prometheus server.
  775. * @param prefix a prefix for every metric.
  776. * @param exporting_options options to configure what data is exported.
  777. * @param output_options options to configure the format of the output.
  778. */
  779. void rrd_stats_api_v1_charts_allmetrics_prometheus_all_hosts(
  780. RRDHOST *host,
  781. const char *filter_string,
  782. BUFFER *wb,
  783. const char *server,
  784. const char *prefix,
  785. EXPORTING_OPTIONS exporting_options,
  786. PROMETHEUS_OUTPUT_OPTIONS output_options)
  787. {
  788. if (unlikely(!prometheus_exporter_instance || !prometheus_exporter_instance->config.initialized))
  789. return;
  790. prometheus_exporter_instance->before = now_realtime_sec();
  791. // we start at the point we had stopped before
  792. prometheus_exporter_instance->after = prometheus_preparation(
  793. prometheus_exporter_instance,
  794. host,
  795. wb,
  796. exporting_options,
  797. server,
  798. prometheus_exporter_instance->before,
  799. output_options);
  800. dfe_start_reentrant(rrdhost_root_index, host)
  801. {
  802. rrd_stats_api_v1_charts_allmetrics_prometheus(
  803. prometheus_exporter_instance, host, filter_string, wb, prefix, exporting_options, 1, output_options);
  804. }
  805. dfe_done(host);
  806. }