Merge branch 'collectd-5.4' into collectd-5.5
[collectd.git] / src / write_sensu.c
1 /**
2  * collectd - src/write_sensu.c
3  * Copyright (C) 2015 Fabrice A. Marie
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Fabrice A. Marie <fabrice at kibinlabs.com>
25  */
26
27 #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 <sys/socket.h>
35 #include <arpa/inet.h>
36 #include <errno.h>
37 #include <netdb.h>
38 #include <inttypes.h>
39 #include <pthread.h>
40 #include <stddef.h>
41
42 #include <stdlib.h>
43 #define SENSU_HOST              "localhost"
44 #define SENSU_PORT              "3030"
45
46 struct str_list {
47         int nb_strs;
48         char **strs;
49 };
50
51 struct sensu_host {
52         char                    *name;
53         char                    *event_service_prefix;
54         struct str_list metric_handlers;
55         struct str_list notification_handlers;
56 #define F_READY      0x01
57         uint8_t                  flags;
58         pthread_mutex_t  lock;
59         _Bool            notifications;
60         _Bool            metrics;
61         _Bool                    store_rates;
62         _Bool                    always_append_ds;
63         char                    *separator;
64         char                    *node;
65         char                    *service;
66         int              s;
67         struct addrinfo *res;
68         int                          reference_count;
69 };
70
71 static char     *sensu_tags = NULL;
72 static char     **sensu_attrs = NULL;
73 static size_t sensu_attrs_num;
74
75 static int add_str_to_list(struct str_list *strs,
76                 const char *str_to_add) /* {{{ */
77 {
78         char **old_strs_ptr = strs->strs;
79         char *newstr = strdup(str_to_add);
80         if (newstr == NULL) {
81                 ERROR("write_sensu plugin: Unable to alloc memory");
82                 return -1;
83         }
84         strs->strs = realloc(strs->strs, sizeof(char *) *(strs->nb_strs + 1));
85         if (strs->strs == NULL) {
86                 strs->strs = old_strs_ptr;
87                 free(newstr);
88                 ERROR("write_sensu plugin: Unable to alloc memory");
89                 return -1;
90         }
91         strs->strs[strs->nb_strs] = newstr;
92         strs->nb_strs++;
93         return 0;
94 }
95 /* }}} int add_str_to_list */
96
97 static void free_str_list(struct str_list *strs) /* {{{ */
98 {
99         int i;
100         for (i=0; i<strs->nb_strs; i++)
101                 free(strs->strs[i]);
102         free(strs->strs);
103 }
104 /* }}} void free_str_list */
105
106 static int sensu_connect(struct sensu_host *host) /* {{{ */
107 {
108         int                      e;
109         struct addrinfo         *ai, hints;
110         char const              *node;
111         char const              *service;
112
113         // Resolve the target if we haven't done already
114         if (!(host->flags & F_READY)) {
115                 memset(&hints, 0, sizeof(hints));
116                 memset(&service, 0, sizeof(service));
117                 host->res = NULL;
118                 hints.ai_family = AF_INET;
119                 hints.ai_socktype = SOCK_STREAM;
120 #ifdef AI_ADDRCONFIG
121                 hints.ai_flags |= AI_ADDRCONFIG;
122 #endif
123
124                 node = (host->node != NULL) ? host->node : SENSU_HOST;
125                 service = (host->service != NULL) ? host->service : SENSU_PORT;
126
127                 if ((e = getaddrinfo(node, service, &hints, &(host->res))) != 0) {
128                         ERROR("write_sensu plugin: Unable to resolve host \"%s\": %s",
129                                         node, gai_strerror(e));
130                         return -1;
131                 }
132                 DEBUG("write_sensu plugin: successfully resolved host/port: %s/%s",
133                                 node, service);
134                 host->flags |= F_READY;
135         }
136
137         struct linger so_linger;
138         host->s = -1;
139         for (ai = host->res; ai != NULL; ai = ai->ai_next) {
140                 // create the socket
141                 if ((host->s = socket(ai->ai_family,
142                                       ai->ai_socktype,
143                                       ai->ai_protocol)) == -1) {
144                         continue;
145                 }
146
147                 // Set very low close() lingering
148                 so_linger.l_onoff = 1;
149                 so_linger.l_linger = 3;
150                 if (setsockopt(host->s, SOL_SOCKET, SO_LINGER, &so_linger, sizeof so_linger) != 0)
151                         WARNING("write_sensu plugin: failed to set socket close() lingering");
152
153                 // connect the socket
154                 if (connect(host->s, ai->ai_addr, ai->ai_addrlen) != 0) {
155                         close(host->s);
156                         host->s = -1;
157                         continue;
158                 }
159                 DEBUG("write_sensu plugin: connected");
160                 break;
161         }
162
163         if (host->s < 0) {
164                 WARNING("write_sensu plugin: Unable to connect to sensu client");
165                 return -1;
166         }
167         return 0;
168 } /* }}} int sensu_connect */
169
170 static void sensu_close_socket(struct sensu_host *host) /* {{{ */
171 {
172         if (host->s != -1)
173                 close(host->s);
174         host->s = -1;
175
176 } /* }}} void sensu_close_socket */
177
178 static char *build_json_str_list(const char *tag, struct str_list const *list) /* {{{ */
179 {
180         int res;
181         char *ret_str;
182         char *temp_str;
183         int i;
184         if (list->nb_strs == 0) {
185                 ret_str = malloc(sizeof(char));
186                 if (ret_str == NULL) {
187                         ERROR("write_sensu plugin: Unable to alloc memory");
188                         return NULL;
189                 }
190                 ret_str[0] = '\0';
191         }
192
193         res = asprintf(&temp_str, "\"%s\": [\"%s\"", tag, list->strs[0]);
194         if (res == -1) {
195                 ERROR("write_sensu plugin: Unable to alloc memory");
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         int 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 = malloc(retlen + 1);
529         if (ret == NULL)
530                 return NULL;
531         // added to original: not optimized, but keeps valgrind happy.
532         memset(ret, 0, retlen + 1);
533
534         r = ret;
535         p = str;
536         while (1) {
537                 /* If the old and new strings are different lengths - in other
538                  * words we have already iterated through with strstr above,
539                  * and thus we know how many times we need to call it - then we
540                  * can avoid the final (potentially lengthy) call to strstr,
541                  * which we already know is going to return NULL, by
542                  * decrementing and checking count.
543                  */
544                 if (!samesize && !count--)
545                         break;
546                 /* Otherwise i.e. when the old and new strings are the same
547                  * length, and we don't know how many times to call strstr,
548                  * we must check for a NULL return here (we check it in any
549                  * event, to avoid further conditions, and because there's
550                  * no harm done with the check even when the old and new
551                  * strings are different lengths).
552                  */
553                 if ((q = strstr(p, old)) == NULL)
554                         break;
555                 /* This is undefined if q - p > PTRDIFF_MAX */
556                 ptrdiff_t l = q - p;
557                 memcpy(r, p, l);
558                 r += l;
559                 memcpy(r, new, newlen);
560                 r += newlen;
561                 p = q + oldlen;
562         }
563         strncpy(r, p, strlen(p));
564
565         return ret;
566 } /* }}} char *replace_str */
567
568 static char *replace_json_reserved(const char *message) /* {{{ */
569 {
570         char *msg = replace_str(message, "\\", "\\\\");
571         if (msg == NULL) {
572                 ERROR("write_sensu plugin: Unable to alloc memory");
573                 return NULL;
574         }
575         char *tmp = replace_str(msg, "\"", "\\\"");
576         free(msg);
577         if (tmp == NULL) {
578                 ERROR("write_sensu plugin: Unable to alloc memory");
579                 return NULL;
580         }
581         msg = replace_str(tmp, "\n", "\\\n");
582         free(tmp);
583         if (msg == NULL) {
584                 ERROR("write_sensu plugin: Unable to alloc memory");
585                 return NULL;
586         }
587         return msg;
588 } /* }}} char *replace_json_reserved */
589
590 static char *sensu_notification_to_json(struct sensu_host *host, /* {{{ */
591                 notification_t const *n)
592 {
593         char service_buffer[6 * DATA_MAX_NAME_LEN];
594         char const *severity;
595         notification_meta_t *meta;
596         char *ret_str;
597         char *temp_str;
598         int status;
599         int i;
600         int res;
601         // add the severity/status
602         switch (n->severity) {
603                 case NOTIF_OKAY:
604                         severity = "OK";
605                         status = 0;
606                         break;
607                 case NOTIF_WARNING:
608                         severity = "WARNING";
609                         status = 1;
610                         break;
611                 case NOTIF_FAILURE:
612                         severity = "CRITICAL";
613                         status = 2;
614                         break;
615                 default:
616                         severity = "UNKNOWN";
617                         status = 3;
618         }
619         res = asprintf(&temp_str, "{\"status\": %d", status);
620         if (res == -1) {
621                 ERROR("write_sensu plugin: Unable to alloc memory");
622                 return NULL;
623         }
624         ret_str = temp_str;
625
626         // incorporate the timestamp
627         res = asprintf(&temp_str, "%s, \"timestamp\": %ld", ret_str, CDTIME_T_TO_TIME_T(n->time));
628         free(ret_str);
629         if (res == -1) {
630                 ERROR("write_sensu plugin: Unable to alloc memory");
631                 return NULL;
632         }
633         ret_str = temp_str;
634
635         char *handlers_str = build_json_str_list("handlers", &(host->notification_handlers));
636         if (handlers_str == NULL) {
637                 ERROR("write_sensu plugin: Unable to alloc memory");
638                 free(ret_str);
639                 return NULL;
640         }
641         // incorporate the handlers
642         if (strlen(handlers_str) != 0) {
643                 res = asprintf(&temp_str, "%s, %s", ret_str, handlers_str);
644                 free(ret_str);
645                 free(handlers_str);
646                 if (res == -1) {
647                         ERROR("write_sensu plugin: Unable to alloc memory");
648                         return NULL;
649                 }
650                 ret_str = temp_str;
651         } else {
652                 free(handlers_str);
653         }
654
655         // incorporate the plugin name information if any
656         if (n->plugin[0] != 0) {
657                 res = asprintf(&temp_str, "%s, \"collectd_plugin\": \"%s\"", ret_str, n->plugin);
658                 free(ret_str);
659                 if (res == -1) {
660                         ERROR("write_sensu plugin: Unable to alloc memory");
661                         return NULL;
662                 }
663                 ret_str = temp_str;
664         }
665
666         // incorporate the plugin type if any
667         if (n->type[0] != 0) {
668                 res = asprintf(&temp_str, "%s, \"collectd_plugin_type\": \"%s\"", ret_str, n->type);
669                 free(ret_str);
670                 if (res == -1) {
671                         ERROR("write_sensu plugin: Unable to alloc memory");
672                         return NULL;
673                 }
674                 ret_str = temp_str;
675         }
676
677         // incorporate the plugin instance if any
678         if (n->plugin_instance[0] != 0) {
679                 res = asprintf(&temp_str, "%s, \"collectd_plugin_instance\": \"%s\"", ret_str, n->plugin_instance);
680                 free(ret_str);
681                 if (res == -1) {
682                         ERROR("write_sensu plugin: Unable to alloc memory");
683                         return NULL;
684                 }
685                 ret_str = temp_str;
686         }
687
688         // incorporate the plugin type instance if any
689         if (n->type_instance[0] != 0) {
690                 res = asprintf(&temp_str, "%s, \"collectd_plugin_type_instance\": \"%s\"", ret_str, n->type_instance);
691                 free(ret_str);
692                 if (res == -1) {
693                         ERROR("write_sensu plugin: Unable to alloc memory");
694                         return NULL;
695                 }
696                 ret_str = temp_str;
697         }
698
699         // add key value attributes from config if any
700         for (i = 0; i < sensu_attrs_num; i += 2) {
701                 res = asprintf(&temp_str, "%s, \"%s\": \"%s\"", ret_str, sensu_attrs[i], sensu_attrs[i+1]);
702                 free(ret_str);
703                 if (res == -1) {
704                         ERROR("write_sensu plugin: Unable to alloc memory");
705                         return NULL;
706                 }
707                 ret_str = temp_str;
708         }
709
710         // incorporate sensu tags from config if any
711         if ((sensu_tags != NULL) && (strlen(sensu_tags) != 0)) {
712                 res = asprintf(&temp_str, "%s, %s", ret_str, sensu_tags);
713                 free(ret_str);
714                 if (res == -1) {
715                         ERROR("write_sensu plugin: Unable to alloc memory");
716                         return NULL;
717                 }
718                 ret_str = temp_str;
719         }
720
721         // incorporate the service name
722         sensu_format_name2(service_buffer, sizeof(service_buffer),
723                                 /* host */ "", n->plugin, n->plugin_instance,
724                                 n->type, n->type_instance, host->separator);
725         // replace sensu event name chars that are considered illegal
726         in_place_replace_sensu_name_reserved(service_buffer);
727         res = asprintf(&temp_str, "%s, \"name\": \"%s\"", ret_str, &service_buffer[1]);
728         free(ret_str);
729         if (res == -1) {
730                 ERROR("write_sensu plugin: Unable to alloc memory");
731                 return NULL;
732         }
733         ret_str = temp_str;
734
735         // incorporate the check output
736         if (n->message[0] != 0) {
737                 char *msg = replace_json_reserved(n->message);
738                 if (msg == NULL) {
739                         ERROR("write_sensu plugin: Unable to alloc memory");
740                         free(ret_str);
741                         return NULL;
742                 }
743                 res = asprintf(&temp_str, "%s, \"output\": \"%s - %s\"", ret_str, severity, msg);
744                 free(ret_str);
745                 free(msg);
746                 if (res == -1) {
747                         ERROR("write_sensu plugin: Unable to alloc memory");
748                         return NULL;
749                 }
750                 ret_str = temp_str;
751         }
752
753         // Pull in values from threshold and add extra attributes
754         for (meta = n->meta; meta != NULL; meta = meta->next) {
755                 if (strcasecmp("CurrentValue", meta->name) == 0 && meta->type == NM_TYPE_DOUBLE) {
756                         res = asprintf(&temp_str, "%s, \"current_value\": \"%.8f\"", ret_str, meta->nm_value.nm_double);
757                         free(ret_str);
758                         if (res == -1) {
759                                 ERROR("write_sensu plugin: Unable to alloc memory");
760                                 return NULL;
761                         }
762                         ret_str = temp_str;
763                 }
764                 if (meta->type == NM_TYPE_STRING) {
765                         res = asprintf(&temp_str, "%s, \"%s\": \"%s\"", ret_str, meta->name, meta->nm_value.nm_string);
766                         free(ret_str);
767                         if (res == -1) {
768                                 ERROR("write_sensu plugin: Unable to alloc memory");
769                                 return NULL;
770                         }
771                         ret_str = temp_str;
772                 }
773         }
774
775         // close the curly bracket
776         res = asprintf(&temp_str, "%s}\n", ret_str);
777         free(ret_str);
778         if (res == -1) {
779                 ERROR("write_sensu plugin: Unable to alloc memory");
780                 return NULL;
781         }
782         ret_str = temp_str;
783
784         DEBUG("write_sensu plugin: Successfully created JSON for notification: "
785                                 "host = \"%s\", service = \"%s\", state = \"%s\"",
786                                 n->host, service_buffer, severity);
787         return ret_str;
788 } /* }}} char *sensu_notification_to_json */
789
790 static int sensu_send_msg(struct sensu_host *host, const char *msg) /* {{{ */
791 {
792         int status = 0;
793         size_t  buffer_len;
794
795         status = sensu_connect(host);
796         if (status != 0)
797                 return status;
798
799         buffer_len = strlen(msg);
800
801         status = (int) swrite(host->s, msg, buffer_len);
802         sensu_close_socket(host);
803
804         if (status != 0) {
805                 char errbuf[1024];
806                 ERROR("write_sensu plugin: Sending to Sensu at %s:%s failed: %s",
807                                 (host->node != NULL) ? host->node : SENSU_HOST,
808                                 (host->service != NULL) ? host->service : SENSU_PORT,
809                                 sstrerror(errno, errbuf, sizeof(errbuf)));
810                 return -1;
811         }
812
813         return 0;
814 } /* }}} int sensu_send_msg */
815
816
817 static int sensu_send(struct sensu_host *host, char const *msg) /* {{{ */
818 {
819         int status = 0;
820
821         status = sensu_send_msg(host, msg);
822         if (status != 0) {
823                 host->flags &= ~F_READY;
824                 if (host->res != NULL) {
825                         freeaddrinfo(host->res);
826                         host->res = NULL;
827                 }
828                 return status;
829         }
830
831         return 0;
832 } /* }}} int sensu_send */
833
834
835 static int sensu_write(const data_set_t *ds, /* {{{ */
836               const value_list_t *vl,
837               user_data_t *ud)
838 {
839         int status = 0;
840         int statuses[vl->values_len];
841         struct sensu_host       *host = ud->data;
842         gauge_t *rates = NULL;
843         int i;
844         char *msg;
845
846         pthread_mutex_lock(&host->lock);
847         memset(statuses, 0, vl->values_len * sizeof(*statuses));
848
849         if (host->store_rates) {
850                 rates = uc_get_rate(ds, vl);
851                 if (rates == NULL) {
852                         ERROR("write_sensu plugin: uc_get_rate failed.");
853                         pthread_mutex_unlock(&host->lock);
854                         return -1;
855                 }
856         }
857         for (i = 0; i < (size_t) vl->values_len; i++) {
858                 msg = sensu_value_to_json(host, ds, vl, (int) i, rates, statuses[i]);
859                 if (msg == NULL) {
860                         sfree(rates);
861                         pthread_mutex_unlock(&host->lock);
862                         return -1;
863                 }
864                 status = sensu_send(host, msg);
865                 free(msg);
866                 if (status != 0) {
867                         ERROR("write_sensu plugin: sensu_send failed with status %i", status);
868                         pthread_mutex_unlock(&host->lock);
869                         sfree(rates);
870                         return status;
871                 }
872         }
873         sfree(rates);
874         pthread_mutex_unlock(&host->lock);
875         return status;
876 } /* }}} int sensu_write */
877
878 static int sensu_notification(const notification_t *n, user_data_t *ud) /* {{{ */
879 {
880         int     status;
881         struct sensu_host *host = ud->data;
882         char *msg;
883
884         pthread_mutex_lock(&host->lock);
885
886         msg = sensu_notification_to_json(host, n);
887         if (msg == NULL) {
888                 pthread_mutex_unlock(&host->lock);
889                 return -1;
890         }
891
892         status = sensu_send(host, msg);
893         free(msg);
894         if (status != 0)
895                 ERROR("write_sensu plugin: sensu_send failed with status %i", status);
896         pthread_mutex_unlock(&host->lock);
897
898         return status;
899 } /* }}} int sensu_notification */
900
901 static void sensu_free(void *p) /* {{{ */
902 {
903         struct sensu_host *host = p;
904
905         if (host == NULL)
906                 return;
907
908         pthread_mutex_lock(&host->lock);
909
910         host->reference_count--;
911         if (host->reference_count > 0) {
912                 pthread_mutex_unlock(&host->lock);
913                 return;
914         }
915
916         sensu_close_socket(host);
917         if (host->res != NULL) {
918                 freeaddrinfo(host->res);
919                 host->res = NULL;
920         }
921         sfree(host->service);
922         sfree(host->event_service_prefix);
923         sfree(host->name);
924         sfree(host->node);
925         sfree(host->separator);
926         free_str_list(&(host->metric_handlers));
927         free_str_list(&(host->notification_handlers));
928         pthread_mutex_destroy(&host->lock);
929         sfree(host);
930 } /* }}} void sensu_free */
931
932
933 static int sensu_config_node(oconfig_item_t *ci) /* {{{ */
934 {
935         struct sensu_host       *host = NULL;
936         int                                     status = 0;
937         int                                     i;
938         oconfig_item_t          *child;
939         char                            callback_name[DATA_MAX_NAME_LEN];
940         user_data_t                     ud;
941
942         if ((host = calloc(1, sizeof(*host))) == NULL) {
943                 ERROR("write_sensu plugin: calloc failed.");
944                 return ENOMEM;
945         }
946         pthread_mutex_init(&host->lock, NULL);
947         host->reference_count = 1;
948         host->node = NULL;
949         host->service = NULL;
950         host->notifications = 0;
951         host->metrics = 0;
952         host->store_rates = 1;
953         host->always_append_ds = 0;
954         host->metric_handlers.nb_strs = 0;
955         host->metric_handlers.strs = NULL;
956         host->notification_handlers.nb_strs = 0;
957         host->notification_handlers.strs = NULL;
958         host->separator = strdup("/");
959         if (host->separator == NULL) {
960                 ERROR("write_sensu plugin: Unable to alloc memory");
961                 sensu_free(host);
962                 return -1;
963         }
964
965         status = cf_util_get_string(ci, &host->name);
966         if (status != 0) {
967                 WARNING("write_sensu plugin: Required host name is missing.");
968                 sensu_free(host);
969                 return -1;
970         }
971
972         for (i = 0; i < ci->children_num; i++) {
973                 child = &ci->children[i];
974                 status = 0;
975
976                 if (strcasecmp("Host", child->key) == 0) {
977                         status = cf_util_get_string(child, &host->node);
978                         if (status != 0)
979                                 break;
980                 } else if (strcasecmp("Notifications", child->key) == 0) {
981                         status = cf_util_get_boolean(child, &host->notifications);
982                         if (status != 0)
983                                 break;
984                 } else if (strcasecmp("Metrics", child->key) == 0) {
985                                         status = cf_util_get_boolean(child, &host->metrics);
986                                         if (status != 0)
987                                                 break;
988                 } else if (strcasecmp("EventServicePrefix", child->key) == 0) {
989                         status = cf_util_get_string(child, &host->event_service_prefix);
990                         if (status != 0)
991                                 break;
992                 } else if (strcasecmp("Separator", child->key) == 0) {
993                                 status = cf_util_get_string(child, &host->separator);
994                                 if (status != 0)
995                                         break;
996                 } else if (strcasecmp("MetricHandler", 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->metric_handlers), temp_str);
1002                         free(temp_str);
1003                         if (status != 0)
1004                                 break;
1005                 } else if (strcasecmp("NotificationHandler", child->key) == 0) {
1006                         char *temp_str = NULL;
1007                         status = cf_util_get_string(child, &temp_str);
1008                         if (status != 0)
1009                                 break;
1010                         status = add_str_to_list(&(host->notification_handlers), temp_str);
1011                         free(temp_str);
1012                         if (status != 0)
1013                                 break;
1014                 } else if (strcasecmp("Port", child->key) == 0) {
1015                         status = cf_util_get_service(child, &host->service);
1016                         if (status != 0) {
1017                                 ERROR("write_sensu plugin: Invalid argument "
1018                                                 "configured for the \"Port\" "
1019                                                 "option.");
1020                                 break;
1021                         }
1022                 } else if (strcasecmp("StoreRates", child->key) == 0) {
1023                         status = cf_util_get_boolean(child, &host->store_rates);
1024                         if (status != 0)
1025                                 break;
1026                 } else if (strcasecmp("AlwaysAppendDS", child->key) == 0) {
1027                         status = cf_util_get_boolean(child,
1028                                         &host->always_append_ds);
1029                         if (status != 0)
1030                                 break;
1031                 } else {
1032                         WARNING("write_sensu plugin: ignoring unknown config "
1033                                 "option: \"%s\"", child->key);
1034                 }
1035         }
1036         if (status != 0) {
1037                 sensu_free(host);
1038                 return status;
1039         }
1040
1041         if (host->metrics && (host->metric_handlers.nb_strs == 0)) {
1042                         sensu_free(host);
1043                         WARNING("write_sensu plugin: metrics enabled but no MetricHandler defined. Giving up.");
1044                         return -1;
1045                 }
1046
1047         if (host->notifications && (host->notification_handlers.nb_strs == 0)) {
1048                 sensu_free(host);
1049                 WARNING("write_sensu plugin: notifications enabled but no NotificationHandler defined. Giving up.");
1050                 return -1;
1051         }
1052
1053         if ((host->notification_handlers.nb_strs > 0) && (host->notifications == 0)) {
1054                 WARNING("write_sensu plugin: NotificationHandler given so forcing notifications to be enabled");
1055                 host->notifications = 1;
1056         }
1057
1058         if ((host->metric_handlers.nb_strs > 0) && (host->metrics == 0)) {
1059                 WARNING("write_sensu plugin: MetricHandler given so forcing metrics to be enabled");
1060                 host->metrics = 1;
1061         }
1062
1063         if (!(host->notifications || host->metrics)) {
1064                 WARNING("write_sensu plugin: neither metrics nor notifications enabled. Giving up.");
1065                 sensu_free(host);
1066                 return -1;
1067         }
1068
1069         ssnprintf(callback_name, sizeof(callback_name), "write_sensu/%s", host->name);
1070         ud.data = host;
1071         ud.free_func = sensu_free;
1072
1073         pthread_mutex_lock(&host->lock);
1074
1075         if (host->metrics) {
1076                 status = plugin_register_write(callback_name, sensu_write, &ud);
1077                 if (status != 0)
1078                         WARNING("write_sensu plugin: plugin_register_write (\"%s\") "
1079                                         "failed with status %i.",
1080                                         callback_name, status);
1081                 else /* success */
1082                         host->reference_count++;
1083         }
1084
1085         if (host->notifications) {
1086                 status = plugin_register_notification(callback_name, sensu_notification, &ud);
1087                 if (status != 0)
1088                         WARNING("write_sensu plugin: plugin_register_notification (\"%s\") "
1089                                         "failed with status %i.",
1090                                         callback_name, status);
1091                 else
1092                         host->reference_count++;
1093         }
1094
1095         if (host->reference_count <= 1) {
1096                 /* Both callbacks failed => free memory.
1097                  * We need to unlock here, because sensu_free() will lock.
1098                  * This is not a race condition, because we're the only one
1099                  * holding a reference. */
1100                 pthread_mutex_unlock(&host->lock);
1101                 sensu_free(host);
1102                 return -1;
1103         }
1104
1105         host->reference_count--;
1106         pthread_mutex_unlock(&host->lock);
1107
1108         return status;
1109 } /* }}} int sensu_config_node */
1110
1111 static int sensu_config(oconfig_item_t *ci) /* {{{ */
1112 {
1113         int              i;
1114         oconfig_item_t  *child;
1115         int              status;
1116         struct str_list sensu_tags_arr;
1117
1118         sensu_tags_arr.nb_strs = 0;
1119         sensu_tags_arr.strs = NULL;
1120
1121         for (i = 0; i < ci->children_num; i++)  {
1122                 child = &ci->children[i];
1123
1124                 if (strcasecmp("Node", child->key) == 0) {
1125                         sensu_config_node(child);
1126                 } else if (strcasecmp(child->key, "attribute") == 0) {
1127                         if (child->values_num != 2) {
1128                                 WARNING("sensu attributes need both a key and a value.");
1129                                 continue;
1130                         }
1131                         if (child->values[0].type != OCONFIG_TYPE_STRING ||
1132                                         child->values[1].type != OCONFIG_TYPE_STRING) {
1133                                 WARNING("sensu attribute needs string arguments.");
1134                                 continue;
1135                         }
1136
1137                         strarray_add(&sensu_attrs, &sensu_attrs_num, child->values[0].value.string);
1138                         strarray_add(&sensu_attrs, &sensu_attrs_num, child->values[1].value.string);
1139
1140                         DEBUG("write_sensu plugin: New attribute: %s => %s",
1141                                         child->values[0].value.string,
1142                                         child->values[1].value.string);
1143                 } else if (strcasecmp(child->key, "tag") == 0) {
1144                         char *tmp = NULL;
1145                         status = cf_util_get_string(child, &tmp);
1146                         if (status != 0)
1147                                 continue;
1148
1149                         status = add_str_to_list(&sensu_tags_arr, tmp);
1150                         sfree(tmp);
1151                         if (status != 0)
1152                                 continue;
1153                         DEBUG("write_sensu plugin: Got tag: %s", tmp);
1154                 } else {
1155                         WARNING("write_sensu plugin: Ignoring unknown "
1156                                  "configuration option \"%s\" at top level.",
1157                                  child->key);
1158                 }
1159         }
1160         if (sensu_tags_arr.nb_strs > 0) {
1161                 sfree (sensu_tags);
1162                 sensu_tags = build_json_str_list("tags", &sensu_tags_arr);
1163                 free_str_list(&sensu_tags_arr);
1164                 if (sensu_tags == NULL) {
1165                         ERROR("write_sensu plugin: Unable to alloc memory");
1166                         return -1;
1167                 }
1168         }
1169         return 0;
1170 } /* }}} int sensu_config */
1171
1172 void module_register(void)
1173 {
1174         plugin_register_complex_config("write_sensu", sensu_config);
1175 }
1176
1177 /* vim: set sw=8 sts=8 ts=8 noet : */