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