write_graphite plugin: Limit number of reconnection attempts per time.
[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-2013  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   *     Protocol "udp"
39   *     LogSendErrors true
40   *     Prefix "collectd"
41   *   </Carbon>
42   * </Plugin>
43   */
44
45 #include "collectd.h"
46 #include "common.h"
47 #include "plugin.h"
48 #include "configfile.h"
49
50 #include "utils_cache.h"
51 #include "utils_complain.h"
52 #include "utils_parse_option.h"
53 #include "utils_format_graphite.h"
54
55 /* Folks without pthread will need to disable this plugin. */
56 #include <pthread.h>
57
58 #include <sys/socket.h>
59 #include <netdb.h>
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_DEFAULT_PROTOCOL
70 # define WG_DEFAULT_PROTOCOL "tcp"
71 #endif
72
73 #ifndef WG_DEFAULT_LOG_SEND_ERRORS
74 # define WG_DEFAULT_LOG_SEND_ERRORS 1
75 #endif
76
77 #ifndef WG_DEFAULT_ESCAPE
78 # define WG_DEFAULT_ESCAPE '_'
79 #endif
80
81 /* Ethernet - (IPv6 + TCP) = 1500 - (40 + 32) = 1428 */
82 #ifndef WG_SEND_BUF_SIZE
83 # define WG_SEND_BUF_SIZE 1428
84 #endif
85
86 #ifndef WG_MIN_RECONNECT_INTERVAL
87 # define WG_MIN_RECONNECT_INTERVAL TIME_T_TO_CDTIME_T (1)
88 #endif
89
90 /*
91  * Private variables
92  */
93 struct wg_callback
94 {
95     int      sock_fd;
96
97     char    *name;
98
99     char    *node;
100     char    *service;
101     char    *protocol;
102     _Bool   log_send_errors;
103     char    *prefix;
104     char    *postfix;
105     char     escape_char;
106
107     unsigned int format_flags;
108
109     char     send_buf[WG_SEND_BUF_SIZE];
110     size_t   send_buf_free;
111     size_t   send_buf_fill;
112     cdtime_t send_buf_init_time;
113
114     pthread_mutex_t send_lock;
115     c_complain_t init_complaint;
116     cdtime_t last_connect_time;
117 };
118
119
120 /*
121  * Functions
122  */
123 static void wg_reset_buffer (struct wg_callback *cb)
124 {
125     memset (cb->send_buf, 0, sizeof (cb->send_buf));
126     cb->send_buf_free = sizeof (cb->send_buf);
127     cb->send_buf_fill = 0;
128     cb->send_buf_init_time = cdtime ();
129 }
130
131 static int wg_send_buffer (struct wg_callback *cb)
132 {
133     ssize_t status = 0;
134
135     status = swrite (cb->sock_fd, cb->send_buf, strlen (cb->send_buf));
136     if (status < 0)
137     {
138         const char *protocol = cb->protocol ? cb->protocol : WG_DEFAULT_PROTOCOL;
139
140         if (cb->log_send_errors)
141         {
142             char errbuf[1024];
143             ERROR ("write_graphite plugin: send to %s:%s (%s) failed with status %zi (%s)",
144                     cb->node, cb->service, protocol,
145                     status, sstrerror (errno, errbuf, sizeof (errbuf)));
146         }
147
148         close (cb->sock_fd);
149         cb->sock_fd = -1;
150
151         return (-1);
152     }
153
154     return (0);
155 }
156
157 /* NOTE: You must hold cb->send_lock when calling this function! */
158 static int wg_flush_nolock (cdtime_t timeout, struct wg_callback *cb)
159 {
160     int status;
161
162     DEBUG ("write_graphite plugin: wg_flush_nolock: timeout = %.3f; "
163             "send_buf_fill = %zu;",
164             (double)timeout,
165             cb->send_buf_fill);
166
167     /* timeout == 0  => flush unconditionally */
168     if (timeout > 0)
169     {
170         cdtime_t now;
171
172         now = cdtime ();
173         if ((cb->send_buf_init_time + timeout) > now)
174             return (0);
175     }
176
177     if (cb->send_buf_fill <= 0)
178     {
179         cb->send_buf_init_time = cdtime ();
180         return (0);
181     }
182
183     status = wg_send_buffer (cb);
184     wg_reset_buffer (cb);
185
186     return (status);
187 }
188
189 static int wg_callback_init (struct wg_callback *cb)
190 {
191     struct addrinfo ai_hints;
192     struct addrinfo *ai_list;
193     struct addrinfo *ai_ptr;
194     cdtime_t now;
195     int status;
196
197     const char *node = cb->node ? cb->node : WG_DEFAULT_NODE;
198     const char *service = cb->service ? cb->service : WG_DEFAULT_SERVICE;
199     const char *protocol = cb->protocol ? cb->protocol : WG_DEFAULT_PROTOCOL;
200
201     if (cb->sock_fd > 0)
202         return (0);
203
204     /* Don't try to reconnect too often. By default, one reconnection attempt
205      * is made per second. */
206     now = cdtime ();
207     if ((now - cb->last_connect_time) < WG_MIN_RECONNECT_INTERVAL)
208         return (EAGAIN);
209     cb->last_connect_time = now;
210
211     memset (&ai_hints, 0, sizeof (ai_hints));
212 #ifdef AI_ADDRCONFIG
213     ai_hints.ai_flags |= AI_ADDRCONFIG;
214 #endif
215     ai_hints.ai_family = AF_UNSPEC;
216
217     if (0 == strcasecmp ("tcp", protocol))
218         ai_hints.ai_socktype = SOCK_STREAM;
219     else
220         ai_hints.ai_socktype = SOCK_DGRAM;
221
222     ai_list = NULL;
223
224     status = getaddrinfo (node, service, &ai_hints, &ai_list);
225     if (status != 0)
226     {
227         ERROR ("write_graphite plugin: getaddrinfo (%s, %s, %s) failed: %s",
228                 node, service, protocol, gai_strerror (status));
229         return (-1);
230     }
231
232     assert (ai_list != NULL);
233     for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
234     {
235         cb->sock_fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
236                 ai_ptr->ai_protocol);
237         if (cb->sock_fd < 0)
238             continue;
239
240         status = connect (cb->sock_fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
241         if (status != 0)
242         {
243             close (cb->sock_fd);
244             cb->sock_fd = -1;
245             continue;
246         }
247
248         break;
249     }
250
251     freeaddrinfo (ai_list);
252
253     if (cb->sock_fd < 0)
254     {
255         char errbuf[1024];
256         c_complain (LOG_ERR, &cb->init_complaint,
257                 "write_graphite plugin: Connecting to %s:%s via %s failed. "
258                 "The last error was: %s", node, service, protocol,
259                 sstrerror (errno, errbuf, sizeof (errbuf)));
260         return (-1);
261     }
262     else
263     {
264         c_release (LOG_INFO, &cb->init_complaint,
265                 "write_graphite plugin: Successfully connected to %s:%s via %s.",
266                 node, service, protocol);
267     }
268
269     wg_reset_buffer (cb);
270
271     return (0);
272 }
273
274 static void wg_callback_free (void *data)
275 {
276     struct wg_callback *cb;
277
278     if (data == NULL)
279         return;
280
281     cb = data;
282
283     pthread_mutex_lock (&cb->send_lock);
284
285     wg_flush_nolock (/* timeout = */ 0, cb);
286
287     if (cb->sock_fd >= 0)
288     {
289         close (cb->sock_fd);
290         cb->sock_fd = -1;
291     }
292
293     sfree(cb->name);
294     sfree(cb->node);
295     sfree(cb->protocol);
296     sfree(cb->service);
297     sfree(cb->prefix);
298     sfree(cb->postfix);
299
300     pthread_mutex_destroy (&cb->send_lock);
301
302     sfree(cb);
303 }
304
305 static int wg_flush (cdtime_t timeout,
306         const char *identifier __attribute__((unused)),
307         user_data_t *user_data)
308 {
309     struct wg_callback *cb;
310     int status;
311
312     if (user_data == NULL)
313         return (-EINVAL);
314
315     cb = user_data->data;
316
317     pthread_mutex_lock (&cb->send_lock);
318
319     if (cb->sock_fd < 0)
320     {
321         status = wg_callback_init (cb);
322         if (status != 0)
323         {
324             /* An error message has already been printed. */
325             pthread_mutex_unlock (&cb->send_lock);
326             return (-1);
327         }
328     }
329
330     status = wg_flush_nolock (timeout, cb);
331     pthread_mutex_unlock (&cb->send_lock);
332
333     return (status);
334 }
335
336 static int wg_send_message (char const *message, struct wg_callback *cb)
337 {
338     int status;
339     size_t message_len;
340
341     message_len = strlen (message);
342
343     pthread_mutex_lock (&cb->send_lock);
344
345     if (cb->sock_fd < 0)
346     {
347         status = wg_callback_init (cb);
348         if (status != 0)
349         {
350             /* An error message has already been printed. */
351             pthread_mutex_unlock (&cb->send_lock);
352             return (-1);
353         }
354     }
355
356     if (message_len >= cb->send_buf_free)
357     {
358         status = wg_flush_nolock (/* timeout = */ 0, cb);
359         if (status != 0)
360         {
361             pthread_mutex_unlock (&cb->send_lock);
362             return (status);
363         }
364     }
365
366     /* Assert that we have enough space for this message. */
367     assert (message_len < cb->send_buf_free);
368
369     /* `message_len + 1' because `message_len' does not include the
370      * trailing null byte. Neither does `send_buffer_fill'. */
371     memcpy (cb->send_buf + cb->send_buf_fill,
372             message, message_len + 1);
373     cb->send_buf_fill += message_len;
374     cb->send_buf_free -= message_len;
375
376     DEBUG ("write_graphite plugin: [%s]:%s (%s) buf %zu/%zu (%.1f %%) \"%s\"",
377             cb->node,
378             cb->service,
379             cb->protocol,
380             cb->send_buf_fill, sizeof (cb->send_buf),
381             100.0 * ((double) cb->send_buf_fill) / ((double) sizeof (cb->send_buf)),
382             message);
383
384     pthread_mutex_unlock (&cb->send_lock);
385
386     return (0);
387 }
388
389 static int wg_write_messages (const data_set_t *ds, const value_list_t *vl,
390         struct wg_callback *cb)
391 {
392     char buffer[WG_SEND_BUF_SIZE];
393     int status;
394
395     if (0 != strcmp (ds->type, vl->type))
396     {
397         ERROR ("write_graphite plugin: DS type does not match "
398                 "value list type");
399         return -1;
400     }
401
402     memset (buffer, 0, sizeof (buffer));
403     status = format_graphite (buffer, sizeof (buffer), ds, vl,
404             cb->prefix, cb->postfix, cb->escape_char, cb->format_flags);
405     if (status != 0) /* error message has been printed already. */
406         return (status);
407
408     /* Send the message to graphite */
409     status = wg_send_message (buffer, cb);
410     if (status != 0) /* error message has been printed already. */
411         return (status);
412
413     return (0);
414 } /* int wg_write_messages */
415
416 static int wg_write (const data_set_t *ds, const value_list_t *vl,
417         user_data_t *user_data)
418 {
419     struct wg_callback *cb;
420     int status;
421
422     if (user_data == NULL)
423         return (EINVAL);
424
425     cb = user_data->data;
426
427     status = wg_write_messages (ds, vl, cb);
428
429     return (status);
430 }
431
432 static int config_set_char (char *dest,
433         oconfig_item_t *ci)
434 {
435     char buffer[4];
436     int status;
437
438     memset (buffer, 0, sizeof (buffer));
439
440     status = cf_util_get_string_buffer (ci, buffer, sizeof (buffer));
441     if (status != 0)
442         return (status);
443
444     if (buffer[0] == 0)
445     {
446         ERROR ("write_graphite plugin: Cannot use an empty string for the "
447                 "\"EscapeCharacter\" option.");
448         return (-1);
449     }
450
451     if (buffer[1] != 0)
452     {
453         WARNING ("write_graphite plugin: Only the first character of the "
454                 "\"EscapeCharacter\" option ('%c') will be used.",
455                 (int) buffer[0]);
456     }
457
458     *dest = buffer[0];
459
460     return (0);
461 }
462
463 static int wg_config_node (oconfig_item_t *ci)
464 {
465     struct wg_callback *cb;
466     user_data_t user_data;
467     char callback_name[DATA_MAX_NAME_LEN];
468     int i;
469     int status = 0;
470
471     cb = malloc (sizeof (*cb));
472     if (cb == NULL)
473     {
474         ERROR ("write_graphite plugin: malloc failed.");
475         return (-1);
476     }
477     memset (cb, 0, sizeof (*cb));
478     cb->sock_fd = -1;
479     cb->name = NULL;
480     cb->node = NULL;
481     cb->service = NULL;
482     cb->protocol = NULL;
483     cb->log_send_errors = WG_DEFAULT_LOG_SEND_ERRORS;
484     cb->prefix = NULL;
485     cb->postfix = NULL;
486     cb->escape_char = WG_DEFAULT_ESCAPE;
487     cb->format_flags = GRAPHITE_STORE_RATES;
488
489     /* FIXME: Legacy configuration syntax. */
490     if (strcasecmp ("Carbon", ci->key) != 0)
491     {
492         status = cf_util_get_string (ci, &cb->name);
493         if (status != 0)
494         {
495             wg_callback_free (cb);
496             return (status);
497         }
498     }
499
500     pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
501     C_COMPLAIN_INIT (&cb->init_complaint);
502
503     for (i = 0; i < ci->children_num; i++)
504     {
505         oconfig_item_t *child = ci->children + i;
506
507         if (strcasecmp ("Host", child->key) == 0)
508             cf_util_get_string (child, &cb->node);
509         else if (strcasecmp ("Port", child->key) == 0)
510             cf_util_get_service (child, &cb->service);
511         else if (strcasecmp ("Protocol", child->key) == 0)
512         {
513             cf_util_get_string (child, &cb->protocol);
514
515             if (strcasecmp ("UDP", cb->protocol) != 0 &&
516                 strcasecmp ("TCP", cb->protocol) != 0)
517             {
518                 ERROR ("write_graphite plugin: Unknown protocol (%s)",
519                         cb->protocol);
520                 status = -1;
521             }
522         }
523         else if (strcasecmp ("LogSendErrors", child->key) == 0)
524             cf_util_get_boolean (child, &cb->log_send_errors);
525         else if (strcasecmp ("Prefix", child->key) == 0)
526             cf_util_get_string (child, &cb->prefix);
527         else if (strcasecmp ("Postfix", child->key) == 0)
528             cf_util_get_string (child, &cb->postfix);
529         else if (strcasecmp ("StoreRates", child->key) == 0)
530             cf_util_get_flag (child, &cb->format_flags,
531                     GRAPHITE_STORE_RATES);
532         else if (strcasecmp ("SeparateInstances", child->key) == 0)
533             cf_util_get_flag (child, &cb->format_flags,
534                     GRAPHITE_SEPARATE_INSTANCES);
535         else if (strcasecmp ("AlwaysAppendDS", child->key) == 0)
536             cf_util_get_flag (child, &cb->format_flags,
537                     GRAPHITE_ALWAYS_APPEND_DS);
538         else if (strcasecmp ("EscapeCharacter", child->key) == 0)
539             config_set_char (&cb->escape_char, child);
540         else
541         {
542             ERROR ("write_graphite plugin: Invalid configuration "
543                         "option: %s.", child->key);
544             status = -1;
545         }
546
547         if (status != 0)
548             break;
549     }
550
551     if (status != 0)
552     {
553         wg_callback_free (cb);
554         return (status);
555     }
556
557     /* FIXME: Legacy configuration syntax. */
558     if (cb->name == NULL)
559         ssnprintf (callback_name, sizeof (callback_name), "write_graphite/%s/%s/%s",
560                 cb->node != NULL ? cb->node : WG_DEFAULT_NODE,
561                 cb->service != NULL ? cb->service : WG_DEFAULT_SERVICE,
562                 cb->protocol != NULL ? cb->protocol : WG_DEFAULT_PROTOCOL);
563     else
564         ssnprintf (callback_name, sizeof (callback_name), "write_graphite/%s",
565                 cb->name);
566
567     memset (&user_data, 0, sizeof (user_data));
568     user_data.data = cb;
569     user_data.free_func = wg_callback_free;
570     plugin_register_write (callback_name, wg_write, &user_data);
571
572     user_data.free_func = NULL;
573     plugin_register_flush (callback_name, wg_flush, &user_data);
574
575     return (0);
576 }
577
578 static int wg_config (oconfig_item_t *ci)
579 {
580     int i;
581
582     for (i = 0; i < ci->children_num; i++)
583     {
584         oconfig_item_t *child = ci->children + i;
585
586         if (strcasecmp ("Node", child->key) == 0)
587             wg_config_node (child);
588         /* FIXME: Remove this legacy mode in version 6. */
589         else if (strcasecmp ("Carbon", child->key) == 0)
590             wg_config_node (child);
591         else
592         {
593             ERROR ("write_graphite plugin: Invalid configuration "
594                     "option: %s.", child->key);
595         }
596     }
597
598     return (0);
599 }
600
601 void module_register (void)
602 {
603     plugin_register_complex_config ("write_graphite", wg_config);
604 }
605
606 /* vim: set sw=4 ts=4 sts=4 tw=78 et : */