1 /**
2 * collectd - src/write_riemann.c
3 *
4 * Copyright (C) 2012,2013 Pierre-Yves Ritschard
5 * Copyright (C) 2013 Florian octo Forster
6 *
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.
10 *
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.
18 *
19 * Authors:
20 * Pierre-Yves Ritschard <pyr at spootnik.org>
21 * Florian octo Forster <octo at collectd.org>
22 */
24 #include "collectd.h"
25 #include "plugin.h"
26 #include "common.h"
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>
33 #include <errno.h>
34 #include <netdb.h>
35 #include <inttypes.h>
36 #include <pthread.h>
38 #define RIEMANN_HOST "localhost"
39 #define RIEMANN_PORT "5555"
40 #define RIEMANN_TTL_FACTOR 2.0
42 struct riemann_host {
43 char *name;
44 #define F_CONNECT 0x01
45 uint8_t flags;
46 pthread_mutex_t lock;
47 _Bool store_rates;
48 _Bool always_append_ds;
49 char *node;
50 char *service;
51 _Bool use_tcp;
52 int s;
53 double ttl_factor;
55 int reference_count;
56 };
58 static char **riemann_tags;
59 static size_t riemann_tags_num;
61 static void riemann_event_protobuf_free (Event *event) /* {{{ */
62 {
63 if (event == NULL)
64 return;
66 sfree (event->state);
67 sfree (event->service);
68 sfree (event->host);
69 sfree (event->description);
71 strarray_free (event->tags, event->n_tags);
72 event->tags = NULL;
73 event->n_tags = 0;
75 sfree (event);
76 } /* }}} void riemann_event_protobuf_free */
78 static void riemann_msg_protobuf_free (Msg *msg) /* {{{ */
79 {
80 size_t i;
82 if (msg == NULL)
83 return;
85 for (i = 0; i < msg->n_events; i++)
86 {
87 riemann_event_protobuf_free (msg->events[i]);
88 msg->events[i] = NULL;
89 }
91 sfree (msg->events);
92 msg->n_events = 0;
94 sfree (msg);
95 } /* }}} void riemann_msg_protobuf_free */
97 /* host->lock must be held when calling this function. */
98 static int
99 riemann_connect(struct riemann_host *host)
100 {
101 int e;
102 struct addrinfo *ai, *res, hints;
103 char const *node;
104 char const *service;
106 if (host->flags & F_CONNECT)
107 return 0;
109 memset(&hints, 0, sizeof(hints));
110 memset(&service, 0, sizeof(service));
111 hints.ai_family = AF_UNSPEC;
112 hints.ai_socktype = host->use_tcp ? SOCK_STREAM : SOCK_DGRAM;
113 #ifdef AI_ADDRCONFIG
114 hints.ai_flags |= AI_ADDRCONFIG;
115 #endif
117 node = (host->node != NULL) ? host->node : RIEMANN_HOST;
118 service = (host->service != NULL) ? host->service : RIEMANN_PORT;
120 if ((e = getaddrinfo(node, service, &hints, &res)) != 0) {
121 ERROR ("write_riemann plugin: Unable to resolve host \"%s\": %s",
122 node, gai_strerror(e));
123 return -1;
124 }
126 host->s = -1;
127 for (ai = res; ai != NULL; ai = ai->ai_next) {
128 if ((host->s = socket(ai->ai_family,
129 ai->ai_socktype,
130 ai->ai_protocol)) == -1) {
131 continue;
132 }
134 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
135 close(host->s);
136 host->s = -1;
137 continue;
138 }
140 host->flags |= F_CONNECT;
141 DEBUG("write_riemann plugin: got a succesful connection for: %s:%s",
142 node, service);
143 break;
144 }
146 freeaddrinfo(res);
148 if (host->s < 0) {
149 WARNING("write_riemann plugin: Unable to connect to Riemann at %s:%s",
150 node, service);
151 return -1;
152 }
153 return 0;
154 }
156 /* host->lock must be held when calling this function. */
157 static int
158 riemann_disconnect (struct riemann_host *host)
159 {
160 if ((host->flags & F_CONNECT) == 0)
161 return (0);
163 close (host->s);
164 host->s = -1;
165 host->flags &= ~F_CONNECT;
167 return (0);
168 }
170 static int
171 riemann_send(struct riemann_host *host, Msg const *msg)
172 {
173 u_char *buffer;
174 size_t buffer_len;
175 int status;
177 pthread_mutex_lock (&host->lock);
179 status = riemann_connect (host);
180 if (status != 0)
181 {
182 pthread_mutex_unlock (&host->lock);
183 return status;
184 }
186 buffer_len = msg__get_packed_size(msg);
187 if (host->use_tcp)
188 buffer_len += 4;
190 buffer = malloc (buffer_len);
191 if (buffer == NULL) {
192 pthread_mutex_unlock (&host->lock);
193 ERROR ("write_riemann plugin: malloc failed.");
194 return ENOMEM;
195 }
196 memset (buffer, 0, buffer_len);
198 if (host->use_tcp)
199 {
200 uint32_t length = htonl ((uint32_t) (buffer_len - 4));
201 memcpy (buffer, &length, 4);
202 msg__pack(msg, buffer + 4);
203 }
204 else
205 {
206 msg__pack(msg, buffer);
207 }
209 status = (int) swrite (host->s, buffer, buffer_len);
210 if (status != 0)
211 {
212 char errbuf[1024];
214 riemann_disconnect (host);
215 pthread_mutex_unlock (&host->lock);
217 ERROR ("write_riemann plugin: Sending to Riemann at %s:%s failed: %s",
218 (host->node != NULL) ? host->node : RIEMANN_HOST,
219 (host->service != NULL) ? host->service : RIEMANN_PORT,
220 sstrerror (errno, errbuf, sizeof (errbuf)));
221 sfree (buffer);
222 return -1;
223 }
225 pthread_mutex_unlock (&host->lock);
226 sfree (buffer);
227 return 0;
228 }
230 static int riemann_event_add_tag (Event *event, char const *tag) /* {{{ */
231 {
232 return (strarray_add (&event->tags, &event->n_tags, tag));
233 } /* }}} int riemann_event_add_tag */
235 static int riemann_event_add_attribute (Event *event, /* {{{ */
236 char const *key, char const *value)
237 {
238 Attribute **new_attributes;
239 Attribute *a;
241 new_attributes = realloc (event->attributes,
242 sizeof (*event->attributes) * (event->n_attributes + 1));
243 if (new_attributes == NULL)
244 {
245 ERROR ("write_riemann plugin: realloc failed.");
246 return (ENOMEM);
247 }
248 event->attributes = new_attributes;
250 a = malloc (sizeof (*a));
251 if (a == NULL)
252 {
253 ERROR ("write_riemann plugin: malloc failed.");
254 return (ENOMEM);
255 }
256 attribute__init (a);
258 a->key = strdup (key);
259 if (value != NULL)
260 a->value = strdup (value);
262 event->attributes[event->n_attributes] = a;
263 event->n_attributes++;
265 return (0);
266 } /* }}} int riemann_event_add_attribute */
268 static Msg *riemann_notification_to_protobuf (struct riemann_host *host, /* {{{ */
269 notification_t const *n)
270 {
271 Msg *msg;
272 Event *event;
273 char service_buffer[6 * DATA_MAX_NAME_LEN];
274 char const *severity;
275 notification_meta_t *meta;
276 int i;
278 msg = malloc (sizeof (*msg));
279 if (msg == NULL)
280 {
281 ERROR ("write_riemann plugin: malloc failed.");
282 return (NULL);
283 }
284 memset (msg, 0, sizeof (*msg));
285 msg__init (msg);
287 msg->events = malloc (sizeof (*msg->events));
288 if (msg->events == NULL)
289 {
290 ERROR ("write_riemann plugin: malloc failed.");
291 sfree (msg);
292 return (NULL);
293 }
295 event = malloc (sizeof (*event));
296 if (event == NULL)
297 {
298 ERROR ("write_riemann plugin: malloc failed.");
299 sfree (msg->events);
300 sfree (msg);
301 return (NULL);
302 }
303 memset (event, 0, sizeof (*event));
304 event__init (event);
306 msg->events[0] = event;
307 msg->n_events = 1;
309 event->host = strdup (n->host);
310 event->time = CDTIME_T_TO_TIME_T (n->time);
311 event->has_time = 1;
313 switch (n->severity)
314 {
315 case NOTIF_OKAY: severity = "ok"; break;
316 case NOTIF_WARNING: severity = "warning"; break;
317 case NOTIF_FAILURE: severity = "critical"; break;
318 default: severity = "unknown";
319 }
320 event->state = strdup (severity);
322 riemann_event_add_tag (event, "notification");
323 if (n->host[0] != 0)
324 riemann_event_add_attribute (event, "host", n->host);
325 if (n->plugin[0] != 0)
326 riemann_event_add_attribute (event, "plugin", n->plugin);
327 if (n->plugin_instance[0] != 0)
328 riemann_event_add_attribute (event, "plugin_instance",
329 n->plugin_instance);
331 if (n->type[0] != 0)
332 riemann_event_add_attribute (event, "type", n->type);
333 if (n->type_instance[0] != 0)
334 riemann_event_add_attribute (event, "type_instance",
335 n->type_instance);
337 for (i = 0; i < riemann_tags_num; i++)
338 riemann_event_add_tag (event, riemann_tags[i]);
340 format_name (service_buffer, sizeof (service_buffer),
341 /* host = */ "", n->plugin, n->plugin_instance,
342 n->type, n->type_instance);
343 event->service = strdup (&service_buffer[1]);
345 /* Pull in values from threshold */
346 for (meta = n->meta; meta != NULL; meta = meta->next)
347 {
348 if (strcasecmp ("CurrentValue", meta->name) != 0)
349 continue;
351 event->metric_d = meta->nm_value.nm_double;
352 event->has_metric_d = 1;
353 break;
354 }
356 DEBUG ("write_riemann plugin: Successfully created protobuf for notification: "
357 "host = \"%s\", service = \"%s\", state = \"%s\"",
358 event->host, event->service, event->state);
359 return (msg);
360 } /* }}} Msg *riemann_notification_to_protobuf */
362 static Event *riemann_value_to_protobuf (struct riemann_host const *host, /* {{{ */
363 data_set_t const *ds,
364 value_list_t const *vl, size_t index,
365 gauge_t const *rates)
366 {
367 Event *event;
368 char name_buffer[5 * DATA_MAX_NAME_LEN];
369 char service_buffer[6 * DATA_MAX_NAME_LEN];
370 double ttl;
371 int i;
373 event = malloc (sizeof (*event));
374 if (event == NULL)
375 {
376 ERROR ("write_riemann plugin: malloc failed.");
377 return (NULL);
378 }
379 memset (event, 0, sizeof (*event));
380 event__init (event);
382 event->host = strdup (vl->host);
383 event->time = CDTIME_T_TO_TIME_T (vl->time);
384 event->has_time = 1;
386 ttl = CDTIME_T_TO_DOUBLE (vl->interval) * host->ttl_factor;
387 event->ttl = (float) ttl;
388 event->has_ttl = 1;
390 riemann_event_add_attribute (event, "plugin", vl->plugin);
391 if (vl->plugin_instance[0] != 0)
392 riemann_event_add_attribute (event, "plugin_instance",
393 vl->plugin_instance);
395 riemann_event_add_attribute (event, "type", vl->type);
396 if (vl->type_instance[0] != 0)
397 riemann_event_add_attribute (event, "type_instance",
398 vl->type_instance);
400 if ((ds->ds[index].type != DS_TYPE_GAUGE) && (rates != NULL))
401 {
402 char ds_type[DATA_MAX_NAME_LEN];
404 ssnprintf (ds_type, sizeof (ds_type), "%s:rate",
405 DS_TYPE_TO_STRING(ds->ds[index].type));
406 riemann_event_add_attribute (event, "ds_type", ds_type);
407 }
408 else
409 {
410 riemann_event_add_attribute (event, "ds_type",
411 DS_TYPE_TO_STRING(ds->ds[index].type));
412 }
413 riemann_event_add_attribute (event, "ds_name", ds->ds[index].name);
414 {
415 char ds_index[DATA_MAX_NAME_LEN];
417 ssnprintf (ds_index, sizeof (ds_index), "%zu", index);
418 riemann_event_add_attribute (event, "ds_index", ds_index);
419 }
421 for (i = 0; i < riemann_tags_num; i++)
422 riemann_event_add_tag (event, riemann_tags[i]);
424 if (ds->ds[index].type == DS_TYPE_GAUGE)
425 {
426 event->has_metric_d = 1;
427 event->metric_d = (double) vl->values[index].gauge;
428 }
429 else if (rates != NULL)
430 {
431 event->has_metric_d = 1;
432 event->metric_d = (double) rates[index];
433 }
434 else
435 {
436 event->has_metric_sint64 = 1;
437 if (ds->ds[index].type == DS_TYPE_DERIVE)
438 event->metric_sint64 = (int64_t) vl->values[index].derive;
439 else if (ds->ds[index].type == DS_TYPE_ABSOLUTE)
440 event->metric_sint64 = (int64_t) vl->values[index].absolute;
441 else
442 event->metric_sint64 = (int64_t) vl->values[index].counter;
443 }
445 format_name (name_buffer, sizeof (name_buffer),
446 /* host = */ "", vl->plugin, vl->plugin_instance,
447 vl->type, vl->type_instance);
448 if (host->always_append_ds || (ds->ds_num > 1))
449 ssnprintf (service_buffer, sizeof (service_buffer),
450 "%s/%s", &name_buffer[1], ds->ds[index].name);
451 else
452 sstrncpy (service_buffer, &name_buffer[1],
453 sizeof (service_buffer));
455 event->service = strdup (service_buffer);
457 DEBUG ("write_riemann plugin: Successfully created protobuf for metric: "
458 "host = \"%s\", service = \"%s\"",
459 event->host, event->service);
460 return (event);
461 } /* }}} Event *riemann_value_to_protobuf */
463 static Msg *riemann_value_list_to_protobuf (struct riemann_host const *host, /* {{{ */
464 data_set_t const *ds,
465 value_list_t const *vl)
466 {
467 Msg *msg;
468 size_t i;
469 gauge_t *rates = NULL;
471 /* Initialize the Msg structure. */
472 msg = malloc (sizeof (*msg));
473 if (msg == NULL)
474 {
475 ERROR ("write_riemann plugin: malloc failed.");
476 return (NULL);
477 }
478 memset (msg, 0, sizeof (*msg));
479 msg__init (msg);
481 /* Set up events. First, the list of pointers. */
482 msg->n_events = (size_t) vl->values_len;
483 msg->events = calloc (msg->n_events, sizeof (*msg->events));
484 if (msg->events == NULL)
485 {
486 ERROR ("write_riemann plugin: calloc failed.");
487 riemann_msg_protobuf_free (msg);
488 return (NULL);
489 }
491 if (host->store_rates)
492 {
493 rates = uc_get_rate (ds, vl);
494 if (rates == NULL)
495 {
496 ERROR ("write_riemann plugin: uc_get_rate failed.");
497 riemann_msg_protobuf_free (msg);
498 return (NULL);
499 }
500 }
502 for (i = 0; i < msg->n_events; i++)
503 {
504 msg->events[i] = riemann_value_to_protobuf (host, ds, vl,
505 (int) i, rates);
506 if (msg->events[i] == NULL)
507 {
508 riemann_msg_protobuf_free (msg);
509 sfree (rates);
510 return (NULL);
511 }
512 }
514 sfree (rates);
515 return (msg);
516 } /* }}} Msg *riemann_value_list_to_protobuf */
518 static int
519 riemann_notification(const notification_t *n, user_data_t *ud)
520 {
521 int status;
522 struct riemann_host *host = ud->data;
523 Msg *msg;
525 msg = riemann_notification_to_protobuf (host, n);
526 if (msg == NULL)
527 return (-1);
529 status = riemann_send (host, msg);
530 if (status != 0)
531 ERROR ("write_riemann plugin: riemann_send failed with status %i",
532 status);
534 riemann_msg_protobuf_free (msg);
535 return (status);
536 } /* }}} int riemann_notification */
538 static int
539 riemann_write(const data_set_t *ds,
540 const value_list_t *vl,
541 user_data_t *ud)
542 {
543 int status;
544 struct riemann_host *host = ud->data;
545 Msg *msg;
547 msg = riemann_value_list_to_protobuf (host, ds, vl);
548 if (msg == NULL)
549 return (-1);
551 status = riemann_send (host, msg);
552 if (status != 0)
553 ERROR ("write_riemann plugin: riemann_send failed with status %i",
554 status);
556 riemann_msg_protobuf_free (msg);
557 return status;
558 }
560 static void
561 riemann_free(void *p)
562 {
563 struct riemann_host *host = p;
565 if (host == NULL)
566 return;
568 pthread_mutex_lock (&host->lock);
570 host->reference_count--;
571 if (host->reference_count > 0)
572 {
573 pthread_mutex_unlock (&host->lock);
574 return;
575 }
577 riemann_disconnect (host);
579 sfree(host->service);
580 pthread_mutex_destroy (&host->lock);
581 sfree(host);
582 }
584 static int
585 riemann_config_node(oconfig_item_t *ci)
586 {
587 struct riemann_host *host = NULL;
588 int status = 0;
589 int i;
590 oconfig_item_t *child;
591 char callback_name[DATA_MAX_NAME_LEN];
592 user_data_t ud;
594 if ((host = calloc(1, sizeof (*host))) == NULL) {
595 ERROR ("write_riemann plugin: calloc failed.");
596 return ENOMEM;
597 }
598 pthread_mutex_init (&host->lock, NULL);
599 host->reference_count = 1;
600 host->node = NULL;
601 host->service = NULL;
602 host->store_rates = 1;
603 host->always_append_ds = 0;
604 host->use_tcp = 0;
605 host->ttl_factor = RIEMANN_TTL_FACTOR;
607 status = cf_util_get_string (ci, &host->name);
608 if (status != 0) {
609 WARNING("write_riemann plugin: Required host name is missing.");
610 riemann_free (host);
611 return -1;
612 }
614 for (i = 0; i < ci->children_num; i++) {
615 /*
616 * The code here could be simplified but makes room
617 * for easy adding of new options later on.
618 */
619 child = &ci->children[i];
620 status = 0;
622 if (strcasecmp ("Host", child->key) == 0) {
623 status = cf_util_get_string (child, &host->node);
624 if (status != 0)
625 break;
626 } else if (strcasecmp ("Port", child->key) == 0) {
627 status = cf_util_get_service (child, &host->service);
628 if (status != 0) {
629 ERROR ("write_riemann plugin: Invalid argument "
630 "configured for the \"Port\" "
631 "option.");
632 break;
633 }
634 } else if (strcasecmp ("Protocol", child->key) == 0) {
635 char tmp[16];
636 status = cf_util_get_string_buffer (child,
637 tmp, sizeof (tmp));
638 if (status != 0)
639 {
640 ERROR ("write_riemann plugin: cf_util_get_"
641 "string_buffer failed with "
642 "status %i.", status);
643 break;
644 }
646 if (strcasecmp ("UDP", tmp) == 0)
647 host->use_tcp = 0;
648 else if (strcasecmp ("TCP", tmp) == 0)
649 host->use_tcp = 1;
650 else
651 WARNING ("write_riemann plugin: The value "
652 "\"%s\" is not valid for the "
653 "\"Protocol\" option. Use "
654 "either \"UDP\" or \"TCP\".",
655 tmp);
656 } else if (strcasecmp ("StoreRates", child->key) == 0) {
657 status = cf_util_get_boolean (child, &host->store_rates);
658 if (status != 0)
659 break;
660 } else if (strcasecmp ("AlwaysAppendDS", child->key) == 0) {
661 status = cf_util_get_boolean (child,
662 &host->always_append_ds);
663 if (status != 0)
664 break;
665 } else if (strcasecmp ("TTLFactor", child->key) == 0) {
666 double tmp = NAN;
667 status = cf_util_get_double (child, &tmp);
668 if (status != 0)
669 break;
670 if (tmp >= 2.0) {
671 host->ttl_factor = tmp;
672 } else if (tmp >= 1.0) {
673 NOTICE ("write_riemann plugin: The configured "
674 "TTLFactor is very small "
675 "(%.1f). A value of 2.0 or "
676 "greater is recommended.",
677 tmp);
678 host->ttl_factor = tmp;
679 } else if (tmp > 0.0) {
680 WARNING ("write_riemann plugin: The configured "
681 "TTLFactor is too small to be "
682 "useful (%.1f). I'll use it "
683 "since the user knows best, "
684 "but under protest.",
685 tmp);
686 host->ttl_factor = tmp;
687 } else { /* zero, negative and NAN */
688 ERROR ("write_riemann plugin: The configured "
689 "TTLFactor is invalid (%.1f).",
690 tmp);
691 }
692 } else {
693 WARNING("write_riemann plugin: ignoring unknown config "
694 "option: \"%s\"", child->key);
695 }
696 }
697 if (status != 0) {
698 riemann_free (host);
699 return status;
700 }
702 ssnprintf (callback_name, sizeof (callback_name), "write_riemann/%s",
703 host->name);
704 ud.data = host;
705 ud.free_func = riemann_free;
707 pthread_mutex_lock (&host->lock);
709 status = plugin_register_write (callback_name, riemann_write, &ud);
710 if (status != 0)
711 WARNING ("write_riemann plugin: plugin_register_write (\"%s\") "
712 "failed with status %i.",
713 callback_name, status);
714 else /* success */
715 host->reference_count++;
717 status = plugin_register_notification (callback_name,
718 riemann_notification, &ud);
719 if (status != 0)
720 WARNING ("write_riemann plugin: plugin_register_notification (\"%s\") "
721 "failed with status %i.",
722 callback_name, status);
723 else /* success */
724 host->reference_count++;
726 if (host->reference_count <= 1)
727 {
728 /* Both callbacks failed => free memory.
729 * We need to unlock here, because riemann_free() will lock.
730 * This is not a race condition, because we're the only one
731 * holding a reference. */
732 pthread_mutex_unlock (&host->lock);
733 riemann_free (host);
734 return (-1);
735 }
737 host->reference_count--;
738 pthread_mutex_unlock (&host->lock);
740 return status;
741 }
743 static int
744 riemann_config(oconfig_item_t *ci)
745 {
746 int i;
747 oconfig_item_t *child;
748 int status;
750 for (i = 0; i < ci->children_num; i++) {
751 child = &ci->children[i];
753 if (strcasecmp("Node", child->key) == 0) {
754 riemann_config_node (child);
755 } else if (strcasecmp(child->key, "tag") == 0) {
756 char *tmp = NULL;
757 status = cf_util_get_string(child, &tmp);
758 if (status != 0)
759 continue;
761 strarray_add (&riemann_tags, &riemann_tags_num, tmp);
762 DEBUG("write_riemann plugin: Got tag: %s", tmp);
763 sfree (tmp);
764 } else {
765 WARNING ("write_riemann plugin: Ignoring unknown "
766 "configuration option \"%s\" at top level.",
767 child->key);
768 }
769 }
770 return (0);
771 }
773 void
774 module_register(void)
775 {
776 plugin_register_complex_config ("write_riemann", riemann_config);
777 }
779 /* vim: set sw=8 sts=8 ts=8 noet : */