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