Code

write_riemann plugin: Use format_name() to generate the service name.
[collectd.git] / src / write_riemann.c
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"
41 struct riemann_host {
42         char                    *name;
43 #define F_CONNECT                0x01
44         uint8_t                  flags;
45         pthread_mutex_t          lock;
46         _Bool                    store_rates;
47         char                    *node;
48         char                    *service;
49         int                      s;
51         int                      reference_count;
52 };
54 static char     **riemann_tags;
55 static size_t     riemann_tags_num;
57 static int      riemann_send(struct riemann_host *, Msg const *);
58 static int      riemann_notification(const notification_t *, user_data_t *);
59 static int      riemann_write(const data_set_t *, const value_list_t *, user_data_t *);
60 static int      riemann_connect(struct riemann_host *);
61 static int      riemann_disconnect (struct riemann_host *host);
62 static void     riemann_free(void *);
63 static int      riemann_config_node(oconfig_item_t *);
64 static int      riemann_config(oconfig_item_t *);
65 void    module_register(void);
67 static void riemann_event_protobuf_free (Event *event) /* {{{ */
68 {
69         if (event == NULL)
70                 return;
72         sfree (event->state);
73         sfree (event->service);
74         sfree (event->host);
75         sfree (event->description);
77         strarray_free (event->tags, event->n_tags);
78         event->tags = NULL;
79         event->n_tags = 0;
81         sfree (event);
82 } /* }}} void riemann_event_protobuf_free */
84 static void riemann_msg_protobuf_free (Msg *msg) /* {{{ */
85 {
86         size_t i;
88         if (msg == NULL)
89                 return;
91         for (i = 0; i < msg->n_events; i++)
92         {
93                 riemann_event_protobuf_free (msg->events[i]);
94                 msg->events[i] = NULL;
95         }
97         sfree (msg->events);
98         msg->n_events = 0;
100         sfree (msg);
101 } /* }}} void riemann_msg_protobuf_free */
103 static int
104 riemann_send(struct riemann_host *host, Msg const *msg)
106         u_char *buffer;
107         size_t  buffer_len;
108         int status;
110         pthread_mutex_lock (&host->lock);
112         status = riemann_connect (host);
113         if (status != 0)
114         {
115                 pthread_mutex_unlock (&host->lock);
116                 return status;
117         }
119         buffer_len = msg__get_packed_size(msg);
120         buffer = malloc (buffer_len);
121         if (buffer == NULL) {
122                 pthread_mutex_unlock (&host->lock);
123                 ERROR ("write_riemann plugin: malloc failed.");
124                 return ENOMEM;
125         }
126         memset (buffer, 0, buffer_len);
128         msg__pack(msg, buffer);
130         status = (int) swrite (host->s, buffer, buffer_len);
131         if (status != 0)
132         {
133                 char errbuf[1024];
135                 riemann_disconnect (host);
136                 pthread_mutex_unlock (&host->lock);
138                 ERROR ("write_riemann plugin: Sending to Riemann at %s:%s failed: %s",
139                                 (host->node != NULL) ? host->node : RIEMANN_HOST,
140                                 (host->service != NULL) ? host->service : RIEMANN_PORT,
141                                 sstrerror (errno, errbuf, sizeof (errbuf)));
142                 sfree (buffer);
143                 return -1;
144         }
146         pthread_mutex_unlock (&host->lock);
147         sfree (buffer);
148         return 0;
151 static int riemann_event_add_tag (Event *event, /* {{{ */
152                 char const *format, ...)
154         va_list ap;
155         char buffer[1024];
156         size_t ret;
158         va_start (ap, format);
159         ret = vsnprintf (buffer, sizeof (buffer), format, ap);
160         if (ret >= sizeof (buffer))
161                 ret = sizeof (buffer) - 1;
162         buffer[ret] = 0;
163         va_end (ap);
165         return (strarray_add (&event->tags, &event->n_tags, buffer));
166 } /* }}} int riemann_event_add_tag */
168 static Msg *riemann_notification_to_protobuf (struct riemann_host *host, /* {{{ */
169                 notification_t const *n)
171         Msg *msg;
172         Event *event;
173         char service_buffer[6 * DATA_MAX_NAME_LEN];
174         char const *severity;
175         notification_meta_t *meta;
176         int i;
178         msg = malloc (sizeof (*msg));
179         if (msg == NULL)
180         {
181                 ERROR ("write_riemann plugin: malloc failed.");
182                 return (NULL);
183         }
184         memset (msg, 0, sizeof (*msg));
185         msg__init (msg);
187         msg->events = malloc (sizeof (*msg->events));
188         if (msg->events == NULL)
189         {
190                 ERROR ("write_riemann plugin: malloc failed.");
191                 sfree (msg);
192                 return (NULL);
193         }
195         event = malloc (sizeof (*event));
196         if (event == NULL)
197         {
198                 ERROR ("write_riemann plugin: malloc failed.");
199                 sfree (msg->events);
200                 sfree (msg);
201                 return (NULL);
202         }
203         memset (event, 0, sizeof (*event));
204         event__init (event);
206         msg->events[0] = event;
207         msg->n_events = 1;
209         event->host = strdup (n->host);
210         event->time = CDTIME_T_TO_TIME_T (n->time);
211         event->has_time = 1;
213         switch (n->severity)
214         {
215                 case NOTIF_OKAY:        severity = "okay"; break;
216                 case NOTIF_WARNING:     severity = "warning"; break;
217                 case NOTIF_FAILURE:     severity = "failure"; break;
218                 default:                severity = "unknown";
219         }
220         event->state = strdup (severity);
222         riemann_event_add_tag (event, "notification");
223         if (n->plugin[0] != 0)
224                 riemann_event_add_tag (event, "plugin:%s", n->plugin);
225         if (n->plugin_instance[0] != 0)
226                 riemann_event_add_tag (event, "plugin_instance:%s",
227                                 n->plugin_instance);
229         if (n->type[0] != 0)
230                 riemann_event_add_tag (event, "type:%s", n->type);
231         if (n->type_instance[0] != 0)
232                 riemann_event_add_tag (event, "type_instance:%s",
233                                 n->type_instance);
235         for (i = 0; i < riemann_tags_num; i++)
236                 riemann_event_add_tag (event, "%s", riemann_tags[i]);
238         format_name (service_buffer, sizeof (service_buffer),
239                         /* host = */ "", n->plugin, n->plugin_instance,
240                         n->type, n->type_instance);
241         event->service = strdup (&service_buffer[1]);
243         /* Pull in values from threshold */
244         for (meta = n->meta; meta != NULL; meta = meta->next)
245         {
246                 if (strcasecmp ("CurrentValue", meta->name) != 0)
247                         continue;
249                 event->metric_d = meta->nm_value.nm_double;
250                 event->has_metric_d = 1;
251                 break;
252         }
254         DEBUG ("write_riemann plugin: Successfully created protobuf for notification: "
255                         "host = \"%s\", service = \"%s\", state = \"%s\"",
256                         event->host, event->service, event->state);
257         return (msg);
258 } /* }}} Msg *riemann_notification_to_protobuf */
260 static Event *riemann_value_to_protobuf (struct riemann_host const *host, /* {{{ */
261                 data_set_t const *ds,
262                 value_list_t const *vl, size_t index,
263                 gauge_t const *rates)
265         Event *event;
266         char name_buffer[5 * DATA_MAX_NAME_LEN];
267         char service_buffer[6 * DATA_MAX_NAME_LEN];
268         int i;
270         event = malloc (sizeof (*event));
271         if (event == NULL)
272         {
273                 ERROR ("write_riemann plugin: malloc failed.");
274                 return (NULL);
275         }
276         memset (event, 0, sizeof (*event));
277         event__init (event);
279         event->host = strdup (vl->host);
280         event->time = CDTIME_T_TO_TIME_T (vl->time);
281         event->has_time = 1;
282         event->ttl = CDTIME_T_TO_TIME_T (2 * vl->interval);
283         event->has_ttl = 1;
285         riemann_event_add_tag (event, "plugin:%s", vl->plugin);
286         if (vl->plugin_instance[0] != 0)
287                 riemann_event_add_tag (event, "plugin_instance:%s",
288                                 vl->plugin_instance);
290         riemann_event_add_tag (event, "type:%s", vl->type);
291         if (vl->type_instance[0] != 0)
292                 riemann_event_add_tag (event, "type_instance:%s",
293                                 vl->type_instance);
295         if ((ds->ds[index].type != DS_TYPE_GAUGE) && (rates != NULL))
296         {
297                 riemann_event_add_tag (event, "ds_type:%s:rate",
298                                 DS_TYPE_TO_STRING(ds->ds[index].type));
299         }
300         else
301         {
302                 riemann_event_add_tag (event, "ds_type:%s",
303                                 DS_TYPE_TO_STRING(ds->ds[index].type));
304         }
305         riemann_event_add_tag (event, "ds_name:%s", ds->ds[index].name);
306         riemann_event_add_tag (event, "ds_index:%zu", index);
308         for (i = 0; i < riemann_tags_num; i++)
309                 riemann_event_add_tag (event, "%s", riemann_tags[i]);
311         if (ds->ds[index].type == DS_TYPE_GAUGE)
312         {
313                 event->has_metric_d = 1;
314                 event->metric_d = (double) vl->values[index].gauge;
315         }
316         else if (rates != NULL)
317         {
318                 event->has_metric_d = 1;
319                 event->metric_d = (double) rates[index];
320         }
321         else
322         {
323                 event->has_metric_sint64 = 1;
324                 if (ds->ds[index].type == DS_TYPE_DERIVE)
325                         event->metric_sint64 = (int64_t) vl->values[index].derive;
326                 else if (ds->ds[index].type == DS_TYPE_ABSOLUTE)
327                         event->metric_sint64 = (int64_t) vl->values[index].absolute;
328                 else
329                         event->metric_sint64 = (int64_t) vl->values[index].counter;
330         }
332         format_name (name_buffer, sizeof (name_buffer),
333                         /* host = */ "", vl->plugin, vl->plugin_instance,
334                         vl->type, vl->type_instance);
335         if (ds->ds_num > 1)
336                 ssnprintf (service_buffer, sizeof (service_buffer),
337                                 "%s/%s", &name_buffer[1], ds->ds[index].name);
338         else
339                 sstrncpy (service_buffer, &name_buffer[1],
340                                 sizeof (service_buffer));
342         event->service = strdup (service_buffer);
344         DEBUG ("write_riemann plugin: Successfully created protobuf for metric: "
345                         "host = \"%s\", service = \"%s\"",
346                         event->host, event->service);
347         return (event);
348 } /* }}} Event *riemann_value_to_protobuf */
350 static Msg *riemann_value_list_to_protobuf (struct riemann_host const *host, /* {{{ */
351                 data_set_t const *ds,
352                 value_list_t const *vl)
354         Msg *msg;
355         size_t i;
356         gauge_t *rates = NULL;
358         /* Initialize the Msg structure. */
359         msg = malloc (sizeof (*msg));
360         if (msg == NULL)
361         {
362                 ERROR ("write_riemann plugin: malloc failed.");
363                 return (NULL);
364         }
365         memset (msg, 0, sizeof (*msg));
366         msg__init (msg);
368         /* Set up events. First, the list of pointers. */
369         msg->n_events = (size_t) vl->values_len;
370         msg->events = calloc (msg->n_events, sizeof (*msg->events));
371         if (msg->events == NULL)
372         {
373                 ERROR ("write_riemann plugin: calloc failed.");
374                 riemann_msg_protobuf_free (msg);
375                 return (NULL);
376         }
378         if (host->store_rates)
379         {
380                 rates = uc_get_rate (ds, vl);
381                 if (rates == NULL)
382                 {
383                         ERROR ("write_riemann plugin: uc_get_rate failed.");
384                         riemann_msg_protobuf_free (msg);
385                         return (NULL);
386                 }
387         }
389         for (i = 0; i < msg->n_events; i++)
390         {
391                 msg->events[i] = riemann_value_to_protobuf (host, ds, vl,
392                                 (int) i, rates);
393                 if (msg->events[i] == NULL)
394                 {
395                         riemann_msg_protobuf_free (msg);
396                         sfree (rates);
397                         return (NULL);
398                 }
399         }
401         sfree (rates);
402         return (msg);
403 } /* }}} Msg *riemann_value_list_to_protobuf */
405 static int
406 riemann_notification(const notification_t *n, user_data_t *ud)
408         int                      status;
409         struct riemann_host     *host = ud->data;
410         Msg                     *msg;
412         msg = riemann_notification_to_protobuf (host, n);
413         if (msg == NULL)
414                 return (-1);
416         status = riemann_send (host, msg);
417         if (status != 0)
418                 ERROR ("write_riemann plugin: riemann_send failed with status %i",
419                                 status);
421         riemann_msg_protobuf_free (msg);
422         return (status);
423 } /* }}} int riemann_notification */
425 static int
426 riemann_write(const data_set_t *ds,
427               const value_list_t *vl,
428               user_data_t *ud)
430         int                      status;
431         struct riemann_host     *host = ud->data;
432         Msg                     *msg;
434         msg = riemann_value_list_to_protobuf (host, ds, vl);
435         if (msg == NULL)
436                 return (-1);
438         status = riemann_send (host, msg);
439         if (status != 0)
440                 ERROR ("write_riemann plugin: riemann_send failed with status %i",
441                                 status);
443         riemann_msg_protobuf_free (msg);
444         return status;
447 /* host->lock must be held when calling this function. */
448 static int
449 riemann_connect(struct riemann_host *host)
451         int                      e;
452         struct addrinfo         *ai, *res, hints;
453         char const              *node;
454         char const              *service;
456         if (host->flags & F_CONNECT)
457                 return 0;
459         memset(&hints, 0, sizeof(hints));
460         memset(&service, 0, sizeof(service));
461         hints.ai_family = AF_UNSPEC;
462         hints.ai_socktype = SOCK_DGRAM;
463 #ifdef AI_ADDRCONFIG
464         hints.ai_flags |= AI_ADDRCONFIG;
465 #endif
467         node = (host->node != NULL) ? host->node : RIEMANN_HOST;
468         service = (host->service != NULL) ? host->service : RIEMANN_PORT;
470         if ((e = getaddrinfo(node, service, &hints, &res)) != 0) {
471                 ERROR ("write_riemann plugin: Unable to resolve host \"%s\": %s",
472                         node, gai_strerror(e));
473                 return -1;
474         }
476         host->s = -1;
477         for (ai = res; ai != NULL; ai = ai->ai_next) {
478                 if ((host->s = socket(ai->ai_family,
479                                       ai->ai_socktype,
480                                       ai->ai_protocol)) == -1) {
481                         continue;
482                 }
484                 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
485                         close(host->s);
486                         host->s = -1;
487                         continue;
488                 }
490                 host->flags |= F_CONNECT;
491                 DEBUG("write_riemann plugin: got a succesful connection for: %s:%s",
492                                 node, service);
493                 break;
494         }
496         freeaddrinfo(res);
498         if (host->s < 0) {
499                 WARNING("write_riemann plugin: Unable to connect to Riemann at %s:%s",
500                                 node, service);
501                 return -1;
502         }
503         return 0;
506 /* host->lock must be held when calling this function. */
507 static int
508 riemann_disconnect (struct riemann_host *host)
510         if ((host->flags & F_CONNECT) == 0)
511                 return (0);
513         close (host->s);
514         host->s = -1;
515         host->flags &= ~F_CONNECT;
517         return (0);
520 static void
521 riemann_free(void *p)
523         struct riemann_host     *host = p;
525         if (host == NULL)
526                 return;
528         pthread_mutex_lock (&host->lock);
530         host->reference_count--;
531         if (host->reference_count > 0)
532         {
533                 pthread_mutex_unlock (&host->lock);
534                 return;
535         }
537         riemann_disconnect (host);
539         sfree(host->service);
540         pthread_mutex_destroy (&host->lock);
541         sfree(host);
544 static int
545 riemann_config_node(oconfig_item_t *ci)
547         struct riemann_host     *host = NULL;
548         int                      status = 0;
549         int                      i;
550         oconfig_item_t          *child;
551         char                     callback_name[DATA_MAX_NAME_LEN];
552         user_data_t              ud;
554         if ((host = calloc(1, sizeof (*host))) == NULL) {
555                 ERROR ("write_riemann plugin: calloc failed.");
556                 return ENOMEM;
557         }
558         pthread_mutex_init (&host->lock, NULL);
559         host->reference_count = 1;
560         host->node = NULL;
561         host->service = NULL;
562         host->store_rates = 1;
564         status = cf_util_get_string (ci, &host->name);
565         if (status != 0) {
566                 WARNING("write_riemann plugin: Required host name is missing.");
567                 riemann_free (host);
568                 return -1;
569         }
571         for (i = 0; i < ci->children_num; i++) {
572                 /*
573                  * The code here could be simplified but makes room
574                  * for easy adding of new options later on.
575                  */
576                 child = &ci->children[i];
577                 status = 0;
579                 if (strcasecmp ("Host", child->key) == 0) {
580                         status = cf_util_get_string (child, &host->node);
581                         if (status != 0)
582                                 break;
583                 } else if (strcasecmp ("Port", child->key) == 0) {
584                         status = cf_util_get_service (child, &host->service);
585                         if (status != 0) {
586                                 ERROR ("write_riemann plugin: Invalid argument "
587                                                 "configured for the \"Port\" "
588                                                 "option.");
589                                 break;
590                         }
591                 } else if (strcasecmp ("StoreRates", child->key) == 0) {
592                         status = cf_util_get_boolean (child, &host->store_rates);
593                         if (status != 0)
594                                 break;
595                 } else {
596                         WARNING("write_riemann plugin: ignoring unknown config "
597                                 "option: \"%s\"", child->key);
598                 }
599         }
600         if (status != 0) {
601                 riemann_free (host);
602                 return status;
603         }
605         ssnprintf (callback_name, sizeof (callback_name), "write_riemann/%s",
606                         host->name);
607         ud.data = host;
608         ud.free_func = riemann_free;
610         pthread_mutex_lock (&host->lock);
612         status = plugin_register_write (callback_name, riemann_write, &ud);
613         if (status != 0)
614                 WARNING ("write_riemann plugin: plugin_register_write (\"%s\") "
615                                 "failed with status %i.",
616                                 callback_name, status);
617         else /* success */
618                 host->reference_count++;
620         status = plugin_register_notification (callback_name,
621                         riemann_notification, &ud);
622         if (status != 0)
623                 WARNING ("write_riemann plugin: plugin_register_notification (\"%s\") "
624                                 "failed with status %i.",
625                                 callback_name, status);
626         else /* success */
627                 host->reference_count++;
629         if (host->reference_count <= 1)
630         {
631                 /* Both callbacks failed => free memory.
632                  * We need to unlock here, because riemann_free() will lock.
633                  * This is not a race condition, because we're the only one
634                  * holding a reference. */
635                 pthread_mutex_unlock (&host->lock);
636                 riemann_free (host);
637                 return (-1);
638         }
640         host->reference_count--;
641         pthread_mutex_unlock (&host->lock);
643         return status;
646 static int
647 riemann_config(oconfig_item_t *ci)
649         int              i;
650         oconfig_item_t  *child;
651         int              status;
653         for (i = 0; i < ci->children_num; i++)  {
654                 child = &ci->children[i];
656                 if (strcasecmp("Node", child->key) == 0) {
657                         riemann_config_node (child);
658                 } else if (strcasecmp(child->key, "tag") == 0) {
659                         char *tmp = NULL;
660                         status = cf_util_get_string(child, &tmp);
661                         if (status != 0)
662                                 continue;
664                         strarray_add (&riemann_tags, &riemann_tags_num, tmp);
665                         DEBUG("write_riemann plugin: Got tag: %s", tmp);
666                         sfree (tmp);
667                 } else {
668                         WARNING ("write_riemann plugin: Ignoring unknown "
669                                  "configuration option \"%s\" at top level.",
670                                  child->key);
671                 }
672         }
673         return (0);
676 void
677 module_register(void)
679         plugin_register_complex_config ("write_riemann", riemann_config);
682 /* vim: set sw=8 sts=8 ts=8 noet : */