Code

de460d7cfc0ba39e94ba4ae94fad4e45b25d34de
[collectd.git] / src / write_graphite.c
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-2012  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_parse_option.h"
51 /* Folks without pthread will need to disable this plugin. */
52 #include <pthread.h>
54 #include <sys/socket.h>
55 #include <netdb.h>
57 #ifndef WG_FORMAT_NAME
58 #define WG_FORMAT_NAME(ret, ret_len, vl, cb, ds_name) \
59         wg_format_name (ret, ret_len, (vl)->host, \
60                          (vl)->plugin, (vl)->plugin_instance, \
61                          (vl)->type, (vl)->type_instance, \
62                          (cb)->prefix, (cb)->postfix, \
63                          ds_name, (cb)->escape_char)
64 #endif
66 #ifndef WG_DEFAULT_NODE
67 # define WG_DEFAULT_NODE "localhost"
68 #endif
70 #ifndef WG_DEFAULT_SERVICE
71 # define WG_DEFAULT_SERVICE "2003"
72 #endif
74 #ifndef WG_SEND_BUF_SIZE
75 # define WG_SEND_BUF_SIZE 4096
76 #endif
78 /*
79  * Private variables
80  */
81 struct wg_callback
82 {
83     int      sock_fd;
85     char    *node;
86     char    *service;
87     char    *prefix;
88     char    *postfix;
89     char     escape_char;
91     char     send_buf[WG_SEND_BUF_SIZE];
92     size_t   send_buf_free;
93     size_t   send_buf_fill;
94     cdtime_t send_buf_init_time;
96     pthread_mutex_t send_lock;
97 };
100 /*
101  * Functions
102  */
103 static void wg_reset_buffer (struct wg_callback *cb)
105     memset (cb->send_buf, 0, sizeof (cb->send_buf));
106     cb->send_buf_free = sizeof (cb->send_buf);
107     cb->send_buf_fill = 0;
108     cb->send_buf_init_time = cdtime ();
111 static int wg_send_buffer (struct wg_callback *cb)
113     int status = 0;
115     status = write (cb->sock_fd, cb->send_buf, strlen (cb->send_buf));
116     if (status < 0)
117     {
118         ERROR ("write_graphite plugin: send failed with "
119                 "status %i (%s)",
120                 status,
121                 strerror (errno));
123         pthread_mutex_trylock (&cb->send_lock);
125         DEBUG ("write_graphite plugin: closing socket and restting fd "
126                 "so reinit will occur");
127         close (cb->sock_fd);
128         cb->sock_fd = -1;
130         pthread_mutex_unlock (&cb->send_lock);
132         return (-1);
133     }
134     return (0);
137 static int wg_flush_nolock (cdtime_t timeout, struct wg_callback *cb)
139     int status;
141     DEBUG ("write_graphite plugin: wg_flush_nolock: timeout = %.3f; "
142             "send_buf_fill = %zu;",
143             (double)timeout,
144             cb->send_buf_fill);
146     /* timeout == 0  => flush unconditionally */
147     if (timeout > 0)
148     {
149         cdtime_t now;
151         now = cdtime ();
152         if ((cb->send_buf_init_time + timeout) > now)
153             return (0);
154     }
156     if (cb->send_buf_fill <= 0)
157     {
158         cb->send_buf_init_time = cdtime ();
159         return (0);
160     }
162     status = wg_send_buffer (cb);
163     wg_reset_buffer (cb);
165     return (status);
168 static int wg_callback_init (struct wg_callback *cb)
170     struct addrinfo ai_hints;
171     struct addrinfo *ai_list;
172     struct addrinfo *ai_ptr;
173     int status;
175     const char *node = cb->node ? cb->node : WG_DEFAULT_NODE;
176     const char *service = cb->service ? cb->service : WG_DEFAULT_SERVICE;
178     if (cb->sock_fd > 0)
179         return (0);
181     memset (&ai_hints, 0, sizeof (ai_hints));
182 #ifdef AI_ADDRCONFIG
183     ai_hints.ai_flags |= AI_ADDRCONFIG;
184 #endif
185     ai_hints.ai_family = AF_UNSPEC;
186     ai_hints.ai_socktype = SOCK_STREAM;
188     ai_list = NULL;
190     status = getaddrinfo (node, service, &ai_hints, &ai_list);
191     if (status != 0)
192     {
193         ERROR ("write_graphite plugin: getaddrinfo (%s, %s) failed: %s",
194                 node, service, gai_strerror (status));
195         return (-1);
196     }
198     assert (ai_list != NULL);
199     for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
200     {
201         cb->sock_fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
202                 ai_ptr->ai_protocol);
203         if (cb->sock_fd < 0)
204             continue;
206         status = connect (cb->sock_fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
207         if (status != 0)
208         {
209             close (cb->sock_fd);
210             cb->sock_fd = -1;
211             continue;
212         }
214         break;
215     }
217     freeaddrinfo (ai_list);
219     if (cb->sock_fd < 0)
220     {
221         char errbuf[1024];
222         ERROR ("write_graphite plugin: Connecting to %s:%s failed. "
223                 "The last error was: %s", node, service,
224                 sstrerror (errno, errbuf, sizeof (errbuf)));
225         close (cb->sock_fd);
226         return (-1);
227     }
229     wg_reset_buffer (cb);
231     return (0);
234 static void wg_callback_free (void *data)
236     struct wg_callback *cb;
238     if (data == NULL)
239         return;
241     cb = data;
243     wg_flush_nolock (/* timeout = */ 0, cb);
245     close(cb->sock_fd);
246     sfree(cb->node);
247     sfree(cb->service);
248     sfree(cb->prefix);
249     sfree(cb->postfix);
251     sfree(cb);
254 static int wg_flush (cdtime_t timeout,
255         const char *identifier __attribute__((unused)),
256         user_data_t *user_data)
258     struct wg_callback *cb;
259     int status;
261     if (user_data == NULL)
262         return (-EINVAL);
264     cb = user_data->data;
266     pthread_mutex_lock (&cb->send_lock);
268     if (cb->sock_fd < 0)
269     {
270         status = wg_callback_init (cb);
271         if (status != 0)
272         {
273             ERROR ("write_graphite plugin: wg_callback_init failed.");
274             pthread_mutex_unlock (&cb->send_lock);
275             return (-1);
276         }
277     }
279     status = wg_flush_nolock (timeout, cb);
280     pthread_mutex_unlock (&cb->send_lock);
282     return (status);
285 static int wg_format_values (char *ret, size_t ret_len,
286         int ds_num, const data_set_t *ds, const value_list_t *vl,
287         _Bool store_rates)
289     size_t offset = 0;
290     int status;
291     gauge_t *rates = NULL;
293     assert (0 == strcmp (ds->type, vl->type));
295     memset (ret, 0, ret_len);
297 #define BUFFER_ADD(...) do { \
298     status = ssnprintf (ret + offset, ret_len - offset, \
299             __VA_ARGS__); \
300     if (status < 1) \
301     { \
302         sfree (rates); \
303         return (-1); \
304     } \
305     else if (((size_t) status) >= (ret_len - offset)) \
306     { \
307         sfree (rates); \
308         return (-1); \
309     } \
310     else \
311     offset += ((size_t) status); \
312 } while (0)
314     if (ds->ds[ds_num].type == DS_TYPE_GAUGE)
315         BUFFER_ADD ("%f", vl->values[ds_num].gauge);
316     else if (store_rates)
317     {
318         if (rates == NULL)
319             rates = uc_get_rate (ds, vl);
320         if (rates == NULL)
321         {
322             WARNING ("format_values: "
323                     "uc_get_rate failed.");
324             return (-1);
325         }
326         BUFFER_ADD ("%g", rates[ds_num]);
327     }
328     else if (ds->ds[ds_num].type == DS_TYPE_COUNTER)
329         BUFFER_ADD ("%llu", vl->values[ds_num].counter);
330     else if (ds->ds[ds_num].type == DS_TYPE_DERIVE)
331         BUFFER_ADD ("%"PRIi64, vl->values[ds_num].derive);
332     else if (ds->ds[ds_num].type == DS_TYPE_ABSOLUTE)
333         BUFFER_ADD ("%"PRIu64, vl->values[ds_num].absolute);
334     else
335     {
336         ERROR ("format_values plugin: Unknown data source type: %i",
337                 ds->ds[ds_num].type);
338         sfree (rates);
339         return (-1);
340     }
342 #undef BUFFER_ADD
344     sfree (rates);
345     return (0);
348 static void wg_copy_escape_part (char *dst, const char *src, size_t dst_len,
349     char escape_char)
351     size_t i;
353     memset (dst, 0, dst_len);
355     if (src == NULL)
356         return;
358     for (i = 0; i < dst_len; i++)
359     {
360         if ((src[i] == '.')
361                 || isspace ((int) src[i])
362                 || iscntrl ((int) src[i]))
363             dst[i] = escape_char;
364         else
365             dst[i] = src[i];
367         if (src[i] == 0)
368             break;
369     }
372 static int wg_format_name (char *ret, int ret_len,
373         const char *hostname,
374         const char *plugin, const char *plugin_instance,
375         const char *type, const char *type_instance,
376         const char *prefix, const char *postfix,
377         const char *ds_name, char escape_char)
379     char n_hostname[DATA_MAX_NAME_LEN];
380     char n_plugin[DATA_MAX_NAME_LEN];
381     char n_plugin_instance[DATA_MAX_NAME_LEN];
382     char n_type[DATA_MAX_NAME_LEN];
383     char n_type_instance[DATA_MAX_NAME_LEN];
384     int  status;
386     assert (hostname != NULL);
387     assert (plugin != NULL);
388     assert (type != NULL);
389     assert (ds_name != NULL);
391     if (prefix == NULL)
392         prefix = "";
394     if (postfix == NULL)
395         postfix = "";
397     wg_copy_escape_part (n_hostname, hostname,
398             sizeof (n_hostname), escape_char);
399     wg_copy_escape_part (n_plugin, plugin,
400             sizeof (n_plugin), escape_char);
401     wg_copy_escape_part (n_plugin_instance, plugin_instance,
402             sizeof (n_plugin_instance), escape_char);
403     wg_copy_escape_part (n_type, type,
404             sizeof (n_type), escape_char);
405     wg_copy_escape_part (n_type_instance, type_instance,
406             sizeof (n_type_instance), escape_char);
408     if (n_plugin_instance[0] == '\0')
409     {
410         if (n_type_instance[0] == '\0')
411         {
412             status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s",
413                     prefix, n_hostname, postfix, n_plugin, n_type, ds_name);
414         }
415         else
416         {
417             status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s-%s.%s",
418                     prefix, n_hostname, postfix, n_plugin, n_type,
419                     n_type_instance, ds_name);
420         }
421     }
422     else
423     {
424         if (n_type_instance[0] == '\0')
425         {
426             status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s.%s",
427                     prefix, n_hostname, postfix, n_plugin,
428                     n_plugin_instance, n_type, ds_name);
429         }
430         else
431         {
432             status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s-%s.%s",
433                     prefix, n_hostname, postfix, n_plugin,
434                     n_plugin_instance, n_type, n_type_instance, ds_name);
435         }
436     }
438     if ((status < 1) || (status >= ret_len))
439         return (-1);
441     return (0);
444 static int wg_send_message (const char* key, const char* value,
445         cdtime_t time, struct wg_callback *cb)
447     int status;
448     size_t message_len;
449     char message[1024];
451     message_len = (size_t) ssnprintf (message, sizeof (message),
452             "%s %s %.0f\n",
453             key,
454             value,
455             CDTIME_T_TO_DOUBLE(time));
456     if (message_len >= sizeof (message)) {
457         ERROR ("write_graphite plugin: message buffer too small: "
458                 "Need %zu bytes.", message_len + 1);
459         return (-1);
460     }
463     pthread_mutex_lock (&cb->send_lock);
465     if (cb->sock_fd < 0)
466     {
467         status = wg_callback_init (cb);
468         if (status != 0)
469         {
470             ERROR ("write_graphite plugin: wg_callback_init failed.");
471             pthread_mutex_unlock (&cb->send_lock);
472             return (-1);
473         }
474     }
476     if (message_len >= cb->send_buf_free)
477     {
478         status = wg_flush_nolock (/* timeout = */ 0, cb);
479         if (status != 0)
480         {
481             pthread_mutex_unlock (&cb->send_lock);
482             return (status);
483         }
484     }
485     assert (message_len < cb->send_buf_free);
487     /* `message_len + 1' because `message_len' does not include the
488      * trailing null byte. Neither does `send_buffer_fill'. */
489     memcpy (cb->send_buf + cb->send_buf_fill,
490             message, message_len + 1);
491     cb->send_buf_fill += message_len;
492     cb->send_buf_free -= message_len;
494     DEBUG ("write_graphite plugin: <%s:%s> buf %zu/%zu (%g%%) \"%s\"",
495             cb->node,
496             cb->service,
497             cb->send_buf_fill, sizeof (cb->send_buf),
498             100.0 * ((double) cb->send_buf_fill) / ((double) sizeof (cb->send_buf)),
499             message);
501     /* Check if we have enough space for this message. */
502     pthread_mutex_unlock (&cb->send_lock);
504     return (0);
507 static int wg_write_messages (const data_set_t *ds, const value_list_t *vl,
508         struct wg_callback *cb)
510     char key[10*DATA_MAX_NAME_LEN];
511     char values[512];
513     int status, i;
515     if (0 != strcmp (ds->type, vl->type))
516     {
517         ERROR ("write_graphite plugin: DS type does not match "
518                 "value list type");
519         return -1;
520     }
522     if (ds->ds_num > 1)
523     {
524         for (i = 0; i < ds->ds_num; i++)
525         {
526             /* Copy the identifier to `key' and escape it. */
527             status = WG_FORMAT_NAME (key, sizeof (key), vl, cb, ds->ds[i].name);
528             if (status != 0)
529             {
530                 ERROR ("write_graphite plugin: error with format_name");
531                 return (status);
532             }
534             escape_string (key, sizeof (key));
535             /* Convert the values to an ASCII representation and put that
536              * into `values'. */
537             status = wg_format_values (values, sizeof (values), i, ds, vl, 0);
538             if (status != 0)
539             {
540                 ERROR ("write_graphite plugin: error with "
541                         "wg_format_values");
542                 return (status);
543             }
545             /* Send the message to graphite */
546             status = wg_send_message (key, values, vl->time, cb);
547             if (status != 0)
548             {
549                 ERROR ("write_graphite plugin: error with "
550                         "wg_send_message");
551                 return (status);
552             }
553         }
554     }
555     else
556     {
557         /* Copy the identifier to `key' and escape it. */
558         status = WG_FORMAT_NAME (key, sizeof (key), vl, cb, NULL);
559         if (status != 0)
560         {
561             ERROR ("write_graphite plugin: error with format_name");
562             return (status);
563         }
565         escape_string (key, sizeof (key));
566         /* Convert the values to an ASCII representation and put that into
567          * `values'. */
568         status = wg_format_values (values, sizeof (values), 0, ds, vl, 0);
569         if (status != 0)
570         {
571             ERROR ("write_graphite plugin: error with "
572                     "wg_format_values");
573             return (status);
574         }
576         /* Send the message to graphite */
577         status = wg_send_message (key, values, vl->time, cb);
578         if (status != 0)
579         {
580             ERROR ("write_graphite plugin: error with "
581                     "wg_send_message");
582             return (status);
583         }
584     }
586     return (0);
589 static int wg_write (const data_set_t *ds, const value_list_t *vl,
590         user_data_t *user_data)
592     struct wg_callback *cb;
593     int status;
595     if (user_data == NULL)
596         return (-EINVAL);
598     cb = user_data->data;
600     status = wg_write_messages (ds, vl, cb);
602     return (status);
605 static int config_set_char (char *dest,
606         oconfig_item_t *ci)
608     if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
609     {
610         WARNING ("write_graphite plugin: The `%s' config option "
611                 "needs exactly one string argument.", ci->key);
612         return (-1);
613     }
615     *dest = ci->values[0].value.string[0];
617     return (0);
620 static int wg_config_carbon (oconfig_item_t *ci)
622     struct wg_callback *cb;
623     user_data_t user_data;
624     int i;
626     cb = malloc (sizeof (*cb));
627     if (cb == NULL)
628     {
629         ERROR ("write_graphite plugin: malloc failed.");
630         return (-1);
631     }
632     memset (cb, 0, sizeof (*cb));
633     cb->sock_fd = -1;
634     cb->node = NULL;
635     cb->service = NULL;
636     cb->prefix = NULL;
637     cb->postfix = NULL;
638     cb->escape_char = '_';
640     pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
642     for (i = 0; i < ci->children_num; i++)
643     {
644         oconfig_item_t *child = ci->children + i;
646         if (strcasecmp ("Host", child->key) == 0)
647             cf_util_get_string (child, &cb->node);
648         else if (strcasecmp ("Port", child->key) == 0)
649             cf_util_get_string (child, &cb->service);
650         else if (strcasecmp ("Prefix", child->key) == 0)
651             cf_util_get_string (child, &cb->prefix);
652         else if (strcasecmp ("Postfix", child->key) == 0)
653             cf_util_get_string (child, &cb->postfix);
654         else if (strcasecmp ("EscapeCharacter", child->key) == 0)
655             config_set_char (&cb->escape_char, child);
656         else
657         {
658             ERROR ("write_graphite plugin: Invalid configuration "
659                         "option: %s.", child->key);
660         }
661     }
663     DEBUG ("write_graphite: Registering write callback to carbon agent %s:%s",
664             cb->node ? cb->node : WG_DEFAULT_NODE,
665             cb->service ? cb->service : WG_DEFAULT_SERVICE);
667     memset (&user_data, 0, sizeof (user_data));
668     user_data.data = cb;
669     user_data.free_func = NULL;
670     plugin_register_flush ("write_graphite", wg_flush, &user_data);
672     user_data.free_func = wg_callback_free;
673     plugin_register_write ("write_graphite", wg_write, &user_data);
675     return (0);
678 static int wg_config (oconfig_item_t *ci)
680     int i;
682     for (i = 0; i < ci->children_num; i++)
683     {
684         oconfig_item_t *child = ci->children + i;
686         if (strcasecmp ("Carbon", child->key) == 0)
687             wg_config_carbon (child);
688         else
689         {
690             ERROR ("write_graphite plugin: Invalid configuration "
691                     "option: %s.", child->key);
692         }
693     }
695     return (0);
698 void module_register (void)
700     plugin_register_complex_config ("write_graphite", wg_config);
703 /* vim: set sw=4 ts=4 sts=4 tw=78 et : */