Merge branch 'collectd-5.4' into 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 <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                 res = asprintf(&value_str, GAUGE_FORMAT, vl->values[index].gauge);
472                 if (res == -1) {
473                         free(ret_str);
474                         ERROR("write_sensu plugin: Unable to alloc memory");
475                         return NULL;
476                 }
477         } else if (rates != NULL) {
478                 res = asprintf(&value_str, GAUGE_FORMAT, rates[index]);
479                 if (res == -1) {
480                         free(ret_str);
481                         ERROR("write_sensu plugin: Unable to alloc memory");
482                         return NULL;
483                 }
484         } else {
485                 if (ds->ds[index].type == DS_TYPE_DERIVE) {
486                         res = asprintf(&value_str, "%"PRIi64, vl->values[index].derive);
487                         if (res == -1) {
488                                 free(ret_str);
489                                 ERROR("write_sensu plugin: Unable to alloc memory");
490                                 return NULL;
491                         }
492                 }
493                 else if (ds->ds[index].type == DS_TYPE_ABSOLUTE) {
494                         res = asprintf(&value_str, "%"PRIu64, vl->values[index].absolute);
495                         if (res == -1) {
496                                 free(ret_str);
497                                 ERROR("write_sensu plugin: Unable to alloc memory");
498                                 return NULL;
499                         }
500                 }
501                 else {
502                         res = asprintf(&value_str, "%llu", vl->values[index].counter);
503                         if (res == -1) {
504                                 free(ret_str);
505                                 ERROR("write_sensu plugin: Unable to alloc memory");
506                                 return NULL;
507                         }
508                 }
509         }
510
511         // Generate the full service name
512         sensu_format_name2(name_buffer, sizeof(name_buffer),
513                 vl->host, vl->plugin, vl->plugin_instance,
514                 vl->type, vl->type_instance, host->separator);
515         if (host->always_append_ds || (ds->ds_num > 1)) {
516                 if (host->event_service_prefix == NULL)
517                         ssnprintf(service_buffer, sizeof(service_buffer), "%s.%s",
518                                         name_buffer, ds->ds[index].name);
519                 else
520                         ssnprintf(service_buffer, sizeof(service_buffer), "%s%s.%s",
521                                         host->event_service_prefix, name_buffer, ds->ds[index].name);
522         } else {
523                 if (host->event_service_prefix == NULL)
524                         sstrncpy(service_buffer, name_buffer, sizeof(service_buffer));
525                 else
526                         ssnprintf(service_buffer, sizeof(service_buffer), "%s%s",
527                                         host->event_service_prefix, name_buffer);
528         }
529
530         // Replace collectd sensor name reserved characters so that time series DB is happy
531         in_place_replace_sensu_name_reserved(service_buffer);
532
533         // finalize the buffer by setting the output and closing curly bracket
534         res = asprintf(&temp_str, "%s, \"output\": \"%s %s %ld\"}\n", ret_str, service_buffer, value_str, CDTIME_T_TO_TIME_T(vl->time));
535         free(ret_str);
536         free(value_str);
537         if (res == -1) {
538                 ERROR("write_sensu plugin: Unable to alloc memory");
539                 return NULL;
540         }
541         ret_str = temp_str;
542
543         DEBUG("write_sensu plugin: Successfully created json for metric: "
544                         "host = \"%s\", service = \"%s\"",
545                         vl->host, service_buffer);
546         return ret_str;
547 } /* }}} char *sensu_value_to_json */
548
549 /*
550  * Uses replace_str2() implementation from
551  * http://creativeandcritical.net/str-replace-c/
552  * copyright (c) Laird Shaw, under public domain.
553  */
554 char *replace_str(const char *str, const char *old, /* {{{ */
555                 const char *new)
556 {
557         char *ret, *r;
558         const char *p, *q;
559         size_t oldlen = strlen(old);
560         size_t count = strlen(new);
561         size_t retlen = count;
562         size_t newlen = count;
563         int samesize = (oldlen == newlen);
564
565         if (!samesize) {
566                 for (count = 0, p = str; (q = strstr(p, old)) != NULL; p = q + oldlen)
567                         count++;
568                 /* This is undefined if p - str > PTRDIFF_MAX */
569                 retlen = p - str + strlen(p) + count * (newlen - oldlen);
570         } else
571                 retlen = strlen(str);
572
573         ret = malloc(retlen + 1);
574         if (ret == NULL)
575                 return NULL;
576         // added to original: not optimized, but keeps valgrind happy.
577         memset(ret, 0, retlen + 1);
578
579         r = ret;
580         p = str;
581         while (1) {
582                 /* If the old and new strings are different lengths - in other
583                  * words we have already iterated through with strstr above,
584                  * and thus we know how many times we need to call it - then we
585                  * can avoid the final (potentially lengthy) call to strstr,
586                  * which we already know is going to return NULL, by
587                  * decrementing and checking count.
588                  */
589                 if (!samesize && !count--)
590                         break;
591                 /* Otherwise i.e. when the old and new strings are the same
592                  * length, and we don't know how many times to call strstr,
593                  * we must check for a NULL return here (we check it in any
594                  * event, to avoid further conditions, and because there's
595                  * no harm done with the check even when the old and new
596                  * strings are different lengths).
597                  */
598                 if ((q = strstr(p, old)) == NULL)
599                         break;
600                 /* This is undefined if q - p > PTRDIFF_MAX */
601                 ptrdiff_t l = q - p;
602                 memcpy(r, p, l);
603                 r += l;
604                 memcpy(r, new, newlen);
605                 r += newlen;
606                 p = q + oldlen;
607         }
608         strncpy(r, p, strlen(p));
609
610         return ret;
611 } /* }}} char *replace_str */
612
613 static char *replace_json_reserved(const char *message) /* {{{ */
614 {
615         char *msg = replace_str(message, "\\", "\\\\");
616         if (msg == NULL) {
617                 ERROR("write_sensu plugin: Unable to alloc memory");
618                 return NULL;
619         }
620         char *tmp = replace_str(msg, "\"", "\\\"");
621         free(msg);
622         if (tmp == NULL) {
623                 ERROR("write_sensu plugin: Unable to alloc memory");
624                 return NULL;
625         }
626         msg = replace_str(tmp, "\n", "\\\n");
627         free(tmp);
628         if (msg == NULL) {
629                 ERROR("write_sensu plugin: Unable to alloc memory");
630                 return NULL;
631         }
632         return msg;
633 } /* }}} char *replace_json_reserved */
634
635 static char *sensu_notification_to_json(struct sensu_host *host, /* {{{ */
636                 notification_t const *n)
637 {
638         char service_buffer[6 * DATA_MAX_NAME_LEN];
639         char const *severity;
640         notification_meta_t *meta;
641         char *ret_str;
642         char *temp_str;
643         int status;
644         int i;
645         int res;
646         // add the severity/status
647         switch (n->severity) {
648                 case NOTIF_OKAY:
649                         severity = "OK";
650                         status = 0;
651                         break;
652                 case NOTIF_WARNING:
653                         severity = "WARNING";
654                         status = 1;
655                         break;
656                 case NOTIF_FAILURE:
657                         severity = "CRITICAL";
658                         status = 2;
659                         break;
660                 default:
661                         severity = "UNKNOWN";
662                         status = 3;
663         }
664         res = asprintf(&temp_str, "{\"status\": %d", status);
665         if (res == -1) {
666                 ERROR("write_sensu plugin: Unable to alloc memory");
667                 return NULL;
668         }
669         ret_str = temp_str;
670
671         // incorporate the timestamp
672         res = asprintf(&temp_str, "%s, \"timestamp\": %ld", ret_str, CDTIME_T_TO_TIME_T(n->time));
673         free(ret_str);
674         if (res == -1) {
675                 ERROR("write_sensu plugin: Unable to alloc memory");
676                 return NULL;
677         }
678         ret_str = temp_str;
679
680         char *handlers_str = build_json_str_list("handlers", &(host->notification_handlers));
681         if (handlers_str == NULL) {
682                 ERROR("write_sensu plugin: Unable to alloc memory");
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 (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                         return NULL;
785                 }
786                 res = asprintf(&temp_str, "%s, \"output\": \"%s - %s\"", ret_str, severity, msg);
787                 free(ret_str);
788                 free(msg);
789                 if (res == -1) {
790                         ERROR("write_sensu plugin: Unable to alloc memory");
791                         return NULL;
792                 }
793                 ret_str = temp_str;
794         }
795
796         // Pull in values from threshold and add extra attributes
797         for (meta = n->meta; meta != NULL; meta = meta->next) {
798                 if (strcasecmp("CurrentValue", meta->name) == 0 && meta->type == NM_TYPE_DOUBLE) {
799                         res = asprintf(&temp_str, "%s, \"current_value\": \"%.8f\"", ret_str, meta->nm_value.nm_double);
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                 if (meta->type == NM_TYPE_STRING) {
808                         res = asprintf(&temp_str, "%s, \"%s\": \"%s\"", ret_str, meta->name, meta->nm_value.nm_string);
809                         free(ret_str);
810                         if (res == -1) {
811                                 ERROR("write_sensu plugin: Unable to alloc memory");
812                                 return NULL;
813                         }
814                         ret_str = temp_str;
815                 }
816         }
817
818         // close the curly bracket
819         res = asprintf(&temp_str, "%s}\n", ret_str);
820         free(ret_str);
821         if (res == -1) {
822                 ERROR("write_sensu plugin: Unable to alloc memory");
823                 return NULL;
824         }
825         ret_str = temp_str;
826
827         DEBUG("write_sensu plugin: Successfully created JSON for notification: "
828                                 "host = \"%s\", service = \"%s\", state = \"%s\"",
829                                 n->host, service_buffer, severity);
830         return ret_str;
831 } /* }}} char *sensu_notification_to_json */
832
833 static int sensu_send_msg(struct sensu_host *host, const char *msg) /* {{{ */
834 {
835         int status = 0;
836         size_t  buffer_len;
837
838         status = sensu_connect(host);
839         if (status != 0)
840                 return status;
841
842         buffer_len = strlen(msg);
843
844         status = (int) swrite(host->s, msg, buffer_len);
845         sensu_close_socket(host);
846
847         if (status != 0) {
848                 char errbuf[1024];
849                 ERROR("write_sensu plugin: Sending to Sensu at %s:%s failed: %s",
850                                 (host->node != NULL) ? host->node : SENSU_HOST,
851                                 (host->service != NULL) ? host->service : SENSU_PORT,
852                                 sstrerror(errno, errbuf, sizeof(errbuf)));
853                 return -1;
854         }
855
856         return 0;
857 } /* }}} int sensu_send_msg */
858
859
860 static int sensu_send(struct sensu_host *host, char const *msg) /* {{{ */
861 {
862         int status = 0;
863
864         status = sensu_send_msg(host, msg);
865         if (status != 0) {
866                 host->flags &= ~F_READY;
867                 if (host->res != NULL) {
868                         freeaddrinfo(host->res);
869                         host->res = NULL;
870                 }
871                 return status;
872         }
873
874         return 0;
875 } /* }}} int sensu_send */
876
877
878 static int sensu_write(const data_set_t *ds, /* {{{ */
879               const value_list_t *vl,
880               user_data_t *ud)
881 {
882         int status = 0;
883         int statuses[vl->values_len];
884         struct sensu_host       *host = ud->data;
885         gauge_t *rates = NULL;
886         int i;
887         char *msg;
888
889         pthread_mutex_lock(&host->lock);
890         memset(statuses, 0, vl->values_len * sizeof(*statuses));
891
892         if (host->store_rates) {
893                 rates = uc_get_rate(ds, vl);
894                 if (rates == NULL) {
895                         ERROR("write_sensu plugin: uc_get_rate failed.");
896                         pthread_mutex_unlock(&host->lock);
897                         return -1;
898                 }
899         }
900         for (i = 0; i < (size_t) vl->values_len; i++) {
901                 msg = sensu_value_to_json(host, ds, vl, (int) i, rates, statuses[i]);
902                 if (msg == NULL) {
903                         sfree(rates);
904                         pthread_mutex_unlock(&host->lock);
905                         return -1;
906                 }
907                 status = sensu_send(host, msg);
908                 free(msg);
909                 if (status != 0) {
910                         ERROR("write_sensu plugin: sensu_send failed with status %i", status);
911                         pthread_mutex_unlock(&host->lock);
912                         sfree(rates);
913                         return status;
914                 }
915         }
916         sfree(rates);
917         pthread_mutex_unlock(&host->lock);
918         return status;
919 } /* }}} int sensu_write */
920
921 static int sensu_notification(const notification_t *n, user_data_t *ud) /* {{{ */
922 {
923         int     status;
924         struct sensu_host *host = ud->data;
925         char *msg;
926
927         pthread_mutex_lock(&host->lock);
928
929         msg = sensu_notification_to_json(host, n);
930         if (msg == NULL) {
931                 pthread_mutex_unlock(&host->lock);
932                 return -1;
933         }
934
935         status = sensu_send(host, msg);
936         free(msg);
937         if (status != 0)
938                 ERROR("write_sensu plugin: sensu_send failed with status %i", status);
939         pthread_mutex_unlock(&host->lock);
940
941         return status;
942 } /* }}} int sensu_notification */
943
944 static void sensu_free(void *p) /* {{{ */
945 {
946         struct sensu_host *host = p;
947
948         if (host == NULL)
949                 return;
950
951         pthread_mutex_lock(&host->lock);
952
953         host->reference_count--;
954         if (host->reference_count > 0) {
955                 pthread_mutex_unlock(&host->lock);
956                 return;
957         }
958
959         sensu_close_socket(host);
960         if (host->res != NULL) {
961                 freeaddrinfo(host->res);
962                 host->res = NULL;
963         }
964         sfree(host->service);
965         sfree(host->event_service_prefix);
966         sfree(host->name);
967         sfree(host->node);
968         sfree(host->separator);
969         free_str_list(&(host->metric_handlers));
970         free_str_list(&(host->notification_handlers));
971         pthread_mutex_destroy(&host->lock);
972         sfree(host);
973 } /* }}} void sensu_free */
974
975
976 static int sensu_config_node(oconfig_item_t *ci) /* {{{ */
977 {
978         struct sensu_host       *host = NULL;
979         int                                     status = 0;
980         int                                     i;
981         oconfig_item_t          *child;
982         char                            callback_name[DATA_MAX_NAME_LEN];
983         user_data_t                     ud;
984
985         if ((host = calloc(1, sizeof(*host))) == NULL) {
986                 ERROR("write_sensu plugin: calloc failed.");
987                 return ENOMEM;
988         }
989         pthread_mutex_init(&host->lock, NULL);
990         host->reference_count = 1;
991         host->node = NULL;
992         host->service = NULL;
993         host->notifications = 0;
994         host->metrics = 0;
995         host->store_rates = 1;
996         host->always_append_ds = 0;
997         host->metric_handlers.nb_strs = 0;
998         host->metric_handlers.strs = NULL;
999         host->notification_handlers.nb_strs = 0;
1000         host->notification_handlers.strs = NULL;
1001         host->separator = strdup("/");
1002         if (host->separator == NULL) {
1003                 ERROR("write_sensu plugin: Unable to alloc memory");
1004                 sensu_free(host);
1005                 return -1;
1006         }
1007
1008         status = cf_util_get_string(ci, &host->name);
1009         if (status != 0) {
1010                 WARNING("write_sensu plugin: Required host name is missing.");
1011                 sensu_free(host);
1012                 return -1;
1013         }
1014
1015         for (i = 0; i < ci->children_num; i++) {
1016                 child = &ci->children[i];
1017                 status = 0;
1018
1019                 if (strcasecmp("Host", child->key) == 0) {
1020                         status = cf_util_get_string(child, &host->node);
1021                         if (status != 0)
1022                                 break;
1023                 } else if (strcasecmp("Notifications", child->key) == 0) {
1024                         status = cf_util_get_boolean(child, &host->notifications);
1025                         if (status != 0)
1026                                 break;
1027                 } else if (strcasecmp("Metrics", child->key) == 0) {
1028                                         status = cf_util_get_boolean(child, &host->metrics);
1029                                         if (status != 0)
1030                                                 break;
1031                 } else if (strcasecmp("EventServicePrefix", child->key) == 0) {
1032                         status = cf_util_get_string(child, &host->event_service_prefix);
1033                         if (status != 0)
1034                                 break;
1035                 } else if (strcasecmp("Separator", child->key) == 0) {
1036                                 status = cf_util_get_string(child, &host->separator);
1037                                 if (status != 0)
1038                                         break;
1039                 } else if (strcasecmp("MetricHandler", 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->metric_handlers), temp_str);
1045                         free(temp_str);
1046                         if (status != 0)
1047                                 break;
1048                 } else if (strcasecmp("NotificationHandler", child->key) == 0) {
1049                         char *temp_str = NULL;
1050                         status = cf_util_get_string(child, &temp_str);
1051                         if (status != 0)
1052                                 break;
1053                         status = add_str_to_list(&(host->notification_handlers), temp_str);
1054                         free(temp_str);
1055                         if (status != 0)
1056                                 break;
1057                 } else if (strcasecmp("Port", child->key) == 0) {
1058                         status = cf_util_get_service(child, &host->service);
1059                         if (status != 0) {
1060                                 ERROR("write_sensu plugin: Invalid argument "
1061                                                 "configured for the \"Port\" "
1062                                                 "option.");
1063                                 break;
1064                         }
1065                 } else if (strcasecmp("StoreRates", child->key) == 0) {
1066                         status = cf_util_get_boolean(child, &host->store_rates);
1067                         if (status != 0)
1068                                 break;
1069                 } else if (strcasecmp("AlwaysAppendDS", child->key) == 0) {
1070                         status = cf_util_get_boolean(child,
1071                                         &host->always_append_ds);
1072                         if (status != 0)
1073                                 break;
1074                 } else {
1075                         WARNING("write_sensu plugin: ignoring unknown config "
1076                                 "option: \"%s\"", child->key);
1077                 }
1078         }
1079         if (status != 0) {
1080                 sensu_free(host);
1081                 return status;
1082         }
1083
1084         if (host->metrics && (host->metric_handlers.nb_strs == 0)) {
1085                         sensu_free(host);
1086                         WARNING("write_sensu plugin: metrics enabled but no MetricHandler defined. Giving up.");
1087                         return -1;
1088                 }
1089
1090         if (host->notifications && (host->notification_handlers.nb_strs == 0)) {
1091                 sensu_free(host);
1092                 WARNING("write_sensu plugin: notifications enabled but no NotificationHandler defined. Giving up.");
1093                 return -1;
1094         }
1095
1096         if ((host->notification_handlers.nb_strs > 0) && (host->notifications == 0)) {
1097                 WARNING("write_sensu plugin: NotificationHandler given so forcing notifications to be enabled");
1098                 host->notifications = 1;
1099         }
1100
1101         if ((host->metric_handlers.nb_strs > 0) && (host->metrics == 0)) {
1102                 WARNING("write_sensu plugin: MetricHandler given so forcing metrics to be enabled");
1103                 host->metrics = 1;
1104         }
1105
1106         if (!(host->notifications || host->metrics)) {
1107                 WARNING("write_sensu plugin: neither metrics nor notifications enabled. Giving up.");
1108                 sensu_free(host);
1109                 return -1;
1110         }
1111
1112         ssnprintf(callback_name, sizeof(callback_name), "write_sensu/%s", host->name);
1113         ud.data = host;
1114         ud.free_func = sensu_free;
1115
1116         pthread_mutex_lock(&host->lock);
1117
1118         if (host->metrics) {
1119                 status = plugin_register_write(callback_name, sensu_write, &ud);
1120                 if (status != 0)
1121                         WARNING("write_sensu plugin: plugin_register_write (\"%s\") "
1122                                         "failed with status %i.",
1123                                         callback_name, status);
1124                 else /* success */
1125                         host->reference_count++;
1126         }
1127
1128         if (host->notifications) {
1129                 status = plugin_register_notification(callback_name, sensu_notification, &ud);
1130                 if (status != 0)
1131                         WARNING("write_sensu plugin: plugin_register_notification (\"%s\") "
1132                                         "failed with status %i.",
1133                                         callback_name, status);
1134                 else
1135                         host->reference_count++;
1136         }
1137
1138         if (host->reference_count <= 1) {
1139                 /* Both callbacks failed => free memory.
1140                  * We need to unlock here, because sensu_free() will lock.
1141                  * This is not a race condition, because we're the only one
1142                  * holding a reference. */
1143                 pthread_mutex_unlock(&host->lock);
1144                 sensu_free(host);
1145                 return -1;
1146         }
1147
1148         host->reference_count--;
1149         pthread_mutex_unlock(&host->lock);
1150
1151         return status;
1152 } /* }}} int sensu_config_node */
1153
1154 static int sensu_config(oconfig_item_t *ci) /* {{{ */
1155 {
1156         int              i;
1157         oconfig_item_t  *child;
1158         int              status;
1159         struct str_list sensu_tags_arr;
1160
1161         sensu_tags_arr.nb_strs = 0;
1162         sensu_tags_arr.strs = NULL;
1163         sensu_tags = malloc(sizeof(char));
1164         if (sensu_tags == NULL) {
1165                 ERROR("write_sensu plugin: Unable to alloc memory");
1166                 return -1;
1167         }
1168         sensu_tags[0] = '\0';
1169
1170         for (i = 0; i < ci->children_num; i++)  {
1171                 child = &ci->children[i];
1172
1173                 if (strcasecmp("Node", child->key) == 0) {
1174                         sensu_config_node(child);
1175                 } else if (strcasecmp(child->key, "attribute") == 0) {
1176                         char *key = NULL;
1177                         char *val = NULL;
1178
1179                         if (child->values_num != 2) {
1180                                 WARNING("sensu attributes need both a key and a value.");
1181                                 free(sensu_tags);
1182                                 return -1;
1183                         }
1184                         if (child->values[0].type != OCONFIG_TYPE_STRING ||
1185                             child->values[1].type != OCONFIG_TYPE_STRING) {
1186                                 WARNING("sensu attribute needs string arguments.");
1187                                 free(sensu_tags);
1188                                 return -1;
1189                         }
1190                         if ((key = strdup(child->values[0].value.string)) == NULL) {
1191                                 ERROR("write_sensu plugin: Unable to alloc memory");
1192                                 free(sensu_tags);
1193                                 return -1;
1194                         }
1195                         if ((val = strdup(child->values[1].value.string)) == NULL) {
1196                                 free(sensu_tags);
1197                                 free(key);
1198                                 ERROR("write_sensu plugin: Unable to alloc memory");
1199                                 return -1;
1200                         }
1201                         strarray_add(&sensu_attrs, &sensu_attrs_num, key);
1202                         strarray_add(&sensu_attrs, &sensu_attrs_num, val);
1203                         DEBUG("write_sensu: got attr: %s => %s", key, val);
1204                         sfree(key);
1205                         sfree(val);
1206                 } else if (strcasecmp(child->key, "tag") == 0) {
1207                         char *tmp = NULL;
1208                         status = cf_util_get_string(child, &tmp);
1209                         if (status != 0)
1210                                 continue;
1211
1212                         status = add_str_to_list(&sensu_tags_arr, tmp);
1213                         sfree(tmp);
1214                         if (status != 0)
1215                                 continue;
1216                         DEBUG("write_sensu plugin: Got tag: %s", tmp);
1217                 } else {
1218                         WARNING("write_sensu plugin: Ignoring unknown "
1219                                  "configuration option \"%s\" at top level.",
1220                                  child->key);
1221                 }
1222         }
1223         if (sensu_tags_arr.nb_strs > 0) {
1224                 free(sensu_tags);
1225                 sensu_tags = build_json_str_list("tags", &sensu_tags_arr);
1226                 free_str_list(&sensu_tags_arr);
1227                 if (sensu_tags == NULL) {
1228                         ERROR("write_sensu plugin: Unable to alloc memory");
1229                         return -1;
1230                 }
1231         }
1232         return 0;
1233 } /* }}} int sensu_config */
1234
1235 void module_register(void)
1236 {
1237         plugin_register_complex_config("write_sensu", sensu_config);
1238 }
1239
1240 /* vim: set sw=8 sts=8 ts=8 noet : */