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