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