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