2 * collectd - src/curl_json.c
3 * Copyright (C) 2009 Doug MacEachern
4 * Copyright (C) 2006-2013 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 <sys/socket.h>
32 #include <sys/types.h>
35 #include <curl/curl.h>
37 #include <yajl/yajl_parse.h>
38 #if HAVE_YAJL_YAJL_VERSION_H
39 # include <yajl/yajl_version.h>
42 #if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
43 # define HAVE_YAJL_V2 1
46 #define CJ_DEFAULT_HOST "localhost"
47 #define CJ_KEY_MAGIC 0x43484b59UL /* CHKY */
48 #define CJ_IS_KEY(key) ((key)->magic == CJ_KEY_MAGIC)
50 #define COUCH_MIN(x,y) ((x) < (y) ? (x) : (y))
53 typedef struct cj_key_s cj_key_t;
54 struct cj_key_s /* {{{ */
77 struct curl_slist *headers;
81 char curl_errbuf[CURL_ERROR_SIZE];
94 char name[DATA_MAX_NAME_LEN];
95 } state[YAJL_MAX_DEPTH];
97 typedef struct cj_s cj_t; /* }}} */
100 typedef size_t yajl_len_t;
102 typedef unsigned int yajl_len_t;
105 static int cj_read (user_data_t *ud);
106 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value);
108 static size_t cj_curl_callback (void *buf, /* {{{ */
109 size_t size, size_t nmemb, void *user_data)
124 status = yajl_parse(db->yajl, (unsigned char *)buf, len);
125 if (status == yajl_status_ok)
128 else if (status == yajl_status_insufficient_data)
132 if (status != yajl_status_ok)
135 yajl_get_error(db->yajl, /* verbose = */ 1,
136 /* jsonText = */ (unsigned char *) buf, (unsigned int) len);
137 ERROR ("curl_json plugin: yajl_parse failed: %s", msg);
138 yajl_free_error(db->yajl, msg);
139 return (0); /* abort write callback */
143 } /* }}} size_t cj_curl_callback */
145 static int cj_get_type (cj_key_t *key)
147 const data_set_t *ds;
149 ds = plugin_get_ds (key->type);
152 static char type[DATA_MAX_NAME_LEN] = "!!!invalid!!!";
154 assert (key->type != NULL);
155 if (strcmp (type, key->type) != 0)
157 ERROR ("curl_json plugin: Unable to look up DS type \"%s\".",
159 sstrncpy (type, key->type, sizeof (type));
164 else if (ds->ds_num > 1)
166 static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
168 c_complain_once (LOG_WARNING, &complaint,
169 "curl_json plugin: The type \"%s\" has more than one data source. "
170 "This is currently not supported. I will return the type of the "
171 "first data source, but this will likely lead to problems later on.",
175 return ds->ds[0].type;
178 static int cj_cb_map_key (void *ctx, const unsigned char *val,
181 static void cj_cb_inc_array_index (void *ctx, _Bool update_key)
183 cj_t *db = (cj_t *)ctx;
185 if (!db->state[db->depth].in_array)
188 db->state[db->depth].index++;
192 char name[DATA_MAX_NAME_LEN];
194 ssnprintf (name, sizeof (name), "%d", db->state[db->depth].index - 1);
196 cj_cb_map_key (ctx, (unsigned char *)name, (yajl_len_t) strlen (name));
201 #define CJ_CB_ABORT 0
202 #define CJ_CB_CONTINUE 1
204 static int cj_cb_boolean (void * ctx, int boolVal)
206 cj_cb_inc_array_index (ctx, /* update_key = */ 0);
207 return (CJ_CB_CONTINUE);
210 static int cj_cb_null (void * ctx)
212 cj_cb_inc_array_index (ctx, /* update_key = */ 0);
213 return (CJ_CB_CONTINUE);
216 static int cj_cb_number (void *ctx,
217 const char *number, yajl_len_t number_len)
219 char buffer[number_len + 1];
221 cj_t *db = (cj_t *)ctx;
222 cj_key_t *key = db->state[db->depth].key;
227 /* Create a null-terminated version of the string. */
228 memcpy (buffer, number, number_len);
229 buffer[sizeof (buffer) - 1] = 0;
231 if ((key == NULL) || !CJ_IS_KEY (key)) {
233 NOTICE ("curl_json plugin: Found \"%s\", but the configuration expects"
235 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
236 key = db->state[db->depth].key;
238 return (CJ_CB_CONTINUE);
243 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
246 type = cj_get_type (key);
247 status = parse_value (buffer, &vt, type);
250 NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
251 return (CJ_CB_CONTINUE);
254 cj_submit (db, key, &vt);
255 return (CJ_CB_CONTINUE);
256 } /* int cj_cb_number */
258 /* Queries the key-tree of the parent context for "in_name" and, if found,
259 * updates the "key" field of the current context. Otherwise, "key" is set to
261 static int cj_cb_map_key (void *ctx,
262 unsigned char const *in_name, yajl_len_t in_name_len)
264 cj_t *db = (cj_t *)ctx;
267 tree = db->state[db->depth-1].tree;
271 cj_key_t *value = NULL;
275 /* Create a null-terminated version of the name. */
276 name = db->state[db->depth].name;
277 name_len = COUCH_MIN ((size_t) in_name_len,
278 sizeof (db->state[db->depth].name) - 1);
279 memcpy (name, in_name, name_len);
282 if (c_avl_get (tree, name, (void *) &value) == 0) {
283 if (CJ_IS_KEY((cj_key_t*)value)) {
284 db->state[db->depth].key = value;
287 db->state[db->depth].tree = (c_avl_tree_t*) value;
290 else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
291 if (CJ_IS_KEY((cj_key_t*)value)) {
292 db->state[db->depth].key = value;
295 db->state[db->depth].tree = (c_avl_tree_t*) value;
298 db->state[db->depth].key = NULL;
301 return (CJ_CB_CONTINUE);
304 static int cj_cb_string (void *ctx, const unsigned char *val,
307 /* Handle the string as if it was a number. */
308 return (cj_cb_number (ctx, (const char *) val, len));
309 } /* int cj_cb_string */
311 static int cj_cb_start (void *ctx)
313 cj_t *db = (cj_t *)ctx;
314 if (++db->depth >= YAJL_MAX_DEPTH)
316 ERROR ("curl_json plugin: %s depth exceeds max, aborting.",
317 db->url ? db->url : db->sock);
318 return (CJ_CB_ABORT);
320 return (CJ_CB_CONTINUE);
323 static int cj_cb_end (void *ctx)
325 cj_t *db = (cj_t *)ctx;
326 db->state[db->depth].tree = NULL;
328 return (CJ_CB_CONTINUE);
331 static int cj_cb_start_map (void *ctx)
333 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
334 return cj_cb_start (ctx);
337 static int cj_cb_end_map (void *ctx)
339 return cj_cb_end (ctx);
342 static int cj_cb_start_array (void * ctx)
344 cj_t *db = (cj_t *)ctx;
345 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
346 if (db->depth+1 < YAJL_MAX_DEPTH) {
347 db->state[db->depth+1].in_array = 1;
348 db->state[db->depth+1].index = 0;
350 return cj_cb_start (ctx);
353 static int cj_cb_end_array (void * ctx)
355 cj_t *db = (cj_t *)ctx;
356 db->state[db->depth].in_array = 0;
357 return cj_cb_end (ctx);
360 static yajl_callbacks ycallbacks = {
361 cj_cb_null, /* null */
362 cj_cb_boolean, /* boolean */
374 /* end yajl callbacks */
376 static void cj_key_free (cj_key_t *key) /* {{{ */
383 sfree (key->instance);
386 } /* }}} void cj_key_free */
388 static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
393 while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
395 cj_key_t *key = (cj_key_t *)value;
400 cj_tree_free ((c_avl_tree_t *)value);
405 c_avl_destroy (tree);
406 } /* }}} void cj_tree_free */
408 static void cj_free (void *arg) /* {{{ */
412 DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
419 if (db->curl != NULL)
420 curl_easy_cleanup (db->curl);
423 if (db->tree != NULL)
424 cj_tree_free (db->tree);
427 sfree (db->instance);
435 sfree (db->credentials);
437 sfree (db->post_body);
438 curl_slist_free_all (db->headers);
441 } /* }}} void cj_free */
443 /* Configuration handling functions {{{ */
445 static c_avl_tree_t *cj_avl_create(void)
447 return c_avl_create ((int (*) (const void *, const void *)) strcmp);
450 static int cj_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
453 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
455 WARNING ("curl_json plugin: `%s' needs exactly one string argument.", name);
459 *dest = curl_slist_append(*dest, ci->values[0].value.string);
464 } /* }}} int cj_config_append_string */
466 static int cj_config_add_key (cj_t *db, /* {{{ */
473 if ((ci->values_num != 1)
474 || (ci->values[0].type != OCONFIG_TYPE_STRING))
476 WARNING ("curl_json plugin: The `Key' block "
477 "needs exactly one string argument.");
481 key = (cj_key_t *) malloc (sizeof (*key));
484 ERROR ("curl_json plugin: malloc failed.");
487 memset (key, 0, sizeof (*key));
488 key->magic = CJ_KEY_MAGIC;
490 if (strcasecmp ("Key", ci->key) == 0)
492 status = cf_util_get_string (ci, &key->path);
501 ERROR ("curl_json plugin: cj_config: "
502 "Invalid key: %s", ci->key);
507 for (i = 0; i < ci->children_num; i++)
509 oconfig_item_t *child = ci->children + i;
511 if (strcasecmp ("Type", child->key) == 0)
512 status = cf_util_get_string (child, &key->type);
513 else if (strcasecmp ("Instance", child->key) == 0)
514 status = cf_util_get_string (child, &key->instance);
517 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
523 } /* for (i = 0; i < ci->children_num; i++) */
527 if (key->type == NULL)
529 WARNING ("curl_json plugin: `Type' missing in `Key' block.");
534 } /* while (status == 0) */
536 /* store path in a tree that will match the json map structure, example:
537 * "httpd/requests/count",
538 * "httpd/requests/current" ->
539 * { "httpd": { "requests": { "count": $key, "current": $key } } }
548 if (db->tree == NULL)
549 db->tree = cj_avl_create();
568 len = COUCH_MIN(len, sizeof (ent)-1);
569 sstrncpy (ent, name, len+1);
571 if (c_avl_get (tree, ent, (void *) &value) != 0)
573 value = cj_avl_create ();
574 c_avl_insert (tree, strdup (ent), value);
583 c_avl_insert (tree, strdup(name), key);
586 ERROR ("curl_json plugin: invalid key: %s", key->path);
592 } /* }}} int cj_config_add_key */
594 static int cj_init_curl (cj_t *db) /* {{{ */
596 db->curl = curl_easy_init ();
597 if (db->curl == NULL)
599 ERROR ("curl_json plugin: curl_easy_init failed.");
603 curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
604 curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
605 curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
606 curl_easy_setopt (db->curl, CURLOPT_USERAGENT,
607 PACKAGE_NAME"/"PACKAGE_VERSION);
608 curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
609 curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
611 if (db->user != NULL)
613 size_t credentials_size;
615 credentials_size = strlen (db->user) + 2;
616 if (db->pass != NULL)
617 credentials_size += strlen (db->pass);
619 db->credentials = (char *) malloc (credentials_size);
620 if (db->credentials == NULL)
622 ERROR ("curl_json plugin: malloc failed.");
626 ssnprintf (db->credentials, credentials_size, "%s:%s",
627 db->user, (db->pass == NULL) ? "" : db->pass);
628 curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
631 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (long) db->verify_peer);
632 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
633 db->verify_host ? 2L : 0L);
634 if (db->cacert != NULL)
635 curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
636 if (db->headers != NULL)
637 curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
638 if (db->post_body != NULL)
639 curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
642 } /* }}} int cj_init_curl */
644 static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
650 if ((ci->values_num != 1)
651 || (ci->values[0].type != OCONFIG_TYPE_STRING))
653 WARNING ("curl_json plugin: The `URL' block "
654 "needs exactly one string argument.");
658 db = (cj_t *) malloc (sizeof (*db));
661 ERROR ("curl_json plugin: malloc failed.");
664 memset (db, 0, sizeof (*db));
666 if (strcasecmp ("URL", ci->key) == 0)
667 status = cf_util_get_string (ci, &db->url);
668 else if (strcasecmp ("Sock", ci->key) == 0)
669 status = cf_util_get_string (ci, &db->sock);
672 ERROR ("curl_json plugin: cj_config: "
673 "Invalid key: %s", ci->key);
682 /* Fill the `cj_t' structure.. */
683 for (i = 0; i < ci->children_num; i++)
685 oconfig_item_t *child = ci->children + i;
687 if (strcasecmp ("Instance", child->key) == 0)
688 status = cf_util_get_string (child, &db->instance);
689 else if (strcasecmp ("Host", child->key) == 0)
690 status = cf_util_get_string (child, &db->host);
691 else if (db->url && strcasecmp ("User", child->key) == 0)
692 status = cf_util_get_string (child, &db->user);
693 else if (db->url && strcasecmp ("Password", child->key) == 0)
694 status = cf_util_get_string (child, &db->pass);
695 else if (db->url && strcasecmp ("VerifyPeer", child->key) == 0)
696 status = cf_util_get_boolean (child, &db->verify_peer);
697 else if (db->url && strcasecmp ("VerifyHost", child->key) == 0)
698 status = cf_util_get_boolean (child, &db->verify_host);
699 else if (db->url && strcasecmp ("CACert", child->key) == 0)
700 status = cf_util_get_string (child, &db->cacert);
701 else if (db->url && strcasecmp ("Header", child->key) == 0)
702 status = cj_config_append_string ("Header", &db->headers, child);
703 else if (db->url && strcasecmp ("Post", child->key) == 0)
704 status = cf_util_get_string (child, &db->post_body);
705 else if (strcasecmp ("Key", child->key) == 0)
706 status = cj_config_add_key (db, child);
709 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
719 if (db->tree == NULL)
721 WARNING ("curl_json plugin: No (valid) `Key' block within `%s' \"`%s'\".",
722 db->url ? "URL" : "Sock", db->url ? db->url : db->sock);
725 if (status == 0 && db->url)
726 status = cj_init_curl (db);
729 /* If all went well, register this database for reading */
735 if (db->instance == NULL)
736 db->instance = strdup("default");
738 DEBUG ("curl_json plugin: Registering new read callback: %s",
741 memset (&ud, 0, sizeof (ud));
742 ud.data = (void *) db;
743 ud.free_func = cj_free;
745 cb_name = ssnprintf_alloc ("curl_json-%s-%s",
746 db->instance, db->url ? db->url : db->sock);
748 plugin_register_complex_read (/* group = */ "curl_json", cb_name, cj_read,
749 /* interval = */ NULL, &ud);
760 /* }}} int cj_config_add_database */
762 static int cj_config (oconfig_item_t *ci) /* {{{ */
772 for (i = 0; i < ci->children_num; i++)
774 oconfig_item_t *child = ci->children + i;
776 if (strcasecmp ("Sock", child->key) == 0
777 || strcasecmp ("URL", child->key) == 0)
779 status = cj_config_add_url (child);
787 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
792 if ((success == 0) && (errors > 0))
794 ERROR ("curl_json plugin: All statements failed.");
799 } /* }}} int cj_config */
801 /* }}} End of configuration handling functions */
803 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
805 value_list_t vl = VALUE_LIST_INIT;
811 if ((db->host == NULL)
812 || (strcmp ("", db->host) == 0)
813 || (strcmp (CJ_DEFAULT_HOST, db->host) == 0))
818 if (key->instance == NULL)
820 if ((db->depth == 0) || (strcmp ("", db->state[db->depth-1].name) == 0))
821 sstrncpy (vl.type_instance, db->state[db->depth].name, sizeof (vl.type_instance));
823 ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s",
824 db->state[db->depth-1].name, db->state[db->depth].name);
827 sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
829 sstrncpy (vl.host, host, sizeof (vl.host));
830 sstrncpy (vl.plugin, "curl_json", sizeof (vl.plugin));
831 sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
832 sstrncpy (vl.type, key->type, sizeof (vl.type));
834 plugin_dispatch_values (&vl);
835 } /* }}} int cj_submit */
837 static int cj_sock_perform (cj_t *db) /* {{{ */
840 struct sockaddr_un sa_unix = {};
841 sa_unix.sun_family = AF_UNIX;
842 sstrncpy (sa_unix.sun_path, db->sock, sizeof (sa_unix.sun_path));
844 int fd = socket (AF_UNIX, SOCK_STREAM, 0);
847 if (connect (fd, (struct sockaddr *)&sa_unix, sizeof(sa_unix)) < 0)
849 ERROR ("curl_json plugin: connect(%s) failed: %s",
850 (db->sock != NULL) ? db->sock : "<null>",
851 sstrerror(errno, errbuf, sizeof (errbuf)));
858 unsigned char buffer[4096];
859 red = read (fd, buffer, sizeof(buffer));
861 ERROR ("curl_json plugin: read(%s) failed: %s",
862 (db->sock != NULL) ? db->sock : "<null>",
863 sstrerror(errno, errbuf, sizeof (errbuf)));
867 if (!cj_curl_callback (buffer, red, 1, db))
872 } /* }}} int cj_sock_perform */
875 static int cj_curl_perform(cj_t *db) /* {{{ */
882 status = curl_easy_perform (db->curl);
883 if (status != CURLE_OK)
885 ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
886 status, db->curl_errbuf, url);
890 curl_easy_getinfo(db->curl, CURLINFO_EFFECTIVE_URL, &url);
891 curl_easy_getinfo(db->curl, CURLINFO_RESPONSE_CODE, &rc);
893 /* The response code is zero if a non-HTTP transport was used. */
894 if ((rc != 0) && (rc != 200))
896 ERROR ("curl_json plugin: curl_easy_perform failed with "
897 "response code %ld (%s)", rc, url);
901 } /* }}} int cj_curl_perform */
903 static int cj_perform (cj_t *db) /* {{{ */
906 yajl_handle yprev = db->yajl;
908 db->yajl = yajl_alloc (&ycallbacks,
910 /* alloc funcs = */ NULL,
912 /* alloc funcs = */ NULL, NULL,
914 /* context = */ (void *)db);
915 if (db->yajl == NULL)
917 ERROR ("curl_json plugin: yajl_alloc failed.");
923 status = cj_curl_perform (db);
925 status = cj_sock_perform (db);
928 yajl_free (db->yajl);
934 status = yajl_complete_parse(db->yajl);
936 status = yajl_parse_complete(db->yajl);
938 if (status != yajl_status_ok)
940 unsigned char *errmsg;
942 errmsg = yajl_get_error (db->yajl, /* verbose = */ 0,
943 /* jsonText = */ NULL, /* jsonTextLen = */ 0);
944 ERROR ("curl_json plugin: yajl_parse_complete failed: %s",
946 yajl_free_error (db->yajl, errmsg);
947 yajl_free (db->yajl);
952 yajl_free (db->yajl);
955 } /* }}} int cj_perform */
957 static int cj_read (user_data_t *ud) /* {{{ */
961 if ((ud == NULL) || (ud->data == NULL))
963 ERROR ("curl_json plugin: cj_read: Invalid user data.");
967 db = (cj_t *) ud->data;
970 memset (&db->state, 0, sizeof(db->state));
971 db->state[db->depth].tree = db->tree;
974 return cj_perform (db);
975 } /* }}} int cj_read */
977 static int cj_init (void) /* {{{ */
979 /* Call this while collectd is still single-threaded to avoid
980 * initialization issues in libgcrypt. */
981 curl_global_init (CURL_GLOBAL_SSL);
983 } /* }}} int cj_init */
985 void module_register (void)
987 plugin_register_complex_config ("curl_json", cj_config);
988 plugin_register_init ("curl_json", cj_init);
989 } /* void module_register */
991 /* vim: set sw=2 sts=2 et fdm=marker : */