Merge branch 'pyr/riemann'
[collectd.git] / src / write_riemann.c
1 /*
2  * collectd - src/write_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 "utils_cache.h"
25 #include "riemann.pb-c.h"
26
27 #include <sys/socket.h>
28 #include <arpa/inet.h>
29 #include <errno.h>
30 #include <netdb.h>
31 #include <inttypes.h>
32 #include <pthread.h>
33
34 #define RIEMANN_HOST            "localhost"
35 #define RIEMANN_PORT            "5555"
36
37 struct riemann_host {
38         char                    *name;
39 #define F_CONNECT                0x01
40         uint8_t                  flags;
41         pthread_mutex_t          lock;
42         _Bool                    store_rates;
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_node(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 ("write_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 ("write_riemann plugin: Sending to Riemann at %s:%s failed: %s",
135                                 (host->node != NULL) ? host->node : RIEMANN_HOST,
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 ("write_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 ("write_riemann plugin: malloc failed.");
187                 sfree (msg);
188                 return (NULL);
189         }
190
191         event = malloc (sizeof (*event));
192         if (event == NULL)
193         {
194                 ERROR ("write_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 ("write_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 ("write_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 (2 * vl->interval);
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         if ((ds->ds[index].type != DS_TYPE_GAUGE) && (rates != NULL))
292         {
293                 riemann_event_add_tag (event, "ds_type:%s:rate",
294                                 DS_TYPE_TO_STRING(ds->ds[index].type));
295         }
296         else
297         {
298                 riemann_event_add_tag (event, "ds_type:%s",
299                                 DS_TYPE_TO_STRING(ds->ds[index].type));
300         }
301         riemann_event_add_tag (event, "ds_name:%s", ds->ds[index].name);
302         riemann_event_add_tag (event, "ds_index:%zu", index);
303
304         for (i = 0; i < riemann_tags_num; i++)
305                 riemann_event_add_tag (event, "%s", riemann_tags[i]);
306
307         if (ds->ds[index].type == DS_TYPE_GAUGE)
308         {
309                 event->has_metric_d = 1;
310                 event->metric_d = (double) vl->values[index].gauge;
311         }
312         else if (rates != NULL)
313         {
314                 event->has_metric_d = 1;
315                 event->metric_d = (double) rates[index];
316         }
317         else
318         {
319                 event->has_metric_sint64 = 1;
320                 if (ds->ds[index].type == DS_TYPE_DERIVE)
321                         event->metric_sint64 = (int64_t) vl->values[index].derive;
322                 else if (ds->ds[index].type == DS_TYPE_ABSOLUTE)
323                         event->metric_sint64 = (int64_t) vl->values[index].absolute;
324                 else
325                         event->metric_sint64 = (int64_t) vl->values[index].counter;
326         }
327
328         /* TODO: Use FORMAT_VL() here. */
329         ssnprintf (service_buffer, sizeof(service_buffer),
330                         "%s-%s-%s-%s-%s", vl->plugin, vl->plugin_instance,
331                         vl->type, vl->type_instance, ds->ds[index].name);
332         event->service = strdup (service_buffer);
333
334         DEBUG ("write_riemann plugin: Successfully created protobuf for metric: "
335                         "host = \"%s\", service = \"%s\"",
336                         event->host, event->service);
337         return (event);
338 } /* }}} Event *riemann_value_to_protobuf */
339
340 static Msg *riemann_value_list_to_protobuf (struct riemann_host const *host, /* {{{ */
341                 data_set_t const *ds,
342                 value_list_t const *vl)
343 {
344         Msg *msg;
345         size_t i;
346         gauge_t *rates = NULL;
347
348         /* Initialize the Msg structure. */
349         msg = malloc (sizeof (*msg));
350         if (msg == NULL)
351         {
352                 ERROR ("write_riemann plugin: malloc failed.");
353                 return (NULL);
354         }
355         memset (msg, 0, sizeof (*msg));
356         msg__init (msg);
357
358         /* Set up events. First, the list of pointers. */
359         msg->n_events = (size_t) vl->values_len;
360         msg->events = calloc (msg->n_events, sizeof (*msg->events));
361         if (msg->events == NULL)
362         {
363                 ERROR ("write_riemann plugin: calloc failed.");
364                 riemann_msg_protobuf_free (msg);
365                 return (NULL);
366         }
367
368         if (host->store_rates)
369         {
370                 rates = uc_get_rate (ds, vl);
371                 if (rates == NULL)
372                 {
373                         ERROR ("write_riemann plugin: uc_get_rate failed.");
374                         riemann_msg_protobuf_free (msg);
375                         return (NULL);
376                 }
377         }
378
379         for (i = 0; i < msg->n_events; i++)
380         {
381                 msg->events[i] = riemann_value_to_protobuf (host, ds, vl,
382                                 (int) i, rates);
383                 if (msg->events[i] == NULL)
384                 {
385                         riemann_msg_protobuf_free (msg);
386                         sfree (rates);
387                         return (NULL);
388                 }
389         }
390
391         sfree (rates);
392         return (msg);
393 } /* }}} Msg *riemann_value_list_to_protobuf */
394
395 static int
396 riemann_notification(const notification_t *n, user_data_t *ud)
397 {
398         int                      status;
399         struct riemann_host     *host = ud->data;
400         Msg                     *msg;
401
402         msg = riemann_notification_to_protobuf (host, n);
403         if (msg == NULL)
404                 return (-1);
405
406         status = riemann_send (host, msg);
407         if (status != 0)
408                 ERROR ("write_riemann plugin: riemann_send failed with status %i",
409                                 status);
410
411         riemann_msg_protobuf_free (msg);
412         return (status);
413 } /* }}} int riemann_notification */
414
415 static int
416 riemann_write(const data_set_t *ds,
417               const value_list_t *vl,
418               user_data_t *ud)
419 {
420         int                      status;
421         struct riemann_host     *host = ud->data;
422         Msg                     *msg;
423
424         msg = riemann_value_list_to_protobuf (host, ds, vl);
425         if (msg == NULL)
426                 return (-1);
427
428         status = riemann_send (host, msg);
429         if (status != 0)
430                 ERROR ("write_riemann plugin: riemann_send failed with status %i",
431                                 status);
432
433         riemann_msg_protobuf_free (msg);
434         return status;
435 }
436
437 /* host->lock must be held when calling this function. */
438 static int
439 riemann_connect(struct riemann_host *host)
440 {
441         int                      e;
442         struct addrinfo         *ai, *res, hints;
443         char const              *node;
444         char const              *service;
445
446         if (host->flags & F_CONNECT)
447                 return 0;
448
449         memset(&hints, 0, sizeof(hints));
450         memset(&service, 0, sizeof(service));
451         hints.ai_family = PF_UNSPEC;
452         hints.ai_socktype = SOCK_DGRAM;
453 #ifdef AI_ADDRCONFIG
454         hints.ai_flags |= AI_ADDRCONFIG;
455 #endif
456
457         node = (host->node != NULL) ? host->node : RIEMANN_HOST;
458         service = (host->service != NULL) ? host->service : RIEMANN_PORT;
459
460         if ((e = getaddrinfo(node, service, &hints, &res)) != 0) {
461                 ERROR ("write_riemann plugin: Unable to resolve host \"%s\": %s",
462                         node, gai_strerror(e));
463                 return -1;
464         }
465
466         host->s = -1;
467         for (ai = res; ai != NULL; ai = ai->ai_next) {
468                 if ((host->s = socket(ai->ai_family,
469                                       ai->ai_socktype,
470                                       ai->ai_protocol)) == -1) {
471                         continue;
472                 }
473
474                 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
475                         close(host->s);
476                         host->s = -1;
477                         continue;
478                 }
479
480                 host->flags |= F_CONNECT;
481                 DEBUG("write_riemann plugin: got a succesful connection for: %s:%s",
482                                 node, service);
483                 break;
484         }
485
486         freeaddrinfo(res);
487
488         if (host->s < 0) {
489                 WARNING("write_riemann plugin: Unable to connect to Riemann at %s:%s",
490                                 node, service);
491                 return -1;
492         }
493         return 0;
494 }
495
496 /* host->lock must be held when calling this function. */
497 static int
498 riemann_disconnect (struct riemann_host *host)
499 {
500         if ((host->flags & F_CONNECT) == 0)
501                 return (0);
502
503         close (host->s);
504         host->s = -1;
505         host->flags &= ~F_CONNECT;
506
507         return (0);
508 }
509
510 static void
511 riemann_free(void *p)
512 {
513         struct riemann_host     *host = p;
514
515         if (host == NULL)
516                 return;
517
518         pthread_mutex_lock (&host->lock);
519
520         host->reference_count--;
521         if (host->reference_count > 0)
522         {
523                 pthread_mutex_unlock (&host->lock);
524                 return;
525         }
526
527         riemann_disconnect (host);
528
529         sfree(host->service);
530         pthread_mutex_destroy (&host->lock);
531         sfree(host);
532 }
533
534 static int
535 riemann_config_node(oconfig_item_t *ci)
536 {
537         struct riemann_host     *host = NULL;
538         int                      status = 0;
539         int                      i;
540         oconfig_item_t          *child;
541         char                     callback_name[DATA_MAX_NAME_LEN];
542         user_data_t              ud;
543
544         if ((host = calloc(1, sizeof (*host))) == NULL) {
545                 ERROR ("write_riemann plugin: calloc failed.");
546                 return ENOMEM;
547         }
548         pthread_mutex_init (&host->lock, NULL);
549         host->reference_count = 1;
550         host->node = NULL;
551         host->service = NULL;
552         host->store_rates = 1;
553
554         status = cf_util_get_string (ci, &host->name);
555         if (status != 0) {
556                 WARNING("write_riemann plugin: Required host name is missing.");
557                 riemann_free (host);
558                 return -1;
559         }
560
561         for (i = 0; i < ci->children_num; i++) {
562                 /*
563                  * The code here could be simplified but makes room
564                  * for easy adding of new options later on.
565                  */
566                 child = &ci->children[i];
567                 status = 0;
568
569                 if (strcasecmp ("Host", child->key) == 0) {
570                         status = cf_util_get_string (child, &host->node);
571                         if (status != 0)
572                                 break;
573                 } else if (strcasecmp ("Port", child->key) == 0) {
574                         status = cf_util_get_service (child, &host->service);
575                         if (status != 0) {
576                                 ERROR ("write_riemann plugin: Invalid argument "
577                                                 "configured for the \"Port\" "
578                                                 "option.");
579                                 break;
580                         }
581                 } else if (strcasecmp ("StoreRates", child->key) == 0) {
582                         status = cf_util_get_boolean (ci, &host->store_rates);
583                         if (status != 0)
584                                 break;
585                 } else {
586                         WARNING("write_riemann plugin: ignoring unknown config "
587                                 "option: \"%s\"", child->key);
588                 }
589         }
590         if (status != 0) {
591                 riemann_free (host);
592                 return status;
593         }
594
595         ssnprintf (callback_name, sizeof (callback_name), "write_riemann/%s",
596                         host->name);
597         ud.data = host;
598         ud.free_func = riemann_free;
599
600         pthread_mutex_lock (&host->lock);
601
602         status = plugin_register_write (callback_name, riemann_write, &ud);
603         if (status != 0)
604                 WARNING ("write_riemann plugin: plugin_register_write (\"%s\") "
605                                 "failed with status %i.",
606                                 callback_name, status);
607         else /* success */
608                 host->reference_count++;
609
610         status = plugin_register_notification (callback_name,
611                         riemann_notification, &ud);
612         if (status != 0)
613                 WARNING ("write_riemann plugin: plugin_register_notification (\"%s\") "
614                                 "failed with status %i.",
615                                 callback_name, status);
616         else /* success */
617                 host->reference_count++;
618
619         if (host->reference_count <= 1)
620         {
621                 /* Both callbacks failed => free memory.
622                  * We need to unlock here, because riemann_free() will lock.
623                  * This is not a race condition, because we're the only one
624                  * holding a reference. */
625                 pthread_mutex_unlock (&host->lock);
626                 riemann_free (host);
627                 return (-1);
628         }
629
630         host->reference_count--;
631         pthread_mutex_unlock (&host->lock);
632
633         return status;
634 }
635
636 static int
637 riemann_config(oconfig_item_t *ci)
638 {
639         int              i;
640         oconfig_item_t  *child;
641         int              status;
642
643         for (i = 0; i < ci->children_num; i++)  {
644                 child = &ci->children[i];
645
646                 if (strcasecmp("Node", child->key) == 0) {
647                         riemann_config_node (child);
648                 } else if (strcasecmp(child->key, "tag") == 0) {
649                         char *tmp = NULL;
650                         status = cf_util_get_string(child, &tmp);
651                         if (status != 0)
652                                 continue;
653
654                         strarray_add (&riemann_tags, &riemann_tags_num, tmp);
655                         DEBUG("write_riemann plugin: Got tag: %s", tmp);
656                         sfree (tmp);
657                 } else {
658                         WARNING ("write_riemann plugin: Ignoring unknown "
659                                  "configuration option \"%s\" at top level.",
660                                  child->key);
661                 }
662         }
663         return (0);
664 }
665
666 void
667 module_register(void)
668 {
669         plugin_register_complex_config ("write_riemann", riemann_config);
670 }
671
672 /* vim: set sw=8 sts=8 ts=8 noet : */