Merge pull request #2512 from Stackdriver/pri
[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 "common.h"
32 #include "plugin.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 = NULL;
123 static char **sensu_attrs = NULL;
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   int len = strlen(orig_name);
313   for (int 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                                  int status) {
342   char name_buffer[5 * DATA_MAX_NAME_LEN];
343   char service_buffer[6 * DATA_MAX_NAME_LEN];
344   char *ret_str;
345   char *temp_str;
346   char *value_str;
347   int res;
348   // First part of the JSON string
349   const char *part1 = "{\"name\": \"collectd\", \"type\": \"metric\"";
350
351   char *handlers_str =
352       build_json_str_list("handlers", &(host->metric_handlers));
353   if (handlers_str == NULL) {
354     ERROR("write_sensu plugin: Unable to alloc memory");
355     return NULL;
356   }
357
358   // incorporate the handlers
359   if (strlen(handlers_str) == 0) {
360     free(handlers_str);
361     ret_str = strdup(part1);
362     if (ret_str == NULL) {
363       ERROR("write_sensu plugin: Unable to alloc memory");
364       return NULL;
365     }
366   } else {
367     res = my_asprintf(&ret_str, "%s, %s", part1, handlers_str);
368     free(handlers_str);
369     if (res == -1) {
370       ERROR("write_sensu plugin: Unable to alloc memory");
371       return NULL;
372     }
373   }
374
375   // incorporate the plugin name information
376   res = my_asprintf(&temp_str, "%s, \"collectd_plugin\": \"%s\"", ret_str,
377                     vl->plugin);
378   free(ret_str);
379   if (res == -1) {
380     ERROR("write_sensu plugin: Unable to alloc memory");
381     return NULL;
382   }
383   ret_str = temp_str;
384
385   // incorporate the plugin type
386   res = my_asprintf(&temp_str, "%s, \"collectd_plugin_type\": \"%s\"", ret_str,
387                     vl->type);
388   free(ret_str);
389   if (res == -1) {
390     ERROR("write_sensu plugin: Unable to alloc memory");
391     return NULL;
392   }
393   ret_str = temp_str;
394
395   // incorporate the plugin instance if any
396   if (vl->plugin_instance[0] != 0) {
397     res = my_asprintf(&temp_str, "%s, \"collectd_plugin_instance\": \"%s\"",
398                       ret_str, vl->plugin_instance);
399     free(ret_str);
400     if (res == -1) {
401       ERROR("write_sensu plugin: Unable to alloc memory");
402       return NULL;
403     }
404     ret_str = temp_str;
405   }
406
407   // incorporate the plugin type instance if any
408   if (vl->type_instance[0] != 0) {
409     res =
410         my_asprintf(&temp_str, "%s, \"collectd_plugin_type_instance\": \"%s\"",
411                     ret_str, vl->type_instance);
412     free(ret_str);
413     if (res == -1) {
414       ERROR("write_sensu plugin: Unable to alloc memory");
415       return NULL;
416     }
417     ret_str = temp_str;
418   }
419
420   // incorporate the data source type
421   if ((ds->ds[index].type != DS_TYPE_GAUGE) && (rates != NULL)) {
422     char ds_type[DATA_MAX_NAME_LEN];
423     snprintf(ds_type, sizeof(ds_type), "%s:rate",
424              DS_TYPE_TO_STRING(ds->ds[index].type));
425     res = my_asprintf(&temp_str, "%s, \"collectd_data_source_type\": \"%s\"",
426                       ret_str, ds_type);
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   } else {
434     res = my_asprintf(&temp_str, "%s, \"collectd_data_source_type\": \"%s\"",
435                       ret_str, DS_TYPE_TO_STRING(ds->ds[index].type));
436     free(ret_str);
437     if (res == -1) {
438       ERROR("write_sensu plugin: Unable to alloc memory");
439       return NULL;
440     }
441     ret_str = temp_str;
442   }
443
444   // incorporate the data source name
445   res = my_asprintf(&temp_str, "%s, \"collectd_data_source_name\": \"%s\"",
446                     ret_str, ds->ds[index].name);
447   free(ret_str);
448   if (res == -1) {
449     ERROR("write_sensu plugin: Unable to alloc memory");
450     return NULL;
451   }
452   ret_str = temp_str;
453
454   // incorporate the data source index
455   {
456     char ds_index[DATA_MAX_NAME_LEN];
457     snprintf(ds_index, sizeof(ds_index), "%" PRIsz, index);
458     res = my_asprintf(&temp_str, "%s, \"collectd_data_source_index\": %s",
459                       ret_str, ds_index);
460     free(ret_str);
461     if (res == -1) {
462       ERROR("write_sensu plugin: Unable to alloc memory");
463       return NULL;
464     }
465     ret_str = temp_str;
466   }
467
468   // add key value attributes from config if any
469   for (size_t i = 0; i < sensu_attrs_num; i += 2) {
470     res = my_asprintf(&temp_str, "%s, \"%s\": \"%s\"", ret_str, sensu_attrs[i],
471                       sensu_attrs[i + 1]);
472     free(ret_str);
473     if (res == -1) {
474       ERROR("write_sensu plugin: Unable to alloc memory");
475       return NULL;
476     }
477     ret_str = temp_str;
478   }
479
480   // incorporate sensu tags from config if any
481   if ((sensu_tags != NULL) && (strlen(sensu_tags) != 0)) {
482     res = my_asprintf(&temp_str, "%s, %s", ret_str, sensu_tags);
483     free(ret_str);
484     if (res == -1) {
485       ERROR("write_sensu plugin: Unable to alloc memory");
486       return NULL;
487     }
488     ret_str = temp_str;
489   }
490
491   // calculate the value and set to a string
492   if (ds->ds[index].type == DS_TYPE_GAUGE) {
493     res = my_asprintf(&value_str, GAUGE_FORMAT, vl->values[index].gauge);
494     if (res == -1) {
495       free(ret_str);
496       ERROR("write_sensu plugin: Unable to alloc memory");
497       return NULL;
498     }
499   } else if (rates != NULL) {
500     res = my_asprintf(&value_str, GAUGE_FORMAT, rates[index]);
501     if (res == -1) {
502       free(ret_str);
503       ERROR("write_sensu plugin: Unable to alloc memory");
504       return NULL;
505     }
506   } else {
507     if (ds->ds[index].type == DS_TYPE_DERIVE) {
508       res = my_asprintf(&value_str, "%" PRIi64, vl->values[index].derive);
509       if (res == -1) {
510         free(ret_str);
511         ERROR("write_sensu plugin: Unable to alloc memory");
512         return NULL;
513       }
514     } else if (ds->ds[index].type == DS_TYPE_ABSOLUTE) {
515       res = my_asprintf(&value_str, "%" PRIu64, vl->values[index].absolute);
516       if (res == -1) {
517         free(ret_str);
518         ERROR("write_sensu plugin: Unable to alloc memory");
519         return NULL;
520       }
521     } else {
522       res = my_asprintf(&value_str, "%" PRIu64,
523                         (uint64_t)vl->values[index].counter);
524       if (res == -1) {
525         free(ret_str);
526         ERROR("write_sensu plugin: Unable to alloc memory");
527         return NULL;
528       }
529     }
530   }
531
532   // Generate the full service name
533   sensu_format_name2(name_buffer, sizeof(name_buffer), vl->host, vl->plugin,
534                      vl->plugin_instance, vl->type, vl->type_instance,
535                      host->separator);
536   if (host->always_append_ds || (ds->ds_num > 1)) {
537     if (host->event_service_prefix == NULL)
538       snprintf(service_buffer, sizeof(service_buffer), "%s.%s", name_buffer,
539                ds->ds[index].name);
540     else
541       snprintf(service_buffer, sizeof(service_buffer), "%s%s.%s",
542                host->event_service_prefix, name_buffer, ds->ds[index].name);
543   } else {
544     if (host->event_service_prefix == NULL)
545       sstrncpy(service_buffer, name_buffer, sizeof(service_buffer));
546     else
547       snprintf(service_buffer, sizeof(service_buffer), "%s%s",
548                host->event_service_prefix, name_buffer);
549   }
550
551   // Replace collectd sensor name reserved characters so that time series DB is
552   // happy
553   in_place_replace_sensu_name_reserved(service_buffer);
554
555   // finalize the buffer by setting the output and closing curly bracket
556   res = my_asprintf(&temp_str, "%s, \"output\": \"%s %s %lld\"}\n", ret_str,
557                     service_buffer, value_str,
558                     (long long)CDTIME_T_TO_TIME_T(vl->time));
559   free(ret_str);
560   free(value_str);
561   if (res == -1) {
562     ERROR("write_sensu plugin: Unable to alloc memory");
563     return NULL;
564   }
565   ret_str = temp_str;
566
567   DEBUG("write_sensu plugin: Successfully created json for metric: "
568         "host = \"%s\", service = \"%s\"",
569         vl->host, service_buffer);
570   return ret_str;
571 } /* }}} char *sensu_value_to_json */
572
573 /*
574  * Uses replace_str2() implementation from
575  * http://creativeandcritical.net/str-replace-c/
576  * copyright (c) Laird Shaw, under public domain.
577  */
578 static char *replace_str(const char *str, const char *old, /* {{{ */
579                          const char *new) {
580   char *ret, *r;
581   const char *p, *q;
582   size_t oldlen = strlen(old);
583   size_t count = strlen(new);
584   size_t retlen;
585   size_t newlen = count;
586   int samesize = (oldlen == newlen);
587
588   if (!samesize) {
589     for (count = 0, p = str; (q = strstr(p, old)) != NULL; p = q + oldlen)
590       count++;
591     /* This is undefined if p - str > PTRDIFF_MAX */
592     retlen = p - str + strlen(p) + count * (newlen - oldlen);
593   } else
594     retlen = strlen(str);
595
596   ret = calloc(1, retlen + 1);
597   if (ret == NULL)
598     return NULL;
599   // added to original: not optimized, but keeps valgrind happy.
600
601   r = ret;
602   p = str;
603   while (1) {
604     /* If the old and new strings are different lengths - in other
605      * words we have already iterated through with strstr above,
606      * and thus we know how many times we need to call it - then we
607      * can avoid the final (potentially lengthy) call to strstr,
608      * which we already know is going to return NULL, by
609      * decrementing and checking count.
610      */
611     if (!samesize && !count--)
612       break;
613     /* Otherwise i.e. when the old and new strings are the same
614      * length, and we don't know how many times to call strstr,
615      * we must check for a NULL return here (we check it in any
616      * event, to avoid further conditions, and because there's
617      * no harm done with the check even when the old and new
618      * strings are different lengths).
619      */
620     if ((q = strstr(p, old)) == NULL)
621       break;
622     /* This is undefined if q - p > PTRDIFF_MAX */
623     ptrdiff_t l = q - p;
624     memcpy(r, p, l);
625     r += l;
626     memcpy(r, new, newlen);
627     r += newlen;
628     p = q + oldlen;
629   }
630   strncpy(r, p, strlen(p));
631
632   return ret;
633 } /* }}} char *replace_str */
634
635 static char *replace_json_reserved(const char *message) /* {{{ */
636 {
637   char *msg = replace_str(message, "\\", "\\\\");
638   if (msg == NULL) {
639     ERROR("write_sensu plugin: Unable to alloc memory");
640     return NULL;
641   }
642   char *tmp = replace_str(msg, "\"", "\\\"");
643   free(msg);
644   if (tmp == NULL) {
645     ERROR("write_sensu plugin: Unable to alloc memory");
646     return NULL;
647   }
648   msg = replace_str(tmp, "\n", "\\\n");
649   free(tmp);
650   if (msg == NULL) {
651     ERROR("write_sensu plugin: Unable to alloc memory");
652     return NULL;
653   }
654   return msg;
655 } /* }}} char *replace_json_reserved */
656
657 static char *sensu_notification_to_json(struct sensu_host *host, /* {{{ */
658                                         notification_t const *n) {
659   char service_buffer[6 * DATA_MAX_NAME_LEN];
660   char const *severity;
661   char *ret_str;
662   char *temp_str;
663   int status;
664   size_t i;
665   int res;
666   // add the severity/status
667   switch (n->severity) {
668   case NOTIF_OKAY:
669     severity = "OK";
670     status = 0;
671     break;
672   case NOTIF_WARNING:
673     severity = "WARNING";
674     status = 1;
675     break;
676   case NOTIF_FAILURE:
677     severity = "CRITICAL";
678     status = 2;
679     break;
680   default:
681     severity = "UNKNOWN";
682     status = 3;
683   }
684   res = my_asprintf(&temp_str, "{\"status\": %d", status);
685   if (res == -1) {
686     ERROR("write_sensu plugin: Unable to alloc memory");
687     return NULL;
688   }
689   ret_str = temp_str;
690
691   // incorporate the timestamp
692   res = my_asprintf(&temp_str, "%s, \"timestamp\": %lld", ret_str,
693                     (long long)CDTIME_T_TO_TIME_T(n->time));
694   free(ret_str);
695   if (res == -1) {
696     ERROR("write_sensu plugin: Unable to alloc memory");
697     return NULL;
698   }
699   ret_str = temp_str;
700
701   char *handlers_str =
702       build_json_str_list("handlers", &(host->notification_handlers));
703   if (handlers_str == NULL) {
704     ERROR("write_sensu plugin: Unable to alloc memory");
705     free(ret_str);
706     return NULL;
707   }
708   // incorporate the handlers
709   if (strlen(handlers_str) != 0) {
710     res = my_asprintf(&temp_str, "%s, %s", ret_str, handlers_str);
711     free(ret_str);
712     free(handlers_str);
713     if (res == -1) {
714       ERROR("write_sensu plugin: Unable to alloc memory");
715       return NULL;
716     }
717     ret_str = temp_str;
718   } else {
719     free(handlers_str);
720   }
721
722   // incorporate the plugin name information if any
723   if (n->plugin[0] != 0) {
724     res = my_asprintf(&temp_str, "%s, \"collectd_plugin\": \"%s\"", ret_str,
725                       n->plugin);
726     free(ret_str);
727     if (res == -1) {
728       ERROR("write_sensu plugin: Unable to alloc memory");
729       return NULL;
730     }
731     ret_str = temp_str;
732   }
733
734   // incorporate the plugin type if any
735   if (n->type[0] != 0) {
736     res = my_asprintf(&temp_str, "%s, \"collectd_plugin_type\": \"%s\"",
737                       ret_str, n->type);
738     free(ret_str);
739     if (res == -1) {
740       ERROR("write_sensu plugin: Unable to alloc memory");
741       return NULL;
742     }
743     ret_str = temp_str;
744   }
745
746   // incorporate the plugin instance if any
747   if (n->plugin_instance[0] != 0) {
748     res = my_asprintf(&temp_str, "%s, \"collectd_plugin_instance\": \"%s\"",
749                       ret_str, n->plugin_instance);
750     free(ret_str);
751     if (res == -1) {
752       ERROR("write_sensu plugin: Unable to alloc memory");
753       return NULL;
754     }
755     ret_str = temp_str;
756   }
757
758   // incorporate the plugin type instance if any
759   if (n->type_instance[0] != 0) {
760     res =
761         my_asprintf(&temp_str, "%s, \"collectd_plugin_type_instance\": \"%s\"",
762                     ret_str, n->type_instance);
763     free(ret_str);
764     if (res == -1) {
765       ERROR("write_sensu plugin: Unable to alloc memory");
766       return NULL;
767     }
768     ret_str = temp_str;
769   }
770
771   // add key value attributes from config if any
772   for (i = 0; i < sensu_attrs_num; i += 2) {
773     res = my_asprintf(&temp_str, "%s, \"%s\": \"%s\"", ret_str, sensu_attrs[i],
774                       sensu_attrs[i + 1]);
775     free(ret_str);
776     if (res == -1) {
777       ERROR("write_sensu plugin: Unable to alloc memory");
778       return NULL;
779     }
780     ret_str = temp_str;
781   }
782
783   // incorporate sensu tags from config if any
784   if ((sensu_tags != NULL) && (strlen(sensu_tags) != 0)) {
785     res = my_asprintf(&temp_str, "%s, %s", ret_str, sensu_tags);
786     free(ret_str);
787     if (res == -1) {
788       ERROR("write_sensu plugin: Unable to alloc memory");
789       return NULL;
790     }
791     ret_str = temp_str;
792   }
793
794   // incorporate the service name
795   sensu_format_name2(service_buffer, sizeof(service_buffer),
796                      /* host */ "", n->plugin, n->plugin_instance, n->type,
797                      n->type_instance, host->separator);
798   // replace sensu event name chars that are considered illegal
799   in_place_replace_sensu_name_reserved(service_buffer);
800   res = my_asprintf(&temp_str, "%s, \"name\": \"%s\"", ret_str,
801                     &service_buffer[1]);
802   free(ret_str);
803   if (res == -1) {
804     ERROR("write_sensu plugin: Unable to alloc memory");
805     return NULL;
806   }
807   ret_str = temp_str;
808
809   // incorporate the check output
810   if (n->message[0] != 0) {
811     char *msg = replace_json_reserved(n->message);
812     if (msg == NULL) {
813       ERROR("write_sensu plugin: Unable to alloc memory");
814       free(ret_str);
815       return NULL;
816     }
817     res = my_asprintf(&temp_str, "%s, \"output\": \"%s - %s\"", ret_str,
818                       severity, msg);
819     free(ret_str);
820     free(msg);
821     if (res == -1) {
822       ERROR("write_sensu plugin: Unable to alloc memory");
823       return NULL;
824     }
825     ret_str = temp_str;
826   }
827
828   // Pull in values from threshold and add extra attributes
829   for (notification_meta_t *meta = n->meta; meta != NULL; meta = meta->next) {
830     if (strcasecmp("CurrentValue", meta->name) == 0 &&
831         meta->type == NM_TYPE_DOUBLE) {
832       res = my_asprintf(&temp_str, "%s, \"current_value\": \"%.8f\"", ret_str,
833                         meta->nm_value.nm_double);
834       free(ret_str);
835       if (res == -1) {
836         ERROR("write_sensu plugin: Unable to alloc memory");
837         return NULL;
838       }
839       ret_str = temp_str;
840     }
841     if (meta->type == NM_TYPE_STRING) {
842       res = my_asprintf(&temp_str, "%s, \"%s\": \"%s\"", ret_str, meta->name,
843                         meta->nm_value.nm_string);
844       free(ret_str);
845       if (res == -1) {
846         ERROR("write_sensu plugin: Unable to alloc memory");
847         return NULL;
848       }
849       ret_str = temp_str;
850     }
851   }
852
853   // close the curly bracket
854   res = my_asprintf(&temp_str, "%s}\n", ret_str);
855   free(ret_str);
856   if (res == -1) {
857     ERROR("write_sensu plugin: Unable to alloc memory");
858     return NULL;
859   }
860   ret_str = temp_str;
861
862   DEBUG("write_sensu plugin: Successfully created JSON for notification: "
863         "host = \"%s\", service = \"%s\", state = \"%s\"",
864         n->host, service_buffer, severity);
865   return ret_str;
866 } /* }}} char *sensu_notification_to_json */
867
868 static int sensu_send_msg(struct sensu_host *host, const char *msg) /* {{{ */
869 {
870   int status = 0;
871   size_t buffer_len;
872
873   status = sensu_connect(host);
874   if (status != 0)
875     return status;
876
877   buffer_len = strlen(msg);
878
879   status = (int)swrite(host->s, msg, buffer_len);
880   sensu_close_socket(host);
881
882   if (status != 0) {
883     ERROR("write_sensu plugin: Sending to Sensu at %s:%s failed: %s",
884           (host->node != NULL) ? host->node : SENSU_HOST,
885           (host->service != NULL) ? host->service : SENSU_PORT, STRERRNO);
886     return -1;
887   }
888
889   return 0;
890 } /* }}} int sensu_send_msg */
891
892 static int sensu_send(struct sensu_host *host, char const *msg) /* {{{ */
893 {
894   int status = 0;
895
896   status = sensu_send_msg(host, msg);
897   if (status != 0) {
898     host->flags &= ~F_READY;
899     if (host->res != NULL) {
900       freeaddrinfo(host->res);
901       host->res = NULL;
902     }
903     return status;
904   }
905
906   return 0;
907 } /* }}} int sensu_send */
908
909 static int sensu_write(const data_set_t *ds, /* {{{ */
910                        const value_list_t *vl, user_data_t *ud) {
911   int status = 0;
912   int statuses[vl->values_len];
913   struct sensu_host *host = ud->data;
914   gauge_t *rates = NULL;
915   char *msg;
916
917   pthread_mutex_lock(&host->lock);
918   memset(statuses, 0, vl->values_len * sizeof(*statuses));
919
920   if (host->store_rates) {
921     rates = uc_get_rate(ds, vl);
922     if (rates == NULL) {
923       ERROR("write_sensu plugin: uc_get_rate failed.");
924       pthread_mutex_unlock(&host->lock);
925       return -1;
926     }
927   }
928   for (size_t i = 0; i < vl->values_len; i++) {
929     msg = sensu_value_to_json(host, ds, vl, (int)i, rates, statuses[i]);
930     if (msg == NULL) {
931       sfree(rates);
932       pthread_mutex_unlock(&host->lock);
933       return -1;
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       sfree(rates);
941       return status;
942     }
943   }
944   sfree(rates);
945   pthread_mutex_unlock(&host->lock);
946   return status;
947 } /* }}} int sensu_write */
948
949 static int sensu_notification(const notification_t *n,
950                               user_data_t *ud) /* {{{ */
951 {
952   int status;
953   struct sensu_host *host = ud->data;
954   char *msg;
955
956   pthread_mutex_lock(&host->lock);
957
958   msg = sensu_notification_to_json(host, n);
959   if (msg == NULL) {
960     pthread_mutex_unlock(&host->lock);
961     return -1;
962   }
963
964   status = sensu_send(host, msg);
965   free(msg);
966   if (status != 0)
967     ERROR("write_sensu plugin: sensu_send failed with status %i", status);
968   pthread_mutex_unlock(&host->lock);
969
970   return status;
971 } /* }}} int sensu_notification */
972
973 static void sensu_free(void *p) /* {{{ */
974 {
975   struct sensu_host *host = p;
976
977   if (host == NULL)
978     return;
979
980   pthread_mutex_lock(&host->lock);
981
982   host->reference_count--;
983   if (host->reference_count > 0) {
984     pthread_mutex_unlock(&host->lock);
985     return;
986   }
987
988   sensu_close_socket(host);
989   if (host->res != NULL) {
990     freeaddrinfo(host->res);
991     host->res = NULL;
992   }
993   sfree(host->service);
994   sfree(host->event_service_prefix);
995   sfree(host->name);
996   sfree(host->node);
997   sfree(host->separator);
998   free_str_list(&(host->metric_handlers));
999   free_str_list(&(host->notification_handlers));
1000
1001   pthread_mutex_unlock(&host->lock);
1002   pthread_mutex_destroy(&host->lock);
1003
1004   sfree(host);
1005 } /* }}} void sensu_free */
1006
1007 static int sensu_config_node(oconfig_item_t *ci) /* {{{ */
1008 {
1009   struct sensu_host *host = NULL;
1010   int status = 0;
1011   oconfig_item_t *child;
1012   char callback_name[DATA_MAX_NAME_LEN];
1013
1014   if ((host = calloc(1, sizeof(*host))) == NULL) {
1015     ERROR("write_sensu plugin: calloc failed.");
1016     return ENOMEM;
1017   }
1018   pthread_mutex_init(&host->lock, NULL);
1019   host->reference_count = 1;
1020   host->node = NULL;
1021   host->service = NULL;
1022   host->notifications = 0;
1023   host->metrics = 0;
1024   host->store_rates = 1;
1025   host->always_append_ds = 0;
1026   host->metric_handlers.nb_strs = 0;
1027   host->metric_handlers.strs = NULL;
1028   host->notification_handlers.nb_strs = 0;
1029   host->notification_handlers.strs = NULL;
1030   host->separator = strdup("/");
1031   if (host->separator == NULL) {
1032     ERROR("write_sensu plugin: Unable to alloc memory");
1033     sensu_free(host);
1034     return -1;
1035   }
1036
1037   status = cf_util_get_string(ci, &host->name);
1038   if (status != 0) {
1039     WARNING("write_sensu plugin: Required host name is missing.");
1040     sensu_free(host);
1041     return -1;
1042   }
1043
1044   for (int i = 0; i < ci->children_num; i++) {
1045     child = &ci->children[i];
1046     status = 0;
1047
1048     if (strcasecmp("Host", child->key) == 0) {
1049       status = cf_util_get_string(child, &host->node);
1050       if (status != 0)
1051         break;
1052     } else if (strcasecmp("Notifications", child->key) == 0) {
1053       status = cf_util_get_boolean(child, &host->notifications);
1054       if (status != 0)
1055         break;
1056     } else if (strcasecmp("Metrics", child->key) == 0) {
1057       status = cf_util_get_boolean(child, &host->metrics);
1058       if (status != 0)
1059         break;
1060     } else if (strcasecmp("EventServicePrefix", child->key) == 0) {
1061       status = cf_util_get_string(child, &host->event_service_prefix);
1062       if (status != 0)
1063         break;
1064     } else if (strcasecmp("Separator", child->key) == 0) {
1065       status = cf_util_get_string(child, &host->separator);
1066       if (status != 0)
1067         break;
1068     } else if (strcasecmp("MetricHandler", child->key) == 0) {
1069       char *temp_str = NULL;
1070       status = cf_util_get_string(child, &temp_str);
1071       if (status != 0)
1072         break;
1073       status = add_str_to_list(&(host->metric_handlers), temp_str);
1074       free(temp_str);
1075       if (status != 0)
1076         break;
1077     } else if (strcasecmp("NotificationHandler", child->key) == 0) {
1078       char *temp_str = NULL;
1079       status = cf_util_get_string(child, &temp_str);
1080       if (status != 0)
1081         break;
1082       status = add_str_to_list(&(host->notification_handlers), temp_str);
1083       free(temp_str);
1084       if (status != 0)
1085         break;
1086     } else if (strcasecmp("Port", child->key) == 0) {
1087       status = cf_util_get_service(child, &host->service);
1088       if (status != 0) {
1089         ERROR("write_sensu plugin: Invalid argument "
1090               "configured for the \"Port\" "
1091               "option.");
1092         break;
1093       }
1094     } else if (strcasecmp("StoreRates", child->key) == 0) {
1095       status = cf_util_get_boolean(child, &host->store_rates);
1096       if (status != 0)
1097         break;
1098     } else if (strcasecmp("AlwaysAppendDS", child->key) == 0) {
1099       status = cf_util_get_boolean(child, &host->always_append_ds);
1100       if (status != 0)
1101         break;
1102     } else {
1103       WARNING("write_sensu plugin: ignoring unknown config "
1104               "option: \"%s\"",
1105               child->key);
1106     }
1107   }
1108   if (status != 0) {
1109     sensu_free(host);
1110     return status;
1111   }
1112
1113   if (host->metrics && (host->metric_handlers.nb_strs == 0)) {
1114     sensu_free(host);
1115     WARNING("write_sensu plugin: metrics enabled but no MetricHandler defined. "
1116             "Giving up.");
1117     return -1;
1118   }
1119
1120   if (host->notifications && (host->notification_handlers.nb_strs == 0)) {
1121     sensu_free(host);
1122     WARNING("write_sensu plugin: notifications enabled but no "
1123             "NotificationHandler defined. Giving up.");
1124     return -1;
1125   }
1126
1127   if ((host->notification_handlers.nb_strs > 0) && (host->notifications == 0)) {
1128     WARNING("write_sensu plugin: NotificationHandler given so forcing "
1129             "notifications to be enabled");
1130     host->notifications = 1;
1131   }
1132
1133   if ((host->metric_handlers.nb_strs > 0) && (host->metrics == 0)) {
1134     WARNING("write_sensu plugin: MetricHandler given so forcing metrics to be "
1135             "enabled");
1136     host->metrics = 1;
1137   }
1138
1139   if (!(host->notifications || host->metrics)) {
1140     WARNING("write_sensu plugin: neither metrics nor notifications enabled. "
1141             "Giving up.");
1142     sensu_free(host);
1143     return -1;
1144   }
1145
1146   snprintf(callback_name, sizeof(callback_name), "write_sensu/%s", host->name);
1147
1148   user_data_t ud = {.data = host, .free_func = sensu_free};
1149
1150   pthread_mutex_lock(&host->lock);
1151
1152   if (host->metrics) {
1153     status = plugin_register_write(callback_name, sensu_write, &ud);
1154     if (status != 0)
1155       WARNING("write_sensu plugin: plugin_register_write (\"%s\") "
1156               "failed with status %i.",
1157               callback_name, status);
1158     else /* success */
1159       host->reference_count++;
1160   }
1161
1162   if (host->notifications) {
1163     status =
1164         plugin_register_notification(callback_name, sensu_notification, &ud);
1165     if (status != 0)
1166       WARNING("write_sensu plugin: plugin_register_notification (\"%s\") "
1167               "failed with status %i.",
1168               callback_name, status);
1169     else
1170       host->reference_count++;
1171   }
1172
1173   if (host->reference_count <= 1) {
1174     /* Both callbacks failed => free memory.
1175      * We need to unlock here, because sensu_free() will lock.
1176      * This is not a race condition, because we're the only one
1177      * holding a reference. */
1178     pthread_mutex_unlock(&host->lock);
1179     sensu_free(host);
1180     return -1;
1181   }
1182
1183   host->reference_count--;
1184   pthread_mutex_unlock(&host->lock);
1185
1186   return status;
1187 } /* }}} int sensu_config_node */
1188
1189 static int sensu_config(oconfig_item_t *ci) /* {{{ */
1190 {
1191   oconfig_item_t *child;
1192   int status;
1193   struct str_list sensu_tags_arr;
1194
1195   sensu_tags_arr.nb_strs = 0;
1196   sensu_tags_arr.strs = NULL;
1197
1198   for (int i = 0; i < ci->children_num; i++) {
1199     child = &ci->children[i];
1200
1201     if (strcasecmp("Node", child->key) == 0) {
1202       sensu_config_node(child);
1203     } else if (strcasecmp(child->key, "attribute") == 0) {
1204       if (child->values_num != 2) {
1205         WARNING("sensu attributes need both a key and a value.");
1206         continue;
1207       }
1208       if (child->values[0].type != OCONFIG_TYPE_STRING ||
1209           child->values[1].type != OCONFIG_TYPE_STRING) {
1210         WARNING("sensu attribute needs string arguments.");
1211         continue;
1212       }
1213
1214       strarray_add(&sensu_attrs, &sensu_attrs_num,
1215                    child->values[0].value.string);
1216       strarray_add(&sensu_attrs, &sensu_attrs_num,
1217                    child->values[1].value.string);
1218
1219       DEBUG("write_sensu plugin: New attribute: %s => %s",
1220             child->values[0].value.string, child->values[1].value.string);
1221     } else if (strcasecmp(child->key, "tag") == 0) {
1222       char *tmp = NULL;
1223       status = cf_util_get_string(child, &tmp);
1224       if (status != 0)
1225         continue;
1226
1227       status = add_str_to_list(&sensu_tags_arr, tmp);
1228       sfree(tmp);
1229       if (status != 0)
1230         continue;
1231       DEBUG("write_sensu plugin: Got tag: %s", tmp);
1232     } else {
1233       WARNING("write_sensu plugin: Ignoring unknown "
1234               "configuration option \"%s\" at top level.",
1235               child->key);
1236     }
1237   }
1238   if (sensu_tags_arr.nb_strs > 0) {
1239     sfree(sensu_tags);
1240     sensu_tags = build_json_str_list("tags", &sensu_tags_arr);
1241     free_str_list(&sensu_tags_arr);
1242     if (sensu_tags == NULL) {
1243       ERROR("write_sensu plugin: Unable to alloc memory");
1244       return -1;
1245     }
1246   }
1247   return 0;
1248 } /* }}} int sensu_config */
1249
1250 void module_register(void) {
1251   plugin_register_complex_config("write_sensu", sensu_config);
1252 }