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