Code

write_riemann plugin: Fix a memory leak.
[collectd.git] / src / write_riemann.c
1 /**
2  * collectd - src/write_riemann.c
3  *
4  * Copyright (C) 2012,2013  Pierre-Yves Ritschard
5  * Copyright (C) 2013       Florian octo Forster
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
16  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
17  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  *
19  * Authors:
20  *   Pierre-Yves Ritschard <pyr at spootnik.org>
21  *   Florian octo Forster <octo at collectd.org>
22  */
24 #include "collectd.h"
25 #include "plugin.h"
26 #include "common.h"
27 #include "configfile.h"
28 #include "utils_cache.h"
29 #include "riemann.pb-c.h"
31 #include <sys/socket.h>
32 #include <arpa/inet.h>
33 #include <errno.h>
34 #include <netdb.h>
35 #include <inttypes.h>
36 #include <pthread.h>
38 #define RIEMANN_HOST            "localhost"
39 #define RIEMANN_PORT            "5555"
41 struct riemann_host {
42         char                    *name;
43 #define F_CONNECT                0x01
44         uint8_t                  flags;
45         pthread_mutex_t          lock;
46         _Bool                    store_rates;
47         _Bool                    always_append_ds;
48         char                    *node;
49         char                    *service;
50         _Bool                    use_tcp;
51         int                      s;
53         int                      reference_count;
54 };
56 static char     **riemann_tags;
57 static size_t     riemann_tags_num;
59 static void riemann_event_protobuf_free (Event *event) /* {{{ */
60 {
61         size_t i;
63         if (event == NULL)
64                 return;
66         sfree (event->state);
67         sfree (event->service);
68         sfree (event->host);
69         sfree (event->description);
71         strarray_free (event->tags, event->n_tags);
72         event->tags = NULL;
73         event->n_tags = 0;
75         for (i = 0; i < event->n_attributes; i++)
76                 sfree (event->attributes[i]);
77         sfree (event->attributes);
78         event->n_attributes = 0;
80         sfree (event);
81 } /* }}} void riemann_event_protobuf_free */
83 static void riemann_msg_protobuf_free (Msg *msg) /* {{{ */
84 {
85         size_t i;
87         if (msg == NULL)
88                 return;
90         for (i = 0; i < msg->n_events; i++)
91         {
92                 riemann_event_protobuf_free (msg->events[i]);
93                 msg->events[i] = NULL;
94         }
96         sfree (msg->events);
97         msg->n_events = 0;
99         sfree (msg);
100 } /* }}} void riemann_msg_protobuf_free */
102 /* host->lock must be held when calling this function. */
103 static int
104 riemann_connect(struct riemann_host *host)
106         int                      e;
107         struct addrinfo         *ai, *res, hints;
108         char const              *node;
109         char const              *service;
111         if (host->flags & F_CONNECT)
112                 return 0;
114         memset(&hints, 0, sizeof(hints));
115         memset(&service, 0, sizeof(service));
116         hints.ai_family = AF_UNSPEC;
117         hints.ai_socktype = host->use_tcp ? SOCK_STREAM : SOCK_DGRAM;
118 #ifdef AI_ADDRCONFIG
119         hints.ai_flags |= AI_ADDRCONFIG;
120 #endif
122         node = (host->node != NULL) ? host->node : RIEMANN_HOST;
123         service = (host->service != NULL) ? host->service : RIEMANN_PORT;
125         if ((e = getaddrinfo(node, service, &hints, &res)) != 0) {
126                 ERROR ("write_riemann plugin: Unable to resolve host \"%s\": %s",
127                         node, gai_strerror(e));
128                 return -1;
129         }
131         host->s = -1;
132         for (ai = res; ai != NULL; ai = ai->ai_next) {
133                 if ((host->s = socket(ai->ai_family,
134                                       ai->ai_socktype,
135                                       ai->ai_protocol)) == -1) {
136                         continue;
137                 }
139                 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
140                         close(host->s);
141                         host->s = -1;
142                         continue;
143                 }
145                 host->flags |= F_CONNECT;
146                 DEBUG("write_riemann plugin: got a succesful connection for: %s:%s",
147                                 node, service);
148                 break;
149         }
151         freeaddrinfo(res);
153         if (host->s < 0) {
154                 WARNING("write_riemann plugin: Unable to connect to Riemann at %s:%s",
155                                 node, service);
156                 return -1;
157         }
158         return 0;
161 /* host->lock must be held when calling this function. */
162 static int
163 riemann_disconnect (struct riemann_host *host)
165         if ((host->flags & F_CONNECT) == 0)
166                 return (0);
168         close (host->s);
169         host->s = -1;
170         host->flags &= ~F_CONNECT;
172         return (0);
175 static int
176 riemann_send(struct riemann_host *host, Msg const *msg)
178         u_char *buffer;
179         size_t  buffer_len;
180         int status;
182         pthread_mutex_lock (&host->lock);
184         status = riemann_connect (host);
185         if (status != 0)
186         {
187                 pthread_mutex_unlock (&host->lock);
188                 return status;
189         }
191         buffer_len = msg__get_packed_size(msg);
192         if (host->use_tcp)
193                 buffer_len += 4;
195         buffer = malloc (buffer_len);
196         if (buffer == NULL) {
197                 pthread_mutex_unlock (&host->lock);
198                 ERROR ("write_riemann plugin: malloc failed.");
199                 return ENOMEM;
200         }
201         memset (buffer, 0, buffer_len);
203         if (host->use_tcp)
204         {
205                 uint32_t length = htonl ((uint32_t) (buffer_len - 4));
206                 memcpy (buffer, &length, 4);
207                 msg__pack(msg, buffer + 4);
208         }
209         else
210         {
211                 msg__pack(msg, buffer);
212         }
214         status = (int) swrite (host->s, buffer, buffer_len);
215         if (status != 0)
216         {
217                 char errbuf[1024];
219                 riemann_disconnect (host);
220                 pthread_mutex_unlock (&host->lock);
222                 ERROR ("write_riemann plugin: Sending to Riemann at %s:%s failed: %s",
223                                 (host->node != NULL) ? host->node : RIEMANN_HOST,
224                                 (host->service != NULL) ? host->service : RIEMANN_PORT,
225                                 sstrerror (errno, errbuf, sizeof (errbuf)));
226                 sfree (buffer);
227                 return -1;
228         }
230         pthread_mutex_unlock (&host->lock);
231         sfree (buffer);
232         return 0;
235 static int riemann_event_add_tag (Event *event, char const *tag) /* {{{ */
237         return (strarray_add (&event->tags, &event->n_tags, tag));
238 } /* }}} int riemann_event_add_tag */
240 static int riemann_event_add_attribute (Event *event, /* {{{ */
241                 char const *key, char const *value)
243         Attribute **new_attributes;
244         Attribute *a;
246         new_attributes = realloc (event->attributes,
247                         sizeof (*event->attributes) * (event->n_attributes + 1));
248         if (new_attributes == NULL)
249         {
250                 ERROR ("write_riemann plugin: realloc failed.");
251                 return (ENOMEM);
252         }
253         event->attributes = new_attributes;
255         a = malloc (sizeof (*a));
256         if (a == NULL)
257         {
258                 ERROR ("write_riemann plugin: malloc failed.");
259                 return (ENOMEM);
260         }
261         attribute__init (a);
263         a->key = strdup (key);
264         if (value != NULL)
265                 a->value = strdup (value);
267         event->attributes[event->n_attributes] = a;
268         event->n_attributes++;
270         return (0);
271 } /* }}} int riemann_event_add_attribute */
273 static Msg *riemann_notification_to_protobuf (struct riemann_host *host, /* {{{ */
274                 notification_t const *n)
276         Msg *msg;
277         Event *event;
278         char service_buffer[6 * DATA_MAX_NAME_LEN];
279         char const *severity;
280         notification_meta_t *meta;
281         int i;
283         msg = malloc (sizeof (*msg));
284         if (msg == NULL)
285         {
286                 ERROR ("write_riemann plugin: malloc failed.");
287                 return (NULL);
288         }
289         memset (msg, 0, sizeof (*msg));
290         msg__init (msg);
292         msg->events = malloc (sizeof (*msg->events));
293         if (msg->events == NULL)
294         {
295                 ERROR ("write_riemann plugin: malloc failed.");
296                 sfree (msg);
297                 return (NULL);
298         }
300         event = malloc (sizeof (*event));
301         if (event == NULL)
302         {
303                 ERROR ("write_riemann plugin: malloc failed.");
304                 sfree (msg->events);
305                 sfree (msg);
306                 return (NULL);
307         }
308         memset (event, 0, sizeof (*event));
309         event__init (event);
311         msg->events[0] = event;
312         msg->n_events = 1;
314         event->host = strdup (n->host);
315         event->time = CDTIME_T_TO_TIME_T (n->time);
316         event->has_time = 1;
318         switch (n->severity)
319         {
320                 case NOTIF_OKAY:        severity = "ok"; break;
321                 case NOTIF_WARNING:     severity = "warning"; break;
322                 case NOTIF_FAILURE:     severity = "critical"; break;
323                 default:                severity = "unknown";
324         }
325         event->state = strdup (severity);
327         riemann_event_add_tag (event, "notification");
328         if (n->host[0] != 0)
329                 riemann_event_add_attribute (event, "host", n->host);
330         if (n->plugin[0] != 0)
331                 riemann_event_add_attribute (event, "plugin", n->plugin);
332         if (n->plugin_instance[0] != 0)
333                 riemann_event_add_attribute (event, "plugin_instance",
334                                 n->plugin_instance);
336         if (n->type[0] != 0)
337                 riemann_event_add_attribute (event, "type", n->type);
338         if (n->type_instance[0] != 0)
339                 riemann_event_add_attribute (event, "type_instance",
340                                 n->type_instance);
342         for (i = 0; i < riemann_tags_num; i++)
343                 riemann_event_add_tag (event, riemann_tags[i]);
345         format_name (service_buffer, sizeof (service_buffer),
346                         /* host = */ "", n->plugin, n->plugin_instance,
347                         n->type, n->type_instance);
348         event->service = strdup (&service_buffer[1]);
350         /* Pull in values from threshold */
351         for (meta = n->meta; meta != NULL; meta = meta->next)
352         {
353                 if (strcasecmp ("CurrentValue", meta->name) != 0)
354                         continue;
356                 event->metric_d = meta->nm_value.nm_double;
357                 event->has_metric_d = 1;
358                 break;
359         }
361         DEBUG ("write_riemann plugin: Successfully created protobuf for notification: "
362                         "host = \"%s\", service = \"%s\", state = \"%s\"",
363                         event->host, event->service, event->state);
364         return (msg);
365 } /* }}} Msg *riemann_notification_to_protobuf */
367 static Event *riemann_value_to_protobuf (struct riemann_host const *host, /* {{{ */
368                 data_set_t const *ds,
369                 value_list_t const *vl, size_t index,
370                 gauge_t const *rates)
372         Event *event;
373         char name_buffer[5 * DATA_MAX_NAME_LEN];
374         char service_buffer[6 * DATA_MAX_NAME_LEN];
375         int i;
377         event = malloc (sizeof (*event));
378         if (event == NULL)
379         {
380                 ERROR ("write_riemann plugin: malloc failed.");
381                 return (NULL);
382         }
383         memset (event, 0, sizeof (*event));
384         event__init (event);
386         event->host = strdup (vl->host);
387         event->time = CDTIME_T_TO_TIME_T (vl->time);
388         event->has_time = 1;
389         event->ttl = CDTIME_T_TO_TIME_T (2 * vl->interval);
390         event->has_ttl = 1;
392         riemann_event_add_attribute (event, "plugin", vl->plugin);
393         if (vl->plugin_instance[0] != 0)
394                 riemann_event_add_attribute (event, "plugin_instance",
395                                 vl->plugin_instance);
397         riemann_event_add_attribute (event, "type", vl->type);
398         if (vl->type_instance[0] != 0)
399                 riemann_event_add_attribute (event, "type_instance",
400                                 vl->type_instance);
402         if ((ds->ds[index].type != DS_TYPE_GAUGE) && (rates != NULL))
403         {
404                 char ds_type[DATA_MAX_NAME_LEN];
406                 ssnprintf (ds_type, sizeof (ds_type), "%s:rate",
407                                 DS_TYPE_TO_STRING(ds->ds[index].type));
408                 riemann_event_add_attribute (event, "ds_type", ds_type);
409         }
410         else
411         {
412                 riemann_event_add_attribute (event, "ds_type",
413                                 DS_TYPE_TO_STRING(ds->ds[index].type));
414         }
415         riemann_event_add_attribute (event, "ds_name", ds->ds[index].name);
416         {
417                 char ds_index[DATA_MAX_NAME_LEN];
419                 ssnprintf (ds_index, sizeof (ds_index), "%zu", index);
420                 riemann_event_add_attribute (event, "ds_index", ds_index);
421         }
423         for (i = 0; i < riemann_tags_num; i++)
424                 riemann_event_add_tag (event, riemann_tags[i]);
426         if (ds->ds[index].type == DS_TYPE_GAUGE)
427         {
428                 event->has_metric_d = 1;
429                 event->metric_d = (double) vl->values[index].gauge;
430         }
431         else if (rates != NULL)
432         {
433                 event->has_metric_d = 1;
434                 event->metric_d = (double) rates[index];
435         }
436         else
437         {
438                 event->has_metric_sint64 = 1;
439                 if (ds->ds[index].type == DS_TYPE_DERIVE)
440                         event->metric_sint64 = (int64_t) vl->values[index].derive;
441                 else if (ds->ds[index].type == DS_TYPE_ABSOLUTE)
442                         event->metric_sint64 = (int64_t) vl->values[index].absolute;
443                 else
444                         event->metric_sint64 = (int64_t) vl->values[index].counter;
445         }
447         format_name (name_buffer, sizeof (name_buffer),
448                         /* host = */ "", vl->plugin, vl->plugin_instance,
449                         vl->type, vl->type_instance);
450         if (host->always_append_ds || (ds->ds_num > 1))
451                 ssnprintf (service_buffer, sizeof (service_buffer),
452                                 "%s/%s", &name_buffer[1], ds->ds[index].name);
453         else
454                 sstrncpy (service_buffer, &name_buffer[1],
455                                 sizeof (service_buffer));
457         event->service = strdup (service_buffer);
459         DEBUG ("write_riemann plugin: Successfully created protobuf for metric: "
460                         "host = \"%s\", service = \"%s\"",
461                         event->host, event->service);
462         return (event);
463 } /* }}} Event *riemann_value_to_protobuf */
465 static Msg *riemann_value_list_to_protobuf (struct riemann_host const *host, /* {{{ */
466                 data_set_t const *ds,
467                 value_list_t const *vl)
469         Msg *msg;
470         size_t i;
471         gauge_t *rates = NULL;
473         /* Initialize the Msg structure. */
474         msg = malloc (sizeof (*msg));
475         if (msg == NULL)
476         {
477                 ERROR ("write_riemann plugin: malloc failed.");
478                 return (NULL);
479         }
480         memset (msg, 0, sizeof (*msg));
481         msg__init (msg);
483         /* Set up events. First, the list of pointers. */
484         msg->n_events = (size_t) vl->values_len;
485         msg->events = calloc (msg->n_events, sizeof (*msg->events));
486         if (msg->events == NULL)
487         {
488                 ERROR ("write_riemann plugin: calloc failed.");
489                 riemann_msg_protobuf_free (msg);
490                 return (NULL);
491         }
493         if (host->store_rates)
494         {
495                 rates = uc_get_rate (ds, vl);
496                 if (rates == NULL)
497                 {
498                         ERROR ("write_riemann plugin: uc_get_rate failed.");
499                         riemann_msg_protobuf_free (msg);
500                         return (NULL);
501                 }
502         }
504         for (i = 0; i < msg->n_events; i++)
505         {
506                 msg->events[i] = riemann_value_to_protobuf (host, ds, vl,
507                                 (int) i, rates);
508                 if (msg->events[i] == NULL)
509                 {
510                         riemann_msg_protobuf_free (msg);
511                         sfree (rates);
512                         return (NULL);
513                 }
514         }
516         sfree (rates);
517         return (msg);
518 } /* }}} Msg *riemann_value_list_to_protobuf */
520 static int
521 riemann_notification(const notification_t *n, user_data_t *ud)
523         int                      status;
524         struct riemann_host     *host = ud->data;
525         Msg                     *msg;
527         msg = riemann_notification_to_protobuf (host, n);
528         if (msg == NULL)
529                 return (-1);
531         status = riemann_send (host, msg);
532         if (status != 0)
533                 ERROR ("write_riemann plugin: riemann_send failed with status %i",
534                                 status);
536         riemann_msg_protobuf_free (msg);
537         return (status);
538 } /* }}} int riemann_notification */
540 static int
541 riemann_write(const data_set_t *ds,
542               const value_list_t *vl,
543               user_data_t *ud)
545         int                      status;
546         struct riemann_host     *host = ud->data;
547         Msg                     *msg;
549         msg = riemann_value_list_to_protobuf (host, ds, vl);
550         if (msg == NULL)
551                 return (-1);
553         status = riemann_send (host, msg);
554         if (status != 0)
555                 ERROR ("write_riemann plugin: riemann_send failed with status %i",
556                                 status);
558         riemann_msg_protobuf_free (msg);
559         return status;
562 static void
563 riemann_free(void *p)
565         struct riemann_host     *host = p;
567         if (host == NULL)
568                 return;
570         pthread_mutex_lock (&host->lock);
572         host->reference_count--;
573         if (host->reference_count > 0)
574         {
575                 pthread_mutex_unlock (&host->lock);
576                 return;
577         }
579         riemann_disconnect (host);
581         sfree(host->service);
582         pthread_mutex_destroy (&host->lock);
583         sfree(host);
586 static int
587 riemann_config_node(oconfig_item_t *ci)
589         struct riemann_host     *host = NULL;
590         int                      status = 0;
591         int                      i;
592         oconfig_item_t          *child;
593         char                     callback_name[DATA_MAX_NAME_LEN];
594         user_data_t              ud;
596         if ((host = calloc(1, sizeof (*host))) == NULL) {
597                 ERROR ("write_riemann plugin: calloc failed.");
598                 return ENOMEM;
599         }
600         pthread_mutex_init (&host->lock, NULL);
601         host->reference_count = 1;
602         host->node = NULL;
603         host->service = NULL;
604         host->store_rates = 1;
605         host->always_append_ds = 0;
606         host->use_tcp = 0;
608         status = cf_util_get_string (ci, &host->name);
609         if (status != 0) {
610                 WARNING("write_riemann plugin: Required host name is missing.");
611                 riemann_free (host);
612                 return -1;
613         }
615         for (i = 0; i < ci->children_num; i++) {
616                 /*
617                  * The code here could be simplified but makes room
618                  * for easy adding of new options later on.
619                  */
620                 child = &ci->children[i];
621                 status = 0;
623                 if (strcasecmp ("Host", child->key) == 0) {
624                         status = cf_util_get_string (child, &host->node);
625                         if (status != 0)
626                                 break;
627                 } else if (strcasecmp ("Port", child->key) == 0) {
628                         status = cf_util_get_service (child, &host->service);
629                         if (status != 0) {
630                                 ERROR ("write_riemann plugin: Invalid argument "
631                                                 "configured for the \"Port\" "
632                                                 "option.");
633                                 break;
634                         }
635                 } else if (strcasecmp ("Protocol", child->key) == 0) {
636                         char tmp[16];
637                         status = cf_util_get_string_buffer (child,
638                                         tmp, sizeof (tmp));
639                         if (status != 0)
640                         {
641                                 ERROR ("write_riemann plugin: cf_util_get_"
642                                                 "string_buffer failed with "
643                                                 "status %i.", status);
644                                 break;
645                         }
647                         if (strcasecmp ("UDP", tmp) == 0)
648                                 host->use_tcp = 0;
649                         else if (strcasecmp ("TCP", tmp) == 0)
650                                 host->use_tcp = 1;
651                         else
652                                 WARNING ("write_riemann plugin: The value "
653                                                 "\"%s\" is not valid for the "
654                                                 "\"Protocol\" option. Use "
655                                                 "either \"UDP\" or \"TCP\".",
656                                                 tmp);
657                 } else if (strcasecmp ("StoreRates", child->key) == 0) {
658                         status = cf_util_get_boolean (child, &host->store_rates);
659                         if (status != 0)
660                                 break;
661                 } else if (strcasecmp ("AlwaysAppendDS", child->key) == 0) {
662                         status = cf_util_get_boolean (child,
663                                         &host->always_append_ds);
664                         if (status != 0)
665                                 break;
666                 } else {
667                         WARNING("write_riemann plugin: ignoring unknown config "
668                                 "option: \"%s\"", child->key);
669                 }
670         }
671         if (status != 0) {
672                 riemann_free (host);
673                 return status;
674         }
676         ssnprintf (callback_name, sizeof (callback_name), "write_riemann/%s",
677                         host->name);
678         ud.data = host;
679         ud.free_func = riemann_free;
681         pthread_mutex_lock (&host->lock);
683         status = plugin_register_write (callback_name, riemann_write, &ud);
684         if (status != 0)
685                 WARNING ("write_riemann plugin: plugin_register_write (\"%s\") "
686                                 "failed with status %i.",
687                                 callback_name, status);
688         else /* success */
689                 host->reference_count++;
691         status = plugin_register_notification (callback_name,
692                         riemann_notification, &ud);
693         if (status != 0)
694                 WARNING ("write_riemann plugin: plugin_register_notification (\"%s\") "
695                                 "failed with status %i.",
696                                 callback_name, status);
697         else /* success */
698                 host->reference_count++;
700         if (host->reference_count <= 1)
701         {
702                 /* Both callbacks failed => free memory.
703                  * We need to unlock here, because riemann_free() will lock.
704                  * This is not a race condition, because we're the only one
705                  * holding a reference. */
706                 pthread_mutex_unlock (&host->lock);
707                 riemann_free (host);
708                 return (-1);
709         }
711         host->reference_count--;
712         pthread_mutex_unlock (&host->lock);
714         return status;
717 static int
718 riemann_config(oconfig_item_t *ci)
720         int              i;
721         oconfig_item_t  *child;
722         int              status;
724         for (i = 0; i < ci->children_num; i++)  {
725                 child = &ci->children[i];
727                 if (strcasecmp("Node", child->key) == 0) {
728                         riemann_config_node (child);
729                 } else if (strcasecmp(child->key, "tag") == 0) {
730                         char *tmp = NULL;
731                         status = cf_util_get_string(child, &tmp);
732                         if (status != 0)
733                                 continue;
735                         strarray_add (&riemann_tags, &riemann_tags_num, tmp);
736                         DEBUG("write_riemann plugin: Got tag: %s", tmp);
737                         sfree (tmp);
738                 } else {
739                         WARNING ("write_riemann plugin: Ignoring unknown "
740                                  "configuration option \"%s\" at top level.",
741                                  child->key);
742                 }
743         }
744         return (0);
747 void
748 module_register(void)
750         plugin_register_complex_config ("write_riemann", riemann_config);
753 /* vim: set sw=8 sts=8 ts=8 noet : */