write_riemann plugin: Rename the "riemann" plugin.
[collectd.git] / src / write_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 #ifdef AI_ADDRCONFIG
455         hints.ai_flags |= AI_ADDRCONFIG;
456 #endif
457
458         assert (host->node != NULL);
459         service = (host->service != NULL) ? host->service : RIEMANN_PORT;
460
461         if ((e = getaddrinfo(host->node, service, &hints, &res)) != 0) {
462                 ERROR ("riemann plugin: Unable to resolve host \"%s\": %s",
463                         host->node, gai_strerror(e));
464                 return -1;
465         }
466
467         host->s = -1;
468         for (ai = res; ai != NULL; ai = ai->ai_next) {
469                 if ((host->s = socket(ai->ai_family,
470                                       ai->ai_socktype,
471                                       ai->ai_protocol)) == -1) {
472                         continue;
473                 }
474
475                 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
476                         close(host->s);
477                         host->s = -1;
478                         continue;
479                 }
480
481                 host->flags |= F_CONNECT;
482                 DEBUG("riemann plugin: got a succesful connection for: %s:%s",
483                                 host->node, service);
484                 break;
485         }
486
487         freeaddrinfo(res);
488
489         if (host->s < 0) {
490                 WARNING("riemann plugin: Unable to connect to Riemann at %s:%s",
491                                 host->node, service);
492                 return -1;
493         }
494         return 0;
495 }
496
497 /* host->lock must be held when calling this function. */
498 static int
499 riemann_disconnect (struct riemann_host *host)
500 {
501         if ((host->flags & F_CONNECT) == 0)
502                 return (0);
503
504         close (host->s);
505         host->s = -1;
506         host->flags &= ~F_CONNECT;
507
508         return (0);
509 }
510
511 static void
512 riemann_free(void *p)
513 {
514         struct riemann_host     *host = p;
515
516         if (host == NULL)
517                 return;
518
519         pthread_mutex_lock (&host->lock);
520
521         host->reference_count--;
522         if (host->reference_count > 0)
523         {
524                 pthread_mutex_unlock (&host->lock);
525                 return;
526         }
527
528         riemann_disconnect (host);
529
530         sfree(host->service);
531         pthread_mutex_destroy (&host->lock);
532         sfree(host);
533 }
534
535 static int
536 riemann_config_host(oconfig_item_t *ci)
537 {
538         struct riemann_host     *host = NULL;
539         int                      status = 0;
540         int                      i;
541         oconfig_item_t          *child;
542         char                     w_cb_name[DATA_MAX_NAME_LEN];
543         char                     n_cb_name[DATA_MAX_NAME_LEN];
544         user_data_t              ud;
545
546         if (ci->values_num != 1 ||
547             ci->values[0].type != OCONFIG_TYPE_STRING) {
548                 WARNING("riemann hosts need one string argument");
549                 return -1;
550         }
551
552         if ((host = calloc(1, sizeof (*host))) == NULL) {
553                 WARNING("riemann host allocation failed");
554                 return ENOMEM;
555         }
556         pthread_mutex_init (&host->lock, NULL);
557         host->reference_count = 1;
558         host->node = NULL;
559         host->service = NULL;
560         host->delay = RIEMANN_DELAY;
561
562         status = cf_util_get_string (ci, &host->node);
563         if (status != 0) {
564                 WARNING("riemann plugin: Required host name is missing.");
565                 riemann_free (host);
566                 return -1;
567         }
568
569         for (i = 0; i < ci->children_num; i++) {
570                 /*
571                  * The code here could be simplified but makes room
572                  * for easy adding of new options later on.
573                  */
574                 child = &ci->children[i];
575                 status = 0;
576
577                 if (strcasecmp(child->key, "port") == 0) {
578                         status = cf_util_get_service (child, &host->service);
579                         if (status != 0) {
580                                 ERROR ("riemann plugin: Invalid argument "
581                                                 "configured for the \"Port\" "
582                                                 "option.");
583                                 break;
584                         }
585                 } else if (strcasecmp(child->key, "delay") == 0) {
586                         if ((status = cf_util_get_int(ci, &host->delay)) != 0)
587                                 break;
588                 } else if (strcasecmp ("StoreRates", child->key) == 0) {
589                         status = cf_util_get_boolean (ci, &host->store_rates);
590                         if (status != 0)
591                                 break;
592                 } else {
593                         WARNING("riemann plugin: ignoring unknown config "
594                                 "option: \"%s\"", child->key);
595                 }
596         }
597         if (status != 0) {
598                 riemann_free (host);
599                 return status;
600         }
601
602         ssnprintf(w_cb_name, sizeof(w_cb_name), "write-riemann/%s:%s",
603                   host->node,
604                   (host->service != NULL) ? host->service : RIEMANN_PORT);
605         ssnprintf(n_cb_name, sizeof(n_cb_name), "notification-riemann/%s:%s",
606                   host->node,
607                   (host->service != NULL) ? host->service : RIEMANN_PORT);
608         DEBUG("riemann w_cb_name: %s", w_cb_name);
609         DEBUG("riemann n_cb_name: %s", n_cb_name);
610         ud.data = host;
611         ud.free_func = riemann_free;
612
613         pthread_mutex_lock (&host->lock);
614
615         status = plugin_register_write (w_cb_name, riemann_write, &ud);
616         if (status != 0)
617                 WARNING ("riemann plugin: plugin_register_write (\"%s\") "
618                                 "failed with status %i.",
619                                 w_cb_name, status);
620         else /* success */
621                 host->reference_count++;
622
623         status = plugin_register_notification (n_cb_name,
624                         riemann_notification, &ud);
625         if (status != 0)
626                 WARNING ("riemann plugin: plugin_register_notification (\"%s\") "
627                                 "failed with status %i.",
628                                 n_cb_name, status);
629         else /* success */
630                 host->reference_count++;
631
632         if (host->reference_count <= 1)
633         {
634                 /* Both callbacks failed => free memory.
635                  * We need to unlock here, because riemann_free() will lock.
636                  * This is not a race condition, because we're the only one
637                  * holding a reference. */
638                 pthread_mutex_unlock (&host->lock);
639                 riemann_free (host);
640                 return (-1);
641         }
642
643         host->reference_count--;
644         pthread_mutex_unlock (&host->lock);
645
646         return status;
647 }
648
649 static int
650 riemann_config(oconfig_item_t *ci)
651 {
652         int              i;
653         oconfig_item_t  *child;
654         int              status;
655
656         for (i = 0; i < ci->children_num; i++)  {
657                 child = &ci->children[i];
658
659                 if (strcasecmp(child->key, "host") == 0) {
660                         riemann_config_host(child);
661                 } else if (strcasecmp(child->key, "tag") == 0) {
662                         char *tmp = NULL;
663                         status = cf_util_get_string(child, &tmp);
664                         if (status != 0)
665                                 continue;
666
667                         strarray_add (&riemann_tags, &riemann_tags_num, tmp);
668                         DEBUG("riemann plugin: Got tag: %s", tmp);
669                         sfree (tmp);
670                 } else {
671                         WARNING ("riemann plugin: Ignoring unknown "
672                                  "configuration option \"%s\" at top level.",
673                                  child->key);
674                 }
675         }
676         return (0);
677 }
678
679 void
680 module_register(void)
681 {
682         DEBUG("riemann: module_register");
683
684         plugin_register_complex_config ("riemann", riemann_config);
685 }
686
687 /* vim: set sw=8 sts=8 ts=8 noet : */