2 * collectd - src/write_riemann.c
3 * Copyright (C) 2012,2013 Pierre-Yves Ritschard
4 * Copyright (C) 2013 Florian octo Forster
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
25 * Pierre-Yves Ritschard <pyr at spootnik.org>
26 * Florian octo Forster <octo at collectd.org>
32 #include "configfile.h"
33 #include "utils_cache.h"
34 #include "riemann.pb-c.h"
36 #include <sys/socket.h>
37 #include <arpa/inet.h>
43 #define RIEMANN_HOST "localhost"
44 #define RIEMANN_PORT "5555"
45 #define RIEMANN_TTL_FACTOR 2.0
47 int write_riemann_threshold_check(const data_set_t *, const value_list_t *, int *);
52 #define F_CONNECT 0x01
56 _Bool check_thresholds;
58 _Bool always_append_ds;
68 static char **riemann_tags;
69 static size_t riemann_tags_num;
70 static char **riemann_attrs;
71 static size_t riemann_attrs_num;
73 static void riemann_event_protobuf_free (Event *event) /* {{{ */
81 sfree (event->service);
83 sfree (event->description);
85 strarray_free (event->tags, event->n_tags);
89 for (i = 0; i < event->n_attributes; i++)
91 sfree (event->attributes[i]->key);
92 sfree (event->attributes[i]->value);
93 sfree (event->attributes[i]);
95 sfree (event->attributes);
96 event->n_attributes = 0;
99 } /* }}} void riemann_event_protobuf_free */
101 static void riemann_msg_protobuf_free (Msg *msg) /* {{{ */
108 for (i = 0; i < msg->n_events; i++)
110 riemann_event_protobuf_free (msg->events[i]);
111 msg->events[i] = NULL;
118 } /* }}} void riemann_msg_protobuf_free */
120 /* host->lock must be held when calling this function. */
121 static int riemann_connect(struct riemann_host *host) /* {{{ */
124 struct addrinfo *ai, *res, hints;
128 if (host->flags & F_CONNECT)
131 memset(&hints, 0, sizeof(hints));
132 memset(&service, 0, sizeof(service));
133 hints.ai_family = AF_UNSPEC;
134 hints.ai_socktype = host->use_tcp ? SOCK_STREAM : SOCK_DGRAM;
136 hints.ai_flags |= AI_ADDRCONFIG;
139 node = (host->node != NULL) ? host->node : RIEMANN_HOST;
140 service = (host->service != NULL) ? host->service : RIEMANN_PORT;
142 if ((e = getaddrinfo(node, service, &hints, &res)) != 0) {
143 ERROR ("write_riemann plugin: Unable to resolve host \"%s\": %s",
144 node, gai_strerror(e));
149 for (ai = res; ai != NULL; ai = ai->ai_next) {
150 if ((host->s = socket(ai->ai_family,
152 ai->ai_protocol)) == -1) {
156 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
162 host->flags |= F_CONNECT;
163 DEBUG("write_riemann plugin: got a successful connection for: %s:%s",
171 WARNING("write_riemann plugin: Unable to connect to Riemann at %s:%s",
176 } /* }}} int riemann_connect */
178 /* host->lock must be held when calling this function. */
179 static int riemann_disconnect (struct riemann_host *host) /* {{{ */
181 if ((host->flags & F_CONNECT) == 0)
186 host->flags &= ~F_CONNECT;
189 } /* }}} int riemann_disconnect */
191 static int riemann_send_msg (struct riemann_host *host, const Msg *msg) /* {{{ */
194 u_char *buffer = NULL;
197 status = riemann_connect (host);
201 buffer_len = msg__get_packed_size(msg);
206 buffer = malloc (buffer_len);
207 if (buffer == NULL) {
208 ERROR ("write_riemann plugin: malloc failed.");
211 memset (buffer, 0, buffer_len);
215 uint32_t length = htonl ((uint32_t) (buffer_len - 4));
216 memcpy (buffer, &length, 4);
217 msg__pack(msg, buffer + 4);
221 msg__pack(msg, buffer);
224 status = (int) swrite (host->s, buffer, buffer_len);
228 ERROR ("write_riemann plugin: Sending to Riemann at %s:%s failed: %s",
229 (host->node != NULL) ? host->node : RIEMANN_HOST,
230 (host->service != NULL) ? host->service : RIEMANN_PORT,
231 sstrerror (errno, errbuf, sizeof (errbuf)));
238 } /* }}} int riemann_send_msg */
240 static int riemann_recv_ack(struct riemann_host *host) /* {{{ */
246 status = (int) sread (host->s, &header, 4);
251 size_t size = ntohl(header);
253 // Buffer on the stack since acknowledges are typically small.
255 memset (buffer, 0, size);
257 status = (int) sread (host->s, buffer, size);
262 msg = msg__unpack (NULL, size, buffer);
269 ERROR ("write_riemann plugin: Sending to Riemann at %s:%s acknowledgement message reported error: %s",
270 (host->node != NULL) ? host->node : RIEMANN_HOST,
271 (host->service != NULL) ? host->service : RIEMANN_PORT,
274 msg__free_unpacked(msg, NULL);
278 msg__free_unpacked (msg, NULL);
280 } /* }}} int riemann_recv_ack */
283 * Function to send messages (Msg) to riemann.
285 * Acquires the host lock, disconnects on errors.
287 static int riemann_send(struct riemann_host *host, Msg const *msg) /* {{{ */
290 pthread_mutex_lock (&host->lock);
292 status = riemann_send_msg(host, msg);
294 riemann_disconnect (host);
295 pthread_mutex_unlock (&host->lock);
300 * For TCP we need to receive message acknowledgemenent.
304 status = riemann_recv_ack(host);
308 riemann_disconnect (host);
309 pthread_mutex_unlock (&host->lock);
314 pthread_mutex_unlock (&host->lock);
316 } /* }}} int riemann_send */
318 static int riemann_event_add_tag (Event *event, char const *tag) /* {{{ */
320 return (strarray_add (&event->tags, &event->n_tags, tag));
321 } /* }}} int riemann_event_add_tag */
323 static int riemann_event_add_attribute (Event *event, /* {{{ */
324 char const *key, char const *value)
326 Attribute **new_attributes;
329 new_attributes = realloc (event->attributes,
330 sizeof (*event->attributes) * (event->n_attributes + 1));
331 if (new_attributes == NULL)
333 ERROR ("write_riemann plugin: realloc failed.");
336 event->attributes = new_attributes;
338 a = malloc (sizeof (*a));
341 ERROR ("write_riemann plugin: malloc failed.");
346 a->key = strdup (key);
348 a->value = strdup (value);
350 event->attributes[event->n_attributes] = a;
351 event->n_attributes++;
354 } /* }}} int riemann_event_add_attribute */
356 static Msg *riemann_notification_to_protobuf (struct riemann_host *host, /* {{{ */
357 notification_t const *n)
361 char service_buffer[6 * DATA_MAX_NAME_LEN];
362 char const *severity;
363 notification_meta_t *meta;
366 msg = malloc (sizeof (*msg));
369 ERROR ("write_riemann plugin: malloc failed.");
372 memset (msg, 0, sizeof (*msg));
375 msg->events = malloc (sizeof (*msg->events));
376 if (msg->events == NULL)
378 ERROR ("write_riemann plugin: malloc failed.");
383 event = malloc (sizeof (*event));
386 ERROR ("write_riemann plugin: malloc failed.");
391 memset (event, 0, sizeof (*event));
394 msg->events[0] = event;
397 event->host = strdup (n->host);
398 event->time = CDTIME_T_TO_TIME_T (n->time);
403 case NOTIF_OKAY: severity = "ok"; break;
404 case NOTIF_WARNING: severity = "warning"; break;
405 case NOTIF_FAILURE: severity = "critical"; break;
406 default: severity = "unknown";
408 event->state = strdup (severity);
410 riemann_event_add_tag (event, "notification");
412 riemann_event_add_attribute (event, "host", n->host);
413 if (n->plugin[0] != 0)
414 riemann_event_add_attribute (event, "plugin", n->plugin);
415 if (n->plugin_instance[0] != 0)
416 riemann_event_add_attribute (event, "plugin_instance",
420 riemann_event_add_attribute (event, "type", n->type);
421 if (n->type_instance[0] != 0)
422 riemann_event_add_attribute (event, "type_instance",
425 for (i = 0; i < riemann_attrs_num; i += 2)
426 riemann_event_add_attribute(event,
428 riemann_attrs[i +1]);
430 for (i = 0; i < riemann_tags_num; i++)
431 riemann_event_add_tag (event, riemann_tags[i]);
433 format_name (service_buffer, sizeof (service_buffer),
434 /* host = */ "", n->plugin, n->plugin_instance,
435 n->type, n->type_instance);
436 event->service = strdup (&service_buffer[1]);
438 if (n->message[0] != 0)
439 riemann_event_add_attribute (event, "description", n->message);
441 /* Pull in values from threshold and add extra attributes */
442 for (meta = n->meta; meta != NULL; meta = meta->next)
444 if (strcasecmp ("CurrentValue", meta->name) == 0 && meta->type == NM_TYPE_DOUBLE)
446 event->metric_d = meta->nm_value.nm_double;
447 event->has_metric_d = 1;
451 if (meta->type == NM_TYPE_STRING) {
452 riemann_event_add_attribute (event, meta->name, meta->nm_value.nm_string);
457 DEBUG ("write_riemann plugin: Successfully created protobuf for notification: "
458 "host = \"%s\", service = \"%s\", state = \"%s\"",
459 event->host, event->service, event->state);
461 } /* }}} Msg *riemann_notification_to_protobuf */
463 static Event *riemann_value_to_protobuf (struct riemann_host const *host, /* {{{ */
464 data_set_t const *ds,
465 value_list_t const *vl, size_t index,
466 gauge_t const *rates,
470 char name_buffer[5 * DATA_MAX_NAME_LEN];
471 char service_buffer[6 * DATA_MAX_NAME_LEN];
475 event = malloc (sizeof (*event));
478 ERROR ("write_riemann plugin: malloc failed.");
481 memset (event, 0, sizeof (*event));
484 event->host = strdup (vl->host);
485 event->time = CDTIME_T_TO_TIME_T (vl->time);
488 if (host->check_thresholds) {
491 event->state = strdup("ok");
494 event->state = strdup("critical");
497 event->state = strdup("warning");
500 event->state = strdup("unknown");
505 ttl = CDTIME_T_TO_DOUBLE (vl->interval) * host->ttl_factor;
506 event->ttl = (float) ttl;
509 riemann_event_add_attribute (event, "plugin", vl->plugin);
510 if (vl->plugin_instance[0] != 0)
511 riemann_event_add_attribute (event, "plugin_instance",
512 vl->plugin_instance);
514 riemann_event_add_attribute (event, "type", vl->type);
515 if (vl->type_instance[0] != 0)
516 riemann_event_add_attribute (event, "type_instance",
519 if ((ds->ds[index].type != DS_TYPE_GAUGE) && (rates != NULL))
521 char ds_type[DATA_MAX_NAME_LEN];
523 ssnprintf (ds_type, sizeof (ds_type), "%s:rate",
524 DS_TYPE_TO_STRING(ds->ds[index].type));
525 riemann_event_add_attribute (event, "ds_type", ds_type);
529 riemann_event_add_attribute (event, "ds_type",
530 DS_TYPE_TO_STRING(ds->ds[index].type));
532 riemann_event_add_attribute (event, "ds_name", ds->ds[index].name);
534 char ds_index[DATA_MAX_NAME_LEN];
536 ssnprintf (ds_index, sizeof (ds_index), "%zu", index);
537 riemann_event_add_attribute (event, "ds_index", ds_index);
540 for (i = 0; i < riemann_attrs_num; i += 2)
541 riemann_event_add_attribute(event,
543 riemann_attrs[i +1]);
545 for (i = 0; i < riemann_tags_num; i++)
546 riemann_event_add_tag (event, riemann_tags[i]);
548 if (ds->ds[index].type == DS_TYPE_GAUGE)
550 event->has_metric_d = 1;
551 event->metric_d = (double) vl->values[index].gauge;
553 else if (rates != NULL)
555 event->has_metric_d = 1;
556 event->metric_d = (double) rates[index];
560 event->has_metric_sint64 = 1;
561 if (ds->ds[index].type == DS_TYPE_DERIVE)
562 event->metric_sint64 = (int64_t) vl->values[index].derive;
563 else if (ds->ds[index].type == DS_TYPE_ABSOLUTE)
564 event->metric_sint64 = (int64_t) vl->values[index].absolute;
566 event->metric_sint64 = (int64_t) vl->values[index].counter;
569 format_name (name_buffer, sizeof (name_buffer),
570 /* host = */ "", vl->plugin, vl->plugin_instance,
571 vl->type, vl->type_instance);
572 if (host->always_append_ds || (ds->ds_num > 1))
573 if (host->prefix == NULL || host->prefix[0] == '\0')
574 ssnprintf (service_buffer, sizeof (service_buffer),
575 "%s/%s", &name_buffer[1], ds->ds[index].name);
577 ssnprintf (service_buffer, sizeof (service_buffer),
578 "%s/%s/%s", host->prefix, &name_buffer[1], ds->ds[index].name);
580 if (host->prefix == NULL || host->prefix[0] == '\0')
581 sstrncpy (service_buffer, &name_buffer[1],
582 sizeof (service_buffer));
584 ssnprintf (service_buffer, sizeof (service_buffer),
585 "%s/%s", host->prefix, &name_buffer[1]);
587 event->service = strdup (service_buffer);
589 DEBUG ("write_riemann plugin: Successfully created protobuf for metric: "
590 "host = \"%s\", service = \"%s\"",
591 event->host, event->service);
593 } /* }}} Event *riemann_value_to_protobuf */
595 static Msg *riemann_value_list_to_protobuf (struct riemann_host const *host, /* {{{ */
596 data_set_t const *ds,
597 value_list_t const *vl,
602 gauge_t *rates = NULL;
604 /* Initialize the Msg structure. */
605 msg = malloc (sizeof (*msg));
608 ERROR ("write_riemann plugin: malloc failed.");
611 memset (msg, 0, sizeof (*msg));
614 /* Set up events. First, the list of pointers. */
615 msg->n_events = (size_t) vl->values_len;
616 msg->events = calloc (msg->n_events, sizeof (*msg->events));
617 if (msg->events == NULL)
619 ERROR ("write_riemann plugin: calloc failed.");
620 riemann_msg_protobuf_free (msg);
624 if (host->store_rates)
626 rates = uc_get_rate (ds, vl);
629 ERROR ("write_riemann plugin: uc_get_rate failed.");
630 riemann_msg_protobuf_free (msg);
635 for (i = 0; i < msg->n_events; i++)
637 msg->events[i] = riemann_value_to_protobuf (host, ds, vl,
638 (int) i, rates, statuses[i]);
639 if (msg->events[i] == NULL)
641 riemann_msg_protobuf_free (msg);
649 } /* }}} Msg *riemann_value_list_to_protobuf */
651 static int riemann_notification(const notification_t *n, user_data_t *ud) /* {{{ */
654 struct riemann_host *host = ud->data;
657 if (!host->notifications)
660 msg = riemann_notification_to_protobuf (host, n);
664 status = riemann_send (host, msg);
666 ERROR ("write_riemann plugin: riemann_send failed with status %i",
669 riemann_msg_protobuf_free (msg);
671 } /* }}} int riemann_notification */
673 static int riemann_write(const data_set_t *ds, /* {{{ */
674 const value_list_t *vl,
678 int statuses[vl->values_len];
679 struct riemann_host *host = ud->data;
682 if (host->check_thresholds)
683 write_riemann_threshold_check(ds, vl, statuses);
684 msg = riemann_value_list_to_protobuf (host, ds, vl, statuses);
688 status = riemann_send (host, msg);
690 ERROR ("write_riemann plugin: riemann_send failed with status %i",
693 riemann_msg_protobuf_free (msg);
695 } /* }}} int riemann_write */
697 static void riemann_free(void *p) /* {{{ */
699 struct riemann_host *host = p;
704 pthread_mutex_lock (&host->lock);
706 host->reference_count--;
707 if (host->reference_count > 0)
709 pthread_mutex_unlock (&host->lock);
713 riemann_disconnect (host);
715 sfree(host->service);
716 pthread_mutex_destroy (&host->lock);
718 } /* }}} void riemann_free */
720 static int riemann_config_node(oconfig_item_t *ci) /* {{{ */
722 struct riemann_host *host = NULL;
725 oconfig_item_t *child;
726 char callback_name[DATA_MAX_NAME_LEN];
729 if ((host = calloc(1, sizeof (*host))) == NULL) {
730 ERROR ("write_riemann plugin: calloc failed.");
733 pthread_mutex_init (&host->lock, NULL);
734 host->reference_count = 1;
736 host->service = NULL;
737 host->notifications = 1;
738 host->check_thresholds = 0;
739 host->store_rates = 1;
740 host->always_append_ds = 0;
742 host->ttl_factor = RIEMANN_TTL_FACTOR;
744 status = cf_util_get_string (ci, &host->name);
746 WARNING("write_riemann plugin: Required host name is missing.");
751 for (i = 0; i < ci->children_num; i++) {
753 * The code here could be simplified but makes room
754 * for easy adding of new options later on.
756 child = &ci->children[i];
759 if (strcasecmp ("Host", child->key) == 0) {
760 status = cf_util_get_string (child, &host->node);
763 } else if (strcasecmp ("Notifications", child->key) == 0) {
764 status = cf_util_get_boolean(child, &host->notifications);
767 } else if (strcasecmp ("EventServicePrefix", child->key) == 0) {
768 status = cf_util_get_string (child, &host->prefix);
771 } else if (strcasecmp ("CheckThresholds", child->key) == 0) {
772 status = cf_util_get_boolean(child, &host->check_thresholds);
775 } else if (strcasecmp ("Port", child->key) == 0) {
776 status = cf_util_get_service (child, &host->service);
778 ERROR ("write_riemann plugin: Invalid argument "
779 "configured for the \"Port\" "
783 } else if (strcasecmp ("Protocol", child->key) == 0) {
785 status = cf_util_get_string_buffer (child,
789 ERROR ("write_riemann plugin: cf_util_get_"
790 "string_buffer failed with "
791 "status %i.", status);
795 if (strcasecmp ("UDP", tmp) == 0)
797 else if (strcasecmp ("TCP", tmp) == 0)
800 WARNING ("write_riemann plugin: The value "
801 "\"%s\" is not valid for the "
802 "\"Protocol\" option. Use "
803 "either \"UDP\" or \"TCP\".",
805 } else if (strcasecmp ("StoreRates", child->key) == 0) {
806 status = cf_util_get_boolean (child, &host->store_rates);
809 } else if (strcasecmp ("AlwaysAppendDS", child->key) == 0) {
810 status = cf_util_get_boolean (child,
811 &host->always_append_ds);
814 } else if (strcasecmp ("TTLFactor", child->key) == 0) {
816 status = cf_util_get_double (child, &tmp);
820 host->ttl_factor = tmp;
821 } else if (tmp >= 1.0) {
822 NOTICE ("write_riemann plugin: The configured "
823 "TTLFactor is very small "
824 "(%.1f). A value of 2.0 or "
825 "greater is recommended.",
827 host->ttl_factor = tmp;
828 } else if (tmp > 0.0) {
829 WARNING ("write_riemann plugin: The configured "
830 "TTLFactor is too small to be "
831 "useful (%.1f). I'll use it "
832 "since the user knows best, "
833 "but under protest.",
835 host->ttl_factor = tmp;
836 } else { /* zero, negative and NAN */
837 ERROR ("write_riemann plugin: The configured "
838 "TTLFactor is invalid (%.1f).",
842 WARNING("write_riemann plugin: ignoring unknown config "
843 "option: \"%s\"", child->key);
851 ssnprintf (callback_name, sizeof (callback_name), "write_riemann/%s",
854 ud.free_func = riemann_free;
856 pthread_mutex_lock (&host->lock);
858 status = plugin_register_write (callback_name, riemann_write, &ud);
860 WARNING ("write_riemann plugin: plugin_register_write (\"%s\") "
861 "failed with status %i.",
862 callback_name, status);
864 host->reference_count++;
866 status = plugin_register_notification (callback_name,
867 riemann_notification, &ud);
869 WARNING ("write_riemann plugin: plugin_register_notification (\"%s\") "
870 "failed with status %i.",
871 callback_name, status);
873 host->reference_count++;
875 if (host->reference_count <= 1)
877 /* Both callbacks failed => free memory.
878 * We need to unlock here, because riemann_free() will lock.
879 * This is not a race condition, because we're the only one
880 * holding a reference. */
881 pthread_mutex_unlock (&host->lock);
886 host->reference_count--;
887 pthread_mutex_unlock (&host->lock);
890 } /* }}} int riemann_config_node */
892 static int riemann_config(oconfig_item_t *ci) /* {{{ */
895 oconfig_item_t *child;
898 for (i = 0; i < ci->children_num; i++) {
899 child = &ci->children[i];
901 if (strcasecmp("Node", child->key) == 0) {
902 riemann_config_node (child);
903 } else if (strcasecmp(child->key, "attribute") == 0) {
907 if (child->values_num != 2) {
908 WARNING("riemann attributes need both a key and a value.");
911 if (child->values[0].type != OCONFIG_TYPE_STRING ||
912 child->values[1].type != OCONFIG_TYPE_STRING) {
913 WARNING("riemann attribute needs string arguments.");
916 if ((key = strdup(child->values[0].value.string)) == NULL) {
917 WARNING("cannot allocate memory for attribute key.");
920 if ((val = strdup(child->values[1].value.string)) == NULL) {
921 WARNING("cannot allocate memory for attribute value.");
924 strarray_add(&riemann_attrs, &riemann_attrs_num, key);
925 strarray_add(&riemann_attrs, &riemann_attrs_num, val);
926 DEBUG("write_riemann: got attr: %s => %s", key, val);
929 } else if (strcasecmp(child->key, "tag") == 0) {
931 status = cf_util_get_string(child, &tmp);
935 strarray_add (&riemann_tags, &riemann_tags_num, tmp);
936 DEBUG("write_riemann plugin: Got tag: %s", tmp);
939 WARNING ("write_riemann plugin: Ignoring unknown "
940 "configuration option \"%s\" at top level.",
945 } /* }}} int riemann_config */
947 void module_register(void)
949 plugin_register_complex_config ("write_riemann", riemann_config);
952 /* vim: set sw=8 sts=8 ts=8 noet : */