Merge pull request #20 from pyr/ss/graphite
[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  **/
23
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   */
34
35 #include "collectd.h"
36 #include "common.h"
37 #include "plugin.h"
38 #include "configfile.h"
39
40 #include "utils_cache.h"
41 #include "utils_parse_option.h"
42
43 /* Folks without pthread will need to disable this plugin. */
44 #include <pthread.h>
45
46 #include <sys/socket.h>
47 #include <netdb.h>
48
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
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_SEND_BUF_SIZE
66 # define WG_SEND_BUF_SIZE 4096
67 #endif
68
69 /*
70  * Private variables
71  */
72 struct wg_callback
73 {
74     int      sock_fd;
75     struct hostent *server;
76
77     char    *node;
78     char    *service;
79     char    *prefix;
80     char    *postfix;
81     char     dotchar;
82
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;
87
88     pthread_mutex_t send_lock;
89 };
90
91
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 }
102
103 static int wg_send_buffer (struct wg_callback *cb)
104 {
105     int status = 0;
106
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));
114
115         pthread_mutex_trylock (&cb->send_lock);
116
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;
121
122         pthread_mutex_unlock (&cb->send_lock);
123
124         return (-1);
125     }
126     return (0);
127 }
128
129 static int wg_flush_nolock (cdtime_t timeout, struct wg_callback *cb)
130 {
131     int status;
132
133     DEBUG ("write_graphite plugin: wg_flush_nolock: timeout = %.3f; "
134             "send_buf_fill = %zu;",
135             (double)timeout,
136             cb->send_buf_fill);
137
138     /* timeout == 0  => flush unconditionally */
139     if (timeout > 0)
140     {
141         cdtime_t now;
142
143         now = cdtime ();
144         if ((cb->send_buf_init_time + timeout) > now)
145             return (0);
146     }
147
148     if (cb->send_buf_fill <= 0)
149     {
150         cb->send_buf_init_time = cdtime ();
151         return (0);
152     }
153
154     status = wg_send_buffer (cb);
155     wg_reset_buffer (cb);
156
157     return (status);
158 }
159
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;
166
167     const char *node = cb->node ? cb->node : WG_DEFAULT_NODE;
168     const char *service = cb->service ? cb->service : WG_DEFAULT_SERVICE;
169
170     if (cb->sock_fd > 0)
171         return (0);
172
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;
179
180     ai_list = NULL;
181
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     }
189
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;
197
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         }
205
206         break;
207     }
208
209     freeaddrinfo (ai_list);
210
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     }
220
221     wg_reset_buffer (cb);
222
223     return (0);
224 }
225
226 static void wg_callback_free (void *data)
227 {
228     struct wg_callback *cb;
229
230     if (data == NULL)
231         return;
232
233     cb = data;
234
235     wg_flush_nolock (/* timeout = */ 0, cb);
236
237     close(cb->sock_fd);
238     sfree(cb->node);
239     sfree(cb->service);
240     sfree(cb->prefix);
241     sfree(cb->postfix);
242
243     sfree(cb);
244 }
245
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;
252
253     if (user_data == NULL)
254         return (-EINVAL);
255
256     cb = user_data->data;
257
258     pthread_mutex_lock (&cb->send_lock);
259
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     }
270
271     status = wg_flush_nolock (timeout, cb);
272     pthread_mutex_unlock (&cb->send_lock);
273
274     return (status);
275 }
276
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;
284
285     assert (0 == strcmp (ds->type, vl->type));
286
287     memset (ret, 0, ret_len);
288
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)
305
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     }
333
334 #undef BUFFER_ADD
335
336     sfree (rates);
337     return (0);
338 }
339
340 static void swap_chars (char *dst, const char *src,
341         const char from, const char to)
342 {
343     size_t i;
344
345     for (i = 0; i < strlen(src) ; i++)
346     {
347         if (src[i] == from)
348             dst[i] = to;
349         else
350             dst[i] = src[i];
351     }
352     dst[i] = '\0';
353 }
354
355 static int wg_format_name (char *ret, int ret_len,
356         const char *hostname,
357         const char *plugin, const char *plugin_instance,
358         const char *type, const char *type_instance,
359         const char *prefix, const char *postfix,
360         const char *ds_name, const char dotchar)
361 {
362     int  status;
363     char *n_hostname = NULL;
364     char *n_plugin = NULL;
365     char *n_plugin_instance = NULL;
366     char *n_type = NULL;
367     char *n_type_instance = NULL;
368
369     assert (plugin != NULL);
370     assert (type != NULL);
371
372     if (prefix == NULL)
373         prefix = "";
374
375     if (postfix == NULL)
376         postfix = "";
377
378     if ((n_hostname = malloc(strlen(hostname)+1)) == NULL)
379     {
380         ERROR ("Unable to allocate memory for normalized hostname buffer");
381         return (-1);
382     }
383
384     if ((n_plugin = malloc(strlen(plugin)+1)) == NULL)
385     {
386         ERROR ("Unable to allocate memory for normalized plugin buffer");
387         return (-1);
388     }
389
390     if ((n_type = malloc(strlen(type)+1)) == NULL)
391     {
392         ERROR ("Unable to allocate memory for normalized type buffer");
393         return (-1);
394     }
395
396     swap_chars(n_hostname, hostname, '.', dotchar);
397     swap_chars(n_plugin, plugin, ' ', '_');
398     swap_chars(n_type, type, ' ', '_');
399
400     if (type_instance != NULL && type_instance[0] != '\0')
401     {
402         if ((n_type_instance = malloc(strlen(type_instance)+1)) == NULL)
403         {
404             ERROR ("Unable to allocate memory for normalized datasource name buffer");
405             return (-1);
406         }
407         swap_chars(n_type_instance, type_instance, '.', dotchar);
408         swap_chars(n_type_instance, type_instance, ' ', '_');
409     }
410
411     if (plugin_instance != NULL && plugin_instance[0] != '\0')
412     {
413         if ((n_plugin_instance = malloc(strlen(plugin_instance)+1)) == NULL)
414         {
415             ERROR ("Unable to allocate memory for normalized plugin instance buffer");
416             return (-1);
417         }
418         swap_chars(n_plugin_instance, plugin_instance, ' ', '_');
419     }
420
421     if ((n_plugin_instance == NULL) || (n_plugin_instance[0] == '\0'))
422     {
423         if ((n_type_instance == NULL) || (n_type_instance[0] == '\0'))
424         {
425             if ((ds_name == NULL) || (ds_name[0] == '\0'))
426                 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s",
427                         prefix, n_hostname, postfix, n_plugin, n_type);
428             else
429                 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s",
430                         prefix, n_hostname, postfix, n_plugin, n_type, ds_name);
431         }
432         else
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, n_plugin, n_type,
437                         n_type_instance);
438             else
439                 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s-%s.%s",
440                         prefix, n_hostname, postfix, n_plugin, n_type,
441                         n_type_instance, ds_name);
442         }
443     }
444     else
445     {
446         if ((n_type_instance == NULL) || (n_type_instance[0] == '\0'))
447         {
448             if ((ds_name == NULL) || (ds_name[0] == '\0'))
449                 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s",
450                         prefix, n_hostname, postfix, n_plugin,
451                         n_plugin_instance, n_type);
452             else
453                 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s.%s",
454                         prefix, n_hostname, postfix, n_plugin,
455                         n_plugin_instance, n_type, ds_name);
456         }
457         else
458         {
459             if ((ds_name == NULL) || (ds_name[0] == '\0'))
460                 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s-%s",
461                         prefix, n_hostname, postfix, n_plugin,
462                         n_plugin_instance, n_type, n_type_instance);
463             else
464                 status = ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s-%s.%s",
465                         prefix, n_hostname, postfix, n_plugin,
466                         n_plugin_instance, n_type, n_type_instance, ds_name);
467         }
468     }
469
470     sfree(n_hostname);
471     sfree(n_type_instance);
472     sfree(n_type);
473     sfree(n_plugin);
474     sfree(n_plugin_instance);
475
476     if ((status < 1) || (status >= ret_len))
477         return (-1);
478     return (0);
479 }
480
481 static int wg_send_message (const char* key, const char* value,
482         cdtime_t time, struct wg_callback *cb)
483 {
484     int status;
485     size_t message_len;
486     char message[1024];
487
488     message_len = (size_t) ssnprintf (message, sizeof (message),
489             "%s %s %.0f\n",
490             key,
491             value,
492             CDTIME_T_TO_DOUBLE(time));
493     if (message_len >= sizeof (message)) {
494         ERROR ("write_graphite plugin: message buffer too small: "
495                 "Need %zu bytes.", message_len + 1);
496         return (-1);
497     }
498
499
500     pthread_mutex_lock (&cb->send_lock);
501
502     if (cb->sock_fd < 0)
503     {
504         status = wg_callback_init (cb);
505         if (status != 0)
506         {
507             ERROR ("write_graphite plugin: wg_callback_init failed.");
508             pthread_mutex_unlock (&cb->send_lock);
509             return (-1);
510         }
511     }
512
513     if (message_len >= cb->send_buf_free)
514     {
515         status = wg_flush_nolock (/* timeout = */ 0, cb);
516         if (status != 0)
517         {
518             pthread_mutex_unlock (&cb->send_lock);
519             return (status);
520         }
521     }
522     assert (message_len < cb->send_buf_free);
523
524     /* `message_len + 1' because `message_len' does not include the
525      * trailing null byte. Neither does `send_buffer_fill'. */
526     memcpy (cb->send_buf + cb->send_buf_fill,
527             message, message_len + 1);
528     cb->send_buf_fill += message_len;
529     cb->send_buf_free -= message_len;
530
531     DEBUG ("write_graphite plugin: <%s:%s> buf %zu/%zu (%g%%) \"%s\"",
532             cb->node,
533             cb->service,
534             cb->send_buf_fill, sizeof (cb->send_buf),
535             100.0 * ((double) cb->send_buf_fill) / ((double) sizeof (cb->send_buf)),
536             message);
537
538     /* Check if we have enough space for this message. */
539     pthread_mutex_unlock (&cb->send_lock);
540
541     return (0);
542 }
543
544 static int wg_write_messages (const data_set_t *ds, const value_list_t *vl,
545         struct wg_callback *cb)
546 {
547     char key[10*DATA_MAX_NAME_LEN];
548     char values[512];
549
550     int status, i;
551
552     if (0 != strcmp (ds->type, vl->type))
553     {
554         ERROR ("write_graphite plugin: DS type does not match "
555                 "value list type");
556         return -1;
557     }
558
559     if (ds->ds_num > 1)
560     {
561         for (i = 0; i < ds->ds_num; i++)
562         {
563             /* Copy the identifier to `key' and escape it. */
564             status = WG_FORMAT_NAME (key, sizeof (key), vl, cb, ds->ds[i].name);
565             if (status != 0)
566             {
567                 ERROR ("write_graphite plugin: error with format_name");
568                 return (status);
569             }
570
571             escape_string (key, sizeof (key));
572             /* Convert the values to an ASCII representation and put that
573              * into `values'. */
574             status = wg_format_values (values, sizeof (values), i, ds, vl, 0);
575             if (status != 0)
576             {
577                 ERROR ("write_graphite plugin: error with "
578                         "wg_format_values");
579                 return (status);
580             }
581
582             /* Send the message to graphite */
583             status = wg_send_message (key, values, vl->time, cb);
584             if (status != 0)
585             {
586                 ERROR ("write_graphite plugin: error with "
587                         "wg_send_message");
588                 return (status);
589             }
590         }
591     }
592     else
593     {
594         /* Copy the identifier to `key' and escape it. */
595         status = WG_FORMAT_NAME (key, sizeof (key), vl, cb, NULL);
596         if (status != 0)
597         {
598             ERROR ("write_graphite plugin: error with format_name");
599             return (status);
600         }
601
602         escape_string (key, sizeof (key));
603         /* Convert the values to an ASCII representation and put that into
604          * `values'. */
605         status = wg_format_values (values, sizeof (values), 0, ds, vl, 0);
606         if (status != 0)
607         {
608             ERROR ("write_graphite plugin: error with "
609                     "wg_format_values");
610             return (status);
611         }
612
613         /* Send the message to graphite */
614         status = wg_send_message (key, values, vl->time, cb);
615         if (status != 0)
616         {
617             ERROR ("write_graphite plugin: error with "
618                     "wg_send_message");
619             return (status);
620         }
621     }
622
623     return (0);
624 }
625
626 static int wg_write (const data_set_t *ds, const value_list_t *vl,
627         user_data_t *user_data)
628 {
629     struct wg_callback *cb;
630     int status;
631
632     if (user_data == NULL)
633         return (-EINVAL);
634
635     cb = user_data->data;
636
637     status = wg_write_messages (ds, vl, cb);
638
639     return (status);
640 }
641
642 static int config_set_char (char *dest,
643         oconfig_item_t *ci)
644 {
645     if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
646     {
647         WARNING ("write_graphite plugin: The `%s' config option "
648                 "needs exactly one string argument.", ci->key);
649         return (-1);
650     }
651
652     *dest = ci->values[0].value.string[0];
653
654     return (0);
655 }
656
657 static int wg_config_carbon (oconfig_item_t *ci)
658 {
659     struct wg_callback *cb;
660     user_data_t user_data;
661     int i;
662
663     cb = malloc (sizeof (*cb));
664     if (cb == NULL)
665     {
666         ERROR ("write_graphite plugin: malloc failed.");
667         return (-1);
668     }
669     memset (cb, 0, sizeof (*cb));
670     cb->sock_fd = -1;
671     cb->node = NULL;
672     cb->service = NULL;
673     cb->prefix = NULL;
674     cb->postfix = NULL;
675     cb->server = NULL;
676     cb->dotchar = '_';
677
678     pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
679
680     for (i = 0; i < ci->children_num; i++)
681     {
682         oconfig_item_t *child = ci->children + i;
683
684         if (strcasecmp ("Host", child->key) == 0)
685             cf_util_get_string (child, &cb->node);
686         else if (strcasecmp ("Port", child->key) == 0)
687             cf_util_get_string (child, &cb->service);
688         else if (strcasecmp ("Prefix", child->key) == 0)
689             cf_util_get_string (child, &cb->prefix);
690         else if (strcasecmp ("Postfix", child->key) == 0)
691             cf_util_get_string (child, &cb->postfix);
692         else if (strcasecmp ("DotCharacter", child->key) == 0)
693             config_set_char (&cb->dotchar, child);
694         else
695         {
696             ERROR ("write_graphite plugin: Invalid configuration "
697                         "option: %s.", child->key);
698         }
699     }
700
701     DEBUG ("write_graphite: Registering write callback to carbon agent %s:%s",
702             cb->node ? cb->node : WG_DEFAULT_NODE,
703             cb->service ? cb->service : WG_DEFAULT_SERVICE);
704
705     memset (&user_data, 0, sizeof (user_data));
706     user_data.data = cb;
707     user_data.free_func = NULL;
708     plugin_register_flush ("write_graphite", wg_flush, &user_data);
709
710     user_data.free_func = wg_callback_free;
711     plugin_register_write ("write_graphite", wg_write, &user_data);
712
713     return (0);
714 }
715
716 static int wg_config (oconfig_item_t *ci)
717 {
718     int i;
719
720     for (i = 0; i < ci->children_num; i++)
721     {
722         oconfig_item_t *child = ci->children + i;
723
724         if (strcasecmp ("Carbon", child->key) == 0)
725             wg_config_carbon (child);
726         else
727         {
728             ERROR ("write_graphite plugin: Invalid configuration "
729                     "option: %s.", child->key);
730         }
731     }
732
733     return (0);
734 }
735
736 void module_register (void)
737 {
738     plugin_register_complex_config ("write_graphite", wg_config);
739 }
740
741 /* vim: set sw=4 ts=4 sts=4 tw=78 et : */