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