2 * collectd - src/curl_json.c
3 * Copyright (C) 2009 Doug MacEachern
4 * Copyright (C) 2006-2011 Florian octo Forster
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; only version 2 of the License is applicable.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 * Doug MacEachern <dougm at hyperic.com>
21 * Florian octo Forster <octo at collectd.org>
27 #include "configfile.h"
28 #include "utils_avltree.h"
29 #include "utils_complain.h"
31 #include <curl/curl.h>
32 #include <yajl/yajl_parse.h>
33 #if HAVE_YAJL_YAJL_VERSION_H
34 # include <yajl/yajl_version.h>
37 #if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
38 # define HAVE_YAJL_V2 1
41 #define CJ_DEFAULT_HOST "localhost"
42 #define CJ_KEY_MAGIC 0x43484b59UL /* CHKY */
43 #define CJ_IS_KEY(key) ((key)->magic == CJ_KEY_MAGIC)
45 #define COUCH_MIN(x,y) ((x) < (y) ? (x) : (y))
48 typedef struct cj_key_s cj_key_t;
49 struct cj_key_s /* {{{ */
70 struct curl_slist *headers;
74 char curl_errbuf[CURL_ERROR_SIZE];
85 char name[DATA_MAX_NAME_LEN];
86 } state[YAJL_MAX_DEPTH];
88 typedef struct cj_s cj_t; /* }}} */
91 typedef size_t yajl_len_t;
93 typedef unsigned int yajl_len_t;
96 static int cj_read (user_data_t *ud);
97 static int cj_curl_perform (cj_t *db, CURL *curl);
98 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value);
100 static size_t cj_curl_callback (void *buf, /* {{{ */
101 size_t size, size_t nmemb, void *user_data)
116 status = yajl_parse(db->yajl, (unsigned char *)buf, len);
117 if (status == yajl_status_ok)
120 else if (status == yajl_status_insufficient_data)
124 if (status != yajl_status_ok)
127 yajl_get_error(db->yajl, /* verbose = */ 1,
128 /* jsonText = */ (unsigned char *) buf, (unsigned int) len);
129 ERROR ("curl_json plugin: yajl_parse failed: %s", msg);
130 yajl_free_error(db->yajl, msg);
131 return (0); /* abort write callback */
135 } /* }}} size_t cj_curl_callback */
137 static int cj_get_type (cj_key_t *key)
139 const data_set_t *ds;
141 ds = plugin_get_ds (key->type);
144 static char type[DATA_MAX_NAME_LEN] = "!!!invalid!!!";
146 assert (key->type != NULL);
147 if (strcmp (type, key->type) != 0)
149 ERROR ("curl_json plugin: Unable to look up DS type \"%s\".",
151 sstrncpy (type, key->type, sizeof (type));
156 else if (ds->ds_num > 1)
158 static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
160 c_complain_once (LOG_WARNING, &complaint,
161 "curl_json plugin: The type \"%s\" has more than one data source. "
162 "This is currently not supported. I will return the type of the "
163 "first data source, but this will likely lead to problems later on.",
167 return ds->ds[0].type;
171 #define CJ_CB_ABORT 0
172 #define CJ_CB_CONTINUE 1
174 /* "number" may not be null terminated, so copy it into a buffer before
176 static int cj_cb_number (void *ctx,
177 const char *number, yajl_len_t number_len)
179 char buffer[number_len + 1];
181 cj_t *db = (cj_t *)ctx;
182 cj_key_t *key = db->state[db->depth].key;
187 if ((key == NULL) || !CJ_IS_KEY (key))
188 return (CJ_CB_CONTINUE);
190 memcpy (buffer, number, number_len);
191 buffer[sizeof (buffer) - 1] = 0;
193 type = cj_get_type (key);
194 status = parse_value (buffer, &vt, type);
197 NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
198 return (CJ_CB_CONTINUE);
201 cj_submit (db, key, &vt);
202 return (CJ_CB_CONTINUE);
203 } /* int cj_cb_number */
205 static int cj_cb_map_key (void *ctx, const unsigned char *val,
208 cj_t *db = (cj_t *)ctx;
211 tree = db->state[db->depth-1].tree;
218 name = db->state[db->depth].name;
219 len = COUCH_MIN(len, sizeof (db->state[db->depth].name)-1);
220 sstrncpy (name, (char *)val, len+1);
222 if (c_avl_get (tree, name, (void *) &value) == 0)
223 db->state[db->depth].key = value;
224 else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
225 db->state[db->depth].key = value;
227 db->state[db->depth].key = NULL;
230 return (CJ_CB_CONTINUE);
233 static int cj_cb_string (void *ctx, const unsigned char *val,
236 cj_t *db = (cj_t *)ctx;
239 /* Create a null-terminated version of the string. */
240 memcpy (str, val, len);
243 /* No configuration for this string -> simply return. */
244 if (db->state[db->depth].key == NULL)
245 return (CJ_CB_CONTINUE);
247 if (!CJ_IS_KEY (db->state[db->depth].key))
249 NOTICE ("curl_json plugin: Found string \"%s\", but the configuration "
250 "expects a map here.", str);
251 return (CJ_CB_CONTINUE);
254 /* Handle the string as if it was a number. */
255 return (cj_cb_number (ctx, (const char *) val, len));
256 } /* int cj_cb_string */
258 static int cj_cb_start (void *ctx)
260 cj_t *db = (cj_t *)ctx;
261 if (++db->depth >= YAJL_MAX_DEPTH)
263 ERROR ("curl_json plugin: %s depth exceeds max, aborting.", db->url);
264 return (CJ_CB_ABORT);
266 return (CJ_CB_CONTINUE);
269 static int cj_cb_end (void *ctx)
271 cj_t *db = (cj_t *)ctx;
272 db->state[db->depth].tree = NULL;
274 return (CJ_CB_CONTINUE);
277 static int cj_cb_start_map (void *ctx)
279 return cj_cb_start (ctx);
282 static int cj_cb_end_map (void *ctx)
284 return cj_cb_end (ctx);
287 static int cj_cb_start_array (void * ctx)
289 return cj_cb_start (ctx);
292 static int cj_cb_end_array (void * ctx)
294 return cj_cb_end (ctx);
297 static yajl_callbacks ycallbacks = {
311 /* end yajl callbacks */
313 static void cj_key_free (cj_key_t *key) /* {{{ */
320 sfree (key->instance);
323 } /* }}} void cj_key_free */
325 static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
330 while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
332 cj_key_t *key = (cj_key_t *)value;
337 cj_tree_free ((c_avl_tree_t *)value);
342 c_avl_destroy (tree);
343 } /* }}} void cj_tree_free */
345 static void cj_free (void *arg) /* {{{ */
349 DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
356 if (db->curl != NULL)
357 curl_easy_cleanup (db->curl);
360 if (db->tree != NULL)
361 cj_tree_free (db->tree);
364 sfree (db->instance);
370 sfree (db->credentials);
372 sfree (db->post_body);
373 curl_slist_free_all (db->headers);
376 } /* }}} void cj_free */
378 /* Configuration handling functions {{{ */
380 static c_avl_tree_t *cj_avl_create(void)
382 return c_avl_create ((int (*) (const void *, const void *)) strcmp);
385 static int cj_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
388 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
390 WARNING ("curl_json plugin: `%s' needs exactly one string argument.", name);
394 *dest = curl_slist_append(*dest, ci->values[0].value.string);
399 } /* }}} int cj_config_append_string */
401 static int cj_config_add_key (cj_t *db, /* {{{ */
408 if ((ci->values_num != 1)
409 || (ci->values[0].type != OCONFIG_TYPE_STRING))
411 WARNING ("curl_json plugin: The `Key' block "
412 "needs exactly one string argument.");
416 key = (cj_key_t *) malloc (sizeof (*key));
419 ERROR ("curl_json plugin: malloc failed.");
422 memset (key, 0, sizeof (*key));
423 key->magic = CJ_KEY_MAGIC;
425 if (strcasecmp ("Key", ci->key) == 0)
427 status = cf_util_get_string (ci, &key->path);
436 ERROR ("curl_json plugin: cj_config: "
437 "Invalid key: %s", ci->key);
442 for (i = 0; i < ci->children_num; i++)
444 oconfig_item_t *child = ci->children + i;
446 if (strcasecmp ("Type", child->key) == 0)
447 status = cf_util_get_string (child, &key->type);
448 else if (strcasecmp ("Instance", child->key) == 0)
449 status = cf_util_get_string (child, &key->instance);
452 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
458 } /* for (i = 0; i < ci->children_num; i++) */
462 if (key->type == NULL)
464 WARNING ("curl_json plugin: `Type' missing in `Key' block.");
469 } /* while (status == 0) */
471 /* store path in a tree that will match the json map structure, example:
472 * "httpd/requests/count",
473 * "httpd/requests/current" ->
474 * { "httpd": { "requests": { "count": $key, "current": $key } } }
483 if (db->tree == NULL)
484 db->tree = cj_avl_create();
503 len = COUCH_MIN(len, sizeof (ent)-1);
504 sstrncpy (ent, name, len+1);
506 if (c_avl_get (tree, ent, (void *) &value) != 0)
508 value = cj_avl_create ();
509 c_avl_insert (tree, strdup (ent), value);
518 c_avl_insert (tree, strdup(name), key);
521 ERROR ("curl_json plugin: invalid key: %s", key->path);
527 } /* }}} int cj_config_add_key */
529 static int cj_init_curl (cj_t *db) /* {{{ */
531 db->curl = curl_easy_init ();
532 if (db->curl == NULL)
534 ERROR ("curl_json plugin: curl_easy_init failed.");
538 curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
539 curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
540 curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
541 curl_easy_setopt (db->curl, CURLOPT_USERAGENT,
542 PACKAGE_NAME"/"PACKAGE_VERSION);
543 curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
544 curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
546 if (db->user != NULL)
548 size_t credentials_size;
550 credentials_size = strlen (db->user) + 2;
551 if (db->pass != NULL)
552 credentials_size += strlen (db->pass);
554 db->credentials = (char *) malloc (credentials_size);
555 if (db->credentials == NULL)
557 ERROR ("curl_json plugin: malloc failed.");
561 ssnprintf (db->credentials, credentials_size, "%s:%s",
562 db->user, (db->pass == NULL) ? "" : db->pass);
563 curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
566 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (long) db->verify_peer);
567 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
568 db->verify_host ? 2L : 0L);
569 if (db->cacert != NULL)
570 curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
571 if (db->headers != NULL)
572 curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
573 if (db->post_body != NULL)
574 curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
577 } /* }}} int cj_init_curl */
579 static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
585 if ((ci->values_num != 1)
586 || (ci->values[0].type != OCONFIG_TYPE_STRING))
588 WARNING ("curl_json plugin: The `URL' block "
589 "needs exactly one string argument.");
593 db = (cj_t *) malloc (sizeof (*db));
596 ERROR ("curl_json plugin: malloc failed.");
599 memset (db, 0, sizeof (*db));
601 if (strcasecmp ("URL", ci->key) == 0)
603 status = cf_util_get_string (ci, &db->url);
612 ERROR ("curl_json plugin: cj_config: "
613 "Invalid key: %s", ci->key);
617 /* Fill the `cj_t' structure.. */
618 for (i = 0; i < ci->children_num; i++)
620 oconfig_item_t *child = ci->children + i;
622 if (strcasecmp ("Instance", child->key) == 0)
623 status = cf_util_get_string (child, &db->instance);
624 else if (strcasecmp ("Host", child->key) == 0)
625 status = cf_util_get_string (child, &db->host);
626 else if (strcasecmp ("User", child->key) == 0)
627 status = cf_util_get_string (child, &db->user);
628 else if (strcasecmp ("Password", child->key) == 0)
629 status = cf_util_get_string (child, &db->pass);
630 else if (strcasecmp ("VerifyPeer", child->key) == 0)
631 status = cf_util_get_boolean (child, &db->verify_peer);
632 else if (strcasecmp ("VerifyHost", child->key) == 0)
633 status = cf_util_get_boolean (child, &db->verify_host);
634 else if (strcasecmp ("CACert", child->key) == 0)
635 status = cf_util_get_string (child, &db->cacert);
636 else if (strcasecmp ("Header", child->key) == 0)
637 status = cj_config_append_string ("Header", &db->headers, child);
638 else if (strcasecmp ("Post", child->key) == 0)
639 status = cf_util_get_string (child, &db->post_body);
640 else if (strcasecmp ("Key", child->key) == 0)
641 status = cj_config_add_key (db, child);
644 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
654 if (db->tree == NULL)
656 WARNING ("curl_json plugin: No (valid) `Key' block "
657 "within `URL' block `%s'.", db->url);
661 status = cj_init_curl (db);
664 /* If all went well, register this database for reading */
668 char cb_name[DATA_MAX_NAME_LEN];
670 if (db->instance == NULL)
671 db->instance = strdup("default");
673 DEBUG ("curl_json plugin: Registering new read callback: %s",
676 memset (&ud, 0, sizeof (ud));
677 ud.data = (void *) db;
678 ud.free_func = cj_free;
680 ssnprintf (cb_name, sizeof (cb_name), "curl_json-%s-%s",
681 db->instance, db->url);
683 plugin_register_complex_read (/* group = */ NULL, cb_name, cj_read,
684 /* interval = */ NULL, &ud);
694 /* }}} int cj_config_add_database */
696 static int cj_config (oconfig_item_t *ci) /* {{{ */
706 for (i = 0; i < ci->children_num; i++)
708 oconfig_item_t *child = ci->children + i;
710 if (strcasecmp ("URL", child->key) == 0)
712 status = cj_config_add_url (child);
720 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
725 if ((success == 0) && (errors > 0))
727 ERROR ("curl_json plugin: All statements failed.");
732 } /* }}} int cj_config */
734 /* }}} End of configuration handling functions */
736 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
738 value_list_t vl = VALUE_LIST_INIT;
744 if ((db->host == NULL)
745 || (strcmp ("", db->host) == 0)
746 || (strcmp (CJ_DEFAULT_HOST, db->host) == 0))
751 if (key->instance == NULL)
753 if ((db->depth == 0) || (strcmp ("", db->state[db->depth-1].name) == 0))
754 sstrncpy (vl.type_instance, db->state[db->depth].name, sizeof (vl.type_instance));
756 ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s",
757 db->state[db->depth-1].name, db->state[db->depth].name);
760 sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
762 sstrncpy (vl.host, host, sizeof (vl.host));
763 sstrncpy (vl.plugin, "curl_json", sizeof (vl.plugin));
764 sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
765 sstrncpy (vl.type, key->type, sizeof (vl.type));
767 plugin_dispatch_values (&vl);
768 } /* }}} int cj_submit */
770 static int cj_curl_perform (cj_t *db, CURL *curl) /* {{{ */
775 yajl_handle yprev = db->yajl;
777 db->yajl = yajl_alloc (&ycallbacks,
779 /* alloc funcs = */ NULL,
781 /* alloc funcs = */ NULL, NULL,
783 /* context = */ (void *)db);
784 if (db->yajl == NULL)
786 ERROR ("curl_json plugin: yajl_alloc failed.");
792 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
794 status = curl_easy_perform (curl);
795 if (status != CURLE_OK)
797 ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
798 status, db->curl_errbuf, (url != NULL) ? url : "<null>");
799 yajl_free (db->yajl);
804 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rc);
806 /* The response code is zero if a non-HTTP transport was used. */
807 if ((rc != 0) && (rc != 200))
809 ERROR ("curl_json plugin: curl_easy_perform failed with "
810 "response code %ld (%s)", rc, url);
811 yajl_free (db->yajl);
817 status = yajl_complete_parse(db->yajl);
819 status = yajl_parse_complete(db->yajl);
821 if (status != yajl_status_ok)
823 unsigned char *errmsg;
825 errmsg = yajl_get_error (db->yajl, /* verbose = */ 0,
826 /* jsonText = */ NULL, /* jsonTextLen = */ 0);
827 ERROR ("curl_json plugin: yajl_parse_complete failed: %s",
829 yajl_free_error (db->yajl, errmsg);
830 yajl_free (db->yajl);
835 yajl_free (db->yajl);
838 } /* }}} int cj_curl_perform */
840 static int cj_read (user_data_t *ud) /* {{{ */
844 if ((ud == NULL) || (ud->data == NULL))
846 ERROR ("curl_json plugin: cj_read: Invalid user data.");
850 db = (cj_t *) ud->data;
853 memset (&db->state, 0, sizeof(db->state));
854 db->state[db->depth].tree = db->tree;
857 return cj_curl_perform (db, db->curl);
858 } /* }}} int cj_read */
860 static int cj_init (void) /* {{{ */
862 /* Call this while collectd is still single-threaded to avoid
863 * initialization issues in libgcrypt. */
864 curl_global_init (CURL_GLOBAL_SSL);
866 } /* }}} int cj_init */
868 void module_register (void)
870 plugin_register_complex_config ("curl_json", cj_config);
871 plugin_register_init ("curl_json", cj_init);
872 } /* void module_register */
874 /* vim: set sw=2 sts=2 et fdm=marker : */