2 * collectd - src/write_prometheus.c
3 * Copyright (C) 2016 Florian octo Forster
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to deal
7 * in the Software without restriction, including without limitation the rights
8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 * copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 * Florian octo Forster <octo at collectd.org>
31 #include "utils_avltree.h"
32 #include "utils_complain.h"
33 #include "utils_time.h"
35 #include "prometheus.pb-c.h"
37 #include <microhttpd.h>
40 #include <sys/socket.h>
41 #include <sys/types.h>
43 #ifndef PROMETHEUS_DEFAULT_STALENESS_DELTA
44 #define PROMETHEUS_DEFAULT_STALENESS_DELTA TIME_T_TO_CDTIME_T_STATIC(300)
47 #define VARINT_UINT32_BYTES 5
49 #define CONTENT_TYPE_PROTO \
50 "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; " \
52 #define CONTENT_TYPE_TEXT "text/plain; version=0.0.4"
54 static c_avl_tree_t *metrics;
55 static pthread_mutex_t metrics_lock = PTHREAD_MUTEX_INITIALIZER;
57 static unsigned short httpd_port = 9103;
58 static struct MHD_Daemon *httpd;
60 static cdtime_t staleness_delta = PROMETHEUS_DEFAULT_STALENESS_DELTA;
62 /* Unfortunately, protoc-c doesn't export its implementation of varint, so we
63 * need to implement our own. */
64 static size_t varint(uint8_t buffer[static VARINT_UINT32_BYTES],
66 for (size_t i = 0; i < VARINT_UINT32_BYTES; i++) {
67 buffer[i] = (uint8_t)(value & 0x7f);
79 /* format_protobuf iterates over all metric families in "metrics" and adds them
80 * to a buffer in ProtoBuf format. It prefixes each protobuf with its encoded
81 * size, the so called "delimited" format. */
82 static void format_protobuf(ProtobufCBuffer *buffer) {
83 pthread_mutex_lock(&metrics_lock);
86 Io__Prometheus__Client__MetricFamily *fam;
87 c_avl_iterator_t *iter = c_avl_get_iterator(metrics);
88 while (c_avl_iterator_next(iter, (void *)&unused_name, (void *)&fam) == 0) {
89 /* Prometheus uses a message length prefix to determine where one
90 * MetricFamily ends and the next begins. This delimiter is encoded as a
91 * "varint", which is common in Protobufs. */
92 uint8_t delim[VARINT_UINT32_BYTES] = {0};
93 size_t delim_len = varint(
95 (uint32_t)io__prometheus__client__metric_family__get_packed_size(fam));
96 buffer->append(buffer, delim_len, delim);
98 io__prometheus__client__metric_family__pack_to_buffer(fam, buffer);
100 c_avl_iterator_destroy(iter);
102 pthread_mutex_unlock(&metrics_lock);
105 static char const *escape_label_value(char *buffer, size_t buffer_size,
107 /* shortcut for values that don't need escaping. */
108 if (strpbrk(value, "\n\"\\") == NULL)
111 size_t value_len = strlen(value);
112 size_t buffer_len = 0;
114 for (size_t i = 0; i < value_len; i++) {
119 if ((buffer_size - buffer_len) < 3) {
122 buffer[buffer_len] = '\\';
123 buffer[buffer_len + 1] = (value[i] == '\n') ? 'n' : value[i];
128 if ((buffer_size - buffer_len) < 2) {
131 buffer[buffer_len] = value[i];
137 assert(buffer_len < buffer_size);
138 buffer[buffer_len] = 0;
142 /* format_labels formats a metric's labels in Prometheus-compatible format. This
143 * format looks like this:
145 * key0="value0",key1="value1"
147 static char *format_labels(char *buffer, size_t buffer_size,
148 Io__Prometheus__Client__Metric const *m) {
149 /* our metrics always have at least one and at most three labels. */
150 assert(m->n_label >= 1);
151 assert(m->n_label <= 3);
153 #define LABEL_KEY_SIZE DATA_MAX_NAME_LEN
154 #define LABEL_VALUE_SIZE (2 * DATA_MAX_NAME_LEN - 1)
155 #define LABEL_BUFFER_SIZE (LABEL_KEY_SIZE + LABEL_VALUE_SIZE + 4)
158 (char[LABEL_BUFFER_SIZE]){0}, (char[LABEL_BUFFER_SIZE]){0},
159 (char[LABEL_BUFFER_SIZE]){0},
162 /* N.B.: the label *names* are hard-coded by this plugin and therefore we
163 * know that they are sane. */
164 for (size_t i = 0; i < m->n_label; i++) {
165 char value[LABEL_VALUE_SIZE];
166 snprintf(labels[i], LABEL_BUFFER_SIZE, "%s=\"%s\"", m->label[i]->name,
167 escape_label_value(value, sizeof(value), m->label[i]->value));
170 strjoin(buffer, buffer_size, labels, m->n_label, ",");
174 /* format_protobuf iterates over all metric families in "metrics" and adds them
175 * to a buffer in plain text format. */
176 static void format_text(ProtobufCBuffer *buffer) {
177 pthread_mutex_lock(&metrics_lock);
180 Io__Prometheus__Client__MetricFamily *fam;
181 c_avl_iterator_t *iter = c_avl_get_iterator(metrics);
182 while (c_avl_iterator_next(iter, (void *)&unused_name, (void *)&fam) == 0) {
183 char line[1024]; /* 4x DATA_MAX_NAME_LEN? */
185 snprintf(line, sizeof(line), "# HELP %s %s\n", fam->name, fam->help);
186 buffer->append(buffer, strlen(line), (uint8_t *)line);
188 snprintf(line, sizeof(line), "# TYPE %s %s\n", fam->name,
189 (fam->type == IO__PROMETHEUS__CLIENT__METRIC_TYPE__GAUGE)
192 buffer->append(buffer, strlen(line), (uint8_t *)line);
194 for (size_t i = 0; i < fam->n_metric; i++) {
195 Io__Prometheus__Client__Metric *m = fam->metric[i];
199 char timestamp_ms[24] = "";
200 if (m->has_timestamp_ms)
201 snprintf(timestamp_ms, sizeof(timestamp_ms), " %" PRIi64,
204 if (fam->type == IO__PROMETHEUS__CLIENT__METRIC_TYPE__GAUGE)
205 snprintf(line, sizeof(line), "%s{%s} " GAUGE_FORMAT "%s\n", fam->name,
206 format_labels(labels, sizeof(labels), m), m->gauge->value,
208 else /* if (fam->type == IO__PROMETHEUS__CLIENT__METRIC_TYPE__COUNTER) */
209 snprintf(line, sizeof(line), "%s{%s} %.0f%s\n", fam->name,
210 format_labels(labels, sizeof(labels), m), m->counter->value,
213 buffer->append(buffer, strlen(line), (uint8_t *)line);
216 c_avl_iterator_destroy(iter);
219 snprintf(server, sizeof(server), "\n# collectd/write_prometheus %s at %s\n",
220 PACKAGE_VERSION, hostname_g);
221 buffer->append(buffer, strlen(server), (uint8_t *)server);
223 pthread_mutex_unlock(&metrics_lock);
226 /* http_handler is the callback called by the microhttpd library. It essentially
227 * handles all HTTP request aspects and creates an HTTP response. */
228 static int http_handler(void *cls, struct MHD_Connection *connection,
229 const char *url, const char *method,
230 const char *version, const char *upload_data,
231 size_t *upload_data_size, void **connection_state) {
232 if (strcmp(method, MHD_HTTP_METHOD_GET) != 0) {
236 /* On the first call for each connection, return without anything further.
237 * Apparently not everything has been initialized yet or so; the docs are not
238 * very specific on the issue. */
239 if (*connection_state == NULL) {
240 /* set to a random non-NULL pointer. */
241 *connection_state = &(int){42};
245 char const *accept = MHD_lookup_connection_value(connection, MHD_HEADER_KIND,
246 MHD_HTTP_HEADER_ACCEPT);
247 bool want_proto = (accept != NULL) &&
248 (strstr(accept, "application/vnd.google.protobuf") != NULL);
250 uint8_t scratch[4096] = {0};
251 ProtobufCBufferSimple simple = PROTOBUF_C_BUFFER_SIMPLE_INIT(scratch);
252 ProtobufCBuffer *buffer = (ProtobufCBuffer *)&simple;
255 format_protobuf(buffer);
259 #if defined(MHD_VERSION) && MHD_VERSION >= 0x00090500
260 struct MHD_Response *res = MHD_create_response_from_buffer(
261 simple.len, simple.data, MHD_RESPMEM_MUST_COPY);
263 struct MHD_Response *res = MHD_create_response_from_data(
264 simple.len, simple.data, /* must_free = */ 0, /* must_copy = */ 1);
266 MHD_add_response_header(res, MHD_HTTP_HEADER_CONTENT_TYPE,
267 want_proto ? CONTENT_TYPE_PROTO : CONTENT_TYPE_TEXT);
269 int status = MHD_queue_response(connection, MHD_HTTP_OK, res);
271 MHD_destroy_response(res);
272 PROTOBUF_C_BUFFER_SIMPLE_CLEAR(&simple);
277 * Functions for manipulating the global state in "metrics". This is organized
278 * in two tiers: the global "metrics" tree holds "metric families", which are
279 * identified by a name (a string). Each metric family has one or more
280 * "metrics", which are identified by a unique set of key-value-pairs. For
284 * {cpu="0",type="idle"}
285 * {cpu="0",type="user"}
292 /* label_pair_destroy frees the memory used by a label pair. */
293 static void label_pair_destroy(Io__Prometheus__Client__LabelPair *msg) {
303 /* label_pair_clone allocates and initializes a new label pair. */
304 static Io__Prometheus__Client__LabelPair *
305 label_pair_clone(Io__Prometheus__Client__LabelPair const *orig) {
306 Io__Prometheus__Client__LabelPair *copy = calloc(1, sizeof(*copy));
309 io__prometheus__client__label_pair__init(copy);
311 copy->name = strdup(orig->name);
312 copy->value = strdup(orig->value);
313 if ((copy->name == NULL) || (copy->value == NULL)) {
314 label_pair_destroy(copy);
321 /* metric_destroy frees the memory used by a metric. */
322 static void metric_destroy(Io__Prometheus__Client__Metric *msg) {
326 for (size_t i = 0; i < msg->n_label; i++) {
327 label_pair_destroy(msg->label[i]);
337 /* metric_cmp compares two metrics. It's prototype makes it easy to use with
338 * qsort(3) and bsearch(3). */
339 static int metric_cmp(void const *a, void const *b) {
340 Io__Prometheus__Client__Metric const *m_a =
341 *((Io__Prometheus__Client__Metric **)a);
342 Io__Prometheus__Client__Metric const *m_b =
343 *((Io__Prometheus__Client__Metric **)b);
345 if (m_a->n_label < m_b->n_label)
347 else if (m_a->n_label > m_b->n_label)
350 /* Prometheus does not care about the order of labels. All labels in this
351 * plugin are created by METRIC_ADD_LABELS(), though, and therefore always
352 * appear in the same order. We take advantage of this and simplify the check
353 * by making sure all labels are the same in each position.
355 * We also only need to check the label values, because the label names are
356 * the same for all metrics in a metric family.
359 * [0] $plugin="$plugin_instance" => $plugin is the same within a family
360 * [1] type="$type_instance" => "type" is a static string
361 * [2] instance="$host" => "instance" is a static string
363 * 2 labels, variant 1:
364 * [0] $plugin="$plugin_instance" => $plugin is the same within a family
365 * [1] instance="$host" => "instance" is a static string
367 * 2 labels, variant 2:
368 * [0] $plugin="$type_instance" => $plugin is the same within a family
369 * [1] instance="$host" => "instance" is a static string
372 * [1] instance="$host" => "instance" is a static string
374 for (size_t i = 0; i < m_a->n_label; i++) {
375 int status = strcmp(m_a->label[i]->value, m_b->label[i]->value);
380 assert(strcmp(m_a->label[i]->name, m_b->label[i]->name) == 0);
387 #define METRIC_INIT \
388 &(Io__Prometheus__Client__Metric) { \
390 (Io__Prometheus__Client__LabelPair *[]){ \
391 &(Io__Prometheus__Client__LabelPair){ \
394 &(Io__Prometheus__Client__LabelPair){ \
397 &(Io__Prometheus__Client__LabelPair){ \
404 #define METRIC_ADD_LABELS(m, vl) \
406 if (strlen((vl)->plugin_instance) != 0) { \
407 (m)->label[(m)->n_label]->name = (char *)(vl)->plugin; \
408 (m)->label[(m)->n_label]->value = (char *)(vl)->plugin_instance; \
412 if (strlen((vl)->type_instance) != 0) { \
413 (m)->label[(m)->n_label]->name = "type"; \
414 if (strlen((vl)->plugin_instance) == 0) \
415 (m)->label[(m)->n_label]->name = (char *)(vl)->plugin; \
416 (m)->label[(m)->n_label]->value = (char *)(vl)->type_instance; \
420 (m)->label[(m)->n_label]->name = "instance"; \
421 (m)->label[(m)->n_label]->value = (char *)(vl)->host; \
425 /* metric_clone allocates and initializes a new metric based on orig. */
426 static Io__Prometheus__Client__Metric *
427 metric_clone(Io__Prometheus__Client__Metric const *orig) {
428 Io__Prometheus__Client__Metric *copy = calloc(1, sizeof(*copy));
431 io__prometheus__client__metric__init(copy);
433 copy->n_label = orig->n_label;
434 copy->label = calloc(copy->n_label, sizeof(*copy->label));
435 if (copy->label == NULL) {
440 for (size_t i = 0; i < copy->n_label; i++) {
441 copy->label[i] = label_pair_clone(orig->label[i]);
442 if (copy->label[i] == NULL) {
443 metric_destroy(copy);
451 /* metric_update stores the new value and timestamp in m. */
452 static int metric_update(Io__Prometheus__Client__Metric *m, value_t value,
453 int ds_type, cdtime_t t, cdtime_t interval) {
454 if (ds_type == DS_TYPE_GAUGE) {
456 if (m->gauge == NULL) {
457 m->gauge = calloc(1, sizeof(*m->gauge));
458 if (m->gauge == NULL)
460 io__prometheus__client__gauge__init(m->gauge);
463 m->gauge->value = (double)value.gauge;
464 m->gauge->has_value = 1;
465 } else { /* not gauge */
467 if (m->counter == NULL) {
468 m->counter = calloc(1, sizeof(*m->counter));
469 if (m->counter == NULL)
471 io__prometheus__client__counter__init(m->counter);
475 case DS_TYPE_ABSOLUTE:
476 m->counter->value = (double)value.absolute;
478 case DS_TYPE_COUNTER:
479 m->counter->value = (double)value.counter;
482 m->counter->value = (double)value.derive;
485 m->counter->has_value = 1;
488 /* Prometheus has a globally configured timeout after which metrics are
489 * considered stale. This causes problems when metrics have an interval
490 * exceeding that limit. We emulate the behavior of "pushgateway" and *not*
491 * send a timestamp value – Prometheus will fill in the current time. */
492 if (interval <= staleness_delta) {
493 m->timestamp_ms = CDTIME_T_TO_MS(t);
494 m->has_timestamp_ms = 1;
496 static c_complain_t long_metric = C_COMPLAIN_INIT_STATIC;
498 LOG_NOTICE, &long_metric,
499 "write_prometheus plugin: You have metrics with an interval exceeding "
500 "\"StalenessDelta\" setting (%.3fs). This is suboptimal, please check "
501 "the collectd.conf(5) manual page to understand what's going on.",
502 CDTIME_T_TO_DOUBLE(staleness_delta));
505 m->has_timestamp_ms = 0;
511 /* metric_family_add_metric adds m to the metric list of fam. */
512 static int metric_family_add_metric(Io__Prometheus__Client__MetricFamily *fam,
513 Io__Prometheus__Client__Metric *m) {
514 Io__Prometheus__Client__Metric **tmp =
515 realloc(fam->metric, (fam->n_metric + 1) * sizeof(*fam->metric));
520 fam->metric[fam->n_metric] = m;
523 /* Sort the metrics so that lookup is fast. */
524 qsort(fam->metric, fam->n_metric, sizeof(*fam->metric), metric_cmp);
529 /* metric_family_delete_metric looks up and deletes the metric corresponding to
532 metric_family_delete_metric(Io__Prometheus__Client__MetricFamily *fam,
533 value_list_t const *vl) {
534 Io__Prometheus__Client__Metric *key = METRIC_INIT;
535 METRIC_ADD_LABELS(key, vl);
538 for (i = 0; i < fam->n_metric; i++) {
539 if (metric_cmp(&key, &fam->metric[i]) == 0)
543 if (i >= fam->n_metric)
546 metric_destroy(fam->metric[i]);
547 if ((fam->n_metric - 1) > i)
548 memmove(&fam->metric[i], &fam->metric[i + 1],
549 ((fam->n_metric - 1) - i) * sizeof(fam->metric[i]));
552 if (fam->n_metric == 0) {
557 Io__Prometheus__Client__Metric **tmp =
558 realloc(fam->metric, fam->n_metric * sizeof(*fam->metric));
565 /* metric_family_get_metric looks up the matching metric in a metric family,
566 * allocating it if necessary. */
567 static Io__Prometheus__Client__Metric *
568 metric_family_get_metric(Io__Prometheus__Client__MetricFamily *fam,
569 value_list_t const *vl) {
570 Io__Prometheus__Client__Metric *key = METRIC_INIT;
571 METRIC_ADD_LABELS(key, vl);
573 /* Metrics are sorted in metric_family_add_metric() so that we can do a binary
575 Io__Prometheus__Client__Metric **m = bsearch(
576 &key, fam->metric, fam->n_metric, sizeof(*fam->metric), metric_cmp);
582 Io__Prometheus__Client__Metric *new_metric = metric_clone(key);
583 if (new_metric == NULL)
586 DEBUG("write_prometheus plugin: created new metric in family");
587 int status = metric_family_add_metric(fam, new_metric);
589 metric_destroy(new_metric);
596 /* metric_family_update looks up the matching metric in a metric family,
597 * allocating it if necessary, and updates the metric to the latest value. */
598 static int metric_family_update(Io__Prometheus__Client__MetricFamily *fam,
599 data_set_t const *ds, value_list_t const *vl,
601 Io__Prometheus__Client__Metric *m = metric_family_get_metric(fam, vl);
605 return metric_update(m, vl->values[ds_index], ds->ds[ds_index].type, vl->time,
609 /* metric_family_destroy frees the memory used by a metric family. */
610 static void metric_family_destroy(Io__Prometheus__Client__MetricFamily *msg) {
617 for (size_t i = 0; i < msg->n_metric; i++) {
618 metric_destroy(msg->metric[i]);
625 /* metric_family_create allocates and initializes a new metric family. */
626 static Io__Prometheus__Client__MetricFamily *
627 metric_family_create(char *name, data_set_t const *ds, value_list_t const *vl,
629 Io__Prometheus__Client__MetricFamily *msg = calloc(1, sizeof(*msg));
632 io__prometheus__client__metric_family__init(msg);
639 "write_prometheus plugin: '%s' Type: '%s', Dstype: '%s', Dsname: '%s'",
640 vl->plugin, vl->type, DS_TYPE_TO_STRING(ds->ds[ds_index].type),
641 ds->ds[ds_index].name);
642 msg->help = strdup(help);
644 msg->type = (ds->ds[ds_index].type == DS_TYPE_GAUGE)
645 ? IO__PROMETHEUS__CLIENT__METRIC_TYPE__GAUGE
646 : IO__PROMETHEUS__CLIENT__METRIC_TYPE__COUNTER;
652 /* metric_family_name creates a metric family's name from a data source. This is
653 * done in the same way as done by the "collectd_exporter" for best possible
654 * compatibility. In essence, the plugin, type and data source name go in the
655 * metric family name, while hostname, plugin instance and type instance go into
656 * the labels of a metric. */
657 static char *metric_family_name(data_set_t const *ds, value_list_t const *vl,
659 char const *fields[5] = {"collectd"};
660 size_t fields_num = 1;
662 if (strcmp(vl->plugin, vl->type) != 0) {
663 fields[fields_num] = vl->plugin;
666 fields[fields_num] = vl->type;
669 if (strcmp("value", ds->ds[ds_index].name) != 0) {
670 fields[fields_num] = ds->ds[ds_index].name;
674 /* Prometheus best practices:
675 * cumulative metrics should have a "total" suffix. */
676 if ((ds->ds[ds_index].type == DS_TYPE_COUNTER) ||
677 (ds->ds[ds_index].type == DS_TYPE_DERIVE)) {
678 fields[fields_num] = "total";
682 char name[5 * DATA_MAX_NAME_LEN];
683 strjoin(name, sizeof(name), (char **)fields, fields_num, "_");
687 /* metric_family_get looks up the matching metric family, allocating it if
689 static Io__Prometheus__Client__MetricFamily *
690 metric_family_get(data_set_t const *ds, value_list_t const *vl, size_t ds_index,
692 char *name = metric_family_name(ds, vl, ds_index);
694 ERROR("write_prometheus plugin: Allocating metric family name failed.");
698 Io__Prometheus__Client__MetricFamily *fam = NULL;
699 if (c_avl_get(metrics, name, (void *)&fam) == 0) {
710 fam = metric_family_create(name, ds, vl, ds_index);
712 ERROR("write_prometheus plugin: Allocating metric family failed.");
717 /* If successful, "name" is owned by "fam", i.e. don't free it here. */
718 DEBUG("write_prometheus plugin: metric family \"%s\" has been created.",
722 int status = c_avl_insert(metrics, fam->name, fam);
724 ERROR("write_prometheus plugin: Adding \"%s\" failed.", name);
725 metric_family_destroy(fam);
733 static void prom_logger(__attribute__((unused)) void *arg, char const *fmt,
737 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
739 ERROR("write_prometheus plugin: %s", errbuf);
740 } /* }}} prom_logger */
742 #if MHD_VERSION >= 0x00090000
743 static int prom_open_socket(int addrfamily) {
745 char service[NI_MAXSERV];
746 snprintf(service, sizeof(service), "%hu", httpd_port);
748 struct addrinfo *res;
749 int status = getaddrinfo(NULL, service,
751 .ai_flags = AI_PASSIVE | AI_ADDRCONFIG,
752 .ai_family = addrfamily,
753 .ai_socktype = SOCK_STREAM,
761 for (struct addrinfo *ai = res; ai != NULL; ai = ai->ai_next) {
762 fd = socket(ai->ai_family, ai->ai_socktype | SOCK_CLOEXEC, 0);
767 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)) != 0) {
768 WARNING("write_prometheus: setsockopt(SO_REUSEADDR) failed: %s",
775 if (bind(fd, ai->ai_addr, ai->ai_addrlen) != 0) {
781 if (listen(fd, /* backlog = */ 16) != 0) {
793 } /* }}} int prom_open_socket */
795 static struct MHD_Daemon *prom_start_daemon() {
797 int fd = prom_open_socket(PF_INET6);
799 fd = prom_open_socket(PF_INET);
801 ERROR("write_prometheus plugin: Opening a listening socket failed.");
805 struct MHD_Daemon *d = MHD_start_daemon(
806 MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG, httpd_port,
807 /* MHD_AcceptPolicyCallback = */ NULL,
808 /* MHD_AcceptPolicyCallback arg = */ NULL, http_handler, NULL,
809 MHD_OPTION_LISTEN_SOCKET, fd, MHD_OPTION_EXTERNAL_LOGGER, prom_logger,
810 NULL, MHD_OPTION_END);
812 ERROR("write_prometheus plugin: MHD_start_daemon() failed.");
818 } /* }}} struct MHD_Daemon *prom_start_daemon */
819 #else /* if MHD_VERSION < 0x00090000 */
820 static struct MHD_Daemon *prom_start_daemon() {
822 struct MHD_Daemon *d = MHD_start_daemon(
823 MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG, httpd_port,
824 /* MHD_AcceptPolicyCallback = */ NULL,
825 /* MHD_AcceptPolicyCallback arg = */ NULL, http_handler, NULL,
826 MHD_OPTION_EXTERNAL_LOGGER, prom_logger, NULL, MHD_OPTION_END);
828 ERROR("write_prometheus plugin: MHD_start_daemon() failed.");
833 } /* }}} struct MHD_Daemon *prom_start_daemon */
839 static int prom_config(oconfig_item_t *ci) {
840 for (int i = 0; i < ci->children_num; i++) {
841 oconfig_item_t *child = ci->children + i;
843 if (strcasecmp("Port", child->key) == 0) {
844 int status = cf_util_get_port_number(child);
846 httpd_port = (unsigned short)status;
847 } else if (strcasecmp("StalenessDelta", child->key) == 0) {
848 cf_util_get_cdtime(child, &staleness_delta);
850 WARNING("write_prometheus plugin: Ignoring unknown configuration option "
859 static int prom_init() {
860 if (metrics == NULL) {
861 metrics = c_avl_create((void *)strcmp);
862 if (metrics == NULL) {
863 ERROR("write_prometheus plugin: c_avl_create() failed.");
869 httpd = prom_start_daemon();
871 ERROR("write_prometheus plugin: MHD_start_daemon() failed.");
874 DEBUG("write_prometheus plugin: Successfully started microhttpd %s",
881 static int prom_write(data_set_t const *ds, value_list_t const *vl,
882 __attribute__((unused)) user_data_t *ud) {
883 pthread_mutex_lock(&metrics_lock);
885 for (size_t i = 0; i < ds->ds_num; i++) {
886 Io__Prometheus__Client__MetricFamily *fam =
887 metric_family_get(ds, vl, i, /* allocate = */ true);
891 int status = metric_family_update(fam, ds, vl, i);
893 ERROR("write_prometheus plugin: Updating metric \"%s\" failed with "
900 pthread_mutex_unlock(&metrics_lock);
904 static int prom_missing(value_list_t const *vl,
905 __attribute__((unused)) user_data_t *ud) {
906 data_set_t const *ds = plugin_get_ds(vl->type);
910 pthread_mutex_lock(&metrics_lock);
912 for (size_t i = 0; i < ds->ds_num; i++) {
913 Io__Prometheus__Client__MetricFamily *fam =
914 metric_family_get(ds, vl, i, /* allocate = */ false);
918 int status = metric_family_delete_metric(fam, vl);
920 ERROR("write_prometheus plugin: Deleting a metric in family \"%s\" "
921 "failed with status %d",
927 if (fam->n_metric == 0) {
928 int status = c_avl_remove(metrics, fam->name, NULL, NULL);
930 ERROR("write_prometheus plugin: Deleting metric family \"%s\" failed "
935 metric_family_destroy(fam);
939 pthread_mutex_unlock(&metrics_lock);
943 static int prom_shutdown() {
945 MHD_stop_daemon(httpd);
949 pthread_mutex_lock(&metrics_lock);
950 if (metrics != NULL) {
952 Io__Prometheus__Client__MetricFamily *fam;
953 while (c_avl_pick(metrics, (void *)&name, (void *)&fam) == 0) {
954 assert(name == fam->name);
957 metric_family_destroy(fam);
959 c_avl_destroy(metrics);
962 pthread_mutex_unlock(&metrics_lock);
967 void module_register() {
968 plugin_register_complex_config("write_prometheus", prom_config);
969 plugin_register_init("write_prometheus", prom_init);
970 plugin_register_write("write_prometheus", prom_write,
971 /* user data = */ NULL);
972 plugin_register_missing("write_prometheus", prom_missing,
973 /* user data = */ NULL);
974 plugin_register_shutdown("write_prometheus", prom_shutdown);