write_prometheus: add support for libmicrohttpd 0.9.45+
[collectd.git] / src / write_prometheus.c
1 /**
2  * collectd - src/write_prometheus.c
3  * Copyright (C) 2016       Florian octo Forster
4  *
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:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
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
21  * SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  */
26
27 #include "collectd.h"
28
29 #include "common.h"
30 #include "plugin.h"
31 #include "utils_avltree.h"
32 #include "utils_complain.h"
33 #include "utils_time.h"
34
35 #include "prometheus.pb-c.h"
36
37 #include <microhttpd.h>
38
39 #ifndef PROMETHEUS_DEFAULT_STALENESS_DELTA
40 #define PROMETHEUS_DEFAULT_STALENESS_DELTA TIME_T_TO_CDTIME_T(300)
41 #endif
42
43 #define VARINT_UINT32_BYTES 5
44
45 #define CONTENT_TYPE_PROTO                                                     \
46   "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; " \
47   "encoding=delimited"
48 #define CONTENT_TYPE_TEXT "text/plain; version=0.0.4"
49
50 static c_avl_tree_t *metrics;
51 static pthread_mutex_t metrics_lock = PTHREAD_MUTEX_INITIALIZER;
52
53 static unsigned short httpd_port = 9103;
54 static struct MHD_Daemon *httpd;
55
56 static cdtime_t staleness_delta = PROMETHEUS_DEFAULT_STALENESS_DELTA;
57
58 /* Unfortunately, protoc-c doesn't export it's implementation of varint, so we
59  * need to implement our own. */
60 static size_t varint(uint8_t buffer[static VARINT_UINT32_BYTES],
61                      uint32_t value) {
62   for (size_t i = 0; i < VARINT_UINT32_BYTES; i++) {
63     buffer[i] = (uint8_t)(value & 0x7f);
64     value >>= 7;
65
66     if (value == 0)
67       return i + 1;
68
69     buffer[i] |= 0x80;
70   }
71
72   return 0;
73 }
74
75 /* format_protobuf iterates over all metric families in "metrics" and adds them
76  * to a buffer in ProtoBuf format. It prefixes each protobuf with its encoded
77  * size, the so called "delimited" format. */
78 static void format_protobuf(ProtobufCBuffer *buffer) {
79   pthread_mutex_lock(&metrics_lock);
80
81   char *unused_name;
82   Io__Prometheus__Client__MetricFamily *fam;
83   c_avl_iterator_t *iter = c_avl_get_iterator(metrics);
84   while (c_avl_iterator_next(iter, (void *)&unused_name, (void *)&fam) == 0) {
85     /* Prometheus uses a message length prefix to determine where one
86      * MetricFamily ends and the next begins. This delimiter is encoded as a
87      * "varint", which is common in Protobufs. */
88     uint8_t delim[VARINT_UINT32_BYTES] = {0};
89     size_t delim_len = varint(
90         delim,
91         (uint32_t)io__prometheus__client__metric_family__get_packed_size(fam));
92     buffer->append(buffer, delim_len, delim);
93
94     io__prometheus__client__metric_family__pack_to_buffer(fam, buffer);
95   }
96   c_avl_iterator_destroy(iter);
97
98   pthread_mutex_unlock(&metrics_lock);
99 }
100
101 /* format_labels formats a metric's labels in Prometheus-compatible format. This
102  * format looks like this:
103  *
104  *   key0="value0",key1="value1"
105  */
106 static char *format_labels(char *buffer, size_t buffer_size,
107                            Io__Prometheus__Client__Metric const *m) {
108   /* our metrics always have at least one and at most three labels. */
109   assert(m->n_label >= 1);
110   assert(m->n_label <= 3);
111
112 #define LABEL_BUFFER_SIZE (2 * DATA_MAX_NAME_LEN + 4)
113
114   char *labels[3] = {
115       (char[LABEL_BUFFER_SIZE]){0}, (char[LABEL_BUFFER_SIZE]){0},
116       (char[LABEL_BUFFER_SIZE]){0},
117   };
118
119   for (size_t i = 0; i < m->n_label; i++)
120     ssnprintf(labels[i], LABEL_BUFFER_SIZE, "%s=\"%s\"", m->label[i]->name,
121               m->label[i]->value);
122
123   strjoin(buffer, buffer_size, labels, m->n_label, ",");
124   return buffer;
125 }
126
127 /* format_protobuf iterates over all metric families in "metrics" and adds them
128  * to a buffer in plain text format. */
129 static void format_text(ProtobufCBuffer *buffer) {
130   pthread_mutex_lock(&metrics_lock);
131
132   char *unused_name;
133   Io__Prometheus__Client__MetricFamily *fam;
134   c_avl_iterator_t *iter = c_avl_get_iterator(metrics);
135   while (c_avl_iterator_next(iter, (void *)&unused_name, (void *)&fam) == 0) {
136     char line[1024]; /* 4x DATA_MAX_NAME_LEN? */
137
138     ssnprintf(line, sizeof(line), "# HELP %s %s\n", fam->name, fam->help);
139     buffer->append(buffer, strlen(line), (uint8_t *)line);
140
141     ssnprintf(line, sizeof(line), "# TYPE %s %s\n", fam->name,
142               (fam->type == IO__PROMETHEUS__CLIENT__METRIC_TYPE__GAUGE)
143                   ? "gauge"
144                   : "counter");
145     buffer->append(buffer, strlen(line), (uint8_t *)line);
146
147     for (size_t i = 0; i < fam->n_metric; i++) {
148       Io__Prometheus__Client__Metric *m = fam->metric[i];
149
150       char labels[1024];
151
152       char timestamp_ms[24] = "";
153       if (m->has_timestamp_ms)
154         ssnprintf(timestamp_ms, sizeof(timestamp_ms), " %" PRIi64,
155                   m->timestamp_ms);
156
157       if (fam->type == IO__PROMETHEUS__CLIENT__METRIC_TYPE__GAUGE)
158         ssnprintf(line, sizeof(line), "%s{%s} " GAUGE_FORMAT "%s\n", fam->name,
159                   format_labels(labels, sizeof(labels), m), m->gauge->value,
160                   timestamp_ms);
161       else /* if (fam->type == IO__PROMETHEUS__CLIENT__METRIC_TYPE__COUNTER) */
162         ssnprintf(line, sizeof(line), "%s{%s} %.0f%s\n", fam->name,
163                   format_labels(labels, sizeof(labels), m), m->counter->value,
164                   timestamp_ms);
165
166       buffer->append(buffer, strlen(line), (uint8_t *)line);
167     }
168   }
169   c_avl_iterator_destroy(iter);
170
171   char server[1024];
172   ssnprintf(server, sizeof(server), "\n# collectd/write_prometheus %s at %s\n",
173             PACKAGE_VERSION, hostname_g);
174   buffer->append(buffer, strlen(server), (uint8_t *)server);
175
176   pthread_mutex_unlock(&metrics_lock);
177 }
178
179 /* http_handler is the callback called by the microhttpd library. It essentially
180  * handles all HTTP request aspects and creates an HTTP response. */
181 static int http_handler(void *cls, struct MHD_Connection *connection,
182                         const char *url, const char *method,
183                         const char *version, const char *upload_data,
184                         size_t *upload_data_size, void **connection_state) {
185   if (strcmp(method, MHD_HTTP_METHOD_GET) != 0) {
186     return MHD_NO;
187   }
188
189   /* On the first call for each connection, return without anything further.
190    * Apparently not everything has been initialized yet or so; the docs are not
191    * very specific on the issue. */
192   if (*connection_state == NULL) {
193     /* set to a random non-NULL pointer. */
194     *connection_state = &(int){42};
195     return MHD_YES;
196   }
197
198   char const *accept = MHD_lookup_connection_value(connection, MHD_HEADER_KIND,
199                                                    MHD_HTTP_HEADER_ACCEPT);
200   _Bool want_proto =
201       (accept != NULL) &&
202       (strstr(accept, "application/vnd.google.protobuf") != NULL);
203
204   uint8_t scratch[4096] = {0};
205   ProtobufCBufferSimple simple = PROTOBUF_C_BUFFER_SIMPLE_INIT(scratch);
206   ProtobufCBuffer *buffer = (ProtobufCBuffer *)&simple;
207
208   if (want_proto)
209     format_protobuf(buffer);
210   else
211     format_text(buffer);
212
213   struct MHD_Response *res =
214 #if defined(MHD_VERSION) && MHD_VERSION >= 0x00090500
215     MHD_create_response_from_buffer(
216       simple.len, simple.data, MHD_RESPMEM_MUST_COPY);
217 #else
218     MHD_create_response_from_data(
219       simple.len, simple.data, /* must_free = */ 0, /* must_copy = */ 1);
220 #endif
221   MHD_add_response_header(res, MHD_HTTP_HEADER_CONTENT_TYPE,
222                           want_proto ? CONTENT_TYPE_PROTO : CONTENT_TYPE_TEXT);
223
224   int status = MHD_queue_response(connection, MHD_HTTP_OK, res);
225
226   MHD_destroy_response(res);
227   PROTOBUF_C_BUFFER_SIMPLE_CLEAR(&simple);
228   return status;
229 }
230
231 /*
232  * Functions for manipulating the global state in "metrics". This is organized
233  * in two tiers: the global "metrics" tree holds "metric families", which are
234  * identified by a name (a string). Each metric family has one or more
235  * "metrics", which are identified by a unique set of key-value-pairs. For
236  * example:
237  *
238  * collectd_cpu_total
239  *   {cpu="0",type="idle"}
240  *   {cpu="0",type="user"}
241  *   ...
242  * collectd_memory
243  *   {memory="used"}
244  *   {memory="free"}
245  *   ...
246  * {{{ */
247 /* label_pair_destroy frees the memory used by a label pair. */
248 static void label_pair_destroy(Io__Prometheus__Client__LabelPair *msg) {
249   if (msg == NULL)
250     return;
251
252   sfree(msg->name);
253   sfree(msg->value);
254
255   sfree(msg);
256 }
257
258 /* label_pair_clone allocates and initializes a new label pair. */
259 static Io__Prometheus__Client__LabelPair *
260 label_pair_clone(Io__Prometheus__Client__LabelPair const *orig) {
261   Io__Prometheus__Client__LabelPair *copy = calloc(1, sizeof(*copy));
262   if (copy == NULL)
263     return NULL;
264   io__prometheus__client__label_pair__init(copy);
265
266   copy->name = strdup(orig->name);
267   copy->value = strdup(orig->value);
268   if ((copy->name == NULL) || (copy->value == NULL)) {
269     label_pair_destroy(copy);
270     return NULL;
271   }
272
273   return copy;
274 }
275
276 /* metric_destroy frees the memory used by a metric. */
277 static void metric_destroy(Io__Prometheus__Client__Metric *msg) {
278   if (msg == NULL)
279     return;
280
281   for (size_t i = 0; i < msg->n_label; i++) {
282     label_pair_destroy(msg->label[i]);
283   }
284   sfree(msg->label);
285
286   sfree(msg->gauge);
287   sfree(msg->counter);
288
289   sfree(msg);
290 }
291
292 /* metric_cmp compares two metrics. It's prototype makes it easy to use with
293  * qsort(3) and bsearch(3). */
294 static int metric_cmp(void const *a, void const *b) {
295   Io__Prometheus__Client__Metric const *m_a =
296       *((Io__Prometheus__Client__Metric **)a);
297   Io__Prometheus__Client__Metric const *m_b =
298       *((Io__Prometheus__Client__Metric **)b);
299
300   if (m_a->n_label < m_b->n_label)
301     return -1;
302   else if (m_a->n_label > m_b->n_label)
303     return 1;
304
305   /* Prometheus does not care about the order of labels. All labels in this
306    * plugin are created by METRIC_ADD_LABELS(), though, and therefore always
307    * appear in the same order. We take advantage of this and simplify the check
308    * by making sure all labels are the same in each position.
309    *
310    * We also only need to check the label values, because the label names are
311    * the same for all metrics in a metric family.
312    *
313    * 3 labels:
314    * [0] $plugin="$plugin_instance" => $plugin is the same within a family
315    * [1] type="$type_instance"      => "type" is a static string
316    * [2] instance="$host"           => "instance" is a static string
317    *
318    * 2 labels, variant 1:
319    * [0] $plugin="$plugin_instance" => $plugin is the same within a family
320    * [1] instance="$host"           => "instance" is a static string
321    *
322    * 2 labels, variant 2:
323    * [0] $plugin="$type_instance"   => $plugin is the same within a family
324    * [1] instance="$host"           => "instance" is a static string
325    *
326    * 1 label:
327    * [1] instance="$host"           => "instance" is a static string
328    */
329   for (size_t i = 0; i < m_a->n_label; i++) {
330     int status = strcmp(m_a->label[i]->value, m_b->label[i]->value);
331     if (status != 0)
332       return status;
333
334 #if COLLECT_DEBUG
335     assert(strcmp(m_a->label[i]->name, m_b->label[i]->name) == 0);
336 #endif
337   }
338
339   return 0;
340 }
341
342 #define METRIC_INIT                                                            \
343   &(Io__Prometheus__Client__Metric) {                                          \
344     .label =                                                                   \
345         (Io__Prometheus__Client__LabelPair *[]){                               \
346             &(Io__Prometheus__Client__LabelPair){                              \
347                 .name = NULL,                                                  \
348             },                                                                 \
349             &(Io__Prometheus__Client__LabelPair){                              \
350                 .name = NULL,                                                  \
351             },                                                                 \
352             &(Io__Prometheus__Client__LabelPair){                              \
353                 .name = NULL,                                                  \
354             },                                                                 \
355         },                                                                     \
356     .n_label = 0,                                                              \
357   }
358
359 #define METRIC_ADD_LABELS(m, vl)                                               \
360   do {                                                                         \
361     if (strlen((vl)->plugin_instance) != 0) {                                  \
362       (m)->label[(m)->n_label]->name = (char *)(vl)->plugin;                   \
363       (m)->label[(m)->n_label]->value = (char *)(vl)->plugin_instance;         \
364       (m)->n_label++;                                                          \
365     }                                                                          \
366                                                                                \
367     if (strlen((vl)->type_instance) != 0) {                                    \
368       (m)->label[(m)->n_label]->name = "type";                                 \
369       if (strlen((vl)->plugin_instance) == 0)                                  \
370         (m)->label[(m)->n_label]->name = (char *)(vl)->plugin;                 \
371       (m)->label[(m)->n_label]->value = (char *)(vl)->type_instance;           \
372       (m)->n_label++;                                                          \
373     }                                                                          \
374                                                                                \
375     (m)->label[(m)->n_label]->name = "instance";                               \
376     (m)->label[(m)->n_label]->value = (char *)(vl)->host;                      \
377     (m)->n_label++;                                                            \
378   } while (0)
379
380 /* metric_clone allocates and initializes a new metric based on orig. */
381 static Io__Prometheus__Client__Metric *
382 metric_clone(Io__Prometheus__Client__Metric const *orig) {
383   Io__Prometheus__Client__Metric *copy = calloc(1, sizeof(*copy));
384   if (copy == NULL)
385     return NULL;
386   io__prometheus__client__metric__init(copy);
387
388   copy->n_label = orig->n_label;
389   copy->label = calloc(copy->n_label, sizeof(*copy->label));
390   if (copy->label == NULL) {
391     sfree(copy);
392     return NULL;
393   }
394
395   for (size_t i = 0; i < copy->n_label; i++) {
396     copy->label[i] = label_pair_clone(orig->label[i]);
397     if (copy->label[i] == NULL) {
398       metric_destroy(copy);
399       return NULL;
400     }
401   }
402
403   return copy;
404 }
405
406 /* metric_update stores the new value and timestamp in m. */
407 static int metric_update(Io__Prometheus__Client__Metric *m, value_t value,
408                          int ds_type, cdtime_t t, cdtime_t interval) {
409   if (ds_type == DS_TYPE_GAUGE) {
410     sfree(m->counter);
411     if (m->gauge == NULL) {
412       m->gauge = calloc(1, sizeof(*m->gauge));
413       if (m->gauge == NULL)
414         return ENOMEM;
415       io__prometheus__client__gauge__init(m->gauge);
416     }
417
418     m->gauge->value = (double)value.gauge;
419     m->gauge->has_value = 1;
420   } else { /* not gauge */
421     sfree(m->gauge);
422     if (m->counter == NULL) {
423       m->counter = calloc(1, sizeof(*m->counter));
424       if (m->counter == NULL)
425         return ENOMEM;
426       io__prometheus__client__counter__init(m->counter);
427     }
428
429     switch (ds_type) {
430     case DS_TYPE_ABSOLUTE:
431       m->counter->value = (double)value.absolute;
432       break;
433     case DS_TYPE_COUNTER:
434       m->counter->value = (double)value.counter;
435       break;
436     default:
437       m->counter->value = (double)value.derive;
438       break;
439     }
440     m->counter->has_value = 1;
441   }
442
443   /* Prometheus has a globally configured timeout after which metrics are
444    * considered stale. This causes problems when metrics have an interval
445    * exceeding that limit. We emulate the behavior of "pushgateway" and *not*
446    * send a timestamp value â€“ Prometheus will fill in the current time. */
447   if (interval <= staleness_delta) {
448     m->timestamp_ms = CDTIME_T_TO_MS(t);
449     m->has_timestamp_ms = 1;
450   } else {
451     static c_complain_t long_metric = C_COMPLAIN_INIT_STATIC;
452     c_complain(
453         LOG_NOTICE, &long_metric,
454         "write_prometheus plugin: You have metrics with an interval exceeding "
455         "\"StalenessDelta\" setting (%.3fs). This is suboptimal, please check "
456         "the collectd.conf(5) manual page to understand what's going on.",
457         CDTIME_T_TO_DOUBLE(staleness_delta));
458
459     m->timestamp_ms = 0;
460     m->has_timestamp_ms = 0;
461   }
462
463   return 0;
464 }
465
466 /* metric_family_add_metric adds m to the metric list of fam. */
467 static int metric_family_add_metric(Io__Prometheus__Client__MetricFamily *fam,
468                                     Io__Prometheus__Client__Metric *m) {
469   Io__Prometheus__Client__Metric **tmp =
470       realloc(fam->metric, (fam->n_metric + 1) * sizeof(*fam->metric));
471   if (tmp == NULL)
472     return ENOMEM;
473   fam->metric = tmp;
474
475   fam->metric[fam->n_metric] = m;
476   fam->n_metric++;
477
478   /* Sort the metrics so that lookup is fast. */
479   qsort(fam->metric, fam->n_metric, sizeof(*fam->metric), metric_cmp);
480
481   return 0;
482 }
483
484 /* metric_family_delete_metric looks up and deletes the metric corresponding to
485  * vl. */
486 static int
487 metric_family_delete_metric(Io__Prometheus__Client__MetricFamily *fam,
488                             value_list_t const *vl) {
489   Io__Prometheus__Client__Metric *key = METRIC_INIT;
490   METRIC_ADD_LABELS(key, vl);
491
492   size_t i;
493   for (i = 0; i < fam->n_metric; i++) {
494     if (metric_cmp(&key, &fam->metric[i]) == 0)
495       break;
496   }
497
498   if (i >= fam->n_metric)
499     return ENOENT;
500
501   metric_destroy(fam->metric[i]);
502   if ((fam->n_metric - 1) > i)
503     memmove(&fam->metric[i], &fam->metric[i + 1],
504             ((fam->n_metric - 1) - i) * sizeof(fam->metric[i]));
505   fam->n_metric--;
506
507   Io__Prometheus__Client__Metric **tmp =
508       realloc(fam->metric, fam->n_metric * sizeof(*fam->metric));
509   if ((tmp != NULL) || (fam->n_metric == 0))
510     fam->metric = tmp;
511
512   return 0;
513 }
514
515 /* metric_family_get_metric looks up the matching metric in a metric family,
516  * allocating it if necessary. */
517 static Io__Prometheus__Client__Metric *
518 metric_family_get_metric(Io__Prometheus__Client__MetricFamily *fam,
519                          value_list_t const *vl) {
520   Io__Prometheus__Client__Metric *key = METRIC_INIT;
521   METRIC_ADD_LABELS(key, vl);
522
523   /* Metrics are sorted in metric_family_add_metric() so that we can do a binary
524    * search here. */
525   Io__Prometheus__Client__Metric **m = bsearch(
526       &key, fam->metric, fam->n_metric, sizeof(*fam->metric), metric_cmp);
527
528   if (m != NULL) {
529     return *m;
530   }
531
532   Io__Prometheus__Client__Metric *new_metric = metric_clone(key);
533   if (new_metric == NULL)
534     return NULL;
535
536   DEBUG("write_prometheus plugin: created new metric in family");
537   int status = metric_family_add_metric(fam, new_metric);
538   if (status != 0) {
539     metric_destroy(new_metric);
540     return NULL;
541   }
542
543   return new_metric;
544 }
545
546 /* metric_family_update looks up the matching metric in a metric family,
547  * allocating it if necessary, and updates the metric to the latest value. */
548 static int metric_family_update(Io__Prometheus__Client__MetricFamily *fam,
549                                 data_set_t const *ds, value_list_t const *vl,
550                                 size_t ds_index) {
551   Io__Prometheus__Client__Metric *m = metric_family_get_metric(fam, vl);
552   if (m == NULL)
553     return -1;
554
555   return metric_update(m, vl->values[ds_index], ds->ds[ds_index].type, vl->time,
556                        vl->interval);
557 }
558
559 /* metric_family_destroy frees the memory used by a metric family. */
560 static void metric_family_destroy(Io__Prometheus__Client__MetricFamily *msg) {
561   if (msg == NULL)
562     return;
563
564   sfree(msg->name);
565   sfree(msg->help);
566
567   for (size_t i = 0; i < msg->n_metric; i++) {
568     metric_destroy(msg->metric[i]);
569   }
570   sfree(msg->metric);
571
572   sfree(msg);
573 }
574
575 /* metric_family_create allocates and initializes a new metric family. */
576 static Io__Prometheus__Client__MetricFamily *
577 metric_family_create(char *name, data_set_t const *ds, value_list_t const *vl,
578                      size_t ds_index) {
579   Io__Prometheus__Client__MetricFamily *msg = calloc(1, sizeof(*msg));
580   if (msg == NULL)
581     return NULL;
582   io__prometheus__client__metric_family__init(msg);
583
584   msg->name = name;
585
586   char help[1024];
587   ssnprintf(
588       help, sizeof(help),
589       "write_prometheus plugin: '%s' Type: '%s', Dstype: '%s', Dsname: '%s'",
590       vl->plugin, vl->type, DS_TYPE_TO_STRING(ds->ds[ds_index].type),
591       ds->ds[ds_index].name);
592   msg->help = strdup(help);
593
594   msg->type = (ds->ds[ds_index].type == DS_TYPE_GAUGE)
595                   ? IO__PROMETHEUS__CLIENT__METRIC_TYPE__GAUGE
596                   : IO__PROMETHEUS__CLIENT__METRIC_TYPE__COUNTER;
597   msg->has_type = 1;
598
599   return msg;
600 }
601
602 /* metric_family_name creates a metric family's name from a data source. This is
603  * done in the same way as done by the "collectd_exporter" for best possible
604  * compatibility. In essence, the plugin, type and data source name go in the
605  * metric family name, while hostname, plugin instance and type instance go into
606  * the labels of a metric. */
607 static char *metric_family_name(data_set_t const *ds, value_list_t const *vl,
608                                 size_t ds_index) {
609   char const *fields[5] = {"collectd"};
610   size_t fields_num = 1;
611
612   if (strcmp(vl->plugin, vl->type) != 0) {
613     fields[fields_num] = vl->plugin;
614     fields_num++;
615   }
616   fields[fields_num] = vl->type;
617   fields_num++;
618
619   if (strcmp("value", ds->ds[ds_index].name) != 0) {
620     fields[fields_num] = ds->ds[ds_index].name;
621     fields_num++;
622   }
623
624   /* Prometheus best practices:
625    * cumulative metrics should have a "total" suffix. */
626   if ((ds->ds[ds_index].type == DS_TYPE_COUNTER) ||
627       (ds->ds[ds_index].type == DS_TYPE_DERIVE)) {
628     fields[fields_num] = "total";
629     fields_num++;
630   }
631
632   char name[5 * DATA_MAX_NAME_LEN];
633   strjoin(name, sizeof(name), (char **)fields, fields_num, "_");
634   return strdup(name);
635 }
636
637 /* metric_family_get looks up the matching metric family, allocating it if
638  * necessary. */
639 static Io__Prometheus__Client__MetricFamily *
640 metric_family_get(data_set_t const *ds, value_list_t const *vl,
641                   size_t ds_index) {
642   char *name = metric_family_name(ds, vl, ds_index);
643   if (name == NULL) {
644     ERROR("write_prometheus plugin: Allocating metric family name failed.");
645     return NULL;
646   }
647
648   Io__Prometheus__Client__MetricFamily *fam = NULL;
649   if (c_avl_get(metrics, name, (void *)&fam) == 0) {
650     sfree(name);
651     assert(fam != NULL);
652     return fam;
653   }
654
655   fam = metric_family_create(name, ds, vl, ds_index);
656   if (fam == NULL) {
657     ERROR("write_prometheus plugin: Allocating metric family failed.");
658     sfree(name);
659     return NULL;
660   }
661
662   /* If successful, "name" is owned by "fam", i.e. don't free it here. */
663   DEBUG("write_prometheus plugin: metric family \"%s\" has been created.",
664         name);
665   name = NULL;
666
667   int status = c_avl_insert(metrics, fam->name, fam);
668   if (status != 0) {
669     ERROR("write_prometheus plugin: Adding \"%s\" failed.", name);
670     metric_family_destroy(fam);
671     return NULL;
672   }
673
674   return fam;
675 }
676 /* }}} */
677
678 /*
679  * collectd callbacks
680  */
681 static int prom_config(oconfig_item_t *ci) {
682   for (int i = 0; i < ci->children_num; i++) {
683     oconfig_item_t *child = ci->children + i;
684
685     if (strcasecmp("Port", child->key) == 0) {
686       int status = cf_util_get_port_number(child);
687       if (status > 0)
688         httpd_port = (unsigned short)status;
689     } else if (strcasecmp("StalenessDelta", child->key) == 0) {
690       cf_util_get_cdtime(child, &staleness_delta);
691     } else {
692       WARNING("write_prometheus plugin: Ignoring unknown configuration option "
693               "\"%s\".",
694               child->key);
695     }
696   }
697
698   return 0;
699 }
700
701 static int prom_init() {
702   if (metrics == NULL) {
703     metrics = c_avl_create((void *)strcmp);
704     if (metrics == NULL) {
705       ERROR("write_prometheus plugin: c_avl_create() failed.");
706       return -1;
707     }
708   }
709
710   if (httpd == NULL) {
711     unsigned int flags = MHD_USE_THREAD_PER_CONNECTION;
712 #if MHD_VERSION >= 0x00093300
713     flags |= MHD_USE_DUAL_STACK;
714 #endif
715
716     httpd = MHD_start_daemon(flags, httpd_port,
717                              /* MHD_AcceptPolicyCallback = */ NULL,
718                              /* MHD_AcceptPolicyCallback arg = */ NULL,
719                              http_handler, NULL, MHD_OPTION_END);
720     if (httpd == NULL) {
721       ERROR("write_prometheus plugin: MHD_start_daemon() failed.");
722       return -1;
723     }
724     DEBUG("write_prometheus plugin: Successfully started microhttpd %s",
725           MHD_get_version());
726   }
727
728   return 0;
729 }
730
731 static int prom_write(data_set_t const *ds, value_list_t const *vl,
732                       __attribute__((unused)) user_data_t *ud) {
733   pthread_mutex_lock(&metrics_lock);
734
735   for (size_t i = 0; i < ds->ds_num; i++) {
736     Io__Prometheus__Client__MetricFamily *fam = metric_family_get(ds, vl, i);
737     if (fam == NULL)
738       continue;
739
740     int status = metric_family_update(fam, ds, vl, i);
741     if (status != 0) {
742       ERROR("write_prometheus plugin: Updating metric \"%s\" failed with "
743             "status %d",
744             fam->name, status);
745       continue;
746     }
747   }
748
749   pthread_mutex_unlock(&metrics_lock);
750   return 0;
751 }
752
753 static int prom_missing(value_list_t const *vl,
754                         __attribute__((unused)) user_data_t *ud) {
755   data_set_t const *ds = plugin_get_ds(vl->type);
756   if (ds == NULL)
757     return ENOENT;
758
759   pthread_mutex_lock(&metrics_lock);
760
761   for (size_t i = 0; i < ds->ds_num; i++) {
762     Io__Prometheus__Client__MetricFamily *fam = metric_family_get(ds, vl, i);
763     if (fam == NULL)
764       continue;
765
766     int status = metric_family_delete_metric(fam, vl);
767     if (status != 0) {
768       ERROR("write_prometheus plugin: Deleting a metric in family \"%s\" "
769             "failed with status %d",
770             fam->name, status);
771       continue;
772     }
773
774     if (fam->n_metric == 0) {
775       int status = c_avl_remove(metrics, fam->name, NULL, NULL);
776       if (status != 0) {
777         ERROR("write_prometheus plugin: Deleting metric family \"%s\" failed "
778               "with status %d",
779               fam->name, status);
780         continue;
781       }
782       metric_family_destroy(fam);
783     }
784   }
785
786   pthread_mutex_unlock(&metrics_lock);
787   return 0;
788 }
789
790 static int prom_shutdown() {
791   if (httpd != NULL) {
792     MHD_stop_daemon(httpd);
793     httpd = NULL;
794   }
795
796   pthread_mutex_lock(&metrics_lock);
797   if (metrics != NULL) {
798     char *name;
799     Io__Prometheus__Client__MetricFamily *fam;
800     while (c_avl_pick(metrics, (void *)&name, (void *)&fam) == 0) {
801       assert(name == fam->name);
802       name = NULL;
803
804       metric_family_destroy(fam);
805     }
806     c_avl_destroy(metrics);
807     metrics = NULL;
808   }
809   pthread_mutex_unlock(&metrics_lock);
810
811   return 0;
812 }
813
814 void module_register() {
815   plugin_register_complex_config("write_prometheus", prom_config);
816   plugin_register_init("write_prometheus", prom_init);
817   plugin_register_write("write_prometheus", prom_write,
818                         /* user data = */ NULL);
819   plugin_register_missing("write_prometheus", prom_missing,
820                           /* user data = */ NULL);
821   plugin_register_shutdown("write_prometheus", prom_shutdown);
822 }
823
824 /* vim: set sw=2 sts=2 et fdm=marker : */