8ddc2eb6d19bd3e2ad4a284ebe75f540f21fa809
[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                     name[DATA_MAX_NAME_LEN];
44         int                      port;
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:%d failed: %s",
121                                 host->name, host->port,
122                                 sstrerror (errno, errbuf, sizeof (errbuf)));
123                 riemann_disconnect (host);
124                 sfree (buffer);
125                 return -1;
126         }
127
128         sfree (buffer);
129         return 0;
130 }
131
132 static int riemann_event_add_tag (Event *event, /* {{{ */
133                 char const *format, ...)
134 {
135         va_list ap;
136         char buffer[1024];
137         size_t ret;
138
139         char **tmp;
140
141         tmp = realloc (event->tags, (event->n_tags + 1) * sizeof (*event->tags));
142         if (tmp == NULL)
143                 return (ENOMEM);
144         event->tags = tmp;
145
146         va_start (ap, format);
147         ret = vsnprintf (buffer, sizeof (buffer), format, ap);
148         if (ret >= sizeof (buffer))
149                 ret = sizeof (buffer) - 1;
150         buffer[ret] = 0;
151         va_end (ap);
152
153         event->tags[event->n_tags] = strdup (buffer);
154         if (event->tags[event->n_tags] == NULL)
155                 return (ENOMEM);
156         event->n_tags++;
157         return (0);
158 } /* }}} int riemann_event_add_tag */
159
160 static Msg *riemann_notification_to_protobuf (struct riemann_host *host, /* {{{ */
161                 notification_t const *n)
162 {
163         Msg *msg;
164         Event *event;
165         char service_buffer[6 * DATA_MAX_NAME_LEN];
166         char const *severity;
167         notification_meta_t *meta;
168         int i;
169
170         msg = malloc (sizeof (*msg));
171         if (msg == NULL)
172         {
173                 ERROR ("riemann plugin: malloc failed.");
174                 return (NULL);
175         }
176         memset (msg, 0, sizeof (*msg));
177         msg__init (msg);
178
179         msg->events = malloc (sizeof (*msg->events));
180         if (msg->events == NULL)
181         {
182                 ERROR ("riemann plugin: malloc failed.");
183                 sfree (msg);
184                 return (NULL);
185         }
186
187         event = malloc (sizeof (*event));
188         if (event == NULL)
189         {
190                 ERROR ("riemann plugin: malloc failed.");
191                 sfree (msg->events);
192                 sfree (msg);
193                 return (NULL);
194         }
195         memset (event, 0, sizeof (*event));
196         event__init (event);
197
198         msg->events[0] = event;
199         msg->n_events = 1;
200
201         event->host = strdup (n->host);
202         event->time = CDTIME_T_TO_TIME_T (n->time);
203         event->has_time = 1;
204
205         switch (n->severity)
206         {
207                 case NOTIF_OKAY:        severity = "okay"; break;
208                 case NOTIF_WARNING:     severity = "warning"; break;
209                 case NOTIF_FAILURE:     severity = "failure"; break;
210                 default:                severity = "unknown";
211         }
212         event->state = strdup (severity);
213
214         riemann_event_add_tag (event, "notification");
215         if (n->plugin[0] != 0)
216                 riemann_event_add_tag (event, "plugin:%s", n->plugin);
217         if (n->plugin_instance[0] != 0)
218                 riemann_event_add_tag (event, "plugin_instance:%s",
219                                 n->plugin_instance);
220
221         if (n->type[0] != 0)
222                 riemann_event_add_tag (event, "type:%s", n->type);
223         if (n->type_instance[0] != 0)
224                 riemann_event_add_tag (event, "type_instance:%s",
225                                 n->type_instance);
226
227         for (i = 0; i < riemann_tagcount; i++)
228                 riemann_event_add_tag (event, "%s", riemann_tags[i]);
229
230         /* TODO: Use FORMAT_VL() here. */
231         ssnprintf (service_buffer, sizeof(service_buffer),
232                         "%s-%s-%s-%s", n->plugin, n->plugin_instance,
233                         n->type, n->type_instance);
234         event->service = strdup (service_buffer);
235
236         /* Pull in values from threshold */
237         for (meta = n->meta; meta != NULL; meta = meta->next)
238         {
239                 if (strcasecmp ("CurrentValue", meta->name) != 0)
240                         continue;
241
242                 event->metric_d = meta->nm_value.nm_double;
243                 event->has_metric_d = 1;
244                 break;
245         }
246
247         DEBUG ("riemann plugin: Successfully created protobuf for notification: "
248                         "host = \"%s\", service = \"%s\", state = \"%s\"",
249                         event->host, event->service, event->state);
250         return (msg);
251 } /* }}} Msg *riemann_notification_to_protobuf */
252
253 static Event *riemann_value_to_protobuf (struct riemann_host *host, /* {{{ */
254                 data_set_t const *ds,
255                 value_list_t const *vl, size_t index,
256                 gauge_t const *rates)
257 {
258         Event *event;
259         char service_buffer[6 * DATA_MAX_NAME_LEN];
260         int i;
261
262         event = malloc (sizeof (*event));
263         if (event == NULL)
264         {
265                 ERROR ("riemann plugin: malloc failed.");
266                 return (NULL);
267         }
268         memset (event, 0, sizeof (*event));
269         event__init (event);
270
271         event->host = strdup (vl->host);
272         event->time = CDTIME_T_TO_TIME_T (vl->time);
273         event->has_time = 1;
274         event->ttl = CDTIME_T_TO_TIME_T (vl->interval) + host->delay;
275         event->has_ttl = 1;
276
277         riemann_event_add_tag (event, "plugin:%s", vl->plugin);
278         if (vl->plugin_instance[0] != 0)
279                 riemann_event_add_tag (event, "plugin_instance:%s",
280                                 vl->plugin_instance);
281
282         riemann_event_add_tag (event, "type:%s", vl->type);
283         if (vl->type_instance[0] != 0)
284                 riemann_event_add_tag (event, "type_instance:%s",
285                                 vl->type_instance);
286
287         riemann_event_add_tag (event, "ds_type:%s",
288                         DS_TYPE_TO_STRING(ds->ds[index].type));
289         riemann_event_add_tag (event, "ds_name:%s", ds->ds[index].name);
290         riemann_event_add_tag (event, "ds_index:%zu", index);
291
292         for (i = 0; i < riemann_tagcount; i++)
293                 riemann_event_add_tag (event, "%s", riemann_tags[i]);
294
295         if (rates != NULL)
296         {
297                 event->has_metric_d = 1;
298                 event->metric_d = (double) rates[index];
299         }
300         else if (ds->ds[index].type == DS_TYPE_GAUGE)
301         {
302                 event->has_metric_d = 1;
303                 event->metric_d = (double) vl->values[index].gauge;
304         }
305         else
306         {
307                 event->has_metric_sint64 = 1;
308                 if (ds->ds[index].type == DS_TYPE_DERIVE)
309                         event->metric_sint64 = (int64_t) vl->values[index].derive;
310                 else if (ds->ds[index].type == DS_TYPE_ABSOLUTE)
311                         event->metric_sint64 = (int64_t) vl->values[index].absolute;
312                 else
313                         event->metric_sint64 = (int64_t) vl->values[index].counter;
314         }
315
316         /* TODO: Use FORMAT_VL() here. */
317         ssnprintf (service_buffer, sizeof(service_buffer),
318                         "%s-%s-%s-%s-%s", vl->plugin, vl->plugin_instance,
319                         vl->type, vl->type_instance, ds->ds[i].name);
320         event->service = strdup (service_buffer);
321
322         DEBUG ("riemann plugin: Successfully created protobuf for metric: "
323                         "host = \"%s\", service = \"%s\"",
324                         event->host, event->service);
325         return (event);
326 } /* }}} Event *riemann_value_to_protobuf */
327
328 static Msg *riemann_value_list_to_protobuf (struct riemann_host *host, /* {{{ */
329                 data_set_t const *ds,
330                 value_list_t const *vl)
331 {
332         Msg *msg;
333         size_t i;
334
335         /* Initialize the Msg structure. */
336         msg = malloc (sizeof (*msg));
337         if (msg == NULL)
338         {
339                 ERROR ("riemann plugin: malloc failed.");
340                 return (NULL);
341         }
342         memset (msg, 0, sizeof (*msg));
343         msg__init (msg);
344
345         /* Set up events. First, the list of pointers. */
346         msg->n_events = (size_t) vl->values_len;
347         msg->events = calloc (msg->n_events, sizeof (*msg->events));
348         if (msg->events == NULL)
349         {
350                 ERROR ("riemann plugin: calloc failed.");
351                 riemann_msg_protobuf_free (msg);
352                 return (NULL);
353         }
354
355         for (i = 0; i < msg->n_events; i++)
356         {
357                 msg->events[i] = riemann_value_to_protobuf (host, ds, vl,
358                                 (int) i, /* rates = */ NULL);
359                 if (msg->events[i])
360                 {
361                         riemann_msg_protobuf_free (msg);
362                         return (NULL);
363                 }
364         }
365
366         return (msg);
367 } /* }}} Msg *riemann_value_list_to_protobuf */
368
369 static int
370 riemann_notification(const notification_t *n, user_data_t *ud)
371 {
372         int                      status;
373         struct riemann_host     *host = ud->data;
374         Msg                     *msg;
375
376         msg = riemann_notification_to_protobuf (host, n);
377         if (msg == NULL)
378                 return (-1);
379
380         status = riemann_send (host, msg);
381         if (status != 0)
382                 ERROR ("riemann plugin: riemann_send failed with status %i",
383                                 status);
384
385         riemann_msg_protobuf_free (msg);
386         return (status);
387 } /* }}} int riemann_notification */
388
389 static int
390 riemann_write(const data_set_t *ds,
391               const value_list_t *vl,
392               user_data_t *ud)
393 {
394         int                      status;
395         struct riemann_host     *host = ud->data;
396         Msg                     *msg;
397
398         if ((status = riemann_connect(host)) != 0)
399                 return status;
400
401         msg = riemann_value_list_to_protobuf (host, ds, vl);
402         if (msg == NULL)
403                 return (-1);
404
405         status = riemann_send (host, msg);
406         if (status != 0)
407                 ERROR ("riemann plugin: riemann_send failed with status %i",
408                                 status);
409
410         riemann_msg_protobuf_free (msg);
411         return status;
412 }
413
414 static int
415 riemann_connect(struct riemann_host *host)
416 {
417         int                      e;
418         struct addrinfo         *ai, *res, hints;
419         char                     service[32];
420
421         if (host->flags & F_CONNECT)
422                 return 0;
423
424         memset(&hints, 0, sizeof(hints));
425         memset(&service, 0, sizeof(service));
426         hints.ai_family = PF_UNSPEC;
427         hints.ai_socktype = SOCK_DGRAM;
428
429         ssnprintf(service, sizeof(service), "%d", host->port);
430
431         if ((e = getaddrinfo(host->name, service, &hints, &res)) != 0) {
432                 WARNING("could not resolve host \"%s\": %s",
433                         host->name, gai_strerror(e));
434                 return -1;
435         }
436
437         for (ai = res; ai != NULL; ai = ai->ai_next) {
438                 pthread_mutex_lock(&host->lock);
439                 /*
440                  * check if another thread did not already succesfully connect
441                  */
442                 if (host->flags & F_CONNECT) {
443                         freeaddrinfo(res);
444                         return 0;
445                 }
446
447                 if ((host->s = socket(ai->ai_family,
448                                       ai->ai_socktype,
449                                       ai->ai_protocol)) == -1) {
450                         pthread_mutex_unlock(&host->lock);
451                         WARNING("riemann_connect: could not open socket");
452                         freeaddrinfo(res);
453                         return -1;
454                 }
455
456                 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
457                         close(host->s);
458                         host->flags |= ~F_CONNECT;
459                         pthread_mutex_unlock(&host->lock);
460                         freeaddrinfo(res);
461                         return -1;
462                 }
463                 host->flags |= F_CONNECT;
464                 DEBUG("got a succesful connection for: %s", host->name);
465                 pthread_mutex_unlock(&host->lock);
466                 break;
467         }
468
469         freeaddrinfo(res);
470         if (ai == NULL) {
471                 WARNING("riemann_connect: no suitable hosts found");
472                 return -1;
473         }
474
475         return 0;
476 }
477
478 static int
479 riemann_disconnect (struct riemann_host *host)
480 {
481         if (host == NULL)
482                 return (EINVAL);
483
484         if ((host->flags & F_CONNECT) == 0)
485                 return (0);
486
487         close (host->s);
488         host->s = -1;
489         host->flags &= ~F_CONNECT;
490
491         return (0);
492 }
493
494 static void
495 riemann_free(void *p)
496 {
497         struct riemann_host     *host = p;
498
499         riemann_disconnect (host);
500         sfree(host);
501 }
502
503 static int
504 riemann_config_host(oconfig_item_t *ci)
505 {
506         struct riemann_host     *host = NULL;
507         int                      status = 0;
508         int                      i;
509         oconfig_item_t          *child;
510         char                     w_cb_name[DATA_MAX_NAME_LEN];
511         char                     n_cb_name[DATA_MAX_NAME_LEN];
512         user_data_t              ud;
513
514         if (ci->values_num != 1 ||
515             ci->values[0].type != OCONFIG_TYPE_STRING) {
516                 WARNING("riemann hosts need one string argument");
517                 return -1;
518         }
519
520         if ((host = calloc(1, sizeof (*host))) == NULL) {
521                 WARNING("riemann host allocation failed");
522                 return ENOMEM;
523         }
524
525         if (cf_util_get_string_buffer(ci, host->name,
526                                       sizeof(host->name)) != 0) {
527                 WARNING("riemann host name too long");
528                 sfree(host);
529                 return -1;
530         }
531
532         host->port = RIEMANN_PORT;
533         host->delay = RIEMANN_DELAY;
534         for (i = 0; i < ci->children_num; i++) {
535                 /*
536                  * The code here could be simplified but makes room
537                  * for easy adding of new options later on.
538                  */
539                 child = &ci->children[i];
540                 status = 0;
541
542                 if (strcasecmp(child->key, "port") == 0) {
543                         if ((status = cf_util_get_port_number(child)) < 0) {
544                                 WARNING("invalid port number");
545                                 break;
546                         }
547                         host->port = status;
548                         status = 0;
549                 } else if (strcasecmp(child->key, "delay") == 0) {
550                         if ((status = cf_util_get_int(ci, &host->delay)) != 0)
551                                 break;
552                 } else {
553                         WARNING("riemann plugin: ignoring unknown config "
554                                 "option: \"%s\"", child->key);
555                 }
556         }
557         if (status != 0) {
558                 sfree(host);
559                 return status;
560         }
561
562         pthread_mutex_init(&host->lock, NULL);
563         ssnprintf(w_cb_name, sizeof(w_cb_name), "write-riemann/%s:%d",
564                   host->name, host->port);
565         ssnprintf(n_cb_name, sizeof(n_cb_name), "notification-riemann/%s:%d",
566                   host->name, host->port);
567         DEBUG("riemann w_cb_name: %s", w_cb_name);
568         DEBUG("riemann n_cb_name: %s", n_cb_name);
569         ud.data = host;
570         ud.free_func = riemann_free;
571
572         if ((status = plugin_register_write(w_cb_name, riemann_write, &ud)) != 0)
573                 riemann_free(host);
574
575         if ((status = plugin_register_notification(n_cb_name,
576                                                    riemann_notification,
577                                                    &ud)) != 0) {
578                 plugin_unregister_write(w_cb_name);
579                 riemann_free(host);
580         }
581         return status;
582 }
583
584 static int
585 riemann_config(oconfig_item_t *ci)
586 {
587         int              i;
588         char            *newtag;
589         oconfig_item_t  *child;
590
591         for (i = 0; i < ci->children_num; i++)  {
592                 child = &ci->children[i];
593
594                 if (strcasecmp(child->key, "host") == 0) {
595                         riemann_config_host(child);
596                 } else if (strcasecmp(child->key, "tag") == 0) {
597                         if (riemann_tagcount >= RIEMANN_EXTRA_TAGS) {
598                                 WARNING("riemann plugin: too many tags");
599                                 return -1;
600                         }
601                         newtag = NULL;
602                         cf_util_get_string(child, &newtag);
603                         if (newtag == NULL)
604                                 return -1;
605                         riemann_tags[riemann_tagcount++] = newtag;
606                         DEBUG("riemann_config: got tag: %s", newtag);
607
608                 } else {
609                         WARNING ("riemann plugin: Ignoring unknown "
610                                  "configuration option \"%s\" at top level.",
611                                  child->key);
612                 }
613         }
614         return (0);
615 }
616
617 void
618 module_register(void)
619 {
620         DEBUG("riemann: module_register");
621
622         plugin_register_complex_config ("riemann", riemann_config);
623 }