1 /**
2 * collectd - src/write_graphite.c
3 * Copyright (C) 2011 Scott Sanders
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 *
18 * Author:
19 * Scott Sanders <scott@jssjr.com>
20 *
21 * based on the excellent write_http plugin
22 **/
24 /* write_graphite plugin configuation example
25 *
26 * <Plugin write_graphite>
27 * <Carbon>
28 * Host "localhost"
29 * Port "2003"
30 * Prefix "collectd"
31 * </Carbon>
32 * </Plugin>
33 */
35 #include "collectd.h"
36 #include "common.h"
37 #include "plugin.h"
38 #include "configfile.h"
40 #include "utils_cache.h"
41 #include "utils_parse_option.h"
43 /* Folks without pthread will need to disable this plugin. */
44 #include <pthread.h>
46 #include <sys/socket.h>
47 #include <netdb.h>
49 #ifndef WG_FORMAT_NAME
50 #define WG_FORMAT_NAME(ret, ret_len, vl, cb, name) \
51 wg_format_name (ret, ret_len, (vl)->host, (vl)->plugin, \
52 (vl)->plugin_instance, (vl)->type, \
53 (vl)->type_instance, (cb)->prefix, (cb)->postfix, \
54 name, (cb)->dotchar)
55 #endif
57 #ifndef WG_DEFAULT_NODE
58 # define WG_DEFAULT_NODE "localhost"
59 #endif
61 #ifndef WG_DEFAULT_SERVICE
62 # define WG_DEFAULT_SERVICE "2003"
63 #endif
65 #ifndef WG_SEND_BUF_SIZE
66 # define WG_SEND_BUF_SIZE 4096
67 #endif
69 /*
70 * Private variables
71 */
72 struct wg_callback
73 {
74 int sock_fd;
75 struct hostent *server;
77 char *node;
78 char *service;
79 char *prefix;
80 char *postfix;
81 char dotchar;
83 char send_buf[WG_SEND_BUF_SIZE];
84 size_t send_buf_free;
85 size_t send_buf_fill;
86 cdtime_t send_buf_init_time;
88 pthread_mutex_t send_lock;
89 };
92 /*
93 * Functions
94 */
95 static void wg_reset_buffer (struct wg_callback *cb)
96 {
97 memset (cb->send_buf, 0, sizeof (cb->send_buf));
98 cb->send_buf_free = sizeof (cb->send_buf);
99 cb->send_buf_fill = 0;
100 cb->send_buf_init_time = cdtime ();
101 }
103 static int wg_send_buffer (struct wg_callback *cb)
104 {
105 int status = 0;
107 status = write (cb->sock_fd, cb->send_buf, strlen (cb->send_buf));
108 if (status < 0)
109 {
110 ERROR ("write_graphite plugin: send failed with "
111 "status %i (%s)",
112 status,
113 strerror (errno));
115 pthread_mutex_trylock (&cb->send_lock);
117 DEBUG ("write_graphite plugin: closing socket and restting fd "
118 "so reinit will occur");
119 close (cb->sock_fd);
120 cb->sock_fd = -1;
122 pthread_mutex_unlock (&cb->send_lock);
124 return (-1);
125 }
126 return (0);
127 }
129 static int wg_flush_nolock (cdtime_t timeout, struct wg_callback *cb)
130 {
131 int status;
133 DEBUG ("write_graphite plugin: wg_flush_nolock: timeout = %.3f; "
134 "send_buf_fill = %zu;",
135 (double)timeout,
136 cb->send_buf_fill);
138 /* timeout == 0 => flush unconditionally */
139 if (timeout > 0)
140 {
141 cdtime_t now;
143 now = cdtime ();
144 if ((cb->send_buf_init_time + timeout) > now)
145 return (0);
146 }
148 if (cb->send_buf_fill <= 0)
149 {
150 cb->send_buf_init_time = cdtime ();
151 return (0);
152 }
154 status = wg_send_buffer (cb);
155 wg_reset_buffer (cb);
157 return (status);
158 }
160 static int wg_callback_init (struct wg_callback *cb)
161 {
162 struct addrinfo ai_hints;
163 struct addrinfo *ai_list;
164 struct addrinfo *ai_ptr;
165 int status;
167 const char *node = cb->node ? cb->node : WG_DEFAULT_NODE;
168 const char *service = cb->service ? cb->service : WG_DEFAULT_SERVICE;
170 if (cb->sock_fd > 0)
171 return (0);
173 memset (&ai_hints, 0, sizeof (ai_hints));
174 #ifdef AI_ADDRCONFIG
175 ai_hints.ai_flags |= AI_ADDRCONFIG;
176 #endif
177 ai_hints.ai_family = AF_UNSPEC;
178 ai_hints.ai_socktype = SOCK_STREAM;
180 ai_list = NULL;
182 status = getaddrinfo (node, service, &ai_hints, &ai_list);
183 if (status != 0)
184 {
185 ERROR ("write_graphite plugin: getaddrinfo (%s, %s) failed: %s",
186 node, service, gai_strerror (status));
187 return (-1);
188 }
190 assert (ai_list != NULL);
191 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
192 {
193 cb->sock_fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
194 ai_ptr->ai_protocol);
195 if (cb->sock_fd < 0)
196 continue;
198 status = connect (cb->sock_fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
199 if (status != 0)
200 {
201 close (cb->sock_fd);
202 cb->sock_fd = -1;
203 continue;
204 }
206 break;
207 }
209 freeaddrinfo (ai_list);
211 if (cb->sock_fd < 0)
212 {
213 char errbuf[1024];
214 ERROR ("write_graphite plugin: Connecting to %s:%s failed. "
215 "The last error was: %s", node, service,
216 sstrerror (errno, errbuf, sizeof (errbuf)));
217 close (cb->sock_fd);
218 return (-1);
219 }
221 wg_reset_buffer (cb);
223 return (0);
224 }
226 static void wg_callback_free (void *data)
227 {
228 struct wg_callback *cb;
230 if (data == NULL)
231 return;
233 cb = data;
235 wg_flush_nolock (/* timeout = */ 0, cb);
237 close(cb->sock_fd);
238 sfree(cb->node);
239 sfree(cb->service);
240 sfree(cb->prefix);
241 sfree(cb->postfix);
243 sfree(cb);
244 }
246 static int wg_flush (cdtime_t timeout,
247 const char *identifier __attribute__((unused)),
248 user_data_t *user_data)
249 {
250 struct wg_callback *cb;
251 int status;
253 if (user_data == NULL)
254 return (-EINVAL);
256 cb = user_data->data;
258 pthread_mutex_lock (&cb->send_lock);
260 if (cb->sock_fd < 0)
261 {
262 status = wg_callback_init (cb);
263 if (status != 0)
264 {
265 ERROR ("write_graphite plugin: wg_callback_init failed.");
266 pthread_mutex_unlock (&cb->send_lock);
267 return (-1);
268 }
269 }
271 status = wg_flush_nolock (timeout, cb);
272 pthread_mutex_unlock (&cb->send_lock);
274 return (status);
275 }
277 static int wg_format_values (char *ret, size_t ret_len,
278 int ds_num, const data_set_t *ds, const value_list_t *vl,
279 _Bool store_rates)
280 {
281 size_t offset = 0;
282 int status;
283 gauge_t *rates = NULL;
285 assert (0 == strcmp (ds->type, vl->type));
287 memset (ret, 0, ret_len);
289 #define BUFFER_ADD(...) do { \
290 status = ssnprintf (ret + offset, ret_len - offset, \
291 __VA_ARGS__); \
292 if (status < 1) \
293 { \
294 sfree (rates); \
295 return (-1); \
296 } \
297 else if (((size_t) status) >= (ret_len - offset)) \
298 { \
299 sfree (rates); \
300 return (-1); \
301 } \
302 else \
303 offset += ((size_t) status); \
304 } while (0)
306 if (ds->ds[ds_num].type == DS_TYPE_GAUGE)
307 BUFFER_ADD ("%f", vl->values[ds_num].gauge);
308 else if (store_rates)
309 {
310 if (rates == NULL)
311 rates = uc_get_rate (ds, vl);
312 if (rates == NULL)
313 {
314 WARNING ("format_values: "
315 "uc_get_rate failed.");
316 return (-1);
317 }
318 BUFFER_ADD ("%g", rates[ds_num]);
319 }
320 else if (ds->ds[ds_num].type == DS_TYPE_COUNTER)
321 BUFFER_ADD ("%llu", vl->values[ds_num].counter);
322 else if (ds->ds[ds_num].type == DS_TYPE_DERIVE)
323 BUFFER_ADD ("%"PRIi64, vl->values[ds_num].derive);
324 else if (ds->ds[ds_num].type == DS_TYPE_ABSOLUTE)
325 BUFFER_ADD ("%"PRIu64, vl->values[ds_num].absolute);
326 else
327 {
328 ERROR ("format_values plugin: Unknown data source type: %i",
329 ds->ds[ds_num].type);
330 sfree (rates);
331 return (-1);
332 }
334 #undef BUFFER_ADD
336 sfree (rates);
337 return (0);
338 }
340 static int swap_chars (char *dst, const char *src,
341 const char from, const char to)
342 {
343 size_t i;
345 int reps = 0;
347 for (i = 0; i < strlen(src) ; i++)
348 {
349 if (src[i] == from)
350 {
351 dst[i] = to;
352 ++reps;
353 }
354 else
355 dst[i] = src[i];
356 }
357 dst[i] = '\0';
359 return reps;
360 }
362 static int wg_format_name (char *ret, int ret_len,
363 const char *hostname,
364 const char *plugin, const char *plugin_instance,
365 const char *type, const char *type_instance,
366 const char *prefix, const char *postfix,
367 const char *ds_name, const char dotchar)
368 {
369 int status;
370 char *n_hostname = 0;
371 char *n_type_instance = 0;
373 assert (plugin != NULL);
374 assert (type != NULL);
376 if (prefix == NULL)
377 prefix = "";
379 if (postfix == NULL)
380 postfix = "";
382 if ((n_hostname = malloc(strlen(hostname)+1)) == NULL)
383 {
384 ERROR ("Unable to allocate memory for normalized hostname buffer");
385 return (-1);
386 }
388 if (swap_chars(n_hostname, hostname, '.', dotchar) == -1)
389 {
390 ERROR ("Unable to normalize hostname");
391 return (-1);
392 }
394 if (type_instance && type_instance[0] != '\0') {
395 if ((n_type_instance = malloc(strlen(type_instance)+1)) == NULL)
396 {
397 ERROR ("Unable to allocate memory for normalized datasource name buffer");
398 return (-1);
399 }
400 if (swap_chars(n_type_instance, type_instance, '.', dotchar) == -1)
401 {
402 ERROR ("Unable to normalize datasource name");
403 return (-1);
404 }
405 }
407 if ((plugin_instance == NULL) || (plugin_instance[0] == '\0'))
408 {
409 if ((n_type_instance == NULL) || (n_type_instance[0] == '\0'))
410 {
411 if ((ds_name == NULL) || (ds_name[0] == '\0'))
412 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s",
413 prefix, n_hostname, postfix, plugin, type);
414 else
415 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s",
416 prefix, n_hostname, postfix, plugin, type, ds_name);
417 }
418 else
419 {
420 if ((ds_name == NULL) || (ds_name[0] == '\0'))
421 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s-%s",
422 prefix, n_hostname, postfix, plugin, type,
423 n_type_instance);
424 else
425 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s-%s.%s",
426 prefix, n_hostname, postfix, plugin, type,
427 n_type_instance, ds_name);
428 }
429 }
430 else
431 {
432 if ((n_type_instance == NULL) || (n_type_instance[0] == '\0'))
433 {
434 if ((ds_name == NULL) || (ds_name[0] == '\0'))
435 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s",
436 prefix, n_hostname, postfix, plugin,
437 plugin_instance, type);
438 else
439 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s.%s",
440 prefix, n_hostname, postfix, plugin,
441 plugin_instance, type, ds_name);
442 }
443 else
444 {
445 if ((ds_name == NULL) || (ds_name[0] == '\0'))
446 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s-%s",
447 prefix, n_hostname, postfix, plugin,
448 plugin_instance, type, n_type_instance);
449 else
450 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s-%s.%s",
451 prefix, n_hostname, postfix, plugin,
452 plugin_instance, type, n_type_instance, ds_name);
453 }
454 }
456 sfree(n_hostname);
457 sfree(n_type_instance);
459 if ((status < 1) || (status >= ret_len))
460 return (-1);
461 return (0);
462 }
464 static int wg_send_message (const char* key, const char* value,
465 cdtime_t time, struct wg_callback *cb)
466 {
467 int status;
468 size_t message_len;
469 char message[1024];
471 message_len = (size_t) ssnprintf (message, sizeof (message),
472 "%s %s %.0f\n",
473 key,
474 value,
475 CDTIME_T_TO_DOUBLE(time));
476 if (message_len >= sizeof (message)) {
477 ERROR ("write_graphite plugin: message buffer too small: "
478 "Need %zu bytes.", message_len + 1);
479 return (-1);
480 }
483 pthread_mutex_lock (&cb->send_lock);
485 if (cb->sock_fd < 0)
486 {
487 status = wg_callback_init (cb);
488 if (status != 0)
489 {
490 ERROR ("write_graphite plugin: wg_callback_init failed.");
491 pthread_mutex_unlock (&cb->send_lock);
492 return (-1);
493 }
494 }
496 if (message_len >= cb->send_buf_free)
497 {
498 status = wg_flush_nolock (/* timeout = */ 0, cb);
499 if (status != 0)
500 {
501 pthread_mutex_unlock (&cb->send_lock);
502 return (status);
503 }
504 }
505 assert (message_len < cb->send_buf_free);
507 /* `message_len + 1' because `message_len' does not include the
508 * trailing null byte. Neither does `send_buffer_fill'. */
509 memcpy (cb->send_buf + cb->send_buf_fill,
510 message, message_len + 1);
511 cb->send_buf_fill += message_len;
512 cb->send_buf_free -= message_len;
514 DEBUG ("write_graphite plugin: <%s:%s> buf %zu/%zu (%g%%) \"%s\"",
515 cb->node,
516 cb->service,
517 cb->send_buf_fill, sizeof (cb->send_buf),
518 100.0 * ((double) cb->send_buf_fill) / ((double) sizeof (cb->send_buf)),
519 message);
521 /* Check if we have enough space for this message. */
522 pthread_mutex_unlock (&cb->send_lock);
524 return (0);
525 }
527 static int wg_write_messages (const data_set_t *ds, const value_list_t *vl,
528 struct wg_callback *cb)
529 {
530 char key[10*DATA_MAX_NAME_LEN];
531 char values[512];
533 int status, i;
535 if (0 != strcmp (ds->type, vl->type))
536 {
537 ERROR ("write_graphite plugin: DS type does not match "
538 "value list type");
539 return -1;
540 }
542 if (ds->ds_num > 1)
543 {
544 for (i = 0; i < ds->ds_num; i++)
545 {
546 /* Copy the identifier to `key' and escape it. */
547 status = WG_FORMAT_NAME (key, sizeof (key), vl, cb, ds->ds[i].name);
548 if (status != 0)
549 {
550 ERROR ("write_graphite plugin: error with format_name");
551 return (status);
552 }
554 escape_string (key, sizeof (key));
555 /* Convert the values to an ASCII representation and put that
556 * into `values'. */
557 status = wg_format_values (values, sizeof (values), i, ds, vl, 0);
558 if (status != 0)
559 {
560 ERROR ("write_graphite plugin: error with "
561 "wg_format_values");
562 return (status);
563 }
565 /* Send the message to graphite */
566 status = wg_send_message (key, values, vl->time, cb);
567 if (status != 0)
568 {
569 ERROR ("write_graphite plugin: error with "
570 "wg_send_message");
571 return (status);
572 }
573 }
574 }
575 else
576 {
577 /* Copy the identifier to `key' and escape it. */
578 status = WG_FORMAT_NAME (key, sizeof (key), vl, cb, NULL);
579 if (status != 0)
580 {
581 ERROR ("write_graphite plugin: error with format_name");
582 return (status);
583 }
585 escape_string (key, sizeof (key));
586 /* Convert the values to an ASCII representation and put that into
587 * `values'. */
588 status = wg_format_values (values, sizeof (values), 0, ds, vl, 0);
589 if (status != 0)
590 {
591 ERROR ("write_graphite plugin: error with "
592 "wg_format_values");
593 return (status);
594 }
596 /* Send the message to graphite */
597 status = wg_send_message (key, values, vl->time, cb);
598 if (status != 0)
599 {
600 ERROR ("write_graphite plugin: error with "
601 "wg_send_message");
602 return (status);
603 }
604 }
606 return (0);
607 }
609 static int wg_write (const data_set_t *ds, const value_list_t *vl,
610 user_data_t *user_data)
611 {
612 struct wg_callback *cb;
613 int status;
615 if (user_data == NULL)
616 return (-EINVAL);
618 cb = user_data->data;
620 status = wg_write_messages (ds, vl, cb);
622 return (status);
623 }
625 static int config_set_char (char *dest,
626 oconfig_item_t *ci)
627 {
628 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
629 {
630 WARNING ("write_graphite plugin: The `%s' config option "
631 "needs exactly one string argument.", ci->key);
632 return (-1);
633 }
635 *dest = ci->values[0].value.string[0];
637 return (0);
638 }
640 static int wg_config_carbon (oconfig_item_t *ci)
641 {
642 struct wg_callback *cb;
643 user_data_t user_data;
644 int i;
646 cb = malloc (sizeof (*cb));
647 if (cb == NULL)
648 {
649 ERROR ("write_graphite plugin: malloc failed.");
650 return (-1);
651 }
652 memset (cb, 0, sizeof (*cb));
653 cb->sock_fd = -1;
654 cb->node = NULL;
655 cb->service = NULL;
656 cb->prefix = NULL;
657 cb->postfix = NULL;
658 cb->server = NULL;
659 cb->dotchar = '_';
661 pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
663 for (i = 0; i < ci->children_num; i++)
664 {
665 oconfig_item_t *child = ci->children + i;
667 if (strcasecmp ("Host", child->key) == 0)
668 cf_util_get_string (child, &cb->node);
669 else if (strcasecmp ("Port", child->key) == 0)
670 cf_util_get_string (child, &cb->service);
671 else if (strcasecmp ("Prefix", child->key) == 0)
672 cf_util_get_string (child, &cb->prefix);
673 else if (strcasecmp ("Postfix", child->key) == 0)
674 cf_util_get_string (child, &cb->postfix);
675 else if (strcasecmp ("DotCharacter", child->key) == 0)
676 config_set_char (&cb->dotchar, child);
677 else
678 {
679 ERROR ("write_graphite plugin: Invalid configuration "
680 "option: %s.", child->key);
681 }
682 }
684 DEBUG ("write_graphite: Registering write callback to carbon agent %s:%s",
685 cb->node ? cb->node : WG_DEFAULT_NODE,
686 cb->service ? cb->service : WG_DEFAULT_SERVICE);
688 memset (&user_data, 0, sizeof (user_data));
689 user_data.data = cb;
690 user_data.free_func = NULL;
691 plugin_register_flush ("write_graphite", wg_flush, &user_data);
693 user_data.free_func = wg_callback_free;
694 plugin_register_write ("write_graphite", wg_write, &user_data);
696 return (0);
697 }
699 static int wg_config (oconfig_item_t *ci)
700 {
701 int i;
703 for (i = 0; i < ci->children_num; i++)
704 {
705 oconfig_item_t *child = ci->children + i;
707 if (strcasecmp ("Carbon", child->key) == 0)
708 wg_config_carbon (child);
709 else
710 {
711 ERROR ("write_graphite plugin: Invalid configuration "
712 "option: %s.", child->key);
713 }
714 }
716 return (0);
717 }
719 void module_register (void)
720 {
721 plugin_register_complex_config ("write_graphite", wg_config);
722 }
724 /* vim: set sw=4 ts=4 sts=4 tw=78 et : */