write_graphite plugin: Use CR-LF line endings.
[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  **/
31
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   */
42
43 #include "collectd.h"
44 #include "common.h"
45 #include "plugin.h"
46 #include "configfile.h"
47
48 #include "utils_cache.h"
49 #include "utils_parse_option.h"
50
51 /* Folks without pthread will need to disable this plugin. */
52 #include <pthread.h>
53
54 #include <sys/socket.h>
55 #include <netdb.h>
56
57 #ifndef WG_DEFAULT_NODE
58 # define WG_DEFAULT_NODE "localhost"
59 #endif
60
61 #ifndef WG_DEFAULT_SERVICE
62 # define WG_DEFAULT_SERVICE "2003"
63 #endif
64
65 #ifndef WG_DEFAULT_ESCAPE
66 # define WG_DEFAULT_ESCAPE '_'
67 #endif
68
69 /* Ethernet - (IPv6 + TCP) = 1500 - (40 + 32) = 1428 */
70 #ifndef WG_SEND_BUF_SIZE
71 # define WG_SEND_BUF_SIZE 1428
72 #endif
73
74 /*
75  * Private variables
76  */
77 struct wg_callback
78 {
79     int      sock_fd;
80
81     char    *node;
82     char    *service;
83     char    *prefix;
84     char    *postfix;
85     char     escape_char;
86
87     _Bool    store_rates;
88     _Bool    always_append_ds;
89
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;
94
95     pthread_mutex_t send_lock;
96 };
97
98
99 /*
100  * Functions
101  */
102 static void wg_reset_buffer (struct wg_callback *cb)
103 {
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 ();
108 }
109
110 static int wg_send_buffer (struct wg_callback *cb)
111 {
112     ssize_t status = 0;
113
114     status = swrite (cb->sock_fd, cb->send_buf, strlen (cb->send_buf));
115     if (status < 0)
116     {
117         char errbuf[1024];
118         ERROR ("write_graphite plugin: send failed with status %zi (%s)",
119                 status, sstrerror (errno, errbuf, sizeof (errbuf)));
120
121
122         close (cb->sock_fd);
123         cb->sock_fd = -1;
124
125         return (-1);
126     }
127
128     return (0);
129 }
130
131 /* NOTE: You must hold cb->send_lock when calling this function! */
132 static int wg_flush_nolock (cdtime_t timeout, struct wg_callback *cb)
133 {
134     int status;
135
136     DEBUG ("write_graphite plugin: wg_flush_nolock: timeout = %.3f; "
137             "send_buf_fill = %zu;",
138             (double)timeout,
139             cb->send_buf_fill);
140
141     /* timeout == 0  => flush unconditionally */
142     if (timeout > 0)
143     {
144         cdtime_t now;
145
146         now = cdtime ();
147         if ((cb->send_buf_init_time + timeout) > now)
148             return (0);
149     }
150
151     if (cb->send_buf_fill <= 0)
152     {
153         cb->send_buf_init_time = cdtime ();
154         return (0);
155     }
156
157     status = wg_send_buffer (cb);
158     wg_reset_buffer (cb);
159
160     return (status);
161 }
162
163 static int wg_callback_init (struct wg_callback *cb)
164 {
165     struct addrinfo ai_hints;
166     struct addrinfo *ai_list;
167     struct addrinfo *ai_ptr;
168     int status;
169
170     const char *node = cb->node ? cb->node : WG_DEFAULT_NODE;
171     const char *service = cb->service ? cb->service : WG_DEFAULT_SERVICE;
172
173     if (cb->sock_fd > 0)
174         return (0);
175
176     memset (&ai_hints, 0, sizeof (ai_hints));
177 #ifdef AI_ADDRCONFIG
178     ai_hints.ai_flags |= AI_ADDRCONFIG;
179 #endif
180     ai_hints.ai_family = AF_UNSPEC;
181     ai_hints.ai_socktype = SOCK_STREAM;
182
183     ai_list = NULL;
184
185     status = getaddrinfo (node, service, &ai_hints, &ai_list);
186     if (status != 0)
187     {
188         ERROR ("write_graphite plugin: getaddrinfo (%s, %s) failed: %s",
189                 node, service, gai_strerror (status));
190         return (-1);
191     }
192
193     assert (ai_list != NULL);
194     for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
195     {
196         cb->sock_fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
197                 ai_ptr->ai_protocol);
198         if (cb->sock_fd < 0)
199             continue;
200
201         status = connect (cb->sock_fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
202         if (status != 0)
203         {
204             close (cb->sock_fd);
205             cb->sock_fd = -1;
206             continue;
207         }
208
209         break;
210     }
211
212     freeaddrinfo (ai_list);
213
214     if (cb->sock_fd < 0)
215     {
216         char errbuf[1024];
217         ERROR ("write_graphite plugin: Connecting to %s:%s failed. "
218                 "The last error was: %s", node, service,
219                 sstrerror (errno, errbuf, sizeof (errbuf)));
220         close (cb->sock_fd);
221         return (-1);
222     }
223
224     wg_reset_buffer (cb);
225
226     return (0);
227 }
228
229 static void wg_callback_free (void *data)
230 {
231     struct wg_callback *cb;
232
233     if (data == NULL)
234         return;
235
236     cb = data;
237
238     pthread_mutex_lock (&cb->send_lock);
239
240     wg_flush_nolock (/* timeout = */ 0, cb);
241
242     close(cb->sock_fd);
243     cb->sock_fd = -1;
244
245     sfree(cb->node);
246     sfree(cb->service);
247     sfree(cb->prefix);
248     sfree(cb->postfix);
249
250     pthread_mutex_destroy (&cb->send_lock);
251
252     sfree(cb);
253 }
254
255 static int wg_flush (cdtime_t timeout,
256         const char *identifier __attribute__((unused)),
257         user_data_t *user_data)
258 {
259     struct wg_callback *cb;
260     int status;
261
262     if (user_data == NULL)
263         return (-EINVAL);
264
265     cb = user_data->data;
266
267     pthread_mutex_lock (&cb->send_lock);
268
269     if (cb->sock_fd < 0)
270     {
271         status = wg_callback_init (cb);
272         if (status != 0)
273         {
274             ERROR ("write_graphite plugin: wg_callback_init failed.");
275             pthread_mutex_unlock (&cb->send_lock);
276             return (-1);
277         }
278     }
279
280     status = wg_flush_nolock (timeout, cb);
281     pthread_mutex_unlock (&cb->send_lock);
282
283     return (status);
284 }
285
286 static int wg_format_values (char *ret, size_t ret_len,
287         int ds_num, const data_set_t *ds, const value_list_t *vl,
288         _Bool store_rates)
289 {
290     size_t offset = 0;
291     int status;
292     gauge_t *rates = NULL;
293
294     assert (0 == strcmp (ds->type, vl->type));
295
296     memset (ret, 0, ret_len);
297
298 #define BUFFER_ADD(...) do { \
299     status = ssnprintf (ret + offset, ret_len - offset, \
300             __VA_ARGS__); \
301     if (status < 1) \
302     { \
303         sfree (rates); \
304         return (-1); \
305     } \
306     else if (((size_t) status) >= (ret_len - offset)) \
307     { \
308         sfree (rates); \
309         return (-1); \
310     } \
311     else \
312     offset += ((size_t) status); \
313 } while (0)
314
315     if (ds->ds[ds_num].type == DS_TYPE_GAUGE)
316         BUFFER_ADD ("%f", vl->values[ds_num].gauge);
317     else if (store_rates)
318     {
319         if (rates == NULL)
320             rates = uc_get_rate (ds, vl);
321         if (rates == NULL)
322         {
323             WARNING ("format_values: "
324                     "uc_get_rate failed.");
325             return (-1);
326         }
327         BUFFER_ADD ("%g", rates[ds_num]);
328     }
329     else if (ds->ds[ds_num].type == DS_TYPE_COUNTER)
330         BUFFER_ADD ("%llu", vl->values[ds_num].counter);
331     else if (ds->ds[ds_num].type == DS_TYPE_DERIVE)
332         BUFFER_ADD ("%"PRIi64, vl->values[ds_num].derive);
333     else if (ds->ds[ds_num].type == DS_TYPE_ABSOLUTE)
334         BUFFER_ADD ("%"PRIu64, vl->values[ds_num].absolute);
335     else
336     {
337         ERROR ("format_values plugin: Unknown data source type: %i",
338                 ds->ds[ds_num].type);
339         sfree (rates);
340         return (-1);
341     }
342
343 #undef BUFFER_ADD
344
345     sfree (rates);
346     return (0);
347 }
348
349 static void wg_copy_escape_part (char *dst, const char *src, size_t dst_len,
350     char escape_char)
351 {
352     size_t i;
353
354     memset (dst, 0, dst_len);
355
356     if (src == NULL)
357         return;
358
359     for (i = 0; i < dst_len; i++)
360     {
361         if (src[i] == 0)
362         {
363             dst[i] = 0;
364             break;
365         }
366
367         if ((src[i] == '.')
368                 || isspace ((int) src[i])
369                 || iscntrl ((int) src[i]))
370             dst[i] = escape_char;
371         else
372             dst[i] = src[i];
373     }
374 }
375
376 static int wg_format_name (char *ret, int ret_len,
377         const value_list_t *vl,
378         const struct wg_callback *cb,
379         const char *ds_name)
380 {
381     char n_host[DATA_MAX_NAME_LEN];
382     char n_plugin[DATA_MAX_NAME_LEN];
383     char n_plugin_instance[DATA_MAX_NAME_LEN];
384     char n_type[DATA_MAX_NAME_LEN];
385     char n_type_instance[DATA_MAX_NAME_LEN];
386
387     char *prefix;
388     char *postfix;
389
390     char tmp_plugin[2 * DATA_MAX_NAME_LEN + 1];
391     char tmp_type[2 * DATA_MAX_NAME_LEN + 1];
392
393     prefix = cb->prefix;
394     if (prefix == NULL)
395         prefix = "";
396
397     postfix = cb->postfix;
398     if (postfix == NULL)
399         postfix = "";
400
401     wg_copy_escape_part (n_host, vl->host,
402             sizeof (n_host), cb->escape_char);
403     wg_copy_escape_part (n_plugin, vl->plugin,
404             sizeof (n_plugin), cb->escape_char);
405     wg_copy_escape_part (n_plugin_instance, vl->plugin_instance,
406             sizeof (n_plugin_instance), cb->escape_char);
407     wg_copy_escape_part (n_type, vl->type,
408             sizeof (n_type), cb->escape_char);
409     wg_copy_escape_part (n_type_instance, vl->type_instance,
410             sizeof (n_type_instance), cb->escape_char);
411
412     if (n_plugin_instance[0] != '\0')
413         ssnprintf (tmp_plugin, sizeof (tmp_plugin), "%s-%s",
414             n_plugin, n_plugin_instance);
415     else
416         sstrncpy (tmp_plugin, n_plugin, sizeof (tmp_plugin));
417
418     if (n_type_instance[0] != '\0')
419         ssnprintf (tmp_type, sizeof (tmp_type), "%s-%s",
420             n_type, n_type_instance);
421     else
422         sstrncpy (tmp_type, n_type, sizeof (tmp_type));
423
424     if (ds_name != NULL)
425         ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s",
426             prefix, n_host, postfix, tmp_plugin, tmp_type, ds_name);
427     else
428         ssnprintf (ret, ret_len, "%s%s%s.%s.%s",
429             prefix, n_host, postfix, tmp_plugin, tmp_type);
430
431     return (0);
432 }
433
434 static int wg_send_message (const char* key, const char* value,
435         cdtime_t time, struct wg_callback *cb)
436 {
437     int status;
438     size_t message_len;
439     char message[1024];
440
441     message_len = (size_t) ssnprintf (message, sizeof (message),
442             "%s %s %.0f\r\n",
443             key,
444             value,
445             CDTIME_T_TO_DOUBLE(time));
446     if (message_len >= sizeof (message)) {
447         ERROR ("write_graphite plugin: message buffer too small: "
448                 "Need %zu bytes.", message_len + 1);
449         return (-1);
450     }
451
452
453     pthread_mutex_lock (&cb->send_lock);
454
455     if (cb->sock_fd < 0)
456     {
457         status = wg_callback_init (cb);
458         if (status != 0)
459         {
460             ERROR ("write_graphite plugin: wg_callback_init failed.");
461             pthread_mutex_unlock (&cb->send_lock);
462             return (-1);
463         }
464     }
465
466     if (message_len >= cb->send_buf_free)
467     {
468         status = wg_flush_nolock (/* timeout = */ 0, cb);
469         if (status != 0)
470         {
471             pthread_mutex_unlock (&cb->send_lock);
472             return (status);
473         }
474     }
475     assert (message_len < cb->send_buf_free);
476
477     /* `message_len + 1' because `message_len' does not include the
478      * trailing null byte. Neither does `send_buffer_fill'. */
479     memcpy (cb->send_buf + cb->send_buf_fill,
480             message, message_len + 1);
481     cb->send_buf_fill += message_len;
482     cb->send_buf_free -= message_len;
483
484     DEBUG ("write_graphite plugin: <%s:%s> buf %zu/%zu (%g%%) \"%s\"",
485             cb->node,
486             cb->service,
487             cb->send_buf_fill, sizeof (cb->send_buf),
488             100.0 * ((double) cb->send_buf_fill) / ((double) sizeof (cb->send_buf)),
489             message);
490
491     /* Check if we have enough space for this message. */
492     pthread_mutex_unlock (&cb->send_lock);
493
494     return (0);
495 }
496
497 static int wg_write_messages (const data_set_t *ds, const value_list_t *vl,
498         struct wg_callback *cb)
499 {
500     char key[10*DATA_MAX_NAME_LEN];
501     char values[512];
502
503     int status, i;
504
505     if (0 != strcmp (ds->type, vl->type))
506     {
507         ERROR ("write_graphite plugin: DS type does not match "
508                 "value list type");
509         return -1;
510     }
511
512     if (ds->ds_num > 1)
513     {
514         for (i = 0; i < ds->ds_num; i++)
515         {
516             /* Copy the identifier to `key' and escape it. */
517             status = wg_format_name (key, sizeof (key), vl, cb, ds->ds[i].name);
518             if (status != 0)
519             {
520                 ERROR ("write_graphite plugin: error with format_name");
521                 return (status);
522             }
523
524             escape_string (key, sizeof (key));
525             /* Convert the values to an ASCII representation and put that
526              * into `values'. */
527             status = wg_format_values (values, sizeof (values), i, ds, vl,
528                     cb->store_rates);
529             if (status != 0)
530             {
531                 ERROR ("write_graphite plugin: error with "
532                         "wg_format_values");
533                 return (status);
534             }
535
536             /* Send the message to graphite */
537             status = wg_send_message (key, values, vl->time, cb);
538             if (status != 0)
539             {
540                 ERROR ("write_graphite plugin: error with "
541                         "wg_send_message");
542                 return (status);
543             }
544         }
545     }
546     else
547     {
548         /* Copy the identifier to `key' and escape it. */
549         status = wg_format_name (key, sizeof (key), vl, cb,
550             cb->always_append_ds ? ds->ds[0].name : NULL);
551         if (status != 0)
552         {
553             ERROR ("write_graphite plugin: error with format_name");
554             return (status);
555         }
556
557         escape_string (key, sizeof (key));
558         /* Convert the values to an ASCII representation and put that into
559          * `values'. */
560         status = wg_format_values (values, sizeof (values), 0, ds, vl,
561                     cb->store_rates);
562         if (status != 0)
563         {
564             ERROR ("write_graphite plugin: error with "
565                     "wg_format_values");
566             return (status);
567         }
568
569         /* Send the message to graphite */
570         status = wg_send_message (key, values, vl->time, cb);
571         if (status != 0)
572         {
573             ERROR ("write_graphite plugin: error with "
574                     "wg_send_message");
575             return (status);
576         }
577     }
578
579     return (0);
580 }
581
582 static int wg_write (const data_set_t *ds, const value_list_t *vl,
583         user_data_t *user_data)
584 {
585     struct wg_callback *cb;
586     int status;
587
588     if (user_data == NULL)
589         return (EINVAL);
590
591     cb = user_data->data;
592
593     status = wg_write_messages (ds, vl, cb);
594
595     return (status);
596 }
597
598 static int config_set_char (char *dest,
599         oconfig_item_t *ci)
600 {
601     if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
602     {
603         WARNING ("write_graphite plugin: The `%s' config option "
604                 "needs exactly one string argument.", ci->key);
605         return (-1);
606     }
607
608     *dest = ci->values[0].value.string[0];
609
610     return (0);
611 }
612
613 static int wg_config_carbon (oconfig_item_t *ci)
614 {
615     struct wg_callback *cb;
616     user_data_t user_data;
617     int i;
618
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
633     pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
634
635     for (i = 0; i < ci->children_num; i++)
636     {
637         oconfig_item_t *child = ci->children + i;
638
639         if (strcasecmp ("Host", child->key) == 0)
640             cf_util_get_string (child, &cb->node);
641         else if (strcasecmp ("Port", child->key) == 0)
642             cf_util_get_service (child, &cb->service);
643         else if (strcasecmp ("Prefix", child->key) == 0)
644             cf_util_get_string (child, &cb->prefix);
645         else if (strcasecmp ("Postfix", child->key) == 0)
646             cf_util_get_string (child, &cb->postfix);
647         else if (strcasecmp ("StoreRates", child->key) == 0)
648             cf_util_get_boolean (child, &cb->store_rates);
649         else if (strcasecmp ("AlwaysAppendDS", child->key) == 0)
650             cf_util_get_boolean (child, &cb->always_append_ds);
651         else if (strcasecmp ("EscapeCharacter", child->key) == 0)
652             config_set_char (&cb->escape_char, child);
653         else
654         {
655             ERROR ("write_graphite plugin: Invalid configuration "
656                         "option: %s.", child->key);
657         }
658     }
659
660     DEBUG ("write_graphite: Registering write callback to carbon agent %s:%s",
661             cb->node ? cb->node : WG_DEFAULT_NODE,
662             cb->service ? cb->service : WG_DEFAULT_SERVICE);
663
664     memset (&user_data, 0, sizeof (user_data));
665     user_data.data = cb;
666     user_data.free_func = NULL;
667     plugin_register_flush ("write_graphite", wg_flush, &user_data);
668
669     user_data.free_func = wg_callback_free;
670     plugin_register_write ("write_graphite", wg_write, &user_data);
671
672     return (0);
673 }
674
675 static int wg_config (oconfig_item_t *ci)
676 {
677     int i;
678
679     for (i = 0; i < ci->children_num; i++)
680     {
681         oconfig_item_t *child = ci->children + i;
682
683         if (strcasecmp ("Carbon", child->key) == 0)
684             wg_config_carbon (child);
685         else
686         {
687             ERROR ("write_graphite plugin: Invalid configuration "
688                     "option: %s.", child->key);
689         }
690     }
691
692     return (0);
693 }
694
695 void module_register (void)
696 {
697     plugin_register_complex_config ("write_graphite", wg_config);
698 }
699
700 /* vim: set sw=4 ts=4 sts=4 tw=78 et : */