curl_json plugin: Use "parse_value" to handle JSON numbers.
[collectd.git] / src / curl_json.c
1 /**
2  * collectd - src/curl_json.c
3  * Copyright (C) 2009       Doug MacEachern
4  * Copyright (C) 2006-2010  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 verplant.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
30 #include <curl/curl.h>
31 #include <yajl/yajl_parse.h>
32
33 #define CJ_DEFAULT_HOST "localhost"
34 #define CJ_KEY_MAGIC 0x43484b59UL /* CHKY */
35 #define CJ_IS_KEY(key) ((key)->magic == CJ_KEY_MAGIC)
36 #define CJ_ANY "*"
37 #define COUCH_MIN(x,y) ((x) < (y) ? (x) : (y))
38
39 struct cj_key_s;
40 typedef struct cj_key_s cj_key_t;
41 struct cj_key_s /* {{{ */
42 {
43   char *path;
44   char *type;
45   char *instance;
46   unsigned long magic;
47 };
48 /* }}} */
49
50 struct cj_s /* {{{ */
51 {
52   char *instance;
53   char *host;
54
55   char *url;
56   char *user;
57   char *pass;
58   char *credentials;
59   _Bool verify_peer;
60   _Bool verify_host;
61   char *cacert;
62
63   CURL *curl;
64   char curl_errbuf[CURL_ERROR_SIZE];
65
66   yajl_handle yajl;
67   c_avl_tree_t *tree;
68   cj_key_t *key;
69   int depth;
70   struct {
71     union {
72       c_avl_tree_t *tree;
73       cj_key_t *key;
74     };
75     char name[DATA_MAX_NAME_LEN];
76   } state[YAJL_MAX_DEPTH];
77 };
78 typedef struct cj_s cj_t; /* }}} */
79
80 static int cj_read (user_data_t *ud);
81 static int cj_curl_perform (cj_t *db, CURL *curl);
82 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value);
83
84 static size_t cj_curl_callback (void *buf, /* {{{ */
85     size_t size, size_t nmemb, void *user_data)
86 {
87   cj_t *db;
88   size_t len;
89   yajl_status status;
90
91   len = size * nmemb;
92
93   if (len <= 0)
94     return (len);
95
96   db = user_data;
97   if (db == NULL)
98     return (0);
99
100   status = yajl_parse(db->yajl, (unsigned char *)buf, len);
101   if ((status != yajl_status_ok)
102       && (status != yajl_status_insufficient_data))
103   {
104     unsigned char *msg =
105       yajl_get_error(db->yajl, /* verbose = */ 1,
106           /* jsonText = */ (unsigned char *) buf, (unsigned int) len);
107     ERROR ("curl_json plugin: yajl_parse failed: %s", msg);
108     yajl_free_error(db->yajl, msg);
109     return (0); /* abort write callback */
110   }
111
112   return (len);
113 } /* }}} size_t cj_curl_callback */
114
115 static int cj_get_type (cj_key_t *key)
116 {
117   const data_set_t *ds;
118
119   ds = plugin_get_ds (key->type);
120   if (ds == NULL)
121     return -1; /* let plugin_write do the complaining */
122   else
123     return ds->ds[0].type; /* XXX support ds->ds_len > 1 */
124 }
125
126 /* yajl callbacks */
127 #define CJ_CB_ABORT    0
128 #define CJ_CB_CONTINUE 1
129
130 /* "number" may not be null terminated, so copy it into a buffer before
131  * parsing. */
132 static int cj_cb_number (void *ctx,
133     const char *number, unsigned int number_len)
134 {
135   char buffer[number_len + 1];
136
137   cj_t *db = (cj_t *)ctx;
138   cj_key_t *key = db->state[db->depth].key;
139   value_t vt;
140   int type;
141   int status;
142
143   if ((key == NULL) || !CJ_IS_KEY (key))
144     return (CJ_CB_CONTINUE);
145
146   memcpy (buffer, number, number_len);
147   buffer[sizeof (buffer) - 1] = 0;
148
149   type = cj_get_type (key);
150   status = parse_value (buffer, &vt, type);
151   if (status != 0)
152   {
153     NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
154     return (CJ_CB_CONTINUE);
155   }
156
157   cj_submit (db, key, &vt);
158   return (CJ_CB_CONTINUE);
159 } /* int cj_cb_number */
160
161 static int cj_cb_map_key (void *ctx, const unsigned char *val,
162                             unsigned int len)
163 {
164   cj_t *db = (cj_t *)ctx;
165   c_avl_tree_t *tree;
166
167   tree = db->state[db->depth-1].tree;
168
169   if (tree != NULL)
170   {
171     cj_key_t *value;
172     char *name;
173
174     name = db->state[db->depth].name;
175     len = COUCH_MIN(len, sizeof (db->state[db->depth].name)-1);
176     sstrncpy (name, (char *)val, len+1);
177
178     if (c_avl_get (tree, name, (void *) &value) == 0)
179       db->state[db->depth].key = value;
180     else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
181       db->state[db->depth].key = value;
182     else
183       db->state[db->depth].key = NULL;
184   }
185
186   return (CJ_CB_CONTINUE);
187 }
188
189 static int cj_cb_string (void *ctx, const unsigned char *val,
190                            unsigned int len)
191 {
192   cj_t *db = (cj_t *)ctx;
193   c_avl_tree_t *tree;
194   char *ptr;
195
196   if (db->depth != 1) /* e.g. _all_dbs */
197     return (CJ_CB_CONTINUE);
198
199   cj_cb_map_key (ctx, val, len); /* same logic */
200
201   tree = db->state[db->depth].tree;
202
203   if ((tree != NULL) && (ptr = rindex (db->url, '/')))
204   {
205     char url[PATH_MAX];
206     CURL *curl;
207
208     /* url =~ s,[^/]+$,$name, */
209     len = (ptr - db->url) + 1;
210     ptr = url;
211     sstrncpy (ptr, db->url, sizeof (url));
212     sstrncpy (ptr + len, db->state[db->depth].name, sizeof (url) - len);
213
214     curl = curl_easy_duphandle (db->curl);
215     curl_easy_setopt (curl, CURLOPT_URL, url);
216     cj_curl_perform (db, curl);
217     curl_easy_cleanup (curl);
218   }
219   return (CJ_CB_CONTINUE);
220 }
221
222 static int cj_cb_start (void *ctx)
223 {
224   cj_t *db = (cj_t *)ctx;
225   if (++db->depth >= YAJL_MAX_DEPTH)
226   {
227     ERROR ("curl_json plugin: %s depth exceeds max, aborting.", db->url);
228     return (CJ_CB_ABORT);
229   }
230   return (CJ_CB_CONTINUE);
231 }
232
233 static int cj_cb_end (void *ctx)
234 {
235   cj_t *db = (cj_t *)ctx;
236   db->state[db->depth].tree = NULL;
237   --db->depth;
238   return (CJ_CB_CONTINUE);
239 }
240
241 static int cj_cb_start_map (void *ctx)
242 {
243   return cj_cb_start (ctx);
244 }
245
246 static int cj_cb_end_map (void *ctx)
247 {
248   return cj_cb_end (ctx);
249 }
250
251 static int cj_cb_start_array (void * ctx)
252 {
253   return cj_cb_start (ctx);
254 }
255
256 static int cj_cb_end_array (void * ctx)
257 {
258   return cj_cb_start (ctx);
259 }
260
261 static yajl_callbacks ycallbacks = {
262   NULL, /* null */
263   NULL, /* boolean */
264   NULL, /* integer */
265   NULL, /* double */
266   cj_cb_number,
267   cj_cb_string,
268   cj_cb_start_map,
269   cj_cb_map_key,
270   cj_cb_end_map,
271   cj_cb_start_array,
272   cj_cb_end_array
273 };
274
275 /* end yajl callbacks */
276
277 static void cj_key_free (cj_key_t *key) /* {{{ */
278 {
279   if (key == NULL)
280     return;
281
282   sfree (key->path);
283   sfree (key->type);
284   sfree (key->instance);
285
286   sfree (key);
287 } /* }}} void cj_key_free */
288
289 static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
290 {
291   char *name;
292   void *value;
293
294   while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
295   {
296     cj_key_t *key = (cj_key_t *)value;
297
298     if (CJ_IS_KEY(key))
299       cj_key_free (key);
300     else
301       cj_tree_free ((c_avl_tree_t *)value);
302
303     sfree (name);
304   }
305
306   c_avl_destroy (tree);
307 } /* }}} void cj_tree_free */
308
309 static void cj_free (void *arg) /* {{{ */
310 {
311   cj_t *db;
312
313   DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
314
315   db = (cj_t *) arg;
316
317   if (db == NULL)
318     return;
319
320   if (db->curl != NULL)
321     curl_easy_cleanup (db->curl);
322   db->curl = NULL;
323
324   if (db->tree != NULL)
325     cj_tree_free (db->tree);
326   db->tree = NULL;
327
328   sfree (db->instance);
329   sfree (db->host);
330
331   sfree (db->url);
332   sfree (db->user);
333   sfree (db->pass);
334   sfree (db->credentials);
335   sfree (db->cacert);
336
337   sfree (db);
338 } /* }}} void cj_free */
339
340 /* Configuration handling functions {{{ */
341
342 static c_avl_tree_t *cj_avl_create(void)
343 {
344   return c_avl_create ((int (*) (const void *, const void *)) strcmp);
345 }
346
347 static int cj_config_add_key (cj_t *db, /* {{{ */
348                                    oconfig_item_t *ci)
349 {
350   cj_key_t *key;
351   int status;
352   int i;
353
354   if ((ci->values_num != 1)
355       || (ci->values[0].type != OCONFIG_TYPE_STRING))
356   {
357     WARNING ("curl_json plugin: The `Key' block "
358              "needs exactly one string argument.");
359     return (-1);
360   }
361
362   key = (cj_key_t *) malloc (sizeof (*key));
363   if (key == NULL)
364   {
365     ERROR ("curl_json plugin: malloc failed.");
366     return (-1);
367   }
368   memset (key, 0, sizeof (*key));
369   key->magic = CJ_KEY_MAGIC;
370
371   if (strcasecmp ("Key", ci->key) == 0)
372   {
373     status = cf_util_get_string (ci, &key->path);
374     if (status != 0)
375     {
376       sfree (key);
377       return (status);
378     }
379   }
380   else
381   {
382     ERROR ("curl_json plugin: cj_config: "
383            "Invalid key: %s", ci->key);
384     return (-1);
385   }
386
387   status = 0;
388   for (i = 0; i < ci->children_num; i++)
389   {
390     oconfig_item_t *child = ci->children + i;
391
392     if (strcasecmp ("Type", child->key) == 0)
393       status = cf_util_get_string (child, &key->type);
394     else if (strcasecmp ("Instance", child->key) == 0)
395       status = cf_util_get_string (child, &key->instance);
396     else
397     {
398       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
399       status = -1;
400     }
401
402     if (status != 0)
403       break;
404   } /* for (i = 0; i < ci->children_num; i++) */
405
406   while (status == 0)
407   {
408     if (key->type == NULL)
409     {
410       WARNING ("curl_json plugin: `Type' missing in `Key' block.");
411       status = -1;
412     }
413
414     break;
415   } /* while (status == 0) */
416
417   /* store path in a tree that will match the json map structure, example:
418    * "httpd/requests/count",
419    * "httpd/requests/current" ->
420    * { "httpd": { "requests": { "count": $key, "current": $key } } }
421    */
422   if (status == 0)
423   {
424     char *ptr;
425     char *name;
426     char ent[PATH_MAX];
427     c_avl_tree_t *tree;
428
429     if (db->tree == NULL)
430       db->tree = cj_avl_create();
431
432     tree = db->tree;
433     name = key->path;
434     ptr = key->path;
435     if (*ptr == '/')
436       ++ptr;
437
438     name = ptr;
439     while (*ptr)
440     {
441       if (*ptr == '/')
442       {
443         c_avl_tree_t *value;
444         int len;
445
446         len = ptr-name;
447         if (len == 0)
448           break;
449         sstrncpy (ent, name, len+1);
450
451         if (c_avl_get (tree, ent, (void *) &value) != 0)
452         {
453           value = cj_avl_create ();
454           c_avl_insert (tree, strdup (ent), value);
455         }
456
457         tree = value;
458         name = ptr+1;
459       }
460       ++ptr;
461     }
462     if (*name)
463       c_avl_insert (tree, strdup(name), key);
464     else
465     {
466       ERROR ("curl_json plugin: invalid key: %s", key->path);
467       status = -1;
468     }
469   }
470
471   return (status);
472 } /* }}} int cj_config_add_key */
473
474 static int cj_init_curl (cj_t *db) /* {{{ */
475 {
476   db->curl = curl_easy_init ();
477   if (db->curl == NULL)
478   {
479     ERROR ("curl_json plugin: curl_easy_init failed.");
480     return (-1);
481   }
482
483   curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
484   curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
485   curl_easy_setopt (db->curl, CURLOPT_USERAGENT,
486                     PACKAGE_NAME"/"PACKAGE_VERSION);
487   curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
488   curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
489
490   if (db->user != NULL)
491   {
492     size_t credentials_size;
493
494     credentials_size = strlen (db->user) + 2;
495     if (db->pass != NULL)
496       credentials_size += strlen (db->pass);
497
498     db->credentials = (char *) malloc (credentials_size);
499     if (db->credentials == NULL)
500     {
501       ERROR ("curl_json plugin: malloc failed.");
502       return (-1);
503     }
504
505     ssnprintf (db->credentials, credentials_size, "%s:%s",
506                db->user, (db->pass == NULL) ? "" : db->pass);
507     curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
508   }
509
510   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (int) db->verify_peer);
511   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
512                     (int) (db->verify_host ? 2 : 0));
513   if (db->cacert != NULL)
514     curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
515
516   return (0);
517 } /* }}} int cj_init_curl */
518
519 static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
520 {
521   cj_t *db;
522   int status = 0;
523   int i;
524
525   if ((ci->values_num != 1)
526       || (ci->values[0].type != OCONFIG_TYPE_STRING))
527   {
528     WARNING ("curl_json plugin: The `URL' block "
529              "needs exactly one string argument.");
530     return (-1);
531   }
532
533   db = (cj_t *) malloc (sizeof (*db));
534   if (db == NULL)
535   {
536     ERROR ("curl_json plugin: malloc failed.");
537     return (-1);
538   }
539   memset (db, 0, sizeof (*db));
540
541   if (strcasecmp ("URL", ci->key) == 0)
542   {
543     status = cf_util_get_string (ci, &db->url);
544     if (status != 0)
545     {
546       sfree (db);
547       return (status);
548     }
549   }
550   else
551   {
552     ERROR ("curl_json plugin: cj_config: "
553            "Invalid key: %s", ci->key);
554     return (-1);
555   }
556
557   /* Fill the `cj_t' structure.. */
558   for (i = 0; i < ci->children_num; i++)
559   {
560     oconfig_item_t *child = ci->children + i;
561
562     if (strcasecmp ("Instance", child->key) == 0)
563       status = cf_util_get_string (child, &db->instance);
564     else if (strcasecmp ("Host", child->key) == 0)
565       status = cf_util_get_string (child, &db->host);
566     else if (strcasecmp ("User", child->key) == 0)
567       status = cf_util_get_string (child, &db->user);
568     else if (strcasecmp ("Password", child->key) == 0)
569       status = cf_util_get_string (child, &db->pass);
570     else if (strcasecmp ("VerifyPeer", child->key) == 0)
571       status = cf_util_get_boolean (child, &db->verify_peer);
572     else if (strcasecmp ("VerifyHost", child->key) == 0)
573       status = cf_util_get_boolean (child, &db->verify_host);
574     else if (strcasecmp ("CACert", child->key) == 0)
575       status = cf_util_get_string (child, &db->cacert);
576     else if (strcasecmp ("Key", child->key) == 0)
577       status = cj_config_add_key (db, child);
578     else
579     {
580       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
581       status = -1;
582     }
583
584     if (status != 0)
585       break;
586   }
587
588   if (status == 0)
589   {
590     if (db->tree == NULL)
591     {
592       WARNING ("curl_json plugin: No (valid) `Key' block "
593                "within `URL' block `%s'.", db->url);
594       status = -1;
595     }
596     if (status == 0)
597       status = cj_init_curl (db);
598   }
599
600   /* If all went well, register this database for reading */
601   if (status == 0)
602   {
603     user_data_t ud;
604     char cb_name[DATA_MAX_NAME_LEN];
605
606     if (db->instance == NULL)
607       db->instance = strdup("default");
608
609     DEBUG ("curl_json plugin: Registering new read callback: %s",
610            db->instance);
611
612     memset (&ud, 0, sizeof (ud));
613     ud.data = (void *) db;
614     ud.free_func = cj_free;
615
616     ssnprintf (cb_name, sizeof (cb_name), "curl_json-%s-%s",
617                db->instance, db->url);
618
619     plugin_register_complex_read (/* group = */ NULL, cb_name, cj_read,
620                                   /* interval = */ NULL, &ud);
621   }
622   else
623   {
624     cj_free (db);
625     return (-1);
626   }
627
628   return (0);
629 }
630  /* }}} int cj_config_add_database */
631
632 static int cj_config (oconfig_item_t *ci) /* {{{ */
633 {
634   int success;
635   int errors;
636   int status;
637   int i;
638
639   success = 0;
640   errors = 0;
641
642   for (i = 0; i < ci->children_num; i++)
643   {
644     oconfig_item_t *child = ci->children + i;
645
646     if (strcasecmp ("URL", child->key) == 0)
647     {
648       status = cj_config_add_url (child);
649       if (status == 0)
650         success++;
651       else
652         errors++;
653     }
654     else
655     {
656       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
657       errors++;
658     }
659   }
660
661   if ((success == 0) && (errors > 0))
662   {
663     ERROR ("curl_json plugin: All statements failed.");
664     return (-1);
665   }
666
667   return (0);
668 } /* }}} int cj_config */
669
670 /* }}} End of configuration handling functions */
671
672 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
673 {
674   value_list_t vl = VALUE_LIST_INIT;
675   char *host;
676
677   vl.values     = value;
678   vl.values_len = 1;
679
680   if ((db->host == NULL)
681       || (strcmp ("", db->host) == 0)
682       || (strcmp (CJ_DEFAULT_HOST, db->host) == 0))
683     host = hostname_g;
684   else
685     host = db->host;
686
687   if (key->instance == NULL)
688     ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s",
689                db->state[db->depth-1].name, db->state[db->depth].name);
690   else
691     sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
692
693   sstrncpy (vl.host, host, sizeof (vl.host));
694   sstrncpy (vl.plugin, "curl_json", sizeof (vl.plugin));
695   sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
696   sstrncpy (vl.type, key->type, sizeof (vl.type));
697
698   plugin_dispatch_values (&vl);
699 } /* }}} int cj_submit */
700
701 static int cj_curl_perform (cj_t *db, CURL *curl) /* {{{ */
702 {
703   int status;
704   long rc;
705   char *url;
706   yajl_handle yprev = db->yajl;
707
708   db->yajl = yajl_alloc (&ycallbacks, NULL, NULL, (void *)db);
709   if (db->yajl == NULL)
710   {
711     ERROR ("curl_json plugin: yajl_alloc failed.");
712     db->yajl = yprev;
713     return (-1);
714   }
715
716   status = curl_easy_perform (curl);
717   if (status != 0)
718   {
719     ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
720            status, db->curl_errbuf, url);
721     yajl_free (db->yajl);
722     db->yajl = yprev;
723     return (-1);
724   }
725
726   curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
727   curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rc);
728
729   /* The response code is zero if a non-HTTP transport was used. */
730   if ((rc != 0) && (rc != 200))
731   {
732     ERROR ("curl_json plugin: curl_easy_perform failed with "
733         "response code %ld (%s)", rc, url);
734     yajl_free (db->yajl);
735     db->yajl = yprev;
736     return (-1);
737   }
738
739   status = yajl_parse_complete (db->yajl);
740   if (status != yajl_status_ok)
741   {
742     unsigned char *errmsg;
743
744     errmsg = yajl_get_error (db->yajl, /* verbose = */ 0,
745         /* jsonText = */ NULL, /* jsonTextLen = */ 0);
746     ERROR ("curl_json plugin: yajl_parse_complete failed: %s",
747         (char *) errmsg);
748     yajl_free_error (db->yajl, errmsg);
749     yajl_free (db->yajl);
750     db->yajl = yprev;
751     return (-1);
752   }
753
754   yajl_free (db->yajl);
755   db->yajl = yprev;
756   return (0);
757 } /* }}} int cj_curl_perform */
758
759 static int cj_read (user_data_t *ud) /* {{{ */
760 {
761   cj_t *db;
762
763   if ((ud == NULL) || (ud->data == NULL))
764   {
765     ERROR ("curl_json plugin: cj_read: Invalid user data.");
766     return (-1);
767   }
768
769   db = (cj_t *) ud->data;
770
771   db->depth = 0;
772   memset (&db->state, 0, sizeof(db->state));
773   db->state[db->depth].tree = db->tree;
774   db->key = NULL;
775
776   return cj_curl_perform (db, db->curl);
777 } /* }}} int cj_read */
778
779 void module_register (void)
780 {
781   plugin_register_complex_config ("curl_json", cj_config);
782 } /* void module_register */
783
784 /* vim: set sw=2 sts=2 et fdm=marker : */