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