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