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/types.h>
34 #include <curl/curl.h>
36 #include <yajl/yajl_parse.h>
37 #if HAVE_YAJL_YAJL_VERSION_H
38 # include <yajl/yajl_version.h>
41 #if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
42 # define HAVE_YAJL_V2 1
45 #define CJ_DEFAULT_HOST "localhost"
46 #define CJ_KEY_MAGIC 0x43484b59UL /* CHKY */
47 #define CJ_IS_KEY(key) ((key)->magic == CJ_KEY_MAGIC)
49 #define COUCH_MIN(x,y) ((x) < (y) ? (x) : (y))
52 typedef struct cj_key_s cj_key_t;
53 struct cj_key_s /* {{{ */
77 struct curl_slist *headers;
83 char curl_errbuf[CURL_ERROR_SIZE];
96 char name[DATA_MAX_NAME_LEN];
97 } state[YAJL_MAX_DEPTH];
99 typedef struct cj_s cj_t; /* }}} */
102 typedef size_t yajl_len_t;
104 typedef unsigned int yajl_len_t;
107 static int cj_read (user_data_t *ud);
108 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value);
110 static size_t cj_curl_callback (void *buf, /* {{{ */
111 size_t size, size_t nmemb, void *user_data)
126 status = yajl_parse(db->yajl, (unsigned char *)buf, len);
127 if (status == yajl_status_ok)
130 else if (status == yajl_status_insufficient_data)
134 unsigned char *msg = yajl_get_error(db->yajl, /* verbose = */ 1,
135 /* jsonText = */ (unsigned char *) buf, (unsigned int) len);
136 ERROR ("curl_json plugin: yajl_parse failed: %s", msg);
137 yajl_free_error(db->yajl, msg);
138 return (0); /* abort write callback */
139 } /* }}} size_t cj_curl_callback */
141 static int cj_get_type (cj_key_t *key)
143 const data_set_t *ds;
145 ds = plugin_get_ds (key->type);
148 static char type[DATA_MAX_NAME_LEN] = "!!!invalid!!!";
150 assert (key->type != NULL);
151 if (strcmp (type, key->type) != 0)
153 ERROR ("curl_json plugin: Unable to look up DS type \"%s\".",
155 sstrncpy (type, key->type, sizeof (type));
160 else if (ds->ds_num > 1)
162 static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
164 c_complain_once (LOG_WARNING, &complaint,
165 "curl_json plugin: The type \"%s\" has more than one data source. "
166 "This is currently not supported. I will return the type of the "
167 "first data source, but this will likely lead to problems later on.",
171 return ds->ds[0].type;
174 static int cj_cb_map_key (void *ctx, const unsigned char *val,
177 static void cj_cb_inc_array_index (void *ctx, _Bool update_key)
179 cj_t *db = (cj_t *)ctx;
181 if (!db->state[db->depth].in_array)
184 db->state[db->depth].index++;
188 char name[DATA_MAX_NAME_LEN];
190 ssnprintf (name, sizeof (name), "%d", db->state[db->depth].index - 1);
192 cj_cb_map_key (ctx, (unsigned char *)name, (yajl_len_t) strlen (name));
197 #define CJ_CB_ABORT 0
198 #define CJ_CB_CONTINUE 1
200 static int cj_cb_boolean (void * ctx, int boolVal)
202 cj_cb_inc_array_index (ctx, /* update_key = */ 0);
203 return (CJ_CB_CONTINUE);
206 static int cj_cb_null (void * ctx)
208 cj_cb_inc_array_index (ctx, /* update_key = */ 0);
209 return (CJ_CB_CONTINUE);
212 static int cj_cb_number (void *ctx,
213 const char *number, yajl_len_t number_len)
215 char buffer[number_len + 1];
217 cj_t *db = (cj_t *)ctx;
218 cj_key_t *key = db->state[db->depth].key;
223 /* Create a null-terminated version of the string. */
224 memcpy (buffer, number, number_len);
225 buffer[sizeof (buffer) - 1] = 0;
227 if ((key == NULL) || !CJ_IS_KEY (key)) {
228 if (key != NULL && !db->state[db->depth].in_array/*can be inhomogeneous*/)
229 NOTICE ("curl_json plugin: Found \"%s\", but the configuration expects"
231 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
232 key = db->state[db->depth].key;
234 return (CJ_CB_CONTINUE);
239 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
242 type = cj_get_type (key);
243 status = parse_value (buffer, &vt, type);
246 NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
247 return (CJ_CB_CONTINUE);
250 cj_submit (db, key, &vt);
251 return (CJ_CB_CONTINUE);
252 } /* int cj_cb_number */
254 /* Queries the key-tree of the parent context for "in_name" and, if found,
255 * updates the "key" field of the current context. Otherwise, "key" is set to
257 static int cj_cb_map_key (void *ctx,
258 unsigned char const *in_name, yajl_len_t in_name_len)
260 cj_t *db = (cj_t *)ctx;
263 tree = db->state[db->depth-1].tree;
267 cj_key_t *value = NULL;
271 /* Create a null-terminated version of the name. */
272 name = db->state[db->depth].name;
273 name_len = COUCH_MIN ((size_t) in_name_len,
274 sizeof (db->state[db->depth].name) - 1);
275 memcpy (name, in_name, name_len);
278 if (c_avl_get (tree, name, (void *) &value) == 0) {
279 if (CJ_IS_KEY((cj_key_t*)value)) {
280 db->state[db->depth].key = value;
283 db->state[db->depth].tree = (c_avl_tree_t*) value;
286 else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
287 if (CJ_IS_KEY((cj_key_t*)value)) {
288 db->state[db->depth].key = value;
291 db->state[db->depth].tree = (c_avl_tree_t*) value;
294 db->state[db->depth].key = NULL;
297 return (CJ_CB_CONTINUE);
300 static int cj_cb_string (void *ctx, const unsigned char *val,
303 /* Handle the string as if it was a number. */
304 return (cj_cb_number (ctx, (const char *) val, len));
305 } /* int cj_cb_string */
307 static int cj_cb_start (void *ctx)
309 cj_t *db = (cj_t *)ctx;
310 if (++db->depth >= YAJL_MAX_DEPTH)
312 ERROR ("curl_json plugin: %s depth exceeds max, aborting.",
313 db->url ? db->url : db->sock);
314 return (CJ_CB_ABORT);
316 return (CJ_CB_CONTINUE);
319 static int cj_cb_end (void *ctx)
321 cj_t *db = (cj_t *)ctx;
322 db->state[db->depth].tree = NULL;
324 return (CJ_CB_CONTINUE);
327 static int cj_cb_start_map (void *ctx)
329 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
330 return cj_cb_start (ctx);
333 static int cj_cb_end_map (void *ctx)
335 return cj_cb_end (ctx);
338 static int cj_cb_start_array (void * ctx)
340 cj_t *db = (cj_t *)ctx;
341 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
342 if (db->depth+1 < YAJL_MAX_DEPTH) {
343 db->state[db->depth+1].in_array = 1;
344 db->state[db->depth+1].index = 0;
346 return cj_cb_start (ctx);
349 static int cj_cb_end_array (void * ctx)
351 cj_t *db = (cj_t *)ctx;
352 db->state[db->depth].in_array = 0;
353 return cj_cb_end (ctx);
356 static yajl_callbacks ycallbacks = {
357 cj_cb_null, /* null */
358 cj_cb_boolean, /* boolean */
370 /* end yajl callbacks */
372 static void cj_key_free (cj_key_t *key) /* {{{ */
379 sfree (key->instance);
382 } /* }}} void cj_key_free */
384 static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
389 while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
391 cj_key_t *key = (cj_key_t *)value;
396 cj_tree_free ((c_avl_tree_t *)value);
401 c_avl_destroy (tree);
402 } /* }}} void cj_tree_free */
404 static void cj_free (void *arg) /* {{{ */
408 DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
415 if (db->curl != NULL)
416 curl_easy_cleanup (db->curl);
419 if (db->tree != NULL)
420 cj_tree_free (db->tree);
423 sfree (db->instance);
431 sfree (db->credentials);
433 sfree (db->post_body);
434 curl_slist_free_all (db->headers);
437 } /* }}} void cj_free */
439 /* Configuration handling functions {{{ */
441 static c_avl_tree_t *cj_avl_create(void)
443 return c_avl_create ((int (*) (const void *, const void *)) strcmp);
446 static int cj_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
449 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
451 WARNING ("curl_json plugin: `%s' needs exactly one string argument.", name);
455 *dest = curl_slist_append(*dest, ci->values[0].value.string);
460 } /* }}} int cj_config_append_string */
462 static int cj_config_add_key (cj_t *db, /* {{{ */
469 if ((ci->values_num != 1)
470 || (ci->values[0].type != OCONFIG_TYPE_STRING))
472 WARNING ("curl_json plugin: The `Key' block "
473 "needs exactly one string argument.");
477 key = (cj_key_t *) malloc (sizeof (*key));
480 ERROR ("curl_json plugin: malloc failed.");
483 memset (key, 0, sizeof (*key));
484 key->magic = CJ_KEY_MAGIC;
486 if (strcasecmp ("Key", ci->key) == 0)
488 status = cf_util_get_string (ci, &key->path);
497 ERROR ("curl_json plugin: cj_config: "
498 "Invalid key: %s", ci->key);
504 for (i = 0; i < ci->children_num; i++)
506 oconfig_item_t *child = ci->children + i;
508 if (strcasecmp ("Type", child->key) == 0)
509 status = cf_util_get_string (child, &key->type);
510 else if (strcasecmp ("Instance", child->key) == 0)
511 status = cf_util_get_string (child, &key->instance);
514 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
520 } /* for (i = 0; i < ci->children_num; i++) */
528 if (key->type == NULL)
530 WARNING ("curl_json plugin: `Type' missing in `Key' block.");
535 /* store path in a tree that will match the json map structure, example:
536 * "httpd/requests/count",
537 * "httpd/requests/current" ->
538 * { "httpd": { "requests": { "count": $key, "current": $key } } }
544 if (db->tree == NULL)
545 db->tree = cj_avl_create();
553 while ((ptr = strchr (name, '/')) != NULL)
563 len = COUCH_MIN(len, sizeof (ent)-1);
564 sstrncpy (ent, name, len+1);
566 if (c_avl_get (tree, ent, (void *) &value) != 0)
568 value = cj_avl_create ();
569 c_avl_insert (tree, strdup (ent), value);
576 if (strlen (name) == 0)
578 ERROR ("curl_json plugin: invalid key: %s", key->path);
583 c_avl_insert (tree, strdup (name), key);
585 } /* }}} int cj_config_add_key */
587 static int cj_init_curl (cj_t *db) /* {{{ */
589 db->curl = curl_easy_init ();
590 if (db->curl == NULL)
592 ERROR ("curl_json plugin: curl_easy_init failed.");
596 curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
597 curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
598 curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
599 curl_easy_setopt (db->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
600 curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
601 curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
602 curl_easy_setopt (db->curl, CURLOPT_FOLLOWLOCATION, 1L);
603 curl_easy_setopt (db->curl, CURLOPT_MAXREDIRS, 50L);
605 if (db->user != NULL)
607 #ifdef HAVE_CURLOPT_USERNAME
608 curl_easy_setopt (db->curl, CURLOPT_USERNAME, db->user);
609 curl_easy_setopt (db->curl, CURLOPT_PASSWORD,
610 (db->pass == NULL) ? "" : db->pass);
612 size_t credentials_size;
614 credentials_size = strlen (db->user) + 2;
615 if (db->pass != NULL)
616 credentials_size += strlen (db->pass);
618 db->credentials = (char *) malloc (credentials_size);
619 if (db->credentials == NULL)
621 ERROR ("curl_json plugin: malloc failed.");
625 ssnprintf (db->credentials, credentials_size, "%s:%s",
626 db->user, (db->pass == NULL) ? "" : db->pass);
627 curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
631 curl_easy_setopt (db->curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
634 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (long) db->verify_peer);
635 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
636 db->verify_host ? 2L : 0L);
637 if (db->cacert != NULL)
638 curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
639 if (db->headers != NULL)
640 curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
641 if (db->post_body != NULL)
642 curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
644 #ifdef HAVE_CURLOPT_TIMEOUT_MS
645 if (db->timeout >= 0)
646 curl_easy_setopt (db->curl, CURLOPT_TIMEOUT_MS, (long) db->timeout);
647 else if (db->interval > 0)
648 curl_easy_setopt (db->curl, CURLOPT_TIMEOUT_MS, (long) CDTIME_T_TO_MS(db->timeout));
650 curl_easy_setopt (db->curl, CURLOPT_TIMEOUT_MS, (long) CDTIME_T_TO_MS(plugin_get_interval()));
654 } /* }}} int cj_init_curl */
656 static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
662 if ((ci->values_num != 1)
663 || (ci->values[0].type != OCONFIG_TYPE_STRING))
665 WARNING ("curl_json plugin: The `URL' block "
666 "needs exactly one string argument.");
670 db = (cj_t *) malloc (sizeof (*db));
673 ERROR ("curl_json plugin: malloc failed.");
676 memset (db, 0, sizeof (*db));
680 if (strcasecmp ("URL", ci->key) == 0)
681 status = cf_util_get_string (ci, &db->url);
682 else if (strcasecmp ("Sock", ci->key) == 0)
683 status = cf_util_get_string (ci, &db->sock);
686 ERROR ("curl_json plugin: cj_config: "
687 "Invalid key: %s", ci->key);
697 /* Fill the `cj_t' structure.. */
698 for (i = 0; i < ci->children_num; i++)
700 oconfig_item_t *child = ci->children + i;
702 if (strcasecmp ("Instance", child->key) == 0)
703 status = cf_util_get_string (child, &db->instance);
704 else if (strcasecmp ("Host", child->key) == 0)
705 status = cf_util_get_string (child, &db->host);
706 else if (db->url && strcasecmp ("User", child->key) == 0)
707 status = cf_util_get_string (child, &db->user);
708 else if (db->url && strcasecmp ("Password", child->key) == 0)
709 status = cf_util_get_string (child, &db->pass);
710 else if (strcasecmp ("Digest", child->key) == 0)
711 status = cf_util_get_boolean (child, &db->digest);
712 else if (db->url && strcasecmp ("VerifyPeer", child->key) == 0)
713 status = cf_util_get_boolean (child, &db->verify_peer);
714 else if (db->url && strcasecmp ("VerifyHost", child->key) == 0)
715 status = cf_util_get_boolean (child, &db->verify_host);
716 else if (db->url && strcasecmp ("CACert", child->key) == 0)
717 status = cf_util_get_string (child, &db->cacert);
718 else if (db->url && strcasecmp ("Header", child->key) == 0)
719 status = cj_config_append_string ("Header", &db->headers, child);
720 else if (db->url && strcasecmp ("Post", child->key) == 0)
721 status = cf_util_get_string (child, &db->post_body);
722 else if (strcasecmp ("Key", child->key) == 0)
723 status = cj_config_add_key (db, child);
724 else if (strcasecmp ("Interval", child->key) == 0)
725 status = cf_util_get_cdtime(child, &db->interval);
726 else if (strcasecmp ("Timeout", child->key) == 0)
727 status = cf_util_get_int (child, &db->timeout);
730 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
740 if (db->tree == NULL)
742 WARNING ("curl_json plugin: No (valid) `Key' block within `%s' \"`%s'\".",
743 db->url ? "URL" : "Sock", db->url ? db->url : db->sock);
746 if (status == 0 && db->url)
747 status = cj_init_curl (db);
750 /* If all went well, register this database for reading */
756 if (db->instance == NULL)
757 db->instance = strdup("default");
759 DEBUG ("curl_json plugin: Registering new read callback: %s",
762 memset (&ud, 0, sizeof (ud));
763 ud.data = (void *) db;
764 ud.free_func = cj_free;
766 cb_name = ssnprintf_alloc ("curl_json-%s-%s",
767 db->instance, db->url ? db->url : db->sock);
769 plugin_register_complex_read (/* group = */ NULL, cb_name, cj_read,
770 /* interval = */ db->interval,
782 /* }}} int cj_config_add_database */
784 static int cj_config (oconfig_item_t *ci) /* {{{ */
794 for (i = 0; i < ci->children_num; i++)
796 oconfig_item_t *child = ci->children + i;
798 if (strcasecmp ("Sock", child->key) == 0
799 || strcasecmp ("URL", child->key) == 0)
801 status = cj_config_add_url (child);
809 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
814 if ((success == 0) && (errors > 0))
816 ERROR ("curl_json plugin: All statements failed.");
821 } /* }}} int cj_config */
823 /* }}} End of configuration handling functions */
825 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
827 value_list_t vl = VALUE_LIST_INIT;
833 if ((db->host == NULL)
834 || (strcmp ("", db->host) == 0)
835 || (strcmp (CJ_DEFAULT_HOST, db->host) == 0))
840 if (key->instance == NULL)
843 for (i = 0; i < db->depth; i++)
844 len += ssnprintf(vl.type_instance+len, sizeof(vl.type_instance)-len,
845 i ? "-%s" : "%s", db->state[i+1].name);
848 sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
850 sstrncpy (vl.host, host, sizeof (vl.host));
851 sstrncpy (vl.plugin, "curl_json", sizeof (vl.plugin));
852 sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
853 sstrncpy (vl.type, key->type, sizeof (vl.type));
855 if (db->interval > 0)
856 vl.interval = db->interval;
858 plugin_dispatch_values (&vl);
859 } /* }}} int cj_submit */
861 static int cj_sock_perform (cj_t *db) /* {{{ */
864 struct sockaddr_un sa_unix = {};
865 sa_unix.sun_family = AF_UNIX;
866 sstrncpy (sa_unix.sun_path, db->sock, sizeof (sa_unix.sun_path));
868 int fd = socket (AF_UNIX, SOCK_STREAM, 0);
871 if (connect (fd, (struct sockaddr *)&sa_unix, sizeof(sa_unix)) < 0)
873 ERROR ("curl_json plugin: connect(%s) failed: %s",
874 (db->sock != NULL) ? db->sock : "<null>",
875 sstrerror(errno, errbuf, sizeof (errbuf)));
882 unsigned char buffer[4096];
883 red = read (fd, buffer, sizeof(buffer));
885 ERROR ("curl_json plugin: read(%s) failed: %s",
886 (db->sock != NULL) ? db->sock : "<null>",
887 sstrerror(errno, errbuf, sizeof (errbuf)));
891 if (!cj_curl_callback (buffer, red, 1, db))
896 } /* }}} int cj_sock_perform */
899 static int cj_curl_perform(cj_t *db) /* {{{ */
906 status = curl_easy_perform (db->curl);
907 if (status != CURLE_OK)
909 ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
910 status, db->curl_errbuf, url);
914 curl_easy_getinfo(db->curl, CURLINFO_EFFECTIVE_URL, &url);
915 curl_easy_getinfo(db->curl, CURLINFO_RESPONSE_CODE, &rc);
917 /* The response code is zero if a non-HTTP transport was used. */
918 if ((rc != 0) && (rc != 200))
920 ERROR ("curl_json plugin: curl_easy_perform failed with "
921 "response code %ld (%s)", rc, url);
925 } /* }}} int cj_curl_perform */
927 static int cj_perform (cj_t *db) /* {{{ */
930 yajl_handle yprev = db->yajl;
932 db->yajl = yajl_alloc (&ycallbacks,
934 /* alloc funcs = */ NULL,
936 /* alloc funcs = */ NULL, NULL,
938 /* context = */ (void *)db);
939 if (db->yajl == NULL)
941 ERROR ("curl_json plugin: yajl_alloc failed.");
947 status = cj_curl_perform (db);
949 status = cj_sock_perform (db);
952 yajl_free (db->yajl);
958 status = yajl_complete_parse(db->yajl);
960 status = yajl_parse_complete(db->yajl);
962 if (status != yajl_status_ok)
964 unsigned char *errmsg;
966 errmsg = yajl_get_error (db->yajl, /* verbose = */ 0,
967 /* jsonText = */ NULL, /* jsonTextLen = */ 0);
968 ERROR ("curl_json plugin: yajl_parse_complete failed: %s",
970 yajl_free_error (db->yajl, errmsg);
971 yajl_free (db->yajl);
976 yajl_free (db->yajl);
979 } /* }}} int cj_perform */
981 static int cj_read (user_data_t *ud) /* {{{ */
985 if ((ud == NULL) || (ud->data == NULL))
987 ERROR ("curl_json plugin: cj_read: Invalid user data.");
991 db = (cj_t *) ud->data;
994 memset (&db->state, 0, sizeof(db->state));
995 db->state[db->depth].tree = db->tree;
998 return cj_perform (db);
999 } /* }}} int cj_read */
1001 static int cj_init (void) /* {{{ */
1003 /* Call this while collectd is still single-threaded to avoid
1004 * initialization issues in libgcrypt. */
1005 curl_global_init (CURL_GLOBAL_SSL);
1007 } /* }}} int cj_init */
1009 void module_register (void)
1011 plugin_register_complex_config ("curl_json", cj_config);
1012 plugin_register_init ("curl_json", cj_init);
1013 } /* void module_register */
1015 /* vim: set sw=2 sts=2 et fdm=marker : */