write_http plugin: Create one cURL object for each read-thread.
[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-2009  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 verplant.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 /*
40  * Private variables
41  */
42 struct wh_callback_s
43 {
44         char *location;
45
46         char *user;
47         char *pass;
48         char *credentials;
49         int   verify_peer;
50         int   verify_host;
51         char *cacert;
52
53 #define WH_FORMAT_COMMAND 0
54 #define WH_FORMAT_JSON    1
55         int format;
56
57         char   send_buffer[4096];
58         size_t send_buffer_free;
59         size_t send_buffer_fill;
60         time_t send_buffer_init_time;
61
62         pthread_mutex_t send_lock;
63 };
64 typedef struct wh_callback_s wh_callback_t;
65
66 struct wh_curl_s
67 {
68         CURL *curl;
69         char errbuf[CURL_ERROR_SIZE];
70 };
71 typedef struct wh_curl_s wh_curl_t;
72
73 static pthread_once_t curl_key_init = PTHREAD_ONCE_INIT;
74 static pthread_key_t curl_key;
75
76 static void wh_curl_destroy (void *data) /* {{{ */
77 {
78         wh_curl_t *c = data;
79
80         if (c == NULL)
81                 return;
82
83         DEBUG ("write_http plugin: Destroying a cURL object.");
84
85         curl_easy_cleanup (c->curl);
86         sfree (c);
87 } /* }}} void wh_curl_destroy */
88
89 static void wh_curl_init (void) /* {{{ */
90 {
91         pthread_key_create(&curl_key, wh_curl_destroy);
92 } /* }}} void wh_curl_init */
93
94 static wh_curl_t *wh_curl_get (wh_callback_t *cb) /* {{{ */
95 {
96         struct curl_slist *headers;
97         wh_curl_t *c;
98
99         pthread_once (&curl_key_init, wh_curl_init);
100
101         c = pthread_getspecific (curl_key);
102         if (c != NULL)
103                 return (c);
104
105         DEBUG ("write_http plugin: Creating a cURL object.");
106
107         c = malloc (sizeof (*c));
108         if (c == NULL)
109         {
110                 ERROR ("write_http plugin: malloc failed.");
111                 return (NULL);
112         }
113         memset (c, 0, sizeof (*c));
114
115         c->curl = curl_easy_init ();
116         if (c->curl == NULL)
117         {
118                 ERROR ("write_http plugin: curl_easy_init failed.");
119                 sfree (c);
120                 return (NULL);
121         }
122
123         curl_easy_setopt (c->curl, CURLOPT_USERAGENT, PACKAGE_NAME"/"PACKAGE_VERSION);
124
125         /* The fields from `cb' we read here are only written to at
126          * configuration time, therefore it's safe to read them without a
127          * lock. */
128         headers = NULL;
129         headers = curl_slist_append (headers, "Accept:  */*");
130         if (cb->format == WH_FORMAT_JSON)
131                 headers = curl_slist_append (headers, "Content-Type: application/json");
132         else
133                 headers = curl_slist_append (headers, "Content-Type: text/plain");
134         headers = curl_slist_append (headers, "Expect:");
135         curl_easy_setopt (c->curl, CURLOPT_HTTPHEADER, headers);
136
137         curl_easy_setopt (c->curl, CURLOPT_ERRORBUFFER, c->errbuf);
138         curl_easy_setopt (c->curl, CURLOPT_URL, cb->location);
139
140         if (cb->credentials != NULL)
141                 curl_easy_setopt (c->curl, CURLOPT_USERPWD, cb->credentials);
142
143         curl_easy_setopt (c->curl, CURLOPT_SSL_VERIFYPEER, cb->verify_peer);
144         curl_easy_setopt (c->curl, CURLOPT_SSL_VERIFYHOST,
145                         cb->verify_host ? 2 : 0);
146         if (cb->cacert != NULL)
147                 curl_easy_setopt (c->curl, CURLOPT_CAINFO, cb->cacert);
148
149         pthread_setspecific (curl_key, c);
150
151         return (c);
152 } /* }}} int wh_curl_get */
153
154 static void wh_reset_buffer (wh_callback_t *cb)  /* {{{ */
155 {
156         memset (cb->send_buffer, 0, sizeof (cb->send_buffer));
157         cb->send_buffer_free = sizeof (cb->send_buffer);
158         cb->send_buffer_fill = 0;
159         cb->send_buffer_init_time = time (NULL);
160
161         if (cb->format == WH_FORMAT_JSON)
162         {
163                 format_json_initialize (cb->send_buffer,
164                                 &cb->send_buffer_fill,
165                                 &cb->send_buffer_free);
166         }
167 } /* }}} wh_reset_buffer */
168
169 static int wh_send_buffer (wh_callback_t *cb, /* {{{ */
170                 const char *buffer)
171 {
172         int status = 0;
173         wh_curl_t *c;
174
175         c = wh_curl_get (cb);
176         if (c == NULL)
177                 return (-1);
178
179         curl_easy_setopt (c->curl, CURLOPT_POSTFIELDS, buffer);
180         status = curl_easy_perform (c->curl);
181         if (status != 0)
182         {
183                 ERROR ("write_http plugin: curl_easy_perform failed with "
184                                 "status %i: %s",
185                                 status, c->errbuf);
186         }
187
188         return (status);
189 } /* }}} wh_send_buffer */
190
191 /* You must hold cb->send_lock when entering `wh_flush_nolock'. */
192 static int wh_flush_nolock (int timeout, wh_callback_t *cb) /* {{{ */
193 {
194         char buffer[sizeof (cb->send_buffer)];
195         int status;
196
197         DEBUG ("write_http plugin: wh_flush_nolock: timeout = %i; "
198                         "send_buffer_fill = %zu;",
199                         timeout, cb->send_buffer_fill);
200
201         if (timeout > 0)
202         {
203                 time_t now;
204
205                 now = time (NULL);
206                 if ((cb->send_buffer_init_time + timeout) > now)
207                         return (0);
208         }
209
210         /* Finalize the send buffer and copy it to `buffer'. */
211         if (cb->format == WH_FORMAT_COMMAND)
212         {
213                 if (cb->send_buffer_fill <= 0)
214                 {
215                         cb->send_buffer_init_time = time (NULL);
216                         return (0);
217                 }
218
219                 memcpy (buffer, cb->send_buffer, sizeof (buffer));
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 = time (NULL);
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                 memcpy (buffer, cb->send_buffer, sizeof (buffer));
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         /* We copied the send buffer to `buffer' and reset it so we can do
253          * without the `send_lock' here. This allows other read-threads to
254          * append stuff to the new buffer while we wait for the web-server to
255          * reply. */
256         pthread_mutex_unlock (&cb->send_lock);
257         status = wh_send_buffer (cb, buffer);
258         pthread_mutex_lock (&cb->send_lock);
259
260         return (status);
261 } /* }}} wh_flush_nolock */
262
263 static int wh_flush (int timeout, /* {{{ */
264                 const char *identifier __attribute__((unused)),
265                 user_data_t *user_data)
266 {
267         wh_callback_t *cb;
268         int status;
269
270         if (user_data == NULL)
271                 return (-EINVAL);
272
273         cb = user_data->data;
274
275         pthread_mutex_lock (&cb->send_lock);
276         status = wh_flush_nolock (timeout, cb);
277         pthread_mutex_unlock (&cb->send_lock);
278
279         return (status);
280 } /* }}} int wh_flush */
281
282 static void wh_callback_free (void *data) /* {{{ */
283 {
284         wh_callback_t *cb;
285
286         if (data == NULL)
287                 return;
288
289         cb = data;
290
291         wh_flush_nolock (/* timeout = */ -1, cb);
292
293         sfree (cb->location);
294         sfree (cb->user);
295         sfree (cb->pass);
296         sfree (cb->credentials);
297         sfree (cb->cacert);
298
299         sfree (cb);
300 } /* }}} void wh_callback_free */
301
302 static int wh_value_list_to_string (char *buffer, /* {{{ */
303                 size_t buffer_size,
304                 const data_set_t *ds, const value_list_t *vl)
305 {
306         size_t offset = 0;
307         int status;
308         int i;
309
310         assert (0 == strcmp (ds->type, vl->type));
311
312         memset (buffer, 0, buffer_size);
313
314 #define BUFFER_ADD(...) do { \
315         status = ssnprintf (buffer + offset, buffer_size - offset, \
316                         __VA_ARGS__); \
317         if (status < 1) \
318                 return (-1); \
319         else if (((size_t) status) >= (buffer_size - offset)) \
320                 return (-1); \
321         else \
322                 offset += ((size_t) status); \
323 } while (0)
324
325         BUFFER_ADD ("%lu", (unsigned long) vl->time);
326
327         for (i = 0; i < ds->ds_num; i++)
328 {
329         if (ds->ds[i].type == DS_TYPE_GAUGE)
330                 BUFFER_ADD (":%f", vl->values[i].gauge);
331         else if (ds->ds[i].type == DS_TYPE_COUNTER)
332                 BUFFER_ADD (":%llu", vl->values[i].counter);
333         else if (ds->ds[i].type == DS_TYPE_DERIVE)
334                 BUFFER_ADD (":%"PRIi64, vl->values[i].derive);
335         else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
336                 BUFFER_ADD (":%"PRIu64, vl->values[i].absolute);
337         else
338         {
339                 ERROR ("write_http plugin: Unknown data source type: %i",
340                                 ds->ds[i].type);
341                 return (-1);
342         }
343 } /* for ds->ds_num */
344
345 #undef BUFFER_ADD
346
347 return (0);
348 } /* }}} int wh_value_list_to_string */
349
350 static int wh_write_command (const data_set_t *ds, const value_list_t *vl, /* {{{ */
351                 wh_callback_t *cb)
352 {
353         char key[10*DATA_MAX_NAME_LEN];
354         char values[512];
355         char command[1024];
356         size_t command_len;
357
358         int status;
359
360         if (0 != strcmp (ds->type, vl->type)) {
361                 ERROR ("write_http plugin: DS type does not match "
362                                 "value list type");
363                 return -1;
364         }
365
366         /* Copy the identifier to `key' and escape it. */
367         status = FORMAT_VL (key, sizeof (key), vl);
368         if (status != 0) {
369                 ERROR ("write_http plugin: error with format_name");
370                 return (status);
371         }
372         escape_string (key, sizeof (key));
373
374         /* Convert the values to an ASCII representation and put that into
375          * `values'. */
376         status = wh_value_list_to_string (values, sizeof (values), ds, vl);
377         if (status != 0) {
378                 ERROR ("write_http plugin: error with "
379                                 "wh_value_list_to_string");
380                 return (status);
381         }
382
383         command_len = (size_t) ssnprintf (command, sizeof (command),
384                         "PUTVAL %s interval=%i %s\r\n",
385                         key, vl->interval, values);
386         if (command_len >= sizeof (command)) {
387                 ERROR ("write_http plugin: Command buffer too small: "
388                                 "Need %zu bytes.", command_len + 1);
389                 return (-1);
390         }
391
392         pthread_mutex_lock (&cb->send_lock);
393
394         if (command_len >= cb->send_buffer_free)
395         {
396                 status = wh_flush_nolock (/* timeout = */ -1, cb);
397                 if (status != 0)
398                 {
399                         pthread_mutex_unlock (&cb->send_lock);
400                         return (status);
401                 }
402         }
403         assert (command_len < cb->send_buffer_free);
404
405         /* `command_len + 1' because `command_len' does not include the
406          * trailing null byte. Neither does `send_buffer_fill'. */
407         memcpy (cb->send_buffer + cb->send_buffer_fill,
408                         command, command_len + 1);
409         cb->send_buffer_fill += command_len;
410         cb->send_buffer_free -= command_len;
411
412         DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%) \"%s\"",
413                         cb->location,
414                         cb->send_buffer_fill, sizeof (cb->send_buffer),
415                         100.0 * ((double) cb->send_buffer_fill) / ((double) sizeof (cb->send_buffer)),
416                         command);
417
418         /* Check if we have enough space for this command. */
419         pthread_mutex_unlock (&cb->send_lock);
420
421         return (0);
422 } /* }}} int wh_write_command */
423
424 static int wh_write_json (const data_set_t *ds, const value_list_t *vl, /* {{{ */
425                 wh_callback_t *cb)
426 {
427         int status;
428
429         pthread_mutex_lock (&cb->send_lock);
430
431         status = format_json_value_list (cb->send_buffer,
432                         &cb->send_buffer_fill,
433                         &cb->send_buffer_free,
434                         ds, vl);
435         if (status == (-ENOMEM))
436         {
437                 status = wh_flush_nolock (/* timeout = */ -1, cb);
438                 if (status != 0)
439                 {
440                         wh_reset_buffer (cb);
441                         pthread_mutex_unlock (&cb->send_lock);
442                         return (status);
443                 }
444
445                 status = format_json_value_list (cb->send_buffer,
446                                 &cb->send_buffer_fill,
447                                 &cb->send_buffer_free,
448                                 ds, vl);
449         }
450         if (status != 0)
451         {
452                 pthread_mutex_unlock (&cb->send_lock);
453                 return (status);
454         }
455
456         DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%)",
457                         cb->location,
458                         cb->send_buffer_fill, sizeof (cb->send_buffer),
459                         100.0 * ((double) cb->send_buffer_fill) / ((double) sizeof (cb->send_buffer)));
460
461         /* Check if we have enough space for this command. */
462         pthread_mutex_unlock (&cb->send_lock);
463
464         return (0);
465 } /* }}} int wh_write_json */
466
467 static int wh_write (const data_set_t *ds, const value_list_t *vl, /* {{{ */
468                 user_data_t *user_data)
469 {
470         wh_callback_t *cb;
471         int status;
472
473         if (user_data == NULL)
474                 return (-EINVAL);
475
476         cb = user_data->data;
477
478         if (cb->format == WH_FORMAT_JSON)
479                 status = wh_write_json (ds, vl, cb);
480         else
481                 status = wh_write_command (ds, vl, cb);
482
483         return (status);
484 } /* }}} int wh_write */
485
486 static int config_set_string (char **ret_string, /* {{{ */
487                 oconfig_item_t *ci)
488 {
489         char *string;
490
491         if ((ci->values_num != 1)
492                         || (ci->values[0].type != OCONFIG_TYPE_STRING))
493         {
494                 WARNING ("write_http plugin: The `%s' config option "
495                                 "needs exactly one string argument.", ci->key);
496                 return (-1);
497         }
498
499         string = strdup (ci->values[0].value.string);
500         if (string == NULL)
501         {
502                 ERROR ("write_http plugin: strdup failed.");
503                 return (-1);
504         }
505
506         if (*ret_string != NULL)
507                 free (*ret_string);
508         *ret_string = string;
509
510         return (0);
511 } /* }}} int config_set_string */
512
513 static int config_set_boolean (int *dest, oconfig_item_t *ci) /* {{{ */
514 {
515         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_BOOLEAN))
516         {
517                 WARNING ("write_http plugin: The `%s' config option "
518                                 "needs exactly one boolean argument.", ci->key);
519                 return (-1);
520         }
521
522         *dest = ci->values[0].value.boolean ? 1 : 0;
523
524         return (0);
525 } /* }}} int config_set_boolean */
526
527 static int config_set_format (wh_callback_t *cb, /* {{{ */
528                 oconfig_item_t *ci)
529 {
530         char *string;
531
532         if ((ci->values_num != 1)
533                         || (ci->values[0].type != OCONFIG_TYPE_STRING))
534         {
535                 WARNING ("write_http plugin: The `%s' config option "
536                                 "needs exactly one string argument.", ci->key);
537                 return (-1);
538         }
539
540         string = ci->values[0].value.string;
541         if (strcasecmp ("Command", string) == 0)
542                 cb->format = WH_FORMAT_COMMAND;
543         else if (strcasecmp ("JSON", string) == 0)
544                 cb->format = WH_FORMAT_JSON;
545         else
546         {
547                 ERROR ("write_http plugin: Invalid format string: %s",
548                                 string);
549                 return (-1);
550         }
551
552         return (0);
553 } /* }}} int config_set_string */
554
555 static int wh_config_url (oconfig_item_t *ci) /* {{{ */
556 {
557         wh_callback_t *cb;
558         user_data_t user_data;
559         int i;
560
561         cb = malloc (sizeof (*cb));
562         if (cb == NULL)
563         {
564                 ERROR ("write_http plugin: malloc failed.");
565                 return (-1);
566         }
567         memset (cb, 0, sizeof (*cb));
568         cb->location = NULL;
569         cb->user = NULL;
570         cb->pass = NULL;
571         cb->credentials = NULL;
572         cb->verify_peer = 1;
573         cb->verify_host = 1;
574         cb->cacert = NULL;
575         cb->format = WH_FORMAT_COMMAND;
576
577         pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
578
579         config_set_string (&cb->location, ci);
580         if (cb->location == NULL)
581                 return (-1);
582
583         for (i = 0; i < ci->children_num; i++)
584         {
585                 oconfig_item_t *child = ci->children + i;
586
587                 if (strcasecmp ("User", child->key) == 0)
588                         config_set_string (&cb->user, child);
589                 else if (strcasecmp ("Password", child->key) == 0)
590                         config_set_string (&cb->pass, child);
591                 else if (strcasecmp ("VerifyPeer", child->key) == 0)
592                         config_set_boolean (&cb->verify_peer, child);
593                 else if (strcasecmp ("VerifyHost", child->key) == 0)
594                         config_set_boolean (&cb->verify_host, child);
595                 else if (strcasecmp ("CACert", child->key) == 0)
596                         config_set_string (&cb->cacert, child);
597                 else if (strcasecmp ("Format", child->key) == 0)
598                         config_set_format (cb, child);
599                 else
600                 {
601                         ERROR ("write_http plugin: Invalid configuration "
602                                         "option: %s.", child->key);
603                 }
604         }
605
606         DEBUG ("write_http: Registering write callback with URL %s",
607                         cb->location);
608
609         if (cb->user != NULL)
610         {
611                 size_t credentials_size;
612
613                 credentials_size = strlen (cb->user) + 2;
614                 if (cb->pass != NULL)
615                         credentials_size += strlen (cb->pass);
616
617                 cb->credentials = (char *) malloc (credentials_size);
618                 if (cb->credentials == NULL)
619                 {
620                         ERROR ("write_http plugin: malloc failed.");
621                         return (-1);
622                 }
623
624                 ssnprintf (cb->credentials, credentials_size, "%s:%s",
625                                 cb->user, (cb->pass == NULL) ? "" : cb->pass);
626         }
627
628         wh_reset_buffer (cb);
629
630         memset (&user_data, 0, sizeof (user_data));
631         user_data.data = cb;
632         user_data.free_func = NULL;
633         plugin_register_flush ("write_http", wh_flush, &user_data);
634
635         user_data.free_func = wh_callback_free;
636         plugin_register_write ("write_http", wh_write, &user_data);
637
638         return (0);
639 } /* }}} int wh_config_url */
640
641 static int wh_config (oconfig_item_t *ci) /* {{{ */
642 {
643         int i;
644
645         for (i = 0; i < ci->children_num; i++)
646         {
647                 oconfig_item_t *child = ci->children + i;
648
649                 if (strcasecmp ("URL", child->key) == 0)
650                         wh_config_url (child);
651                 else
652                 {
653                         ERROR ("write_http plugin: Invalid configuration "
654                                         "option: %s.", child->key);
655                 }
656         }
657
658         return (0);
659 } /* }}} int wh_config */
660
661 void module_register (void) /* {{{ */
662 {
663         plugin_register_complex_config ("write_http", wh_config);
664 } /* }}} void module_register */
665
666 /* vim: set fdm=marker sw=8 ts=8 tw=78 et : */