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;
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 if (status != yajl_status_ok)
137 yajl_get_error(db->yajl, /* verbose = */ 1,
138 /* jsonText = */ (unsigned char *) buf, (unsigned int) len);
139 ERROR ("curl_json plugin: yajl_parse failed: %s", msg);
140 yajl_free_error(db->yajl, msg);
141 return (0); /* abort write callback */
145 } /* }}} size_t cj_curl_callback */
147 static int cj_get_type (cj_key_t *key)
149 const data_set_t *ds;
151 ds = plugin_get_ds (key->type);
154 static char type[DATA_MAX_NAME_LEN] = "!!!invalid!!!";
156 assert (key->type != NULL);
157 if (strcmp (type, key->type) != 0)
159 ERROR ("curl_json plugin: Unable to look up DS type \"%s\".",
161 sstrncpy (type, key->type, sizeof (type));
166 else if (ds->ds_num > 1)
168 static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
170 c_complain_once (LOG_WARNING, &complaint,
171 "curl_json plugin: The type \"%s\" has more than one data source. "
172 "This is currently not supported. I will return the type of the "
173 "first data source, but this will likely lead to problems later on.",
177 return ds->ds[0].type;
180 static int cj_cb_map_key (void *ctx, const unsigned char *val,
183 static void cj_cb_inc_array_index (void *ctx, _Bool update_key)
185 cj_t *db = (cj_t *)ctx;
187 if (!db->state[db->depth].in_array)
190 db->state[db->depth].index++;
194 char name[DATA_MAX_NAME_LEN];
196 ssnprintf (name, sizeof (name), "%d", db->state[db->depth].index - 1);
198 cj_cb_map_key (ctx, (unsigned char *)name, (yajl_len_t) strlen (name));
203 #define CJ_CB_ABORT 0
204 #define CJ_CB_CONTINUE 1
206 static int cj_cb_boolean (void * ctx, int boolVal)
208 cj_cb_inc_array_index (ctx, /* update_key = */ 0);
209 return (CJ_CB_CONTINUE);
212 static int cj_cb_null (void * ctx)
214 cj_cb_inc_array_index (ctx, /* update_key = */ 0);
215 return (CJ_CB_CONTINUE);
218 static int cj_cb_number (void *ctx,
219 const char *number, yajl_len_t number_len)
221 char buffer[number_len + 1];
223 cj_t *db = (cj_t *)ctx;
224 cj_key_t *key = db->state[db->depth].key;
229 /* Create a null-terminated version of the string. */
230 memcpy (buffer, number, number_len);
231 buffer[sizeof (buffer) - 1] = 0;
233 if ((key == NULL) || !CJ_IS_KEY (key)) {
235 NOTICE ("curl_json plugin: Found \"%s\", but the configuration expects"
237 cj_cb_inc_array_index (ctx, /* update_key = */ 0);
238 return (CJ_CB_CONTINUE);
240 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
243 type = cj_get_type (key);
244 status = parse_value (buffer, &vt, type);
247 NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
248 return (CJ_CB_CONTINUE);
251 cj_submit (db, key, &vt);
252 return (CJ_CB_CONTINUE);
253 } /* int cj_cb_number */
255 /* Queries the key-tree of the parent context for "in_name" and, if found,
256 * updates the "key" field of the current context. Otherwise, "key" is set to
258 static int cj_cb_map_key (void *ctx,
259 unsigned char const *in_name, yajl_len_t in_name_len)
261 cj_t *db = (cj_t *)ctx;
264 tree = db->state[db->depth-1].tree;
268 cj_key_t *value = NULL;
272 /* Create a null-terminated version of the name. */
273 name = db->state[db->depth].name;
274 name_len = COUCH_MIN ((size_t) in_name_len,
275 sizeof (db->state[db->depth].name) - 1);
276 memcpy (name, in_name, name_len);
279 if (c_avl_get (tree, name, (void *) &value) == 0)
280 db->state[db->depth].key = value;
281 else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
282 db->state[db->depth].key = value;
284 db->state[db->depth].key = NULL;
287 return (CJ_CB_CONTINUE);
290 static int cj_cb_string (void *ctx, const unsigned char *val,
293 /* Handle the string as if it was a number. */
294 return (cj_cb_number (ctx, (const char *) val, len));
295 } /* int cj_cb_string */
297 static int cj_cb_start (void *ctx)
299 cj_t *db = (cj_t *)ctx;
300 if (++db->depth >= YAJL_MAX_DEPTH)
302 ERROR ("curl_json plugin: %s depth exceeds max, aborting.",
303 db->url ? db->url : db->sock);
304 return (CJ_CB_ABORT);
306 return (CJ_CB_CONTINUE);
309 static int cj_cb_end (void *ctx)
311 cj_t *db = (cj_t *)ctx;
312 db->state[db->depth].tree = NULL;
314 return (CJ_CB_CONTINUE);
317 static int cj_cb_start_map (void *ctx)
319 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
320 return cj_cb_start (ctx);
323 static int cj_cb_end_map (void *ctx)
325 return cj_cb_end (ctx);
328 static int cj_cb_start_array (void * ctx)
330 cj_t *db = (cj_t *)ctx;
331 cj_cb_inc_array_index (ctx, /* update_key = */ 1);
332 if (db->depth+1 < YAJL_MAX_DEPTH) {
333 db->state[db->depth+1].in_array = 1;
334 db->state[db->depth+1].index = 0;
336 return cj_cb_start (ctx);
339 static int cj_cb_end_array (void * ctx)
341 cj_t *db = (cj_t *)ctx;
342 db->state[db->depth].in_array = 0;
343 return cj_cb_end (ctx);
346 static yajl_callbacks ycallbacks = {
347 cj_cb_null, /* null */
348 cj_cb_boolean, /* boolean */
360 /* end yajl callbacks */
362 static void cj_key_free (cj_key_t *key) /* {{{ */
369 sfree (key->instance);
372 } /* }}} void cj_key_free */
374 static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
379 while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
381 cj_key_t *key = (cj_key_t *)value;
386 cj_tree_free ((c_avl_tree_t *)value);
391 c_avl_destroy (tree);
392 } /* }}} void cj_tree_free */
394 static void cj_free (void *arg) /* {{{ */
398 DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
405 if (db->curl != NULL)
406 curl_easy_cleanup (db->curl);
409 if (db->tree != NULL)
410 cj_tree_free (db->tree);
413 sfree (db->instance);
421 sfree (db->credentials);
423 sfree (db->post_body);
424 curl_slist_free_all (db->headers);
427 } /* }}} void cj_free */
429 /* Configuration handling functions {{{ */
431 static c_avl_tree_t *cj_avl_create(void)
433 return c_avl_create ((int (*) (const void *, const void *)) strcmp);
436 static int cj_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
439 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
441 WARNING ("curl_json plugin: `%s' needs exactly one string argument.", name);
445 *dest = curl_slist_append(*dest, ci->values[0].value.string);
450 } /* }}} int cj_config_append_string */
452 static int cj_config_add_key (cj_t *db, /* {{{ */
459 if ((ci->values_num != 1)
460 || (ci->values[0].type != OCONFIG_TYPE_STRING))
462 WARNING ("curl_json plugin: The `Key' block "
463 "needs exactly one string argument.");
467 key = (cj_key_t *) malloc (sizeof (*key));
470 ERROR ("curl_json plugin: malloc failed.");
473 memset (key, 0, sizeof (*key));
474 key->magic = CJ_KEY_MAGIC;
476 if (strcasecmp ("Key", ci->key) == 0)
478 status = cf_util_get_string (ci, &key->path);
487 ERROR ("curl_json plugin: cj_config: "
488 "Invalid key: %s", ci->key);
493 for (i = 0; i < ci->children_num; i++)
495 oconfig_item_t *child = ci->children + i;
497 if (strcasecmp ("Type", child->key) == 0)
498 status = cf_util_get_string (child, &key->type);
499 else if (strcasecmp ("Instance", child->key) == 0)
500 status = cf_util_get_string (child, &key->instance);
503 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
509 } /* for (i = 0; i < ci->children_num; i++) */
513 if (key->type == NULL)
515 WARNING ("curl_json plugin: `Type' missing in `Key' block.");
520 } /* while (status == 0) */
522 /* store path in a tree that will match the json map structure, example:
523 * "httpd/requests/count",
524 * "httpd/requests/current" ->
525 * { "httpd": { "requests": { "count": $key, "current": $key } } }
534 if (db->tree == NULL)
535 db->tree = cj_avl_create();
554 len = COUCH_MIN(len, sizeof (ent)-1);
555 sstrncpy (ent, name, len+1);
557 if (c_avl_get (tree, ent, (void *) &value) != 0)
559 value = cj_avl_create ();
560 c_avl_insert (tree, strdup (ent), value);
569 c_avl_insert (tree, strdup(name), key);
572 ERROR ("curl_json plugin: invalid key: %s", key->path);
578 } /* }}} int cj_config_add_key */
580 static int cj_init_curl (cj_t *db) /* {{{ */
582 db->curl = curl_easy_init ();
583 if (db->curl == NULL)
585 ERROR ("curl_json plugin: curl_easy_init failed.");
589 curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
590 curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
591 curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
592 curl_easy_setopt (db->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
593 curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
594 curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
596 if (db->user != NULL)
598 size_t credentials_size;
600 credentials_size = strlen (db->user) + 2;
601 if (db->pass != NULL)
602 credentials_size += strlen (db->pass);
604 db->credentials = (char *) malloc (credentials_size);
605 if (db->credentials == NULL)
607 ERROR ("curl_json plugin: malloc failed.");
611 ssnprintf (db->credentials, credentials_size, "%s:%s",
612 db->user, (db->pass == NULL) ? "" : db->pass);
613 curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
616 curl_easy_setopt (db->curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
619 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (long) db->verify_peer);
620 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
621 db->verify_host ? 2L : 0L);
622 if (db->cacert != NULL)
623 curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
624 if (db->headers != NULL)
625 curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
626 if (db->post_body != NULL)
627 curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
630 } /* }}} int cj_init_curl */
632 static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
638 if ((ci->values_num != 1)
639 || (ci->values[0].type != OCONFIG_TYPE_STRING))
641 WARNING ("curl_json plugin: The `URL' block "
642 "needs exactly one string argument.");
646 db = (cj_t *) malloc (sizeof (*db));
649 ERROR ("curl_json plugin: malloc failed.");
652 memset (db, 0, sizeof (*db));
654 if (strcasecmp ("URL", ci->key) == 0)
655 status = cf_util_get_string (ci, &db->url);
656 else if (strcasecmp ("Sock", ci->key) == 0)
657 status = cf_util_get_string (ci, &db->sock);
660 ERROR ("curl_json plugin: cj_config: "
661 "Invalid key: %s", ci->key);
670 /* Fill the `cj_t' structure.. */
671 for (i = 0; i < ci->children_num; i++)
673 oconfig_item_t *child = ci->children + i;
675 if (strcasecmp ("Instance", child->key) == 0)
676 status = cf_util_get_string (child, &db->instance);
677 else if (strcasecmp ("Host", child->key) == 0)
678 status = cf_util_get_string (child, &db->host);
679 else if (db->url && strcasecmp ("User", child->key) == 0)
680 status = cf_util_get_string (child, &db->user);
681 else if (db->url && strcasecmp ("Password", child->key) == 0)
682 status = cf_util_get_string (child, &db->pass);
683 else if (strcasecmp ("Digest", child->key) == 0)
684 status = cf_util_get_boolean (child, &db->digest);
685 else if (db->url && strcasecmp ("VerifyPeer", child->key) == 0)
686 status = cf_util_get_boolean (child, &db->verify_peer);
687 else if (db->url && strcasecmp ("VerifyHost", child->key) == 0)
688 status = cf_util_get_boolean (child, &db->verify_host);
689 else if (db->url && strcasecmp ("CACert", child->key) == 0)
690 status = cf_util_get_string (child, &db->cacert);
691 else if (db->url && strcasecmp ("Header", child->key) == 0)
692 status = cj_config_append_string ("Header", &db->headers, child);
693 else if (db->url && strcasecmp ("Post", child->key) == 0)
694 status = cf_util_get_string (child, &db->post_body);
695 else if (strcasecmp ("Key", child->key) == 0)
696 status = cj_config_add_key (db, child);
697 else if (strcasecmp ("Interval", child->key) == 0)
698 status = cf_util_get_cdtime(child, &db->interval);
701 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
711 if (db->tree == NULL)
713 WARNING ("curl_json plugin: No (valid) `Key' block within `%s' \"`%s'\".",
714 db->url ? "URL" : "Sock", db->url ? db->url : db->sock);
717 if (status == 0 && db->url)
718 status = cj_init_curl (db);
721 /* If all went well, register this database for reading */
725 char cb_name[DATA_MAX_NAME_LEN];
726 struct timespec interval = { 0, 0 };
728 CDTIME_T_TO_TIMESPEC (db->interval, &interval);
730 if (db->instance == NULL)
731 db->instance = strdup("default");
733 DEBUG ("curl_json plugin: Registering new read callback: %s",
736 memset (&ud, 0, sizeof (ud));
737 ud.data = (void *) db;
738 ud.free_func = cj_free;
740 ssnprintf (cb_name, sizeof (cb_name), "curl_json-%s-%s",
741 db->instance, db->url ? db->url : db->sock);
743 plugin_register_complex_read (/* group = */ NULL, cb_name, cj_read,
744 /* interval = */ (db->interval > 0) ? &interval : NULL,
755 /* }}} int cj_config_add_database */
757 static int cj_config (oconfig_item_t *ci) /* {{{ */
767 for (i = 0; i < ci->children_num; i++)
769 oconfig_item_t *child = ci->children + i;
771 if (strcasecmp ("Sock", child->key) == 0
772 || strcasecmp ("URL", child->key) == 0)
774 status = cj_config_add_url (child);
782 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
787 if ((success == 0) && (errors > 0))
789 ERROR ("curl_json plugin: All statements failed.");
794 } /* }}} int cj_config */
796 /* }}} End of configuration handling functions */
798 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
800 value_list_t vl = VALUE_LIST_INIT;
806 if ((db->host == NULL)
807 || (strcmp ("", db->host) == 0)
808 || (strcmp (CJ_DEFAULT_HOST, db->host) == 0))
813 if (key->instance == NULL)
816 for (i = 0; i < db->depth; i++)
817 len += ssnprintf(vl.type_instance+len, sizeof(vl.type_instance)-len,
818 i ? "-%s" : "%s", db->state[i+1].name);
821 sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
823 sstrncpy (vl.host, host, sizeof (vl.host));
824 sstrncpy (vl.plugin, "curl_json", sizeof (vl.plugin));
825 sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
826 sstrncpy (vl.type, key->type, sizeof (vl.type));
828 if (db->interval > 0)
829 vl.interval = db->interval;
831 plugin_dispatch_values (&vl);
832 } /* }}} int cj_submit */
834 static int cj_sock_perform (cj_t *db) /* {{{ */
837 struct sockaddr_un sa_unix = {};
838 sa_unix.sun_family = AF_UNIX;
839 sstrncpy (sa_unix.sun_path, db->sock, sizeof (sa_unix.sun_path));
841 int fd = socket (AF_UNIX, SOCK_STREAM, 0);
844 if (connect (fd, (struct sockaddr *)&sa_unix, sizeof(sa_unix)) < 0)
846 ERROR ("curl_json plugin: connect(%s) failed: %s",
847 (db->sock != NULL) ? db->sock : "<null>",
848 sstrerror(errno, errbuf, sizeof (errbuf)));
855 unsigned char buffer[4096];
856 red = read (fd, buffer, sizeof(buffer));
858 ERROR ("curl_json plugin: read(%s) failed: %s",
859 (db->sock != NULL) ? db->sock : "<null>",
860 sstrerror(errno, errbuf, sizeof (errbuf)));
864 if (!cj_curl_callback (buffer, red, 1, db))
869 } /* }}} int cj_sock_perform */
872 static int cj_curl_perform(cj_t *db) /* {{{ */
879 status = curl_easy_perform (db->curl);
880 if (status != CURLE_OK)
882 ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
883 status, db->curl_errbuf, url);
887 curl_easy_getinfo(db->curl, CURLINFO_EFFECTIVE_URL, &url);
888 curl_easy_getinfo(db->curl, CURLINFO_RESPONSE_CODE, &rc);
890 /* The response code is zero if a non-HTTP transport was used. */
891 if ((rc != 0) && (rc != 200))
893 ERROR ("curl_json plugin: curl_easy_perform failed with "
894 "response code %ld (%s)", rc, url);
898 } /* }}} int cj_curl_perform */
900 static int cj_perform (cj_t *db) /* {{{ */
903 yajl_handle yprev = db->yajl;
905 db->yajl = yajl_alloc (&ycallbacks,
907 /* alloc funcs = */ NULL,
909 /* alloc funcs = */ NULL, NULL,
911 /* context = */ (void *)db);
912 if (db->yajl == NULL)
914 ERROR ("curl_json plugin: yajl_alloc failed.");
920 status = cj_curl_perform (db);
922 status = cj_sock_perform (db);
925 yajl_free (db->yajl);
931 status = yajl_complete_parse(db->yajl);
933 status = yajl_parse_complete(db->yajl);
935 if (status != yajl_status_ok)
937 unsigned char *errmsg;
939 errmsg = yajl_get_error (db->yajl, /* verbose = */ 0,
940 /* jsonText = */ NULL, /* jsonTextLen = */ 0);
941 ERROR ("curl_json plugin: yajl_parse_complete failed: %s",
943 yajl_free_error (db->yajl, errmsg);
944 yajl_free (db->yajl);
949 yajl_free (db->yajl);
952 } /* }}} int cj_perform */
954 static int cj_read (user_data_t *ud) /* {{{ */
958 if ((ud == NULL) || (ud->data == NULL))
960 ERROR ("curl_json plugin: cj_read: Invalid user data.");
964 db = (cj_t *) ud->data;
967 memset (&db->state, 0, sizeof(db->state));
968 db->state[db->depth].tree = db->tree;
971 return cj_perform (db);
972 } /* }}} int cj_read */
974 void module_register (void)
976 plugin_register_complex_config ("curl_json", cj_config);
977 } /* void module_register */
979 /* vim: set sw=2 sts=2 et fdm=marker : */