1 /**
2 * collectd - src/write_graphite.c
3 * Copyright (C) 2012 Pierre-Yves Ritschard
4 * Copyright (C) 2011 Scott Sanders
5 * Copyright (C) 2009 Paul Sadauskas
6 * Copyright (C) 2009 Doug MacEachern
7 * Copyright (C) 2007-2013 Florian octo Forster
8 *
9 * This program is free software; you can redistribute it and/or modify it
10 * under the terms of the GNU General Public License as published by the
11 * Free Software Foundation; only version 2 of the License is applicable.
12 *
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 *
22 * Authors:
23 * Florian octo Forster <octo at collectd.org>
24 * Doug MacEachern <dougm at hyperic.com>
25 * Paul Sadauskas <psadauskas at gmail.com>
26 * Scott Sanders <scott at jssjr.com>
27 * Pierre-Yves Ritschard <pyr at spootnik.org>
28 *
29 * Based on the write_http plugin.
30 **/
32 /* write_graphite plugin configuation example
33 *
34 * <Plugin write_graphite>
35 * <Carbon>
36 * Host "localhost"
37 * Port "2003"
38 * Prefix "collectd"
39 * </Carbon>
40 * </Plugin>
41 */
43 #include "collectd.h"
44 #include "common.h"
45 #include "plugin.h"
46 #include "configfile.h"
48 #include "utils_cache.h"
49 #include "utils_complain.h"
50 #include "utils_parse_option.h"
52 /* Folks without pthread will need to disable this plugin. */
53 #include <pthread.h>
55 #include <sys/socket.h>
56 #include <netdb.h>
58 #ifndef WG_DEFAULT_NODE
59 # define WG_DEFAULT_NODE "localhost"
60 #endif
62 #ifndef WG_DEFAULT_SERVICE
63 # define WG_DEFAULT_SERVICE "2003"
64 #endif
66 #ifndef WG_DEFAULT_ESCAPE
67 # define WG_DEFAULT_ESCAPE '_'
68 #endif
70 /* Ethernet - (IPv6 + TCP) = 1500 - (40 + 32) = 1428 */
71 #ifndef WG_SEND_BUF_SIZE
72 # define WG_SEND_BUF_SIZE 1428
73 #endif
75 /*
76 * Private variables
77 */
78 struct wg_callback
79 {
80 int sock_fd;
82 char *node;
83 char *service;
84 char *prefix;
85 char *postfix;
86 char escape_char;
88 _Bool store_rates;
89 _Bool separate_instances;
90 _Bool always_append_ds;
92 char send_buf[WG_SEND_BUF_SIZE];
93 size_t send_buf_free;
94 size_t send_buf_fill;
95 cdtime_t send_buf_init_time;
97 pthread_mutex_t send_lock;
98 c_complain_t init_complaint;
99 };
102 /*
103 * Functions
104 */
105 static void wg_reset_buffer (struct wg_callback *cb)
106 {
107 memset (cb->send_buf, 0, sizeof (cb->send_buf));
108 cb->send_buf_free = sizeof (cb->send_buf);
109 cb->send_buf_fill = 0;
110 cb->send_buf_init_time = cdtime ();
111 }
113 static int wg_send_buffer (struct wg_callback *cb)
114 {
115 ssize_t status = 0;
117 status = swrite (cb->sock_fd, cb->send_buf, strlen (cb->send_buf));
118 if (status < 0)
119 {
120 char errbuf[1024];
121 ERROR ("write_graphite plugin: send failed with status %zi (%s)",
122 status, sstrerror (errno, errbuf, sizeof (errbuf)));
125 close (cb->sock_fd);
126 cb->sock_fd = -1;
128 return (-1);
129 }
131 return (0);
132 }
134 /* NOTE: You must hold cb->send_lock when calling this function! */
135 static int wg_flush_nolock (cdtime_t timeout, struct wg_callback *cb)
136 {
137 int status;
139 DEBUG ("write_graphite plugin: wg_flush_nolock: timeout = %.3f; "
140 "send_buf_fill = %zu;",
141 (double)timeout,
142 cb->send_buf_fill);
144 /* timeout == 0 => flush unconditionally */
145 if (timeout > 0)
146 {
147 cdtime_t now;
149 now = cdtime ();
150 if ((cb->send_buf_init_time + timeout) > now)
151 return (0);
152 }
154 if (cb->send_buf_fill <= 0)
155 {
156 cb->send_buf_init_time = cdtime ();
157 return (0);
158 }
160 status = wg_send_buffer (cb);
161 wg_reset_buffer (cb);
163 return (status);
164 }
166 static int wg_callback_init (struct wg_callback *cb)
167 {
168 struct addrinfo ai_hints;
169 struct addrinfo *ai_list;
170 struct addrinfo *ai_ptr;
171 int status;
173 const char *node = cb->node ? cb->node : WG_DEFAULT_NODE;
174 const char *service = cb->service ? cb->service : WG_DEFAULT_SERVICE;
176 if (cb->sock_fd > 0)
177 return (0);
179 memset (&ai_hints, 0, sizeof (ai_hints));
180 #ifdef AI_ADDRCONFIG
181 ai_hints.ai_flags |= AI_ADDRCONFIG;
182 #endif
183 ai_hints.ai_family = AF_UNSPEC;
184 ai_hints.ai_socktype = SOCK_STREAM;
186 ai_list = NULL;
188 status = getaddrinfo (node, service, &ai_hints, &ai_list);
189 if (status != 0)
190 {
191 ERROR ("write_graphite plugin: getaddrinfo (%s, %s) failed: %s",
192 node, service, gai_strerror (status));
193 return (-1);
194 }
196 assert (ai_list != NULL);
197 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
198 {
199 cb->sock_fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
200 ai_ptr->ai_protocol);
201 if (cb->sock_fd < 0)
202 continue;
204 status = connect (cb->sock_fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
205 if (status != 0)
206 {
207 close (cb->sock_fd);
208 cb->sock_fd = -1;
209 continue;
210 }
212 break;
213 }
215 freeaddrinfo (ai_list);
217 if (cb->sock_fd < 0)
218 {
219 char errbuf[1024];
220 c_complain (LOG_ERR, &cb->init_complaint,
221 "write_graphite plugin: Connecting to %s:%s failed. "
222 "The last error was: %s", node, service,
223 sstrerror (errno, errbuf, sizeof (errbuf)));
224 close (cb->sock_fd);
225 return (-1);
226 }
227 else
228 {
229 c_release (LOG_INFO, &cb->init_complaint,
230 "write_graphite plugin: Successfully connected to %s:%s.",
231 node, service);
232 }
234 wg_reset_buffer (cb);
236 return (0);
237 }
239 static void wg_callback_free (void *data)
240 {
241 struct wg_callback *cb;
243 if (data == NULL)
244 return;
246 cb = data;
248 pthread_mutex_lock (&cb->send_lock);
250 wg_flush_nolock (/* timeout = */ 0, cb);
252 close(cb->sock_fd);
253 cb->sock_fd = -1;
255 sfree(cb->node);
256 sfree(cb->service);
257 sfree(cb->prefix);
258 sfree(cb->postfix);
260 pthread_mutex_destroy (&cb->send_lock);
262 sfree(cb);
263 }
265 static int wg_flush (cdtime_t timeout,
266 const char *identifier __attribute__((unused)),
267 user_data_t *user_data)
268 {
269 struct wg_callback *cb;
270 int status;
272 if (user_data == NULL)
273 return (-EINVAL);
275 cb = user_data->data;
277 pthread_mutex_lock (&cb->send_lock);
279 if (cb->sock_fd < 0)
280 {
281 status = wg_callback_init (cb);
282 if (status != 0)
283 {
284 /* An error message has already been printed. */
285 pthread_mutex_unlock (&cb->send_lock);
286 return (-1);
287 }
288 }
290 status = wg_flush_nolock (timeout, cb);
291 pthread_mutex_unlock (&cb->send_lock);
293 return (status);
294 }
296 static int wg_format_values (char *ret, size_t ret_len,
297 int ds_num, const data_set_t *ds, const value_list_t *vl,
298 _Bool store_rates)
299 {
300 size_t offset = 0;
301 int status;
302 gauge_t *rates = NULL;
304 assert (0 == strcmp (ds->type, vl->type));
306 memset (ret, 0, ret_len);
308 #define BUFFER_ADD(...) do { \
309 status = ssnprintf (ret + offset, ret_len - offset, \
310 __VA_ARGS__); \
311 if (status < 1) \
312 { \
313 sfree (rates); \
314 return (-1); \
315 } \
316 else if (((size_t) status) >= (ret_len - offset)) \
317 { \
318 sfree (rates); \
319 return (-1); \
320 } \
321 else \
322 offset += ((size_t) status); \
323 } while (0)
325 if (ds->ds[ds_num].type == DS_TYPE_GAUGE)
326 BUFFER_ADD ("%f", vl->values[ds_num].gauge);
327 else if (store_rates)
328 {
329 if (rates == NULL)
330 rates = uc_get_rate (ds, vl);
331 if (rates == NULL)
332 {
333 WARNING ("format_values: "
334 "uc_get_rate failed.");
335 return (-1);
336 }
337 BUFFER_ADD ("%g", rates[ds_num]);
338 }
339 else if (ds->ds[ds_num].type == DS_TYPE_COUNTER)
340 BUFFER_ADD ("%llu", vl->values[ds_num].counter);
341 else if (ds->ds[ds_num].type == DS_TYPE_DERIVE)
342 BUFFER_ADD ("%"PRIi64, vl->values[ds_num].derive);
343 else if (ds->ds[ds_num].type == DS_TYPE_ABSOLUTE)
344 BUFFER_ADD ("%"PRIu64, vl->values[ds_num].absolute);
345 else
346 {
347 ERROR ("format_values plugin: Unknown data source type: %i",
348 ds->ds[ds_num].type);
349 sfree (rates);
350 return (-1);
351 }
353 #undef BUFFER_ADD
355 sfree (rates);
356 return (0);
357 }
359 static void wg_copy_escape_part (char *dst, const char *src, size_t dst_len,
360 char escape_char)
361 {
362 size_t i;
364 memset (dst, 0, dst_len);
366 if (src == NULL)
367 return;
369 for (i = 0; i < dst_len; i++)
370 {
371 if (src[i] == 0)
372 {
373 dst[i] = 0;
374 break;
375 }
377 if ((src[i] == '.')
378 || isspace ((int) src[i])
379 || iscntrl ((int) src[i]))
380 dst[i] = escape_char;
381 else
382 dst[i] = src[i];
383 }
384 }
386 static int wg_format_name (char *ret, int ret_len,
387 const value_list_t *vl,
388 const struct wg_callback *cb,
389 const char *ds_name)
390 {
391 char n_host[DATA_MAX_NAME_LEN];
392 char n_plugin[DATA_MAX_NAME_LEN];
393 char n_plugin_instance[DATA_MAX_NAME_LEN];
394 char n_type[DATA_MAX_NAME_LEN];
395 char n_type_instance[DATA_MAX_NAME_LEN];
397 char *prefix;
398 char *postfix;
400 char tmp_plugin[2 * DATA_MAX_NAME_LEN + 1];
401 char tmp_type[2 * DATA_MAX_NAME_LEN + 1];
403 prefix = cb->prefix;
404 if (prefix == NULL)
405 prefix = "";
407 postfix = cb->postfix;
408 if (postfix == NULL)
409 postfix = "";
411 wg_copy_escape_part (n_host, vl->host,
412 sizeof (n_host), cb->escape_char);
413 wg_copy_escape_part (n_plugin, vl->plugin,
414 sizeof (n_plugin), cb->escape_char);
415 wg_copy_escape_part (n_plugin_instance, vl->plugin_instance,
416 sizeof (n_plugin_instance), cb->escape_char);
417 wg_copy_escape_part (n_type, vl->type,
418 sizeof (n_type), cb->escape_char);
419 wg_copy_escape_part (n_type_instance, vl->type_instance,
420 sizeof (n_type_instance), cb->escape_char);
422 if (n_plugin_instance[0] != '\0')
423 ssnprintf (tmp_plugin, sizeof (tmp_plugin), "%s%c%s",
424 n_plugin,
425 cb->separate_instances ? '.' : '-',
426 n_plugin_instance);
427 else
428 sstrncpy (tmp_plugin, n_plugin, sizeof (tmp_plugin));
430 if (n_type_instance[0] != '\0')
431 ssnprintf (tmp_type, sizeof (tmp_type), "%s%c%s",
432 n_type,
433 cb->separate_instances ? '.' : '-',
434 n_type_instance);
435 else
436 sstrncpy (tmp_type, n_type, sizeof (tmp_type));
438 if (ds_name != NULL)
439 ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s",
440 prefix, n_host, postfix, tmp_plugin, tmp_type, ds_name);
441 else
442 ssnprintf (ret, ret_len, "%s%s%s.%s.%s",
443 prefix, n_host, postfix, tmp_plugin, tmp_type);
445 return (0);
446 }
448 static int wg_send_message (const char* key, const char* value,
449 cdtime_t time, struct wg_callback *cb)
450 {
451 int status;
452 size_t message_len;
453 char message[1024];
455 message_len = (size_t) ssnprintf (message, sizeof (message),
456 "%s %s %u\r\n",
457 key,
458 value,
459 (unsigned int) CDTIME_T_TO_TIME_T (time));
460 if (message_len >= sizeof (message)) {
461 ERROR ("write_graphite plugin: message buffer too small: "
462 "Need %zu bytes.", message_len + 1);
463 return (-1);
464 }
466 pthread_mutex_lock (&cb->send_lock);
468 if (cb->sock_fd < 0)
469 {
470 status = wg_callback_init (cb);
471 if (status != 0)
472 {
473 /* An error message has already been printed. */
474 pthread_mutex_unlock (&cb->send_lock);
475 return (-1);
476 }
477 }
479 if (message_len >= cb->send_buf_free)
480 {
481 status = wg_flush_nolock (/* timeout = */ 0, cb);
482 if (status != 0)
483 {
484 pthread_mutex_unlock (&cb->send_lock);
485 return (status);
486 }
487 }
489 /* Assert that we have enough space for this message. */
490 assert (message_len < cb->send_buf_free);
492 /* `message_len + 1' because `message_len' does not include the
493 * trailing null byte. Neither does `send_buffer_fill'. */
494 memcpy (cb->send_buf + cb->send_buf_fill,
495 message, message_len + 1);
496 cb->send_buf_fill += message_len;
497 cb->send_buf_free -= message_len;
499 DEBUG ("write_graphite plugin: [%s]:%s buf %zu/%zu (%.1f %%) \"%s\"",
500 cb->node,
501 cb->service,
502 cb->send_buf_fill, sizeof (cb->send_buf),
503 100.0 * ((double) cb->send_buf_fill) / ((double) sizeof (cb->send_buf)),
504 message);
506 pthread_mutex_unlock (&cb->send_lock);
508 return (0);
509 }
511 static int wg_write_messages (const data_set_t *ds, const value_list_t *vl,
512 struct wg_callback *cb)
513 {
514 char key[10*DATA_MAX_NAME_LEN];
515 char values[512];
517 int status, i;
519 if (0 != strcmp (ds->type, vl->type))
520 {
521 ERROR ("write_graphite plugin: DS type does not match "
522 "value list type");
523 return -1;
524 }
526 for (i = 0; i < ds->ds_num; i++)
527 {
528 const char *ds_name = NULL;
530 if (cb->always_append_ds || (ds->ds_num > 1))
531 ds_name = ds->ds[i].name;
533 /* Copy the identifier to `key' and escape it. */
534 status = wg_format_name (key, sizeof (key), vl, cb, ds_name);
535 if (status != 0)
536 {
537 ERROR ("write_graphite plugin: error with format_name");
538 return (status);
539 }
541 escape_string (key, sizeof (key));
542 /* Convert the values to an ASCII representation and put that into
543 * `values'. */
544 status = wg_format_values (values, sizeof (values), i, ds, vl,
545 cb->store_rates);
546 if (status != 0)
547 {
548 ERROR ("write_graphite plugin: error with "
549 "wg_format_values");
550 return (status);
551 }
553 /* Send the message to graphite */
554 status = wg_send_message (key, values, vl->time, cb);
555 if (status != 0)
556 {
557 /* An error message has already been printed. */
558 return (status);
559 }
560 }
562 return (0);
563 }
565 static int wg_write (const data_set_t *ds, const value_list_t *vl,
566 user_data_t *user_data)
567 {
568 struct wg_callback *cb;
569 int status;
571 if (user_data == NULL)
572 return (EINVAL);
574 cb = user_data->data;
576 status = wg_write_messages (ds, vl, cb);
578 return (status);
579 }
581 static int config_set_char (char *dest,
582 oconfig_item_t *ci)
583 {
584 char buffer[4];
585 int status;
587 memset (buffer, 0, sizeof (buffer));
589 status = cf_util_get_string_buffer (ci, buffer, sizeof (buffer));
590 if (status != 0)
591 return (status);
593 if (buffer[0] == 0)
594 {
595 ERROR ("write_graphite plugin: Cannot use an empty string for the "
596 "\"EscapeCharacter\" option.");
597 return (-1);
598 }
600 if (buffer[1] != 0)
601 {
602 WARNING ("write_graphite plugin: Only the first character of the "
603 "\"EscapeCharacter\" option ('%c') will be used.",
604 (int) buffer[0]);
605 }
607 *dest = buffer[0];
609 return (0);
610 }
612 static int wg_config_carbon (oconfig_item_t *ci)
613 {
614 struct wg_callback *cb;
615 user_data_t user_data;
616 char callback_name[DATA_MAX_NAME_LEN];
617 int i;
619 cb = malloc (sizeof (*cb));
620 if (cb == NULL)
621 {
622 ERROR ("write_graphite plugin: malloc failed.");
623 return (-1);
624 }
625 memset (cb, 0, sizeof (*cb));
626 cb->sock_fd = -1;
627 cb->node = NULL;
628 cb->service = NULL;
629 cb->prefix = NULL;
630 cb->postfix = NULL;
631 cb->escape_char = WG_DEFAULT_ESCAPE;
632 cb->store_rates = 1;
634 pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
635 C_COMPLAIN_INIT (&cb->init_complaint);
637 for (i = 0; i < ci->children_num; i++)
638 {
639 oconfig_item_t *child = ci->children + i;
641 if (strcasecmp ("Host", child->key) == 0)
642 cf_util_get_string (child, &cb->node);
643 else if (strcasecmp ("Port", child->key) == 0)
644 cf_util_get_service (child, &cb->service);
645 else if (strcasecmp ("Prefix", child->key) == 0)
646 cf_util_get_string (child, &cb->prefix);
647 else if (strcasecmp ("Postfix", child->key) == 0)
648 cf_util_get_string (child, &cb->postfix);
649 else if (strcasecmp ("StoreRates", child->key) == 0)
650 cf_util_get_boolean (child, &cb->store_rates);
651 else if (strcasecmp ("SeparateInstances", child->key) == 0)
652 cf_util_get_boolean (child, &cb->separate_instances);
653 else if (strcasecmp ("AlwaysAppendDS", child->key) == 0)
654 cf_util_get_boolean (child, &cb->always_append_ds);
655 else if (strcasecmp ("EscapeCharacter", child->key) == 0)
656 config_set_char (&cb->escape_char, child);
657 else
658 {
659 ERROR ("write_graphite plugin: Invalid configuration "
660 "option: %s.", child->key);
661 }
662 }
664 ssnprintf (callback_name, sizeof (callback_name), "write_graphite/%s/%s",
665 cb->node != NULL ? cb->node : WG_DEFAULT_NODE,
666 cb->service != NULL ? cb->service : WG_DEFAULT_SERVICE);
668 memset (&user_data, 0, sizeof (user_data));
669 user_data.data = cb;
670 user_data.free_func = wg_callback_free;
671 plugin_register_write (callback_name, wg_write, &user_data);
673 user_data.free_func = NULL;
674 plugin_register_flush (callback_name, wg_flush, &user_data);
676 return (0);
677 }
679 static int wg_config (oconfig_item_t *ci)
680 {
681 int i;
683 for (i = 0; i < ci->children_num; i++)
684 {
685 oconfig_item_t *child = ci->children + i;
687 if (strcasecmp ("Carbon", child->key) == 0)
688 wg_config_carbon (child);
689 else
690 {
691 ERROR ("write_graphite plugin: Invalid configuration "
692 "option: %s.", child->key);
693 }
694 }
696 return (0);
697 }
699 void module_register (void)
700 {
701 plugin_register_complex_config ("write_graphite", wg_config);
702 }
704 /* vim: set sw=4 ts=4 sts=4 tw=78 et : */