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