2 * collectd - src/curl_json.c
3 * Copyright (C) 2009 Doug MacEachern
4 * Copyright (C) 2006-2011 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];
92 char name[DATA_MAX_NAME_LEN];
93 } state[YAJL_MAX_DEPTH];
95 typedef struct cj_s cj_t; /* }}} */
98 typedef size_t yajl_len_t;
100 typedef unsigned int yajl_len_t;
103 static int cj_read (user_data_t *ud);
104 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value);
106 static size_t cj_curl_callback (void *buf, /* {{{ */
107 size_t size, size_t nmemb, void *user_data)
122 status = yajl_parse(db->yajl, (unsigned char *)buf, len);
123 if (status == yajl_status_ok)
126 else if (status == yajl_status_insufficient_data)
130 if (status != yajl_status_ok)
133 yajl_get_error(db->yajl, /* verbose = */ 1,
134 /* jsonText = */ (unsigned char *) buf, (unsigned int) len);
135 ERROR ("curl_json plugin: yajl_parse failed: %s", msg);
136 yajl_free_error(db->yajl, msg);
137 return (0); /* abort write callback */
141 } /* }}} size_t cj_curl_callback */
143 static int cj_get_type (cj_key_t *key)
145 const data_set_t *ds;
147 ds = plugin_get_ds (key->type);
150 static char type[DATA_MAX_NAME_LEN] = "!!!invalid!!!";
152 assert (key->type != NULL);
153 if (strcmp (type, key->type) != 0)
155 ERROR ("curl_json plugin: Unable to look up DS type \"%s\".",
157 sstrncpy (type, key->type, sizeof (type));
162 else if (ds->ds_num > 1)
164 static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
166 c_complain_once (LOG_WARNING, &complaint,
167 "curl_json plugin: The type \"%s\" has more than one data source. "
168 "This is currently not supported. I will return the type of the "
169 "first data source, but this will likely lead to problems later on.",
173 return ds->ds[0].type;
177 #define CJ_CB_ABORT 0
178 #define CJ_CB_CONTINUE 1
180 /* "number" may not be null terminated, so copy it into a buffer before
182 static int cj_cb_number (void *ctx,
183 const char *number, yajl_len_t number_len)
185 char buffer[number_len + 1];
187 cj_t *db = (cj_t *)ctx;
188 cj_key_t *key = db->state[db->depth].key;
193 if ((key == NULL) || !CJ_IS_KEY (key))
194 return (CJ_CB_CONTINUE);
196 memcpy (buffer, number, number_len);
197 buffer[sizeof (buffer) - 1] = 0;
199 type = cj_get_type (key);
200 status = parse_value (buffer, &vt, type);
203 NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
204 return (CJ_CB_CONTINUE);
207 cj_submit (db, key, &vt);
208 return (CJ_CB_CONTINUE);
209 } /* int cj_cb_number */
211 static int cj_cb_map_key (void *ctx, const unsigned char *val,
214 cj_t *db = (cj_t *)ctx;
217 tree = db->state[db->depth-1].tree;
224 name = db->state[db->depth].name;
225 len = COUCH_MIN(len, sizeof (db->state[db->depth].name)-1);
226 sstrncpy (name, (char *)val, len+1);
228 if (c_avl_get (tree, name, (void *) &value) == 0)
229 db->state[db->depth].key = value;
230 else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
231 db->state[db->depth].key = value;
233 db->state[db->depth].key = NULL;
236 return (CJ_CB_CONTINUE);
239 static int cj_cb_string (void *ctx, const unsigned char *val,
242 cj_t *db = (cj_t *)ctx;
245 /* Create a null-terminated version of the string. */
246 memcpy (str, val, len);
249 /* No configuration for this string -> simply return. */
250 if (db->state[db->depth].key == NULL)
251 return (CJ_CB_CONTINUE);
253 if (!CJ_IS_KEY (db->state[db->depth].key))
255 NOTICE ("curl_json plugin: Found string \"%s\", but the configuration "
256 "expects a map here.", str);
257 return (CJ_CB_CONTINUE);
260 /* Handle the string as if it was a number. */
261 return (cj_cb_number (ctx, (const char *) val, len));
262 } /* int cj_cb_string */
264 static int cj_cb_start (void *ctx)
266 cj_t *db = (cj_t *)ctx;
267 if (++db->depth >= YAJL_MAX_DEPTH)
269 ERROR ("curl_json plugin: %s depth exceeds max, aborting.",
270 db->url ? db->url : db->sock);
271 return (CJ_CB_ABORT);
273 return (CJ_CB_CONTINUE);
276 static int cj_cb_end (void *ctx)
278 cj_t *db = (cj_t *)ctx;
279 db->state[db->depth].tree = NULL;
281 return (CJ_CB_CONTINUE);
284 static int cj_cb_start_map (void *ctx)
286 return cj_cb_start (ctx);
289 static int cj_cb_end_map (void *ctx)
291 return cj_cb_end (ctx);
294 static int cj_cb_start_array (void * ctx)
296 return cj_cb_start (ctx);
299 static int cj_cb_end_array (void * ctx)
301 return cj_cb_end (ctx);
304 static yajl_callbacks ycallbacks = {
318 /* end yajl callbacks */
320 static void cj_key_free (cj_key_t *key) /* {{{ */
327 sfree (key->instance);
330 } /* }}} void cj_key_free */
332 static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
337 while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
339 cj_key_t *key = (cj_key_t *)value;
344 cj_tree_free ((c_avl_tree_t *)value);
349 c_avl_destroy (tree);
350 } /* }}} void cj_tree_free */
352 static void cj_free (void *arg) /* {{{ */
356 DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
363 if (db->curl != NULL)
364 curl_easy_cleanup (db->curl);
367 if (db->tree != NULL)
368 cj_tree_free (db->tree);
371 sfree (db->instance);
377 sfree (db->credentials);
379 sfree (db->post_body);
380 curl_slist_free_all (db->headers);
383 } /* }}} void cj_free */
385 /* Configuration handling functions {{{ */
387 static c_avl_tree_t *cj_avl_create(void)
389 return c_avl_create ((int (*) (const void *, const void *)) strcmp);
392 static int cj_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
395 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
397 WARNING ("curl_json plugin: `%s' needs exactly one string argument.", name);
401 *dest = curl_slist_append(*dest, ci->values[0].value.string);
406 } /* }}} int cj_config_append_string */
408 static int cj_config_add_key (cj_t *db, /* {{{ */
415 if ((ci->values_num != 1)
416 || (ci->values[0].type != OCONFIG_TYPE_STRING))
418 WARNING ("curl_json plugin: The `Key' block "
419 "needs exactly one string argument.");
423 key = (cj_key_t *) malloc (sizeof (*key));
426 ERROR ("curl_json plugin: malloc failed.");
429 memset (key, 0, sizeof (*key));
430 key->magic = CJ_KEY_MAGIC;
432 if (strcasecmp ("Key", ci->key) == 0)
434 status = cf_util_get_string (ci, &key->path);
443 ERROR ("curl_json plugin: cj_config: "
444 "Invalid key: %s", ci->key);
449 for (i = 0; i < ci->children_num; i++)
451 oconfig_item_t *child = ci->children + i;
453 if (strcasecmp ("Type", child->key) == 0)
454 status = cf_util_get_string (child, &key->type);
455 else if (strcasecmp ("Instance", child->key) == 0)
456 status = cf_util_get_string (child, &key->instance);
459 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
465 } /* for (i = 0; i < ci->children_num; i++) */
469 if (key->type == NULL)
471 WARNING ("curl_json plugin: `Type' missing in `Key' block.");
476 } /* while (status == 0) */
478 /* store path in a tree that will match the json map structure, example:
479 * "httpd/requests/count",
480 * "httpd/requests/current" ->
481 * { "httpd": { "requests": { "count": $key, "current": $key } } }
490 if (db->tree == NULL)
491 db->tree = cj_avl_create();
510 sstrncpy (ent, name, len+1);
512 if (c_avl_get (tree, ent, (void *) &value) != 0)
514 value = cj_avl_create ();
515 c_avl_insert (tree, strdup (ent), value);
524 c_avl_insert (tree, strdup(name), key);
527 ERROR ("curl_json plugin: invalid key: %s", key->path);
533 } /* }}} int cj_config_add_key */
535 static int cj_init_curl (cj_t *db) /* {{{ */
537 db->curl = curl_easy_init ();
538 if (db->curl == NULL)
540 ERROR ("curl_json plugin: curl_easy_init failed.");
544 curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
545 curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
546 curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
547 curl_easy_setopt (db->curl, CURLOPT_USERAGENT,
548 PACKAGE_NAME"/"PACKAGE_VERSION);
549 curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
550 curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
552 if (db->user != NULL)
554 size_t credentials_size;
556 credentials_size = strlen (db->user) + 2;
557 if (db->pass != NULL)
558 credentials_size += strlen (db->pass);
560 db->credentials = (char *) malloc (credentials_size);
561 if (db->credentials == NULL)
563 ERROR ("curl_json plugin: malloc failed.");
567 ssnprintf (db->credentials, credentials_size, "%s:%s",
568 db->user, (db->pass == NULL) ? "" : db->pass);
569 curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
572 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (long) db->verify_peer);
573 curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
574 db->verify_host ? 2L : 0L);
575 if (db->cacert != NULL)
576 curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
577 if (db->headers != NULL)
578 curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
579 if (db->post_body != NULL)
580 curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
583 } /* }}} int cj_init_curl */
585 static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
591 if ((ci->values_num != 1)
592 || (ci->values[0].type != OCONFIG_TYPE_STRING))
594 WARNING ("curl_json plugin: The `URL' block "
595 "needs exactly one string argument.");
599 db = (cj_t *) malloc (sizeof (*db));
602 ERROR ("curl_json plugin: malloc failed.");
605 memset (db, 0, sizeof (*db));
607 if (strcasecmp ("URL", ci->key) == 0)
608 status = cf_util_get_string (ci, &db->url);
609 else if (strcasecmp ("Sock", ci->key) == 0)
610 status = cf_util_get_string (ci, &db->sock);
613 ERROR ("curl_json plugin: cj_config: "
614 "Invalid key: %s", ci->key);
623 /* Fill the `cj_t' structure.. */
624 for (i = 0; i < ci->children_num; i++)
626 oconfig_item_t *child = ci->children + i;
628 if (strcasecmp ("Instance", child->key) == 0)
629 status = cf_util_get_string (child, &db->instance);
630 else if (strcasecmp ("Host", child->key) == 0)
631 status = cf_util_get_string (child, &db->host);
632 else if (db->url && strcasecmp ("User", child->key) == 0)
633 status = cf_util_get_string (child, &db->user);
634 else if (db->url && strcasecmp ("Password", child->key) == 0)
635 status = cf_util_get_string (child, &db->pass);
636 else if (db->url && strcasecmp ("VerifyPeer", child->key) == 0)
637 status = cf_util_get_boolean (child, &db->verify_peer);
638 else if (db->url && strcasecmp ("VerifyHost", child->key) == 0)
639 status = cf_util_get_boolean (child, &db->verify_host);
640 else if (db->url && strcasecmp ("CACert", child->key) == 0)
641 status = cf_util_get_string (child, &db->cacert);
642 else if (db->url && strcasecmp ("Header", child->key) == 0)
643 status = cj_config_append_string ("Header", &db->headers, child);
644 else if (db->url && strcasecmp ("Post", child->key) == 0)
645 status = cf_util_get_string (child, &db->post_body);
646 else if (strcasecmp ("Key", child->key) == 0)
647 status = cj_config_add_key (db, child);
650 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
660 if (db->tree == NULL)
662 WARNING ("curl_json plugin: No (valid) `Key' block within `%s' \"`%s'\".",
663 db->url ? "URL" : "Sock", db->url ? db->url : db->sock);
666 if (status == 0 && db->url)
667 status = cj_init_curl (db);
670 /* If all went well, register this database for reading */
674 char cb_name[DATA_MAX_NAME_LEN];
676 if (db->instance == NULL)
677 db->instance = strdup("default");
679 DEBUG ("curl_json plugin: Registering new read callback: %s",
682 memset (&ud, 0, sizeof (ud));
683 ud.data = (void *) db;
684 ud.free_func = cj_free;
686 ssnprintf (cb_name, sizeof (cb_name), "curl_json-%s-%s",
687 db->instance, db->url ? db->url : db->sock);
689 plugin_register_complex_read (/* group = */ NULL, cb_name, cj_read,
690 /* interval = */ NULL, &ud);
700 /* }}} int cj_config_add_database */
702 static int cj_config (oconfig_item_t *ci) /* {{{ */
712 for (i = 0; i < ci->children_num; i++)
714 oconfig_item_t *child = ci->children + i;
716 if (strcasecmp ("Sock", child->key) == 0
717 || strcasecmp ("URL", child->key) == 0)
719 status = cj_config_add_url (child);
727 WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
732 if ((success == 0) && (errors > 0))
734 ERROR ("curl_json plugin: All statements failed.");
739 } /* }}} int cj_config */
741 /* }}} End of configuration handling functions */
743 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
745 value_list_t vl = VALUE_LIST_INIT;
751 if ((db->host == NULL)
752 || (strcmp ("", db->host) == 0)
753 || (strcmp (CJ_DEFAULT_HOST, db->host) == 0))
758 if (key->instance == NULL)
760 if ((db->depth == 0) || (strcmp ("", db->state[db->depth-1].name) == 0))
761 sstrncpy (vl.type_instance, db->state[db->depth].name, sizeof (vl.type_instance));
763 ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s",
764 db->state[db->depth-1].name, db->state[db->depth].name);
767 sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
769 sstrncpy (vl.host, host, sizeof (vl.host));
770 sstrncpy (vl.plugin, "curl_json", sizeof (vl.plugin));
771 sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
772 sstrncpy (vl.type, key->type, sizeof (vl.type));
774 plugin_dispatch_values (&vl);
775 } /* }}} int cj_submit */
777 static int cj_sock_perform (cj_t *db) /* {{{ */
780 struct sockaddr_un sa_unix = {};
781 sa_unix.sun_family = AF_UNIX;
782 sstrncpy (sa_unix.sun_path, db->sock, sizeof (sa_unix.sun_path));
784 int fd = socket (AF_UNIX, SOCK_STREAM, 0);
787 if (connect (fd, (struct sockaddr *)&sa_unix, sizeof(sa_unix)) < 0)
789 ERROR ("curl_json plugin: connect(%s) failed: %s",
790 (db->sock != NULL) ? db->sock : "<null>",
791 sstrerror(errno, errbuf, sizeof (errbuf)));
798 unsigned char buffer[4096];
799 red = read (fd, buffer, sizeof(buffer));
801 ERROR ("curl_json plugin: read(%s) failed: %s",
802 (db->sock != NULL) ? db->sock : "<null>",
803 sstrerror(errno, errbuf, sizeof (errbuf)));
807 if (!cj_curl_callback (buffer, red, 1, db))
812 } /* }}} int cj_sock_perform */
815 static int cj_curl_perform(cj_t *db) /* {{{ */
821 curl_easy_getinfo(db->curl, CURLINFO_EFFECTIVE_URL, &url);
823 status = curl_easy_perform (db->curl);
824 if (status != CURLE_OK)
826 ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
827 status, db->curl_errbuf, (url != NULL) ? url : "<null>");
831 curl_easy_getinfo(db->curl, CURLINFO_RESPONSE_CODE, &rc);
833 /* The response code is zero if a non-HTTP transport was used. */
834 if ((rc != 0) && (rc != 200))
836 ERROR ("curl_json plugin: curl_easy_perform failed with "
837 "response code %ld (%s)", rc, url);
841 } /* }}} int cj_curl_perform */
843 static int cj_perform (cj_t *db) /* {{{ */
846 yajl_handle yprev = db->yajl;
848 db->yajl = yajl_alloc (&ycallbacks,
850 /* alloc funcs = */ NULL,
852 /* alloc funcs = */ NULL, NULL,
854 /* context = */ (void *)db);
855 if (db->yajl == NULL)
857 ERROR ("curl_json plugin: yajl_alloc failed.");
863 status = cj_curl_perform (db);
865 status = cj_sock_perform (db);
868 yajl_free (db->yajl);
874 status = yajl_complete_parse(db->yajl);
876 status = yajl_parse_complete(db->yajl);
878 if (status != yajl_status_ok)
880 unsigned char *errmsg;
882 errmsg = yajl_get_error (db->yajl, /* verbose = */ 0,
883 /* jsonText = */ NULL, /* jsonTextLen = */ 0);
884 ERROR ("curl_json plugin: yajl_parse_complete failed: %s",
886 yajl_free_error (db->yajl, errmsg);
887 yajl_free (db->yajl);
892 yajl_free (db->yajl);
895 } /* }}} int cj_perform */
897 static int cj_read (user_data_t *ud) /* {{{ */
901 if ((ud == NULL) || (ud->data == NULL))
903 ERROR ("curl_json plugin: cj_read: Invalid user data.");
907 db = (cj_t *) ud->data;
910 memset (&db->state, 0, sizeof(db->state));
911 db->state[db->depth].tree = db->tree;
914 return cj_perform (db);
915 } /* }}} int cj_read */
917 void module_register (void)
919 plugin_register_complex_config ("curl_json", cj_config);
920 } /* void module_register */
922 /* vim: set sw=2 sts=2 et fdm=marker : */