80f42ab5b365801b195018b43e05e8bcf54bff43
[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 *location;
48
49         char *user;
50         char *pass;
51         char *credentials;
52         _Bool verify_peer;
53         _Bool verify_host;
54         char *cacert;
55         char *capath;
56         char *clientkey;
57         char *clientcert;
58         char *clientkeypass;
59         long sslversion;
60         _Bool store_rates;
61         int   abort_on_slow;
62         time_t interval;
63
64 #define WH_FORMAT_COMMAND 0
65 #define WH_FORMAT_JSON    1
66         int format;
67
68         CURL *curl;
69         char curl_errbuf[CURL_ERROR_SIZE];
70
71         char  *send_buffer;
72         size_t send_buffer_size;
73         size_t send_buffer_free;
74         size_t send_buffer_fill;
75         cdtime_t send_buffer_init_time;
76
77         pthread_mutex_t send_lock;
78 };
79 typedef struct wh_callback_s wh_callback_t;
80
81 static void wh_reset_buffer (wh_callback_t *cb)  /* {{{ */
82 {
83         memset (cb->send_buffer, 0, cb->send_buffer_size);
84         cb->send_buffer_free = cb->send_buffer_size;
85         cb->send_buffer_fill = 0;
86         cb->send_buffer_init_time = cdtime ();
87
88         if (cb->format == WH_FORMAT_JSON)
89         {
90                 format_json_initialize (cb->send_buffer,
91                                 &cb->send_buffer_fill,
92                                 &cb->send_buffer_free);
93         }
94 } /* }}} wh_reset_buffer */
95
96 static int wh_send_buffer (wh_callback_t *cb) /* {{{ */
97 {
98         int status = 0;
99
100         curl_easy_setopt (cb->curl, CURLOPT_POSTFIELDS, cb->send_buffer);
101         status = curl_easy_perform (cb->curl);
102         if (status != CURLE_OK)
103         {
104                 ERROR ("write_http plugin: curl_easy_perform failed with "
105                                 "status %i: %s",
106                                 status, cb->curl_errbuf);
107         }
108         return (status);
109 } /* }}} wh_send_buffer */
110
111 static int wh_callback_init (wh_callback_t *cb) /* {{{ */
112 {
113         struct curl_slist *headers;
114
115         if (cb->curl != NULL)
116                 return (0);
117
118         cb->curl = curl_easy_init ();
119         if (cb->curl == NULL)
120         {
121                 ERROR ("curl plugin: curl_easy_init failed.");
122                 return (-1);
123         }
124
125         if(cb->abort_on_slow && cb->interval > 0)
126         {
127             curl_easy_setopt(cb->curl, CURLOPT_LOW_SPEED_LIMIT, 100);
128             curl_easy_setopt(cb->curl, CURLOPT_LOW_SPEED_TIME, cb->interval);
129         }
130
131         curl_easy_setopt (cb->curl, CURLOPT_NOSIGNAL, 1L);
132         curl_easy_setopt (cb->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
133
134         headers = NULL;
135         headers = curl_slist_append (headers, "Accept:  */*");
136         if (cb->format == WH_FORMAT_JSON)
137                 headers = curl_slist_append (headers, "Content-Type: application/json");
138         else
139                 headers = curl_slist_append (headers, "Content-Type: text/plain");
140         headers = curl_slist_append (headers, "Expect:");
141         curl_easy_setopt (cb->curl, CURLOPT_HTTPHEADER, headers);
142
143         curl_easy_setopt (cb->curl, CURLOPT_ERRORBUFFER, cb->curl_errbuf);
144         curl_easy_setopt (cb->curl, CURLOPT_URL, cb->location);
145
146         if (cb->user != NULL)
147         {
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                 curl_easy_setopt (cb->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
165         }
166
167         curl_easy_setopt (cb->curl, CURLOPT_SSL_VERIFYPEER, (long) cb->verify_peer);
168         curl_easy_setopt (cb->curl, CURLOPT_SSL_VERIFYHOST,
169                         cb->verify_host ? 2L : 0L);
170         curl_easy_setopt (cb->curl, CURLOPT_SSLVERSION, cb->sslversion);
171         if (cb->cacert != NULL)
172                 curl_easy_setopt (cb->curl, CURLOPT_CAINFO, cb->cacert);
173         if (cb->capath != NULL)
174                 curl_easy_setopt (cb->curl, CURLOPT_CAPATH, cb->capath);
175
176         if (cb->clientkey != NULL && cb->clientcert != NULL)
177         {
178             curl_easy_setopt (cb->curl, CURLOPT_SSLKEY, cb->clientkey);
179             curl_easy_setopt (cb->curl, CURLOPT_SSLCERT, cb->clientcert);
180
181             if (cb->clientkeypass != NULL)
182                 curl_easy_setopt (cb->curl, CURLOPT_SSLKEYPASSWD, cb->clientkeypass);
183         }
184
185         wh_reset_buffer (cb);
186
187         return (0);
188 } /* }}} int wh_callback_init */
189
190 static int wh_flush_nolock (cdtime_t timeout, wh_callback_t *cb) /* {{{ */
191 {
192         int status;
193
194         DEBUG ("write_http plugin: wh_flush_nolock: timeout = %.3f; "
195                         "send_buffer_fill = %zu;",
196                         CDTIME_T_TO_DOUBLE (timeout),
197                         cb->send_buffer_fill);
198
199         /* timeout == 0  => flush unconditionally */
200         if (timeout > 0)
201         {
202                 cdtime_t now;
203
204                 now = cdtime ();
205                 if ((cb->send_buffer_init_time + timeout) > now)
206                         return (0);
207         }
208
209         if (cb->format == WH_FORMAT_COMMAND)
210         {
211                 if (cb->send_buffer_fill <= 0)
212                 {
213                         cb->send_buffer_init_time = cdtime ();
214                         return (0);
215                 }
216
217                 status = wh_send_buffer (cb);
218                 wh_reset_buffer (cb);
219         }
220         else if (cb->format == WH_FORMAT_JSON)
221         {
222                 if (cb->send_buffer_fill <= 2)
223                 {
224                         cb->send_buffer_init_time = cdtime ();
225                         return (0);
226                 }
227
228                 status = format_json_finalize (cb->send_buffer,
229                                 &cb->send_buffer_fill,
230                                 &cb->send_buffer_free);
231                 if (status != 0)
232                 {
233                         ERROR ("write_http: wh_flush_nolock: "
234                                         "format_json_finalize failed.");
235                         wh_reset_buffer (cb);
236                         return (status);
237                 }
238
239                 status = wh_send_buffer (cb);
240                 wh_reset_buffer (cb);
241         }
242         else
243         {
244                 ERROR ("write_http: wh_flush_nolock: "
245                                 "Unknown format: %i",
246                                 cb->format);
247                 return (-1);
248         }
249
250         return (status);
251 } /* }}} wh_flush_nolock */
252
253 static int wh_flush (cdtime_t timeout, /* {{{ */
254                 const char *identifier __attribute__((unused)),
255                 user_data_t *user_data)
256 {
257         wh_callback_t *cb;
258         int status;
259
260         if (user_data == NULL)
261                 return (-EINVAL);
262
263         cb = user_data->data;
264
265         pthread_mutex_lock (&cb->send_lock);
266
267         if (cb->curl == NULL)
268         {
269                 status = wh_callback_init (cb);
270                 if (status != 0)
271                 {
272                         ERROR ("write_http plugin: wh_callback_init failed.");
273                         pthread_mutex_unlock (&cb->send_lock);
274                         return (-1);
275                 }
276         }
277
278         status = wh_flush_nolock (timeout, cb);
279         pthread_mutex_unlock (&cb->send_lock);
280
281         return (status);
282 } /* }}} int wh_flush */
283
284 static void wh_callback_free (void *data) /* {{{ */
285 {
286         wh_callback_t *cb;
287
288         if (data == NULL)
289                 return;
290
291         cb = data;
292
293         wh_flush_nolock (/* timeout = */ 0, cb);
294
295         if (cb->curl != NULL)
296         {
297                 curl_easy_cleanup (cb->curl);
298                 cb->curl = NULL;
299         }
300         sfree (cb->location);
301         sfree (cb->user);
302         sfree (cb->pass);
303         sfree (cb->credentials);
304         sfree (cb->cacert);
305         sfree (cb->capath);
306         sfree (cb->clientkey);
307         sfree (cb->clientcert);
308         sfree (cb->clientkeypass);
309         sfree (cb->send_buffer);
310
311         sfree (cb);
312 } /* }}} void wh_callback_free */
313
314 static int wh_write_command (const data_set_t *ds, const value_list_t *vl, /* {{{ */
315                 wh_callback_t *cb)
316 {
317         char key[10*DATA_MAX_NAME_LEN];
318         char values[512];
319         char command[1024];
320         size_t command_len;
321
322         int status;
323
324         if (0 != strcmp (ds->type, vl->type)) {
325                 ERROR ("write_http plugin: DS type does not match "
326                                 "value list type");
327                 return -1;
328         }
329
330         /* Copy the identifier to `key' and escape it. */
331         status = FORMAT_VL (key, sizeof (key), vl);
332         if (status != 0) {
333                 ERROR ("write_http plugin: error with format_name");
334                 return (status);
335         }
336         escape_string (key, sizeof (key));
337
338         /* Convert the values to an ASCII representation and put that into
339          * `values'. */
340         status = format_values (values, sizeof (values), ds, vl, cb->store_rates);
341         if (status != 0) {
342                 ERROR ("write_http plugin: error with "
343                                 "wh_value_list_to_string");
344                 return (status);
345         }
346
347         command_len = (size_t) ssnprintf (command, sizeof (command),
348                         "PUTVAL %s interval=%.3f %s\r\n",
349                         key,
350                         CDTIME_T_TO_DOUBLE (vl->interval),
351                         values);
352         if (command_len >= sizeof (command)) {
353                 ERROR ("write_http plugin: Command buffer too small: "
354                                 "Need %zu bytes.", command_len + 1);
355                 return (-1);
356         }
357
358                 cb->interval = CDTIME_T_TO_TIME_T(vl->interval);
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                 cb->interval = CDTIME_T_TO_TIME_T(vl->interval);
409
410         pthread_mutex_lock (&cb->send_lock);
411
412         if (cb->curl == NULL)
413         {
414                 status = wh_callback_init (cb);
415                 if (status != 0)
416                 {
417                         ERROR ("write_http plugin: wh_callback_init failed.");
418                         pthread_mutex_unlock (&cb->send_lock);
419                         return (-1);
420                 }
421         }
422
423         status = format_json_value_list (cb->send_buffer,
424                         &cb->send_buffer_fill,
425                         &cb->send_buffer_free,
426                         ds, vl, cb->store_rates);
427         if (status == (-ENOMEM))
428         {
429                 status = wh_flush_nolock (/* timeout = */ 0, cb);
430                 if (status != 0)
431                 {
432                         wh_reset_buffer (cb);
433                         pthread_mutex_unlock (&cb->send_lock);
434                         return (status);
435                 }
436
437                 status = format_json_value_list (cb->send_buffer,
438                                 &cb->send_buffer_fill,
439                                 &cb->send_buffer_free,
440                                 ds, vl, cb->store_rates);
441         }
442         if (status != 0)
443         {
444                 pthread_mutex_unlock (&cb->send_lock);
445                 return (status);
446         }
447
448         DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%)",
449                         cb->location,
450                         cb->send_buffer_fill, cb->send_buffer_size,
451                         100.0 * ((double) cb->send_buffer_fill) / ((double) cb->send_buffer_size));
452
453         /* Check if we have enough space for this command. */
454         pthread_mutex_unlock (&cb->send_lock);
455
456         return (0);
457 } /* }}} int wh_write_json */
458
459 static int wh_write (const data_set_t *ds, const value_list_t *vl, /* {{{ */
460                 user_data_t *user_data)
461 {
462         wh_callback_t *cb;
463         int status;
464
465         if (user_data == NULL)
466                 return (-EINVAL);
467
468         cb = user_data->data;
469
470         if (cb->format == WH_FORMAT_JSON)
471                 status = wh_write_json (ds, vl, cb);
472         else
473                 status = wh_write_command (ds, vl, cb);
474
475         return (status);
476 } /* }}} int wh_write */
477
478 static int config_set_format (wh_callback_t *cb, /* {{{ */
479                 oconfig_item_t *ci)
480 {
481         char *string;
482
483         if ((ci->values_num != 1)
484                         || (ci->values[0].type != OCONFIG_TYPE_STRING))
485         {
486                 WARNING ("write_http plugin: The `%s' config option "
487                                 "needs exactly one string argument.", ci->key);
488                 return (-1);
489         }
490
491         string = ci->values[0].value.string;
492         if (strcasecmp ("Command", string) == 0)
493                 cb->format = WH_FORMAT_COMMAND;
494         else if (strcasecmp ("JSON", string) == 0)
495                 cb->format = WH_FORMAT_JSON;
496         else
497         {
498                 ERROR ("write_http plugin: Invalid format string: %s",
499                                 string);
500                 return (-1);
501         }
502
503         return (0);
504 } /* }}} int config_set_format */
505
506 static int wh_config_url (oconfig_item_t *ci) /* {{{ */
507 {
508         wh_callback_t *cb;
509         int buffer_size = 0;
510         user_data_t user_data;
511         int i;
512
513         cb = malloc (sizeof (*cb));
514         if (cb == NULL)
515         {
516                 ERROR ("write_http plugin: malloc failed.");
517                 return (-1);
518         }
519         memset (cb, 0, sizeof (*cb));
520         cb->verify_peer = 1;
521         cb->verify_host = 1;
522         cb->format = WH_FORMAT_COMMAND;
523         cb->sslversion = CURL_SSLVERSION_DEFAULT;
524
525         pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
526
527         cf_util_get_string (ci, &cb->location);
528         if (cb->location == NULL)
529                 return (-1);
530
531         for (i = 0; i < ci->children_num; i++)
532         {
533                 oconfig_item_t *child = ci->children + i;
534
535                 if (strcasecmp ("User", child->key) == 0)
536                         cf_util_get_string (child, &cb->user);
537                 else if (strcasecmp ("Password", child->key) == 0)
538                         cf_util_get_string (child, &cb->pass);
539                 else if (strcasecmp ("VerifyPeer", child->key) == 0)
540                         cf_util_get_boolean (child, &cb->verify_peer);
541                 else if (strcasecmp ("VerifyHost", child->key) == 0)
542                         cf_util_get_boolean (child, &cb->verify_host);
543                 else if (strcasecmp ("CACert", child->key) == 0)
544                         cf_util_get_string (child, &cb->cacert);
545                 else if (strcasecmp ("CAPath", child->key) == 0)
546                         cf_util_get_string (child, &cb->capath);
547                 else if (strcasecmp ("ClientKey", child->key) == 0)
548                         cf_util_get_string (child, &cb->clientkey);
549                 else if (strcasecmp ("ClientCert", child->key) == 0)
550                         cf_util_get_string (child, &cb->clientcert);
551                 else if (strcasecmp ("ClientKeyPass", child->key) == 0)
552                         cf_util_get_string (child, &cb->clientkeypass);
553                 else if (strcasecmp ("SSLVersion", child->key) == 0)
554                 {
555                         char *value = NULL;
556
557                         cf_util_get_string (child, &value);
558
559                         if (value == NULL || strcasecmp ("default", value) == 0)
560                                 cb->sslversion = CURL_SSLVERSION_DEFAULT;
561                         else if (strcasecmp ("SSLv2", value) == 0)
562                                 cb->sslversion = CURL_SSLVERSION_SSLv2;
563                         else if (strcasecmp ("SSLv3", value) == 0)
564                                 cb->sslversion = CURL_SSLVERSION_SSLv3;
565                         else if (strcasecmp ("TLSv1", value) == 0)
566                                 cb->sslversion = CURL_SSLVERSION_TLSv1;
567 #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 34)
568                         else if (strcasecmp ("TLSv1_0", value) == 0)
569                                 cb->sslversion = CURL_SSLVERSION_TLSv1_0;
570                         else if (strcasecmp ("TLSv1_1", value) == 0)
571                                 cb->sslversion = CURL_SSLVERSION_TLSv1_1;
572                         else if (strcasecmp ("TLSv1_2", value) == 0)
573                                 cb->sslversion = CURL_SSLVERSION_TLSv1_2;
574 #endif
575                         else
576                                 ERROR ("write_http plugin: Invalid SSLVersion "
577                                                 "option: %s.", value);
578
579                         sfree(value);
580                 }
581                 else if (strcasecmp ("Format", child->key) == 0)
582                         config_set_format (cb, child);
583                 else if (strcasecmp ("StoreRates", child->key) == 0)
584                         cf_util_get_boolean (child, &cb->store_rates);
585                 else if (strcasecmp ("BufferSize", child->key) == 0)
586                         cf_util_get_int (child, &buffer_size);
587                     else if (strcasecmp ("LowSpeedLimit", child->key) == 0)
588                         config_set_boolean (&cb->abort_on_slow, child);
589                 else
590                 {
591                         ERROR ("write_http plugin: Invalid configuration "
592                                         "option: %s.", child->key);
593                 }
594         }
595
596         if(cb->abort_on_slow)
597         {
598                 cb->interval = CDTIME_T_TO_TIME_T(cf_get_default_interval ());
599         }
600
601         /* Determine send_buffer_size. */
602         cb->send_buffer_size = WRITE_HTTP_DEFAULT_BUFFER_SIZE;
603         if (buffer_size >= 1024)
604                 cb->send_buffer_size = (size_t) buffer_size;
605         else if (buffer_size != 0)
606                 ERROR ("write_http plugin: Ignoring invalid BufferSize setting (%d).",
607                                 buffer_size);
608
609         /* Allocate the buffer. */
610         cb->send_buffer = malloc (cb->send_buffer_size);
611         if (cb->send_buffer == NULL)
612         {
613                 ERROR ("write_http plugin: malloc(%zu) failed.", cb->send_buffer_size);
614                 wh_callback_free (cb);
615                 return (-1);
616         }
617         /* Nulls the buffer and sets ..._free and ..._fill. */
618         wh_reset_buffer (cb);
619
620         DEBUG ("write_http: Registering write callback with URL %s",
621                         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 ("write_http", wh_flush, &user_data);
627
628         user_data.free_func = wh_callback_free;
629         plugin_register_write ("write_http", wh_write, &user_data);
630
631         return (0);
632 } /* }}} int wh_config_url */
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 ("URL", child->key) == 0)
643                         wh_config_url (child);
644                 else
645                 {
646                         ERROR ("write_http plugin: Invalid configuration "
647                                         "option: %s.", child->key);
648                 }
649         }
650
651         return (0);
652 } /* }}} int wh_config */
653
654 static int wh_init (void) /* {{{ */
655 {
656         /* Call this while collectd is still single-threaded to avoid
657          * initialization issues in libgcrypt. */
658         curl_global_init (CURL_GLOBAL_SSL);
659         return (0);
660 } /* }}} int wh_init */
661
662 void module_register (void) /* {{{ */
663 {
664         plugin_register_complex_config ("write_http", wh_config);
665         plugin_register_init ("write_http", wh_init);
666 } /* }}} void module_register */
667
668 /* vim: set fdm=marker sw=8 ts=8 tw=78 et : */