Merge branch 'collectd-5.4'
[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_parse_option.h"
31 #include "utils_format_json.h"
32
33 #if HAVE_PTHREAD_H
34 # include <pthread.h>
35 #endif
36
37 #include <curl/curl.h>
38
39 #ifndef WRITE_HTTP_DEFAULT_BUFFER_SIZE
40 # define WRITE_HTTP_DEFAULT_BUFFER_SIZE 4096
41 #endif
42
43 /*
44  * Private variables
45  */
46 struct wh_callback_s
47 {
48         char *location;
49
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
139         if (cb->user != NULL)
140         {
141                 size_t credentials_size;
142
143                 credentials_size = strlen (cb->user) + 2;
144                 if (cb->pass != NULL)
145                         credentials_size += strlen (cb->pass);
146
147                 cb->credentials = (char *) malloc (credentials_size);
148                 if (cb->credentials == NULL)
149                 {
150                         ERROR ("curl plugin: malloc failed.");
151                         return (-1);
152                 }
153
154                 ssnprintf (cb->credentials, credentials_size, "%s:%s",
155                                 cb->user, (cb->pass == NULL) ? "" : cb->pass);
156                 curl_easy_setopt (cb->curl, CURLOPT_USERPWD, cb->credentials);
157                 curl_easy_setopt (cb->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
158         }
159
160         curl_easy_setopt (cb->curl, CURLOPT_SSL_VERIFYPEER, (long) cb->verify_peer);
161         curl_easy_setopt (cb->curl, CURLOPT_SSL_VERIFYHOST,
162                         cb->verify_host ? 2L : 0L);
163         curl_easy_setopt (cb->curl, CURLOPT_SSLVERSION, cb->sslversion);
164         if (cb->cacert != NULL)
165                 curl_easy_setopt (cb->curl, CURLOPT_CAINFO, cb->cacert);
166         if (cb->capath != NULL)
167                 curl_easy_setopt (cb->curl, CURLOPT_CAPATH, cb->capath);
168
169         if (cb->clientkey != NULL && cb->clientcert != NULL)
170         {
171             curl_easy_setopt (cb->curl, CURLOPT_SSLKEY, cb->clientkey);
172             curl_easy_setopt (cb->curl, CURLOPT_SSLCERT, cb->clientcert);
173
174             if (cb->clientkeypass != NULL)
175                 curl_easy_setopt (cb->curl, CURLOPT_SSLKEYPASSWD, cb->clientkeypass);
176         }
177
178         wh_reset_buffer (cb);
179
180         return (0);
181 } /* }}} int wh_callback_init */
182
183 static int wh_flush_nolock (cdtime_t timeout, wh_callback_t *cb) /* {{{ */
184 {
185         int status;
186
187         DEBUG ("write_http plugin: wh_flush_nolock: timeout = %.3f; "
188                         "send_buffer_fill = %zu;",
189                         CDTIME_T_TO_DOUBLE (timeout),
190                         cb->send_buffer_fill);
191
192         /* timeout == 0  => flush unconditionally */
193         if (timeout > 0)
194         {
195                 cdtime_t now;
196
197                 now = cdtime ();
198                 if ((cb->send_buffer_init_time + timeout) > now)
199                         return (0);
200         }
201
202         if (cb->format == WH_FORMAT_COMMAND)
203         {
204                 if (cb->send_buffer_fill <= 0)
205                 {
206                         cb->send_buffer_init_time = cdtime ();
207                         return (0);
208                 }
209
210                 status = wh_send_buffer (cb);
211                 wh_reset_buffer (cb);
212         }
213         else if (cb->format == WH_FORMAT_JSON)
214         {
215                 if (cb->send_buffer_fill <= 2)
216                 {
217                         cb->send_buffer_init_time = cdtime ();
218                         return (0);
219                 }
220
221                 status = format_json_finalize (cb->send_buffer,
222                                 &cb->send_buffer_fill,
223                                 &cb->send_buffer_free);
224                 if (status != 0)
225                 {
226                         ERROR ("write_http: wh_flush_nolock: "
227                                         "format_json_finalize failed.");
228                         wh_reset_buffer (cb);
229                         return (status);
230                 }
231
232                 status = wh_send_buffer (cb);
233                 wh_reset_buffer (cb);
234         }
235         else
236         {
237                 ERROR ("write_http: wh_flush_nolock: "
238                                 "Unknown format: %i",
239                                 cb->format);
240                 return (-1);
241         }
242
243         return (status);
244 } /* }}} wh_flush_nolock */
245
246 static int wh_flush (cdtime_t timeout, /* {{{ */
247                 const char *identifier __attribute__((unused)),
248                 user_data_t *user_data)
249 {
250         wh_callback_t *cb;
251         int status;
252
253         if (user_data == NULL)
254                 return (-EINVAL);
255
256         cb = user_data->data;
257
258         pthread_mutex_lock (&cb->send_lock);
259
260         if (cb->curl == NULL)
261         {
262                 status = wh_callback_init (cb);
263                 if (status != 0)
264                 {
265                         ERROR ("write_http plugin: wh_callback_init failed.");
266                         pthread_mutex_unlock (&cb->send_lock);
267                         return (-1);
268                 }
269         }
270
271         status = wh_flush_nolock (timeout, cb);
272         pthread_mutex_unlock (&cb->send_lock);
273
274         return (status);
275 } /* }}} int wh_flush */
276
277 static void wh_callback_free (void *data) /* {{{ */
278 {
279         wh_callback_t *cb;
280
281         if (data == NULL)
282                 return;
283
284         cb = data;
285
286         wh_flush_nolock (/* timeout = */ 0, cb);
287
288         if (cb->curl != NULL)
289         {
290                 curl_easy_cleanup (cb->curl);
291                 cb->curl = NULL;
292         }
293         sfree (cb->location);
294         sfree (cb->user);
295         sfree (cb->pass);
296         sfree (cb->credentials);
297         sfree (cb->cacert);
298         sfree (cb->capath);
299         sfree (cb->clientkey);
300         sfree (cb->clientcert);
301         sfree (cb->clientkeypass);
302         sfree (cb->send_buffer);
303
304         sfree (cb);
305 } /* }}} void wh_callback_free */
306
307 static int wh_write_command (const data_set_t *ds, const value_list_t *vl, /* {{{ */
308                 wh_callback_t *cb)
309 {
310         char key[10*DATA_MAX_NAME_LEN];
311         char values[512];
312         char command[1024];
313         size_t command_len;
314
315         int status;
316
317         if (0 != strcmp (ds->type, vl->type)) {
318                 ERROR ("write_http plugin: DS type does not match "
319                                 "value list type");
320                 return -1;
321         }
322
323         /* Copy the identifier to `key' and escape it. */
324         status = FORMAT_VL (key, sizeof (key), vl);
325         if (status != 0) {
326                 ERROR ("write_http plugin: error with format_name");
327                 return (status);
328         }
329         escape_string (key, sizeof (key));
330
331         /* Convert the values to an ASCII representation and put that into
332          * `values'. */
333         status = format_values (values, sizeof (values), ds, vl, cb->store_rates);
334         if (status != 0) {
335                 ERROR ("write_http plugin: error with "
336                                 "wh_value_list_to_string");
337                 return (status);
338         }
339
340         command_len = (size_t) ssnprintf (command, sizeof (command),
341                         "PUTVAL %s interval=%.3f %s\r\n",
342                         key,
343                         CDTIME_T_TO_DOUBLE (vl->interval),
344                         values);
345         if (command_len >= sizeof (command)) {
346                 ERROR ("write_http plugin: Command buffer too small: "
347                                 "Need %zu bytes.", command_len + 1);
348                 return (-1);
349         }
350
351         pthread_mutex_lock (&cb->send_lock);
352
353         if (cb->curl == NULL)
354         {
355                 status = wh_callback_init (cb);
356                 if (status != 0)
357                 {
358                         ERROR ("write_http plugin: wh_callback_init failed.");
359                         pthread_mutex_unlock (&cb->send_lock);
360                         return (-1);
361                 }
362         }
363
364         if (command_len >= cb->send_buffer_free)
365         {
366                 status = wh_flush_nolock (/* timeout = */ 0, cb);
367                 if (status != 0)
368                 {
369                         pthread_mutex_unlock (&cb->send_lock);
370                         return (status);
371                 }
372         }
373         assert (command_len < cb->send_buffer_free);
374
375         /* `command_len + 1' because `command_len' does not include the
376          * trailing null byte. Neither does `send_buffer_fill'. */
377         memcpy (cb->send_buffer + cb->send_buffer_fill,
378                         command, command_len + 1);
379         cb->send_buffer_fill += command_len;
380         cb->send_buffer_free -= command_len;
381
382         DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%) \"%s\"",
383                         cb->location,
384                         cb->send_buffer_fill, cb->send_buffer_size,
385                         100.0 * ((double) cb->send_buffer_fill) / ((double) cb->send_buffer_size),
386                         command);
387
388         /* Check if we have enough space for this command. */
389         pthread_mutex_unlock (&cb->send_lock);
390
391         return (0);
392 } /* }}} int wh_write_command */
393
394 static int wh_write_json (const data_set_t *ds, const value_list_t *vl, /* {{{ */
395                 wh_callback_t *cb)
396 {
397         int status;
398
399         pthread_mutex_lock (&cb->send_lock);
400
401         if (cb->curl == NULL)
402         {
403                 status = wh_callback_init (cb);
404                 if (status != 0)
405                 {
406                         ERROR ("write_http plugin: wh_callback_init failed.");
407                         pthread_mutex_unlock (&cb->send_lock);
408                         return (-1);
409                 }
410         }
411
412         status = format_json_value_list (cb->send_buffer,
413                         &cb->send_buffer_fill,
414                         &cb->send_buffer_free,
415                         ds, vl, cb->store_rates);
416         if (status == (-ENOMEM))
417         {
418                 status = wh_flush_nolock (/* timeout = */ 0, cb);
419                 if (status != 0)
420                 {
421                         wh_reset_buffer (cb);
422                         pthread_mutex_unlock (&cb->send_lock);
423                         return (status);
424                 }
425
426                 status = format_json_value_list (cb->send_buffer,
427                                 &cb->send_buffer_fill,
428                                 &cb->send_buffer_free,
429                                 ds, vl, cb->store_rates);
430         }
431         if (status != 0)
432         {
433                 pthread_mutex_unlock (&cb->send_lock);
434                 return (status);
435         }
436
437         DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%)",
438                         cb->location,
439                         cb->send_buffer_fill, cb->send_buffer_size,
440                         100.0 * ((double) cb->send_buffer_fill) / ((double) cb->send_buffer_size));
441
442         /* Check if we have enough space for this command. */
443         pthread_mutex_unlock (&cb->send_lock);
444
445         return (0);
446 } /* }}} int wh_write_json */
447
448 static int wh_write (const data_set_t *ds, const value_list_t *vl, /* {{{ */
449                 user_data_t *user_data)
450 {
451         wh_callback_t *cb;
452         int status;
453
454         if (user_data == NULL)
455                 return (-EINVAL);
456
457         cb = user_data->data;
458
459         if (cb->format == WH_FORMAT_JSON)
460                 status = wh_write_json (ds, vl, cb);
461         else
462                 status = wh_write_command (ds, vl, cb);
463
464         return (status);
465 } /* }}} int wh_write */
466
467 static int config_set_format (wh_callback_t *cb, /* {{{ */
468                 oconfig_item_t *ci)
469 {
470         char *string;
471
472         if ((ci->values_num != 1)
473                         || (ci->values[0].type != OCONFIG_TYPE_STRING))
474         {
475                 WARNING ("write_http plugin: The `%s' config option "
476                                 "needs exactly one string argument.", ci->key);
477                 return (-1);
478         }
479
480         string = ci->values[0].value.string;
481         if (strcasecmp ("Command", string) == 0)
482                 cb->format = WH_FORMAT_COMMAND;
483         else if (strcasecmp ("JSON", string) == 0)
484                 cb->format = WH_FORMAT_JSON;
485         else
486         {
487                 ERROR ("write_http plugin: Invalid format string: %s",
488                                 string);
489                 return (-1);
490         }
491
492         return (0);
493 } /* }}} int config_set_format */
494
495 static int wh_config_url (oconfig_item_t *ci) /* {{{ */
496 {
497         wh_callback_t *cb;
498         int buffer_size = 0;
499         user_data_t user_data;
500         int i;
501
502         cb = malloc (sizeof (*cb));
503         if (cb == NULL)
504         {
505                 ERROR ("write_http plugin: malloc failed.");
506                 return (-1);
507         }
508         memset (cb, 0, sizeof (*cb));
509         cb->verify_peer = 1;
510         cb->verify_host = 1;
511         cb->format = WH_FORMAT_COMMAND;
512         cb->sslversion = CURL_SSLVERSION_DEFAULT;
513
514         pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
515
516         cf_util_get_string (ci, &cb->location);
517         if (cb->location == NULL)
518                 return (-1);
519
520         for (i = 0; i < ci->children_num; i++)
521         {
522                 oconfig_item_t *child = ci->children + i;
523
524                 if (strcasecmp ("User", child->key) == 0)
525                         cf_util_get_string (child, &cb->user);
526                 else if (strcasecmp ("Password", child->key) == 0)
527                         cf_util_get_string (child, &cb->pass);
528                 else if (strcasecmp ("VerifyPeer", child->key) == 0)
529                         cf_util_get_boolean (child, &cb->verify_peer);
530                 else if (strcasecmp ("VerifyHost", child->key) == 0)
531                         cf_util_get_boolean (child, &cb->verify_host);
532                 else if (strcasecmp ("CACert", child->key) == 0)
533                         cf_util_get_string (child, &cb->cacert);
534                 else if (strcasecmp ("CAPath", child->key) == 0)
535                         cf_util_get_string (child, &cb->capath);
536                 else if (strcasecmp ("ClientKey", child->key) == 0)
537                         cf_util_get_string (child, &cb->clientkey);
538                 else if (strcasecmp ("ClientCert", child->key) == 0)
539                         cf_util_get_string (child, &cb->clientcert);
540                 else if (strcasecmp ("ClientKeyPass", child->key) == 0)
541                         cf_util_get_string (child, &cb->clientkeypass);
542                 else if (strcasecmp ("SSLVersion", child->key) == 0)
543                 {
544                         char *value = NULL;
545
546                         cf_util_get_string (child, &value);
547
548                         if (value == NULL || strcasecmp ("default", value) == 0)
549                                 cb->sslversion = CURL_SSLVERSION_DEFAULT;
550                         else if (strcasecmp ("SSLv2", value) == 0)
551                                 cb->sslversion = CURL_SSLVERSION_SSLv2;
552                         else if (strcasecmp ("SSLv3", value) == 0)
553                                 cb->sslversion = CURL_SSLVERSION_SSLv3;
554                         else if (strcasecmp ("TLSv1", value) == 0)
555                                 cb->sslversion = CURL_SSLVERSION_TLSv1;
556 #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 34)
557                         else if (strcasecmp ("TLSv1_0", value) == 0)
558                                 cb->sslversion = CURL_SSLVERSION_TLSv1_0;
559                         else if (strcasecmp ("TLSv1_1", value) == 0)
560                                 cb->sslversion = CURL_SSLVERSION_TLSv1_1;
561                         else if (strcasecmp ("TLSv1_2", value) == 0)
562                                 cb->sslversion = CURL_SSLVERSION_TLSv1_2;
563 #endif
564                         else
565                                 ERROR ("write_http plugin: Invalid SSLVersion "
566                                                 "option: %s.", value);
567
568                         sfree(value);
569                 }
570                 else if (strcasecmp ("Format", child->key) == 0)
571                         config_set_format (cb, child);
572                 else if (strcasecmp ("StoreRates", child->key) == 0)
573                         cf_util_get_boolean (child, &cb->store_rates);
574                 else if (strcasecmp ("BufferSize", child->key) == 0)
575                         cf_util_get_int (child, &buffer_size);
576                 else
577                 {
578                         ERROR ("write_http plugin: Invalid configuration "
579                                         "option: %s.", child->key);
580                 }
581         }
582
583         /* Determine send_buffer_size. */
584         cb->send_buffer_size = WRITE_HTTP_DEFAULT_BUFFER_SIZE;
585         if (buffer_size >= 1024)
586                 cb->send_buffer_size = (size_t) buffer_size;
587         else if (buffer_size != 0)
588                 ERROR ("write_http plugin: Ignoring invalid BufferSize setting (%d).",
589                                 buffer_size);
590
591         /* Allocate the buffer. */
592         cb->send_buffer = malloc (cb->send_buffer_size);
593         if (cb->send_buffer == NULL)
594         {
595                 ERROR ("write_http plugin: malloc(%zu) failed.", cb->send_buffer_size);
596                 wh_callback_free (cb);
597                 return (-1);
598         }
599         /* Nulls the buffer and sets ..._free and ..._fill. */
600         wh_reset_buffer (cb);
601
602         DEBUG ("write_http: Registering write callback with URL %s",
603                         cb->location);
604
605         memset (&user_data, 0, sizeof (user_data));
606         user_data.data = cb;
607         user_data.free_func = NULL;
608         plugin_register_flush ("write_http", wh_flush, &user_data);
609
610         user_data.free_func = wh_callback_free;
611         plugin_register_write ("write_http", wh_write, &user_data);
612
613         return (0);
614 } /* }}} int wh_config_url */
615
616 static int wh_config (oconfig_item_t *ci) /* {{{ */
617 {
618         int i;
619
620         for (i = 0; i < ci->children_num; i++)
621         {
622                 oconfig_item_t *child = ci->children + i;
623
624                 if (strcasecmp ("URL", child->key) == 0)
625                         wh_config_url (child);
626                 else
627                 {
628                         ERROR ("write_http plugin: Invalid configuration "
629                                         "option: %s.", child->key);
630                 }
631         }
632
633         return (0);
634 } /* }}} int wh_config */
635
636 static int wh_init (void) /* {{{ */
637 {
638         /* Call this while collectd is still single-threaded to avoid
639          * initialization issues in libgcrypt. */
640         curl_global_init (CURL_GLOBAL_SSL);
641         return (0);
642 } /* }}} int wh_init */
643
644 void module_register (void) /* {{{ */
645 {
646         plugin_register_complex_config ("write_http", wh_config);
647         plugin_register_init ("write_http", wh_init);
648 } /* }}} void module_register */
649
650 /* vim: set fdm=marker sw=8 ts=8 tw=78 et : */