lua plugin: Implement conversion of Lua numbers to value_t.
[collectd.git] / src / lua.c
1 /**
2  * collectd - src/lua.c
3  * Copyright (C) 2010       Julien Ammous
4  * Copyright (C) 2010       Florian Forster
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation; only version 2.1 of the License is
9  * applicable.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * Authors:
21  *   Julien Ammous
22  *   Florian Forster <octo at collectd.org>
23  **/
24
25 /* <lua5.1/luaconf.h> defines a macro using "sprintf". Although not used here,
26  * GCC will complain about the macro definition. */
27 #define DONT_POISON_SPRINTF_YET
28
29 #include "collectd.h"
30 #include "plugin.h"
31 #include "common.h"
32 #include "configfile.h"
33 #include "utils_cache.h"
34
35 /* Include the Lua API header files. */
36 #include <lua.h>
37 #include <lauxlib.h>
38 #include <lualib.h>
39
40 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
41 # undef sprintf
42 # pragma GCC poison sprintf
43 #endif
44
45 typedef struct lua_script_s {
46   char          *script_path;
47   lua_State     *lua_state;
48   
49   struct lua_script_s  *next;
50 } lua_script_t;
51
52 struct clua_read_function_s
53 {
54   lua_State *lua_state;
55   char *lua_function_name;
56 };
57 typedef struct clua_read_function_s clua_read_function_t;
58
59 struct lua_c_functions_s
60 {
61   char         *name;
62   lua_CFunction func;
63 };
64 typedef struct lua_c_functions_s lua_c_functions_t;
65
66 static char           base_path[PATH_MAX + 1] = "";
67 static lua_script_t  *scripts = NULL;
68
69 static int clua_read (user_data_t *ud) /* {{{ */
70 {
71   clua_read_function_t *rf = ud->data;
72   int status;
73
74   /* Load the function to the stack */
75   lua_pushstring (rf->lua_state, rf->lua_function_name);
76   lua_gettable (rf->lua_state, LUA_REGISTRYINDEX);
77
78   if (!lua_isfunction (rf->lua_state, /* stack pos = */ -1))
79   {
80     ERROR ("lua plugin: Unable to lookup the read function \"%s\".",
81         rf->lua_function_name);
82     /* pop the value again */
83     lua_settop (rf->lua_state, -2);
84     return (-1);
85   }
86
87   lua_call (rf->lua_state, /* nargs = */ 0, /* nresults = */ 1);
88
89   if (lua_isnumber (rf->lua_state, -1))
90   {
91     status = (int) lua_tonumber (rf->lua_state, -1);
92   }
93   else
94   {
95     ERROR ("lua plugin: Read function \"%s\" did not return a numeric status.",
96         rf->lua_function_name);
97     status = -1;
98   }
99   /* pop the value */
100   lua_settop (rf->lua_state, -2);
101
102   return (status);
103 } /* }}} int clua_read */
104
105 /* Cleans up the stack, pushes the return value as a number onto the stack and
106  * returns the number of values returned (1). */
107 #define RETURN_LUA(l,status) do {                    \
108   lua_State *_l_state = (l);                         \
109   lua_settop (_l_state, 0);                          \
110   lua_pushnumber (_l_state, (lua_Number) (status));  \
111   return (1);                                        \
112 } while (0)
113
114 static int ltoc_value (lua_State *l, /* {{{ */
115     int ds_type, value_t *ret_value)
116 {
117   if (!lua_isnumber (l, /* stack pos = */ -1))
118     return (-1);
119
120   if (ds_type == DS_TYPE_GAUGE)
121     ret_value->gauge = (gauge_t) lua_tonumber (l, /* stack pos = */ -1);
122   else if (ds_type == DS_TYPE_DERIVE)
123     ret_value->derive = (derive_t) lua_tointeger (l, /* stack pos = */ -1);
124   else if (ds_type == DS_TYPE_COUNTER)
125     ret_value->counter = (counter_t) lua_tointeger (l, /* stack pos = */ -1);
126   else if (ds_type == DS_TYPE_ABSOLUTE)
127     ret_value->absolute = (absolute_t) lua_tointeger (l, /* stack pos = */ -1);
128   else
129     assert (23 == 42);
130
131   return (0);
132 } /* }}} int ltoc_value */
133
134 static int ltoc_values (lua_State *l, /* {{{ */
135     const data_set_t *ds,
136     value_t *ret_values)
137 {
138   size_t i;
139   int status = 0;
140
141   if (!lua_istable (l, -1))
142   {
143     lua_pop (l, /* nelem = */ 1);
144     return (-1);
145   }
146
147   /* Push initial key */
148   lua_pushnil (l);
149   for (i = 0; i < ((size_t) ds->ds_num); i++)
150   {
151     /* Pops old key and pushed new key and value. */
152     status = lua_next (l, -2);
153     if (status == 0) /* no more elements */
154       break;
155
156     status = ltoc_value (l, ds->ds[i].type, ret_values + i);
157     if (status != 0)
158     {
159       DEBUG ("ltoc_value failed.");
160       break;
161     }
162
163     /* Pop the value */
164     lua_pop (l, /* nelems = */ 1);
165   }
166   /* Pop the key and the table itself */
167   lua_pop (l, /* nelems = */ 2);
168
169   return (status);
170 } /* }}} int ltoc_values */
171
172 static int ltoc_table_values (lua_State *l, /* {{{ */
173     const data_set_t *ds, value_list_t *vl)
174 {
175   int status;
176
177   lua_pushstring (l, "values");
178   lua_gettable (l, -2);
179
180   if (!lua_istable (l, -1))
181   {
182     NOTICE ("lua plugin: ltoc_table_values: The \"values\" member is not a table.");
183     lua_pop (l, /* nelem = */ 1);
184     return (-1);
185   }
186
187   vl->values_len = ds->ds_num;
188   vl->values = calloc ((size_t) vl->values_len, sizeof (*vl->values));
189   if (vl->values == NULL)
190   {
191     ERROR ("lua plugin: calloc failed.");
192     vl->values_len = 0;
193     lua_pop (l, /* nelem = */ 1);
194     return (-1);
195   }
196
197   status = ltoc_values (l, ds, vl->values);
198
199   lua_pop (l, /* nelem = */ 1);
200
201   if (status != 0)
202   {
203     vl->values_len = 0;
204     sfree (vl->values);
205   }
206
207   return (status);
208 } /* }}} int ltoc_table_values */
209
210 static int ltoc_string_buffer (lua_State *l, /* {{{ */
211     char *buffer, size_t buffer_size,
212     _Bool consume)
213 {
214   const char *str;
215
216   str = lua_tostring (l, /* stack pos = */ -1);
217   if (str != NULL)
218     sstrncpy (buffer, str, buffer_size);
219
220   if (consume)
221     lua_pop (l, /* nelem = */ 1);
222
223   return ((str != NULL) ? 0 : -1);
224 } /* }}} int ltoc_string_buffer */
225
226 static int ltoc_table_string_buffer (lua_State *l, /* {{{ */
227     const char *table_key,
228     char *buffer, size_t buffer_size)
229 {
230   lua_pushstring (l, table_key);
231   lua_gettable (l, -2);
232
233   if (!lua_isstring (l, /* stack pos = */ -1))
234   {
235     lua_pop (l, /* nelem = */ 1);
236     return (-1);
237   }
238
239   return (ltoc_string_buffer (l, buffer, buffer_size, /* consume = */ 1));
240 } /* }}} int ltoc_table_string_buffer */
241
242 static int ltoc_table_cdtime (lua_State *l, /* {{{ */
243     const char *table_key, cdtime_t *ret_time)
244 {
245   double d;
246
247   lua_pushstring (l, table_key);
248   lua_gettable (l, -2);
249
250   if (!lua_isnumber (l, /* stack pos = */ -1))
251   {
252     lua_pop (l, /* nelem = */ 1);
253     return (-1);
254   }
255
256   d = (double) lua_tonumber (l, -1);
257   lua_pop (l, /* nelem = */ 1);
258
259   *ret_time = DOUBLE_TO_CDTIME_T (d);
260   return (0);
261 } /* }}} int ltoc_table_cdtime */
262
263 static value_list_t *ltoc_value_list (lua_State *l) /* {{{ */
264 {
265   const data_set_t *ds;
266   value_list_t *vl;
267   int status;
268
269   vl = malloc (sizeof (*vl));
270   if (vl == NULL)
271     return (NULL);
272   memset (vl, 0, sizeof (*vl));
273   vl->values = NULL;
274   vl->meta = NULL;
275
276 #define COPY_FIELD(field,def) do {                                              \
277   status = ltoc_table_string_buffer (l, #field, vl->field, sizeof (vl->field)); \
278   if (status != 0) {                                                            \
279     if ((def) == NULL)                                                          \
280       return (NULL);                                                            \
281     else                                                                        \
282       sstrncpy (vl->field, (def), sizeof (vl->field));                          \
283   }                                                                             \
284 } while (0)
285
286   COPY_FIELD (host, hostname_g);
287   COPY_FIELD (plugin, NULL);
288   COPY_FIELD (plugin_instance, "");
289   COPY_FIELD (type, NULL);
290   COPY_FIELD (type_instance, "");
291
292 #undef COPY_FIELD
293
294   ds = plugin_get_ds (vl->type);
295   if (ds == NULL)
296   {
297     INFO ("lua plugin: Unable to lookup type \"%s\".", vl->type);
298     sfree (vl);
299     return (NULL);
300   }
301
302   status = ltoc_table_cdtime (l, "time", &vl->time);
303   if (status != 0)
304     vl->time = cdtime ();
305
306   status = ltoc_table_cdtime (l, "interval", &vl->interval);
307   if (status != 0)
308     vl->interval = interval_g;
309
310   status = ltoc_table_values (l, ds, vl);
311   if (status != 0)
312   {
313     WARNING ("lua plugin: ltoc_table_values failed.");
314     sfree (vl);
315     return (NULL);
316   }
317
318   return (vl);
319 } /* }}} value_list_t *ltoc_value_list */
320
321 /*
322  * Exported functions
323  */
324 static int lua_cb_log (lua_State *l) /* {{{ */
325 {
326   int nargs = lua_gettop (l); /* number of arguments */
327   int severity;
328   const char *msg;
329
330   if (nargs != 2)
331   {
332     WARNING ("lua plugin: collectd_log() called with an invalid number of arguments (%i).",
333         nargs);
334     RETURN_LUA (l, -1);
335   }
336
337   if (!lua_isnumber (l, 1))
338   {
339     WARNING ("lua plugin: The first argument to collectd_log() must be a number.");
340     RETURN_LUA (l, -1);
341   }
342
343   if (!lua_isstring (l, 2))
344   {
345     WARNING ("lua plugin: The second argument to collectd_log() must be a string.");
346     RETURN_LUA (l, -1);
347   }
348
349   severity = (int) lua_tonumber (l, /* stack pos = */ 1);
350   if ((severity != LOG_ERR)
351       && (severity != LOG_WARNING)
352       && (severity != LOG_NOTICE)
353       && (severity != LOG_INFO)
354       && (severity != LOG_DEBUG))
355     severity = LOG_ERR;
356
357   msg = lua_tostring (l, 2);
358   if (msg == NULL)
359   {
360     ERROR ("lua plugin: lua_tostring failed.");
361     RETURN_LUA (l, -1);
362   }
363
364   plugin_log (severity, "%s", msg);
365
366   RETURN_LUA (l, 0);
367 } /* }}} int lua_cb_log */
368
369 static int lua_cb_dispatch_values (lua_State *l) /* {{{ */
370 {
371   value_list_t *vl;
372   int nargs = lua_gettop (l); /* number of arguments */
373   char identifier[6 * DATA_MAX_NAME_LEN];
374
375   if (nargs != 1)
376   {
377     WARNING ("lua plugin: collectd_dispatch_values() called "
378         "with an invalid number of arguments (%i).", nargs);
379     RETURN_LUA (l, -1);
380   }
381
382   if (!lua_istable (l, 1))
383   {
384     WARNING ("lua plugin: The first argument to collectd_dispatch_values() "
385         "must be a table.");
386     RETURN_LUA (l, -1);
387   }
388
389   vl = ltoc_value_list (l);
390   if (vl == NULL)
391   {
392     WARNING ("lua plugin: ltoc_value_list failed.");
393     RETURN_LUA (l, -1);
394   }
395
396   FORMAT_VL (identifier, sizeof (identifier), vl);
397
398   DEBUG ("lua plugin: collectd_dispatch_values: Received value list \"%s\", time %.3f, interval %.3f.",
399       identifier, CDTIME_T_TO_DOUBLE (vl->time), CDTIME_T_TO_DOUBLE (vl->interval));
400
401   sfree (vl->values);
402   sfree (vl);
403   RETURN_LUA (l, 0);
404 } /* }}} lua_cb_dispatch_values */
405
406 static int lua_cb_register_read (lua_State *l) /* {{{ */
407 {
408   static int count = 0;
409   int nargs = lua_gettop (l); /* number of arguments */
410   clua_read_function_t *rf;
411
412   int num = count++; /* XXX FIXME: Not thread-safe! */
413   char function_name[64];
414
415   if (nargs != 1)
416   {
417     WARNING ("lua plugin: collectd_register_read() called with an invalid "
418         "number of arguments (%i).", nargs);
419     RETURN_LUA (l, -1);
420   }
421
422   /* If the argument is a string, assume it's a global function and try to look
423    * it up. */
424   if (lua_isstring (l, /* stack pos = */ 1))
425     lua_gettable (l, LUA_GLOBALSINDEX);
426
427   if (!lua_isfunction (l, /* stack pos = */ 1))
428   {
429     WARNING ("lua plugin: The first argument of collectd_register_read() "
430         "must be a function.");
431     RETURN_LUA (l, -1);
432   }
433
434   ssnprintf (function_name, sizeof (function_name), "collectd.read_func_%i", num);
435
436   /* Push the name of the global variable */
437   lua_pushstring (l, function_name);
438   /* Push the name down to the first position */
439   lua_insert (l, 1);
440   /* Now set the global variable called "collectd". */
441   lua_settable (l, LUA_REGISTRYINDEX);
442
443   rf = malloc (sizeof (*rf));
444   if (rf == NULL)
445   {
446     ERROR ("lua plugin: malloc failed.");
447     RETURN_LUA (l, -1);
448   }
449   else
450   {
451     user_data_t ud = { rf, /* free func */ NULL /* FIXME */ };
452     char cb_name[DATA_MAX_NAME_LEN];
453
454     memset (rf, 0, sizeof (*rf));
455     rf->lua_state = l;
456     rf->lua_function_name = strdup (function_name);
457
458     ssnprintf (cb_name, sizeof (cb_name), "lua/read_func_%i", num);
459
460     plugin_register_complex_read (/* group = */ "lua",
461         /* name      = */ cb_name,
462         /* callback  = */ clua_read,
463         /* interval  = */ NULL,
464         /* user_data = */ &ud);
465   }
466
467   DEBUG ("lua plugin: Successful call to lua_cb_register_read().");
468
469   RETURN_LUA (l, 0);
470 } /* }}} int lua_cb_register_read */
471
472 static lua_c_functions_t lua_c_functions[] =
473 {
474   { "collectd_log", lua_cb_log },
475   { "collectd_dispatch_values", lua_cb_dispatch_values },
476   { "collectd_register_read", lua_cb_register_read }
477 };
478
479 static void lua_script_free (lua_script_t *script) /* {{{ */
480 {
481   lua_script_t *next;
482
483   if (script == NULL)
484     return;
485
486   next = script->next;
487
488   if (script->lua_state != NULL)
489   {
490     lua_close (script->lua_state);
491     script->lua_state = NULL;
492   }
493
494   sfree (script->script_path);
495   sfree (script);
496
497   lua_script_free (next);
498 } /* }}} void lua_script_free */
499
500 static int lua_script_init (lua_script_t *script) /* {{{ */
501 {
502   size_t i;
503
504   memset (script, 0, sizeof (*script));
505   script->script_path = NULL;
506   script->next = NULL;
507
508   /* initialize the lua context */
509   script->lua_state = lua_open();
510   if (script->lua_state == NULL)
511   {
512     ERROR ("lua plugin: lua_open failed.");
513     return (-1);
514   }
515
516   /* Open up all the standard Lua libraries. */
517   luaL_openlibs (script->lua_state);
518
519   /* Register all the functions we implement in C */
520   for (i = 0; i < STATIC_ARRAY_SIZE (lua_c_functions); i++)
521     lua_register (script->lua_state,
522         lua_c_functions[i].name, lua_c_functions[i].func);
523
524   return (0);
525 } /* }}} int lua_script_init */
526
527 static int lua_script_load (const char *script_path) /* {{{ */
528 {
529   lua_script_t *script;
530   int status;
531
532   script = malloc (sizeof (*script));
533   if (script == NULL)
534   {
535     ERROR ("lua plugin: malloc failed.");
536     return (-1);
537   }
538
539   status = lua_script_init (script);
540   if (status != 0)
541   {
542     lua_script_free (script);
543     return (status);
544   }
545
546   script->script_path = strdup (script_path);
547   if (script->script_path == NULL)
548   {
549     ERROR ("lua plugin: strdup failed.");
550     lua_script_free (script);
551     return (-1);
552   }
553
554   status = luaL_loadfile (script->lua_state, script->script_path);
555   if (status != 0)
556   {
557     ERROR ("lua plugin: luaL_loadfile failed with status %i", status);
558     lua_script_free (script);
559     return (-1);
560   }
561
562   status = lua_pcall (script->lua_state,
563       /* nargs = */    0,
564       /* nresults = */ LUA_MULTRET,
565       /* errfunc = */  0);
566   if (status != 0)
567   {
568     const char *errmsg;
569
570     errmsg = lua_tostring (script->lua_state, /* stack pos = */ -1);
571
572     if (errmsg == NULL)
573       ERROR ("lua plugin: lua_pcall failed with status %i. "
574           "In addition, no error message could be retrieved from the stack.",
575           status);
576     else
577       ERROR ("lua plugin: Executing script \"%s\" failed:\n%s",
578           script->script_path, errmsg);
579
580     lua_script_free (script);
581     return (-1);
582   }
583
584   /* Append this script to the global list of scripts. */
585   if (scripts == NULL)
586   {
587     scripts = script;
588   }
589   else
590   {
591     lua_script_t *last;
592
593     last = scripts;
594     while (last->next != NULL)
595       last = last->next;
596
597     last->next = script;
598   }
599
600   return (0);
601 } /* }}} int lua_script_load */
602
603 static int lua_config_base_path (const oconfig_item_t *ci) /* {{{ */
604 {
605   int status;
606   size_t len;
607
608   status = cf_util_get_string_buffer (ci, base_path, sizeof (base_path));
609   if (status != 0)
610     return (status);
611
612   len = strlen (base_path);
613   while ((len > 0) && (base_path[len - 1] == '/'))
614   {
615     len--;
616     base_path[len] = 0;
617   }
618
619   DEBUG ("lua plugin: base_path = \"%s\";", base_path);
620
621   return (0);
622 } /* }}} int lua_config_base_path */
623
624 static int lua_config_script (const oconfig_item_t *ci) /* {{{ */
625 {
626   char rel_path[PATH_MAX + 1];
627   char abs_path[PATH_MAX + 1];
628   int status;
629
630   status = cf_util_get_string_buffer (ci, rel_path, sizeof (rel_path));
631   if (status != 0)
632     return (status);
633
634   if (base_path[0] == 0)
635     sstrncpy (abs_path, rel_path, sizeof (abs_path));
636   else
637     ssnprintf (abs_path, sizeof (abs_path), "%s/%s", base_path, rel_path);
638
639   DEBUG ("lua plugin: abs_path = \"%s\";", abs_path);
640
641   status = lua_script_load (abs_path);
642   if (status != 0)
643     return (status);
644
645   INFO("lua plugin: File \"%s\" loaded succesfully", abs_path);
646   
647   return 0;
648 } /* }}} int lua_config_script */
649
650 /*
651  * <Plugin lua>
652  *   BasePath "/"
653  *   Script "script1.lua"
654  *   Script "script2.lua"
655  * </Plugin>
656  */
657 static int lua_config (oconfig_item_t *ci) /* {{{ */
658 {
659   int i;
660
661   for (i = 0; i < ci->children_num; i++)
662   {
663     oconfig_item_t *child = ci->children + i;
664
665     if (strcasecmp ("BasePath", child->key) == 0) {
666       lua_config_base_path(child);
667     }
668     else if (strcasecmp ("Script", child->key) == 0){
669       lua_config_script(child);
670     }
671     else
672     {
673       WARNING ("network plugin: Option `%s' is not allowed here.",
674           child->key);
675     }
676   }
677   
678   return 0;
679 } /* }}} int lua_config */
680
681 static int lua_shutdown (void) /* {{{ */
682 {
683   lua_script_free (scripts);
684   scripts = NULL;
685
686   return (0);
687 } /* }}} int lua_shutdown */
688
689 void module_register()
690 {
691   plugin_register_complex_config("lua", lua_config);
692   plugin_register_shutdown("lua", lua_shutdown);
693 }
694
695 /* vim: set sw=2 sts=2 et fdm=marker : */