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