cd0f949ce1a502facd637000ce36d2ac560f85e5
[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 #define WH_DEFAULT_LOW_LIMIT_BYTES_PER_SEC 100
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                 _Bool abort_on_slow;
63                 int   low_limit_bytes;
64         time_t interval;
65
66 #define WH_FORMAT_COMMAND 0
67 #define WH_FORMAT_JSON    1
68         int format;
69
70         CURL *curl;
71         char curl_errbuf[CURL_ERROR_SIZE];
72
73         char  *send_buffer;
74         size_t send_buffer_size;
75         size_t send_buffer_free;
76         size_t send_buffer_fill;
77         cdtime_t send_buffer_init_time;
78
79         pthread_mutex_t send_lock;
80 };
81 typedef struct wh_callback_s wh_callback_t;
82
83 static void wh_reset_buffer (wh_callback_t *cb)  /* {{{ */
84 {
85         memset (cb->send_buffer, 0, cb->send_buffer_size);
86         cb->send_buffer_free = cb->send_buffer_size;
87         cb->send_buffer_fill = 0;
88         cb->send_buffer_init_time = cdtime ();
89
90         if (cb->format == WH_FORMAT_JSON)
91         {
92                 format_json_initialize (cb->send_buffer,
93                                 &cb->send_buffer_fill,
94                                 &cb->send_buffer_free);
95         }
96 } /* }}} wh_reset_buffer */
97
98 static int wh_send_buffer (wh_callback_t *cb) /* {{{ */
99 {
100         int status = 0;
101
102         curl_easy_setopt (cb->curl, CURLOPT_POSTFIELDS, cb->send_buffer);
103         status = curl_easy_perform (cb->curl);
104         if (status != CURLE_OK)
105         {
106                 ERROR ("write_http plugin: curl_easy_perform failed with "
107                                 "status %i: %s",
108                                 status, cb->curl_errbuf);
109         }
110         return (status);
111 } /* }}} wh_send_buffer */
112
113 static int wh_callback_init (wh_callback_t *cb) /* {{{ */
114 {
115         struct curl_slist *headers;
116
117         if (cb->curl != NULL)
118                 return (0);
119
120         cb->curl = curl_easy_init ();
121         if (cb->curl == NULL)
122         {
123                 ERROR ("curl plugin: curl_easy_init failed.");
124                 return (-1);
125         }
126
127         if(cb->abort_on_slow && cb->interval > 0)
128         {
129             curl_easy_setopt(cb->curl, CURLOPT_LOW_SPEED_LIMIT, (cb->low_limit_bytes?cb->low_limit_bytes:WH_DEFAULT_LOW_LIMIT_BYTES_PER_SEC));
130             curl_easy_setopt(cb->curl, CURLOPT_LOW_SPEED_TIME, cb->interval);
131         }
132
133         curl_easy_setopt (cb->curl, CURLOPT_NOSIGNAL, 1L);
134         curl_easy_setopt (cb->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
135
136         headers = NULL;
137         headers = curl_slist_append (headers, "Accept:  */*");
138         if (cb->format == WH_FORMAT_JSON)
139                 headers = curl_slist_append (headers, "Content-Type: application/json");
140         else
141                 headers = curl_slist_append (headers, "Content-Type: text/plain");
142         headers = curl_slist_append (headers, "Expect:");
143         curl_easy_setopt (cb->curl, CURLOPT_HTTPHEADER, headers);
144
145         curl_easy_setopt (cb->curl, CURLOPT_ERRORBUFFER, cb->curl_errbuf);
146         curl_easy_setopt (cb->curl, CURLOPT_URL, cb->location);
147
148         if (cb->user != NULL)
149         {
150                 size_t credentials_size;
151
152                 credentials_size = strlen (cb->user) + 2;
153                 if (cb->pass != NULL)
154                         credentials_size += strlen (cb->pass);
155
156                 cb->credentials = (char *) malloc (credentials_size);
157                 if (cb->credentials == NULL)
158                 {
159                         ERROR ("curl plugin: malloc failed.");
160                         return (-1);
161                 }
162
163                 ssnprintf (cb->credentials, credentials_size, "%s:%s",
164                                 cb->user, (cb->pass == NULL) ? "" : cb->pass);
165                 curl_easy_setopt (cb->curl, CURLOPT_USERPWD, cb->credentials);
166                 curl_easy_setopt (cb->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
167         }
168
169         curl_easy_setopt (cb->curl, CURLOPT_SSL_VERIFYPEER, (long) cb->verify_peer);
170         curl_easy_setopt (cb->curl, CURLOPT_SSL_VERIFYHOST,
171                         cb->verify_host ? 2L : 0L);
172         curl_easy_setopt (cb->curl, CURLOPT_SSLVERSION, cb->sslversion);
173         if (cb->cacert != NULL)
174                 curl_easy_setopt (cb->curl, CURLOPT_CAINFO, cb->cacert);
175         if (cb->capath != NULL)
176                 curl_easy_setopt (cb->curl, CURLOPT_CAPATH, cb->capath);
177
178         if (cb->clientkey != NULL && cb->clientcert != NULL)
179         {
180             curl_easy_setopt (cb->curl, CURLOPT_SSLKEY, cb->clientkey);
181             curl_easy_setopt (cb->curl, CURLOPT_SSLCERT, cb->clientcert);
182
183             if (cb->clientkeypass != NULL)
184                 curl_easy_setopt (cb->curl, CURLOPT_SSLKEYPASSWD, cb->clientkeypass);
185         }
186
187         wh_reset_buffer (cb);
188
189         return (0);
190 } /* }}} int wh_callback_init */
191
192 static int wh_flush_nolock (cdtime_t timeout, wh_callback_t *cb) /* {{{ */
193 {
194         int status;
195
196         DEBUG ("write_http plugin: wh_flush_nolock: timeout = %.3f; "
197                         "send_buffer_fill = %zu;",
198                         CDTIME_T_TO_DOUBLE (timeout),
199                         cb->send_buffer_fill);
200
201         /* timeout == 0  => flush unconditionally */
202         if (timeout > 0)
203         {
204                 cdtime_t now;
205
206                 now = cdtime ();
207                 if ((cb->send_buffer_init_time + timeout) > now)
208                         return (0);
209         }
210
211         if (cb->format == WH_FORMAT_COMMAND)
212         {
213                 if (cb->send_buffer_fill <= 0)
214                 {
215                         cb->send_buffer_init_time = cdtime ();
216                         return (0);
217                 }
218
219                 status = wh_send_buffer (cb);
220                 wh_reset_buffer (cb);
221         }
222         else if (cb->format == WH_FORMAT_JSON)
223         {
224                 if (cb->send_buffer_fill <= 2)
225                 {
226                         cb->send_buffer_init_time = cdtime ();
227                         return (0);
228                 }
229
230                 status = format_json_finalize (cb->send_buffer,
231                                 &cb->send_buffer_fill,
232                                 &cb->send_buffer_free);
233                 if (status != 0)
234                 {
235                         ERROR ("write_http: wh_flush_nolock: "
236                                         "format_json_finalize failed.");
237                         wh_reset_buffer (cb);
238                         return (status);
239                 }
240
241                 status = wh_send_buffer (cb);
242                 wh_reset_buffer (cb);
243         }
244         else
245         {
246                 ERROR ("write_http: wh_flush_nolock: "
247                                 "Unknown format: %i",
248                                 cb->format);
249                 return (-1);
250         }
251
252         return (status);
253 } /* }}} wh_flush_nolock */
254
255 static int wh_flush (cdtime_t timeout, /* {{{ */
256                 const char *identifier __attribute__((unused)),
257                 user_data_t *user_data)
258 {
259         wh_callback_t *cb;
260         int status;
261
262         if (user_data == NULL)
263                 return (-EINVAL);
264
265         cb = user_data->data;
266
267         pthread_mutex_lock (&cb->send_lock);
268
269         if (cb->curl == NULL)
270         {
271                 status = wh_callback_init (cb);
272                 if (status != 0)
273                 {
274                         ERROR ("write_http plugin: wh_callback_init failed.");
275                         pthread_mutex_unlock (&cb->send_lock);
276                         return (-1);
277                 }
278         }
279
280         status = wh_flush_nolock (timeout, cb);
281         pthread_mutex_unlock (&cb->send_lock);
282
283         return (status);
284 } /* }}} int wh_flush */
285
286 static void wh_callback_free (void *data) /* {{{ */
287 {
288         wh_callback_t *cb;
289
290         if (data == NULL)
291                 return;
292
293         cb = data;
294
295         wh_flush_nolock (/* timeout = */ 0, cb);
296
297         if (cb->curl != NULL)
298         {
299                 curl_easy_cleanup (cb->curl);
300                 cb->curl = NULL;
301         }
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                 cb->interval = CDTIME_T_TO_TIME_T(vl->interval);
361                 
362         pthread_mutex_lock (&cb->send_lock);
363
364         if (cb->curl == NULL)
365         {
366                 status = wh_callback_init (cb);
367                 if (status != 0)
368                 {
369                         ERROR ("write_http plugin: wh_callback_init failed.");
370                         pthread_mutex_unlock (&cb->send_lock);
371                         return (-1);
372                 }
373         }
374
375         if (command_len >= cb->send_buffer_free)
376         {
377                 status = wh_flush_nolock (/* timeout = */ 0, cb);
378                 if (status != 0)
379                 {
380                         pthread_mutex_unlock (&cb->send_lock);
381                         return (status);
382                 }
383         }
384         assert (command_len < cb->send_buffer_free);
385
386         /* `command_len + 1' because `command_len' does not include the
387          * trailing null byte. Neither does `send_buffer_fill'. */
388         memcpy (cb->send_buffer + cb->send_buffer_fill,
389                         command, command_len + 1);
390         cb->send_buffer_fill += command_len;
391         cb->send_buffer_free -= command_len;
392
393         DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%) \"%s\"",
394                         cb->location,
395                         cb->send_buffer_fill, cb->send_buffer_size,
396                         100.0 * ((double) cb->send_buffer_fill) / ((double) cb->send_buffer_size),
397                         command);
398
399         /* Check if we have enough space for this command. */
400         pthread_mutex_unlock (&cb->send_lock);
401
402         return (0);
403 } /* }}} int wh_write_command */
404
405 static int wh_write_json (const data_set_t *ds, const value_list_t *vl, /* {{{ */
406                 wh_callback_t *cb)
407 {
408         int status;
409                 
410                 cb->interval = CDTIME_T_TO_TIME_T(vl->interval);
411
412         pthread_mutex_lock (&cb->send_lock);
413
414         if (cb->curl == NULL)
415         {
416                 status = wh_callback_init (cb);
417                 if (status != 0)
418                 {
419                         ERROR ("write_http plugin: wh_callback_init failed.");
420                         pthread_mutex_unlock (&cb->send_lock);
421                         return (-1);
422                 }
423         }
424
425         status = format_json_value_list (cb->send_buffer,
426                         &cb->send_buffer_fill,
427                         &cb->send_buffer_free,
428                         ds, vl, cb->store_rates);
429         if (status == (-ENOMEM))
430         {
431                 status = wh_flush_nolock (/* timeout = */ 0, cb);
432                 if (status != 0)
433                 {
434                         wh_reset_buffer (cb);
435                         pthread_mutex_unlock (&cb->send_lock);
436                         return (status);
437                 }
438
439                 status = format_json_value_list (cb->send_buffer,
440                                 &cb->send_buffer_fill,
441                                 &cb->send_buffer_free,
442                                 ds, vl, cb->store_rates);
443         }
444         if (status != 0)
445         {
446                 pthread_mutex_unlock (&cb->send_lock);
447                 return (status);
448         }
449
450         DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%)",
451                         cb->location,
452                         cb->send_buffer_fill, cb->send_buffer_size,
453                         100.0 * ((double) cb->send_buffer_fill) / ((double) cb->send_buffer_size));
454
455         /* Check if we have enough space for this command. */
456         pthread_mutex_unlock (&cb->send_lock);
457
458         return (0);
459 } /* }}} int wh_write_json */
460
461 static int wh_write (const data_set_t *ds, const value_list_t *vl, /* {{{ */
462                 user_data_t *user_data)
463 {
464         wh_callback_t *cb;
465         int status;
466
467         if (user_data == NULL)
468                 return (-EINVAL);
469
470         cb = user_data->data;
471
472         if (cb->format == WH_FORMAT_JSON)
473                 status = wh_write_json (ds, vl, cb);
474         else
475                 status = wh_write_command (ds, vl, cb);
476
477         return (status);
478 } /* }}} int wh_write */
479
480 static int config_set_format (wh_callback_t *cb, /* {{{ */
481                 oconfig_item_t *ci)
482 {
483         char *string;
484
485         if ((ci->values_num != 1)
486                         || (ci->values[0].type != OCONFIG_TYPE_STRING))
487         {
488                 WARNING ("write_http plugin: The `%s' config option "
489                                 "needs exactly one string argument.", ci->key);
490                 return (-1);
491         }
492
493         string = ci->values[0].value.string;
494         if (strcasecmp ("Command", string) == 0)
495                 cb->format = WH_FORMAT_COMMAND;
496         else if (strcasecmp ("JSON", string) == 0)
497                 cb->format = WH_FORMAT_JSON;
498         else
499         {
500                 ERROR ("write_http plugin: Invalid format string: %s",
501                                 string);
502                 return (-1);
503         }
504
505         return (0);
506 } /* }}} int config_set_format */
507
508 static int wh_config_url (oconfig_item_t *ci) /* {{{ */
509 {
510         wh_callback_t *cb;
511         int buffer_size = 0;
512         user_data_t user_data;
513         int i;
514
515         cb = malloc (sizeof (*cb));
516         if (cb == NULL)
517         {
518                 ERROR ("write_http plugin: malloc failed.");
519                 return (-1);
520         }
521         memset (cb, 0, sizeof (*cb));
522         cb->verify_peer = 1;
523         cb->verify_host = 1;
524         cb->format = WH_FORMAT_COMMAND;
525         cb->sslversion = CURL_SSLVERSION_DEFAULT;
526                 cb->low_limit_bytes = WH_DEFAULT_LOW_LIMIT_BYTES_PER_SEC;
527
528         pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
529
530         cf_util_get_string (ci, &cb->location);
531         if (cb->location == NULL)
532                 return (-1);
533
534         for (i = 0; i < ci->children_num; i++)
535         {
536                 oconfig_item_t *child = ci->children + i;
537
538                 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 if (strcasecmp ("LowSpeedLimit", child->key) == 0)
591                         cf_util_get_boolean (child,&cb->abort_on_slow);
592                 else if (strcasecmp ("LowLimitBytesPerSec", child->key) == 0)
593                         cf_util_get_int (child, &cb->low_limit_bytes);
594                 else
595                 {
596                         ERROR ("write_http plugin: Invalid configuration "
597                                         "option: %s.", child->key);
598                 }
599         }
600
601         if(cb->abort_on_slow)
602         {
603                 cb->interval = CDTIME_T_TO_TIME_T(cf_get_default_interval ());
604         }
605
606         /* Determine send_buffer_size. */
607         cb->send_buffer_size = WRITE_HTTP_DEFAULT_BUFFER_SIZE;
608         if (buffer_size >= 1024)
609                 cb->send_buffer_size = (size_t) buffer_size;
610         else if (buffer_size != 0)
611                 ERROR ("write_http plugin: Ignoring invalid BufferSize setting (%d).",
612                                 buffer_size);
613
614         /* Allocate the buffer. */
615         cb->send_buffer = malloc (cb->send_buffer_size);
616         if (cb->send_buffer == NULL)
617         {
618                 ERROR ("write_http plugin: malloc(%zu) failed.", cb->send_buffer_size);
619                 wh_callback_free (cb);
620                 return (-1);
621         }
622         /* Nulls the buffer and sets ..._free and ..._fill. */
623         wh_reset_buffer (cb);
624
625         DEBUG ("write_http: Registering write callback with URL %s",
626                         cb->location);
627
628         memset (&user_data, 0, sizeof (user_data));
629         user_data.data = cb;
630         user_data.free_func = NULL;
631         plugin_register_flush ("write_http", wh_flush, &user_data);
632
633         user_data.free_func = wh_callback_free;
634         plugin_register_write ("write_http", wh_write, &user_data);
635
636         return (0);
637 } /* }}} int wh_config_url */
638
639 static int wh_config (oconfig_item_t *ci) /* {{{ */
640 {
641         int i;
642
643         for (i = 0; i < ci->children_num; i++)
644         {
645                 oconfig_item_t *child = ci->children + i;
646
647                 if (strcasecmp ("URL", child->key) == 0)
648                         wh_config_url (child);
649                 else
650                 {
651                         ERROR ("write_http plugin: Invalid configuration "
652                                         "option: %s.", child->key);
653                 }
654         }
655
656         return (0);
657 } /* }}} int wh_config */
658
659 static int wh_init (void) /* {{{ */
660 {
661         /* Call this while collectd is still single-threaded to avoid
662          * initialization issues in libgcrypt. */
663         curl_global_init (CURL_GLOBAL_SSL);
664         return (0);
665 } /* }}} int wh_init */
666
667 void module_register (void) /* {{{ */
668 {
669         plugin_register_complex_config ("write_http", wh_config);
670         plugin_register_init ("write_http", wh_init);
671 } /* }}} void module_register */
672
673 /* vim: set fdm=marker sw=8 ts=8 tw=78 et : */