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