Code

Modify whitepsace
[collectd.git] / src / write_graphite.c
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 "local-agent">
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 <sys/stat.h>
48 #include <sys/types.h>
50 #include <netinet/in.h>
51 #include <netdb.h>
53 #ifndef WG_FORMAT_NAME
54 #define WG_FORMAT_NAME(ret, ret_len, vl, prefix, name) \
55         wg_format_name (ret, ret_len, (vl)->host, (vl)->plugin, \
56                          (vl)->plugin_instance, (vl)->type, \
57                          (vl)->type_instance, prefix, name)
58 #endif
60 #ifndef WG_SEND_BUF_SIZE
61 #define WG_SEND_BUF_SIZE 4096
62 #endif
64 /*
65  * Private variables
66  */
67 struct wg_callback
68 {
69     char    *name;
71     int      sock_fd;
72     struct hostent *server;
74     char    *host;
75     int      port;
76     char    *prefix;
78     char     send_buf[WG_SEND_BUF_SIZE];
79     size_t   send_buf_free;
80     size_t   send_buf_fill;
81     cdtime_t send_buf_init_time;
83     pthread_mutex_t send_lock;
84 };
87 /*
88  * Functions
89  */
90 static void wg_reset_buffer (struct wg_callback *cb)
91 {
92     memset (cb->send_buf, 0, sizeof (cb->send_buf));
93     cb->send_buf_free = sizeof (cb->send_buf);
94     cb->send_buf_fill = 0;
95     cb->send_buf_init_time = cdtime ();
96 }
98 static int wg_send_buffer (struct wg_callback *cb)
99 {
100     int status = 0;
102     status = write (cb->sock_fd, cb->send_buf, strlen (cb->send_buf));
103     if (status < 0)
104     {
105         ERROR ("write_graphite plugin: send failed with "
106                 "status %i (%s)",
107                 status,
108                 strerror (errno));
110         pthread_mutex_lock (&cb->send_lock);
112         DEBUG ("write_graphite plugin: closing socket and restting fd "
113                 "so reinit will occur");
114         close (cb->sock_fd);
115         cb->sock_fd = -1;
117         pthread_mutex_unlock (&cb->send_lock);
119         return (-1);
120     }
121     return (0);
124 static int wg_flush_nolock (cdtime_t timeout, struct wg_callback *cb)
126     int status;
128     DEBUG ("write_graphite plugin: wg_flush_nolock: timeout = %.3f; "
129             "send_buf_fill = %zu;",
130             (double)timeout,
131             cb->send_buf_fill);
133     /* timeout == 0  => flush unconditionally */
134     if (timeout > 0)
135     {
136         cdtime_t now;
138         now = cdtime ();
139         if ((cb->send_buf_init_time + timeout) > now)
140             return (0);
141     }
143     if (cb->send_buf_fill <= 0)
144     {
145         cb->send_buf_init_time = cdtime ();
146         return (0);
147     }
149     status = wg_send_buffer (cb);
150     wg_reset_buffer (cb);
152     return (status);
155 static int wg_callback_init (struct wg_callback *cb)
157     int status;
159     struct sockaddr_in serv_addr;
161     if (cb->sock_fd > 0)
162         return (0);
164     cb->sock_fd = socket (AF_INET, SOCK_STREAM, 0);
165     if (cb->sock_fd < 0)
166     {
167         ERROR ("write_graphite plugin: socket failed: %s", strerror (errno));
168         return (-1);
169     }
170     cb->server = gethostbyname(cb->host);
171     if (cb->server == NULL)
172     {
173         ERROR ("write_graphite plugin: no such host");
174         return (-1);
175     }
176     memset (&serv_addr, 0, sizeof (serv_addr));
177     serv_addr.sin_family = AF_INET;
178     memcpy (&serv_addr.sin_addr.s_addr,
179              cb->server->h_addr,
180              cb->server->h_length);
181     serv_addr.sin_port = htons(cb->port);
183     status = connect(cb->sock_fd,
184                       (struct sockaddr *) &serv_addr,
185                       sizeof(serv_addr));
186     if (status < 0)
187     {
188         char errbuf[1024];
189         sstrerror (errno, errbuf, sizeof (errbuf));
190         ERROR ("write_graphite plugin: connect failed: %s", errbuf);
191         close (cb->sock_fd);
192         cb->sock_fd = -1;
193         return (-1);
194     }
196     wg_reset_buffer (cb);
198     return (0);
201 static void wg_callback_free (void *data)
203     struct wg_callback *cb;
205     if (data == NULL)
206         return;
208     cb = data;
210     wg_flush_nolock (/* timeout = */ 0, cb);
212     close(cb->sock_fd);
213     sfree(cb->name);
214     sfree(cb->host);
215     sfree(cb->prefix);
217     sfree(cb);
220 static int wg_flush (cdtime_t timeout,
221         const char *identifier __attribute__((unused)),
222         user_data_t *user_data)
224     struct wg_callback *cb;
225     int status;
227     if (user_data == NULL)
228         return (-EINVAL);
230     cb = user_data->data;
232     pthread_mutex_lock (&cb->send_lock);
234     if (cb->sock_fd < 0)
235     {
236         status = wg_callback_init (cb);
237         if (status != 0)
238         {
239             ERROR ("write_graphite plugin: wg_callback_init failed.");
240             pthread_mutex_unlock (&cb->send_lock);
241             return (-1);
242         }
243     }
245     status = wg_flush_nolock (timeout, cb);
246     pthread_mutex_unlock (&cb->send_lock);
248     return (status);
251 static int wg_format_values (char *ret, size_t ret_len,
252         int ds_num, const data_set_t *ds, const value_list_t *vl,
253         _Bool store_rates)
255     size_t offset = 0;
256     int status;
257     gauge_t *rates = NULL;
259     assert (0 == strcmp (ds->type, vl->type));
261     memset (ret, 0, ret_len);
263 #define BUFFER_ADD(...) do { \
264     status = ssnprintf (ret + offset, ret_len - offset, \
265             __VA_ARGS__); \
266     if (status < 1) \
267     { \
268         sfree (rates); \
269         return (-1); \
270     } \
271     else if (((size_t) status) >= (ret_len - offset)) \
272     { \
273         sfree (rates); \
274         return (-1); \
275     } \
276     else \
277     offset += ((size_t) status); \
278 } while (0)
280     if (ds->ds[ds_num].type == DS_TYPE_GAUGE)
281         BUFFER_ADD ("%f", vl->values[ds_num].gauge);
282     else if (store_rates)
283     {
284         if (rates == NULL)
285             rates = uc_get_rate (ds, vl);
286         if (rates == NULL)
287         {
288             WARNING ("format_values: "
289                     "uc_get_rate failed.");
290             return (-1);
291         }
292         BUFFER_ADD ("%g", rates[ds_num]);
293     }
294     else if (ds->ds[ds_num].type == DS_TYPE_COUNTER)
295         BUFFER_ADD ("%llu", vl->values[ds_num].counter);
296     else if (ds->ds[ds_num].type == DS_TYPE_DERIVE)
297         BUFFER_ADD ("%"PRIi64, vl->values[ds_num].derive);
298     else if (ds->ds[ds_num].type == DS_TYPE_ABSOLUTE)
299         BUFFER_ADD ("%"PRIu64, vl->values[ds_num].absolute);
300     else
301     {
302         ERROR ("format_values plugin: Unknown data source type: %i",
303                 ds->ds[ds_num].type);
304         sfree (rates);
305         return (-1);
306     }
308 #undef BUFFER_ADD
310     sfree (rates);
311     return (0);
314 static int normalize_hostname (char *dst, const char *src)
316     size_t i;
318     int reps = 0;
320     for (i = 0; i < strlen(src) ; i++)
321     {
322         if (src[i] == '.')
323         {
324             dst[i] = '_';
325             ++reps;
326         }
327         else
328             dst[i] = src[i];
329     }
330     dst[i] = '\0';
332     return reps;
335 static int wg_format_name (char *ret, int ret_len,
336         const char *hostname,
337         const char *plugin, const char *plugin_instance,
338         const char *type, const char *type_instance,
339         const char *prefix, const char *ds_name)
341     int  status;
342     char *n_hostname;
344     assert (plugin != NULL);
345     assert (type != NULL);
347     if ((n_hostname = malloc(strlen(hostname)+1)) == NULL)
348     {
349         ERROR ("Unable to allocate memory for normalized hostname buffer");
350         return (-1);
351     }
353     if (normalize_hostname(n_hostname, hostname) == -1)
354     {
355         ERROR ("Unable to normalize hostname");
356         return (-1);
357     }
359     if ((plugin_instance == NULL) || (plugin_instance[0] == '\0'))
360     {
361         if ((type_instance == NULL) || (type_instance[0] == '\0'))
362         {
363             if ((ds_name == NULL) || (ds_name[0] == '\0'))
364                 status = ssnprintf (ret, ret_len, "%s.%s.%s.%s",
365                         prefix, n_hostname, plugin, type);
366             else
367                 status = ssnprintf (ret, ret_len, "%s.%s.%s.%s.%s",
368                         prefix, n_hostname, plugin, type, ds_name);
369         }
370         else
371         {
372             if ((ds_name == NULL) || (ds_name[0] == '\0'))
373                 status = ssnprintf (ret, ret_len, "%s.%s.%s.%s-%s",
374                         prefix, n_hostname, plugin, type,
375                         type_instance);
376             else
377                 status = ssnprintf (ret, ret_len, "%s.%s.%s.%s-%s.%s",
378                         prefix, n_hostname, plugin, type,
379                         type_instance, ds_name);
380         }
381     }
382     else
383     {
384         if ((type_instance == NULL) || (type_instance[0] == '\0'))
385         {
386             if ((ds_name == NULL) || (ds_name[0] == '\0'))
387                 status = ssnprintf (ret, ret_len, "%s.%s.%s.%s.%s",
388                         prefix, n_hostname, plugin,
389                         plugin_instance, type);
390             else
391                 status = ssnprintf (ret, ret_len, "%s.%s.%s.%s.%s.%s",
392                         prefix, n_hostname, plugin,
393                         plugin_instance, type, ds_name);
394         }
395         else
396         {
397             if ((ds_name == NULL) || (ds_name[0] == '\0'))
398                 status = ssnprintf (ret, ret_len, "%s.%s.%s.%s.%s-%s",
399                         prefix, n_hostname, plugin,
400                         plugin_instance, type, type_instance);
401             else
402                 status = ssnprintf (ret, ret_len, "%s.%s.%s.%s.%s-%s.%s",
403                         prefix, n_hostname, plugin,
404                         plugin_instance, type, type_instance, ds_name);
405         }
406     }
408     sfree(n_hostname);
410     if ((status < 1) || (status >= ret_len))
411         return (-1);
412     return (0);
415 static int wg_send_message (const char* key, const char* value,
416         cdtime_t time, struct wg_callback *cb)
418     int status;
419     size_t message_len;
420     char message[1024];
422     message_len = (size_t) ssnprintf (message, sizeof (message),
423             "%s %s %.0f\n",
424             key,
425             value,
426             CDTIME_T_TO_DOUBLE(time));
427     if (message_len >= sizeof (message)) {
428         ERROR ("write_graphite plugin: message buffer too small: "
429                 "Need %zu bytes.", message_len + 1);
430         return (-1);
431     }
434     pthread_mutex_lock (&cb->send_lock);
436     if (cb->sock_fd < 0)
437     {
438         status = wg_callback_init (cb);
439         if (status != 0)
440         {
441             ERROR ("write_graphite plugin: wg_callback_init failed.");
442             pthread_mutex_unlock (&cb->send_lock);
443             return (-1);
444         }
445     }
447     if (message_len >= cb->send_buf_free)
448     {
449         status = wg_flush_nolock (/* timeout = */ 0, cb);
450         if (status != 0)
451         {
452             pthread_mutex_unlock (&cb->send_lock);
453             return (status);
454         }
455     }
456     assert (message_len < cb->send_buf_free);
458     /* `message_len + 1' because `message_len' does not include the
459      * trailing null byte. Neither does `send_buffer_fill'. */
460     memcpy (cb->send_buf + cb->send_buf_fill,
461             message, message_len + 1);
462     cb->send_buf_fill += message_len;
463     cb->send_buf_free -= message_len;
465     DEBUG ("write_graphite plugin: <%s:%d> buf %zu/%zu (%g%%) \"%s\"",
466             cb->host,
467             cb->port,
468             cb->send_buf_fill, sizeof (cb->send_buf),
469             100.0 * ((double) cb->send_buf_fill) / ((double) sizeof (cb->send_buf)),
470             message);
472     /* Check if we have enough space for this message. */
473     pthread_mutex_unlock (&cb->send_lock);
475     return (0);
478 static int wg_write_messages (const data_set_t *ds, const value_list_t *vl,
479         struct wg_callback *cb)
481     char key[10*DATA_MAX_NAME_LEN];
482     char values[512];
484     int status, i;
486     if (0 != strcmp (ds->type, vl->type))
487     {
488         ERROR ("write_graphite plugin: DS type does not match "
489                 "value list type");
490         return -1;
491     }
493     if (ds->ds_num > 1)
494     {
495         for (i = 0; i < ds->ds_num; i++)
496         {
497             /* Copy the identifier to `key' and escape it. */
498             status = WG_FORMAT_NAME (key, sizeof (key), vl, cb->prefix, \
499                     ds->ds[i].name);
500             if (status != 0)
501             {
502                 ERROR ("write_graphite plugin: error with format_name");
503                 return (status);
504             }
506             escape_string (key, sizeof (key));
507             /* Convert the values to an ASCII representation and put that
508              * into `values'. */
509             status = wg_format_values (values, sizeof (values), i, ds, vl, 0);
510             if (status != 0)
511             {
512                 ERROR ("write_graphite plugin: error with "
513                         "wg_format_values");
514                 return (status);
515             }
517             /* Send the message to graphite */
518             status = wg_send_message (key, values, vl->time, cb);
519             if (status != 0)
520             {
521                 ERROR ("write_graphite plugin: error with "
522                         "wg_send_message");
523                 return (status);
524             }
525         }
526     }
527     else
528     {
529         /* Copy the identifier to `key' and escape it. */
530         status = WG_FORMAT_NAME (key, sizeof (key), vl, cb->prefix, NULL);
531         if (status != 0)
532         {
533             ERROR ("write_graphite plugin: error with format_name");
534             return (status);
535         }
537         escape_string (key, sizeof (key));
538         /* Convert the values to an ASCII representation and put that into
539          * `values'. */
540         status = wg_format_values (values, sizeof (values), 0, ds, vl, 0);
541         if (status != 0)
542         {
543             ERROR ("write_graphite plugin: error with "
544                     "wg_format_values");
545             return (status);
546         }
548         /* Send the message to graphite */
549         status = wg_send_message (key, values, vl->time, cb);
550         if (status != 0)
551         {
552             ERROR ("write_graphite plugin: error with "
553                     "wg_send_message");
554             return (status);
555         }
556     }
558     return (0);
561 static int wg_write (const data_set_t *ds, const value_list_t *vl,
562         user_data_t *user_data)
564     struct wg_callback *cb;
565     int status;
567     if (user_data == NULL)
568         return (-EINVAL);
570     cb = user_data->data;
572     status = wg_write_messages (ds, vl, cb);
574     return (status);
577 static int config_set_number (int *dest,
578         oconfig_item_t *ci)
580     if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
581     {
582         WARNING ("write_graphite plugin: The `%s' config option "
583                 "needs exactly one numeric argument.", ci->key);
584         return (-1);
585     }
587     *dest = ci->values[0].value.number;
589     return (0);
592 static int config_set_string (char **ret_string,
593         oconfig_item_t *ci)
595     char *string;
597     if ((ci->values_num != 1)
598             || (ci->values[0].type != OCONFIG_TYPE_STRING))
599     {
600         WARNING ("write_graphite plugin: The `%s' config option "
601                 "needs exactly one string argument.", ci->key);
602         return (-1);
603     }
605     string = strdup (ci->values[0].value.string);
606     if (string == NULL)
607     {
608         ERROR ("write_graphite plugin: strdup failed.");
609         return (-1);
610     }
612     if (*ret_string != NULL)
613         sfree (*ret_string);
614     *ret_string = string;
616     return (0);
619 static int wg_config_carbon (oconfig_item_t *ci)
621     struct wg_callback *cb;
622     user_data_t user_data;
623     int i;
625     cb = malloc (sizeof (*cb));
626     if (cb == NULL)
627     {
628         ERROR ("write_graphite plugin: malloc failed.");
629         return (-1);
630     }
631     memset (cb, 0, sizeof (*cb));
632     cb->sock_fd = -1;
633     cb->host = NULL;
634     cb->name = NULL;
635     cb->port = 2003;
636     cb->prefix = NULL;
637     cb->server = NULL;
639     pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
641     config_set_string (&cb->name, ci);
642     if (cb->name == NULL)
643         return (-1);
645     for (i = 0; i < ci->children_num; i++)
646     {
647         oconfig_item_t *child = ci->children + i;
649         if (strcasecmp ("Host", child->key) == 0)
650             config_set_string (&cb->host, child);
651         else if (strcasecmp ("Port", child->key) == 0)
652             config_set_number (&cb->port, child);
653         else if (strcasecmp ("Prefix", child->key) == 0)
654             config_set_string (&cb->prefix, child);
655         else
656         {
657             ERROR ("write_graphite plugin: Invalid configuration "
658                         "option: %s.", child->key);
659         }
660     }
662     DEBUG ("write_graphite: Registering write callback to carbon agent "
663             "%s:%d", cb->host, cb->port);
665     memset (&user_data, 0, sizeof (user_data));
666     user_data.data = cb;
667     user_data.free_func = NULL;
668     plugin_register_flush ("write_graphite", wg_flush, &user_data);
670     user_data.free_func = wg_callback_free;
671     plugin_register_write ("write_graphite", wg_write, &user_data);
673     return (0);
676 static int wg_config (oconfig_item_t *ci)
678     int i;
680     for (i = 0; i < ci->children_num; i++)
681     {
682         oconfig_item_t *child = ci->children + i;
684         if (strcasecmp ("Carbon", child->key) == 0)
685             wg_config_carbon (child);
686         else
687         {
688             ERROR ("write_graphite plugin: Invalid configuration "
689                     "option: %s.", child->key);
690         }
691     }
693     return (0);
696 void module_register (void)
698     plugin_register_complex_config ("write_graphite", wg_config);
701 /* vim: set sw=4 ts=4 sts=4 tw=78 et : */