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