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