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