Merge branch 'collectd-5.5'
[collectd.git] / src / write_sensu.c
1 /**
2  * collectd - src/write_sensu.c
3  * Copyright (C) 2015 Fabrice A. Marie
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Fabrice A. Marie <fabrice at kibinlabs.com>
25  */
26
27 #include "collectd.h"
28 #include "plugin.h"
29 #include "common.h"
30 #include "configfile.h"
31 #include "utils_cache.h"
32 #include <arpa/inet.h>
33 #include <errno.h>
34 #include <netdb.h>
35 #include <inttypes.h>
36 #include <pthread.h>
37 #include <stddef.h>
38
39 #include <stdlib.h>
40 #ifndef HAVE_ASPRINTF
41 /*
42  * Uses asprintf() portable implementation from
43  * https://github.com/littlstar/asprintf.c/blob/master/
44  * copyright (c) 2014 joseph werle <joseph.werle@gmail.com> under MIT license.
45  */
46 #include <stdio.h>
47 #include <stdarg.h>
48
49 int vasprintf(char **str, const char *fmt, va_list args) {
50         int size = 0;
51         va_list tmpa;
52         // copy
53         va_copy(tmpa, args);
54         // apply variadic arguments to
55         // sprintf with format to get size
56         size = vsnprintf(NULL, size, fmt, tmpa);
57         // toss args
58         va_end(tmpa);
59         // return -1 to be compliant if
60         // size is less than 0
61         if (size < 0) { return -1; }
62         // alloc with size plus 1 for `\0'
63         *str = (char *) malloc(size + 1);
64         // return -1 to be compliant
65         // if pointer is `NULL'
66         if (NULL == *str) { return -1; }
67         // format string with original
68         // variadic arguments and set new size
69         size = vsprintf(*str, fmt, args);
70         return size;
71 }
72
73 int asprintf(char **str, const char *fmt, ...) {
74         int size = 0;
75         va_list args;
76         // init variadic argumens
77         va_start(args, fmt);
78         // format and get size
79         size = vasprintf(str, fmt, args);
80         // toss args
81         va_end(args);
82         return size;
83 }
84
85 #endif
86
87 #define SENSU_HOST              "localhost"
88 #define SENSU_PORT              "3030"
89
90 struct str_list {
91         int nb_strs;
92         char **strs;
93 };
94
95 struct sensu_host {
96         char                    *name;
97         char                    *event_service_prefix;
98         struct str_list metric_handlers;
99         struct str_list notification_handlers;
100 #define F_READY      0x01
101         uint8_t                  flags;
102         pthread_mutex_t  lock;
103         _Bool            notifications;
104         _Bool            metrics;
105         _Bool                    store_rates;
106         _Bool                    always_append_ds;
107         char                    *separator;
108         char                    *node;
109         char                    *service;
110         int              s;
111         struct addrinfo *res;
112         int                          reference_count;
113 };
114
115 static char     *sensu_tags = NULL;
116 static char     **sensu_attrs = NULL;
117 static size_t sensu_attrs_num;
118
119 static int add_str_to_list(struct str_list *strs,
120                 const char *str_to_add) /* {{{ */
121 {
122         char **old_strs_ptr = strs->strs;
123         char *newstr = strdup(str_to_add);
124         if (newstr == NULL) {
125                 ERROR("write_sensu plugin: Unable to alloc memory");
126                 return -1;
127         }
128         strs->strs = realloc(strs->strs, sizeof(char *) *(strs->nb_strs + 1));
129         if (strs->strs == NULL) {
130                 strs->strs = old_strs_ptr;
131                 free(newstr);
132                 ERROR("write_sensu plugin: Unable to alloc memory");
133                 return -1;
134         }
135         strs->strs[strs->nb_strs] = newstr;
136         strs->nb_strs++;
137         return 0;
138 }
139 /* }}} int add_str_to_list */
140
141 static void free_str_list(struct str_list *strs) /* {{{ */
142 {
143         int i;
144         for (i=0; i<strs->nb_strs; i++)
145                 free(strs->strs[i]);
146         free(strs->strs);
147 }
148 /* }}} void free_str_list */
149
150 static int sensu_connect(struct sensu_host *host) /* {{{ */
151 {
152         int                      e;
153         struct addrinfo         *ai, hints;
154         char const              *node;
155         char const              *service;
156
157         // Resolve the target if we haven't done already
158         if (!(host->flags & F_READY)) {
159                 memset(&hints, 0, sizeof(hints));
160                 memset(&service, 0, sizeof(service));
161                 host->res = NULL;
162                 hints.ai_family = AF_INET;
163                 hints.ai_socktype = SOCK_STREAM;
164 #ifdef AI_ADDRCONFIG
165                 hints.ai_flags |= AI_ADDRCONFIG;
166 #endif
167
168                 node = (host->node != NULL) ? host->node : SENSU_HOST;
169                 service = (host->service != NULL) ? host->service : SENSU_PORT;
170
171                 if ((e = getaddrinfo(node, service, &hints, &(host->res))) != 0) {
172                         ERROR("write_sensu plugin: Unable to resolve host \"%s\": %s",
173                                         node, gai_strerror(e));
174                         return -1;
175                 }
176                 DEBUG("write_sensu plugin: successfully resolved host/port: %s/%s",
177                                 node, service);
178                 host->flags |= F_READY;
179         }
180
181         struct linger so_linger;
182         host->s = -1;
183         for (ai = host->res; ai != NULL; ai = ai->ai_next) {
184                 // create the socket
185                 if ((host->s = socket(ai->ai_family,
186                                       ai->ai_socktype,
187                                       ai->ai_protocol)) == -1) {
188                         continue;
189                 }
190
191                 // Set very low close() lingering
192                 so_linger.l_onoff = 1;
193                 so_linger.l_linger = 3;
194                 if (setsockopt(host->s, SOL_SOCKET, SO_LINGER, &so_linger, sizeof so_linger) != 0)
195                         WARNING("write_sensu plugin: failed to set socket close() lingering");
196
197                 // connect the socket
198                 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
199                         close(host->s);
200                         host->s = -1;
201                         continue;
202                 }
203                 DEBUG("write_sensu plugin: connected");
204                 break;
205         }
206
207         if (host->s < 0) {
208                 WARNING("write_sensu plugin: Unable to connect to sensu client");
209                 return -1;
210         }
211         return 0;
212 } /* }}} int sensu_connect */
213
214 static void sensu_close_socket(struct sensu_host *host) /* {{{ */
215 {
216         if (host->s != -1)
217                 close(host->s);
218         host->s = -1;
219
220 } /* }}} void sensu_close_socket */
221
222 static char *build_json_str_list(const char *tag, struct str_list const *list) /* {{{ */
223 {
224         int res;
225         char *ret_str;
226         char *temp_str;
227         int i;
228         if (list->nb_strs == 0) {
229                 ret_str = malloc(sizeof(char));
230                 if (ret_str == NULL) {
231                         ERROR("write_sensu plugin: Unable to alloc memory");
232                         return NULL;
233                 }
234                 ret_str[0] = '\0';
235         }
236
237         res = asprintf(&temp_str, "\"%s\": [\"%s\"", tag, list->strs[0]);
238         if (res == -1) {
239                 ERROR("write_sensu plugin: Unable to alloc memory");
240                 return NULL;
241         }
242         for (i=1; i<list->nb_strs; i++) {
243                 res = asprintf(&ret_str, "%s, \"%s\"", temp_str, list->strs[i]);
244                 free(temp_str);
245                 if (res == -1) {
246                         ERROR("write_sensu plugin: Unable to alloc memory");
247                         return NULL;
248                 }
249                 temp_str = ret_str;
250         }
251         res = asprintf(&ret_str, "%s]", temp_str);
252         free(temp_str);
253         if (res == -1) {
254                 ERROR("write_sensu plugin: Unable to alloc memory");
255                 return NULL;
256         }
257
258         return ret_str;
259 } /* }}} char *build_json_str_list*/
260
261 int sensu_format_name2(char *ret, int ret_len,
262                 const char *hostname,
263                 const char *plugin, const char *plugin_instance,
264                 const char *type, const char *type_instance,
265                 const char *separator)
266 {
267         char *buffer;
268         size_t buffer_size;
269
270         buffer = ret;
271         buffer_size = (size_t) ret_len;
272
273 #define APPEND(str) do {          \
274         size_t l = strlen (str);        \
275         if (l >= buffer_size)           \
276                 return (ENOBUFS);             \
277         memcpy (buffer, (str), l);      \
278         buffer += l; buffer_size -= l;  \
279 } while (0)
280
281         assert (plugin != NULL);
282         assert (type != NULL);
283
284         APPEND (hostname);
285         APPEND (separator);
286         APPEND (plugin);
287         if ((plugin_instance != NULL) && (plugin_instance[0] != 0))
288         {
289                 APPEND ("-");
290                 APPEND (plugin_instance);
291         }
292         APPEND (separator);
293         APPEND (type);
294         if ((type_instance != NULL) && (type_instance[0] != 0))
295         {
296                 APPEND ("-");
297                 APPEND (type_instance);
298         }
299         assert (buffer_size > 0);
300         buffer[0] = 0;
301
302 #undef APPEND
303         return (0);
304 } /* int sensu_format_name2 */
305
306 static void in_place_replace_sensu_name_reserved(char *orig_name) /* {{{ */
307 {
308         int i;
309         int len=strlen(orig_name);
310         for (i=0; i<len; i++) {
311                 // some plugins like ipmi generate special characters in metric name
312                 switch(orig_name[i]) {
313                         case '(': orig_name[i] = '_'; break;
314                         case ')': orig_name[i] = '_'; break;
315                         case ' ': orig_name[i] = '_'; break;
316                         case '"': orig_name[i] = '_'; break;
317                         case '\'': orig_name[i] = '_'; break;
318                         case '+': orig_name[i] = '_'; break;
319                 }
320         }
321 } /* }}} char *replace_sensu_name_reserved */
322
323 static char *sensu_value_to_json(struct sensu_host const *host, /* {{{ */
324                 data_set_t const *ds,
325                 value_list_t const *vl, size_t index,
326                 gauge_t const *rates,
327                 int status)
328 {
329         char name_buffer[5 * DATA_MAX_NAME_LEN];
330         char service_buffer[6 * DATA_MAX_NAME_LEN];
331         size_t i;
332         char *ret_str;
333         char *temp_str;
334         char *value_str;
335         int res;
336         // First part of the JSON string
337         const char *part1 = "{\"name\": \"collectd\", \"type\": \"metric\"";
338
339         char *handlers_str = build_json_str_list("handlers", &(host->metric_handlers));
340         if (handlers_str == NULL) {
341                 ERROR("write_sensu plugin: Unable to alloc memory");
342                 return NULL;
343         }
344
345         // incorporate the handlers
346         if (strlen(handlers_str) == 0) {
347                 free(handlers_str);
348                 ret_str = strdup(part1);
349                 if (ret_str == NULL) {
350                         ERROR("write_sensu plugin: Unable to alloc memory");
351                         return NULL;
352                 }
353         }
354         else {
355                 res = asprintf(&ret_str, "%s, %s", part1, handlers_str);
356                 free(handlers_str);
357                 if (res == -1) {
358                         ERROR("write_sensu plugin: Unable to alloc memory");
359                         return NULL;
360                 }
361         }
362
363         // incorporate the plugin name information
364         res = asprintf(&temp_str, "%s, \"collectd_plugin\": \"%s\"", ret_str, vl->plugin);
365         free(ret_str);
366         if (res == -1) {
367                 ERROR("write_sensu plugin: Unable to alloc memory");
368                 return NULL;
369         }
370         ret_str = temp_str;
371
372         // incorporate the plugin type
373         res = asprintf(&temp_str, "%s, \"collectd_plugin_type\": \"%s\"", ret_str, vl->type);
374         free(ret_str);
375         if (res == -1) {
376                 ERROR("write_sensu plugin: Unable to alloc memory");
377                 return NULL;
378         }
379         ret_str = temp_str;
380
381         // incorporate the plugin instance if any
382         if (vl->plugin_instance[0] != 0) {
383                 res = asprintf(&temp_str, "%s, \"collectd_plugin_instance\": \"%s\"", ret_str, vl->plugin_instance);
384                 free(ret_str);
385                 if (res == -1) {
386                         ERROR("write_sensu plugin: Unable to alloc memory");
387                         return NULL;
388                 }
389                 ret_str = temp_str;
390         }
391
392         // incorporate the plugin type instance if any
393         if (vl->type_instance[0] != 0) {
394                 res = asprintf(&temp_str, "%s, \"collectd_plugin_type_instance\": \"%s\"", ret_str, vl->type_instance);
395                 free(ret_str);
396                 if (res == -1) {
397                         ERROR("write_sensu plugin: Unable to alloc memory");
398                         return NULL;
399                 }
400                 ret_str = temp_str;
401         }
402
403         // incorporate the data source type
404         if ((ds->ds[index].type != DS_TYPE_GAUGE) && (rates != NULL)) {
405                 char ds_type[DATA_MAX_NAME_LEN];
406                 ssnprintf (ds_type, sizeof (ds_type), "%s:rate", DS_TYPE_TO_STRING(ds->ds[index].type));
407                 res = asprintf(&temp_str, "%s, \"collectd_data_source_type\": \"%s\"", ret_str, ds_type);
408                 free(ret_str);
409                 if (res == -1) {
410                         ERROR("write_sensu plugin: Unable to alloc memory");
411                         return NULL;
412                 }
413                 ret_str = temp_str;
414         } else {
415                 res = asprintf(&temp_str, "%s, \"collectd_data_source_type\": \"%s\"", ret_str, DS_TYPE_TO_STRING(ds->ds[index].type));
416                 free(ret_str);
417                 if (res == -1) {
418                         ERROR("write_sensu plugin: Unable to alloc memory");
419                         return NULL;
420                 }
421                 ret_str = temp_str;
422         }
423
424         // incorporate the data source name
425         res = asprintf(&temp_str, "%s, \"collectd_data_source_name\": \"%s\"", ret_str, ds->ds[index].name);
426         free(ret_str);
427         if (res == -1) {
428                 ERROR("write_sensu plugin: Unable to alloc memory");
429                 return NULL;
430         }
431         ret_str = temp_str;
432
433         // incorporate the data source index
434         {
435                 char ds_index[DATA_MAX_NAME_LEN];
436                 ssnprintf (ds_index, sizeof (ds_index), "%zu", index);
437                 res = asprintf(&temp_str, "%s, \"collectd_data_source_index\": %s", ret_str, ds_index);
438                 free(ret_str);
439                 if (res == -1) {
440                         ERROR("write_sensu plugin: Unable to alloc memory");
441                         return NULL;
442                 }
443                 ret_str = temp_str;
444         }
445
446         // add key value attributes from config if any
447         for (i = 0; i < sensu_attrs_num; i += 2) {
448                 res = asprintf(&temp_str, "%s, \"%s\": \"%s\"", ret_str, sensu_attrs[i], sensu_attrs[i+1]);
449                 free(ret_str);
450                 if (res == -1) {
451                         ERROR("write_sensu plugin: Unable to alloc memory");
452                         return NULL;
453                 }
454                 ret_str = temp_str;
455         }
456
457         // incorporate sensu tags from config if any
458         if ((sensu_tags != NULL) && (strlen(sensu_tags) != 0)) {
459                 res = asprintf(&temp_str, "%s, %s", ret_str, sensu_tags);
460                 free(ret_str);
461                 if (res == -1) {
462                         ERROR("write_sensu plugin: Unable to alloc memory");
463                         return NULL;
464                 }
465                 ret_str = temp_str;
466         }
467
468         // calculate the value and set to a string
469         if (ds->ds[index].type == DS_TYPE_GAUGE) {
470                 res = asprintf(&value_str, GAUGE_FORMAT, vl->values[index].gauge);
471                 if (res == -1) {
472                         free(ret_str);
473                         ERROR("write_sensu plugin: Unable to alloc memory");
474                         return NULL;
475                 }
476         } else if (rates != NULL) {
477                 res = asprintf(&value_str, GAUGE_FORMAT, rates[index]);
478                 if (res == -1) {
479                         free(ret_str);
480                         ERROR("write_sensu plugin: Unable to alloc memory");
481                         return NULL;
482                 }
483         } else {
484                 if (ds->ds[index].type == DS_TYPE_DERIVE) {
485                         res = asprintf(&value_str, "%"PRIi64, vl->values[index].derive);
486                         if (res == -1) {
487                                 free(ret_str);
488                                 ERROR("write_sensu plugin: Unable to alloc memory");
489                                 return NULL;
490                         }
491                 }
492                 else if (ds->ds[index].type == DS_TYPE_ABSOLUTE) {
493                         res = asprintf(&value_str, "%"PRIu64, vl->values[index].absolute);
494                         if (res == -1) {
495                                 free(ret_str);
496                                 ERROR("write_sensu plugin: Unable to alloc memory");
497                                 return NULL;
498                         }
499                 }
500                 else {
501                         res = asprintf(&value_str, "%llu", vl->values[index].counter);
502                         if (res == -1) {
503                                 free(ret_str);
504                                 ERROR("write_sensu plugin: Unable to alloc memory");
505                                 return NULL;
506                         }
507                 }
508         }
509
510         // Generate the full service name
511         sensu_format_name2(name_buffer, sizeof(name_buffer),
512                 vl->host, vl->plugin, vl->plugin_instance,
513                 vl->type, vl->type_instance, host->separator);
514         if (host->always_append_ds || (ds->ds_num > 1)) {
515                 if (host->event_service_prefix == NULL)
516                         ssnprintf(service_buffer, sizeof(service_buffer), "%s.%s",
517                                         name_buffer, ds->ds[index].name);
518                 else
519                         ssnprintf(service_buffer, sizeof(service_buffer), "%s%s.%s",
520                                         host->event_service_prefix, name_buffer, ds->ds[index].name);
521         } else {
522                 if (host->event_service_prefix == NULL)
523                         sstrncpy(service_buffer, name_buffer, sizeof(service_buffer));
524                 else
525                         ssnprintf(service_buffer, sizeof(service_buffer), "%s%s",
526                                         host->event_service_prefix, name_buffer);
527         }
528
529         // Replace collectd sensor name reserved characters so that time series DB is happy
530         in_place_replace_sensu_name_reserved(service_buffer);
531
532         // finalize the buffer by setting the output and closing curly bracket
533         res = asprintf(&temp_str, "%s, \"output\": \"%s %s %ld\"}\n", ret_str, service_buffer, value_str, CDTIME_T_TO_TIME_T(vl->time));
534         free(ret_str);
535         free(value_str);
536         if (res == -1) {
537                 ERROR("write_sensu plugin: Unable to alloc memory");
538                 return NULL;
539         }
540         ret_str = temp_str;
541
542         DEBUG("write_sensu plugin: Successfully created json for metric: "
543                         "host = \"%s\", service = \"%s\"",
544                         vl->host, service_buffer);
545         return ret_str;
546 } /* }}} char *sensu_value_to_json */
547
548 /*
549  * Uses replace_str2() implementation from
550  * http://creativeandcritical.net/str-replace-c/
551  * copyright (c) Laird Shaw, under public domain.
552  */
553 char *replace_str(const char *str, const char *old, /* {{{ */
554                 const char *new)
555 {
556         char *ret, *r;
557         const char *p, *q;
558         size_t oldlen = strlen(old);
559         size_t count = strlen(new);
560         size_t retlen;
561         size_t newlen = count;
562         int samesize = (oldlen == newlen);
563
564         if (!samesize) {
565                 for (count = 0, p = str; (q = strstr(p, old)) != NULL; p = q + oldlen)
566                         count++;
567                 /* This is undefined if p - str > PTRDIFF_MAX */
568                 retlen = p - str + strlen(p) + count * (newlen - oldlen);
569         } else
570                 retlen = strlen(str);
571
572         ret = malloc(retlen + 1);
573         if (ret == NULL)
574                 return NULL;
575         // added to original: not optimized, but keeps valgrind happy.
576         memset(ret, 0, retlen + 1);
577
578         r = ret;
579         p = str;
580         while (1) {
581                 /* If the old and new strings are different lengths - in other
582                  * words we have already iterated through with strstr above,
583                  * and thus we know how many times we need to call it - then we
584                  * can avoid the final (potentially lengthy) call to strstr,
585                  * which we already know is going to return NULL, by
586                  * decrementing and checking count.
587                  */
588                 if (!samesize && !count--)
589                         break;
590                 /* Otherwise i.e. when the old and new strings are the same
591                  * length, and we don't know how many times to call strstr,
592                  * we must check for a NULL return here (we check it in any
593                  * event, to avoid further conditions, and because there's
594                  * no harm done with the check even when the old and new
595                  * strings are different lengths).
596                  */
597                 if ((q = strstr(p, old)) == NULL)
598                         break;
599                 /* This is undefined if q - p > PTRDIFF_MAX */
600                 ptrdiff_t l = q - p;
601                 memcpy(r, p, l);
602                 r += l;
603                 memcpy(r, new, newlen);
604                 r += newlen;
605                 p = q + oldlen;
606         }
607         strncpy(r, p, strlen(p));
608
609         return ret;
610 } /* }}} char *replace_str */
611
612 static char *replace_json_reserved(const char *message) /* {{{ */
613 {
614         char *msg = replace_str(message, "\\", "\\\\");
615         if (msg == NULL) {
616                 ERROR("write_sensu plugin: Unable to alloc memory");
617                 return NULL;
618         }
619         char *tmp = replace_str(msg, "\"", "\\\"");
620         free(msg);
621         if (tmp == NULL) {
622                 ERROR("write_sensu plugin: Unable to alloc memory");
623                 return NULL;
624         }
625         msg = replace_str(tmp, "\n", "\\\n");
626         free(tmp);
627         if (msg == NULL) {
628                 ERROR("write_sensu plugin: Unable to alloc memory");
629                 return NULL;
630         }
631         return msg;
632 } /* }}} char *replace_json_reserved */
633
634 static char *sensu_notification_to_json(struct sensu_host *host, /* {{{ */
635                 notification_t const *n)
636 {
637         char service_buffer[6 * DATA_MAX_NAME_LEN];
638         char const *severity;
639         notification_meta_t *meta;
640         char *ret_str;
641         char *temp_str;
642         int status;
643         size_t i;
644         int res;
645         // add the severity/status
646         switch (n->severity) {
647                 case NOTIF_OKAY:
648                         severity = "OK";
649                         status = 0;
650                         break;
651                 case NOTIF_WARNING:
652                         severity = "WARNING";
653                         status = 1;
654                         break;
655                 case NOTIF_FAILURE:
656                         severity = "CRITICAL";
657                         status = 2;
658                         break;
659                 default:
660                         severity = "UNKNOWN";
661                         status = 3;
662         }
663         res = asprintf(&temp_str, "{\"status\": %d", status);
664         if (res == -1) {
665                 ERROR("write_sensu plugin: Unable to alloc memory");
666                 return NULL;
667         }
668         ret_str = temp_str;
669
670         // incorporate the timestamp
671         res = asprintf(&temp_str, "%s, \"timestamp\": %ld", ret_str, CDTIME_T_TO_TIME_T(n->time));
672         free(ret_str);
673         if (res == -1) {
674                 ERROR("write_sensu plugin: Unable to alloc memory");
675                 return NULL;
676         }
677         ret_str = temp_str;
678
679         char *handlers_str = build_json_str_list("handlers", &(host->notification_handlers));
680         if (handlers_str == NULL) {
681                 ERROR("write_sensu plugin: Unable to alloc memory");
682                 free(ret_str);
683                 return NULL;
684         }
685         // incorporate the handlers
686         if (strlen(handlers_str) != 0) {
687                 res = asprintf(&temp_str, "%s, %s", ret_str, handlers_str);
688                 free(ret_str);
689                 free(handlers_str);
690                 if (res == -1) {
691                         ERROR("write_sensu plugin: Unable to alloc memory");
692                         return NULL;
693                 }
694                 ret_str = temp_str;
695         } else {
696                 free(handlers_str);
697         }
698
699         // incorporate the plugin name information if any
700         if (n->plugin[0] != 0) {
701                 res = asprintf(&temp_str, "%s, \"collectd_plugin\": \"%s\"", ret_str, n->plugin);
702                 free(ret_str);
703                 if (res == -1) {
704                         ERROR("write_sensu plugin: Unable to alloc memory");
705                         return NULL;
706                 }
707                 ret_str = temp_str;
708         }
709
710         // incorporate the plugin type if any
711         if (n->type[0] != 0) {
712                 res = asprintf(&temp_str, "%s, \"collectd_plugin_type\": \"%s\"", ret_str, n->type);
713                 free(ret_str);
714                 if (res == -1) {
715                         ERROR("write_sensu plugin: Unable to alloc memory");
716                         return NULL;
717                 }
718                 ret_str = temp_str;
719         }
720
721         // incorporate the plugin instance if any
722         if (n->plugin_instance[0] != 0) {
723                 res = asprintf(&temp_str, "%s, \"collectd_plugin_instance\": \"%s\"", ret_str, n->plugin_instance);
724                 free(ret_str);
725                 if (res == -1) {
726                         ERROR("write_sensu plugin: Unable to alloc memory");
727                         return NULL;
728                 }
729                 ret_str = temp_str;
730         }
731
732         // incorporate the plugin type instance if any
733         if (n->type_instance[0] != 0) {
734                 res = asprintf(&temp_str, "%s, \"collectd_plugin_type_instance\": \"%s\"", ret_str, n->type_instance);
735                 free(ret_str);
736                 if (res == -1) {
737                         ERROR("write_sensu plugin: Unable to alloc memory");
738                         return NULL;
739                 }
740                 ret_str = temp_str;
741         }
742
743         // add key value attributes from config if any
744         for (i = 0; i < sensu_attrs_num; i += 2) {
745                 res = asprintf(&temp_str, "%s, \"%s\": \"%s\"", ret_str, sensu_attrs[i], sensu_attrs[i+1]);
746                 free(ret_str);
747                 if (res == -1) {
748                         ERROR("write_sensu plugin: Unable to alloc memory");
749                         return NULL;
750                 }
751                 ret_str = temp_str;
752         }
753
754         // incorporate sensu tags from config if any
755         if ((sensu_tags != NULL) && (strlen(sensu_tags) != 0)) {
756                 res = asprintf(&temp_str, "%s, %s", ret_str, sensu_tags);
757                 free(ret_str);
758                 if (res == -1) {
759                         ERROR("write_sensu plugin: Unable to alloc memory");
760                         return NULL;
761                 }
762                 ret_str = temp_str;
763         }
764
765         // incorporate the service name
766         sensu_format_name2(service_buffer, sizeof(service_buffer),
767                                 /* host */ "", n->plugin, n->plugin_instance,
768                                 n->type, n->type_instance, host->separator);
769         // replace sensu event name chars that are considered illegal
770         in_place_replace_sensu_name_reserved(service_buffer);
771         res = asprintf(&temp_str, "%s, \"name\": \"%s\"", ret_str, &service_buffer[1]);
772         free(ret_str);
773         if (res == -1) {
774                 ERROR("write_sensu plugin: Unable to alloc memory");
775                 return NULL;
776         }
777         ret_str = temp_str;
778
779         // incorporate the check output
780         if (n->message[0] != 0) {
781                 char *msg = replace_json_reserved(n->message);
782                 if (msg == NULL) {
783                         ERROR("write_sensu plugin: Unable to alloc memory");
784                         free(ret_str);
785                         return NULL;
786                 }
787                 res = asprintf(&temp_str, "%s, \"output\": \"%s - %s\"", ret_str, severity, msg);
788                 free(ret_str);
789                 free(msg);
790                 if (res == -1) {
791                         ERROR("write_sensu plugin: Unable to alloc memory");
792                         return NULL;
793                 }
794                 ret_str = temp_str;
795         }
796
797         // Pull in values from threshold and add extra attributes
798         for (meta = n->meta; meta != NULL; meta = meta->next) {
799                 if (strcasecmp("CurrentValue", meta->name) == 0 && meta->type == NM_TYPE_DOUBLE) {
800                         res = asprintf(&temp_str, "%s, \"current_value\": \"%.8f\"", ret_str, meta->nm_value.nm_double);
801                         free(ret_str);
802                         if (res == -1) {
803                                 ERROR("write_sensu plugin: Unable to alloc memory");
804                                 return NULL;
805                         }
806                         ret_str = temp_str;
807                 }
808                 if (meta->type == NM_TYPE_STRING) {
809                         res = asprintf(&temp_str, "%s, \"%s\": \"%s\"", ret_str, meta->name, meta->nm_value.nm_string);
810                         free(ret_str);
811                         if (res == -1) {
812                                 ERROR("write_sensu plugin: Unable to alloc memory");
813                                 return NULL;
814                         }
815                         ret_str = temp_str;
816                 }
817         }
818
819         // close the curly bracket
820         res = asprintf(&temp_str, "%s}\n", ret_str);
821         free(ret_str);
822         if (res == -1) {
823                 ERROR("write_sensu plugin: Unable to alloc memory");
824                 return NULL;
825         }
826         ret_str = temp_str;
827
828         DEBUG("write_sensu plugin: Successfully created JSON for notification: "
829                                 "host = \"%s\", service = \"%s\", state = \"%s\"",
830                                 n->host, service_buffer, severity);
831         return ret_str;
832 } /* }}} char *sensu_notification_to_json */
833
834 static int sensu_send_msg(struct sensu_host *host, const char *msg) /* {{{ */
835 {
836         int status = 0;
837         size_t  buffer_len;
838
839         status = sensu_connect(host);
840         if (status != 0)
841                 return status;
842
843         buffer_len = strlen(msg);
844
845         status = (int) swrite(host->s, msg, buffer_len);
846         sensu_close_socket(host);
847
848         if (status != 0) {
849                 char errbuf[1024];
850                 ERROR("write_sensu plugin: Sending to Sensu at %s:%s failed: %s",
851                                 (host->node != NULL) ? host->node : SENSU_HOST,
852                                 (host->service != NULL) ? host->service : SENSU_PORT,
853                                 sstrerror(errno, errbuf, sizeof(errbuf)));
854                 return -1;
855         }
856
857         return 0;
858 } /* }}} int sensu_send_msg */
859
860
861 static int sensu_send(struct sensu_host *host, char const *msg) /* {{{ */
862 {
863         int status = 0;
864
865         status = sensu_send_msg(host, msg);
866         if (status != 0) {
867                 host->flags &= ~F_READY;
868                 if (host->res != NULL) {
869                         freeaddrinfo(host->res);
870                         host->res = NULL;
871                 }
872                 return status;
873         }
874
875         return 0;
876 } /* }}} int sensu_send */
877
878
879 static int sensu_write(const data_set_t *ds, /* {{{ */
880               const value_list_t *vl,
881               user_data_t *ud)
882 {
883         int status = 0;
884         int statuses[vl->values_len];
885         struct sensu_host       *host = ud->data;
886         gauge_t *rates = NULL;
887         size_t i;
888         char *msg;
889
890         pthread_mutex_lock(&host->lock);
891         memset(statuses, 0, vl->values_len * sizeof(*statuses));
892
893         if (host->store_rates) {
894                 rates = uc_get_rate(ds, vl);
895                 if (rates == NULL) {
896                         ERROR("write_sensu plugin: uc_get_rate failed.");
897                         pthread_mutex_unlock(&host->lock);
898                         return -1;
899                 }
900         }
901         for (i = 0; i < vl->values_len; i++) {
902                 msg = sensu_value_to_json(host, ds, vl, (int) i, rates, statuses[i]);
903                 if (msg == NULL) {
904                         sfree(rates);
905                         pthread_mutex_unlock(&host->lock);
906                         return -1;
907                 }
908                 status = sensu_send(host, msg);
909                 free(msg);
910                 if (status != 0) {
911                         ERROR("write_sensu plugin: sensu_send failed with status %i", status);
912                         pthread_mutex_unlock(&host->lock);
913                         sfree(rates);
914                         return status;
915                 }
916         }
917         sfree(rates);
918         pthread_mutex_unlock(&host->lock);
919         return status;
920 } /* }}} int sensu_write */
921
922 static int sensu_notification(const notification_t *n, user_data_t *ud) /* {{{ */
923 {
924         int     status;
925         struct sensu_host *host = ud->data;
926         char *msg;
927
928         pthread_mutex_lock(&host->lock);
929
930         msg = sensu_notification_to_json(host, n);
931         if (msg == NULL) {
932                 pthread_mutex_unlock(&host->lock);
933                 return -1;
934         }
935
936         status = sensu_send(host, msg);
937         free(msg);
938         if (status != 0)
939                 ERROR("write_sensu plugin: sensu_send failed with status %i", status);
940         pthread_mutex_unlock(&host->lock);
941
942         return status;
943 } /* }}} int sensu_notification */
944
945 static void sensu_free(void *p) /* {{{ */
946 {
947         struct sensu_host *host = p;
948
949         if (host == NULL)
950                 return;
951
952         pthread_mutex_lock(&host->lock);
953
954         host->reference_count--;
955         if (host->reference_count > 0) {
956                 pthread_mutex_unlock(&host->lock);
957                 return;
958         }
959
960         sensu_close_socket(host);
961         if (host->res != NULL) {
962                 freeaddrinfo(host->res);
963                 host->res = NULL;
964         }
965         sfree(host->service);
966         sfree(host->event_service_prefix);
967         sfree(host->name);
968         sfree(host->node);
969         sfree(host->separator);
970         free_str_list(&(host->metric_handlers));
971         free_str_list(&(host->notification_handlers));
972         pthread_mutex_destroy(&host->lock);
973         sfree(host);
974 } /* }}} void sensu_free */
975
976
977 static int sensu_config_node(oconfig_item_t *ci) /* {{{ */
978 {
979         struct sensu_host       *host = NULL;
980         int                                     status = 0;
981         int                                     i;
982         oconfig_item_t          *child;
983         char                            callback_name[DATA_MAX_NAME_LEN];
984         user_data_t                     ud;
985
986         if ((host = calloc(1, sizeof(*host))) == NULL) {
987                 ERROR("write_sensu plugin: calloc failed.");
988                 return ENOMEM;
989         }
990         pthread_mutex_init(&host->lock, NULL);
991         host->reference_count = 1;
992         host->node = NULL;
993         host->service = NULL;
994         host->notifications = 0;
995         host->metrics = 0;
996         host->store_rates = 1;
997         host->always_append_ds = 0;
998         host->metric_handlers.nb_strs = 0;
999         host->metric_handlers.strs = NULL;
1000         host->notification_handlers.nb_strs = 0;
1001         host->notification_handlers.strs = NULL;
1002         host->separator = strdup("/");
1003         if (host->separator == NULL) {
1004                 ERROR("write_sensu plugin: Unable to alloc memory");
1005                 sensu_free(host);
1006                 return -1;
1007         }
1008
1009         status = cf_util_get_string(ci, &host->name);
1010         if (status != 0) {
1011                 WARNING("write_sensu plugin: Required host name is missing.");
1012                 sensu_free(host);
1013                 return -1;
1014         }
1015
1016         for (i = 0; i < ci->children_num; i++) {
1017                 child = &ci->children[i];
1018                 status = 0;
1019
1020                 if (strcasecmp("Host", child->key) == 0) {
1021                         status = cf_util_get_string(child, &host->node);
1022                         if (status != 0)
1023                                 break;
1024                 } else if (strcasecmp("Notifications", child->key) == 0) {
1025                         status = cf_util_get_boolean(child, &host->notifications);
1026                         if (status != 0)
1027                                 break;
1028                 } else if (strcasecmp("Metrics", child->key) == 0) {
1029                                         status = cf_util_get_boolean(child, &host->metrics);
1030                                         if (status != 0)
1031                                                 break;
1032                 } else if (strcasecmp("EventServicePrefix", child->key) == 0) {
1033                         status = cf_util_get_string(child, &host->event_service_prefix);
1034                         if (status != 0)
1035                                 break;
1036                 } else if (strcasecmp("Separator", child->key) == 0) {
1037                                 status = cf_util_get_string(child, &host->separator);
1038                                 if (status != 0)
1039                                         break;
1040                 } else if (strcasecmp("MetricHandler", child->key) == 0) {
1041                         char *temp_str = NULL;
1042                         status = cf_util_get_string(child, &temp_str);
1043                         if (status != 0)
1044                                 break;
1045                         status = add_str_to_list(&(host->metric_handlers), temp_str);
1046                         free(temp_str);
1047                         if (status != 0)
1048                                 break;
1049                 } else if (strcasecmp("NotificationHandler", child->key) == 0) {
1050                         char *temp_str = NULL;
1051                         status = cf_util_get_string(child, &temp_str);
1052                         if (status != 0)
1053                                 break;
1054                         status = add_str_to_list(&(host->notification_handlers), temp_str);
1055                         free(temp_str);
1056                         if (status != 0)
1057                                 break;
1058                 } else if (strcasecmp("Port", child->key) == 0) {
1059                         status = cf_util_get_service(child, &host->service);
1060                         if (status != 0) {
1061                                 ERROR("write_sensu plugin: Invalid argument "
1062                                                 "configured for the \"Port\" "
1063                                                 "option.");
1064                                 break;
1065                         }
1066                 } else if (strcasecmp("StoreRates", child->key) == 0) {
1067                         status = cf_util_get_boolean(child, &host->store_rates);
1068                         if (status != 0)
1069                                 break;
1070                 } else if (strcasecmp("AlwaysAppendDS", child->key) == 0) {
1071                         status = cf_util_get_boolean(child,
1072                                         &host->always_append_ds);
1073                         if (status != 0)
1074                                 break;
1075                 } else {
1076                         WARNING("write_sensu plugin: ignoring unknown config "
1077                                 "option: \"%s\"", child->key);
1078                 }
1079         }
1080         if (status != 0) {
1081                 sensu_free(host);
1082                 return status;
1083         }
1084
1085         if (host->metrics && (host->metric_handlers.nb_strs == 0)) {
1086                         sensu_free(host);
1087                         WARNING("write_sensu plugin: metrics enabled but no MetricHandler defined. Giving up.");
1088                         return -1;
1089                 }
1090
1091         if (host->notifications && (host->notification_handlers.nb_strs == 0)) {
1092                 sensu_free(host);
1093                 WARNING("write_sensu plugin: notifications enabled but no NotificationHandler defined. Giving up.");
1094                 return -1;
1095         }
1096
1097         if ((host->notification_handlers.nb_strs > 0) && (host->notifications == 0)) {
1098                 WARNING("write_sensu plugin: NotificationHandler given so forcing notifications to be enabled");
1099                 host->notifications = 1;
1100         }
1101
1102         if ((host->metric_handlers.nb_strs > 0) && (host->metrics == 0)) {
1103                 WARNING("write_sensu plugin: MetricHandler given so forcing metrics to be enabled");
1104                 host->metrics = 1;
1105         }
1106
1107         if (!(host->notifications || host->metrics)) {
1108                 WARNING("write_sensu plugin: neither metrics nor notifications enabled. Giving up.");
1109                 sensu_free(host);
1110                 return -1;
1111         }
1112
1113         ssnprintf(callback_name, sizeof(callback_name), "write_sensu/%s", host->name);
1114         ud.data = host;
1115         ud.free_func = sensu_free;
1116
1117         pthread_mutex_lock(&host->lock);
1118
1119         if (host->metrics) {
1120                 status = plugin_register_write(callback_name, sensu_write, &ud);
1121                 if (status != 0)
1122                         WARNING("write_sensu plugin: plugin_register_write (\"%s\") "
1123                                         "failed with status %i.",
1124                                         callback_name, status);
1125                 else /* success */
1126                         host->reference_count++;
1127         }
1128
1129         if (host->notifications) {
1130                 status = plugin_register_notification(callback_name, sensu_notification, &ud);
1131                 if (status != 0)
1132                         WARNING("write_sensu plugin: plugin_register_notification (\"%s\") "
1133                                         "failed with status %i.",
1134                                         callback_name, status);
1135                 else
1136                         host->reference_count++;
1137         }
1138
1139         if (host->reference_count <= 1) {
1140                 /* Both callbacks failed => free memory.
1141                  * We need to unlock here, because sensu_free() will lock.
1142                  * This is not a race condition, because we're the only one
1143                  * holding a reference. */
1144                 pthread_mutex_unlock(&host->lock);
1145                 sensu_free(host);
1146                 return -1;
1147         }
1148
1149         host->reference_count--;
1150         pthread_mutex_unlock(&host->lock);
1151
1152         return status;
1153 } /* }}} int sensu_config_node */
1154
1155 static int sensu_config(oconfig_item_t *ci) /* {{{ */
1156 {
1157         int              i;
1158         oconfig_item_t  *child;
1159         int              status;
1160         struct str_list sensu_tags_arr;
1161
1162         sensu_tags_arr.nb_strs = 0;
1163         sensu_tags_arr.strs = NULL;
1164
1165         for (i = 0; i < ci->children_num; i++)  {
1166                 child = &ci->children[i];
1167
1168                 if (strcasecmp("Node", child->key) == 0) {
1169                         sensu_config_node(child);
1170                 } else if (strcasecmp(child->key, "attribute") == 0) {
1171                         if (child->values_num != 2) {
1172                                 WARNING("sensu attributes need both a key and a value.");
1173                                 continue;
1174                         }
1175                         if (child->values[0].type != OCONFIG_TYPE_STRING ||
1176                                         child->values[1].type != OCONFIG_TYPE_STRING) {
1177                                 WARNING("sensu attribute needs string arguments.");
1178                                 continue;
1179                         }
1180
1181                         strarray_add(&sensu_attrs, &sensu_attrs_num, child->values[0].value.string);
1182                         strarray_add(&sensu_attrs, &sensu_attrs_num, child->values[1].value.string);
1183
1184                         DEBUG("write_sensu plugin: New attribute: %s => %s",
1185                                         child->values[0].value.string,
1186                                         child->values[1].value.string);
1187                 } else if (strcasecmp(child->key, "tag") == 0) {
1188                         char *tmp = NULL;
1189                         status = cf_util_get_string(child, &tmp);
1190                         if (status != 0)
1191                                 continue;
1192
1193                         status = add_str_to_list(&sensu_tags_arr, tmp);
1194                         sfree(tmp);
1195                         if (status != 0)
1196                                 continue;
1197                         DEBUG("write_sensu plugin: Got tag: %s", tmp);
1198                 } else {
1199                         WARNING("write_sensu plugin: Ignoring unknown "
1200                                  "configuration option \"%s\" at top level.",
1201                                  child->key);
1202                 }
1203         }
1204         if (sensu_tags_arr.nb_strs > 0) {
1205                 sfree (sensu_tags);
1206                 sensu_tags = build_json_str_list("tags", &sensu_tags_arr);
1207                 free_str_list(&sensu_tags_arr);
1208                 if (sensu_tags == NULL) {
1209                         ERROR("write_sensu plugin: Unable to alloc memory");
1210                         return -1;
1211                 }
1212         }
1213         return 0;
1214 } /* }}} int sensu_config */
1215
1216 void module_register(void)
1217 {
1218         plugin_register_complex_config("write_sensu", sensu_config);
1219 }
1220
1221 /* vim: set sw=8 sts=8 ts=8 noet : */