Merge branch 'master' into sr/pf
[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 #include "utils_format_graphite.h"
51
52 /* Folks without pthread will need to disable this plugin. */
53 #include <pthread.h>
54
55 #include <sys/socket.h>
56 #include <netdb.h>
57
58 #ifndef WG_DEFAULT_NODE
59 # define WG_DEFAULT_NODE "localhost"
60 #endif
61
62 #ifndef WG_DEFAULT_SERVICE
63 # define WG_DEFAULT_SERVICE "2003"
64 #endif
65
66 #ifndef WG_DEFAULT_ESCAPE
67 # define WG_DEFAULT_ESCAPE '_'
68 #endif
69
70 /* Ethernet - (IPv6 + TCP) = 1500 - (40 + 32) = 1428 */
71 #ifndef WG_SEND_BUF_SIZE
72 # define WG_SEND_BUF_SIZE 1428
73 #endif
74
75 /*
76  * Private variables
77  */
78 struct wg_callback
79 {
80     int      sock_fd;
81
82     char    *node;
83     char    *service;
84     char    *prefix;
85     char    *postfix;
86     char     escape_char;
87
88     _Bool    store_rates;
89     _Bool    separate_instances;
90     _Bool    always_append_ds;
91
92     char     send_buf[WG_SEND_BUF_SIZE];
93     size_t   send_buf_free;
94     size_t   send_buf_fill;
95     cdtime_t send_buf_init_time;
96
97     pthread_mutex_t send_lock;
98 };
99
100
101 /*
102  * Functions
103  */
104 static void wg_reset_buffer (struct wg_callback *cb)
105 {
106     memset (cb->send_buf, 0, sizeof (cb->send_buf));
107     cb->send_buf_free = sizeof (cb->send_buf);
108     cb->send_buf_fill = 0;
109     cb->send_buf_init_time = cdtime ();
110 }
111
112 static int wg_send_buffer (struct wg_callback *cb)
113 {
114     ssize_t status = 0;
115
116     status = swrite (cb->sock_fd, cb->send_buf, strlen (cb->send_buf));
117     if (status < 0)
118     {
119         char errbuf[1024];
120         ERROR ("write_graphite plugin: send failed with status %zi (%s)",
121                 status, sstrerror (errno, errbuf, sizeof (errbuf)));
122
123
124         close (cb->sock_fd);
125         cb->sock_fd = -1;
126
127         return (-1);
128     }
129
130     return (0);
131 }
132
133 /* NOTE: You must hold cb->send_lock when calling this function! */
134 static int wg_flush_nolock (cdtime_t timeout, struct wg_callback *cb)
135 {
136     int status;
137
138     DEBUG ("write_graphite plugin: wg_flush_nolock: timeout = %.3f; "
139             "send_buf_fill = %zu;",
140             (double)timeout,
141             cb->send_buf_fill);
142
143     /* timeout == 0  => flush unconditionally */
144     if (timeout > 0)
145     {
146         cdtime_t now;
147
148         now = cdtime ();
149         if ((cb->send_buf_init_time + timeout) > now)
150             return (0);
151     }
152
153     if (cb->send_buf_fill <= 0)
154     {
155         cb->send_buf_init_time = cdtime ();
156         return (0);
157     }
158
159     status = wg_send_buffer (cb);
160     wg_reset_buffer (cb);
161
162     return (status);
163 }
164
165 static int wg_callback_init (struct wg_callback *cb)
166 {
167     struct addrinfo ai_hints;
168     struct addrinfo *ai_list;
169     struct addrinfo *ai_ptr;
170     int status;
171
172     const char *node = cb->node ? cb->node : WG_DEFAULT_NODE;
173     const char *service = cb->service ? cb->service : WG_DEFAULT_SERVICE;
174
175     if (cb->sock_fd > 0)
176         return (0);
177
178     memset (&ai_hints, 0, sizeof (ai_hints));
179 #ifdef AI_ADDRCONFIG
180     ai_hints.ai_flags |= AI_ADDRCONFIG;
181 #endif
182     ai_hints.ai_family = AF_UNSPEC;
183     ai_hints.ai_socktype = SOCK_STREAM;
184
185     ai_list = NULL;
186
187     status = getaddrinfo (node, service, &ai_hints, &ai_list);
188     if (status != 0)
189     {
190         ERROR ("write_graphite plugin: getaddrinfo (%s, %s) failed: %s",
191                 node, service, gai_strerror (status));
192         return (-1);
193     }
194
195     assert (ai_list != NULL);
196     for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
197     {
198         cb->sock_fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
199                 ai_ptr->ai_protocol);
200         if (cb->sock_fd < 0)
201             continue;
202
203         status = connect (cb->sock_fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
204         if (status != 0)
205         {
206             close (cb->sock_fd);
207             cb->sock_fd = -1;
208             continue;
209         }
210
211         break;
212     }
213
214     freeaddrinfo (ai_list);
215
216     if (cb->sock_fd < 0)
217     {
218         char errbuf[1024];
219         ERROR ("write_graphite plugin: Connecting to %s:%s failed. "
220                 "The last error was: %s", node, service,
221                 sstrerror (errno, errbuf, sizeof (errbuf)));
222         close (cb->sock_fd);
223         return (-1);
224     }
225
226     wg_reset_buffer (cb);
227
228     return (0);
229 }
230
231 static void wg_callback_free (void *data)
232 {
233     struct wg_callback *cb;
234
235     if (data == NULL)
236         return;
237
238     cb = data;
239
240     pthread_mutex_lock (&cb->send_lock);
241
242     wg_flush_nolock (/* timeout = */ 0, cb);
243
244     close(cb->sock_fd);
245     cb->sock_fd = -1;
246
247     sfree(cb->node);
248     sfree(cb->service);
249     sfree(cb->prefix);
250     sfree(cb->postfix);
251
252     pthread_mutex_destroy (&cb->send_lock);
253
254     sfree(cb);
255 }
256
257 static int wg_flush (cdtime_t timeout,
258         const char *identifier __attribute__((unused)),
259         user_data_t *user_data)
260 {
261     struct wg_callback *cb;
262     int status;
263
264     if (user_data == NULL)
265         return (-EINVAL);
266
267     cb = user_data->data;
268
269     pthread_mutex_lock (&cb->send_lock);
270
271     if (cb->sock_fd < 0)
272     {
273         status = wg_callback_init (cb);
274         if (status != 0)
275         {
276             ERROR ("write_graphite plugin: wg_callback_init failed.");
277             pthread_mutex_unlock (&cb->send_lock);
278             return (-1);
279         }
280     }
281
282     status = wg_flush_nolock (timeout, cb);
283     pthread_mutex_unlock (&cb->send_lock);
284
285     return (status);
286 }
287
288 static int wg_send_message (char const *message, struct wg_callback *cb)
289 {
290     int status;
291     size_t message_len;
292
293     message_len = strlen (message);
294
295     pthread_mutex_lock (&cb->send_lock);
296
297     if (cb->sock_fd < 0)
298     {
299         status = wg_callback_init (cb);
300         if (status != 0)
301         {
302             ERROR ("write_graphite plugin: wg_callback_init failed.");
303             pthread_mutex_unlock (&cb->send_lock);
304             return (-1);
305         }
306     }
307
308     if (message_len >= cb->send_buf_free)
309     {
310         status = wg_flush_nolock (/* timeout = */ 0, cb);
311         if (status != 0)
312         {
313             pthread_mutex_unlock (&cb->send_lock);
314             return (status);
315         }
316     }
317
318     /* Assert that we have enough space for this message. */
319     assert (message_len < cb->send_buf_free);
320
321     /* `message_len + 1' because `message_len' does not include the
322      * trailing null byte. Neither does `send_buffer_fill'. */
323     memcpy (cb->send_buf + cb->send_buf_fill,
324             message, message_len + 1);
325     cb->send_buf_fill += message_len;
326     cb->send_buf_free -= message_len;
327
328     DEBUG ("write_graphite plugin: [%s]:%s buf %zu/%zu (%.1f %%) \"%s\"",
329             cb->node,
330             cb->service,
331             cb->send_buf_fill, sizeof (cb->send_buf),
332             100.0 * ((double) cb->send_buf_fill) / ((double) sizeof (cb->send_buf)),
333             message);
334
335     pthread_mutex_unlock (&cb->send_lock);
336
337     return (0);
338 }
339
340 static int wg_write_messages (const data_set_t *ds, const value_list_t *vl,
341         struct wg_callback *cb)
342 {
343     char buffer[4096];
344     int status;
345
346     if (0 != strcmp (ds->type, vl->type))
347     {
348         ERROR ("write_graphite plugin: DS type does not match "
349                 "value list type");
350         return -1;
351     }
352
353     memset (buffer, 0, sizeof (buffer));
354     status = format_graphite (buffer, sizeof (buffer), ds, vl,
355             cb->prefix, cb->postfix, cb->escape_char);
356     if (status != 0) /* error message has been printed already. */
357         return (status);
358
359     wg_send_message (buffer, cb);
360     if (status != 0)
361     {
362         ERROR ("write_graphite plugin: wg_send_message failed "
363                 "with status %i.", status);
364         return (status);
365     }
366
367     return (0);
368 } /* int wg_write_messages */
369
370 static int wg_write (const data_set_t *ds, const value_list_t *vl,
371         user_data_t *user_data)
372 {
373     struct wg_callback *cb;
374     int status;
375
376     if (user_data == NULL)
377         return (EINVAL);
378
379     cb = user_data->data;
380
381     status = wg_write_messages (ds, vl, cb);
382
383     return (status);
384 }
385
386 static int config_set_char (char *dest,
387         oconfig_item_t *ci)
388 {
389     char buffer[4];
390     int status;
391
392     memset (buffer, 0, sizeof (buffer));
393
394     status = cf_util_get_string_buffer (ci, buffer, sizeof (buffer));
395     if (status != 0)
396         return (status);
397
398     if (buffer[0] == 0)
399     {
400         ERROR ("write_graphite plugin: Cannot use an empty string for the "
401                 "\"EscapeCharacter\" option.");
402         return (-1);
403     }
404
405     if (buffer[1] != 0)
406     {
407         WARNING ("write_graphite plugin: Only the first character of the "
408                 "\"EscapeCharacter\" option ('%c') will be used.",
409                 (int) buffer[0]);
410     }
411
412     *dest = buffer[0];
413
414     return (0);
415 }
416
417 static int wg_config_carbon (oconfig_item_t *ci)
418 {
419     struct wg_callback *cb;
420     user_data_t user_data;
421     char callback_name[DATA_MAX_NAME_LEN];
422     int i;
423
424     cb = malloc (sizeof (*cb));
425     if (cb == NULL)
426     {
427         ERROR ("write_graphite plugin: malloc failed.");
428         return (-1);
429     }
430     memset (cb, 0, sizeof (*cb));
431     cb->sock_fd = -1;
432     cb->node = NULL;
433     cb->service = NULL;
434     cb->prefix = NULL;
435     cb->postfix = NULL;
436     cb->escape_char = WG_DEFAULT_ESCAPE;
437     cb->store_rates = 1;
438
439     pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
440
441     for (i = 0; i < ci->children_num; i++)
442     {
443         oconfig_item_t *child = ci->children + i;
444
445         if (strcasecmp ("Host", child->key) == 0)
446             cf_util_get_string (child, &cb->node);
447         else if (strcasecmp ("Port", child->key) == 0)
448             cf_util_get_service (child, &cb->service);
449         else if (strcasecmp ("Prefix", child->key) == 0)
450             cf_util_get_string (child, &cb->prefix);
451         else if (strcasecmp ("Postfix", child->key) == 0)
452             cf_util_get_string (child, &cb->postfix);
453         else if (strcasecmp ("StoreRates", child->key) == 0)
454             cf_util_get_boolean (child, &cb->store_rates);
455         else if (strcasecmp ("SeparateInstances", child->key) == 0)
456             cf_util_get_boolean (child, &cb->separate_instances);
457         else if (strcasecmp ("AlwaysAppendDS", child->key) == 0)
458             cf_util_get_boolean (child, &cb->always_append_ds);
459         else if (strcasecmp ("EscapeCharacter", child->key) == 0)
460             config_set_char (&cb->escape_char, child);
461         else
462         {
463             ERROR ("write_graphite plugin: Invalid configuration "
464                         "option: %s.", child->key);
465         }
466     }
467
468     ssnprintf (callback_name, sizeof (callback_name), "write_graphite/%s/%s",
469             cb->node != NULL ? cb->node : WG_DEFAULT_NODE,
470             cb->service != NULL ? cb->service : WG_DEFAULT_SERVICE);
471
472     memset (&user_data, 0, sizeof (user_data));
473     user_data.data = cb;
474     user_data.free_func = wg_callback_free;
475     plugin_register_write (callback_name, wg_write, &user_data);
476
477     user_data.free_func = NULL;
478     plugin_register_flush (callback_name, wg_flush, &user_data);
479
480     return (0);
481 }
482
483 static int wg_config (oconfig_item_t *ci)
484 {
485     int i;
486
487     for (i = 0; i < ci->children_num; i++)
488     {
489         oconfig_item_t *child = ci->children + i;
490
491         if (strcasecmp ("Carbon", child->key) == 0)
492             wg_config_carbon (child);
493         else
494         {
495             ERROR ("write_graphite plugin: Invalid configuration "
496                     "option: %s.", child->key);
497         }
498     }
499
500     return (0);
501 }
502
503 void module_register (void)
504 {
505     plugin_register_complex_config ("write_graphite", wg_config);
506 }
507
508 /* vim: set sw=4 ts=4 sts=4 tw=78 et : */