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