Add request specific statistics to all CURL-based plugins.
[collectd.git] / src / curl_json.c
1 /**
2  * collectd - src/curl_json.c
3  * Copyright (C) 2009       Doug MacEachern
4  * Copyright (C) 2006-2013  Florian octo Forster
5  *
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.
9  *
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.
14  *
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
18  *
19  * Authors:
20  *   Doug MacEachern <dougm at hyperic.com>
21  *   Florian octo Forster <octo at collectd.org>
22  **/
23
24 #include "collectd.h"
25 #include "common.h"
26 #include "plugin.h"
27 #include "configfile.h"
28 #include "utils_avltree.h"
29 #include "utils_complain.h"
30 #include "utils_curl_stats.h"
31
32 #include <sys/types.h>
33 #include <sys/un.h>
34
35 #include <curl/curl.h>
36
37 #include <yajl/yajl_parse.h>
38 #if HAVE_YAJL_YAJL_VERSION_H
39 # include <yajl/yajl_version.h>
40 #endif
41
42 #if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
43 # define HAVE_YAJL_V2 1
44 #endif
45
46 #define CJ_DEFAULT_HOST "localhost"
47 #define CJ_KEY_MAGIC 0x43484b59UL /* CHKY */
48 #define CJ_IS_KEY(key) ((key)->magic == CJ_KEY_MAGIC)
49 #define CJ_ANY "*"
50 #define COUCH_MIN(x,y) ((x) < (y) ? (x) : (y))
51
52 struct cj_key_s;
53 typedef struct cj_key_s cj_key_t;
54 struct cj_key_s /* {{{ */
55 {
56   unsigned long magic;
57   char *path;
58   char *type;
59   char *instance;
60 };
61 /* }}} */
62
63 struct cj_s /* {{{ */
64 {
65   char *instance;
66   char *host;
67
68   char *sock;
69
70   char *url;
71   char *user;
72   char *pass;
73   char *credentials;
74   _Bool digest;
75   _Bool verify_peer;
76   _Bool verify_host;
77   char *cacert;
78   struct curl_slist *headers;
79   char *post_body;
80   cdtime_t interval;
81   int timeout;
82   curl_stats_t *stats;
83
84   CURL *curl;
85   char curl_errbuf[CURL_ERROR_SIZE];
86
87   yajl_handle yajl;
88   c_avl_tree_t *tree;
89   cj_key_t *key;
90   int depth;
91   struct {
92     union {
93       c_avl_tree_t *tree;
94       cj_key_t *key;
95     };
96     _Bool in_array;
97     int index;
98     char name[DATA_MAX_NAME_LEN];
99   } state[YAJL_MAX_DEPTH];
100 };
101 typedef struct cj_s cj_t; /* }}} */
102
103 #if HAVE_YAJL_V2
104 typedef size_t yajl_len_t;
105 #else
106 typedef unsigned int yajl_len_t;
107 #endif
108
109 static int cj_read (user_data_t *ud);
110 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value);
111
112 static size_t cj_curl_callback (void *buf, /* {{{ */
113     size_t size, size_t nmemb, void *user_data)
114 {
115   cj_t *db;
116   size_t len;
117   yajl_status status;
118
119   len = size * nmemb;
120
121   if (len == 0)
122     return (len);
123
124   db = user_data;
125   if (db == NULL)
126     return (0);
127
128   status = yajl_parse(db->yajl, (unsigned char *)buf, len);
129   if (status == yajl_status_ok)
130     return (len);
131 #if !HAVE_YAJL_V2
132   else if (status == yajl_status_insufficient_data)
133     return (len);
134 #endif
135
136   unsigned char *msg = yajl_get_error(db->yajl, /* verbose = */ 1,
137         /* jsonText = */ (unsigned char *) buf, (unsigned int) len);
138   ERROR ("curl_json plugin: yajl_parse failed: %s", msg);
139   yajl_free_error(db->yajl, msg);
140   return (0); /* abort write callback */
141 } /* }}} size_t cj_curl_callback */
142
143 static int cj_get_type (cj_key_t *key)
144 {
145   const data_set_t *ds;
146
147   ds = plugin_get_ds (key->type);
148   if (ds == NULL)
149   {
150     static char type[DATA_MAX_NAME_LEN] = "!!!invalid!!!";
151
152     assert (key->type != NULL);
153     if (strcmp (type, key->type) != 0)
154     {
155       ERROR ("curl_json plugin: Unable to look up DS type \"%s\".",
156           key->type);
157       sstrncpy (type, key->type, sizeof (type));
158     }
159
160     return -1;
161   }
162   else if (ds->ds_num > 1)
163   {
164     static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
165
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.",
170         key->type);
171   }
172
173   return ds->ds[0].type;
174 }
175
176 static int cj_cb_map_key (void *ctx, const unsigned char *val,
177     yajl_len_t len);
178
179 static void cj_cb_inc_array_index (void *ctx, _Bool update_key)
180 {
181   cj_t *db = (cj_t *)ctx;
182
183   if (!db->state[db->depth].in_array)
184     return;
185
186   db->state[db->depth].index++;
187
188   if (update_key)
189   {
190     char name[DATA_MAX_NAME_LEN];
191
192     ssnprintf (name, sizeof (name), "%d", db->state[db->depth].index - 1);
193
194     cj_cb_map_key (ctx, (unsigned char *)name, (yajl_len_t) strlen (name));
195   }
196 }
197
198 /* yajl callbacks */
199 #define CJ_CB_ABORT    0
200 #define CJ_CB_CONTINUE 1
201
202 static int cj_cb_boolean (void * ctx, int boolVal)
203 {
204   cj_cb_inc_array_index (ctx, /* update_key = */ 0);
205   return (CJ_CB_CONTINUE);
206 }
207
208 static int cj_cb_null (void * ctx)
209 {
210   cj_cb_inc_array_index (ctx, /* update_key = */ 0);
211   return (CJ_CB_CONTINUE);
212 }
213
214 static int cj_cb_number (void *ctx,
215     const char *number, yajl_len_t number_len)
216 {
217   char buffer[number_len + 1];
218
219   cj_t *db = (cj_t *)ctx;
220   cj_key_t *key = db->state[db->depth].key;
221   value_t vt;
222   int type;
223   int status;
224
225   /* Create a null-terminated version of the string. */
226   memcpy (buffer, number, number_len);
227   buffer[sizeof (buffer) - 1] = 0;
228
229   if ((key == NULL) || !CJ_IS_KEY (key)) {
230     if (key != NULL && !db->state[db->depth].in_array/*can be inhomogeneous*/)
231       NOTICE ("curl_json plugin: Found \"%s\", but the configuration expects"
232               " a map.", buffer);
233     cj_cb_inc_array_index (ctx, /* update_key = */ 1);
234     key = db->state[db->depth].key;
235     if (key == NULL) {
236       return (CJ_CB_CONTINUE);
237     }
238   }
239   else
240   {
241     cj_cb_inc_array_index (ctx, /* update_key = */ 1);
242   }
243
244   type = cj_get_type (key);
245   status = parse_value (buffer, &vt, type);
246   if (status != 0)
247   {
248     NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
249     return (CJ_CB_CONTINUE);
250   }
251
252   cj_submit (db, key, &vt);
253   return (CJ_CB_CONTINUE);
254 } /* int cj_cb_number */
255
256 /* Queries the key-tree of the parent context for "in_name" and, if found,
257  * updates the "key" field of the current context. Otherwise, "key" is set to
258  * NULL. */
259 static int cj_cb_map_key (void *ctx,
260     unsigned char const *in_name, yajl_len_t in_name_len)
261 {
262   cj_t *db = (cj_t *)ctx;
263   c_avl_tree_t *tree;
264
265   tree = db->state[db->depth-1].tree;
266
267   if (tree != NULL)
268   {
269     cj_key_t *value = NULL;
270     char *name;
271     size_t name_len;
272
273     /* Create a null-terminated version of the name. */
274     name = db->state[db->depth].name;
275     name_len = COUCH_MIN ((size_t) in_name_len,
276         sizeof (db->state[db->depth].name) - 1);
277     memcpy (name, in_name, name_len);
278     name[name_len] = 0;
279
280     if (c_avl_get (tree, name, (void *) &value) == 0) {
281       if (CJ_IS_KEY((cj_key_t*)value)) {
282         db->state[db->depth].key = value;
283       }
284       else {
285         db->state[db->depth].tree = (c_avl_tree_t*) value;
286       }
287     }
288     else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
289       if (CJ_IS_KEY((cj_key_t*)value)) {
290         db->state[db->depth].key = value;
291       }
292       else {
293         db->state[db->depth].tree = (c_avl_tree_t*) value;
294       }
295     else
296       db->state[db->depth].key = NULL;
297   }
298
299   return (CJ_CB_CONTINUE);
300 }
301
302 static int cj_cb_string (void *ctx, const unsigned char *val,
303     yajl_len_t len)
304 {
305   /* Handle the string as if it was a number. */
306   return (cj_cb_number (ctx, (const char *) val, len));
307 } /* int cj_cb_string */
308
309 static int cj_cb_start (void *ctx)
310 {
311   cj_t *db = (cj_t *)ctx;
312   if (++db->depth >= YAJL_MAX_DEPTH)
313   {
314     ERROR ("curl_json plugin: %s depth exceeds max, aborting.",
315            db->url ? db->url : db->sock);
316     return (CJ_CB_ABORT);
317   }
318   return (CJ_CB_CONTINUE);
319 }
320
321 static int cj_cb_end (void *ctx)
322 {
323   cj_t *db = (cj_t *)ctx;
324   db->state[db->depth].tree = NULL;
325   --db->depth;
326   return (CJ_CB_CONTINUE);
327 }
328
329 static int cj_cb_start_map (void *ctx)
330 {
331   cj_cb_inc_array_index (ctx, /* update_key = */ 1);
332   return cj_cb_start (ctx);
333 }
334
335 static int cj_cb_end_map (void *ctx)
336 {
337   return cj_cb_end (ctx);
338 }
339
340 static int cj_cb_start_array (void * ctx)
341 {
342   cj_t *db = (cj_t *)ctx;
343   cj_cb_inc_array_index (ctx, /* update_key = */ 1);
344   if (db->depth+1 < YAJL_MAX_DEPTH) {
345     db->state[db->depth+1].in_array = 1;
346     db->state[db->depth+1].index = 0;
347   }
348   return cj_cb_start (ctx);
349 }
350
351 static int cj_cb_end_array (void * ctx)
352 {
353   cj_t *db = (cj_t *)ctx;
354   db->state[db->depth].in_array = 0;
355   return cj_cb_end (ctx);
356 }
357
358 static yajl_callbacks ycallbacks = {
359   cj_cb_null, /* null */
360   cj_cb_boolean, /* boolean */
361   NULL, /* integer */
362   NULL, /* double */
363   cj_cb_number,
364   cj_cb_string,
365   cj_cb_start_map,
366   cj_cb_map_key,
367   cj_cb_end_map,
368   cj_cb_start_array,
369   cj_cb_end_array
370 };
371
372 /* end yajl callbacks */
373
374 static void cj_key_free (cj_key_t *key) /* {{{ */
375 {
376   if (key == NULL)
377     return;
378
379   sfree (key->path);
380   sfree (key->type);
381   sfree (key->instance);
382
383   sfree (key);
384 } /* }}} void cj_key_free */
385
386 static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
387 {
388   char *name;
389   void *value;
390
391   while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
392   {
393     cj_key_t *key = (cj_key_t *)value;
394
395     if (CJ_IS_KEY(key))
396       cj_key_free (key);
397     else
398       cj_tree_free ((c_avl_tree_t *)value);
399
400     sfree (name);
401   }
402
403   c_avl_destroy (tree);
404 } /* }}} void cj_tree_free */
405
406 static void cj_free (void *arg) /* {{{ */
407 {
408   cj_t *db;
409
410   DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
411
412   db = (cj_t *) arg;
413
414   if (db == NULL)
415     return;
416
417   if (db->curl != NULL)
418     curl_easy_cleanup (db->curl);
419   db->curl = NULL;
420
421   if (db->tree != NULL)
422     cj_tree_free (db->tree);
423   db->tree = NULL;
424
425   sfree (db->instance);
426   sfree (db->host);
427
428   sfree (db->sock);
429
430   sfree (db->url);
431   sfree (db->user);
432   sfree (db->pass);
433   sfree (db->credentials);
434   sfree (db->cacert);
435   sfree (db->post_body);
436   curl_slist_free_all (db->headers);
437   curl_stats_destroy (db->stats);
438
439   sfree (db);
440 } /* }}} void cj_free */
441
442 /* Configuration handling functions {{{ */
443
444 static c_avl_tree_t *cj_avl_create(void)
445 {
446   return c_avl_create ((int (*) (const void *, const void *)) strcmp);
447 }
448
449 static int cj_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
450     oconfig_item_t *ci)
451 {
452   struct curl_slist *temp = NULL;
453   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
454   {
455     WARNING ("curl_json plugin: `%s' needs exactly one string argument.", name);
456     return (-1);
457   }
458
459   temp = curl_slist_append(*dest, ci->values[0].value.string);
460   if (temp == NULL)
461     return (-1);
462
463   *dest = temp;
464
465   return (0);
466 } /* }}} int cj_config_append_string */
467
468 static int cj_config_add_key (cj_t *db, /* {{{ */
469                                    oconfig_item_t *ci)
470 {
471   cj_key_t *key;
472   int status;
473   int i;
474
475   if ((ci->values_num != 1)
476       || (ci->values[0].type != OCONFIG_TYPE_STRING))
477   {
478     WARNING ("curl_json plugin: The `Key' block "
479              "needs exactly one string argument.");
480     return (-1);
481   }
482
483   key = calloc (1, sizeof (*key));
484   if (key == NULL)
485   {
486     ERROR ("curl_json plugin: calloc failed.");
487     return (-1);
488   }
489   key->magic = CJ_KEY_MAGIC;
490
491   if (strcasecmp ("Key", ci->key) == 0)
492   {
493     status = cf_util_get_string (ci, &key->path);
494     if (status != 0)
495     {
496       sfree (key);
497       return (status);
498     }
499   }
500   else
501   {
502     ERROR ("curl_json plugin: cj_config: "
503            "Invalid key: %s", ci->key);
504     cj_key_free (key);
505     return (-1);
506   }
507
508   status = 0;
509   for (i = 0; i < ci->children_num; i++)
510   {
511     oconfig_item_t *child = ci->children + i;
512
513     if (strcasecmp ("Type", child->key) == 0)
514       status = cf_util_get_string (child, &key->type);
515     else if (strcasecmp ("Instance", child->key) == 0)
516       status = cf_util_get_string (child, &key->instance);
517     else
518     {
519       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
520       status = -1;
521     }
522
523     if (status != 0)
524       break;
525   } /* for (i = 0; i < ci->children_num; i++) */
526
527   if (status != 0)
528   {
529     cj_key_free (key);
530     return (-1);
531   }
532
533   if (key->type == NULL)
534   {
535     WARNING ("curl_json plugin: `Type' missing in `Key' block.");
536     cj_key_free (key);
537     return (-1);
538   }
539
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 } } }
544    */
545   char *ptr;
546   char *name;
547   c_avl_tree_t *tree;
548
549   if (db->tree == NULL)
550     db->tree = cj_avl_create();
551
552   tree = db->tree;
553   ptr = key->path;
554   if (*ptr == '/')
555     ++ptr;
556
557   name = ptr;
558   while ((ptr = strchr (name, '/')) != NULL)
559   {
560     char ent[PATH_MAX];
561     c_avl_tree_t *value;
562     size_t len;
563
564     len = ptr - name;
565     if (len == 0)
566       break;
567
568     len = COUCH_MIN(len, sizeof (ent)-1);
569     sstrncpy (ent, name, len+1);
570
571     if (c_avl_get (tree, ent, (void *) &value) != 0)
572     {
573       value = cj_avl_create ();
574       c_avl_insert (tree, strdup (ent), value);
575     }
576
577     tree = value;
578     name = ptr + 1;
579   }
580
581   if (strlen (name) == 0)
582   {
583     ERROR ("curl_json plugin: invalid key: %s", key->path);
584     cj_key_free (key);
585     return (-1);
586   }
587
588   c_avl_insert (tree, strdup (name), key);
589   return (status);
590 } /* }}} int cj_config_add_key */
591
592 static int cj_init_curl (cj_t *db) /* {{{ */
593 {
594   db->curl = curl_easy_init ();
595   if (db->curl == NULL)
596   {
597     ERROR ("curl_json plugin: curl_easy_init failed.");
598     return (-1);
599   }
600
601   curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
602   curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
603   curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
604   curl_easy_setopt (db->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
605   curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
606   curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
607   curl_easy_setopt (db->curl, CURLOPT_FOLLOWLOCATION, 1L);
608   curl_easy_setopt (db->curl, CURLOPT_MAXREDIRS, 50L);
609
610   if (db->user != NULL)
611   {
612 #ifdef HAVE_CURLOPT_USERNAME
613     curl_easy_setopt (db->curl, CURLOPT_USERNAME, db->user);
614     curl_easy_setopt (db->curl, CURLOPT_PASSWORD,
615         (db->pass == NULL) ? "" : db->pass);
616 #else
617     size_t credentials_size;
618
619     credentials_size = strlen (db->user) + 2;
620     if (db->pass != NULL)
621       credentials_size += strlen (db->pass);
622
623     db->credentials = malloc (credentials_size);
624     if (db->credentials == NULL)
625     {
626       ERROR ("curl_json plugin: malloc failed.");
627       return (-1);
628     }
629
630     ssnprintf (db->credentials, credentials_size, "%s:%s",
631                db->user, (db->pass == NULL) ? "" : db->pass);
632     curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
633 #endif
634
635     if (db->digest)
636       curl_easy_setopt (db->curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
637   }
638
639   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (long) db->verify_peer);
640   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
641                     db->verify_host ? 2L : 0L);
642   if (db->cacert != NULL)
643     curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
644   if (db->headers != NULL)
645     curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
646   if (db->post_body != NULL)
647     curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
648
649 #ifdef HAVE_CURLOPT_TIMEOUT_MS
650   if (db->timeout >= 0)
651     curl_easy_setopt (db->curl, CURLOPT_TIMEOUT_MS, (long) db->timeout);
652   else if (db->interval > 0)
653     curl_easy_setopt (db->curl, CURLOPT_TIMEOUT_MS, (long) CDTIME_T_TO_MS(db->timeout));
654   else
655     curl_easy_setopt (db->curl, CURLOPT_TIMEOUT_MS, (long) CDTIME_T_TO_MS(plugin_get_interval()));
656 #endif
657
658   return (0);
659 } /* }}} int cj_init_curl */
660
661 static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
662 {
663   cj_t *db;
664   int status = 0;
665   int i;
666
667   if ((ci->values_num != 1)
668       || (ci->values[0].type != OCONFIG_TYPE_STRING))
669   {
670     WARNING ("curl_json plugin: The `URL' block "
671              "needs exactly one string argument.");
672     return (-1);
673   }
674
675   db = calloc (1, sizeof (*db));
676   if (db == NULL)
677   {
678     ERROR ("curl_json plugin: calloc failed.");
679     return (-1);
680   }
681
682   db->timeout = -1;
683
684   if (strcasecmp ("URL", ci->key) == 0)
685     status = cf_util_get_string (ci, &db->url);
686   else if (strcasecmp ("Sock", ci->key) == 0)
687     status = cf_util_get_string (ci, &db->sock);
688   else
689   {
690     ERROR ("curl_json plugin: cj_config: "
691            "Invalid key: %s", ci->key);
692     cj_free (db);
693     return (-1);
694   }
695   if (status != 0)
696   {
697     sfree (db);
698     return (status);
699   }
700
701   /* Fill the `cj_t' structure.. */
702   for (i = 0; i < ci->children_num; i++)
703   {
704     oconfig_item_t *child = ci->children + i;
705
706     if (strcasecmp ("Instance", child->key) == 0)
707       status = cf_util_get_string (child, &db->instance);
708     else if (strcasecmp ("Host", child->key) == 0)
709       status = cf_util_get_string (child, &db->host);
710     else if (db->url && strcasecmp ("User", child->key) == 0)
711       status = cf_util_get_string (child, &db->user);
712     else if (db->url && strcasecmp ("Password", child->key) == 0)
713       status = cf_util_get_string (child, &db->pass);
714     else if (strcasecmp ("Digest", child->key) == 0)
715       status = cf_util_get_boolean (child, &db->digest);
716     else if (db->url && strcasecmp ("VerifyPeer", child->key) == 0)
717       status = cf_util_get_boolean (child, &db->verify_peer);
718     else if (db->url && strcasecmp ("VerifyHost", child->key) == 0)
719       status = cf_util_get_boolean (child, &db->verify_host);
720     else if (db->url && strcasecmp ("CACert", child->key) == 0)
721       status = cf_util_get_string (child, &db->cacert);
722     else if (db->url && strcasecmp ("Header", child->key) == 0)
723       status = cj_config_append_string ("Header", &db->headers, child);
724     else if (db->url && strcasecmp ("Post", child->key) == 0)
725       status = cf_util_get_string (child, &db->post_body);
726     else if (strcasecmp ("Key", child->key) == 0)
727       status = cj_config_add_key (db, child);
728     else if (strcasecmp ("Interval", child->key) == 0)
729       status = cf_util_get_cdtime(child, &db->interval);
730     else if (strcasecmp ("Timeout", child->key) == 0)
731       status = cf_util_get_int (child, &db->timeout);
732     else if (strcasecmp ("Statistics", child->key) == 0)
733     {
734       db->stats = curl_stats_from_config (child);
735       if (db->stats == NULL)
736         status = -1;
737     }
738     else
739     {
740       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
741       status = -1;
742     }
743
744     if (status != 0)
745       break;
746   }
747
748   if (status == 0)
749   {
750     if (db->tree == NULL)
751     {
752       WARNING ("curl_json plugin: No (valid) `Key' block within `%s' \"`%s'\".",
753                db->url ? "URL" : "Sock", db->url ? db->url : db->sock);
754       status = -1;
755     }
756     if (status == 0 && db->url)
757       status = cj_init_curl (db);
758   }
759
760   /* If all went well, register this database for reading */
761   if (status == 0)
762   {
763     user_data_t ud;
764     char *cb_name;
765
766     if (db->instance == NULL)
767       db->instance = strdup("default");
768
769     DEBUG ("curl_json plugin: Registering new read callback: %s",
770            db->instance);
771
772     memset (&ud, 0, sizeof (ud));
773     ud.data = (void *) db;
774     ud.free_func = cj_free;
775
776     cb_name = ssnprintf_alloc ("curl_json-%s-%s",
777                db->instance, db->url ? db->url : db->sock);
778
779     plugin_register_complex_read (/* group = */ NULL, cb_name, cj_read,
780                                   /* interval = */ db->interval,
781                                   &ud);
782     sfree (cb_name);
783   }
784   else
785   {
786     cj_free (db);
787     return (-1);
788   }
789
790   return (0);
791 }
792  /* }}} int cj_config_add_database */
793
794 static int cj_config (oconfig_item_t *ci) /* {{{ */
795 {
796   int success;
797   int errors;
798   int status;
799   int i;
800
801   success = 0;
802   errors = 0;
803
804   for (i = 0; i < ci->children_num; i++)
805   {
806     oconfig_item_t *child = ci->children + i;
807
808     if (strcasecmp ("Sock", child->key) == 0
809         || strcasecmp ("URL", child->key) == 0)
810     {
811       status = cj_config_add_url (child);
812       if (status == 0)
813         success++;
814       else
815         errors++;
816     }
817     else
818     {
819       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
820       errors++;
821     }
822   }
823
824   if ((success == 0) && (errors > 0))
825   {
826     ERROR ("curl_json plugin: All statements failed.");
827     return (-1);
828   }
829
830   return (0);
831 } /* }}} int cj_config */
832
833 /* }}} End of configuration handling functions */
834
835 static const char *cj_host (cj_t *db) /* {{{ */
836 {
837   if ((db->host == NULL)
838       || (strcmp ("", db->host) == 0)
839       || (strcmp (CJ_DEFAULT_HOST, db->host) == 0))
840     return hostname_g;
841   return db->host;
842 } /* }}} cj_host */
843
844 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
845 {
846   value_list_t vl = VALUE_LIST_INIT;
847
848   vl.values     = value;
849   vl.values_len = 1;
850
851   if (key->instance == NULL)
852   {
853     int i, len = 0;
854     for (i = 0; i < db->depth; i++)
855       len += ssnprintf(vl.type_instance+len, sizeof(vl.type_instance)-len,
856                        i ? "-%s" : "%s", db->state[i+1].name);
857   }
858   else
859     sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
860
861   sstrncpy (vl.host, cj_host (db), sizeof (vl.host));
862   sstrncpy (vl.plugin, "curl_json", sizeof (vl.plugin));
863   sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
864   sstrncpy (vl.type, key->type, sizeof (vl.type));
865
866   if (db->interval > 0)
867     vl.interval = db->interval;
868
869   plugin_dispatch_values (&vl);
870 } /* }}} int cj_submit */
871
872 static int cj_sock_perform (cj_t *db) /* {{{ */
873 {
874   char errbuf[1024];
875   struct sockaddr_un sa_unix = { 0 };
876   sa_unix.sun_family = AF_UNIX;
877   sstrncpy (sa_unix.sun_path, db->sock, sizeof (sa_unix.sun_path));
878
879   int fd = socket (AF_UNIX, SOCK_STREAM, 0);
880   if (fd < 0)
881     return (-1);
882   if (connect (fd, (struct sockaddr *)&sa_unix, sizeof(sa_unix)) < 0)
883   {
884     ERROR ("curl_json plugin: connect(%s) failed: %s",
885            (db->sock != NULL) ? db->sock : "<null>",
886            sstrerror(errno, errbuf, sizeof (errbuf)));
887     close (fd);
888     return (-1);
889   }
890
891   ssize_t red;
892   do {
893     unsigned char buffer[4096];
894     red = read (fd, buffer, sizeof(buffer));
895     if (red < 0) {
896         ERROR ("curl_json plugin: read(%s) failed: %s",
897                (db->sock != NULL) ? db->sock : "<null>",
898                sstrerror(errno, errbuf, sizeof (errbuf)));
899         close (fd);
900         return (-1);
901     }
902     if (!cj_curl_callback (buffer, red, 1, db))
903         break;
904   } while (red > 0);
905   close (fd);
906   return (0);
907 } /* }}} int cj_sock_perform */
908
909
910 static int cj_curl_perform(cj_t *db) /* {{{ */
911 {
912   int status;
913   long rc;
914   char *url;
915   url = db->url;
916
917   status = curl_easy_perform (db->curl);
918   if (status != CURLE_OK)
919   {
920     ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
921            status, db->curl_errbuf, url);
922     return (-1);
923   }
924   if (db->stats != NULL)
925     curl_stats_dispatch (db->stats, db->curl, cj_host (db), "curl_json", db->instance, NULL);
926
927   curl_easy_getinfo(db->curl, CURLINFO_EFFECTIVE_URL, &url);
928   curl_easy_getinfo(db->curl, CURLINFO_RESPONSE_CODE, &rc);
929
930   /* The response code is zero if a non-HTTP transport was used. */
931   if ((rc != 0) && (rc != 200))
932   {
933     ERROR ("curl_json plugin: curl_easy_perform failed with "
934         "response code %ld (%s)", rc, url);
935     return (-1);
936   }
937   return (0);
938 } /* }}} int cj_curl_perform */
939
940 static int cj_perform (cj_t *db) /* {{{ */
941 {
942   int status;
943   yajl_handle yprev = db->yajl;
944
945   db->yajl = yajl_alloc (&ycallbacks,
946 #if HAVE_YAJL_V2
947       /* alloc funcs = */ NULL,
948 #else
949       /* alloc funcs = */ NULL, NULL,
950 #endif
951       /* context = */ (void *)db);
952   if (db->yajl == NULL)
953   {
954     ERROR ("curl_json plugin: yajl_alloc failed.");
955     db->yajl = yprev;
956     return (-1);
957   }
958
959   if (db->url)
960     status = cj_curl_perform (db);
961   else
962     status = cj_sock_perform (db);
963   if (status < 0)
964   {
965     yajl_free (db->yajl);
966     db->yajl = yprev;
967     return (-1);
968   }
969
970 #if HAVE_YAJL_V2
971     status = yajl_complete_parse(db->yajl);
972 #else
973     status = yajl_parse_complete(db->yajl);
974 #endif
975   if (status != yajl_status_ok)
976   {
977     unsigned char *errmsg;
978
979     errmsg = yajl_get_error (db->yajl, /* verbose = */ 0,
980         /* jsonText = */ NULL, /* jsonTextLen = */ 0);
981     ERROR ("curl_json plugin: yajl_parse_complete failed: %s",
982         (char *) errmsg);
983     yajl_free_error (db->yajl, errmsg);
984     yajl_free (db->yajl);
985     db->yajl = yprev;
986     return (-1);
987   }
988
989   yajl_free (db->yajl);
990   db->yajl = yprev;
991   return (0);
992 } /* }}} int cj_perform */
993
994 static int cj_read (user_data_t *ud) /* {{{ */
995 {
996   cj_t *db;
997
998   if ((ud == NULL) || (ud->data == NULL))
999   {
1000     ERROR ("curl_json plugin: cj_read: Invalid user data.");
1001     return (-1);
1002   }
1003
1004   db = (cj_t *) ud->data;
1005
1006   db->depth = 0;
1007   memset (&db->state, 0, sizeof(db->state));
1008   db->state[db->depth].tree = db->tree;
1009   db->key = NULL;
1010
1011   return cj_perform (db);
1012 } /* }}} int cj_read */
1013
1014 static int cj_init (void) /* {{{ */
1015 {
1016   /* Call this while collectd is still single-threaded to avoid
1017    * initialization issues in libgcrypt. */
1018   curl_global_init (CURL_GLOBAL_SSL);
1019   return (0);
1020 } /* }}} int cj_init */
1021
1022 void module_register (void)
1023 {
1024   plugin_register_complex_config ("curl_json", cj_config);
1025   plugin_register_init ("curl_json", cj_init);
1026 } /* void module_register */
1027
1028 /* vim: set sw=2 sts=2 et fdm=marker : */