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 = */ 0);
236 return (CJ_CB_CONTINUE);
238 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
241 type = cj_get_type (key);
242 status = parse_value (buffer, &vt, type);
245 NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
246 return (CJ_CB_CONTINUE);
249 cj_submit (db, key, &vt);
250 return (CJ_CB_CONTINUE);
251 } /* int cj_cb_number */
253 /* Queries the key-tree of the parent context for "in_name" and, if found,
254 * updates the "key" field of the current context. Otherwise, "key" is set to
256 static int cj_cb_map_key (void *ctx,
257 unsigned char const *in_name, yajl_len_t in_name_len)
259 cj_t *db = (cj_t *)ctx;
262 tree = db->state[db->depth-1].tree;
266 cj_key_t *value = NULL;
270 /* Create a null-terminated version of the name. */
271 name = db->state[db->depth].name;
272 name_len = COUCH_MIN ((size_t) in_name_len,
273 sizeof (db->state[db->depth].name) - 1);
274 memcpy (name, in_name, name_len);
277 if (c_avl_get (tree, name, (void *) &value) == 0)
278 db->state[db->depth].key = value;
279 else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
280 db->state[db->depth].key = value;
282 db->state[db->depth].key = NULL;
285 return (CJ_CB_CONTINUE);
288 static int cj_cb_string (void *ctx, const unsigned char *val,
291 /* Handle the string as if it was a number. */
292 return (cj_cb_number (ctx, (const char *) val, len));
293 } /* int cj_cb_string */
295 static int cj_cb_start (void *ctx)
297 cj_t *db = (cj_t *)ctx;
298 if (++db->depth >= YAJL_MAX_DEPTH)
300 ERROR ("curl_json plugin: %s depth exceeds max, aborting.",
301 db->url ? db->url : db->sock);
302 return (CJ_CB_ABORT);
304 return (CJ_CB_CONTINUE);
307 static int cj_cb_end (void *ctx)
309 cj_t *db = (cj_t *)ctx;
310 db->state[db->depth].tree = NULL;
312 return (CJ_CB_CONTINUE);
315 static int cj_cb_start_map (void *ctx)
317 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
318 return cj_cb_start (ctx);
321 static int cj_cb_end_map (void *ctx)
323 return cj_cb_end (ctx);
326 static int cj_cb_start_array (void * ctx)
328 cj_t *db = (cj_t *)ctx;
329 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
330 if (db->depth+1 < YAJL_MAX_DEPTH) {
331 db->state[db->depth+1].in_array = 1;
332 db->state[db->depth+1].index = 0;
334 return cj_cb_start (ctx);
337 static int cj_cb_end_array (void * ctx)
339 cj_t *db = (cj_t *)ctx;
340 db->state[db->depth].in_array = 0;
341 return cj_cb_end (ctx);
344 static yajl_callbacks ycallbacks = {
345 cj_cb_null, /* null */
346 cj_cb_boolean, /* boolean */
358 /* end yajl callbacks */
360 static void cj_key_free (cj_key_t *key) /* {{{ */
367 sfree (key->instance);
370 } /* }}} void cj_key_free */
372 static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
377 while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
379 cj_key_t *key = (cj_key_t *)value;
384 cj_tree_free ((c_avl_tree_t *)value);
389 c_avl_destroy (tree);
390 } /* }}} void cj_tree_free */
392 static void cj_free (void *arg) /* {{{ */
396 DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
403 if (db->curl != NULL)
404 curl_easy_cleanup (db->curl);
407 if (db->tree != NULL)
408 cj_tree_free (db->tree);
411 sfree (db->instance);
419 sfree (db->credentials);
421 sfree (db->post_body);
422 curl_slist_free_all (db->headers);
425 } /* }}} void cj_free */
427 /* Configuration handling functions {{{ */
429 static c_avl_tree_t *cj_avl_create(void)
431 return c_avl_create ((int (*) (const void *, const void *)) strcmp);
434 static int cj_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
437 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
439 WARNING ("curl_json plugin: `%s' needs exactly one string argument.", name);
443 *dest = curl_slist_append(*dest, ci->values[0].value.string);
448 } /* }}} int cj_config_append_string */
450 static int cj_config_add_key (cj_t *db, /* {{{ */
457 if ((ci->values_num != 1)
458 || (ci->values[0].type != OCONFIG_TYPE_STRING))
460 WARNING ("curl_json plugin: The `Key' block "
461 "needs exactly one string argument.");
465 key = (cj_key_t *) malloc (sizeof (*key));
468 ERROR ("curl_json plugin: malloc failed.");
471 memset (key, 0, sizeof (*key));
472 key->magic = CJ_KEY_MAGIC;
474 if (strcasecmp ("Key", ci->key) == 0)
476 status = cf_util_get_string (ci, &key->path);
485 ERROR ("curl_json plugin: cj_config: "
486 "Invalid key: %s", ci->key);
491 for (i = 0; i < ci->children_num; i++)
493 oconfig_item_t *child = ci->children + i;
495 if (strcasecmp ("Type", child->key) == 0)
496 status = cf_util_get_string (child, &key->type);
497 else if (strcasecmp ("Instance", child->key) == 0)
498 status = cf_util_get_string (child, &key->instance);
501 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
507 } /* for (i = 0; i < ci->children_num; i++) */
511 if (key->type == NULL)
513 WARNING ("curl_json plugin: `Type' missing in `Key' block.");
518 } /* while (status == 0) */
520 /* store path in a tree that will match the json map structure, example:
521 * "httpd/requests/count",
522 * "httpd/requests/current" ->
523 * { "httpd": { "requests": { "count": $key, "current": $key } } }
532 if (db->tree == NULL)
533 db->tree = cj_avl_create();
552 len = COUCH_MIN(len, sizeof (ent)-1);
553 sstrncpy (ent, name, len+1);
555 if (c_avl_get (tree, ent, (void *) &value) != 0)
557 value = cj_avl_create ();
558 c_avl_insert (tree, strdup (ent), value);
567 c_avl_insert (tree, strdup(name), key);
570 ERROR ("curl_json plugin: invalid key: %s", key->path);
576 } /* }}} int cj_config_add_key */
578 static int cj_init_curl (cj_t *db) /* {{{ */
580 db->curl = curl_easy_init ();
581 if (db->curl == NULL)
583 ERROR ("curl_json plugin: curl_easy_init failed.");
587 curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
588 curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
589 curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
590 curl_easy_setopt (db->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
591 curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
592 curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
594 if (db->user != NULL)
596 size_t credentials_size;
598 credentials_size = strlen (db->user) + 2;
599 if (db->pass != NULL)
600 credentials_size += strlen (db->pass);
602 db->credentials = (char *) malloc (credentials_size);
603 if (db->credentials == NULL)
605 ERROR ("curl_json plugin: malloc failed.");
609 ssnprintf (db->credentials, credentials_size, "%s:%s",
610 db->user, (db->pass == NULL) ? "" : db->pass);
611 curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
614 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (long) db->verify_peer);
615 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
616 db->verify_host ? 2L : 0L);
617 if (db->cacert != NULL)
618 curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
619 if (db->headers != NULL)
620 curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
621 if (db->post_body != NULL)
622 curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
625 } /* }}} int cj_init_curl */
627 static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
633 if ((ci->values_num != 1)
634 || (ci->values[0].type != OCONFIG_TYPE_STRING))
636 WARNING ("curl_json plugin: The `URL' block "
637 "needs exactly one string argument.");
641 db = (cj_t *) malloc (sizeof (*db));
644 ERROR ("curl_json plugin: malloc failed.");
647 memset (db, 0, sizeof (*db));
649 if (strcasecmp ("URL", ci->key) == 0)
650 status = cf_util_get_string (ci, &db->url);
651 else if (strcasecmp ("Sock", ci->key) == 0)
652 status = cf_util_get_string (ci, &db->sock);
655 ERROR ("curl_json plugin: cj_config: "
656 "Invalid key: %s", ci->key);
665 /* Fill the `cj_t' structure.. */
666 for (i = 0; i < ci->children_num; i++)
668 oconfig_item_t *child = ci->children + i;
670 if (strcasecmp ("Instance", child->key) == 0)
671 status = cf_util_get_string (child, &db->instance);
672 else if (strcasecmp ("Host", child->key) == 0)
673 status = cf_util_get_string (child, &db->host);
674 else if (db->url && strcasecmp ("User", child->key) == 0)
675 status = cf_util_get_string (child, &db->user);
676 else if (db->url && strcasecmp ("Password", child->key) == 0)
677 status = cf_util_get_string (child, &db->pass);
678 else if (db->url && strcasecmp ("VerifyPeer", child->key) == 0)
679 status = cf_util_get_boolean (child, &db->verify_peer);
680 else if (db->url && strcasecmp ("VerifyHost", child->key) == 0)
681 status = cf_util_get_boolean (child, &db->verify_host);
682 else if (db->url && strcasecmp ("CACert", child->key) == 0)
683 status = cf_util_get_string (child, &db->cacert);
684 else if (db->url && strcasecmp ("Header", child->key) == 0)
685 status = cj_config_append_string ("Header", &db->headers, child);
686 else if (db->url && strcasecmp ("Post", child->key) == 0)
687 status = cf_util_get_string (child, &db->post_body);
688 else if (strcasecmp ("Key", child->key) == 0)
689 status = cj_config_add_key (db, child);
692 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
702 if (db->tree == NULL)
704 WARNING ("curl_json plugin: No (valid) `Key' block within `%s' \"`%s'\".",
705 db->url ? "URL" : "Sock", db->url ? db->url : db->sock);
708 if (status == 0 && db->url)
709 status = cj_init_curl (db);
712 /* If all went well, register this database for reading */
716 char cb_name[DATA_MAX_NAME_LEN];
718 if (db->instance == NULL)
719 db->instance = strdup("default");
721 DEBUG ("curl_json plugin: Registering new read callback: %s",
724 memset (&ud, 0, sizeof (ud));
725 ud.data = (void *) db;
726 ud.free_func = cj_free;
728 ssnprintf (cb_name, sizeof (cb_name), "curl_json-%s-%s",
729 db->instance, db->url ? db->url : db->sock);
731 plugin_register_complex_read (/* group = */ NULL, cb_name, cj_read,
732 /* interval = */ NULL, &ud);
742 /* }}} int cj_config_add_database */
744 static int cj_config (oconfig_item_t *ci) /* {{{ */
754 for (i = 0; i < ci->children_num; i++)
756 oconfig_item_t *child = ci->children + i;
758 if (strcasecmp ("Sock", child->key) == 0
759 || strcasecmp ("URL", child->key) == 0)
761 status = cj_config_add_url (child);
769 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
774 if ((success == 0) && (errors > 0))
776 ERROR ("curl_json plugin: All statements failed.");
781 } /* }}} int cj_config */
783 /* }}} End of configuration handling functions */
785 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
787 value_list_t vl = VALUE_LIST_INIT;
793 if ((db->host == NULL)
794 || (strcmp ("", db->host) == 0)
795 || (strcmp (CJ_DEFAULT_HOST, db->host) == 0))
800 if (key->instance == NULL)
802 if ((db->depth == 0) || (strcmp ("", db->state[db->depth-1].name) == 0))
803 sstrncpy (vl.type_instance, db->state[db->depth].name, sizeof (vl.type_instance));
805 ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s",
806 db->state[db->depth-1].name, db->state[db->depth].name);
809 sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
811 sstrncpy (vl.host, host, sizeof (vl.host));
812 sstrncpy (vl.plugin, "curl_json", sizeof (vl.plugin));
813 sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
814 sstrncpy (vl.type, key->type, sizeof (vl.type));
816 plugin_dispatch_values (&vl);
817 } /* }}} int cj_submit */
819 static int cj_sock_perform (cj_t *db) /* {{{ */
822 struct sockaddr_un sa_unix = {};
823 sa_unix.sun_family = AF_UNIX;
824 sstrncpy (sa_unix.sun_path, db->sock, sizeof (sa_unix.sun_path));
826 int fd = socket (AF_UNIX, SOCK_STREAM, 0);
829 if (connect (fd, (struct sockaddr *)&sa_unix, sizeof(sa_unix)) < 0)
831 ERROR ("curl_json plugin: connect(%s) failed: %s",
832 (db->sock != NULL) ? db->sock : "<null>",
833 sstrerror(errno, errbuf, sizeof (errbuf)));
840 unsigned char buffer[4096];
841 red = read (fd, buffer, sizeof(buffer));
843 ERROR ("curl_json plugin: read(%s) failed: %s",
844 (db->sock != NULL) ? db->sock : "<null>",
845 sstrerror(errno, errbuf, sizeof (errbuf)));
849 if (!cj_curl_callback (buffer, red, 1, db))
854 } /* }}} int cj_sock_perform */
857 static int cj_curl_perform(cj_t *db) /* {{{ */
864 status = curl_easy_perform (db->curl);
865 if (status != CURLE_OK)
867 ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
868 status, db->curl_errbuf, url);
872 curl_easy_getinfo(db->curl, CURLINFO_EFFECTIVE_URL, &url);
873 curl_easy_getinfo(db->curl, CURLINFO_RESPONSE_CODE, &rc);
875 /* The response code is zero if a non-HTTP transport was used. */
876 if ((rc != 0) && (rc != 200))
878 ERROR ("curl_json plugin: curl_easy_perform failed with "
879 "response code %ld (%s)", rc, url);
883 } /* }}} int cj_curl_perform */
885 static int cj_perform (cj_t *db) /* {{{ */
888 yajl_handle yprev = db->yajl;
890 db->yajl = yajl_alloc (&ycallbacks,
892 /* alloc funcs = */ NULL,
894 /* alloc funcs = */ NULL, NULL,
896 /* context = */ (void *)db);
897 if (db->yajl == NULL)
899 ERROR ("curl_json plugin: yajl_alloc failed.");
905 status = cj_curl_perform (db);
907 status = cj_sock_perform (db);
910 yajl_free (db->yajl);
916 status = yajl_complete_parse(db->yajl);
918 status = yajl_parse_complete(db->yajl);
920 if (status != yajl_status_ok)
922 unsigned char *errmsg;
924 errmsg = yajl_get_error (db->yajl, /* verbose = */ 0,
925 /* jsonText = */ NULL, /* jsonTextLen = */ 0);
926 ERROR ("curl_json plugin: yajl_parse_complete failed: %s",
928 yajl_free_error (db->yajl, errmsg);
929 yajl_free (db->yajl);
934 yajl_free (db->yajl);
937 } /* }}} int cj_perform */
939 static int cj_read (user_data_t *ud) /* {{{ */
943 if ((ud == NULL) || (ud->data == NULL))
945 ERROR ("curl_json plugin: cj_read: Invalid user data.");
949 db = (cj_t *) ud->data;
952 memset (&db->state, 0, sizeof(db->state));
953 db->state[db->depth].tree = db->tree;
956 return cj_perform (db);
957 } /* }}} int cj_read */
959 void module_register (void)
961 plugin_register_complex_config ("curl_json", cj_config);
962 } /* void module_register */
964 /* vim: set sw=2 sts=2 et fdm=marker : */