riemann plugin: Add support for service names.
[collectd.git] / src / riemann.c
1 /*
2  * collectd - src/riemann.c
3  *
4  * Copyright (C) 2012  Pierre-Yves Ritschard <pyr@spootnik.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  *
18  */
19
20 #include "collectd.h"
21 #include "plugin.h"
22 #include "common.h"
23 #include "configfile.h"
24 #include "riemann.pb-c.h"
25
26 #include <sys/socket.h>
27 #include <arpa/inet.h>
28 #include <errno.h>
29 #include <netdb.h>
30 #include <inttypes.h>
31 #include <pthread.h>
32
33 #define RIEMANN_DELAY           1
34 #define RIEMANN_PORT            "5555"
35 #define RIEMANN_MAX_TAGS        37
36 #define RIEMANN_EXTRA_TAGS      32
37
38 struct riemann_host {
39 #define F_CONNECT                0x01
40         u_int8_t                 flags;
41         pthread_mutex_t          lock;
42         int                      delay;
43         char                    *node;
44         char                    *service;
45         int                      s;
46 };
47
48 static char     *riemann_tags[RIEMANN_EXTRA_TAGS];
49 static int       riemann_tagcount;
50
51 static int      riemann_send(struct riemann_host *, Msg const *);
52 static int      riemann_notification(const notification_t *, user_data_t *);
53 static int      riemann_write(const data_set_t *, const value_list_t *, user_data_t *);
54 static int      riemann_connect(struct riemann_host *);
55 static int      riemann_disconnect (struct riemann_host *host);
56 static void     riemann_free(void *);
57 static int      riemann_config_host(oconfig_item_t *);
58 static int      riemann_config(oconfig_item_t *);
59 void    module_register(void);
60
61 static void riemann_event_protobuf_free (Event *event) /* {{{ */
62 {
63         size_t i;
64
65         if (event == NULL)
66                 return;
67
68         sfree (event->state);
69         sfree (event->service);
70         sfree (event->host);
71         sfree (event->description);
72
73         for (i = 0; i < event->n_tags; i++)
74                 sfree (event->tags[i]);
75         sfree (event->tags);
76
77         sfree (event);
78 } /* }}} void riemann_event_protobuf_free */
79
80 static void riemann_msg_protobuf_free (Msg *msg) /* {{{ */
81 {
82         size_t i;
83
84         if (msg == NULL)
85                 return;
86
87         for (i = 0; i < msg->n_events; i++)
88         {
89                 riemann_event_protobuf_free (msg->events[i]);
90                 msg->events[i] = NULL;
91         }
92
93         sfree (msg->events);
94         msg->n_events = 0;
95
96         sfree (msg);
97 } /* }}} void riemann_msg_protobuf_free */
98
99 static int
100 riemann_send(struct riemann_host *host, Msg const *msg)
101 {
102         u_char *buffer;
103         size_t  buffer_len;
104         ssize_t status;
105
106         buffer_len = msg__get_packed_size(msg);
107         buffer = malloc (buffer_len);
108         if (buffer == NULL) {
109                 ERROR ("riemann plugin: malloc failed.");
110                 return ENOMEM;
111         }
112         memset (buffer, 0, buffer_len);
113
114         msg__pack(msg, buffer);
115
116         status = swrite (host->s, buffer, buffer_len);
117         if (status != 0)
118         {
119                 char errbuf[1024];
120                 ERROR ("riemann plugin: Sending to Riemann at %s:%s failed: %s",
121                                 host->node,
122                                 (host->service != NULL) ? host->service : RIEMANN_PORT,
123                                 sstrerror (errno, errbuf, sizeof (errbuf)));
124                 riemann_disconnect (host);
125                 sfree (buffer);
126                 return -1;
127         }
128
129         sfree (buffer);
130         return 0;
131 }
132
133 static int riemann_event_add_tag (Event *event, /* {{{ */
134                 char const *format, ...)
135 {
136         va_list ap;
137         char buffer[1024];
138         size_t ret;
139
140         char **tmp;
141
142         tmp = realloc (event->tags, (event->n_tags + 1) * sizeof (*event->tags));
143         if (tmp == NULL)
144                 return (ENOMEM);
145         event->tags = tmp;
146
147         va_start (ap, format);
148         ret = vsnprintf (buffer, sizeof (buffer), format, ap);
149         if (ret >= sizeof (buffer))
150                 ret = sizeof (buffer) - 1;
151         buffer[ret] = 0;
152         va_end (ap);
153
154         event->tags[event->n_tags] = strdup (buffer);
155         if (event->tags[event->n_tags] == NULL)
156                 return (ENOMEM);
157         event->n_tags++;
158         return (0);
159 } /* }}} int riemann_event_add_tag */
160
161 static Msg *riemann_notification_to_protobuf (struct riemann_host *host, /* {{{ */
162                 notification_t const *n)
163 {
164         Msg *msg;
165         Event *event;
166         char service_buffer[6 * DATA_MAX_NAME_LEN];
167         char const *severity;
168         notification_meta_t *meta;
169         int i;
170
171         msg = malloc (sizeof (*msg));
172         if (msg == NULL)
173         {
174                 ERROR ("riemann plugin: malloc failed.");
175                 return (NULL);
176         }
177         memset (msg, 0, sizeof (*msg));
178         msg__init (msg);
179
180         msg->events = malloc (sizeof (*msg->events));
181         if (msg->events == NULL)
182         {
183                 ERROR ("riemann plugin: malloc failed.");
184                 sfree (msg);
185                 return (NULL);
186         }
187
188         event = malloc (sizeof (*event));
189         if (event == NULL)
190         {
191                 ERROR ("riemann plugin: malloc failed.");
192                 sfree (msg->events);
193                 sfree (msg);
194                 return (NULL);
195         }
196         memset (event, 0, sizeof (*event));
197         event__init (event);
198
199         msg->events[0] = event;
200         msg->n_events = 1;
201
202         event->host = strdup (n->host);
203         event->time = CDTIME_T_TO_TIME_T (n->time);
204         event->has_time = 1;
205
206         switch (n->severity)
207         {
208                 case NOTIF_OKAY:        severity = "okay"; break;
209                 case NOTIF_WARNING:     severity = "warning"; break;
210                 case NOTIF_FAILURE:     severity = "failure"; break;
211                 default:                severity = "unknown";
212         }
213         event->state = strdup (severity);
214
215         riemann_event_add_tag (event, "notification");
216         if (n->plugin[0] != 0)
217                 riemann_event_add_tag (event, "plugin:%s", n->plugin);
218         if (n->plugin_instance[0] != 0)
219                 riemann_event_add_tag (event, "plugin_instance:%s",
220                                 n->plugin_instance);
221
222         if (n->type[0] != 0)
223                 riemann_event_add_tag (event, "type:%s", n->type);
224         if (n->type_instance[0] != 0)
225                 riemann_event_add_tag (event, "type_instance:%s",
226                                 n->type_instance);
227
228         for (i = 0; i < riemann_tagcount; i++)
229                 riemann_event_add_tag (event, "%s", riemann_tags[i]);
230
231         /* TODO: Use FORMAT_VL() here. */
232         ssnprintf (service_buffer, sizeof(service_buffer),
233                         "%s-%s-%s-%s", n->plugin, n->plugin_instance,
234                         n->type, n->type_instance);
235         event->service = strdup (service_buffer);
236
237         /* Pull in values from threshold */
238         for (meta = n->meta; meta != NULL; meta = meta->next)
239         {
240                 if (strcasecmp ("CurrentValue", meta->name) != 0)
241                         continue;
242
243                 event->metric_d = meta->nm_value.nm_double;
244                 event->has_metric_d = 1;
245                 break;
246         }
247
248         DEBUG ("riemann plugin: Successfully created protobuf for notification: "
249                         "host = \"%s\", service = \"%s\", state = \"%s\"",
250                         event->host, event->service, event->state);
251         return (msg);
252 } /* }}} Msg *riemann_notification_to_protobuf */
253
254 static Event *riemann_value_to_protobuf (struct riemann_host *host, /* {{{ */
255                 data_set_t const *ds,
256                 value_list_t const *vl, size_t index,
257                 gauge_t const *rates)
258 {
259         Event *event;
260         char service_buffer[6 * DATA_MAX_NAME_LEN];
261         int i;
262
263         event = malloc (sizeof (*event));
264         if (event == NULL)
265         {
266                 ERROR ("riemann plugin: malloc failed.");
267                 return (NULL);
268         }
269         memset (event, 0, sizeof (*event));
270         event__init (event);
271
272         event->host = strdup (vl->host);
273         event->time = CDTIME_T_TO_TIME_T (vl->time);
274         event->has_time = 1;
275         event->ttl = CDTIME_T_TO_TIME_T (vl->interval) + host->delay;
276         event->has_ttl = 1;
277
278         riemann_event_add_tag (event, "plugin:%s", vl->plugin);
279         if (vl->plugin_instance[0] != 0)
280                 riemann_event_add_tag (event, "plugin_instance:%s",
281                                 vl->plugin_instance);
282
283         riemann_event_add_tag (event, "type:%s", vl->type);
284         if (vl->type_instance[0] != 0)
285                 riemann_event_add_tag (event, "type_instance:%s",
286                                 vl->type_instance);
287
288         riemann_event_add_tag (event, "ds_type:%s",
289                         DS_TYPE_TO_STRING(ds->ds[index].type));
290         riemann_event_add_tag (event, "ds_name:%s", ds->ds[index].name);
291         riemann_event_add_tag (event, "ds_index:%zu", index);
292
293         for (i = 0; i < riemann_tagcount; i++)
294                 riemann_event_add_tag (event, "%s", riemann_tags[i]);
295
296         if (rates != NULL)
297         {
298                 event->has_metric_d = 1;
299                 event->metric_d = (double) rates[index];
300         }
301         else if (ds->ds[index].type == DS_TYPE_GAUGE)
302         {
303                 event->has_metric_d = 1;
304                 event->metric_d = (double) vl->values[index].gauge;
305         }
306         else
307         {
308                 event->has_metric_sint64 = 1;
309                 if (ds->ds[index].type == DS_TYPE_DERIVE)
310                         event->metric_sint64 = (int64_t) vl->values[index].derive;
311                 else if (ds->ds[index].type == DS_TYPE_ABSOLUTE)
312                         event->metric_sint64 = (int64_t) vl->values[index].absolute;
313                 else
314                         event->metric_sint64 = (int64_t) vl->values[index].counter;
315         }
316
317         /* TODO: Use FORMAT_VL() here. */
318         ssnprintf (service_buffer, sizeof(service_buffer),
319                         "%s-%s-%s-%s-%s", vl->plugin, vl->plugin_instance,
320                         vl->type, vl->type_instance, ds->ds[i].name);
321         event->service = strdup (service_buffer);
322
323         DEBUG ("riemann plugin: Successfully created protobuf for metric: "
324                         "host = \"%s\", service = \"%s\"",
325                         event->host, event->service);
326         return (event);
327 } /* }}} Event *riemann_value_to_protobuf */
328
329 static Msg *riemann_value_list_to_protobuf (struct riemann_host *host, /* {{{ */
330                 data_set_t const *ds,
331                 value_list_t const *vl)
332 {
333         Msg *msg;
334         size_t i;
335
336         /* Initialize the Msg structure. */
337         msg = malloc (sizeof (*msg));
338         if (msg == NULL)
339         {
340                 ERROR ("riemann plugin: malloc failed.");
341                 return (NULL);
342         }
343         memset (msg, 0, sizeof (*msg));
344         msg__init (msg);
345
346         /* Set up events. First, the list of pointers. */
347         msg->n_events = (size_t) vl->values_len;
348         msg->events = calloc (msg->n_events, sizeof (*msg->events));
349         if (msg->events == NULL)
350         {
351                 ERROR ("riemann plugin: calloc failed.");
352                 riemann_msg_protobuf_free (msg);
353                 return (NULL);
354         }
355
356         for (i = 0; i < msg->n_events; i++)
357         {
358                 msg->events[i] = riemann_value_to_protobuf (host, ds, vl,
359                                 (int) i, /* rates = */ NULL);
360                 if (msg->events[i])
361                 {
362                         riemann_msg_protobuf_free (msg);
363                         return (NULL);
364                 }
365         }
366
367         return (msg);
368 } /* }}} Msg *riemann_value_list_to_protobuf */
369
370 static int
371 riemann_notification(const notification_t *n, user_data_t *ud)
372 {
373         int                      status;
374         struct riemann_host     *host = ud->data;
375         Msg                     *msg;
376
377         msg = riemann_notification_to_protobuf (host, n);
378         if (msg == NULL)
379                 return (-1);
380
381         status = riemann_send (host, msg);
382         if (status != 0)
383                 ERROR ("riemann plugin: riemann_send failed with status %i",
384                                 status);
385
386         riemann_msg_protobuf_free (msg);
387         return (status);
388 } /* }}} int riemann_notification */
389
390 static int
391 riemann_write(const data_set_t *ds,
392               const value_list_t *vl,
393               user_data_t *ud)
394 {
395         int                      status;
396         struct riemann_host     *host = ud->data;
397         Msg                     *msg;
398
399         if ((status = riemann_connect(host)) != 0)
400                 return status;
401
402         msg = riemann_value_list_to_protobuf (host, ds, vl);
403         if (msg == NULL)
404                 return (-1);
405
406         status = riemann_send (host, msg);
407         if (status != 0)
408                 ERROR ("riemann plugin: riemann_send failed with status %i",
409                                 status);
410
411         riemann_msg_protobuf_free (msg);
412         return status;
413 }
414
415 static int
416 riemann_connect(struct riemann_host *host)
417 {
418         int                      e;
419         struct addrinfo         *ai, *res, hints;
420         char const              *service;
421
422         if (host->flags & F_CONNECT)
423                 return 0;
424
425         memset(&hints, 0, sizeof(hints));
426         memset(&service, 0, sizeof(service));
427         hints.ai_family = PF_UNSPEC;
428         hints.ai_socktype = SOCK_DGRAM;
429
430         assert (host->node != NULL);
431         service = (host->service != NULL) ? host->service : RIEMANN_PORT;
432
433         if ((e = getaddrinfo(host->node, service, &hints, &res)) != 0) {
434                 ERROR ("riemann plugin: Unable to resolve host \"%s\": %s",
435                         host->node, gai_strerror(e));
436                 return -1;
437         }
438
439         for (ai = res; ai != NULL; ai = ai->ai_next) {
440                 pthread_mutex_lock(&host->lock);
441                 /*
442                  * check if another thread did not already succesfully connect
443                  */
444                 if (host->flags & F_CONNECT) {
445                         freeaddrinfo(res);
446                         return 0;
447                 }
448
449                 if ((host->s = socket(ai->ai_family,
450                                       ai->ai_socktype,
451                                       ai->ai_protocol)) == -1) {
452                         pthread_mutex_unlock(&host->lock);
453                         WARNING("riemann_connect: could not open socket");
454                         freeaddrinfo(res);
455                         return -1;
456                 }
457
458                 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
459                         close(host->s);
460                         host->flags |= ~F_CONNECT;
461                         pthread_mutex_unlock(&host->lock);
462                         freeaddrinfo(res);
463                         return -1;
464                 }
465                 host->flags |= F_CONNECT;
466                 DEBUG("riemann plugin: got a succesful connection for: %s",
467                                 host->node);
468                 pthread_mutex_unlock(&host->lock);
469                 break;
470         }
471
472         freeaddrinfo(res);
473         if (ai == NULL) {
474                 WARNING("riemann_connect: no suitable hosts found");
475                 return -1;
476         }
477
478         return 0;
479 }
480
481 static int
482 riemann_disconnect (struct riemann_host *host)
483 {
484         if (host == NULL)
485                 return (EINVAL);
486
487         if ((host->flags & F_CONNECT) == 0)
488                 return (0);
489
490         close (host->s);
491         host->s = -1;
492         host->flags &= ~F_CONNECT;
493
494         return (0);
495 }
496
497 static void
498 riemann_free(void *p)
499 {
500         struct riemann_host     *host = p;
501
502         if (host == NULL)
503                 return;
504
505         riemann_disconnect (host);
506
507         sfree(host->service);
508         sfree(host);
509 }
510
511 static int
512 riemann_config_host(oconfig_item_t *ci)
513 {
514         struct riemann_host     *host = NULL;
515         int                      status = 0;
516         int                      i;
517         oconfig_item_t          *child;
518         char                     w_cb_name[DATA_MAX_NAME_LEN];
519         char                     n_cb_name[DATA_MAX_NAME_LEN];
520         user_data_t              ud;
521
522         if (ci->values_num != 1 ||
523             ci->values[0].type != OCONFIG_TYPE_STRING) {
524                 WARNING("riemann hosts need one string argument");
525                 return -1;
526         }
527
528         if ((host = calloc(1, sizeof (*host))) == NULL) {
529                 WARNING("riemann host allocation failed");
530                 return ENOMEM;
531         }
532         pthread_mutex_init(&host->lock, NULL);
533         host->node = NULL;
534         host->service = NULL;
535         host->delay = RIEMANN_DELAY;
536
537         status = cf_util_get_string (ci, &host->node);
538         if (status != 0) {
539                 WARNING("riemann plugin: Required host name is missing.");
540                 riemann_free (host);
541                 return -1;
542         }
543
544         for (i = 0; i < ci->children_num; i++) {
545                 /*
546                  * The code here could be simplified but makes room
547                  * for easy adding of new options later on.
548                  */
549                 child = &ci->children[i];
550                 status = 0;
551
552                 if (strcasecmp(child->key, "port") == 0) {
553                         status = cf_util_get_service (child, &host->service);
554                         if (status != 0) {
555                                 ERROR ("riemann plugin: Invalid argument "
556                                                 "configured for the \"Port\" "
557                                                 "option.");
558                                 break;
559                         }
560                 } else if (strcasecmp(child->key, "delay") == 0) {
561                         if ((status = cf_util_get_int(ci, &host->delay)) != 0)
562                                 break;
563                 } else {
564                         WARNING("riemann plugin: ignoring unknown config "
565                                 "option: \"%s\"", child->key);
566                 }
567         }
568         if (status != 0) {
569                 sfree(host);
570                 return status;
571         }
572
573         ssnprintf(w_cb_name, sizeof(w_cb_name), "write-riemann/%s:%s",
574                   host->node,
575                   (host->service != NULL) ? host->service : RIEMANN_PORT);
576         ssnprintf(n_cb_name, sizeof(n_cb_name), "notification-riemann/%s:%s",
577                   host->node,
578                   (host->service != NULL) ? host->service : RIEMANN_PORT);
579         DEBUG("riemann w_cb_name: %s", w_cb_name);
580         DEBUG("riemann n_cb_name: %s", n_cb_name);
581         ud.data = host;
582         ud.free_func = riemann_free;
583
584         if ((status = plugin_register_write(w_cb_name, riemann_write, &ud)) != 0)
585                 riemann_free(host);
586
587         if ((status = plugin_register_notification(n_cb_name,
588                                                    riemann_notification,
589                                                    &ud)) != 0) {
590                 plugin_unregister_write(w_cb_name);
591                 riemann_free(host);
592         }
593         return status;
594 }
595
596 static int
597 riemann_config(oconfig_item_t *ci)
598 {
599         int              i;
600         char            *newtag;
601         oconfig_item_t  *child;
602
603         for (i = 0; i < ci->children_num; i++)  {
604                 child = &ci->children[i];
605
606                 if (strcasecmp(child->key, "host") == 0) {
607                         riemann_config_host(child);
608                 } else if (strcasecmp(child->key, "tag") == 0) {
609                         if (riemann_tagcount >= RIEMANN_EXTRA_TAGS) {
610                                 WARNING("riemann plugin: too many tags");
611                                 return -1;
612                         }
613                         newtag = NULL;
614                         cf_util_get_string(child, &newtag);
615                         if (newtag == NULL)
616                                 return -1;
617                         riemann_tags[riemann_tagcount++] = newtag;
618                         DEBUG("riemann_config: got tag: %s", newtag);
619
620                 } else {
621                         WARNING ("riemann plugin: Ignoring unknown "
622                                  "configuration option \"%s\" at top level.",
623                                  child->key);
624                 }
625         }
626         return (0);
627 }
628
629 void
630 module_register(void)
631 {
632         DEBUG("riemann: module_register");
633
634         plugin_register_complex_config ("riemann", riemann_config);
635 }
636
637 /* vim: set sw=8 sts=8 ts=8 noet : */