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