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