Code

sensors plugin: malloc + memset -> calloc
[collectd.git] / src / write_riemann.c
1 /**
2  * collectd - src/write_riemann.c
3  * Copyright (C) 2012,2013  Pierre-Yves Ritschard
4  * Copyright (C) 2013       Florian octo Forster
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  *
24  * Authors:
25  *   Pierre-Yves Ritschard <pyr at spootnik.org>
26  *   Florian octo Forster <octo at collectd.org>
27  */
29 #include <arpa/inet.h>
30 #include <errno.h>
31 #include <netdb.h>
32 #include <inttypes.h>
33 #include <pthread.h>
35 #include "collectd.h"
36 #include "plugin.h"
37 #include "common.h"
38 #include "configfile.h"
39 #include "utils_cache.h"
40 #include "riemann.pb-c.h"
41 #include "write_riemann_threshold.h"
43 #define RIEMANN_HOST            "localhost"
44 #define RIEMANN_PORT            "5555"
45 #define RIEMANN_TTL_FACTOR      2.0
46 #define RIEMANN_BATCH_MAX      8192
48 struct riemann_host {
49         char                    *name;
50         char                    *event_service_prefix;
51 #define F_CONNECT        0x01
52         uint8_t                  flags;
53         pthread_mutex_t  lock;
54     _Bool            batch_mode;
55         _Bool            notifications;
56         _Bool            check_thresholds;
57         _Bool                    store_rates;
58         _Bool                    always_append_ds;
59         char                    *node;
60         char                    *service;
61         _Bool                    use_tcp;
62         int                          s;
63         double                   ttl_factor;
64     Msg             *batch_msg;
65     cdtime_t         batch_init;
66     int              batch_max;
67         int                          reference_count;
68 };
70 static char     **riemann_tags;
71 static size_t     riemann_tags_num;
72 static char     **riemann_attrs;
73 static size_t     riemann_attrs_num;
75 static void riemann_event_protobuf_free (Event *event) /* {{{ */
76 {
77         size_t i;
79         if (event == NULL)
80                 return;
82         sfree (event->state);
83         sfree (event->service);
84         sfree (event->host);
85         sfree (event->description);
87         strarray_free (event->tags, event->n_tags);
88         event->tags = NULL;
89         event->n_tags = 0;
91         for (i = 0; i < event->n_attributes; i++)
92         {
93                 sfree (event->attributes[i]->key);
94                 sfree (event->attributes[i]->value);
95                 sfree (event->attributes[i]);
96         }
97         sfree (event->attributes);
98         event->n_attributes = 0;
100         sfree (event);
101 } /* }}} void riemann_event_protobuf_free */
103 static void riemann_msg_protobuf_free(Msg *msg) /* {{{ */
105         size_t i;
107         if (msg == NULL)
108                 return;
110         for (i = 0; i < msg->n_events; i++)
111         {
112                 riemann_event_protobuf_free (msg->events[i]);
113                 msg->events[i] = NULL;
114         }
116         sfree (msg->events);
117         msg->n_events = 0;
119         sfree (msg);
120 } /* }}} void riemann_msg_protobuf_free */
122 /* host->lock must be held when calling this function. */
123 static int riemann_connect(struct riemann_host *host) /* {{{ */
125         int                      e;
126         struct addrinfo         *ai, *res, hints;
127         char const              *node;
128         char const              *service;
130         if (host->flags & F_CONNECT)
131                 return 0;
133         memset(&hints, 0, sizeof(hints));
134         memset(&service, 0, sizeof(service));
135         hints.ai_family = AF_UNSPEC;
136         hints.ai_socktype = host->use_tcp ? SOCK_STREAM : SOCK_DGRAM;
137 #ifdef AI_ADDRCONFIG
138         hints.ai_flags |= AI_ADDRCONFIG;
139 #endif
141         node = (host->node != NULL) ? host->node : RIEMANN_HOST;
142         service = (host->service != NULL) ? host->service : RIEMANN_PORT;
144         if ((e = getaddrinfo(node, service, &hints, &res)) != 0) {
145                 ERROR ("write_riemann plugin: Unable to resolve host \"%s\": %s",
146                         node, gai_strerror(e));
147                 return -1;
148         }
150         host->s = -1;
151         for (ai = res; ai != NULL; ai = ai->ai_next) {
152                 if ((host->s = socket(ai->ai_family,
153                                       ai->ai_socktype,
154                                       ai->ai_protocol)) == -1) {
155                         continue;
156                 }
158                 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
159                         close(host->s);
160                         host->s = -1;
161                         continue;
162                 }
164                 host->flags |= F_CONNECT;
165                 DEBUG("write_riemann plugin: got a successful connection for: %s:%s",
166                                 node, service);
167                 break;
168         }
170         freeaddrinfo(res);
172         if (host->s < 0) {
173                 WARNING("write_riemann plugin: Unable to connect to Riemann at %s:%s",
174                                 node, service);
175                 return -1;
176         }
177         return 0;
178 } /* }}} int riemann_connect */
180 /* host->lock must be held when calling this function. */
181 static int riemann_disconnect (struct riemann_host *host) /* {{{ */
183         if ((host->flags & F_CONNECT) == 0)
184                 return (0);
186         close (host->s);
187         host->s = -1;
188         host->flags &= ~F_CONNECT;
190         return (0);
191 } /* }}} int riemann_disconnect */
193 static int riemann_send_msg (struct riemann_host *host, const Msg *msg) /* {{{ */
195         int status = 0;
196         u_char *buffer = NULL;
197         size_t  buffer_len;
199         status = riemann_connect (host);
200         if (status != 0)
201                 return status;
203         buffer_len = msg__get_packed_size(msg);
205         if (host->use_tcp)
206                 buffer_len += 4;
208         buffer = malloc (buffer_len);
209         if (buffer == NULL) {
210                 ERROR ("write_riemann plugin: malloc failed.");
211                 return ENOMEM;
212         }
213         memset (buffer, 0, buffer_len);
215         if (host->use_tcp)
216         {
217                 uint32_t length = htonl ((uint32_t) (buffer_len - 4));
218                 memcpy (buffer, &length, 4);
219                 msg__pack(msg, buffer + 4);
220         }
221         else
222         {
223                 msg__pack(msg, buffer);
224         }
226         status = (int) swrite (host->s, buffer, buffer_len);
227         if (status != 0)
228         {
229                 char errbuf[1024];
230                 ERROR ("write_riemann plugin: Sending to Riemann at %s:%s failed: %s",
231                                 (host->node != NULL) ? host->node : RIEMANN_HOST,
232                                 (host->service != NULL) ? host->service : RIEMANN_PORT,
233                                 sstrerror (errno, errbuf, sizeof (errbuf)));
234                 sfree (buffer);
235                 return -1;
236         }
238         sfree (buffer);
239         return 0;
240 } /* }}} int riemann_send_msg */
242 static int riemann_recv_ack(struct riemann_host *host) /* {{{ */
244         int status = 0;
245         Msg *msg = NULL;
246         uint32_t header;
248         status = (int) sread (host->s, &header, 4);
250         if (status != 0)
251                 return -1;
253         size_t size = ntohl(header);
255         // Buffer on the stack since acknowledges are typically small.
256         u_char buffer[size];
257         memset (buffer, 0, size);
259         status = (int) sread (host->s, buffer, size);
261         if (status != 0)
262                 return status;
264         msg = msg__unpack (NULL, size, buffer);
266         if (msg == NULL)
267                 return -1;
269         if (!msg->ok)
270         {
271                 ERROR ("write_riemann plugin: Sending to Riemann at %s:%s acknowledgement message reported error: %s",
272                                 (host->node != NULL) ? host->node : RIEMANN_HOST,
273                                 (host->service != NULL) ? host->service : RIEMANN_PORT,
274                                 msg->error);
276                 msg__free_unpacked(msg, NULL);
277                 return -1;
278         }
280         msg__free_unpacked (msg, NULL);
281         return 0;
282 } /* }}} int riemann_recv_ack */
284 /**
285  * Function to send messages (Msg) to riemann.
286  *
287  * Acquires the host lock, disconnects on errors.
288  */
289 static int riemann_send(struct riemann_host *host, Msg const *msg) /* {{{ */
291         int status = 0;
292         pthread_mutex_lock (&host->lock);
294         status = riemann_send_msg(host, msg);
295         if (status != 0) {
296                 riemann_disconnect (host);
297                 pthread_mutex_unlock (&host->lock);
298                 return status;
299         }
301         /*
302          * For TCP we need to receive message acknowledgemenent.
303          */
304         if (host->use_tcp)
305         {
306                 status = riemann_recv_ack(host);
308                 if (status != 0)
309                 {
310                         riemann_disconnect (host);
311                         pthread_mutex_unlock (&host->lock);
312                         return status;
313                 }
314         }
316         pthread_mutex_unlock (&host->lock);
317         return 0;
318 } /* }}} int riemann_send */
320 static int riemann_event_add_tag (Event *event, char const *tag) /* {{{ */
322         return (strarray_add (&event->tags, &event->n_tags, tag));
323 } /* }}} int riemann_event_add_tag */
325 static int riemann_event_add_attribute(Event *event, /* {{{ */
326                 char const *key, char const *value)
328         Attribute **new_attributes;
329         Attribute *a;
331         new_attributes = realloc (event->attributes,
332                         sizeof (*event->attributes) * (event->n_attributes + 1));
333         if (new_attributes == NULL)
334         {
335                 ERROR ("write_riemann plugin: realloc failed.");
336                 return (ENOMEM);
337         }
338         event->attributes = new_attributes;
340         a = malloc (sizeof (*a));
341         if (a == NULL)
342         {
343                 ERROR ("write_riemann plugin: malloc failed.");
344                 return (ENOMEM);
345         }
346         attribute__init (a);
348         a->key = strdup (key);
349         if (value != NULL)
350                 a->value = strdup (value);
352         event->attributes[event->n_attributes] = a;
353         event->n_attributes++;
355         return (0);
356 } /* }}} int riemann_event_add_attribute */
358 static Msg *riemann_notification_to_protobuf(struct riemann_host *host, /* {{{ */
359                 notification_t const *n)
361         Msg *msg;
362         Event *event;
363         char service_buffer[6 * DATA_MAX_NAME_LEN];
364         char const *severity;
365         notification_meta_t *meta;
366         size_t i;
368         msg = malloc (sizeof (*msg));
369         if (msg == NULL)
370         {
371                 ERROR ("write_riemann plugin: malloc failed.");
372                 return (NULL);
373         }
374         memset (msg, 0, sizeof (*msg));
375         msg__init (msg);
377         msg->events = malloc (sizeof (*msg->events));
378         if (msg->events == NULL)
379         {
380                 ERROR ("write_riemann plugin: malloc failed.");
381                 sfree (msg);
382                 return (NULL);
383         }
385         event = malloc (sizeof (*event));
386         if (event == NULL)
387         {
388                 ERROR ("write_riemann plugin: malloc failed.");
389                 sfree (msg->events);
390                 sfree (msg);
391                 return (NULL);
392         }
393         memset (event, 0, sizeof (*event));
394         event__init (event);
396         msg->events[0] = event;
397         msg->n_events = 1;
399         event->host = strdup (n->host);
400         event->time = CDTIME_T_TO_TIME_T (n->time);
401         event->has_time = 1;
403         switch (n->severity)
404         {
405                 case NOTIF_OKAY:        severity = "ok"; break;
406                 case NOTIF_WARNING:     severity = "warning"; break;
407                 case NOTIF_FAILURE:     severity = "critical"; break;
408                 default:                severity = "unknown";
409         }
410         event->state = strdup (severity);
412         riemann_event_add_tag (event, "notification");
413         if (n->host[0] != 0)
414                 riemann_event_add_attribute (event, "host", n->host);
415         if (n->plugin[0] != 0)
416                 riemann_event_add_attribute (event, "plugin", n->plugin);
417         if (n->plugin_instance[0] != 0)
418                 riemann_event_add_attribute (event, "plugin_instance",
419                                 n->plugin_instance);
421         if (n->type[0] != 0)
422                 riemann_event_add_attribute (event, "type", n->type);
423         if (n->type_instance[0] != 0)
424                 riemann_event_add_attribute (event, "type_instance",
425                                 n->type_instance);
427         for (i = 0; i < riemann_attrs_num; i += 2)
428                 riemann_event_add_attribute(event,
429                                             riemann_attrs[i],
430                                             riemann_attrs[i +1]);
432         for (i = 0; i < riemann_tags_num; i++)
433                 riemann_event_add_tag (event, riemann_tags[i]);
435         format_name (service_buffer, sizeof (service_buffer),
436                         /* host = */ "", n->plugin, n->plugin_instance,
437                         n->type, n->type_instance);
438         event->service = strdup (&service_buffer[1]);
440         if (n->message[0] != 0)
441                 riemann_event_add_attribute (event, "description", n->message);
443         /* Pull in values from threshold and add extra attributes */
444         for (meta = n->meta; meta != NULL; meta = meta->next)
445         {
446                 if (strcasecmp ("CurrentValue", meta->name) == 0 && meta->type == NM_TYPE_DOUBLE)
447                 {
448                         event->metric_d = meta->nm_value.nm_double;
449                         event->has_metric_d = 1;
450                         continue;
451                 }
453                 if (meta->type == NM_TYPE_STRING) {
454                         riemann_event_add_attribute (event, meta->name, meta->nm_value.nm_string);
455                         continue;
456                 }
457         }
459         DEBUG ("write_riemann plugin: Successfully created protobuf for notification: "
460                         "host = \"%s\", service = \"%s\", state = \"%s\"",
461                         event->host, event->service, event->state);
462         return (msg);
463 } /* }}} Msg *riemann_notification_to_protobuf */
465 static Event *riemann_value_to_protobuf(struct riemann_host const *host, /* {{{ */
466                 data_set_t const *ds,
467                 value_list_t const *vl, size_t index,
468                                          gauge_t const *rates,
469                                          int status)
471         Event *event;
472         char name_buffer[5 * DATA_MAX_NAME_LEN];
473         char service_buffer[6 * DATA_MAX_NAME_LEN];
474         double ttl;
475         size_t i;
477         event = malloc (sizeof (*event));
478         if (event == NULL)
479         {
480                 ERROR ("write_riemann plugin: malloc failed.");
481                 return (NULL);
482         }
483         memset (event, 0, sizeof (*event));
484         event__init (event);
486         event->host = strdup (vl->host);
487         event->time = CDTIME_T_TO_TIME_T (vl->time);
488         event->has_time = 1;
490         if (host->check_thresholds) {
491                 switch (status) {
492                         case STATE_OKAY:
493                                 event->state = strdup("ok");
494                                 break;
495                         case STATE_ERROR:
496                                 event->state = strdup("critical");
497                                 break;
498                         case STATE_WARNING:
499                                 event->state = strdup("warning");
500                                 break;
501                         case STATE_MISSING:
502                                 event->state = strdup("unknown");
503                                 break;
504                 }
505         }
507         ttl = CDTIME_T_TO_DOUBLE (vl->interval) * host->ttl_factor;
508         event->ttl = (float) ttl;
509         event->has_ttl = 1;
511         riemann_event_add_attribute (event, "plugin", vl->plugin);
512         if (vl->plugin_instance[0] != 0)
513                 riemann_event_add_attribute (event, "plugin_instance",
514                                 vl->plugin_instance);
516         riemann_event_add_attribute (event, "type", vl->type);
517         if (vl->type_instance[0] != 0)
518                 riemann_event_add_attribute (event, "type_instance",
519                                 vl->type_instance);
521         if ((ds->ds[index].type != DS_TYPE_GAUGE) && (rates != NULL))
522         {
523                 char ds_type[DATA_MAX_NAME_LEN];
525                 ssnprintf (ds_type, sizeof (ds_type), "%s:rate",
526                                 DS_TYPE_TO_STRING(ds->ds[index].type));
527                 riemann_event_add_attribute (event, "ds_type", ds_type);
528         }
529         else
530         {
531                 riemann_event_add_attribute (event, "ds_type",
532                                 DS_TYPE_TO_STRING(ds->ds[index].type));
533         }
534         riemann_event_add_attribute (event, "ds_name", ds->ds[index].name);
535         {
536                 char ds_index[DATA_MAX_NAME_LEN];
538                 ssnprintf (ds_index, sizeof (ds_index), "%zu", index);
539                 riemann_event_add_attribute (event, "ds_index", ds_index);
540         }
542         for (i = 0; i < riemann_attrs_num; i += 2)
543                 riemann_event_add_attribute(event,
544                                             riemann_attrs[i],
545                                             riemann_attrs[i +1]);
547         for (i = 0; i < riemann_tags_num; i++)
548                 riemann_event_add_tag (event, riemann_tags[i]);
550         if (ds->ds[index].type == DS_TYPE_GAUGE)
551         {
552                 event->has_metric_d = 1;
553                 event->metric_d = (double) vl->values[index].gauge;
554         }
555         else if (rates != NULL)
556         {
557                 event->has_metric_d = 1;
558                 event->metric_d = (double) rates[index];
559         }
560         else
561         {
562                 event->has_metric_sint64 = 1;
563                 if (ds->ds[index].type == DS_TYPE_DERIVE)
564                         event->metric_sint64 = (int64_t) vl->values[index].derive;
565                 else if (ds->ds[index].type == DS_TYPE_ABSOLUTE)
566                         event->metric_sint64 = (int64_t) vl->values[index].absolute;
567                 else
568                         event->metric_sint64 = (int64_t) vl->values[index].counter;
569         }
571         format_name (name_buffer, sizeof (name_buffer),
572                         /* host = */ "", vl->plugin, vl->plugin_instance,
573                         vl->type, vl->type_instance);
574         if (host->always_append_ds || (ds->ds_num > 1))
575         {
576                 if (host->event_service_prefix == NULL)
577                         ssnprintf (service_buffer, sizeof (service_buffer), "%s/%s",
578                                         &name_buffer[1], ds->ds[index].name);
579                 else
580                         ssnprintf (service_buffer, sizeof (service_buffer), "%s%s/%s",
581                                         host->event_service_prefix, &name_buffer[1], ds->ds[index].name);
582         }
583         else
584         {
585                 if (host->event_service_prefix == NULL)
586                         sstrncpy (service_buffer, &name_buffer[1], sizeof (service_buffer));
587                 else
588                         ssnprintf (service_buffer, sizeof (service_buffer), "%s%s",
589                                         host->event_service_prefix, &name_buffer[1]);
590         }
592         event->service = strdup (service_buffer);
594         DEBUG ("write_riemann plugin: Successfully created protobuf for metric: "
595                         "host = \"%s\", service = \"%s\"",
596                         event->host, event->service);
597         return (event);
598 } /* }}} Event *riemann_value_to_protobuf */
600 static Msg *riemann_value_list_to_protobuf (struct riemann_host const *host, /* {{{ */
601                                             data_set_t const *ds,
602                                             value_list_t const *vl,
603                                             int *statuses)
605         Msg *msg;
606         size_t i;
607         gauge_t *rates = NULL;
609         /* Initialize the Msg structure. */
610         msg = malloc (sizeof (*msg));
611         if (msg == NULL)
612         {
613                 ERROR ("write_riemann plugin: malloc failed.");
614                 return (NULL);
615         }
616         memset (msg, 0, sizeof (*msg));
617         msg__init (msg);
619         /* Set up events. First, the list of pointers. */
620         msg->n_events = vl->values_len;
621         msg->events = calloc (msg->n_events, sizeof (*msg->events));
622         if (msg->events == NULL)
623         {
624                 ERROR ("write_riemann plugin: calloc failed.");
625                 riemann_msg_protobuf_free (msg);
626                 return (NULL);
627         }
629         if (host->store_rates)
630         {
631                 rates = uc_get_rate (ds, vl);
632                 if (rates == NULL)
633                 {
634                         ERROR ("write_riemann plugin: uc_get_rate failed.");
635                         riemann_msg_protobuf_free (msg);
636                         return (NULL);
637                 }
638         }
640         for (i = 0; i < msg->n_events; i++)
641         {
642                 msg->events[i] = riemann_value_to_protobuf (host, ds, vl,
643                                                             (int) i, rates, statuses[i]);
644                 if (msg->events[i] == NULL)
645                 {
646                         riemann_msg_protobuf_free (msg);
647                         sfree (rates);
648                         return (NULL);
649                 }
650         }
652         sfree (rates);
653         return (msg);
654 } /* }}} Msg *riemann_value_list_to_protobuf */
657 /*
658  * Always call while holding host->lock !
659  */
660 static int riemann_batch_flush_nolock (cdtime_t timeout,
661                                        struct riemann_host *host)
663     cdtime_t    now;
664     int         status = 0;
666     if (timeout > 0) {
667         now = cdtime ();
668         if ((host->batch_init + timeout) > now)
669             return status;
670     }
671     riemann_send_msg(host, host->batch_msg);
672     riemann_msg_protobuf_free(host->batch_msg);
674         if (host->use_tcp && ((status = riemann_recv_ack(host)) != 0))
675         riemann_disconnect (host);
677     host->batch_init = cdtime();
678     host->batch_msg = NULL;
679     return status;
682 static int riemann_batch_flush (cdtime_t timeout,
683         const char *identifier __attribute__((unused)),
684         user_data_t *user_data)
686     struct riemann_host *host;
687     int status;
689     if (user_data == NULL)
690         return (-EINVAL);
692     host = user_data->data;
693     pthread_mutex_lock (&host->lock);
694     status = riemann_batch_flush_nolock (timeout, host);
695     if (status != 0)
696         ERROR ("write_riemann plugin: riemann_send failed with status %i",
697                status);
699     pthread_mutex_unlock(&host->lock);
700     return status;
703 static int riemann_batch_add_value_list (struct riemann_host *host, /* {{{ */
704                                          data_set_t const *ds,
705                                          value_list_t const *vl,
706                                          int *statuses)
708         size_t i;
709     Event **events;
710     Msg *msg;
711     size_t len;
712     int ret;
714     msg = riemann_value_list_to_protobuf (host, ds, vl, statuses);
715     if (msg == NULL)
716         return -1;
718     pthread_mutex_lock(&host->lock);
720     if (host->batch_msg == NULL) {
721         host->batch_msg = msg;
722     } else {
723         len = msg->n_events + host->batch_msg->n_events;
724         events = realloc(host->batch_msg->events,
725                          (len * sizeof(*host->batch_msg->events)));
726         if (events == NULL) {
727             pthread_mutex_unlock(&host->lock);
728             ERROR ("write_riemann plugin: out of memory");
729             riemann_msg_protobuf_free (msg);
730             return -1;
731         }
732         host->batch_msg->events = events;
734         for (i = host->batch_msg->n_events; i < len; i++)
735             host->batch_msg->events[i] = msg->events[i - host->batch_msg->n_events];
737         host->batch_msg->n_events = len;
738         sfree (msg->events);
739         msg->n_events = 0;
740         sfree (msg);
741     }
743         len = msg__get_packed_size(host->batch_msg);
744     ret = 0;
745     if ((host->batch_max < 0) || (((size_t) host->batch_max) <= len)) {
746             ret = riemann_batch_flush_nolock(0, host);
747     }
749     pthread_mutex_unlock(&host->lock);
750     return ret;
751 } /* }}} Msg *riemann_batch_add_value_list */
753 static int riemann_notification(const notification_t *n, user_data_t *ud) /* {{{ */
755         int                      status;
756         struct riemann_host     *host = ud->data;
757         Msg                     *msg;
759         if (!host->notifications)
760                 return 0;
762     /*
763      * Never batch for notifications, send them ASAP
764      */
765         msg = riemann_notification_to_protobuf (host, n);
766         if (msg == NULL)
767                 return (-1);
769         status = riemann_send (host, msg);
770         if (status != 0)
771                 ERROR ("write_riemann plugin: riemann_send failed with status %i",
772                                 status);
774         riemann_msg_protobuf_free (msg);
775         return (status);
776 } /* }}} int riemann_notification */
778 static int riemann_write(const data_set_t *ds, /* {{{ */
779                 const value_list_t *vl,
780                 user_data_t *ud)
782         int                      status = 0;
783         int                      statuses[vl->values_len];
784         struct riemann_host     *host = ud->data;
786         if (host->check_thresholds) {
787                 status = write_riemann_threshold_check(ds, vl, statuses);
788                 if (status != 0)
789                         return status;
790         } else {
791                 memset (statuses, 0, sizeof (statuses));
792         }
794         if (host->use_tcp == 1 && host->batch_mode) {
795                 riemann_batch_add_value_list (host, ds, vl, statuses);
796         } else {
797                 Msg *msg = riemann_value_list_to_protobuf (host, ds, vl, statuses);
798                 if (msg == NULL)
799                         return (-1);
801                 status = riemann_send (host, msg);
802                 if (status != 0)
803                         ERROR ("write_riemann plugin: riemann_send failed with status %i", status);
805                 riemann_msg_protobuf_free (msg);
806         }
808         return status;
809 } /* }}} int riemann_write */
811 static void riemann_free(void *p) /* {{{ */
813         struct riemann_host     *host = p;
815         if (host == NULL)
816                 return;
818         pthread_mutex_lock (&host->lock);
820         host->reference_count--;
821         if (host->reference_count > 0)
822         {
823                 pthread_mutex_unlock (&host->lock);
824                 return;
825         }
827         riemann_disconnect (host);
829         sfree(host->service);
830         pthread_mutex_destroy (&host->lock);
831         sfree(host);
832 } /* }}} void riemann_free */
834 static int riemann_config_node(oconfig_item_t *ci) /* {{{ */
836         struct riemann_host     *host = NULL;
837         int                      status = 0;
838         int                      i;
839         oconfig_item_t          *child;
840         char                     callback_name[DATA_MAX_NAME_LEN];
841         user_data_t              ud;
843         if ((host = calloc(1, sizeof (*host))) == NULL) {
844                 ERROR ("write_riemann plugin: calloc failed.");
845                 return ENOMEM;
846         }
847         pthread_mutex_init (&host->lock, NULL);
848         host->reference_count = 1;
849         host->node = NULL;
850         host->service = NULL;
851         host->notifications = 1;
852         host->check_thresholds = 0;
853         host->store_rates = 1;
854         host->always_append_ds = 0;
855         host->use_tcp = 1;
856         host->batch_mode = 1;
857         host->batch_max = RIEMANN_BATCH_MAX; /* typical MSS */
858         host->batch_init = cdtime();
859         host->ttl_factor = RIEMANN_TTL_FACTOR;
861         status = cf_util_get_string (ci, &host->name);
862         if (status != 0) {
863                 WARNING("write_riemann plugin: Required host name is missing.");
864                 riemann_free (host);
865                 return -1;
866         }
868         for (i = 0; i < ci->children_num; i++) {
869                 /*
870                  * The code here could be simplified but makes room
871                  * for easy adding of new options later on.
872                  */
873                 child = &ci->children[i];
874                 status = 0;
876                 if (strcasecmp ("Host", child->key) == 0) {
877                         status = cf_util_get_string (child, &host->node);
878                         if (status != 0)
879                                 break;
880                 } else if (strcasecmp ("Notifications", child->key) == 0) {
881                         status = cf_util_get_boolean(child, &host->notifications);
882                         if (status != 0)
883                                 break;
884                 } else if (strcasecmp ("EventServicePrefix", child->key) == 0) {
885                         status = cf_util_get_string (child, &host->event_service_prefix);
886                         if (status != 0)
887                                 break;
888                 } else if (strcasecmp ("CheckThresholds", child->key) == 0) {
889                         status = cf_util_get_boolean(child, &host->check_thresholds);
890                         if (status != 0)
891                                 break;
892         } else if (strcasecmp ("Batch", child->key) == 0) {
893             status = cf_util_get_boolean(child, &host->batch_mode);
894             if (status != 0)
895                 break;
896         } else if (strcasecmp("BatchMaxSize", child->key) == 0) {
897             status = cf_util_get_int(child, &host->batch_max);
898             if (status != 0)
899                 break;
900                 } else if (strcasecmp ("Port", child->key) == 0) {
901                         status = cf_util_get_service (child, &host->service);
902                         if (status != 0) {
903                                 ERROR ("write_riemann plugin: Invalid argument "
904                                                 "configured for the \"Port\" "
905                                                 "option.");
906                                 break;
907                         }
908                 } else if (strcasecmp ("Protocol", child->key) == 0) {
909                         char tmp[16];
910                         status = cf_util_get_string_buffer (child,
911                                         tmp, sizeof (tmp));
912                         if (status != 0)
913                         {
914                                 ERROR ("write_riemann plugin: cf_util_get_"
915                                                 "string_buffer failed with "
916                                                 "status %i.", status);
917                                 break;
918                         }
920                         if (strcasecmp ("UDP", tmp) == 0)
921                                 host->use_tcp = 0;
922                         else if (strcasecmp ("TCP", tmp) == 0)
923                                 host->use_tcp = 1;
924                         else
925                                 WARNING ("write_riemann plugin: The value "
926                                                 "\"%s\" is not valid for the "
927                                                 "\"Protocol\" option. Use "
928                                                 "either \"UDP\" or \"TCP\".",
929                                                 tmp);
930                 } else if (strcasecmp ("StoreRates", child->key) == 0) {
931                         status = cf_util_get_boolean (child, &host->store_rates);
932                         if (status != 0)
933                                 break;
934                 } else if (strcasecmp ("AlwaysAppendDS", child->key) == 0) {
935                         status = cf_util_get_boolean (child,
936                                         &host->always_append_ds);
937                         if (status != 0)
938                                 break;
939                 } else if (strcasecmp ("TTLFactor", child->key) == 0) {
940                         double tmp = NAN;
941                         status = cf_util_get_double (child, &tmp);
942                         if (status != 0)
943                                 break;
944                         if (tmp >= 2.0) {
945                                 host->ttl_factor = tmp;
946                         } else if (tmp >= 1.0) {
947                                 NOTICE ("write_riemann plugin: The configured "
948                                                 "TTLFactor is very small "
949                                                 "(%.1f). A value of 2.0 or "
950                                                 "greater is recommended.",
951                                                 tmp);
952                                 host->ttl_factor = tmp;
953                         } else if (tmp > 0.0) {
954                                 WARNING ("write_riemann plugin: The configured "
955                                                 "TTLFactor is too small to be "
956                                                 "useful (%.1f). I'll use it "
957                                                 "since the user knows best, "
958                                                 "but under protest.",
959                                                 tmp);
960                                 host->ttl_factor = tmp;
961                         } else { /* zero, negative and NAN */
962                                 ERROR ("write_riemann plugin: The configured "
963                                                 "TTLFactor is invalid (%.1f).",
964                                                 tmp);
965                         }
966                 } else {
967                         WARNING("write_riemann plugin: ignoring unknown config "
968                                 "option: \"%s\"", child->key);
969                 }
970         }
971         if (status != 0) {
972                 riemann_free (host);
973                 return status;
974         }
976         ssnprintf (callback_name, sizeof (callback_name), "write_riemann/%s",
977                         host->name);
978         ud.data = host;
979         ud.free_func = riemann_free;
981         pthread_mutex_lock (&host->lock);
983         status = plugin_register_write (callback_name, riemann_write, &ud);
985     if (host->use_tcp == 1 && host->batch_mode) {
986         ud.free_func = NULL;
987         plugin_register_flush(callback_name, riemann_batch_flush, &ud);
988     }
989         if (status != 0)
990                 WARNING ("write_riemann plugin: plugin_register_write (\"%s\") "
991                                 "failed with status %i.",
992                                 callback_name, status);
993         else /* success */
994                 host->reference_count++;
996         status = plugin_register_notification (callback_name,
997                         riemann_notification, &ud);
998         if (status != 0)
999                 WARNING ("write_riemann plugin: plugin_register_notification (\"%s\") "
1000                                 "failed with status %i.",
1001                                 callback_name, status);
1002         else /* success */
1003                 host->reference_count++;
1005         if (host->reference_count <= 1)
1006         {
1007                 /* Both callbacks failed => free memory.
1008                  * We need to unlock here, because riemann_free() will lock.
1009                  * This is not a race condition, because we're the only one
1010                  * holding a reference. */
1011                 pthread_mutex_unlock (&host->lock);
1012                 riemann_free (host);
1013                 return (-1);
1014         }
1016         host->reference_count--;
1017         pthread_mutex_unlock (&host->lock);
1019         return status;
1020 } /* }}} int riemann_config_node */
1022 static int riemann_config(oconfig_item_t *ci) /* {{{ */
1024         int              i;
1025         oconfig_item_t  *child;
1026         int              status;
1028         for (i = 0; i < ci->children_num; i++)  {
1029                 child = &ci->children[i];
1031                 if (strcasecmp("Node", child->key) == 0) {
1032                         riemann_config_node (child);
1033                 } else if (strcasecmp(child->key, "attribute") == 0) {
1034                         char *key = NULL;
1035                         char *val = NULL;
1037                         if (child->values_num != 2) {
1038                                 WARNING("riemann attributes need both a key and a value.");
1039                                 return (-1);
1040                         }
1041                         if (child->values[0].type != OCONFIG_TYPE_STRING ||
1042                             child->values[1].type != OCONFIG_TYPE_STRING) {
1043                                 WARNING("riemann attribute needs string arguments.");
1044                                 return (-1);
1045                         }
1046                         if ((key = strdup(child->values[0].value.string)) == NULL) {
1047                                 WARNING("cannot allocate memory for attribute key.");
1048                                 return (-1);
1049                         }
1050                         if ((val = strdup(child->values[1].value.string)) == NULL) {
1051                                 WARNING("cannot allocate memory for attribute value.");
1052                                 sfree (key);
1053                                 return (-1);
1054                         }
1055                         strarray_add(&riemann_attrs, &riemann_attrs_num, key);
1056                         strarray_add(&riemann_attrs, &riemann_attrs_num, val);
1057                         DEBUG("write_riemann: got attr: %s => %s", key, val);
1058                         sfree(key);
1059                         sfree(val);
1060                 } else if (strcasecmp(child->key, "tag") == 0) {
1061                         char *tmp = NULL;
1062                         status = cf_util_get_string(child, &tmp);
1063                         if (status != 0)
1064                                 continue;
1066                         strarray_add (&riemann_tags, &riemann_tags_num, tmp);
1067                         DEBUG("write_riemann plugin: Got tag: %s", tmp);
1068                         sfree (tmp);
1069                 } else {
1070                         WARNING ("write_riemann plugin: Ignoring unknown "
1071                                  "configuration option \"%s\" at top level.",
1072                                  child->key);
1073                 }
1074         }
1075         return (0);
1076 } /* }}} int riemann_config */
1078 void module_register(void)
1080         plugin_register_complex_config ("write_riemann", riemann_config);
1083 /* vim: set sw=8 sts=8 ts=8 noet : */