proto/collectd.proto: Improve documentation.
[collectd.git] / src / write_tsdb.c
1 /**
2  * collectd - src/write_tsdb.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  * Copyright (C) 2013-2014  Limelight Networks, Inc.
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  * Based on the write_graphite plugin. 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  * write_tsdb Authors:
29  *   Brett Hawn <bhawn at llnw.com>
30  *   Kevin Bowling <kbowling@llnw.com>
31  **/
32
33 /* write_tsdb plugin configuation example
34  *
35  * <Plugin write_tsdb>
36  *   <Node>
37  *     Host "localhost"
38  *     Port "4242"
39  *     HostTags "status=production deviceclass=www"
40  *   </Node>
41  * </Plugin>
42  */
43
44 #include "collectd.h"
45 #include "common.h"
46 #include "plugin.h"
47 #include "configfile.h"
48
49 #include "utils_cache.h"
50
51 #include <netdb.h>
52
53 #ifndef WT_DEFAULT_NODE
54 # define WT_DEFAULT_NODE "localhost"
55 #endif
56
57 #ifndef WT_DEFAULT_SERVICE
58 # define WT_DEFAULT_SERVICE "4242"
59 #endif
60
61 #ifndef WT_DEFAULT_ESCAPE
62 # define WT_DEFAULT_ESCAPE '.'
63 #endif
64
65 /* Ethernet - (IPv6 + TCP) = 1500 - (40 + 32) = 1428 */
66 #ifndef WT_SEND_BUF_SIZE
67 # define WT_SEND_BUF_SIZE 1428
68 #endif
69
70 /*
71  * Private variables
72  */
73 struct wt_callback
74 {
75     int      sock_fd;
76
77     char     *node;
78     char     *service;
79     char     *host_tags;
80
81     _Bool    store_rates;
82     _Bool    always_append_ds;
83
84     char     send_buf[WT_SEND_BUF_SIZE];
85     size_t   send_buf_free;
86     size_t   send_buf_fill;
87     cdtime_t send_buf_init_time;
88
89     pthread_mutex_t send_lock;
90 };
91
92
93 /*
94  * Functions
95  */
96 static void wt_reset_buffer(struct wt_callback *cb)
97 {
98     memset(cb->send_buf, 0, sizeof(cb->send_buf));
99     cb->send_buf_free = sizeof(cb->send_buf);
100     cb->send_buf_fill = 0;
101     cb->send_buf_init_time = cdtime();
102 }
103
104 static int wt_send_buffer(struct wt_callback *cb)
105 {
106     ssize_t status = 0;
107
108     status = swrite(cb->sock_fd, cb->send_buf, strlen(cb->send_buf));
109     if (status < 0)
110     {
111         char errbuf[1024];
112         ERROR("write_tsdb plugin: send failed with status %zi (%s)",
113               status, sstrerror (errno, errbuf, sizeof (errbuf)));
114
115         close (cb->sock_fd);
116         cb->sock_fd = -1;
117
118         return -1;
119     }
120
121     return 0;
122 }
123
124 /* NOTE: You must hold cb->send_lock when calling this function! */
125 static int wt_flush_nolock(cdtime_t timeout, struct wt_callback *cb)
126 {
127     int status;
128
129     DEBUG("write_tsdb plugin: wt_flush_nolock: timeout = %.3f; "
130           "send_buf_fill = %zu;",
131           (double)timeout,
132           cb->send_buf_fill);
133
134     /* timeout == 0  => flush unconditionally */
135     if (timeout > 0)
136     {
137         cdtime_t now;
138
139         now = cdtime();
140         if ((cb->send_buf_init_time + timeout) > now)
141             return 0;
142     }
143
144     if (cb->send_buf_fill == 0)
145     {
146         cb->send_buf_init_time = cdtime();
147         return 0;
148     }
149
150     status = wt_send_buffer(cb);
151     wt_reset_buffer(cb);
152
153     return status;
154 }
155
156 static int wt_callback_init(struct wt_callback *cb)
157 {
158     struct addrinfo ai_hints = { 0 };
159     struct addrinfo *ai_list;
160     struct addrinfo *ai_ptr;
161     int status;
162
163     const char *node = cb->node ? cb->node : WT_DEFAULT_NODE;
164     const char *service = cb->service ? cb->service : WT_DEFAULT_SERVICE;
165
166     if (cb->sock_fd > 0)
167         return 0;
168
169 #ifdef AI_ADDRCONFIG
170     ai_hints.ai_flags    |= AI_ADDRCONFIG;
171 #endif
172     ai_hints.ai_family   = AF_UNSPEC;
173     ai_hints.ai_socktype = SOCK_STREAM;
174
175     ai_list = NULL;
176
177     status = getaddrinfo(node, service, &ai_hints, &ai_list);
178     if (status != 0)
179     {
180         ERROR("write_tsdb plugin: getaddrinfo (%s, %s) failed: %s",
181               node, service, gai_strerror (status));
182         return -1;
183     }
184
185     assert (ai_list != NULL);
186     for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
187     {
188         cb->sock_fd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype,
189                              ai_ptr->ai_protocol);
190         if (cb->sock_fd < 0)
191             continue;
192
193         status = connect(cb->sock_fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
194         if (status != 0)
195         {
196             close(cb->sock_fd);
197             cb->sock_fd = -1;
198             continue;
199         }
200
201         break;
202     }
203
204     freeaddrinfo(ai_list);
205
206     if (cb->sock_fd < 0)
207     {
208         char errbuf[1024];
209         ERROR("write_tsdb plugin: Connecting to %s:%s failed. "
210               "The last error was: %s", node, service,
211               sstrerror (errno, errbuf, sizeof(errbuf)));
212         return -1;
213     }
214
215     wt_reset_buffer(cb);
216
217     return 0;
218 }
219
220 static void wt_callback_free(void *data)
221 {
222     struct wt_callback *cb;
223
224     if (data == NULL)
225         return;
226
227     cb = data;
228
229     pthread_mutex_lock(&cb->send_lock);
230
231     wt_flush_nolock(0, cb);
232
233     close(cb->sock_fd);
234     cb->sock_fd = -1;
235
236     sfree(cb->node);
237     sfree(cb->service);
238     sfree(cb->host_tags);
239
240     pthread_mutex_destroy(&cb->send_lock);
241
242     sfree(cb);
243 }
244
245 static int wt_flush(cdtime_t timeout,
246                     const char *identifier __attribute__((unused)),
247                     user_data_t *user_data)
248 {
249     struct wt_callback *cb;
250     int status;
251
252     if (user_data == NULL)
253         return -EINVAL;
254
255     cb = user_data->data;
256
257     pthread_mutex_lock(&cb->send_lock);
258
259     if (cb->sock_fd < 0)
260     {
261         status = wt_callback_init(cb);
262         if (status != 0)
263         {
264             ERROR("write_tsdb plugin: wt_callback_init failed.");
265             pthread_mutex_unlock(&cb->send_lock);
266             return -1;
267         }
268     }
269
270     status = wt_flush_nolock(timeout, cb);
271     pthread_mutex_unlock(&cb->send_lock);
272
273     return status;
274 }
275
276 static int wt_format_values(char *ret, size_t ret_len,
277                             int ds_num, const data_set_t *ds,
278                             const value_list_t *vl,
279                             _Bool store_rates)
280 {
281     size_t offset = 0;
282     int status;
283     gauge_t *rates = NULL;
284
285     assert(0 == strcmp (ds->type, vl->type));
286
287     memset(ret, 0, ret_len);
288
289 #define BUFFER_ADD(...) do { \
290         status = ssnprintf (ret + offset, ret_len - offset, \
291                             __VA_ARGS__); \
292         if (status < 1) \
293         { \
294             sfree(rates); \
295             return -1; \
296         } \
297         else if (((size_t) status) >= (ret_len - offset)) \
298         { \
299             sfree(rates); \
300             return -1; \
301         } \
302         else \
303             offset += ((size_t) status); \
304 } while (0)
305
306     if (ds->ds[ds_num].type == DS_TYPE_GAUGE)
307         BUFFER_ADD(GAUGE_FORMAT, vl->values[ds_num].gauge);
308     else if (store_rates)
309     {
310         if (rates == NULL)
311             rates = uc_get_rate (ds, vl);
312         if (rates == NULL)
313         {
314             WARNING("format_values: "
315                     "uc_get_rate failed.");
316             return -1;
317         }
318         BUFFER_ADD(GAUGE_FORMAT, rates[ds_num]);
319     }
320     else if (ds->ds[ds_num].type == DS_TYPE_COUNTER)
321         BUFFER_ADD("%llu", vl->values[ds_num].counter);
322     else if (ds->ds[ds_num].type == DS_TYPE_DERIVE)
323         BUFFER_ADD("%" PRIi64, vl->values[ds_num].derive);
324     else if (ds->ds[ds_num].type == DS_TYPE_ABSOLUTE)
325         BUFFER_ADD("%" PRIu64, vl->values[ds_num].absolute);
326     else
327     {
328         ERROR("format_values plugin: Unknown data source type: %i",
329               ds->ds[ds_num].type);
330         sfree(rates);
331         return -1;
332     }
333
334 #undef BUFFER_ADD
335
336     sfree(rates);
337     return 0;
338 }
339
340 static int wt_format_name(char *ret, int ret_len,
341                           const value_list_t *vl,
342                           const struct wt_callback *cb,
343                           const char *ds_name)
344 {
345     int status;
346     char *temp = NULL;
347     const char *prefix = "";
348     const char *meta_prefix = "tsdb_prefix";
349
350     if (vl->meta) {
351         status = meta_data_get_string(vl->meta, meta_prefix, &temp);
352         if (status == -ENOENT) {
353             /* defaults to empty string */
354         } else if (status < 0) {
355             sfree(temp);
356             return status;
357         } else {
358             prefix = temp;
359         }
360     }
361
362     if (ds_name != NULL) {
363         if (vl->plugin_instance[0] == '\0') {
364             if (vl->type_instance[0] == '\0') {
365                 ssnprintf(ret, ret_len, "%s%s.%s.%s", prefix, vl->plugin,
366                         vl->type, ds_name);
367             } else {
368                 ssnprintf(ret, ret_len, "%s%s.%s.%s.%s", prefix, vl->plugin,
369                         vl->type, vl->type_instance, ds_name);
370             }
371         } else { /* vl->plugin_instance != "" */
372             if (vl->type_instance[0] == '\0') {
373                 ssnprintf(ret, ret_len, "%s%s.%s.%s.%s", prefix, vl->plugin,
374                         vl->plugin_instance, vl->type, ds_name);
375             } else {
376                 ssnprintf(ret, ret_len, "%s%s.%s.%s.%s.%s", prefix,
377                         vl->plugin, vl->plugin_instance, vl->type,
378                         vl->type_instance, ds_name);
379             }
380         }
381     } else { /* ds_name == NULL */
382         if (vl->plugin_instance[0] == '\0') {
383             if (vl->type_instance[0] == '\0') {
384                 ssnprintf(ret, ret_len, "%s%s.%s", prefix, vl->plugin,
385                         vl->type);
386             } else {
387                 ssnprintf(ret, ret_len, "%s%s.%s.%s", prefix, vl->plugin,
388                         vl->type_instance, vl->type);
389             }
390         } else { /* vl->plugin_instance != "" */
391             if (vl->type_instance[0] == '\0') {
392                 ssnprintf(ret, ret_len, "%s%s.%s.%s", prefix, vl->plugin,
393                         vl->plugin_instance, vl->type);
394             } else {
395                 ssnprintf(ret, ret_len, "%s%s.%s.%s.%s", prefix, vl->plugin,
396                         vl->plugin_instance, vl->type, vl->type_instance);
397             }
398         }
399     }
400
401     sfree(temp);
402     return 0;
403 }
404
405 static int wt_send_message (const char* key, const char* value,
406                             cdtime_t time, struct wt_callback *cb,
407                             const char* host, meta_data_t *md)
408 {
409     int status;
410     size_t message_len;
411     char *temp = NULL;
412     const char *tags = "";
413     char message[1024];
414     const char *host_tags = cb->host_tags ? cb->host_tags : "";
415     const char *meta_tsdb = "tsdb_tags";
416
417     /* skip if value is NaN */
418     if (value[0] == 'n')
419         return 0;
420
421     if (md) {
422         status = meta_data_get_string(md, meta_tsdb, &temp);
423         if (status == -ENOENT) {
424             /* defaults to empty string */
425         } else if (status < 0) {
426             ERROR("write_tsdb plugin: tags metadata get failure");
427             sfree(temp);
428             pthread_mutex_unlock(&cb->send_lock);
429             return status;
430         } else {
431             tags = temp;
432         }
433     }
434
435     status = ssnprintf (message,
436                              sizeof(message),
437                              "put %s %.0f %s fqdn=%s %s %s\r\n",
438                              key,
439                              CDTIME_T_TO_DOUBLE(time),
440                              value,
441                              host,
442                              tags,
443                              host_tags);
444     sfree(temp);
445     if (status < 0)
446         return -1;
447     message_len = (size_t) status;
448
449     if (message_len >= sizeof(message)) {
450         ERROR("write_tsdb plugin: message buffer too small: "
451               "Need %zu bytes.", message_len + 1);
452         return -1;
453     }
454
455     pthread_mutex_lock(&cb->send_lock);
456
457     if (cb->sock_fd < 0)
458     {
459         status = wt_callback_init(cb);
460         if (status != 0)
461         {
462             ERROR("write_tsdb plugin: wt_callback_init failed.");
463             pthread_mutex_unlock(&cb->send_lock);
464             return -1;
465         }
466     }
467
468     if (message_len >= cb->send_buf_free)
469     {
470         status = wt_flush_nolock(0, cb);
471         if (status != 0)
472         {
473             pthread_mutex_unlock(&cb->send_lock);
474             return status;
475         }
476     }
477
478     /* Assert that we have enough space for this message. */
479     assert(message_len < cb->send_buf_free);
480
481     /* `message_len + 1' because `message_len' does not include the
482      * trailing null byte. Neither does `send_buffer_fill'. */
483     memcpy(cb->send_buf + cb->send_buf_fill,
484             message, message_len + 1);
485     cb->send_buf_fill += message_len;
486     cb->send_buf_free -= message_len;
487
488     DEBUG("write_tsdb plugin: [%s]:%s buf %zu/%zu (%.1f %%) \"%s\"",
489           cb->node,
490           cb->service,
491           cb->send_buf_fill, sizeof(cb->send_buf),
492           100.0 * ((double) cb->send_buf_fill) /
493           ((double) sizeof(cb->send_buf)),
494           message);
495
496     pthread_mutex_unlock(&cb->send_lock);
497
498     return 0;
499 }
500
501 static int wt_write_messages(const data_set_t *ds, const value_list_t *vl,
502                              struct wt_callback *cb)
503 {
504     char key[10*DATA_MAX_NAME_LEN];
505     char values[512];
506
507     int status;
508     size_t i;
509
510     if (0 != strcmp(ds->type, vl->type))
511     {
512         ERROR("write_tsdb plugin: DS type does not match "
513               "value list type");
514         return -1;
515     }
516
517     for (i = 0; i < ds->ds_num; i++)
518     {
519         const char *ds_name = NULL;
520
521         if (cb->always_append_ds || (ds->ds_num > 1))
522             ds_name = ds->ds[i].name;
523
524         /* Copy the identifier to 'key' and escape it. */
525         status = wt_format_name(key, sizeof(key), vl, cb, ds_name);
526         if (status != 0)
527         {
528             ERROR("write_tsdb plugin: error with format_name");
529             return status;
530         }
531
532         escape_string(key, sizeof(key));
533         /* Convert the values to an ASCII representation and put that into
534          * 'values'. */
535         status = wt_format_values(values, sizeof(values), i, ds, vl,
536                                   cb->store_rates);
537         if (status != 0)
538         {
539             ERROR("write_tsdb plugin: error with "
540                   "wt_format_values");
541             return status;
542         }
543
544         /* Send the message to tsdb */
545         status = wt_send_message(key, values, vl->time, cb, vl->host, vl->meta);
546         if (status != 0)
547         {
548             ERROR("write_tsdb plugin: error with "
549                   "wt_send_message");
550             return status;
551         }
552     }
553
554     return 0;
555 }
556
557 static int wt_write(const data_set_t *ds, const value_list_t *vl,
558                     user_data_t *user_data)
559 {
560     struct wt_callback *cb;
561     int status;
562
563     if (user_data == NULL)
564         return EINVAL;
565
566     cb = user_data->data;
567
568     status = wt_write_messages(ds, vl, cb);
569
570     return status;
571 }
572
573 static int wt_config_tsd(oconfig_item_t *ci)
574 {
575     struct wt_callback *cb;
576     user_data_t user_data = { 0 };
577     char callback_name[DATA_MAX_NAME_LEN];
578     int i;
579
580     cb = calloc(1, sizeof(*cb));
581     if (cb == NULL)
582     {
583         ERROR("write_tsdb plugin: calloc failed.");
584         return -1;
585     }
586     cb->sock_fd = -1;
587     cb->node = NULL;
588     cb->service = NULL;
589     cb->host_tags = NULL;
590     cb->store_rates = 0;
591
592     pthread_mutex_init (&cb->send_lock, NULL);
593
594     for (i = 0; i < ci->children_num; i++)
595     {
596         oconfig_item_t *child = ci->children + i;
597
598         if (strcasecmp("Host", child->key) == 0)
599             cf_util_get_string(child, &cb->node);
600         else if (strcasecmp("Port", child->key) == 0)
601             cf_util_get_service(child, &cb->service);
602         else if (strcasecmp("HostTags", child->key) == 0)
603             cf_util_get_string(child, &cb->host_tags);
604         else if (strcasecmp("StoreRates", child->key) == 0)
605             cf_util_get_boolean(child, &cb->store_rates);
606         else if (strcasecmp("AlwaysAppendDS", child->key) == 0)
607             cf_util_get_boolean(child, &cb->always_append_ds);
608         else
609         {
610             ERROR("write_tsdb plugin: Invalid configuration "
611                   "option: %s.", child->key);
612         }
613     }
614
615     ssnprintf(callback_name, sizeof(callback_name), "write_tsdb/%s/%s",
616               cb->node != NULL ? cb->node : WT_DEFAULT_NODE,
617               cb->service != NULL ? cb->service : WT_DEFAULT_SERVICE);
618
619     user_data.data = cb;
620     user_data.free_func = wt_callback_free;
621     plugin_register_write(callback_name, wt_write, &user_data);
622
623     user_data.free_func = NULL;
624     plugin_register_flush(callback_name, wt_flush, &user_data);
625
626     return 0;
627 }
628
629 static int wt_config(oconfig_item_t *ci)
630 {
631     int i;
632
633     for (i = 0; i < ci->children_num; i++)
634     {
635         oconfig_item_t *child = ci->children + i;
636
637         if (strcasecmp("Node", child->key) == 0)
638             wt_config_tsd(child);
639         else
640         {
641             ERROR("write_tsdb plugin: Invalid configuration "
642                   "option: %s.", child->key);
643         }
644     }
645
646     return 0;
647 }
648
649 void module_register(void)
650 {
651     plugin_register_complex_config("write_tsdb", wt_config);
652 }
653
654 /* vim: set sw=4 ts=4 sts=4 tw=78 et : */