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 char *httpd_host = NULL;
58 static unsigned short httpd_port = 9103;
59 static struct MHD_Daemon *httpd;
61 static cdtime_t staleness_delta = PROMETHEUS_DEFAULT_STALENESS_DELTA;
63 /* Unfortunately, protoc-c doesn't export its implementation of varint, so we
64 * need to implement our own. */
65 static size_t varint(uint8_t buffer[static VARINT_UINT32_BYTES],
67 for (size_t i = 0; i < VARINT_UINT32_BYTES; i++) {
68 buffer[i] = (uint8_t)(value & 0x7f);
80 /* format_protobuf iterates over all metric families in "metrics" and adds them
81 * to a buffer in ProtoBuf format. It prefixes each protobuf with its encoded
82 * size, the so called "delimited" format. */
83 static void format_protobuf(ProtobufCBuffer *buffer) {
84 pthread_mutex_lock(&metrics_lock);
87 Io__Prometheus__Client__MetricFamily *fam;
88 c_avl_iterator_t *iter = c_avl_get_iterator(metrics);
89 while (c_avl_iterator_next(iter, (void *)&unused_name, (void *)&fam) == 0) {
90 /* Prometheus uses a message length prefix to determine where one
91 * MetricFamily ends and the next begins. This delimiter is encoded as a
92 * "varint", which is common in Protobufs. */
93 uint8_t delim[VARINT_UINT32_BYTES] = {0};
94 size_t delim_len = varint(
96 (uint32_t)io__prometheus__client__metric_family__get_packed_size(fam));
97 buffer->append(buffer, delim_len, delim);
99 io__prometheus__client__metric_family__pack_to_buffer(fam, buffer);
101 c_avl_iterator_destroy(iter);
103 pthread_mutex_unlock(&metrics_lock);
106 static char const *escape_label_value(char *buffer, size_t buffer_size,
108 /* shortcut for values that don't need escaping. */
109 if (strpbrk(value, "\n\"\\") == NULL)
112 size_t value_len = strlen(value);
113 size_t buffer_len = 0;
115 for (size_t i = 0; i < value_len; i++) {
120 if ((buffer_size - buffer_len) < 3) {
123 buffer[buffer_len] = '\\';
124 buffer[buffer_len + 1] = (value[i] == '\n') ? 'n' : value[i];
129 if ((buffer_size - buffer_len) < 2) {
132 buffer[buffer_len] = value[i];
138 assert(buffer_len < buffer_size);
139 buffer[buffer_len] = 0;
143 /* format_labels formats a metric's labels in Prometheus-compatible format. This
144 * format looks like this:
146 * key0="value0",key1="value1"
148 static char *format_labels(char *buffer, size_t buffer_size,
149 Io__Prometheus__Client__Metric const *m) {
150 /* our metrics always have at least one and at most three labels. */
151 assert(m->n_label >= 1);
152 assert(m->n_label <= 3);
154 #define LABEL_KEY_SIZE DATA_MAX_NAME_LEN
155 #define LABEL_VALUE_SIZE (2 * DATA_MAX_NAME_LEN - 1)
156 #define LABEL_BUFFER_SIZE (LABEL_KEY_SIZE + LABEL_VALUE_SIZE + 4)
159 (char[LABEL_BUFFER_SIZE]){0}, (char[LABEL_BUFFER_SIZE]){0},
160 (char[LABEL_BUFFER_SIZE]){0},
163 /* N.B.: the label *names* are hard-coded by this plugin and therefore we
164 * know that they are sane. */
165 for (size_t i = 0; i < m->n_label; i++) {
166 char value[LABEL_VALUE_SIZE];
167 snprintf(labels[i], LABEL_BUFFER_SIZE, "%s=\"%s\"", m->label[i]->name,
168 escape_label_value(value, sizeof(value), m->label[i]->value));
171 strjoin(buffer, buffer_size, labels, m->n_label, ",");
175 /* format_protobuf iterates over all metric families in "metrics" and adds them
176 * to a buffer in plain text format. */
177 static void format_text(ProtobufCBuffer *buffer) {
178 pthread_mutex_lock(&metrics_lock);
181 Io__Prometheus__Client__MetricFamily *fam;
182 c_avl_iterator_t *iter = c_avl_get_iterator(metrics);
183 while (c_avl_iterator_next(iter, (void *)&unused_name, (void *)&fam) == 0) {
184 char line[1024]; /* 4x DATA_MAX_NAME_LEN? */
186 snprintf(line, sizeof(line), "# HELP %s %s\n", fam->name, fam->help);
187 buffer->append(buffer, strlen(line), (uint8_t *)line);
189 snprintf(line, sizeof(line), "# TYPE %s %s\n", fam->name,
190 (fam->type == IO__PROMETHEUS__CLIENT__METRIC_TYPE__GAUGE)
193 buffer->append(buffer, strlen(line), (uint8_t *)line);
195 for (size_t i = 0; i < fam->n_metric; i++) {
196 Io__Prometheus__Client__Metric *m = fam->metric[i];
200 char timestamp_ms[24] = "";
201 if (m->has_timestamp_ms)
202 snprintf(timestamp_ms, sizeof(timestamp_ms), " %" PRIi64,
205 if (fam->type == IO__PROMETHEUS__CLIENT__METRIC_TYPE__GAUGE)
206 snprintf(line, sizeof(line), "%s{%s} " GAUGE_FORMAT "%s\n", fam->name,
207 format_labels(labels, sizeof(labels), m), m->gauge->value,
209 else /* if (fam->type == IO__PROMETHEUS__CLIENT__METRIC_TYPE__COUNTER) */
210 snprintf(line, sizeof(line), "%s{%s} %.0f%s\n", fam->name,
211 format_labels(labels, sizeof(labels), m), m->counter->value,
214 buffer->append(buffer, strlen(line), (uint8_t *)line);
217 c_avl_iterator_destroy(iter);
220 snprintf(server, sizeof(server), "\n# collectd/write_prometheus %s at %s\n",
221 PACKAGE_VERSION, hostname_g);
222 buffer->append(buffer, strlen(server), (uint8_t *)server);
224 pthread_mutex_unlock(&metrics_lock);
227 /* http_handler is the callback called by the microhttpd library. It essentially
228 * handles all HTTP request aspects and creates an HTTP response. */
229 static int http_handler(void *cls, struct MHD_Connection *connection,
230 const char *url, const char *method,
231 const char *version, const char *upload_data,
232 size_t *upload_data_size, void **connection_state) {
233 if (strcmp(method, MHD_HTTP_METHOD_GET) != 0) {
237 /* On the first call for each connection, return without anything further.
238 * Apparently not everything has been initialized yet or so; the docs are not
239 * very specific on the issue. */
240 if (*connection_state == NULL) {
241 /* set to a random non-NULL pointer. */
242 *connection_state = &(int){42};
246 char const *accept = MHD_lookup_connection_value(connection, MHD_HEADER_KIND,
247 MHD_HTTP_HEADER_ACCEPT);
248 bool want_proto = (accept != NULL) &&
249 (strstr(accept, "application/vnd.google.protobuf") != NULL);
251 uint8_t scratch[4096] = {0};
252 ProtobufCBufferSimple simple = PROTOBUF_C_BUFFER_SIMPLE_INIT(scratch);
253 ProtobufCBuffer *buffer = (ProtobufCBuffer *)&simple;
256 format_protobuf(buffer);
260 #if defined(MHD_VERSION) && MHD_VERSION >= 0x00090500
261 struct MHD_Response *res = MHD_create_response_from_buffer(
262 simple.len, simple.data, MHD_RESPMEM_MUST_COPY);
264 struct MHD_Response *res = MHD_create_response_from_data(
265 simple.len, simple.data, /* must_free = */ 0, /* must_copy = */ 1);
267 MHD_add_response_header(res, MHD_HTTP_HEADER_CONTENT_TYPE,
268 want_proto ? CONTENT_TYPE_PROTO : CONTENT_TYPE_TEXT);
270 int status = MHD_queue_response(connection, MHD_HTTP_OK, res);
272 MHD_destroy_response(res);
273 PROTOBUF_C_BUFFER_SIMPLE_CLEAR(&simple);
278 * Functions for manipulating the global state in "metrics". This is organized
279 * in two tiers: the global "metrics" tree holds "metric families", which are
280 * identified by a name (a string). Each metric family has one or more
281 * "metrics", which are identified by a unique set of key-value-pairs. For
285 * {cpu="0",type="idle"}
286 * {cpu="0",type="user"}
293 /* label_pair_destroy frees the memory used by a label pair. */
294 static void label_pair_destroy(Io__Prometheus__Client__LabelPair *msg) {
304 /* label_pair_clone allocates and initializes a new label pair. */
305 static Io__Prometheus__Client__LabelPair *
306 label_pair_clone(Io__Prometheus__Client__LabelPair const *orig) {
307 Io__Prometheus__Client__LabelPair *copy = calloc(1, sizeof(*copy));
310 io__prometheus__client__label_pair__init(copy);
312 copy->name = strdup(orig->name);
313 copy->value = strdup(orig->value);
314 if ((copy->name == NULL) || (copy->value == NULL)) {
315 label_pair_destroy(copy);
322 /* metric_destroy frees the memory used by a metric. */
323 static void metric_destroy(Io__Prometheus__Client__Metric *msg) {
327 for (size_t i = 0; i < msg->n_label; i++) {
328 label_pair_destroy(msg->label[i]);
338 /* metric_cmp compares two metrics. It's prototype makes it easy to use with
339 * qsort(3) and bsearch(3). */
340 static int metric_cmp(void const *a, void const *b) {
341 Io__Prometheus__Client__Metric const *m_a =
342 *((Io__Prometheus__Client__Metric **)a);
343 Io__Prometheus__Client__Metric const *m_b =
344 *((Io__Prometheus__Client__Metric **)b);
346 if (m_a->n_label < m_b->n_label)
348 else if (m_a->n_label > m_b->n_label)
351 /* Prometheus does not care about the order of labels. All labels in this
352 * plugin are created by METRIC_ADD_LABELS(), though, and therefore always
353 * appear in the same order. We take advantage of this and simplify the check
354 * by making sure all labels are the same in each position.
356 * We also only need to check the label values, because the label names are
357 * the same for all metrics in a metric family.
360 * [0] $plugin="$plugin_instance" => $plugin is the same within a family
361 * [1] type="$type_instance" => "type" is a static string
362 * [2] instance="$host" => "instance" is a static string
364 * 2 labels, variant 1:
365 * [0] $plugin="$plugin_instance" => $plugin is the same within a family
366 * [1] instance="$host" => "instance" is a static string
368 * 2 labels, variant 2:
369 * [0] $plugin="$type_instance" => $plugin is the same within a family
370 * [1] instance="$host" => "instance" is a static string
373 * [1] instance="$host" => "instance" is a static string
375 for (size_t i = 0; i < m_a->n_label; i++) {
376 int status = strcmp(m_a->label[i]->value, m_b->label[i]->value);
381 assert(strcmp(m_a->label[i]->name, m_b->label[i]->name) == 0);
388 #define METRIC_INIT \
389 &(Io__Prometheus__Client__Metric) { \
391 (Io__Prometheus__Client__LabelPair *[]){ \
392 &(Io__Prometheus__Client__LabelPair){ \
395 &(Io__Prometheus__Client__LabelPair){ \
398 &(Io__Prometheus__Client__LabelPair){ \
405 #define METRIC_ADD_LABELS(m, vl) \
407 if (strlen((vl)->plugin_instance) != 0) { \
408 (m)->label[(m)->n_label]->name = (char *)(vl)->plugin; \
409 (m)->label[(m)->n_label]->value = (char *)(vl)->plugin_instance; \
413 if (strlen((vl)->type_instance) != 0) { \
414 (m)->label[(m)->n_label]->name = "type"; \
415 if (strlen((vl)->plugin_instance) == 0) \
416 (m)->label[(m)->n_label]->name = (char *)(vl)->plugin; \
417 (m)->label[(m)->n_label]->value = (char *)(vl)->type_instance; \
421 (m)->label[(m)->n_label]->name = "instance"; \
422 (m)->label[(m)->n_label]->value = (char *)(vl)->host; \
426 /* metric_clone allocates and initializes a new metric based on orig. */
427 static Io__Prometheus__Client__Metric *
428 metric_clone(Io__Prometheus__Client__Metric const *orig) {
429 Io__Prometheus__Client__Metric *copy = calloc(1, sizeof(*copy));
432 io__prometheus__client__metric__init(copy);
434 copy->n_label = orig->n_label;
435 copy->label = calloc(copy->n_label, sizeof(*copy->label));
436 if (copy->label == NULL) {
441 for (size_t i = 0; i < copy->n_label; i++) {
442 copy->label[i] = label_pair_clone(orig->label[i]);
443 if (copy->label[i] == NULL) {
444 metric_destroy(copy);
452 /* metric_update stores the new value and timestamp in m. */
453 static int metric_update(Io__Prometheus__Client__Metric *m, value_t value,
454 int ds_type, cdtime_t t, cdtime_t interval) {
455 if (ds_type == DS_TYPE_GAUGE) {
457 if (m->gauge == NULL) {
458 m->gauge = calloc(1, sizeof(*m->gauge));
459 if (m->gauge == NULL)
461 io__prometheus__client__gauge__init(m->gauge);
464 m->gauge->value = (double)value.gauge;
465 m->gauge->has_value = 1;
466 } else { /* not gauge */
468 if (m->counter == NULL) {
469 m->counter = calloc(1, sizeof(*m->counter));
470 if (m->counter == NULL)
472 io__prometheus__client__counter__init(m->counter);
476 case DS_TYPE_ABSOLUTE:
477 m->counter->value = (double)value.absolute;
479 case DS_TYPE_COUNTER:
480 m->counter->value = (double)value.counter;
483 m->counter->value = (double)value.derive;
486 m->counter->has_value = 1;
489 /* Prometheus has a globally configured timeout after which metrics are
490 * considered stale. This causes problems when metrics have an interval
491 * exceeding that limit. We emulate the behavior of "pushgateway" and *not*
492 * send a timestamp value – Prometheus will fill in the current time. */
493 if (interval <= staleness_delta) {
494 m->timestamp_ms = CDTIME_T_TO_MS(t);
495 m->has_timestamp_ms = 1;
497 static c_complain_t long_metric = C_COMPLAIN_INIT_STATIC;
499 LOG_NOTICE, &long_metric,
500 "write_prometheus plugin: You have metrics with an interval exceeding "
501 "\"StalenessDelta\" setting (%.3fs). This is suboptimal, please check "
502 "the collectd.conf(5) manual page to understand what's going on.",
503 CDTIME_T_TO_DOUBLE(staleness_delta));
506 m->has_timestamp_ms = 0;
512 /* metric_family_add_metric adds m to the metric list of fam. */
513 static int metric_family_add_metric(Io__Prometheus__Client__MetricFamily *fam,
514 Io__Prometheus__Client__Metric *m) {
515 Io__Prometheus__Client__Metric **tmp =
516 realloc(fam->metric, (fam->n_metric + 1) * sizeof(*fam->metric));
521 fam->metric[fam->n_metric] = m;
524 /* Sort the metrics so that lookup is fast. */
525 qsort(fam->metric, fam->n_metric, sizeof(*fam->metric), metric_cmp);
530 /* metric_family_delete_metric looks up and deletes the metric corresponding to
533 metric_family_delete_metric(Io__Prometheus__Client__MetricFamily *fam,
534 value_list_t const *vl) {
535 Io__Prometheus__Client__Metric *key = METRIC_INIT;
536 METRIC_ADD_LABELS(key, vl);
539 for (i = 0; i < fam->n_metric; i++) {
540 if (metric_cmp(&key, &fam->metric[i]) == 0)
544 if (i >= fam->n_metric)
547 metric_destroy(fam->metric[i]);
548 if ((fam->n_metric - 1) > i)
549 memmove(&fam->metric[i], &fam->metric[i + 1],
550 ((fam->n_metric - 1) - i) * sizeof(fam->metric[i]));
553 if (fam->n_metric == 0) {
558 Io__Prometheus__Client__Metric **tmp =
559 realloc(fam->metric, fam->n_metric * sizeof(*fam->metric));
566 /* metric_family_get_metric looks up the matching metric in a metric family,
567 * allocating it if necessary. */
568 static Io__Prometheus__Client__Metric *
569 metric_family_get_metric(Io__Prometheus__Client__MetricFamily *fam,
570 value_list_t const *vl) {
571 Io__Prometheus__Client__Metric *key = METRIC_INIT;
572 METRIC_ADD_LABELS(key, vl);
574 /* Metrics are sorted in metric_family_add_metric() so that we can do a binary
576 Io__Prometheus__Client__Metric **m = bsearch(
577 &key, fam->metric, fam->n_metric, sizeof(*fam->metric), metric_cmp);
583 Io__Prometheus__Client__Metric *new_metric = metric_clone(key);
584 if (new_metric == NULL)
587 DEBUG("write_prometheus plugin: created new metric in family");
588 int status = metric_family_add_metric(fam, new_metric);
590 metric_destroy(new_metric);
597 /* metric_family_update looks up the matching metric in a metric family,
598 * allocating it if necessary, and updates the metric to the latest value. */
599 static int metric_family_update(Io__Prometheus__Client__MetricFamily *fam,
600 data_set_t const *ds, value_list_t const *vl,
602 Io__Prometheus__Client__Metric *m = metric_family_get_metric(fam, vl);
606 return metric_update(m, vl->values[ds_index], ds->ds[ds_index].type, vl->time,
610 /* metric_family_destroy frees the memory used by a metric family. */
611 static void metric_family_destroy(Io__Prometheus__Client__MetricFamily *msg) {
618 for (size_t i = 0; i < msg->n_metric; i++) {
619 metric_destroy(msg->metric[i]);
626 /* metric_family_create allocates and initializes a new metric family. */
627 static Io__Prometheus__Client__MetricFamily *
628 metric_family_create(char *name, data_set_t const *ds, value_list_t const *vl,
630 Io__Prometheus__Client__MetricFamily *msg = calloc(1, sizeof(*msg));
633 io__prometheus__client__metric_family__init(msg);
640 "write_prometheus plugin: '%s' Type: '%s', Dstype: '%s', Dsname: '%s'",
641 vl->plugin, vl->type, DS_TYPE_TO_STRING(ds->ds[ds_index].type),
642 ds->ds[ds_index].name);
643 msg->help = strdup(help);
645 msg->type = (ds->ds[ds_index].type == DS_TYPE_GAUGE)
646 ? IO__PROMETHEUS__CLIENT__METRIC_TYPE__GAUGE
647 : IO__PROMETHEUS__CLIENT__METRIC_TYPE__COUNTER;
653 /* metric_family_name creates a metric family's name from a data source. This is
654 * done in the same way as done by the "collectd_exporter" for best possible
655 * compatibility. In essence, the plugin, type and data source name go in the
656 * metric family name, while hostname, plugin instance and type instance go into
657 * the labels of a metric. */
658 static char *metric_family_name(data_set_t const *ds, value_list_t const *vl,
660 char const *fields[5] = {"collectd"};
661 size_t fields_num = 1;
663 if (strcmp(vl->plugin, vl->type) != 0) {
664 fields[fields_num] = vl->plugin;
667 fields[fields_num] = vl->type;
670 if (strcmp("value", ds->ds[ds_index].name) != 0) {
671 fields[fields_num] = ds->ds[ds_index].name;
675 /* Prometheus best practices:
676 * cumulative metrics should have a "total" suffix. */
677 if ((ds->ds[ds_index].type == DS_TYPE_COUNTER) ||
678 (ds->ds[ds_index].type == DS_TYPE_DERIVE)) {
679 fields[fields_num] = "total";
683 char name[5 * DATA_MAX_NAME_LEN];
684 strjoin(name, sizeof(name), (char **)fields, fields_num, "_");
688 /* metric_family_get looks up the matching metric family, allocating it if
690 static Io__Prometheus__Client__MetricFamily *
691 metric_family_get(data_set_t const *ds, value_list_t const *vl, size_t ds_index,
693 char *name = metric_family_name(ds, vl, ds_index);
695 ERROR("write_prometheus plugin: Allocating metric family name failed.");
699 Io__Prometheus__Client__MetricFamily *fam = NULL;
700 if (c_avl_get(metrics, name, (void *)&fam) == 0) {
711 fam = metric_family_create(name, ds, vl, ds_index);
713 ERROR("write_prometheus plugin: Allocating metric family failed.");
718 /* If successful, "name" is owned by "fam", i.e. don't free it here. */
719 DEBUG("write_prometheus plugin: metric family \"%s\" has been created.",
723 int status = c_avl_insert(metrics, fam->name, fam);
725 ERROR("write_prometheus plugin: Adding \"%s\" failed.", name);
726 metric_family_destroy(fam);
734 static void prom_logger(__attribute__((unused)) void *arg, char const *fmt,
738 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
740 ERROR("write_prometheus plugin: %s", errbuf);
741 } /* }}} prom_logger */
743 #if MHD_VERSION >= 0x00090000
744 static int prom_open_socket(int addrfamily) {
746 char service[NI_MAXSERV];
747 snprintf(service, sizeof(service), "%hu", httpd_port);
749 struct addrinfo *res;
750 int status = getaddrinfo(httpd_host, service,
752 .ai_flags = AI_PASSIVE | AI_ADDRCONFIG,
753 .ai_family = addrfamily,
754 .ai_socktype = SOCK_STREAM,
762 for (struct addrinfo *ai = res; ai != NULL; ai = ai->ai_next) {
763 fd = socket(ai->ai_family, ai->ai_socktype | SOCK_CLOEXEC, 0);
767 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) != 0) {
768 WARNING("write_prometheus plugin: setsockopt(SO_REUSEADDR) failed: %s",
775 if (bind(fd, ai->ai_addr, ai->ai_addrlen) != 0) {
781 if (listen(fd, /* backlog = */ 16) != 0) {
787 char str_node[NI_MAXHOST];
788 char str_service[NI_MAXSERV];
790 getnameinfo(ai->ai_addr, ai->ai_addrlen, str_node, sizeof(str_node),
791 str_service, sizeof(str_service),
792 NI_NUMERICHOST | NI_NUMERICSERV);
794 INFO("write_prometheus plugin: Listening on [%s]:%s.", str_node,
802 } /* }}} int prom_open_socket */
804 static struct MHD_Daemon *prom_start_daemon() {
806 int fd = prom_open_socket(PF_INET6);
808 fd = prom_open_socket(PF_INET);
810 ERROR("write_prometheus plugin: Opening a listening socket for [%s]:%hu "
812 (httpd_host != NULL) ? httpd_host : "::", httpd_port);
816 unsigned int flags = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG;
817 #if MHD_VERSION >= 0x00095300
818 flags |= MHD_USE_INTERNAL_POLLING_THREAD;
821 struct MHD_Daemon *d = MHD_start_daemon(
823 /* MHD_AcceptPolicyCallback = */ NULL,
824 /* MHD_AcceptPolicyCallback arg = */ NULL, http_handler, NULL,
825 MHD_OPTION_LISTEN_SOCKET, fd, MHD_OPTION_EXTERNAL_LOGGER, prom_logger,
826 NULL, MHD_OPTION_END);
828 ERROR("write_prometheus plugin: MHD_start_daemon() failed.");
834 } /* }}} struct MHD_Daemon *prom_start_daemon */
835 #else /* if MHD_VERSION < 0x00090000 */
836 static struct MHD_Daemon *prom_start_daemon() {
838 struct MHD_Daemon *d = MHD_start_daemon(
839 MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG, httpd_port,
840 /* MHD_AcceptPolicyCallback = */ NULL,
841 /* MHD_AcceptPolicyCallback arg = */ NULL, http_handler, NULL,
842 MHD_OPTION_EXTERNAL_LOGGER, prom_logger, NULL, MHD_OPTION_END);
844 ERROR("write_prometheus plugin: MHD_start_daemon() failed.");
849 } /* }}} struct MHD_Daemon *prom_start_daemon */
855 static int prom_config(oconfig_item_t *ci) {
856 for (int i = 0; i < ci->children_num; i++) {
857 oconfig_item_t *child = ci->children + i;
859 if (strcasecmp("Host", child->key) == 0) {
860 #if MHD_VERSION >= 0x00090000
861 cf_util_get_string(child, &httpd_host);
863 ERROR("write_prometheus plugin: Option `Host' not supported. Please "
864 "upgrade libmicrohttpd to at least 0.9.0");
867 } else if (strcasecmp("Port", child->key) == 0) {
868 int status = cf_util_get_port_number(child);
870 httpd_port = (unsigned short)status;
871 } else if (strcasecmp("StalenessDelta", child->key) == 0) {
872 cf_util_get_cdtime(child, &staleness_delta);
874 WARNING("write_prometheus plugin: Ignoring unknown configuration option "
883 static int prom_init() {
884 if (metrics == NULL) {
885 metrics = c_avl_create((void *)strcmp);
886 if (metrics == NULL) {
887 ERROR("write_prometheus plugin: c_avl_create() failed.");
893 httpd = prom_start_daemon();
897 DEBUG("write_prometheus plugin: Successfully started microhttpd %s",
904 static int prom_write(data_set_t const *ds, value_list_t const *vl,
905 __attribute__((unused)) user_data_t *ud) {
906 pthread_mutex_lock(&metrics_lock);
908 for (size_t i = 0; i < ds->ds_num; i++) {
909 Io__Prometheus__Client__MetricFamily *fam =
910 metric_family_get(ds, vl, i, /* allocate = */ true);
914 int status = metric_family_update(fam, ds, vl, i);
916 ERROR("write_prometheus plugin: Updating metric \"%s\" failed with "
923 pthread_mutex_unlock(&metrics_lock);
927 static int prom_missing(value_list_t const *vl,
928 __attribute__((unused)) user_data_t *ud) {
929 data_set_t const *ds = plugin_get_ds(vl->type);
933 pthread_mutex_lock(&metrics_lock);
935 for (size_t i = 0; i < ds->ds_num; i++) {
936 Io__Prometheus__Client__MetricFamily *fam =
937 metric_family_get(ds, vl, i, /* allocate = */ false);
941 int status = metric_family_delete_metric(fam, vl);
943 ERROR("write_prometheus plugin: Deleting a metric in family \"%s\" "
944 "failed with status %d",
950 if (fam->n_metric == 0) {
951 int status = c_avl_remove(metrics, fam->name, NULL, NULL);
953 ERROR("write_prometheus plugin: Deleting metric family \"%s\" failed "
958 metric_family_destroy(fam);
962 pthread_mutex_unlock(&metrics_lock);
966 static int prom_shutdown() {
968 MHD_stop_daemon(httpd);
972 pthread_mutex_lock(&metrics_lock);
973 if (metrics != NULL) {
975 Io__Prometheus__Client__MetricFamily *fam;
976 while (c_avl_pick(metrics, (void *)&name, (void *)&fam) == 0) {
977 assert(name == fam->name);
980 metric_family_destroy(fam);
982 c_avl_destroy(metrics);
985 pthread_mutex_unlock(&metrics_lock);
992 void module_register() {
993 plugin_register_complex_config("write_prometheus", prom_config);
994 plugin_register_init("write_prometheus", prom_init);
995 plugin_register_write("write_prometheus", prom_write,
996 /* user data = */ NULL);
997 plugin_register_missing("write_prometheus", prom_missing,
998 /* user data = */ NULL);
999 plugin_register_shutdown("write_prometheus", prom_shutdown);