Merge pull request #1646 from rubenk/cleanup-malloc-calls
[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  */
28
29 #include <arpa/inet.h>
30 #include <errno.h>
31 #include <netdb.h>
32 #include <inttypes.h>
33 #include <pthread.h>
34
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"
42
43 #define RIEMANN_HOST            "localhost"
44 #define RIEMANN_PORT            "5555"
45 #define RIEMANN_TTL_FACTOR      2.0
46 #define RIEMANN_BATCH_MAX      8192
47
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 };
69
70 static char     **riemann_tags;
71 static size_t     riemann_tags_num;
72 static char     **riemann_attrs;
73 static size_t     riemann_attrs_num;
74
75 static void riemann_event_protobuf_free (Event *event) /* {{{ */
76 {
77         size_t i;
78
79         if (event == NULL)
80                 return;
81
82         sfree (event->state);
83         sfree (event->service);
84         sfree (event->host);
85         sfree (event->description);
86
87         strarray_free (event->tags, event->n_tags);
88         event->tags = NULL;
89         event->n_tags = 0;
90
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;
99
100         sfree (event);
101 } /* }}} void riemann_event_protobuf_free */
102
103 static void riemann_msg_protobuf_free(Msg *msg) /* {{{ */
104 {
105         size_t i;
106
107         if (msg == NULL)
108                 return;
109
110         for (i = 0; i < msg->n_events; i++)
111         {
112                 riemann_event_protobuf_free (msg->events[i]);
113                 msg->events[i] = NULL;
114         }
115
116         sfree (msg->events);
117         msg->n_events = 0;
118
119         sfree (msg);
120 } /* }}} void riemann_msg_protobuf_free */
121
122 /* host->lock must be held when calling this function. */
123 static int riemann_connect(struct riemann_host *host) /* {{{ */
124 {
125         int                      e;
126         struct addrinfo         *ai, *res, hints;
127         char const              *node;
128         char const              *service;
129
130         if (host->flags & F_CONNECT)
131                 return 0;
132
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
140
141         node = (host->node != NULL) ? host->node : RIEMANN_HOST;
142         service = (host->service != NULL) ? host->service : RIEMANN_PORT;
143
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         }
149
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                 }
157
158                 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
159                         close(host->s);
160                         host->s = -1;
161                         continue;
162                 }
163
164                 host->flags |= F_CONNECT;
165                 DEBUG("write_riemann plugin: got a successful connection for: %s:%s",
166                                 node, service);
167                 break;
168         }
169
170         freeaddrinfo(res);
171
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 */
179
180 /* host->lock must be held when calling this function. */
181 static int riemann_disconnect (struct riemann_host *host) /* {{{ */
182 {
183         if ((host->flags & F_CONNECT) == 0)
184                 return (0);
185
186         close (host->s);
187         host->s = -1;
188         host->flags &= ~F_CONNECT;
189
190         return (0);
191 } /* }}} int riemann_disconnect */
192
193 static int riemann_send_msg (struct riemann_host *host, const Msg *msg) /* {{{ */
194 {
195         int status = 0;
196         u_char *buffer = NULL;
197         size_t  buffer_len;
198
199         status = riemann_connect (host);
200         if (status != 0)
201                 return status;
202
203         buffer_len = msg__get_packed_size(msg);
204
205         if (host->use_tcp)
206                 buffer_len += 4;
207
208         buffer = calloc (1, buffer_len);
209         if (buffer == NULL) {
210                 ERROR ("write_riemann plugin: calloc failed.");
211                 return ENOMEM;
212         }
213
214         if (host->use_tcp)
215         {
216                 uint32_t length = htonl ((uint32_t) (buffer_len - 4));
217                 memcpy (buffer, &length, 4);
218                 msg__pack(msg, buffer + 4);
219         }
220         else
221         {
222                 msg__pack(msg, buffer);
223         }
224
225         status = (int) swrite (host->s, buffer, buffer_len);
226         if (status != 0)
227         {
228                 char errbuf[1024];
229                 ERROR ("write_riemann plugin: Sending to Riemann at %s:%s failed: %s",
230                                 (host->node != NULL) ? host->node : RIEMANN_HOST,
231                                 (host->service != NULL) ? host->service : RIEMANN_PORT,
232                                 sstrerror (errno, errbuf, sizeof (errbuf)));
233                 sfree (buffer);
234                 return -1;
235         }
236
237         sfree (buffer);
238         return 0;
239 } /* }}} int riemann_send_msg */
240
241 static int riemann_recv_ack(struct riemann_host *host) /* {{{ */
242 {
243         int status = 0;
244         Msg *msg = NULL;
245         uint32_t header;
246
247         status = (int) sread (host->s, &header, 4);
248
249         if (status != 0)
250                 return -1;
251
252         size_t size = ntohl(header);
253
254         // Buffer on the stack since acknowledges are typically small.
255         u_char buffer[size];
256         memset (buffer, 0, size);
257
258         status = (int) sread (host->s, buffer, size);
259
260         if (status != 0)
261                 return status;
262
263         msg = msg__unpack (NULL, size, buffer);
264
265         if (msg == NULL)
266                 return -1;
267
268         if (!msg->ok)
269         {
270                 ERROR ("write_riemann plugin: Sending to Riemann at %s:%s acknowledgement message reported error: %s",
271                                 (host->node != NULL) ? host->node : RIEMANN_HOST,
272                                 (host->service != NULL) ? host->service : RIEMANN_PORT,
273                                 msg->error);
274
275                 msg__free_unpacked(msg, NULL);
276                 return -1;
277         }
278
279         msg__free_unpacked (msg, NULL);
280         return 0;
281 } /* }}} int riemann_recv_ack */
282
283 /**
284  * Function to send messages (Msg) to riemann.
285  *
286  * Acquires the host lock, disconnects on errors.
287  */
288 static int riemann_send(struct riemann_host *host, Msg const *msg) /* {{{ */
289 {
290         int status = 0;
291         pthread_mutex_lock (&host->lock);
292
293         status = riemann_send_msg(host, msg);
294         if (status != 0) {
295                 riemann_disconnect (host);
296                 pthread_mutex_unlock (&host->lock);
297                 return status;
298         }
299
300         /*
301          * For TCP we need to receive message acknowledgemenent.
302          */
303         if (host->use_tcp)
304         {
305                 status = riemann_recv_ack(host);
306
307                 if (status != 0)
308                 {
309                         riemann_disconnect (host);
310                         pthread_mutex_unlock (&host->lock);
311                         return status;
312                 }
313         }
314
315         pthread_mutex_unlock (&host->lock);
316         return 0;
317 } /* }}} int riemann_send */
318
319 static int riemann_event_add_tag (Event *event, char const *tag) /* {{{ */
320 {
321         return (strarray_add (&event->tags, &event->n_tags, tag));
322 } /* }}} int riemann_event_add_tag */
323
324 static int riemann_event_add_attribute(Event *event, /* {{{ */
325                 char const *key, char const *value)
326 {
327         Attribute **new_attributes;
328         Attribute *a;
329
330         new_attributes = realloc (event->attributes,
331                         sizeof (*event->attributes) * (event->n_attributes + 1));
332         if (new_attributes == NULL)
333         {
334                 ERROR ("write_riemann plugin: realloc failed.");
335                 return (ENOMEM);
336         }
337         event->attributes = new_attributes;
338
339         a = malloc (sizeof (*a));
340         if (a == NULL)
341         {
342                 ERROR ("write_riemann plugin: malloc failed.");
343                 return (ENOMEM);
344         }
345         attribute__init (a);
346
347         a->key = strdup (key);
348         if (value != NULL)
349                 a->value = strdup (value);
350
351         event->attributes[event->n_attributes] = a;
352         event->n_attributes++;
353
354         return (0);
355 } /* }}} int riemann_event_add_attribute */
356
357 static Msg *riemann_notification_to_protobuf(struct riemann_host *host, /* {{{ */
358                 notification_t const *n)
359 {
360         Msg *msg;
361         Event *event;
362         char service_buffer[6 * DATA_MAX_NAME_LEN];
363         char const *severity;
364         notification_meta_t *meta;
365         size_t i;
366
367         msg = calloc (1, sizeof (*msg));
368         if (msg == NULL)
369         {
370                 ERROR ("write_riemann plugin: calloc failed.");
371                 return (NULL);
372         }
373         msg__init (msg);
374
375         msg->events = malloc (sizeof (*msg->events));
376         if (msg->events == NULL)
377         {
378                 ERROR ("write_riemann plugin: malloc failed.");
379                 sfree (msg);
380                 return (NULL);
381         }
382
383         event = calloc (1, sizeof (*event));
384         if (event == NULL)
385         {
386                 ERROR ("write_riemann plugin: calloc failed.");
387                 sfree (msg->events);
388                 sfree (msg);
389                 return (NULL);
390         }
391         event__init (event);
392
393         msg->events[0] = event;
394         msg->n_events = 1;
395
396         event->host = strdup (n->host);
397         event->time = CDTIME_T_TO_TIME_T (n->time);
398         event->has_time = 1;
399
400         switch (n->severity)
401         {
402                 case NOTIF_OKAY:        severity = "ok"; break;
403                 case NOTIF_WARNING:     severity = "warning"; break;
404                 case NOTIF_FAILURE:     severity = "critical"; break;
405                 default:                severity = "unknown";
406         }
407         event->state = strdup (severity);
408
409         riemann_event_add_tag (event, "notification");
410         if (n->host[0] != 0)
411                 riemann_event_add_attribute (event, "host", n->host);
412         if (n->plugin[0] != 0)
413                 riemann_event_add_attribute (event, "plugin", n->plugin);
414         if (n->plugin_instance[0] != 0)
415                 riemann_event_add_attribute (event, "plugin_instance",
416                                 n->plugin_instance);
417
418         if (n->type[0] != 0)
419                 riemann_event_add_attribute (event, "type", n->type);
420         if (n->type_instance[0] != 0)
421                 riemann_event_add_attribute (event, "type_instance",
422                                 n->type_instance);
423
424         for (i = 0; i < riemann_attrs_num; i += 2)
425                 riemann_event_add_attribute(event,
426                                             riemann_attrs[i],
427                                             riemann_attrs[i +1]);
428
429         for (i = 0; i < riemann_tags_num; i++)
430                 riemann_event_add_tag (event, riemann_tags[i]);
431
432         format_name (service_buffer, sizeof (service_buffer),
433                         /* host = */ "", n->plugin, n->plugin_instance,
434                         n->type, n->type_instance);
435         event->service = strdup (&service_buffer[1]);
436
437         if (n->message[0] != 0)
438                 riemann_event_add_attribute (event, "description", n->message);
439
440         /* Pull in values from threshold and add extra attributes */
441         for (meta = n->meta; meta != NULL; meta = meta->next)
442         {
443                 if (strcasecmp ("CurrentValue", meta->name) == 0 && meta->type == NM_TYPE_DOUBLE)
444                 {
445                         event->metric_d = meta->nm_value.nm_double;
446                         event->has_metric_d = 1;
447                         continue;
448                 }
449
450                 if (meta->type == NM_TYPE_STRING) {
451                         riemann_event_add_attribute (event, meta->name, meta->nm_value.nm_string);
452                         continue;
453                 }
454         }
455
456         DEBUG ("write_riemann plugin: Successfully created protobuf for notification: "
457                         "host = \"%s\", service = \"%s\", state = \"%s\"",
458                         event->host, event->service, event->state);
459         return (msg);
460 } /* }}} Msg *riemann_notification_to_protobuf */
461
462 static Event *riemann_value_to_protobuf(struct riemann_host const *host, /* {{{ */
463                 data_set_t const *ds,
464                 value_list_t const *vl, size_t index,
465                                          gauge_t const *rates,
466                                          int status)
467 {
468         Event *event;
469         char name_buffer[5 * DATA_MAX_NAME_LEN];
470         char service_buffer[6 * DATA_MAX_NAME_LEN];
471         double ttl;
472         size_t i;
473
474         event = calloc (1, sizeof (*event));
475         if (event == NULL)
476         {
477                 ERROR ("write_riemann plugin: calloc failed.");
478                 return (NULL);
479         }
480         event__init (event);
481
482         event->host = strdup (vl->host);
483         event->time = CDTIME_T_TO_TIME_T (vl->time);
484         event->has_time = 1;
485
486         if (host->check_thresholds) {
487                 switch (status) {
488                         case STATE_OKAY:
489                                 event->state = strdup("ok");
490                                 break;
491                         case STATE_ERROR:
492                                 event->state = strdup("critical");
493                                 break;
494                         case STATE_WARNING:
495                                 event->state = strdup("warning");
496                                 break;
497                         case STATE_MISSING:
498                                 event->state = strdup("unknown");
499                                 break;
500                 }
501         }
502
503         ttl = CDTIME_T_TO_DOUBLE (vl->interval) * host->ttl_factor;
504         event->ttl = (float) ttl;
505         event->has_ttl = 1;
506
507         riemann_event_add_attribute (event, "plugin", vl->plugin);
508         if (vl->plugin_instance[0] != 0)
509                 riemann_event_add_attribute (event, "plugin_instance",
510                                 vl->plugin_instance);
511
512         riemann_event_add_attribute (event, "type", vl->type);
513         if (vl->type_instance[0] != 0)
514                 riemann_event_add_attribute (event, "type_instance",
515                                 vl->type_instance);
516
517         if ((ds->ds[index].type != DS_TYPE_GAUGE) && (rates != NULL))
518         {
519                 char ds_type[DATA_MAX_NAME_LEN];
520
521                 ssnprintf (ds_type, sizeof (ds_type), "%s:rate",
522                                 DS_TYPE_TO_STRING(ds->ds[index].type));
523                 riemann_event_add_attribute (event, "ds_type", ds_type);
524         }
525         else
526         {
527                 riemann_event_add_attribute (event, "ds_type",
528                                 DS_TYPE_TO_STRING(ds->ds[index].type));
529         }
530         riemann_event_add_attribute (event, "ds_name", ds->ds[index].name);
531         {
532                 char ds_index[DATA_MAX_NAME_LEN];
533
534                 ssnprintf (ds_index, sizeof (ds_index), "%zu", index);
535                 riemann_event_add_attribute (event, "ds_index", ds_index);
536         }
537
538         for (i = 0; i < riemann_attrs_num; i += 2)
539                 riemann_event_add_attribute(event,
540                                             riemann_attrs[i],
541                                             riemann_attrs[i +1]);
542
543         for (i = 0; i < riemann_tags_num; i++)
544                 riemann_event_add_tag (event, riemann_tags[i]);
545
546         if (ds->ds[index].type == DS_TYPE_GAUGE)
547         {
548                 event->has_metric_d = 1;
549                 event->metric_d = (double) vl->values[index].gauge;
550         }
551         else if (rates != NULL)
552         {
553                 event->has_metric_d = 1;
554                 event->metric_d = (double) rates[index];
555         }
556         else
557         {
558                 event->has_metric_sint64 = 1;
559                 if (ds->ds[index].type == DS_TYPE_DERIVE)
560                         event->metric_sint64 = (int64_t) vl->values[index].derive;
561                 else if (ds->ds[index].type == DS_TYPE_ABSOLUTE)
562                         event->metric_sint64 = (int64_t) vl->values[index].absolute;
563                 else
564                         event->metric_sint64 = (int64_t) vl->values[index].counter;
565         }
566
567         format_name (name_buffer, sizeof (name_buffer),
568                         /* host = */ "", vl->plugin, vl->plugin_instance,
569                         vl->type, vl->type_instance);
570         if (host->always_append_ds || (ds->ds_num > 1))
571         {
572                 if (host->event_service_prefix == NULL)
573                         ssnprintf (service_buffer, sizeof (service_buffer), "%s/%s",
574                                         &name_buffer[1], ds->ds[index].name);
575                 else
576                         ssnprintf (service_buffer, sizeof (service_buffer), "%s%s/%s",
577                                         host->event_service_prefix, &name_buffer[1], ds->ds[index].name);
578         }
579         else
580         {
581                 if (host->event_service_prefix == NULL)
582                         sstrncpy (service_buffer, &name_buffer[1], sizeof (service_buffer));
583                 else
584                         ssnprintf (service_buffer, sizeof (service_buffer), "%s%s",
585                                         host->event_service_prefix, &name_buffer[1]);
586         }
587
588         event->service = strdup (service_buffer);
589
590         DEBUG ("write_riemann plugin: Successfully created protobuf for metric: "
591                         "host = \"%s\", service = \"%s\"",
592                         event->host, event->service);
593         return (event);
594 } /* }}} Event *riemann_value_to_protobuf */
595
596 static Msg *riemann_value_list_to_protobuf (struct riemann_host const *host, /* {{{ */
597                                             data_set_t const *ds,
598                                             value_list_t const *vl,
599                                             int *statuses)
600 {
601         Msg *msg;
602         size_t i;
603         gauge_t *rates = NULL;
604
605         /* Initialize the Msg structure. */
606         msg = calloc (1, sizeof (*msg));
607         if (msg == NULL)
608         {
609                 ERROR ("write_riemann plugin: calloc failed.");
610                 return (NULL);
611         }
612         msg__init (msg);
613
614         /* Set up events. First, the list of pointers. */
615         msg->n_events = vl->values_len;
616         msg->events = calloc (msg->n_events, sizeof (*msg->events));
617         if (msg->events == NULL)
618         {
619                 ERROR ("write_riemann plugin: calloc failed.");
620                 riemann_msg_protobuf_free (msg);
621                 return (NULL);
622         }
623
624         if (host->store_rates)
625         {
626                 rates = uc_get_rate (ds, vl);
627                 if (rates == NULL)
628                 {
629                         ERROR ("write_riemann plugin: uc_get_rate failed.");
630                         riemann_msg_protobuf_free (msg);
631                         return (NULL);
632                 }
633         }
634
635         for (i = 0; i < msg->n_events; i++)
636         {
637                 msg->events[i] = riemann_value_to_protobuf (host, ds, vl,
638                                                             (int) i, rates, statuses[i]);
639                 if (msg->events[i] == NULL)
640                 {
641                         riemann_msg_protobuf_free (msg);
642                         sfree (rates);
643                         return (NULL);
644                 }
645         }
646
647         sfree (rates);
648         return (msg);
649 } /* }}} Msg *riemann_value_list_to_protobuf */
650
651
652 /*
653  * Always call while holding host->lock !
654  */
655 static int riemann_batch_flush_nolock (cdtime_t timeout,
656                                        struct riemann_host *host)
657 {
658     cdtime_t    now;
659     int         status = 0;
660
661     if (timeout > 0) {
662         now = cdtime ();
663         if ((host->batch_init + timeout) > now)
664             return status;
665     }
666     riemann_send_msg(host, host->batch_msg);
667     riemann_msg_protobuf_free(host->batch_msg);
668
669         if (host->use_tcp && ((status = riemann_recv_ack(host)) != 0))
670         riemann_disconnect (host);
671
672     host->batch_init = cdtime();
673     host->batch_msg = NULL;
674     return status;
675 }
676
677 static int riemann_batch_flush (cdtime_t timeout,
678         const char *identifier __attribute__((unused)),
679         user_data_t *user_data)
680 {
681     struct riemann_host *host;
682     int status;
683
684     if (user_data == NULL)
685         return (-EINVAL);
686
687     host = user_data->data;
688     pthread_mutex_lock (&host->lock);
689     status = riemann_batch_flush_nolock (timeout, host);
690     if (status != 0)
691         ERROR ("write_riemann plugin: riemann_send failed with status %i",
692                status);
693
694     pthread_mutex_unlock(&host->lock);
695     return status;
696 }
697
698 static int riemann_batch_add_value_list (struct riemann_host *host, /* {{{ */
699                                          data_set_t const *ds,
700                                          value_list_t const *vl,
701                                          int *statuses)
702 {
703         size_t i;
704     Event **events;
705     Msg *msg;
706     size_t len;
707     int ret;
708
709     msg = riemann_value_list_to_protobuf (host, ds, vl, statuses);
710     if (msg == NULL)
711         return -1;
712
713     pthread_mutex_lock(&host->lock);
714
715     if (host->batch_msg == NULL) {
716         host->batch_msg = msg;
717     } else {
718         len = msg->n_events + host->batch_msg->n_events;
719         events = realloc(host->batch_msg->events,
720                          (len * sizeof(*host->batch_msg->events)));
721         if (events == NULL) {
722             pthread_mutex_unlock(&host->lock);
723             ERROR ("write_riemann plugin: out of memory");
724             riemann_msg_protobuf_free (msg);
725             return -1;
726         }
727         host->batch_msg->events = events;
728
729         for (i = host->batch_msg->n_events; i < len; i++)
730             host->batch_msg->events[i] = msg->events[i - host->batch_msg->n_events];
731
732         host->batch_msg->n_events = len;
733         sfree (msg->events);
734         msg->n_events = 0;
735         sfree (msg);
736     }
737
738         len = msg__get_packed_size(host->batch_msg);
739     ret = 0;
740     if ((host->batch_max < 0) || (((size_t) host->batch_max) <= len)) {
741             ret = riemann_batch_flush_nolock(0, host);
742     }
743
744     pthread_mutex_unlock(&host->lock);
745     return ret;
746 } /* }}} Msg *riemann_batch_add_value_list */
747
748 static int riemann_notification(const notification_t *n, user_data_t *ud) /* {{{ */
749 {
750         int                      status;
751         struct riemann_host     *host = ud->data;
752         Msg                     *msg;
753
754         if (!host->notifications)
755                 return 0;
756
757     /*
758      * Never batch for notifications, send them ASAP
759      */
760         msg = riemann_notification_to_protobuf (host, n);
761         if (msg == NULL)
762                 return (-1);
763
764         status = riemann_send (host, msg);
765         if (status != 0)
766                 ERROR ("write_riemann plugin: riemann_send failed with status %i",
767                                 status);
768
769         riemann_msg_protobuf_free (msg);
770         return (status);
771 } /* }}} int riemann_notification */
772
773 static int riemann_write(const data_set_t *ds, /* {{{ */
774                 const value_list_t *vl,
775                 user_data_t *ud)
776 {
777         int                      status = 0;
778         int                      statuses[vl->values_len];
779         struct riemann_host     *host = ud->data;
780
781         if (host->check_thresholds) {
782                 status = write_riemann_threshold_check(ds, vl, statuses);
783                 if (status != 0)
784                         return status;
785         } else {
786                 memset (statuses, 0, sizeof (statuses));
787         }
788
789         if (host->use_tcp == 1 && host->batch_mode) {
790                 riemann_batch_add_value_list (host, ds, vl, statuses);
791         } else {
792                 Msg *msg = riemann_value_list_to_protobuf (host, ds, vl, statuses);
793                 if (msg == NULL)
794                         return (-1);
795
796                 status = riemann_send (host, msg);
797                 if (status != 0)
798                         ERROR ("write_riemann plugin: riemann_send failed with status %i", status);
799
800                 riemann_msg_protobuf_free (msg);
801         }
802
803         return status;
804 } /* }}} int riemann_write */
805
806 static void riemann_free(void *p) /* {{{ */
807 {
808         struct riemann_host     *host = p;
809
810         if (host == NULL)
811                 return;
812
813         pthread_mutex_lock (&host->lock);
814
815         host->reference_count--;
816         if (host->reference_count > 0)
817         {
818                 pthread_mutex_unlock (&host->lock);
819                 return;
820         }
821
822         riemann_disconnect (host);
823
824         sfree(host->service);
825         pthread_mutex_destroy (&host->lock);
826         sfree(host);
827 } /* }}} void riemann_free */
828
829 static int riemann_config_node(oconfig_item_t *ci) /* {{{ */
830 {
831         struct riemann_host     *host = NULL;
832         int                      status = 0;
833         int                      i;
834         oconfig_item_t          *child;
835         char                     callback_name[DATA_MAX_NAME_LEN];
836         user_data_t              ud;
837
838         if ((host = calloc(1, sizeof (*host))) == NULL) {
839                 ERROR ("write_riemann plugin: calloc failed.");
840                 return ENOMEM;
841         }
842         pthread_mutex_init (&host->lock, NULL);
843         host->reference_count = 1;
844         host->node = NULL;
845         host->service = NULL;
846         host->notifications = 1;
847         host->check_thresholds = 0;
848         host->store_rates = 1;
849         host->always_append_ds = 0;
850         host->use_tcp = 1;
851         host->batch_mode = 1;
852         host->batch_max = RIEMANN_BATCH_MAX; /* typical MSS */
853         host->batch_init = cdtime();
854         host->ttl_factor = RIEMANN_TTL_FACTOR;
855
856         status = cf_util_get_string (ci, &host->name);
857         if (status != 0) {
858                 WARNING("write_riemann plugin: Required host name is missing.");
859                 riemann_free (host);
860                 return -1;
861         }
862
863         for (i = 0; i < ci->children_num; i++) {
864                 /*
865                  * The code here could be simplified but makes room
866                  * for easy adding of new options later on.
867                  */
868                 child = &ci->children[i];
869                 status = 0;
870
871                 if (strcasecmp ("Host", child->key) == 0) {
872                         status = cf_util_get_string (child, &host->node);
873                         if (status != 0)
874                                 break;
875                 } else if (strcasecmp ("Notifications", child->key) == 0) {
876                         status = cf_util_get_boolean(child, &host->notifications);
877                         if (status != 0)
878                                 break;
879                 } else if (strcasecmp ("EventServicePrefix", child->key) == 0) {
880                         status = cf_util_get_string (child, &host->event_service_prefix);
881                         if (status != 0)
882                                 break;
883                 } else if (strcasecmp ("CheckThresholds", child->key) == 0) {
884                         status = cf_util_get_boolean(child, &host->check_thresholds);
885                         if (status != 0)
886                                 break;
887         } else if (strcasecmp ("Batch", child->key) == 0) {
888             status = cf_util_get_boolean(child, &host->batch_mode);
889             if (status != 0)
890                 break;
891         } else if (strcasecmp("BatchMaxSize", child->key) == 0) {
892             status = cf_util_get_int(child, &host->batch_max);
893             if (status != 0)
894                 break;
895                 } else if (strcasecmp ("Port", child->key) == 0) {
896                         status = cf_util_get_service (child, &host->service);
897                         if (status != 0) {
898                                 ERROR ("write_riemann plugin: Invalid argument "
899                                                 "configured for the \"Port\" "
900                                                 "option.");
901                                 break;
902                         }
903                 } else if (strcasecmp ("Protocol", child->key) == 0) {
904                         char tmp[16];
905                         status = cf_util_get_string_buffer (child,
906                                         tmp, sizeof (tmp));
907                         if (status != 0)
908                         {
909                                 ERROR ("write_riemann plugin: cf_util_get_"
910                                                 "string_buffer failed with "
911                                                 "status %i.", status);
912                                 break;
913                         }
914
915                         if (strcasecmp ("UDP", tmp) == 0)
916                                 host->use_tcp = 0;
917                         else if (strcasecmp ("TCP", tmp) == 0)
918                                 host->use_tcp = 1;
919                         else
920                                 WARNING ("write_riemann plugin: The value "
921                                                 "\"%s\" is not valid for the "
922                                                 "\"Protocol\" option. Use "
923                                                 "either \"UDP\" or \"TCP\".",
924                                                 tmp);
925                 } else if (strcasecmp ("StoreRates", child->key) == 0) {
926                         status = cf_util_get_boolean (child, &host->store_rates);
927                         if (status != 0)
928                                 break;
929                 } else if (strcasecmp ("AlwaysAppendDS", child->key) == 0) {
930                         status = cf_util_get_boolean (child,
931                                         &host->always_append_ds);
932                         if (status != 0)
933                                 break;
934                 } else if (strcasecmp ("TTLFactor", child->key) == 0) {
935                         double tmp = NAN;
936                         status = cf_util_get_double (child, &tmp);
937                         if (status != 0)
938                                 break;
939                         if (tmp >= 2.0) {
940                                 host->ttl_factor = tmp;
941                         } else if (tmp >= 1.0) {
942                                 NOTICE ("write_riemann plugin: The configured "
943                                                 "TTLFactor is very small "
944                                                 "(%.1f). A value of 2.0 or "
945                                                 "greater is recommended.",
946                                                 tmp);
947                                 host->ttl_factor = tmp;
948                         } else if (tmp > 0.0) {
949                                 WARNING ("write_riemann plugin: The configured "
950                                                 "TTLFactor is too small to be "
951                                                 "useful (%.1f). I'll use it "
952                                                 "since the user knows best, "
953                                                 "but under protest.",
954                                                 tmp);
955                                 host->ttl_factor = tmp;
956                         } else { /* zero, negative and NAN */
957                                 ERROR ("write_riemann plugin: The configured "
958                                                 "TTLFactor is invalid (%.1f).",
959                                                 tmp);
960                         }
961                 } else {
962                         WARNING("write_riemann plugin: ignoring unknown config "
963                                 "option: \"%s\"", child->key);
964                 }
965         }
966         if (status != 0) {
967                 riemann_free (host);
968                 return status;
969         }
970
971         ssnprintf (callback_name, sizeof (callback_name), "write_riemann/%s",
972                         host->name);
973         ud.data = host;
974         ud.free_func = riemann_free;
975
976         pthread_mutex_lock (&host->lock);
977
978         status = plugin_register_write (callback_name, riemann_write, &ud);
979
980     if (host->use_tcp == 1 && host->batch_mode) {
981         ud.free_func = NULL;
982         plugin_register_flush(callback_name, riemann_batch_flush, &ud);
983     }
984         if (status != 0)
985                 WARNING ("write_riemann plugin: plugin_register_write (\"%s\") "
986                                 "failed with status %i.",
987                                 callback_name, status);
988         else /* success */
989                 host->reference_count++;
990
991         status = plugin_register_notification (callback_name,
992                         riemann_notification, &ud);
993         if (status != 0)
994                 WARNING ("write_riemann plugin: plugin_register_notification (\"%s\") "
995                                 "failed with status %i.",
996                                 callback_name, status);
997         else /* success */
998                 host->reference_count++;
999
1000         if (host->reference_count <= 1)
1001         {
1002                 /* Both callbacks failed => free memory.
1003                  * We need to unlock here, because riemann_free() will lock.
1004                  * This is not a race condition, because we're the only one
1005                  * holding a reference. */
1006                 pthread_mutex_unlock (&host->lock);
1007                 riemann_free (host);
1008                 return (-1);
1009         }
1010
1011         host->reference_count--;
1012         pthread_mutex_unlock (&host->lock);
1013
1014         return status;
1015 } /* }}} int riemann_config_node */
1016
1017 static int riemann_config(oconfig_item_t *ci) /* {{{ */
1018 {
1019         int              i;
1020         oconfig_item_t  *child;
1021         int              status;
1022
1023         for (i = 0; i < ci->children_num; i++)  {
1024                 child = &ci->children[i];
1025
1026                 if (strcasecmp("Node", child->key) == 0) {
1027                         riemann_config_node (child);
1028                 } else if (strcasecmp(child->key, "attribute") == 0) {
1029                         char *key = NULL;
1030                         char *val = NULL;
1031
1032                         if (child->values_num != 2) {
1033                                 WARNING("riemann attributes need both a key and a value.");
1034                                 return (-1);
1035                         }
1036                         if (child->values[0].type != OCONFIG_TYPE_STRING ||
1037                             child->values[1].type != OCONFIG_TYPE_STRING) {
1038                                 WARNING("riemann attribute needs string arguments.");
1039                                 return (-1);
1040                         }
1041                         if ((key = strdup(child->values[0].value.string)) == NULL) {
1042                                 WARNING("cannot allocate memory for attribute key.");
1043                                 return (-1);
1044                         }
1045                         if ((val = strdup(child->values[1].value.string)) == NULL) {
1046                                 WARNING("cannot allocate memory for attribute value.");
1047                                 sfree (key);
1048                                 return (-1);
1049                         }
1050                         strarray_add(&riemann_attrs, &riemann_attrs_num, key);
1051                         strarray_add(&riemann_attrs, &riemann_attrs_num, val);
1052                         DEBUG("write_riemann: got attr: %s => %s", key, val);
1053                         sfree(key);
1054                         sfree(val);
1055                 } else if (strcasecmp(child->key, "tag") == 0) {
1056                         char *tmp = NULL;
1057                         status = cf_util_get_string(child, &tmp);
1058                         if (status != 0)
1059                                 continue;
1060
1061                         strarray_add (&riemann_tags, &riemann_tags_num, tmp);
1062                         DEBUG("write_riemann plugin: Got tag: %s", tmp);
1063                         sfree (tmp);
1064                 } else {
1065                         WARNING ("write_riemann plugin: Ignoring unknown "
1066                                  "configuration option \"%s\" at top level.",
1067                                  child->key);
1068                 }
1069         }
1070         return (0);
1071 } /* }}} int riemann_config */
1072
1073 void module_register(void)
1074 {
1075         plugin_register_complex_config ("write_riemann", riemann_config);
1076 }
1077
1078 /* vim: set sw=8 sts=8 ts=8 noet : */