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