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