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