log_logstash: adapt JSON format to logstash 1.2+
[collectd.git] / src / write_http.c
1 /**
2  * collectd - src/write_http.c
3  * Copyright (C) 2009       Paul Sadauskas
4  * Copyright (C) 2009       Doug MacEachern
5  * Copyright (C) 2007-2014  Florian octo Forster
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; only version 2 of the License is applicable.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  *
20  * Authors:
21  *   Florian octo Forster <octo at collectd.org>
22  *   Doug MacEachern <dougm@hyperic.com>
23  *   Paul Sadauskas <psadauskas@gmail.com>
24  **/
25
26 #include "collectd.h"
27 #include "plugin.h"
28 #include "common.h"
29 #include "utils_cache.h"
30 #include "utils_format_json.h"
31
32 #if HAVE_PTHREAD_H
33 # include <pthread.h>
34 #endif
35
36 #include <curl/curl.h>
37
38 #ifndef WRITE_HTTP_DEFAULT_BUFFER_SIZE
39 # define WRITE_HTTP_DEFAULT_BUFFER_SIZE 4096
40 #endif
41
42 /*
43  * Private variables
44  */
45 struct wh_callback_s
46 {
47         char *name;
48
49         char *location;
50         char *user;
51         char *pass;
52         char *credentials;
53         _Bool verify_peer;
54         _Bool verify_host;
55         char *cacert;
56         char *capath;
57         char *clientkey;
58         char *clientcert;
59         char *clientkeypass;
60         long sslversion;
61         _Bool store_rates;
62
63 #define WH_FORMAT_COMMAND 0
64 #define WH_FORMAT_JSON    1
65         int format;
66
67         CURL *curl;
68         char curl_errbuf[CURL_ERROR_SIZE];
69
70         char  *send_buffer;
71         size_t send_buffer_size;
72         size_t send_buffer_free;
73         size_t send_buffer_fill;
74         cdtime_t send_buffer_init_time;
75
76         pthread_mutex_t send_lock;
77 };
78 typedef struct wh_callback_s wh_callback_t;
79
80 static void wh_reset_buffer (wh_callback_t *cb)  /* {{{ */
81 {
82         memset (cb->send_buffer, 0, cb->send_buffer_size);
83         cb->send_buffer_free = cb->send_buffer_size;
84         cb->send_buffer_fill = 0;
85         cb->send_buffer_init_time = cdtime ();
86
87         if (cb->format == WH_FORMAT_JSON)
88         {
89                 format_json_initialize (cb->send_buffer,
90                                 &cb->send_buffer_fill,
91                                 &cb->send_buffer_free);
92         }
93 } /* }}} wh_reset_buffer */
94
95 static int wh_send_buffer (wh_callback_t *cb) /* {{{ */
96 {
97         int status = 0;
98
99         curl_easy_setopt (cb->curl, CURLOPT_POSTFIELDS, cb->send_buffer);
100         status = curl_easy_perform (cb->curl);
101         if (status != CURLE_OK)
102         {
103                 ERROR ("write_http plugin: curl_easy_perform failed with "
104                                 "status %i: %s",
105                                 status, cb->curl_errbuf);
106         }
107         return (status);
108 } /* }}} wh_send_buffer */
109
110 static int wh_callback_init (wh_callback_t *cb) /* {{{ */
111 {
112         struct curl_slist *headers;
113
114         if (cb->curl != NULL)
115                 return (0);
116
117         cb->curl = curl_easy_init ();
118         if (cb->curl == NULL)
119         {
120                 ERROR ("curl plugin: curl_easy_init failed.");
121                 return (-1);
122         }
123
124         curl_easy_setopt (cb->curl, CURLOPT_NOSIGNAL, 1L);
125         curl_easy_setopt (cb->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
126
127         headers = NULL;
128         headers = curl_slist_append (headers, "Accept:  */*");
129         if (cb->format == WH_FORMAT_JSON)
130                 headers = curl_slist_append (headers, "Content-Type: application/json");
131         else
132                 headers = curl_slist_append (headers, "Content-Type: text/plain");
133         headers = curl_slist_append (headers, "Expect:");
134         curl_easy_setopt (cb->curl, CURLOPT_HTTPHEADER, headers);
135
136         curl_easy_setopt (cb->curl, CURLOPT_ERRORBUFFER, cb->curl_errbuf);
137         curl_easy_setopt (cb->curl, CURLOPT_URL, cb->location);
138         curl_easy_setopt (cb->curl, CURLOPT_FOLLOWLOCATION, 1L);
139         curl_easy_setopt (cb->curl, CURLOPT_MAXREDIRS, 50L);
140
141         if (cb->user != NULL)
142         {
143 #ifdef HAVE_CURLOPT_USERNAME
144                 curl_easy_setopt (cb->curl, CURLOPT_USERNAME, cb->user);
145                 curl_easy_setopt (cb->curl, CURLOPT_PASSWORD,
146                         (cb->pass == NULL) ? "" : cb->pass);
147 #else
148                 size_t credentials_size;
149
150                 credentials_size = strlen (cb->user) + 2;
151                 if (cb->pass != NULL)
152                         credentials_size += strlen (cb->pass);
153
154                 cb->credentials = (char *) malloc (credentials_size);
155                 if (cb->credentials == NULL)
156                 {
157                         ERROR ("curl plugin: malloc failed.");
158                         return (-1);
159                 }
160
161                 ssnprintf (cb->credentials, credentials_size, "%s:%s",
162                                 cb->user, (cb->pass == NULL) ? "" : cb->pass);
163                 curl_easy_setopt (cb->curl, CURLOPT_USERPWD, cb->credentials);
164 #endif
165                 curl_easy_setopt (cb->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
166         }
167
168         curl_easy_setopt (cb->curl, CURLOPT_SSL_VERIFYPEER, (long) cb->verify_peer);
169         curl_easy_setopt (cb->curl, CURLOPT_SSL_VERIFYHOST,
170                         cb->verify_host ? 2L : 0L);
171         curl_easy_setopt (cb->curl, CURLOPT_SSLVERSION, cb->sslversion);
172         if (cb->cacert != NULL)
173                 curl_easy_setopt (cb->curl, CURLOPT_CAINFO, cb->cacert);
174         if (cb->capath != NULL)
175                 curl_easy_setopt (cb->curl, CURLOPT_CAPATH, cb->capath);
176
177         if (cb->clientkey != NULL && cb->clientcert != NULL)
178         {
179             curl_easy_setopt (cb->curl, CURLOPT_SSLKEY, cb->clientkey);
180             curl_easy_setopt (cb->curl, CURLOPT_SSLCERT, cb->clientcert);
181
182             if (cb->clientkeypass != NULL)
183                 curl_easy_setopt (cb->curl, CURLOPT_SSLKEYPASSWD, cb->clientkeypass);
184         }
185
186         wh_reset_buffer (cb);
187
188         return (0);
189 } /* }}} int wh_callback_init */
190
191 static int wh_flush_nolock (cdtime_t timeout, wh_callback_t *cb) /* {{{ */
192 {
193         int status;
194
195         DEBUG ("write_http plugin: wh_flush_nolock: timeout = %.3f; "
196                         "send_buffer_fill = %zu;",
197                         CDTIME_T_TO_DOUBLE (timeout),
198                         cb->send_buffer_fill);
199
200         /* timeout == 0  => flush unconditionally */
201         if (timeout > 0)
202         {
203                 cdtime_t now;
204
205                 now = cdtime ();
206                 if ((cb->send_buffer_init_time + timeout) > now)
207                         return (0);
208         }
209
210         if (cb->format == WH_FORMAT_COMMAND)
211         {
212                 if (cb->send_buffer_fill <= 0)
213                 {
214                         cb->send_buffer_init_time = cdtime ();
215                         return (0);
216                 }
217
218                 status = wh_send_buffer (cb);
219                 wh_reset_buffer (cb);
220         }
221         else if (cb->format == WH_FORMAT_JSON)
222         {
223                 if (cb->send_buffer_fill <= 2)
224                 {
225                         cb->send_buffer_init_time = cdtime ();
226                         return (0);
227                 }
228
229                 status = format_json_finalize (cb->send_buffer,
230                                 &cb->send_buffer_fill,
231                                 &cb->send_buffer_free);
232                 if (status != 0)
233                 {
234                         ERROR ("write_http: wh_flush_nolock: "
235                                         "format_json_finalize failed.");
236                         wh_reset_buffer (cb);
237                         return (status);
238                 }
239
240                 status = wh_send_buffer (cb);
241                 wh_reset_buffer (cb);
242         }
243         else
244         {
245                 ERROR ("write_http: wh_flush_nolock: "
246                                 "Unknown format: %i",
247                                 cb->format);
248                 return (-1);
249         }
250
251         return (status);
252 } /* }}} wh_flush_nolock */
253
254 static int wh_flush (cdtime_t timeout, /* {{{ */
255                 const char *identifier __attribute__((unused)),
256                 user_data_t *user_data)
257 {
258         wh_callback_t *cb;
259         int status;
260
261         if (user_data == NULL)
262                 return (-EINVAL);
263
264         cb = user_data->data;
265
266         pthread_mutex_lock (&cb->send_lock);
267
268         if (cb->curl == NULL)
269         {
270                 status = wh_callback_init (cb);
271                 if (status != 0)
272                 {
273                         ERROR ("write_http plugin: wh_callback_init failed.");
274                         pthread_mutex_unlock (&cb->send_lock);
275                         return (-1);
276                 }
277         }
278
279         status = wh_flush_nolock (timeout, cb);
280         pthread_mutex_unlock (&cb->send_lock);
281
282         return (status);
283 } /* }}} int wh_flush */
284
285 static void wh_callback_free (void *data) /* {{{ */
286 {
287         wh_callback_t *cb;
288
289         if (data == NULL)
290                 return;
291
292         cb = data;
293
294         wh_flush_nolock (/* timeout = */ 0, cb);
295
296         if (cb->curl != NULL)
297         {
298                 curl_easy_cleanup (cb->curl);
299                 cb->curl = NULL;
300         }
301         sfree (cb->name);
302         sfree (cb->location);
303         sfree (cb->user);
304         sfree (cb->pass);
305         sfree (cb->credentials);
306         sfree (cb->cacert);
307         sfree (cb->capath);
308         sfree (cb->clientkey);
309         sfree (cb->clientcert);
310         sfree (cb->clientkeypass);
311         sfree (cb->send_buffer);
312
313         sfree (cb);
314 } /* }}} void wh_callback_free */
315
316 static int wh_write_command (const data_set_t *ds, const value_list_t *vl, /* {{{ */
317                 wh_callback_t *cb)
318 {
319         char key[10*DATA_MAX_NAME_LEN];
320         char values[512];
321         char command[1024];
322         size_t command_len;
323
324         int status;
325
326         if (0 != strcmp (ds->type, vl->type)) {
327                 ERROR ("write_http plugin: DS type does not match "
328                                 "value list type");
329                 return -1;
330         }
331
332         /* Copy the identifier to `key' and escape it. */
333         status = FORMAT_VL (key, sizeof (key), vl);
334         if (status != 0) {
335                 ERROR ("write_http plugin: error with format_name");
336                 return (status);
337         }
338         escape_string (key, sizeof (key));
339
340         /* Convert the values to an ASCII representation and put that into
341          * `values'. */
342         status = format_values (values, sizeof (values), ds, vl, cb->store_rates);
343         if (status != 0) {
344                 ERROR ("write_http plugin: error with "
345                                 "wh_value_list_to_string");
346                 return (status);
347         }
348
349         command_len = (size_t) ssnprintf (command, sizeof (command),
350                         "PUTVAL %s interval=%.3f %s\r\n",
351                         key,
352                         CDTIME_T_TO_DOUBLE (vl->interval),
353                         values);
354         if (command_len >= sizeof (command)) {
355                 ERROR ("write_http plugin: Command buffer too small: "
356                                 "Need %zu bytes.", command_len + 1);
357                 return (-1);
358         }
359
360         pthread_mutex_lock (&cb->send_lock);
361
362         if (cb->curl == NULL)
363         {
364                 status = wh_callback_init (cb);
365                 if (status != 0)
366                 {
367                         ERROR ("write_http plugin: wh_callback_init failed.");
368                         pthread_mutex_unlock (&cb->send_lock);
369                         return (-1);
370                 }
371         }
372
373         if (command_len >= cb->send_buffer_free)
374         {
375                 status = wh_flush_nolock (/* timeout = */ 0, cb);
376                 if (status != 0)
377                 {
378                         pthread_mutex_unlock (&cb->send_lock);
379                         return (status);
380                 }
381         }
382         assert (command_len < cb->send_buffer_free);
383
384         /* `command_len + 1' because `command_len' does not include the
385          * trailing null byte. Neither does `send_buffer_fill'. */
386         memcpy (cb->send_buffer + cb->send_buffer_fill,
387                         command, command_len + 1);
388         cb->send_buffer_fill += command_len;
389         cb->send_buffer_free -= command_len;
390
391         DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%) \"%s\"",
392                         cb->location,
393                         cb->send_buffer_fill, cb->send_buffer_size,
394                         100.0 * ((double) cb->send_buffer_fill) / ((double) cb->send_buffer_size),
395                         command);
396
397         /* Check if we have enough space for this command. */
398         pthread_mutex_unlock (&cb->send_lock);
399
400         return (0);
401 } /* }}} int wh_write_command */
402
403 static int wh_write_json (const data_set_t *ds, const value_list_t *vl, /* {{{ */
404                 wh_callback_t *cb)
405 {
406         int status;
407
408         pthread_mutex_lock (&cb->send_lock);
409
410         if (cb->curl == NULL)
411         {
412                 status = wh_callback_init (cb);
413                 if (status != 0)
414                 {
415                         ERROR ("write_http plugin: wh_callback_init failed.");
416                         pthread_mutex_unlock (&cb->send_lock);
417                         return (-1);
418                 }
419         }
420
421         status = format_json_value_list (cb->send_buffer,
422                         &cb->send_buffer_fill,
423                         &cb->send_buffer_free,
424                         ds, vl, cb->store_rates);
425         if (status == (-ENOMEM))
426         {
427                 status = wh_flush_nolock (/* timeout = */ 0, cb);
428                 if (status != 0)
429                 {
430                         wh_reset_buffer (cb);
431                         pthread_mutex_unlock (&cb->send_lock);
432                         return (status);
433                 }
434
435                 status = format_json_value_list (cb->send_buffer,
436                                 &cb->send_buffer_fill,
437                                 &cb->send_buffer_free,
438                                 ds, vl, cb->store_rates);
439         }
440         if (status != 0)
441         {
442                 pthread_mutex_unlock (&cb->send_lock);
443                 return (status);
444         }
445
446         DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%)",
447                         cb->location,
448                         cb->send_buffer_fill, cb->send_buffer_size,
449                         100.0 * ((double) cb->send_buffer_fill) / ((double) cb->send_buffer_size));
450
451         /* Check if we have enough space for this command. */
452         pthread_mutex_unlock (&cb->send_lock);
453
454         return (0);
455 } /* }}} int wh_write_json */
456
457 static int wh_write (const data_set_t *ds, const value_list_t *vl, /* {{{ */
458                 user_data_t *user_data)
459 {
460         wh_callback_t *cb;
461         int status;
462
463         if (user_data == NULL)
464                 return (-EINVAL);
465
466         cb = user_data->data;
467
468         if (cb->format == WH_FORMAT_JSON)
469                 status = wh_write_json (ds, vl, cb);
470         else
471                 status = wh_write_command (ds, vl, cb);
472
473         return (status);
474 } /* }}} int wh_write */
475
476 static int config_set_format (wh_callback_t *cb, /* {{{ */
477                 oconfig_item_t *ci)
478 {
479         char *string;
480
481         if ((ci->values_num != 1)
482                         || (ci->values[0].type != OCONFIG_TYPE_STRING))
483         {
484                 WARNING ("write_http plugin: The `%s' config option "
485                                 "needs exactly one string argument.", ci->key);
486                 return (-1);
487         }
488
489         string = ci->values[0].value.string;
490         if (strcasecmp ("Command", string) == 0)
491                 cb->format = WH_FORMAT_COMMAND;
492         else if (strcasecmp ("JSON", string) == 0)
493                 cb->format = WH_FORMAT_JSON;
494         else
495         {
496                 ERROR ("write_http plugin: Invalid format string: %s",
497                                 string);
498                 return (-1);
499         }
500
501         return (0);
502 } /* }}} int config_set_format */
503
504 static int wh_config_node (oconfig_item_t *ci) /* {{{ */
505 {
506         wh_callback_t *cb;
507         int buffer_size = 0;
508         user_data_t user_data;
509         char callback_name[DATA_MAX_NAME_LEN];
510         int i;
511
512         cb = malloc (sizeof (*cb));
513         if (cb == NULL)
514         {
515                 ERROR ("write_http plugin: malloc failed.");
516                 return (-1);
517         }
518         memset (cb, 0, sizeof (*cb));
519         cb->verify_peer = 1;
520         cb->verify_host = 1;
521         cb->format = WH_FORMAT_COMMAND;
522         cb->sslversion = CURL_SSLVERSION_DEFAULT;
523
524         pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
525
526         cf_util_get_string (ci, &cb->name);
527
528         /* FIXME: Remove this legacy mode in version 6. */
529         if (strcasecmp ("URL", ci->key) == 0)
530                 cf_util_get_string (ci, &cb->location);
531
532         for (i = 0; i < ci->children_num; i++)
533         {
534                 oconfig_item_t *child = ci->children + i;
535
536                 if (strcasecmp ("URL", child->key) == 0)
537                         cf_util_get_string (child, &cb->location);
538                 else if (strcasecmp ("User", child->key) == 0)
539                         cf_util_get_string (child, &cb->user);
540                 else if (strcasecmp ("Password", child->key) == 0)
541                         cf_util_get_string (child, &cb->pass);
542                 else if (strcasecmp ("VerifyPeer", child->key) == 0)
543                         cf_util_get_boolean (child, &cb->verify_peer);
544                 else if (strcasecmp ("VerifyHost", child->key) == 0)
545                         cf_util_get_boolean (child, &cb->verify_host);
546                 else if (strcasecmp ("CACert", child->key) == 0)
547                         cf_util_get_string (child, &cb->cacert);
548                 else if (strcasecmp ("CAPath", child->key) == 0)
549                         cf_util_get_string (child, &cb->capath);
550                 else if (strcasecmp ("ClientKey", child->key) == 0)
551                         cf_util_get_string (child, &cb->clientkey);
552                 else if (strcasecmp ("ClientCert", child->key) == 0)
553                         cf_util_get_string (child, &cb->clientcert);
554                 else if (strcasecmp ("ClientKeyPass", child->key) == 0)
555                         cf_util_get_string (child, &cb->clientkeypass);
556                 else if (strcasecmp ("SSLVersion", child->key) == 0)
557                 {
558                         char *value = NULL;
559
560                         cf_util_get_string (child, &value);
561
562                         if (value == NULL || strcasecmp ("default", value) == 0)
563                                 cb->sslversion = CURL_SSLVERSION_DEFAULT;
564                         else if (strcasecmp ("SSLv2", value) == 0)
565                                 cb->sslversion = CURL_SSLVERSION_SSLv2;
566                         else if (strcasecmp ("SSLv3", value) == 0)
567                                 cb->sslversion = CURL_SSLVERSION_SSLv3;
568                         else if (strcasecmp ("TLSv1", value) == 0)
569                                 cb->sslversion = CURL_SSLVERSION_TLSv1;
570 #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 34)
571                         else if (strcasecmp ("TLSv1_0", value) == 0)
572                                 cb->sslversion = CURL_SSLVERSION_TLSv1_0;
573                         else if (strcasecmp ("TLSv1_1", value) == 0)
574                                 cb->sslversion = CURL_SSLVERSION_TLSv1_1;
575                         else if (strcasecmp ("TLSv1_2", value) == 0)
576                                 cb->sslversion = CURL_SSLVERSION_TLSv1_2;
577 #endif
578                         else
579                                 ERROR ("write_http plugin: Invalid SSLVersion "
580                                                 "option: %s.", value);
581
582                         sfree(value);
583                 }
584                 else if (strcasecmp ("Format", child->key) == 0)
585                         config_set_format (cb, child);
586                 else if (strcasecmp ("StoreRates", child->key) == 0)
587                         cf_util_get_boolean (child, &cb->store_rates);
588                 else if (strcasecmp ("BufferSize", child->key) == 0)
589                         cf_util_get_int (child, &buffer_size);
590                 else
591                 {
592                         ERROR ("write_http plugin: Invalid configuration "
593                                         "option: %s.", child->key);
594                 }
595         }
596
597         if (cb->location == NULL)
598         {
599                 ERROR ("write_http plugin: no URL defined for instance '%s'",
600                         cb->name);
601                 wh_callback_free (cb);
602                 return (-1);
603         }
604
605         /* Determine send_buffer_size. */
606         cb->send_buffer_size = WRITE_HTTP_DEFAULT_BUFFER_SIZE;
607         if (buffer_size >= 1024)
608                 cb->send_buffer_size = (size_t) buffer_size;
609         else if (buffer_size != 0)
610                 ERROR ("write_http plugin: Ignoring invalid BufferSize setting (%d).",
611                                 buffer_size);
612
613         /* Allocate the buffer. */
614         cb->send_buffer = malloc (cb->send_buffer_size);
615         if (cb->send_buffer == NULL)
616         {
617                 ERROR ("write_http plugin: malloc(%zu) failed.", cb->send_buffer_size);
618                 wh_callback_free (cb);
619                 return (-1);
620         }
621         /* Nulls the buffer and sets ..._free and ..._fill. */
622         wh_reset_buffer (cb);
623
624         ssnprintf (callback_name, sizeof (callback_name), "write_http/%s",
625                         cb->name);
626         DEBUG ("write_http: Registering write callback '%s' with URL '%s'",
627                         callback_name, cb->location);
628
629         memset (&user_data, 0, sizeof (user_data));
630         user_data.data = cb;
631         user_data.free_func = NULL;
632         plugin_register_flush (callback_name, wh_flush, &user_data);
633
634         user_data.free_func = wh_callback_free;
635         plugin_register_write (callback_name, wh_write, &user_data);
636
637         return (0);
638 } /* }}} int wh_config_node */
639
640 static int wh_config (oconfig_item_t *ci) /* {{{ */
641 {
642         int i;
643
644         for (i = 0; i < ci->children_num; i++)
645         {
646                 oconfig_item_t *child = ci->children + i;
647
648                 if (strcasecmp ("Node", child->key) == 0)
649                         wh_config_node (child);
650                 /* FIXME: Remove this legacy mode in version 6. */
651                 else if (strcasecmp ("URL", child->key) == 0) {
652                         WARNING ("write_http plugin: Legacy <URL> block found. "
653                                 "Please use <Node> instead.");
654                         wh_config_node (child);
655                 }
656                 else
657                 {
658                         ERROR ("write_http plugin: Invalid configuration "
659                                         "option: %s.", child->key);
660                 }
661         }
662
663         return (0);
664 } /* }}} int wh_config */
665
666 static int wh_init (void) /* {{{ */
667 {
668         /* Call this while collectd is still single-threaded to avoid
669          * initialization issues in libgcrypt. */
670         curl_global_init (CURL_GLOBAL_SSL);
671         return (0);
672 } /* }}} int wh_init */
673
674 void module_register (void) /* {{{ */
675 {
676         plugin_register_complex_config ("write_http", wh_config);
677         plugin_register_init ("write_http", wh_init);
678 } /* }}} void module_register */
679
680 /* vim: set fdm=marker sw=8 ts=8 tw=78 et : */