Code

write_graphite plugin: Decrese buffer size.
[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_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_DEFAULT_ESCAPE
66 # define WG_DEFAULT_ESCAPE '_'
67 #endif
69 /* Ethernet - (IPv6 + TCP) = 1500 - (40 + 32) = 1428 */
70 #ifndef WG_SEND_BUF_SIZE
71 # define WG_SEND_BUF_SIZE 1428
72 #endif
74 /*
75  * Private variables
76  */
77 struct wg_callback
78 {
79     int      sock_fd;
81     char    *node;
82     char    *service;
83     char    *prefix;
84     char    *postfix;
85     char     escape_char;
87     _Bool    store_rates;
88     _Bool    always_append_ds;
90     char     send_buf[WG_SEND_BUF_SIZE];
91     size_t   send_buf_free;
92     size_t   send_buf_fill;
93     cdtime_t send_buf_init_time;
95     pthread_mutex_t send_lock;
96 };
99 /*
100  * Functions
101  */
102 static void wg_reset_buffer (struct wg_callback *cb)
104     memset (cb->send_buf, 0, sizeof (cb->send_buf));
105     cb->send_buf_free = sizeof (cb->send_buf);
106     cb->send_buf_fill = 0;
107     cb->send_buf_init_time = cdtime ();
110 static int wg_send_buffer (struct wg_callback *cb)
112     int status = 0;
114     status = write (cb->sock_fd, cb->send_buf, strlen (cb->send_buf));
115     if (status < 0)
116     {
117         ERROR ("write_graphite plugin: send failed with "
118                 "status %i (%s)",
119                 status,
120                 strerror (errno));
122         close (cb->sock_fd);
123         cb->sock_fd = -1;
125         return (-1);
126     }
127     return (0);
130 /* NOTE: You must hold cb->send_lock when calling this function! */
131 static int wg_flush_nolock (cdtime_t timeout, struct wg_callback *cb)
133     int status;
135     DEBUG ("write_graphite plugin: wg_flush_nolock: timeout = %.3f; "
136             "send_buf_fill = %zu;",
137             (double)timeout,
138             cb->send_buf_fill);
140     /* timeout == 0  => flush unconditionally */
141     if (timeout > 0)
142     {
143         cdtime_t now;
145         now = cdtime ();
146         if ((cb->send_buf_init_time + timeout) > now)
147             return (0);
148     }
150     if (cb->send_buf_fill <= 0)
151     {
152         cb->send_buf_init_time = cdtime ();
153         return (0);
154     }
156     status = wg_send_buffer (cb);
157     wg_reset_buffer (cb);
159     return (status);
162 static int wg_callback_init (struct wg_callback *cb)
164     struct addrinfo ai_hints;
165     struct addrinfo *ai_list;
166     struct addrinfo *ai_ptr;
167     int status;
169     const char *node = cb->node ? cb->node : WG_DEFAULT_NODE;
170     const char *service = cb->service ? cb->service : WG_DEFAULT_SERVICE;
172     if (cb->sock_fd > 0)
173         return (0);
175     memset (&ai_hints, 0, sizeof (ai_hints));
176 #ifdef AI_ADDRCONFIG
177     ai_hints.ai_flags |= AI_ADDRCONFIG;
178 #endif
179     ai_hints.ai_family = AF_UNSPEC;
180     ai_hints.ai_socktype = SOCK_STREAM;
182     ai_list = NULL;
184     status = getaddrinfo (node, service, &ai_hints, &ai_list);
185     if (status != 0)
186     {
187         ERROR ("write_graphite plugin: getaddrinfo (%s, %s) failed: %s",
188                 node, service, gai_strerror (status));
189         return (-1);
190     }
192     assert (ai_list != NULL);
193     for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
194     {
195         cb->sock_fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
196                 ai_ptr->ai_protocol);
197         if (cb->sock_fd < 0)
198             continue;
200         status = connect (cb->sock_fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
201         if (status != 0)
202         {
203             close (cb->sock_fd);
204             cb->sock_fd = -1;
205             continue;
206         }
208         break;
209     }
211     freeaddrinfo (ai_list);
213     if (cb->sock_fd < 0)
214     {
215         char errbuf[1024];
216         ERROR ("write_graphite plugin: Connecting to %s:%s failed. "
217                 "The last error was: %s", node, service,
218                 sstrerror (errno, errbuf, sizeof (errbuf)));
219         close (cb->sock_fd);
220         return (-1);
221     }
223     wg_reset_buffer (cb);
225     return (0);
228 static void wg_callback_free (void *data)
230     struct wg_callback *cb;
232     if (data == NULL)
233         return;
235     cb = data;
237     pthread_mutex_lock (&cb->send_lock);
239     wg_flush_nolock (/* timeout = */ 0, cb);
241     close(cb->sock_fd);
242     cb->sock_fd = -1;
244     sfree(cb->node);
245     sfree(cb->service);
246     sfree(cb->prefix);
247     sfree(cb->postfix);
249     pthread_mutex_destroy (&cb->send_lock);
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] == 0)
361         {
362             dst[i] = 0;
363             break;
364         }
366         if ((src[i] == '.')
367                 || isspace ((int) src[i])
368                 || iscntrl ((int) src[i]))
369             dst[i] = escape_char;
370         else
371             dst[i] = src[i];
372     }
375 static int wg_format_name (char *ret, int ret_len,
376         const value_list_t *vl,
377         const struct wg_callback *cb,
378         const char *ds_name)
380     char n_host[DATA_MAX_NAME_LEN];
381     char n_plugin[DATA_MAX_NAME_LEN];
382     char n_plugin_instance[DATA_MAX_NAME_LEN];
383     char n_type[DATA_MAX_NAME_LEN];
384     char n_type_instance[DATA_MAX_NAME_LEN];
386     char *prefix;
387     char *postfix;
389     char tmp_plugin[2 * DATA_MAX_NAME_LEN + 1];
390     char tmp_type[2 * DATA_MAX_NAME_LEN + 1];
392     prefix = cb->prefix;
393     if (prefix == NULL)
394         prefix = "";
396     postfix = cb->postfix;
397     if (postfix == NULL)
398         postfix = "";
400     wg_copy_escape_part (n_host, vl->host,
401             sizeof (n_host), cb->escape_char);
402     wg_copy_escape_part (n_plugin, vl->plugin,
403             sizeof (n_plugin), cb->escape_char);
404     wg_copy_escape_part (n_plugin_instance, vl->plugin_instance,
405             sizeof (n_plugin_instance), cb->escape_char);
406     wg_copy_escape_part (n_type, vl->type,
407             sizeof (n_type), cb->escape_char);
408     wg_copy_escape_part (n_type_instance, vl->type_instance,
409             sizeof (n_type_instance), cb->escape_char);
411     if (n_plugin_instance[0] != '\0')
412         ssnprintf (tmp_plugin, sizeof (tmp_plugin), "%s-%s",
413             n_plugin, n_plugin_instance);
414     else
415         sstrncpy (tmp_plugin, n_plugin, sizeof (tmp_plugin));
417     if (n_type_instance[0] != '\0')
418         ssnprintf (tmp_type, sizeof (tmp_type), "%s-%s",
419             n_type, n_type_instance);
420     else
421         sstrncpy (tmp_type, n_type, sizeof (tmp_type));
423     if (ds_name != NULL)
424         ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s",
425             prefix, n_host, postfix, tmp_plugin, tmp_type, ds_name);
426     else
427         ssnprintf (ret, ret_len, "%s%s%s.%s.%s",
428             prefix, n_host, postfix, tmp_plugin, tmp_type);
430     return (0);
433 static int wg_send_message (const char* key, const char* value,
434         cdtime_t time, struct wg_callback *cb)
436     int status;
437     size_t message_len;
438     char message[1024];
440     message_len = (size_t) ssnprintf (message, sizeof (message),
441             "%s %s %.0f\n",
442             key,
443             value,
444             CDTIME_T_TO_DOUBLE(time));
445     if (message_len >= sizeof (message)) {
446         ERROR ("write_graphite plugin: message buffer too small: "
447                 "Need %zu bytes.", message_len + 1);
448         return (-1);
449     }
452     pthread_mutex_lock (&cb->send_lock);
454     if (cb->sock_fd < 0)
455     {
456         status = wg_callback_init (cb);
457         if (status != 0)
458         {
459             ERROR ("write_graphite plugin: wg_callback_init failed.");
460             pthread_mutex_unlock (&cb->send_lock);
461             return (-1);
462         }
463     }
465     if (message_len >= cb->send_buf_free)
466     {
467         status = wg_flush_nolock (/* timeout = */ 0, cb);
468         if (status != 0)
469         {
470             pthread_mutex_unlock (&cb->send_lock);
471             return (status);
472         }
473     }
474     assert (message_len < cb->send_buf_free);
476     /* `message_len + 1' because `message_len' does not include the
477      * trailing null byte. Neither does `send_buffer_fill'. */
478     memcpy (cb->send_buf + cb->send_buf_fill,
479             message, message_len + 1);
480     cb->send_buf_fill += message_len;
481     cb->send_buf_free -= message_len;
483     DEBUG ("write_graphite plugin: <%s:%s> buf %zu/%zu (%g%%) \"%s\"",
484             cb->node,
485             cb->service,
486             cb->send_buf_fill, sizeof (cb->send_buf),
487             100.0 * ((double) cb->send_buf_fill) / ((double) sizeof (cb->send_buf)),
488             message);
490     /* Check if we have enough space for this message. */
491     pthread_mutex_unlock (&cb->send_lock);
493     return (0);
496 static int wg_write_messages (const data_set_t *ds, const value_list_t *vl,
497         struct wg_callback *cb)
499     char key[10*DATA_MAX_NAME_LEN];
500     char values[512];
502     int status, i;
504     if (0 != strcmp (ds->type, vl->type))
505     {
506         ERROR ("write_graphite plugin: DS type does not match "
507                 "value list type");
508         return -1;
509     }
511     if (ds->ds_num > 1)
512     {
513         for (i = 0; i < ds->ds_num; i++)
514         {
515             /* Copy the identifier to `key' and escape it. */
516             status = wg_format_name (key, sizeof (key), vl, cb, ds->ds[i].name);
517             if (status != 0)
518             {
519                 ERROR ("write_graphite plugin: error with format_name");
520                 return (status);
521             }
523             escape_string (key, sizeof (key));
524             /* Convert the values to an ASCII representation and put that
525              * into `values'. */
526             status = wg_format_values (values, sizeof (values), i, ds, vl,
527                     cb->store_rates);
528             if (status != 0)
529             {
530                 ERROR ("write_graphite plugin: error with "
531                         "wg_format_values");
532                 return (status);
533             }
535             /* Send the message to graphite */
536             status = wg_send_message (key, values, vl->time, cb);
537             if (status != 0)
538             {
539                 ERROR ("write_graphite plugin: error with "
540                         "wg_send_message");
541                 return (status);
542             }
543         }
544     }
545     else
546     {
547         /* Copy the identifier to `key' and escape it. */
548         status = wg_format_name (key, sizeof (key), vl, cb,
549             cb->always_append_ds ? ds->ds[0].name : NULL);
550         if (status != 0)
551         {
552             ERROR ("write_graphite plugin: error with format_name");
553             return (status);
554         }
556         escape_string (key, sizeof (key));
557         /* Convert the values to an ASCII representation and put that into
558          * `values'. */
559         status = wg_format_values (values, sizeof (values), 0, ds, vl,
560                     cb->store_rates);
561         if (status != 0)
562         {
563             ERROR ("write_graphite plugin: error with "
564                     "wg_format_values");
565             return (status);
566         }
568         /* Send the message to graphite */
569         status = wg_send_message (key, values, vl->time, cb);
570         if (status != 0)
571         {
572             ERROR ("write_graphite plugin: error with "
573                     "wg_send_message");
574             return (status);
575         }
576     }
578     return (0);
581 static int wg_write (const data_set_t *ds, const value_list_t *vl,
582         user_data_t *user_data)
584     struct wg_callback *cb;
585     int status;
587     if (user_data == NULL)
588         return (EINVAL);
590     cb = user_data->data;
592     status = wg_write_messages (ds, vl, cb);
594     return (status);
597 static int config_set_char (char *dest,
598         oconfig_item_t *ci)
600     if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
601     {
602         WARNING ("write_graphite plugin: The `%s' config option "
603                 "needs exactly one string argument.", ci->key);
604         return (-1);
605     }
607     *dest = ci->values[0].value.string[0];
609     return (0);
612 static int wg_config_carbon (oconfig_item_t *ci)
614     struct wg_callback *cb;
615     user_data_t user_data;
616     int i;
618     cb = malloc (sizeof (*cb));
619     if (cb == NULL)
620     {
621         ERROR ("write_graphite plugin: malloc failed.");
622         return (-1);
623     }
624     memset (cb, 0, sizeof (*cb));
625     cb->sock_fd = -1;
626     cb->node = NULL;
627     cb->service = NULL;
628     cb->prefix = NULL;
629     cb->postfix = NULL;
630     cb->escape_char = WG_DEFAULT_ESCAPE;
632     pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
634     for (i = 0; i < ci->children_num; i++)
635     {
636         oconfig_item_t *child = ci->children + i;
638         if (strcasecmp ("Host", child->key) == 0)
639             cf_util_get_string (child, &cb->node);
640         else if (strcasecmp ("Port", child->key) == 0)
641             cf_util_get_service (child, &cb->service);
642         else if (strcasecmp ("Prefix", child->key) == 0)
643             cf_util_get_string (child, &cb->prefix);
644         else if (strcasecmp ("Postfix", child->key) == 0)
645             cf_util_get_string (child, &cb->postfix);
646         else if (strcasecmp ("StoreRates", child->key) == 0)
647             cf_util_get_boolean (child, &cb->store_rates);
648         else if (strcasecmp ("AlwaysAppendDS", child->key) == 0)
649             cf_util_get_boolean (child, &cb->always_append_ds);
650         else if (strcasecmp ("EscapeCharacter", child->key) == 0)
651             config_set_char (&cb->escape_char, child);
652         else
653         {
654             ERROR ("write_graphite plugin: Invalid configuration "
655                         "option: %s.", child->key);
656         }
657     }
659     DEBUG ("write_graphite: Registering write callback to carbon agent %s:%s",
660             cb->node ? cb->node : WG_DEFAULT_NODE,
661             cb->service ? cb->service : WG_DEFAULT_SERVICE);
663     memset (&user_data, 0, sizeof (user_data));
664     user_data.data = cb;
665     user_data.free_func = NULL;
666     plugin_register_flush ("write_graphite", wg_flush, &user_data);
668     user_data.free_func = wg_callback_free;
669     plugin_register_write ("write_graphite", wg_write, &user_data);
671     return (0);
674 static int wg_config (oconfig_item_t *ci)
676     int i;
678     for (i = 0; i < ci->children_num; i++)
679     {
680         oconfig_item_t *child = ci->children + i;
682         if (strcasecmp ("Carbon", child->key) == 0)
683             wg_config_carbon (child);
684         else
685         {
686             ERROR ("write_graphite plugin: Invalid configuration "
687                     "option: %s.", child->key);
688         }
689     }
691     return (0);
694 void module_register (void)
696     plugin_register_complex_config ("write_graphite", wg_config);
699 /* vim: set sw=4 ts=4 sts=4 tw=78 et : */