2 * collectd - src/write_riemann.c
4 * Copyright (C) 2012,2013 Pierre-Yves Ritschard
5 * Copyright (C) 2013 Florian octo Forster
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
16 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
17 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 * Pierre-Yves Ritschard <pyr at spootnik.org>
21 * Florian octo Forster <octo at collectd.org>
27 #include "configfile.h"
28 #include "utils_cache.h"
29 #include "riemann.pb-c.h"
31 #include <sys/socket.h>
32 #include <arpa/inet.h>
38 #define RIEMANN_HOST "localhost"
39 #define RIEMANN_PORT "5555"
40 #define RIEMANN_TTL_FACTOR 2.0
42 int write_riemann_threshold_check(const data_set_t *, const value_list_t *, int *);
46 #define F_CONNECT 0x01
50 _Bool check_thresholds;
52 _Bool always_append_ds;
62 static char **riemann_tags;
63 static size_t riemann_tags_num;
64 static char **riemann_attrs;
65 static size_t riemann_attrs_num;
67 static void riemann_event_protobuf_free (Event *event) /* {{{ */
75 sfree (event->service);
77 sfree (event->description);
79 strarray_free (event->tags, event->n_tags);
83 for (i = 0; i < event->n_attributes; i++)
85 sfree (event->attributes[i]->key);
86 sfree (event->attributes[i]->value);
87 sfree (event->attributes[i]);
89 sfree (event->attributes);
90 event->n_attributes = 0;
93 } /* }}} void riemann_event_protobuf_free */
95 static void riemann_msg_protobuf_free (Msg *msg) /* {{{ */
102 for (i = 0; i < msg->n_events; i++)
104 riemann_event_protobuf_free (msg->events[i]);
105 msg->events[i] = NULL;
112 } /* }}} void riemann_msg_protobuf_free */
114 /* host->lock must be held when calling this function. */
115 static int riemann_connect(struct riemann_host *host) /* {{{ */
118 struct addrinfo *ai, *res, hints;
122 if (host->flags & F_CONNECT)
125 memset(&hints, 0, sizeof(hints));
126 memset(&service, 0, sizeof(service));
127 hints.ai_family = AF_UNSPEC;
128 hints.ai_socktype = host->use_tcp ? SOCK_STREAM : SOCK_DGRAM;
130 hints.ai_flags |= AI_ADDRCONFIG;
133 node = (host->node != NULL) ? host->node : RIEMANN_HOST;
134 service = (host->service != NULL) ? host->service : RIEMANN_PORT;
136 if ((e = getaddrinfo(node, service, &hints, &res)) != 0) {
137 ERROR ("write_riemann plugin: Unable to resolve host \"%s\": %s",
138 node, gai_strerror(e));
143 for (ai = res; ai != NULL; ai = ai->ai_next) {
144 if ((host->s = socket(ai->ai_family,
146 ai->ai_protocol)) == -1) {
150 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
156 host->flags |= F_CONNECT;
157 DEBUG("write_riemann plugin: got a succesful connection for: %s:%s",
165 WARNING("write_riemann plugin: Unable to connect to Riemann at %s:%s",
170 } /* }}} int riemann_connect */
172 /* host->lock must be held when calling this function. */
173 static int riemann_disconnect (struct riemann_host *host) /* {{{ */
175 if ((host->flags & F_CONNECT) == 0)
180 host->flags &= ~F_CONNECT;
183 } /* }}} int riemann_disconnect */
185 static int riemann_send_msg (struct riemann_host *host, const Msg *msg) /* {{{ */
188 u_char *buffer = NULL;
191 status = riemann_connect (host);
195 buffer_len = msg__get_packed_size(msg);
200 buffer = malloc (buffer_len);
201 if (buffer == NULL) {
202 ERROR ("write_riemann plugin: malloc failed.");
205 memset (buffer, 0, buffer_len);
209 uint32_t length = htonl ((uint32_t) (buffer_len - 4));
210 memcpy (buffer, &length, 4);
211 msg__pack(msg, buffer + 4);
215 msg__pack(msg, buffer);
218 status = (int) swrite (host->s, buffer, buffer_len);
222 ERROR ("write_riemann plugin: Sending to Riemann at %s:%s failed: %s",
223 (host->node != NULL) ? host->node : RIEMANN_HOST,
224 (host->service != NULL) ? host->service : RIEMANN_PORT,
225 sstrerror (errno, errbuf, sizeof (errbuf)));
232 } /* }}} int riemann_send_msg */
234 static int riemann_recv_ack(struct riemann_host *host) /* {{{ */
240 status = (int) sread (host->s, &header, 4);
245 size_t size = ntohl(header);
247 // Buffer on the stack since acknowledges are typically small.
249 memset (buffer, 0, size);
251 status = (int) sread (host->s, buffer, size);
256 msg = msg__unpack (NULL, size, buffer);
263 ERROR ("write_riemann plugin: Sending to Riemann at %s:%s acknowledgement message reported error: %s",
264 (host->node != NULL) ? host->node : RIEMANN_HOST,
265 (host->service != NULL) ? host->service : RIEMANN_PORT,
268 msg__free_unpacked(msg, NULL);
272 msg__free_unpacked (msg, NULL);
274 } /* }}} int riemann_recv_ack */
277 * Function to send messages (Msg) to riemann.
279 * Acquires the host lock, disconnects on errors.
281 static int riemann_send(struct riemann_host *host, Msg const *msg) /* {{{ */
284 pthread_mutex_lock (&host->lock);
286 status = riemann_send_msg(host, msg);
288 riemann_disconnect (host);
289 pthread_mutex_unlock (&host->lock);
294 * For TCP we need to receive message acknowledgemenent.
298 status = riemann_recv_ack(host);
302 riemann_disconnect (host);
303 pthread_mutex_unlock (&host->lock);
308 pthread_mutex_unlock (&host->lock);
310 } /* }}} int riemann_send */
312 static int riemann_event_add_tag (Event *event, char const *tag) /* {{{ */
314 return (strarray_add (&event->tags, &event->n_tags, tag));
315 } /* }}} int riemann_event_add_tag */
317 static int riemann_event_add_attribute (Event *event, /* {{{ */
318 char const *key, char const *value)
320 Attribute **new_attributes;
323 new_attributes = realloc (event->attributes,
324 sizeof (*event->attributes) * (event->n_attributes + 1));
325 if (new_attributes == NULL)
327 ERROR ("write_riemann plugin: realloc failed.");
330 event->attributes = new_attributes;
332 a = malloc (sizeof (*a));
335 ERROR ("write_riemann plugin: malloc failed.");
340 a->key = strdup (key);
342 a->value = strdup (value);
344 event->attributes[event->n_attributes] = a;
345 event->n_attributes++;
348 } /* }}} int riemann_event_add_attribute */
350 static Msg *riemann_notification_to_protobuf (struct riemann_host *host, /* {{{ */
351 notification_t const *n)
355 char service_buffer[6 * DATA_MAX_NAME_LEN];
356 char const *severity;
357 notification_meta_t *meta;
360 msg = malloc (sizeof (*msg));
363 ERROR ("write_riemann plugin: malloc failed.");
366 memset (msg, 0, sizeof (*msg));
369 msg->events = malloc (sizeof (*msg->events));
370 if (msg->events == NULL)
372 ERROR ("write_riemann plugin: malloc failed.");
377 event = malloc (sizeof (*event));
380 ERROR ("write_riemann plugin: malloc failed.");
385 memset (event, 0, sizeof (*event));
388 msg->events[0] = event;
391 event->host = strdup (n->host);
392 event->time = CDTIME_T_TO_TIME_T (n->time);
397 case NOTIF_OKAY: severity = "ok"; break;
398 case NOTIF_WARNING: severity = "warning"; break;
399 case NOTIF_FAILURE: severity = "critical"; break;
400 default: severity = "unknown";
402 event->state = strdup (severity);
404 riemann_event_add_tag (event, "notification");
406 riemann_event_add_attribute (event, "host", n->host);
407 if (n->plugin[0] != 0)
408 riemann_event_add_attribute (event, "plugin", n->plugin);
409 if (n->plugin_instance[0] != 0)
410 riemann_event_add_attribute (event, "plugin_instance",
414 riemann_event_add_attribute (event, "type", n->type);
415 if (n->type_instance[0] != 0)
416 riemann_event_add_attribute (event, "type_instance",
419 for (i = 0; i < riemann_attrs_num; i += 2)
420 riemann_event_add_attribute(event,
422 riemann_attrs[i +1]);
424 for (i = 0; i < riemann_tags_num; i++)
425 riemann_event_add_tag (event, riemann_tags[i]);
427 format_name (service_buffer, sizeof (service_buffer),
428 /* host = */ "", n->plugin, n->plugin_instance,
429 n->type, n->type_instance);
430 event->service = strdup (&service_buffer[1]);
432 if (n->message[0] != 0)
433 riemann_event_add_attribute (event, "description", n->message);
435 /* Pull in values from threshold and add extra attributes */
436 for (meta = n->meta; meta != NULL; meta = meta->next)
438 if (strcasecmp ("CurrentValue", meta->name) == 0 && meta->type == NM_TYPE_DOUBLE)
440 event->metric_d = meta->nm_value.nm_double;
441 event->has_metric_d = 1;
445 if (meta->type == NM_TYPE_STRING) {
446 riemann_event_add_attribute (event, meta->name, meta->nm_value.nm_string);
451 DEBUG ("write_riemann plugin: Successfully created protobuf for notification: "
452 "host = \"%s\", service = \"%s\", state = \"%s\"",
453 event->host, event->service, event->state);
455 } /* }}} Msg *riemann_notification_to_protobuf */
457 static Event *riemann_value_to_protobuf (struct riemann_host const *host, /* {{{ */
458 data_set_t const *ds,
459 value_list_t const *vl, size_t index,
460 gauge_t const *rates,
464 char name_buffer[5 * DATA_MAX_NAME_LEN];
465 char service_buffer[6 * DATA_MAX_NAME_LEN];
469 event = malloc (sizeof (*event));
472 ERROR ("write_riemann plugin: malloc failed.");
475 memset (event, 0, sizeof (*event));
478 event->host = strdup (vl->host);
479 event->time = CDTIME_T_TO_TIME_T (vl->time);
482 if (host->check_thresholds) {
485 event->state = strdup("ok");
488 event->state = strdup("critical");
491 event->state = strdup("warning");
494 event->state = strdup("unknown");
499 ttl = CDTIME_T_TO_DOUBLE (vl->interval) * host->ttl_factor;
500 event->ttl = (float) ttl;
503 riemann_event_add_attribute (event, "plugin", vl->plugin);
504 if (vl->plugin_instance[0] != 0)
505 riemann_event_add_attribute (event, "plugin_instance",
506 vl->plugin_instance);
508 riemann_event_add_attribute (event, "type", vl->type);
509 if (vl->type_instance[0] != 0)
510 riemann_event_add_attribute (event, "type_instance",
513 if ((ds->ds[index].type != DS_TYPE_GAUGE) && (rates != NULL))
515 char ds_type[DATA_MAX_NAME_LEN];
517 ssnprintf (ds_type, sizeof (ds_type), "%s:rate",
518 DS_TYPE_TO_STRING(ds->ds[index].type));
519 riemann_event_add_attribute (event, "ds_type", ds_type);
523 riemann_event_add_attribute (event, "ds_type",
524 DS_TYPE_TO_STRING(ds->ds[index].type));
526 riemann_event_add_attribute (event, "ds_name", ds->ds[index].name);
528 char ds_index[DATA_MAX_NAME_LEN];
530 ssnprintf (ds_index, sizeof (ds_index), "%zu", index);
531 riemann_event_add_attribute (event, "ds_index", ds_index);
534 for (i = 0; i < riemann_attrs_num; i += 2)
535 riemann_event_add_attribute(event,
537 riemann_attrs[i +1]);
539 for (i = 0; i < riemann_tags_num; i++)
540 riemann_event_add_tag (event, riemann_tags[i]);
542 if (ds->ds[index].type == DS_TYPE_GAUGE)
544 event->has_metric_d = 1;
545 event->metric_d = (double) vl->values[index].gauge;
547 else if (rates != NULL)
549 event->has_metric_d = 1;
550 event->metric_d = (double) rates[index];
554 event->has_metric_sint64 = 1;
555 if (ds->ds[index].type == DS_TYPE_DERIVE)
556 event->metric_sint64 = (int64_t) vl->values[index].derive;
557 else if (ds->ds[index].type == DS_TYPE_ABSOLUTE)
558 event->metric_sint64 = (int64_t) vl->values[index].absolute;
560 event->metric_sint64 = (int64_t) vl->values[index].counter;
563 format_name (name_buffer, sizeof (name_buffer),
564 /* host = */ "", vl->plugin, vl->plugin_instance,
565 vl->type, vl->type_instance);
566 if (host->always_append_ds || (ds->ds_num > 1))
567 ssnprintf (service_buffer, sizeof (service_buffer),
568 "%s/%s", &name_buffer[1], ds->ds[index].name);
570 sstrncpy (service_buffer, &name_buffer[1],
571 sizeof (service_buffer));
573 event->service = strdup (service_buffer);
575 DEBUG ("write_riemann plugin: Successfully created protobuf for metric: "
576 "host = \"%s\", service = \"%s\"",
577 event->host, event->service);
579 } /* }}} Event *riemann_value_to_protobuf */
581 static Msg *riemann_value_list_to_protobuf (struct riemann_host const *host, /* {{{ */
582 data_set_t const *ds,
583 value_list_t const *vl,
588 gauge_t *rates = NULL;
590 /* Initialize the Msg structure. */
591 msg = malloc (sizeof (*msg));
594 ERROR ("write_riemann plugin: malloc failed.");
597 memset (msg, 0, sizeof (*msg));
600 /* Set up events. First, the list of pointers. */
601 msg->n_events = (size_t) vl->values_len;
602 msg->events = calloc (msg->n_events, sizeof (*msg->events));
603 if (msg->events == NULL)
605 ERROR ("write_riemann plugin: calloc failed.");
606 riemann_msg_protobuf_free (msg);
610 if (host->store_rates)
612 rates = uc_get_rate (ds, vl);
615 ERROR ("write_riemann plugin: uc_get_rate failed.");
616 riemann_msg_protobuf_free (msg);
621 for (i = 0; i < msg->n_events; i++)
623 msg->events[i] = riemann_value_to_protobuf (host, ds, vl,
624 (int) i, rates, statuses[i]);
625 if (msg->events[i] == NULL)
627 riemann_msg_protobuf_free (msg);
635 } /* }}} Msg *riemann_value_list_to_protobuf */
637 static int riemann_notification(const notification_t *n, user_data_t *ud) /* {{{ */
640 struct riemann_host *host = ud->data;
643 if (!host->notifications)
646 msg = riemann_notification_to_protobuf (host, n);
650 status = riemann_send (host, msg);
652 ERROR ("write_riemann plugin: riemann_send failed with status %i",
655 riemann_msg_protobuf_free (msg);
657 } /* }}} int riemann_notification */
659 static int riemann_write(const data_set_t *ds, /* {{{ */
660 const value_list_t *vl,
664 int statuses[vl->values_len];
665 struct riemann_host *host = ud->data;
668 if (host->check_thresholds)
669 write_riemann_threshold_check(ds, vl, statuses);
670 msg = riemann_value_list_to_protobuf (host, ds, vl, statuses);
674 status = riemann_send (host, msg);
676 ERROR ("write_riemann plugin: riemann_send failed with status %i",
679 riemann_msg_protobuf_free (msg);
681 } /* }}} int riemann_write */
683 static void riemann_free(void *p) /* {{{ */
685 struct riemann_host *host = p;
690 pthread_mutex_lock (&host->lock);
692 host->reference_count--;
693 if (host->reference_count > 0)
695 pthread_mutex_unlock (&host->lock);
699 riemann_disconnect (host);
701 sfree(host->service);
702 pthread_mutex_destroy (&host->lock);
704 } /* }}} void riemann_free */
706 static int riemann_config_node(oconfig_item_t *ci) /* {{{ */
708 struct riemann_host *host = NULL;
711 oconfig_item_t *child;
712 char callback_name[DATA_MAX_NAME_LEN];
715 if ((host = calloc(1, sizeof (*host))) == NULL) {
716 ERROR ("write_riemann plugin: calloc failed.");
719 pthread_mutex_init (&host->lock, NULL);
720 host->reference_count = 1;
722 host->service = NULL;
723 host->notifications = 1;
724 host->check_thresholds = 0;
725 host->store_rates = 1;
726 host->always_append_ds = 0;
728 host->ttl_factor = RIEMANN_TTL_FACTOR;
730 status = cf_util_get_string (ci, &host->name);
732 WARNING("write_riemann plugin: Required host name is missing.");
737 for (i = 0; i < ci->children_num; i++) {
739 * The code here could be simplified but makes room
740 * for easy adding of new options later on.
742 child = &ci->children[i];
745 if (strcasecmp ("Host", child->key) == 0) {
746 status = cf_util_get_string (child, &host->node);
749 } else if (strcasecmp ("Notifications", child->key) == 0) {
750 status = cf_util_get_boolean(child, &host->notifications);
753 } else if (strcasecmp ("CheckThresholds", child->key) == 0) {
754 status = cf_util_get_boolean(child, &host->check_thresholds);
757 } else if (strcasecmp ("Port", child->key) == 0) {
758 status = cf_util_get_service (child, &host->service);
760 ERROR ("write_riemann plugin: Invalid argument "
761 "configured for the \"Port\" "
765 } else if (strcasecmp ("Protocol", child->key) == 0) {
767 status = cf_util_get_string_buffer (child,
771 ERROR ("write_riemann plugin: cf_util_get_"
772 "string_buffer failed with "
773 "status %i.", status);
777 if (strcasecmp ("UDP", tmp) == 0)
779 else if (strcasecmp ("TCP", tmp) == 0)
782 WARNING ("write_riemann plugin: The value "
783 "\"%s\" is not valid for the "
784 "\"Protocol\" option. Use "
785 "either \"UDP\" or \"TCP\".",
787 } else if (strcasecmp ("StoreRates", child->key) == 0) {
788 status = cf_util_get_boolean (child, &host->store_rates);
791 } else if (strcasecmp ("AlwaysAppendDS", child->key) == 0) {
792 status = cf_util_get_boolean (child,
793 &host->always_append_ds);
796 } else if (strcasecmp ("TTLFactor", child->key) == 0) {
798 status = cf_util_get_double (child, &tmp);
802 host->ttl_factor = tmp;
803 } else if (tmp >= 1.0) {
804 NOTICE ("write_riemann plugin: The configured "
805 "TTLFactor is very small "
806 "(%.1f). A value of 2.0 or "
807 "greater is recommended.",
809 host->ttl_factor = tmp;
810 } else if (tmp > 0.0) {
811 WARNING ("write_riemann plugin: The configured "
812 "TTLFactor is too small to be "
813 "useful (%.1f). I'll use it "
814 "since the user knows best, "
815 "but under protest.",
817 host->ttl_factor = tmp;
818 } else { /* zero, negative and NAN */
819 ERROR ("write_riemann plugin: The configured "
820 "TTLFactor is invalid (%.1f).",
824 WARNING("write_riemann plugin: ignoring unknown config "
825 "option: \"%s\"", child->key);
833 ssnprintf (callback_name, sizeof (callback_name), "write_riemann/%s",
836 ud.free_func = riemann_free;
838 pthread_mutex_lock (&host->lock);
840 status = plugin_register_write (callback_name, riemann_write, &ud);
842 WARNING ("write_riemann plugin: plugin_register_write (\"%s\") "
843 "failed with status %i.",
844 callback_name, status);
846 host->reference_count++;
848 status = plugin_register_notification (callback_name,
849 riemann_notification, &ud);
851 WARNING ("write_riemann plugin: plugin_register_notification (\"%s\") "
852 "failed with status %i.",
853 callback_name, status);
855 host->reference_count++;
857 if (host->reference_count <= 1)
859 /* Both callbacks failed => free memory.
860 * We need to unlock here, because riemann_free() will lock.
861 * This is not a race condition, because we're the only one
862 * holding a reference. */
863 pthread_mutex_unlock (&host->lock);
868 host->reference_count--;
869 pthread_mutex_unlock (&host->lock);
872 } /* }}} int riemann_config_node */
874 static int riemann_config(oconfig_item_t *ci) /* {{{ */
877 oconfig_item_t *child;
880 for (i = 0; i < ci->children_num; i++) {
881 child = &ci->children[i];
883 if (strcasecmp("Node", child->key) == 0) {
884 riemann_config_node (child);
885 } else if (strcasecmp(child->key, "attribute") == 0) {
889 if (child->values_num != 2) {
890 WARNING("riemann attributes need both a key and a value.");
893 if (child->values[0].type != OCONFIG_TYPE_STRING ||
894 child->values[1].type != OCONFIG_TYPE_STRING) {
895 WARNING("riemann attribute needs string arguments.");
898 if ((key = strdup(child->values[0].value.string)) == NULL) {
899 WARNING("cannot allocate memory for attribute key.");
902 if ((val = strdup(child->values[1].value.string)) == NULL) {
903 WARNING("cannot allocate memory for attribute value.");
906 strarray_add(&riemann_attrs, &riemann_attrs_num, key);
907 strarray_add(&riemann_attrs, &riemann_attrs_num, val);
908 DEBUG("write_riemann: got attr: %s => %s", key, val);
911 } else if (strcasecmp(child->key, "tag") == 0) {
913 status = cf_util_get_string(child, &tmp);
917 strarray_add (&riemann_tags, &riemann_tags_num, tmp);
918 DEBUG("write_riemann plugin: Got tag: %s", tmp);
921 WARNING ("write_riemann plugin: Ignoring unknown "
922 "configuration option \"%s\" at top level.",
927 } /* }}} int riemann_config */
929 void module_register(void)
931 plugin_register_complex_config ("write_riemann", riemann_config);
934 /* vim: set sw=8 sts=8 ts=8 noet : */