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 /* {{{ */
78 struct curl_slist *headers;
84 char curl_errbuf[CURL_ERROR_SIZE];
97 char name[DATA_MAX_NAME_LEN];
98 } state[YAJL_MAX_DEPTH];
100 typedef struct cj_s cj_t; /* }}} */
103 typedef size_t yajl_len_t;
105 typedef unsigned int yajl_len_t;
108 static int cj_read (user_data_t *ud);
109 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value);
111 static size_t cj_curl_callback (void *buf, /* {{{ */
112 size_t size, size_t nmemb, void *user_data)
127 status = yajl_parse(db->yajl, (unsigned char *)buf, len);
128 if (status == yajl_status_ok)
131 else if (status == yajl_status_insufficient_data)
135 if (status != yajl_status_ok)
138 yajl_get_error(db->yajl, /* verbose = */ 1,
139 /* jsonText = */ (unsigned char *) buf, (unsigned int) len);
140 ERROR ("curl_json plugin: yajl_parse failed: %s", msg);
141 yajl_free_error(db->yajl, msg);
142 return (0); /* abort write callback */
146 } /* }}} size_t cj_curl_callback */
148 static int cj_get_type (cj_key_t *key)
150 const data_set_t *ds;
152 ds = plugin_get_ds (key->type);
155 static char type[DATA_MAX_NAME_LEN] = "!!!invalid!!!";
157 assert (key->type != NULL);
158 if (strcmp (type, key->type) != 0)
160 ERROR ("curl_json plugin: Unable to look up DS type \"%s\".",
162 sstrncpy (type, key->type, sizeof (type));
167 else if (ds->ds_num > 1)
169 static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
171 c_complain_once (LOG_WARNING, &complaint,
172 "curl_json plugin: The type \"%s\" has more than one data source. "
173 "This is currently not supported. I will return the type of the "
174 "first data source, but this will likely lead to problems later on.",
178 return ds->ds[0].type;
181 static int cj_cb_map_key (void *ctx, const unsigned char *val,
184 static void cj_cb_inc_array_index (void *ctx, _Bool update_key)
186 cj_t *db = (cj_t *)ctx;
188 if (!db->state[db->depth].in_array)
191 db->state[db->depth].index++;
195 char name[DATA_MAX_NAME_LEN];
197 ssnprintf (name, sizeof (name), "%d", db->state[db->depth].index - 1);
199 cj_cb_map_key (ctx, (unsigned char *)name, (yajl_len_t) strlen (name));
204 #define CJ_CB_ABORT 0
205 #define CJ_CB_CONTINUE 1
207 static int cj_cb_boolean (void * ctx, int boolVal)
209 cj_cb_inc_array_index (ctx, /* update_key = */ 0);
210 return (CJ_CB_CONTINUE);
213 static int cj_cb_null (void * ctx)
215 cj_cb_inc_array_index (ctx, /* update_key = */ 0);
216 return (CJ_CB_CONTINUE);
219 static int cj_cb_number (void *ctx,
220 const char *number, yajl_len_t number_len)
222 char buffer[number_len + 1];
224 cj_t *db = (cj_t *)ctx;
225 cj_key_t *key = db->state[db->depth].key;
230 /* Create a null-terminated version of the string. */
231 memcpy (buffer, number, number_len);
232 buffer[sizeof (buffer) - 1] = 0;
234 if ((key == NULL) || !CJ_IS_KEY (key)) {
235 if (key != NULL && !db->state[db->depth].in_array/*can be inhomogeneous*/)
236 NOTICE ("curl_json plugin: Found \"%s\", but the configuration expects"
238 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
239 key = db->state[db->depth].key;
241 return (CJ_CB_CONTINUE);
246 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
249 type = cj_get_type (key);
250 status = parse_value (buffer, &vt, type);
253 NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
254 return (CJ_CB_CONTINUE);
257 cj_submit (db, key, &vt);
258 return (CJ_CB_CONTINUE);
259 } /* int cj_cb_number */
261 /* Queries the key-tree of the parent context for "in_name" and, if found,
262 * updates the "key" field of the current context. Otherwise, "key" is set to
264 static int cj_cb_map_key (void *ctx,
265 unsigned char const *in_name, yajl_len_t in_name_len)
267 cj_t *db = (cj_t *)ctx;
270 tree = db->state[db->depth-1].tree;
274 cj_key_t *value = NULL;
278 /* Create a null-terminated version of the name. */
279 name = db->state[db->depth].name;
280 name_len = COUCH_MIN ((size_t) in_name_len,
281 sizeof (db->state[db->depth].name) - 1);
282 memcpy (name, in_name, name_len);
285 if (c_avl_get (tree, name, (void *) &value) == 0) {
286 if (CJ_IS_KEY((cj_key_t*)value)) {
287 db->state[db->depth].key = value;
290 db->state[db->depth].tree = (c_avl_tree_t*) value;
293 else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
294 if (CJ_IS_KEY((cj_key_t*)value)) {
295 db->state[db->depth].key = value;
298 db->state[db->depth].tree = (c_avl_tree_t*) value;
301 db->state[db->depth].key = NULL;
304 return (CJ_CB_CONTINUE);
307 static int cj_cb_string (void *ctx, const unsigned char *val,
310 /* Handle the string as if it was a number. */
311 return (cj_cb_number (ctx, (const char *) val, len));
312 } /* int cj_cb_string */
314 static int cj_cb_start (void *ctx)
316 cj_t *db = (cj_t *)ctx;
317 if (++db->depth >= YAJL_MAX_DEPTH)
319 ERROR ("curl_json plugin: %s depth exceeds max, aborting.",
320 db->url ? db->url : db->sock);
321 return (CJ_CB_ABORT);
323 return (CJ_CB_CONTINUE);
326 static int cj_cb_end (void *ctx)
328 cj_t *db = (cj_t *)ctx;
329 db->state[db->depth].tree = NULL;
331 return (CJ_CB_CONTINUE);
334 static int cj_cb_start_map (void *ctx)
336 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
337 return cj_cb_start (ctx);
340 static int cj_cb_end_map (void *ctx)
342 return cj_cb_end (ctx);
345 static int cj_cb_start_array (void * ctx)
347 cj_t *db = (cj_t *)ctx;
348 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
349 if (db->depth+1 < YAJL_MAX_DEPTH) {
350 db->state[db->depth+1].in_array = 1;
351 db->state[db->depth+1].index = 0;
353 return cj_cb_start (ctx);
356 static int cj_cb_end_array (void * ctx)
358 cj_t *db = (cj_t *)ctx;
359 db->state[db->depth].in_array = 0;
360 return cj_cb_end (ctx);
363 static yajl_callbacks ycallbacks = {
364 cj_cb_null, /* null */
365 cj_cb_boolean, /* boolean */
377 /* end yajl callbacks */
379 static void cj_key_free (cj_key_t *key) /* {{{ */
386 sfree (key->instance);
389 } /* }}} void cj_key_free */
391 static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
396 while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
398 cj_key_t *key = (cj_key_t *)value;
403 cj_tree_free ((c_avl_tree_t *)value);
408 c_avl_destroy (tree);
409 } /* }}} void cj_tree_free */
411 static void cj_free (void *arg) /* {{{ */
415 DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
422 if (db->curl != NULL)
423 curl_easy_cleanup (db->curl);
426 if (db->tree != NULL)
427 cj_tree_free (db->tree);
430 sfree (db->instance);
438 sfree (db->credentials);
440 sfree (db->post_body);
441 curl_slist_free_all (db->headers);
444 } /* }}} void cj_free */
446 /* Configuration handling functions {{{ */
448 static c_avl_tree_t *cj_avl_create(void)
450 return c_avl_create ((int (*) (const void *, const void *)) strcmp);
453 static int cj_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
456 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
458 WARNING ("curl_json plugin: `%s' needs exactly one string argument.", name);
462 *dest = curl_slist_append(*dest, ci->values[0].value.string);
467 } /* }}} int cj_config_append_string */
469 static int cj_config_add_key (cj_t *db, /* {{{ */
476 if ((ci->values_num != 1)
477 || (ci->values[0].type != OCONFIG_TYPE_STRING))
479 WARNING ("curl_json plugin: The `Key' block "
480 "needs exactly one string argument.");
484 key = (cj_key_t *) malloc (sizeof (*key));
487 ERROR ("curl_json plugin: malloc failed.");
490 memset (key, 0, sizeof (*key));
491 key->magic = CJ_KEY_MAGIC;
493 if (strcasecmp ("Key", ci->key) == 0)
495 status = cf_util_get_string (ci, &key->path);
504 ERROR ("curl_json plugin: cj_config: "
505 "Invalid key: %s", ci->key);
511 for (i = 0; i < ci->children_num; i++)
513 oconfig_item_t *child = ci->children + i;
515 if (strcasecmp ("Type", child->key) == 0)
516 status = cf_util_get_string (child, &key->type);
517 else if (strcasecmp ("Instance", child->key) == 0)
518 status = cf_util_get_string (child, &key->instance);
521 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
527 } /* for (i = 0; i < ci->children_num; i++) */
531 if (key->type == NULL)
533 WARNING ("curl_json plugin: `Type' missing in `Key' block.");
538 } /* while (status == 0) */
540 /* store path in a tree that will match the json map structure, example:
541 * "httpd/requests/count",
542 * "httpd/requests/current" ->
543 * { "httpd": { "requests": { "count": $key, "current": $key } } }
552 if (db->tree == NULL)
553 db->tree = cj_avl_create();
571 len = COUCH_MIN(len, sizeof (ent)-1);
572 sstrncpy (ent, name, len+1);
574 if (c_avl_get (tree, ent, (void *) &value) != 0)
576 value = cj_avl_create ();
577 c_avl_insert (tree, strdup (ent), value);
586 c_avl_insert (tree, strdup(name), key);
589 ERROR ("curl_json plugin: invalid key: %s", key->path);
595 } /* }}} int cj_config_add_key */
597 static int cj_init_curl (cj_t *db) /* {{{ */
599 db->curl = curl_easy_init ();
600 if (db->curl == NULL)
602 ERROR ("curl_json plugin: curl_easy_init failed.");
606 curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
607 curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
608 curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
609 curl_easy_setopt (db->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
610 curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
611 curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
612 curl_easy_setopt (db->curl, CURLOPT_FOLLOWLOCATION, 1L);
613 curl_easy_setopt (db->curl, CURLOPT_MAXREDIRS, 50L);
615 if (db->user != NULL)
617 #ifdef HAVE_CURLOPT_USERNAME
618 curl_easy_setopt (db->curl, CURLOPT_USERNAME, db->user);
619 curl_easy_setopt (db->curl, CURLOPT_PASSWORD,
620 (db->pass == NULL) ? "" : db->pass);
622 size_t credentials_size;
624 credentials_size = strlen (db->user) + 2;
625 if (db->pass != NULL)
626 credentials_size += strlen (db->pass);
628 db->credentials = (char *) malloc (credentials_size);
629 if (db->credentials == NULL)
631 ERROR ("curl_json plugin: malloc failed.");
635 ssnprintf (db->credentials, credentials_size, "%s:%s",
636 db->user, (db->pass == NULL) ? "" : db->pass);
637 curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
641 curl_easy_setopt (db->curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
644 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (long) db->verify_peer);
645 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
646 db->verify_host ? 2L : 0L);
647 if (db->cacert != NULL)
648 curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
649 if (db->headers != NULL)
650 curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
651 if (db->post_body != NULL)
652 curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
654 #ifdef HAVE_CURLOPT_TIMEOUT_MS
655 if (db->timeout >= 0)
656 curl_easy_setopt (db->curl, CURLOPT_TIMEOUT_MS, (long) db->timeout);
657 else if (db->interval > 0)
658 curl_easy_setopt (db->curl, CURLOPT_TIMEOUT_MS,
659 CDTIME_T_TO_MS(db->timeout));
661 curl_easy_setopt (db->curl, CURLOPT_TIMEOUT_MS,
662 CDTIME_T_TO_MS(plugin_get_interval()));
666 } /* }}} int cj_init_curl */
668 static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
674 if ((ci->values_num != 1)
675 || (ci->values[0].type != OCONFIG_TYPE_STRING))
677 WARNING ("curl_json plugin: The `URL' block "
678 "needs exactly one string argument.");
682 db = (cj_t *) malloc (sizeof (*db));
685 ERROR ("curl_json plugin: malloc failed.");
688 memset (db, 0, sizeof (*db));
692 if (strcasecmp ("URL", ci->key) == 0)
693 status = cf_util_get_string (ci, &db->url);
694 else if (strcasecmp ("Sock", ci->key) == 0)
695 status = cf_util_get_string (ci, &db->sock);
698 ERROR ("curl_json plugin: cj_config: "
699 "Invalid key: %s", ci->key);
709 /* Fill the `cj_t' structure.. */
710 for (i = 0; i < ci->children_num; i++)
712 oconfig_item_t *child = ci->children + i;
714 if (strcasecmp ("Instance", child->key) == 0)
715 status = cf_util_get_string (child, &db->instance);
716 else if (strcasecmp ("Host", child->key) == 0)
717 status = cf_util_get_string (child, &db->host);
718 else if (db->url && strcasecmp ("User", child->key) == 0)
719 status = cf_util_get_string (child, &db->user);
720 else if (db->url && strcasecmp ("Password", child->key) == 0)
721 status = cf_util_get_string (child, &db->pass);
722 else if (strcasecmp ("Digest", child->key) == 0)
723 status = cf_util_get_boolean (child, &db->digest);
724 else if (db->url && strcasecmp ("VerifyPeer", child->key) == 0)
725 status = cf_util_get_boolean (child, &db->verify_peer);
726 else if (db->url && strcasecmp ("VerifyHost", child->key) == 0)
727 status = cf_util_get_boolean (child, &db->verify_host);
728 else if (db->url && strcasecmp ("CACert", child->key) == 0)
729 status = cf_util_get_string (child, &db->cacert);
730 else if (db->url && strcasecmp ("Header", child->key) == 0)
731 status = cj_config_append_string ("Header", &db->headers, child);
732 else if (db->url && strcasecmp ("Post", child->key) == 0)
733 status = cf_util_get_string (child, &db->post_body);
734 else if (strcasecmp ("Key", child->key) == 0)
735 status = cj_config_add_key (db, child);
736 else if (strcasecmp ("Interval", child->key) == 0)
737 status = cf_util_get_cdtime(child, &db->interval);
738 else if (strcasecmp ("Timeout", child->key) == 0)
739 status = cf_util_get_int (child, &db->timeout);
742 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
752 if (db->tree == NULL)
754 WARNING ("curl_json plugin: No (valid) `Key' block within `%s' \"`%s'\".",
755 db->url ? "URL" : "Sock", db->url ? db->url : db->sock);
758 if (status == 0 && db->url)
759 status = cj_init_curl (db);
762 /* If all went well, register this database for reading */
768 if (db->instance == NULL)
769 db->instance = strdup("default");
771 DEBUG ("curl_json plugin: Registering new read callback: %s",
774 memset (&ud, 0, sizeof (ud));
775 ud.data = (void *) db;
776 ud.free_func = cj_free;
778 cb_name = ssnprintf_alloc ("curl_json-%s-%s",
779 db->instance, db->url ? db->url : db->sock);
781 plugin_register_complex_read (/* group = */ NULL, cb_name, cj_read,
782 /* interval = */ db->interval,
794 /* }}} int cj_config_add_database */
796 static int cj_config (oconfig_item_t *ci) /* {{{ */
806 for (i = 0; i < ci->children_num; i++)
808 oconfig_item_t *child = ci->children + i;
810 if (strcasecmp ("Sock", child->key) == 0
811 || strcasecmp ("URL", child->key) == 0)
813 status = cj_config_add_url (child);
821 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
826 if ((success == 0) && (errors > 0))
828 ERROR ("curl_json plugin: All statements failed.");
833 } /* }}} int cj_config */
835 /* }}} End of configuration handling functions */
837 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
839 value_list_t vl = VALUE_LIST_INIT;
845 if ((db->host == NULL)
846 || (strcmp ("", db->host) == 0)
847 || (strcmp (CJ_DEFAULT_HOST, db->host) == 0))
852 if (key->instance == NULL)
855 for (i = 0; i < db->depth; i++)
856 len += ssnprintf(vl.type_instance+len, sizeof(vl.type_instance)-len,
857 i ? "-%s" : "%s", db->state[i+1].name);
860 sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
862 sstrncpy (vl.host, host, sizeof (vl.host));
863 sstrncpy (vl.plugin, "curl_json", sizeof (vl.plugin));
864 sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
865 sstrncpy (vl.type, key->type, sizeof (vl.type));
867 if (db->interval > 0)
868 vl.interval = db->interval;
870 plugin_dispatch_values (&vl);
871 } /* }}} int cj_submit */
873 static int cj_sock_perform (cj_t *db) /* {{{ */
876 struct sockaddr_un sa_unix = {};
877 sa_unix.sun_family = AF_UNIX;
878 sstrncpy (sa_unix.sun_path, db->sock, sizeof (sa_unix.sun_path));
880 int fd = socket (AF_UNIX, SOCK_STREAM, 0);
883 if (connect (fd, (struct sockaddr *)&sa_unix, sizeof(sa_unix)) < 0)
885 ERROR ("curl_json plugin: connect(%s) failed: %s",
886 (db->sock != NULL) ? db->sock : "<null>",
887 sstrerror(errno, errbuf, sizeof (errbuf)));
894 unsigned char buffer[4096];
895 red = read (fd, buffer, sizeof(buffer));
897 ERROR ("curl_json plugin: read(%s) failed: %s",
898 (db->sock != NULL) ? db->sock : "<null>",
899 sstrerror(errno, errbuf, sizeof (errbuf)));
903 if (!cj_curl_callback (buffer, red, 1, db))
908 } /* }}} int cj_sock_perform */
911 static int cj_curl_perform(cj_t *db) /* {{{ */
918 status = curl_easy_perform (db->curl);
919 if (status != CURLE_OK)
921 ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
922 status, db->curl_errbuf, url);
926 curl_easy_getinfo(db->curl, CURLINFO_EFFECTIVE_URL, &url);
927 curl_easy_getinfo(db->curl, CURLINFO_RESPONSE_CODE, &rc);
929 /* The response code is zero if a non-HTTP transport was used. */
930 if ((rc != 0) && (rc != 200))
932 ERROR ("curl_json plugin: curl_easy_perform failed with "
933 "response code %ld (%s)", rc, url);
937 } /* }}} int cj_curl_perform */
939 static int cj_perform (cj_t *db) /* {{{ */
942 yajl_handle yprev = db->yajl;
944 db->yajl = yajl_alloc (&ycallbacks,
946 /* alloc funcs = */ NULL,
948 /* alloc funcs = */ NULL, NULL,
950 /* context = */ (void *)db);
951 if (db->yajl == NULL)
953 ERROR ("curl_json plugin: yajl_alloc failed.");
959 status = cj_curl_perform (db);
961 status = cj_sock_perform (db);
964 yajl_free (db->yajl);
970 status = yajl_complete_parse(db->yajl);
972 status = yajl_parse_complete(db->yajl);
974 if (status != yajl_status_ok)
976 unsigned char *errmsg;
978 errmsg = yajl_get_error (db->yajl, /* verbose = */ 0,
979 /* jsonText = */ NULL, /* jsonTextLen = */ 0);
980 ERROR ("curl_json plugin: yajl_parse_complete failed: %s",
982 yajl_free_error (db->yajl, errmsg);
983 yajl_free (db->yajl);
988 yajl_free (db->yajl);
991 } /* }}} int cj_perform */
993 static int cj_read (user_data_t *ud) /* {{{ */
997 if ((ud == NULL) || (ud->data == NULL))
999 ERROR ("curl_json plugin: cj_read: Invalid user data.");
1003 db = (cj_t *) ud->data;
1006 memset (&db->state, 0, sizeof(db->state));
1007 db->state[db->depth].tree = db->tree;
1010 return cj_perform (db);
1011 } /* }}} int cj_read */
1013 static int cj_init (void) /* {{{ */
1015 /* Call this while collectd is still single-threaded to avoid
1016 * initialization issues in libgcrypt. */
1017 curl_global_init (CURL_GLOBAL_SSL);
1019 } /* }}} int cj_init */
1021 void module_register (void)
1023 plugin_register_complex_config ("curl_json", cj_config);
1024 plugin_register_init ("curl_json", cj_init);
1025 } /* void module_register */
1027 /* vim: set sw=2 sts=2 et fdm=marker : */