e371eab399b9f1743165e8ed3060298573ad3ec4
[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 #include "utils_lua.h"
40
41 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
42 # undef sprintf
43 # pragma GCC poison sprintf
44 #endif
45
46 typedef struct lua_script_s {
47   char          *script_path;
48   lua_State     *lua_state;
49   
50   struct lua_script_s  *next;
51 } lua_script_t;
52
53 struct clua_read_function_s
54 {
55   lua_State *lua_state;
56   char *lua_function_name;
57   int callback_id;
58 };
59 typedef struct clua_read_function_s clua_read_function_t;
60
61 struct lua_c_functions_s
62 {
63   char         *name;
64   lua_CFunction func;
65 };
66 typedef struct lua_c_functions_s lua_c_functions_t;
67
68 static char           base_path[PATH_MAX + 1] = "";
69 static lua_script_t  *scripts = NULL;
70
71 static int clua_store_callback (lua_State *l, int idx) /* {{{ */
72 {
73   static int callback_num = 0;
74   int callback_id;
75
76   /* XXX FIXME: Not thread-safe! */
77   callback_id = callback_num++;
78
79   if (idx < 0)
80     idx += lua_gettop (l) + 1;
81
82   lua_getfield (l, LUA_REGISTRYINDEX, "collectd_callbacks"); /* +1 = 1 */
83   if (!lua_istable (l, /* idx = */ -1))
84   {
85     lua_pop (l, /* nelems = */ 1); /* -1 = 0 */
86     lua_newtable (l); /* +1 = 1 */
87     lua_pushvalue (l, -1); /* +1 = 2 */
88     lua_setfield (l, LUA_REGISTRYINDEX, "collectd_callbacks"); /* -1 = 1 */
89   }
90
91   /* The table is now on top of the stack */
92   lua_pushinteger (l, (lua_Integer) callback_id); /* +1 = 2 */
93
94   /* Copy the function pointer */
95   lua_pushvalue (l, idx); /* +1 = 3 */
96   /* Lookup function if it's a string */
97   if (lua_isstring (l, /* idx = */ -1))
98     lua_gettable (l, LUA_GLOBALSINDEX); /* +-0 = 3 */
99
100   if (!lua_isfunction (l, /* idx = */ -1))
101   {
102     lua_pop (l, /* nelems = */ 3); /* -3 = 0 */
103     return (-1);
104   }
105
106   lua_settable (l, /* idx = */ -3); /* -2 = 1 */
107   lua_pop (l, /* nelems = */ 1); /* -1 = 0 */
108   return (callback_id);
109 } /* }}} int clua_store_callback */
110
111 static int clua_load_callback (lua_State *l, int callback_id) /* {{{ */
112 {
113   lua_getfield (l, LUA_REGISTRYINDEX, "collectd_callbacks"); /* +1 */
114   if (!lua_istable (l, /* idx = */ -1))
115   {
116     lua_pop (l, /* nelems = */ 1); /* -1 */
117     return (-1);
118   }
119
120   lua_pushinteger (l, (lua_Integer) callback_id); /* + 1 */
121   lua_gettable (l, /* idx = */ -2); /* +-0 */
122
123   if (!lua_isfunction (l, -1))
124   {
125     lua_pop (l, /* nelems = */ 2); /* -2 */
126     return (-1);
127   }
128
129   /* Remove table */
130   lua_remove (l, /* idx = */ -2); /* -1 */
131   return (0);
132 } /* }}} int clua_load_callback */
133
134 static int clua_read (user_data_t *ud) /* {{{ */
135 {
136   clua_read_function_t *rf = ud->data;
137   int status;
138
139   status = clua_load_callback (rf->lua_state, rf->callback_id);
140   if (status != 0)
141   {
142     ERROR ("lua plugin: Unable to load callback \"%s\" (id %i).",
143         rf->lua_function_name, rf->callback_id);
144     return (-1);
145   }
146   /* +1 */
147
148   lua_call (rf->lua_state, /* nargs = */ 0, /* nresults = */ 1); /* +1 */
149
150   if (lua_isnumber (rf->lua_state, /* idx = */ -1))
151   {
152     status = (int) lua_tointeger (rf->lua_state, /* idx = */ -1);
153   }
154   else
155   {
156     ERROR ("lua plugin: Read function \"%s\" (id %i) did not return a numeric status.",
157         rf->lua_function_name, rf->callback_id);
158     status = -1;
159   }
160   /* pop return value and function */
161   lua_settop (rf->lua_state, /* idx = */ -2); /* -2 */
162
163   return (status);
164 } /* }}} int clua_read */
165
166 /* Cleans up the stack, pushes the return value as a number onto the stack and
167  * returns the number of values returned (1). */
168 #define RETURN_LUA(l,status) do {                    \
169   lua_State *_l_state = (l);                         \
170   lua_settop (_l_state, 0);                          \
171   lua_pushnumber (_l_state, (lua_Number) (status));  \
172   return (1);                                        \
173 } while (0)
174
175 /*
176  * Exported functions
177  */
178 static int lua_cb_log (lua_State *l) /* {{{ */
179 {
180   int nargs = lua_gettop (l); /* number of arguments */
181   int severity;
182   const char *msg;
183
184   if (nargs != 2)
185   {
186     WARNING ("lua plugin: collectd_log() called with an invalid number of arguments (%i).",
187         nargs);
188     RETURN_LUA (l, -1);
189   }
190
191   if (!lua_isnumber (l, 1))
192   {
193     WARNING ("lua plugin: The first argument to collectd_log() must be a number.");
194     RETURN_LUA (l, -1);
195   }
196
197   if (!lua_isstring (l, 2))
198   {
199     WARNING ("lua plugin: The second argument to collectd_log() must be a string.");
200     RETURN_LUA (l, -1);
201   }
202
203   severity = (int) lua_tonumber (l, /* stack pos = */ 1);
204   if ((severity != LOG_ERR)
205       && (severity != LOG_WARNING)
206       && (severity != LOG_NOTICE)
207       && (severity != LOG_INFO)
208       && (severity != LOG_DEBUG))
209     severity = LOG_ERR;
210
211   msg = lua_tostring (l, 2);
212   if (msg == NULL)
213   {
214     ERROR ("lua plugin: lua_tostring failed.");
215     RETURN_LUA (l, -1);
216   }
217
218   plugin_log (severity, "%s", msg);
219
220   RETURN_LUA (l, 0);
221 } /* }}} int lua_cb_log */
222
223 static int lua_cb_dispatch_values (lua_State *l) /* {{{ */
224 {
225   value_list_t *vl;
226   int nargs = lua_gettop (l); /* number of arguments */
227   char identifier[6 * DATA_MAX_NAME_LEN];
228
229   if (nargs != 1)
230   {
231     WARNING ("lua plugin: collectd_dispatch_values() called "
232         "with an invalid number of arguments (%i).", nargs);
233     RETURN_LUA (l, -1);
234   }
235
236   if (!lua_istable (l, 1))
237   {
238     WARNING ("lua plugin: The first argument to collectd_dispatch_values() "
239         "must be a \"value list\" (i.e. a table).");
240     RETURN_LUA (l, -1);
241   }
242
243   vl = luaC_tovaluelist (l, /* idx = */ -1);
244   if (vl == NULL)
245   {
246     WARNING ("lua plugin: ltoc_value_list failed.");
247     RETURN_LUA (l, -1);
248   }
249
250   FORMAT_VL (identifier, sizeof (identifier), vl);
251
252   DEBUG ("lua plugin: collectd_dispatch_values: Received value list \"%s\", time %.3f, interval %.3f.",
253       identifier, CDTIME_T_TO_DOUBLE (vl->time), CDTIME_T_TO_DOUBLE (vl->interval));
254
255   sfree (vl->values);
256   sfree (vl);
257   RETURN_LUA (l, 0);
258 } /* }}} lua_cb_dispatch_values */
259
260 static int lua_cb_register_read (lua_State *l) /* {{{ */
261 {
262   int nargs = lua_gettop (l); /* number of arguments */
263   clua_read_function_t *rf;
264
265   int callback_id;
266   char function_name[DATA_MAX_NAME_LEN] = "";
267
268   if (nargs != 1)
269   {
270     WARNING ("lua plugin: collectd_register_read() called with an invalid "
271         "number of arguments (%i).", nargs);
272     RETURN_LUA (l, -1);
273   }
274
275   if (lua_isstring (l, /* stack pos = */ 1))
276   {
277     const char *tmp = lua_tostring (l, /* idx = */ 1);
278     ssnprintf (function_name, sizeof (function_name), "lua/%s", tmp);
279   }
280
281   callback_id = clua_store_callback (l, /* idx = */ 1);
282   if (callback_id < 0)
283   {
284     ERROR ("lua plugin: Storing callback function failed.");
285     RETURN_LUA (l, -1);
286   }
287
288   if (function_name[0] == 0)
289     ssnprintf (function_name, sizeof (function_name), "lua/callback_%i", callback_id);
290
291   rf = malloc (sizeof (*rf));
292   if (rf == NULL)
293   {
294     ERROR ("lua plugin: malloc failed.");
295     RETURN_LUA (l, -1);
296   }
297   else
298   {
299     user_data_t ud = { rf, /* free func */ NULL /* FIXME */ };
300
301     memset (rf, 0, sizeof (*rf));
302     rf->lua_state = l;
303     rf->callback_id = callback_id;
304     rf->lua_function_name = strdup (function_name);
305
306     plugin_register_complex_read (/* group = */ "lua",
307         /* name      = */ function_name,
308         /* callback  = */ clua_read,
309         /* interval  = */ NULL,
310         /* user_data = */ &ud);
311   }
312
313   DEBUG ("lua plugin: Successful call to lua_cb_register_read().");
314
315   RETURN_LUA (l, 0);
316 } /* }}} int lua_cb_register_read */
317
318 static lua_c_functions_t lua_c_functions[] =
319 {
320   { "collectd_log", lua_cb_log },
321   { "collectd_dispatch_values", lua_cb_dispatch_values },
322   { "collectd_register_read", lua_cb_register_read }
323 };
324
325 static void lua_script_free (lua_script_t *script) /* {{{ */
326 {
327   lua_script_t *next;
328
329   if (script == NULL)
330     return;
331
332   next = script->next;
333
334   if (script->lua_state != NULL)
335   {
336     lua_close (script->lua_state);
337     script->lua_state = NULL;
338   }
339
340   sfree (script->script_path);
341   sfree (script);
342
343   lua_script_free (next);
344 } /* }}} void lua_script_free */
345
346 static int lua_script_init (lua_script_t *script) /* {{{ */
347 {
348   size_t i;
349
350   memset (script, 0, sizeof (*script));
351   script->script_path = NULL;
352   script->next = NULL;
353
354   /* initialize the lua context */
355   script->lua_state = lua_open();
356   if (script->lua_state == NULL)
357   {
358     ERROR ("lua plugin: lua_open failed.");
359     return (-1);
360   }
361
362   /* Open up all the standard Lua libraries. */
363   luaL_openlibs (script->lua_state);
364
365   /* Register all the functions we implement in C */
366   for (i = 0; i < STATIC_ARRAY_SIZE (lua_c_functions); i++)
367     lua_register (script->lua_state,
368         lua_c_functions[i].name, lua_c_functions[i].func);
369
370   return (0);
371 } /* }}} int lua_script_init */
372
373 static int lua_script_load (const char *script_path) /* {{{ */
374 {
375   lua_script_t *script;
376   int status;
377
378   script = malloc (sizeof (*script));
379   if (script == NULL)
380   {
381     ERROR ("lua plugin: malloc failed.");
382     return (-1);
383   }
384
385   status = lua_script_init (script);
386   if (status != 0)
387   {
388     lua_script_free (script);
389     return (status);
390   }
391
392   script->script_path = strdup (script_path);
393   if (script->script_path == NULL)
394   {
395     ERROR ("lua plugin: strdup failed.");
396     lua_script_free (script);
397     return (-1);
398   }
399
400   status = luaL_loadfile (script->lua_state, script->script_path);
401   if (status != 0)
402   {
403     ERROR ("lua plugin: luaL_loadfile failed with status %i", status);
404     lua_script_free (script);
405     return (-1);
406   }
407
408   status = lua_pcall (script->lua_state,
409       /* nargs = */    0,
410       /* nresults = */ LUA_MULTRET,
411       /* errfunc = */  0);
412   if (status != 0)
413   {
414     const char *errmsg;
415
416     errmsg = lua_tostring (script->lua_state, /* stack pos = */ -1);
417
418     if (errmsg == NULL)
419       ERROR ("lua plugin: lua_pcall failed with status %i. "
420           "In addition, no error message could be retrieved from the stack.",
421           status);
422     else
423       ERROR ("lua plugin: Executing script \"%s\" failed:\n%s",
424           script->script_path, errmsg);
425
426     lua_script_free (script);
427     return (-1);
428   }
429
430   /* Append this script to the global list of scripts. */
431   if (scripts == NULL)
432   {
433     scripts = script;
434   }
435   else
436   {
437     lua_script_t *last;
438
439     last = scripts;
440     while (last->next != NULL)
441       last = last->next;
442
443     last->next = script;
444   }
445
446   return (0);
447 } /* }}} int lua_script_load */
448
449 static int lua_config_base_path (const oconfig_item_t *ci) /* {{{ */
450 {
451   int status;
452   size_t len;
453
454   status = cf_util_get_string_buffer (ci, base_path, sizeof (base_path));
455   if (status != 0)
456     return (status);
457
458   len = strlen (base_path);
459   while ((len > 0) && (base_path[len - 1] == '/'))
460   {
461     len--;
462     base_path[len] = 0;
463   }
464
465   DEBUG ("lua plugin: base_path = \"%s\";", base_path);
466
467   return (0);
468 } /* }}} int lua_config_base_path */
469
470 static int lua_config_script (const oconfig_item_t *ci) /* {{{ */
471 {
472   char rel_path[PATH_MAX + 1];
473   char abs_path[PATH_MAX + 1];
474   int status;
475
476   status = cf_util_get_string_buffer (ci, rel_path, sizeof (rel_path));
477   if (status != 0)
478     return (status);
479
480   if (base_path[0] == 0)
481     sstrncpy (abs_path, rel_path, sizeof (abs_path));
482   else
483     ssnprintf (abs_path, sizeof (abs_path), "%s/%s", base_path, rel_path);
484
485   DEBUG ("lua plugin: abs_path = \"%s\";", abs_path);
486
487   status = lua_script_load (abs_path);
488   if (status != 0)
489     return (status);
490
491   INFO("lua plugin: File \"%s\" loaded succesfully", abs_path);
492   
493   return 0;
494 } /* }}} int lua_config_script */
495
496 /*
497  * <Plugin lua>
498  *   BasePath "/"
499  *   Script "script1.lua"
500  *   Script "script2.lua"
501  * </Plugin>
502  */
503 static int lua_config (oconfig_item_t *ci) /* {{{ */
504 {
505   int i;
506
507   for (i = 0; i < ci->children_num; i++)
508   {
509     oconfig_item_t *child = ci->children + i;
510
511     if (strcasecmp ("BasePath", child->key) == 0) {
512       lua_config_base_path(child);
513     }
514     else if (strcasecmp ("Script", child->key) == 0){
515       lua_config_script(child);
516     }
517     else
518     {
519       WARNING ("network plugin: Option `%s' is not allowed here.",
520           child->key);
521     }
522   }
523   
524   return 0;
525 } /* }}} int lua_config */
526
527 static int lua_shutdown (void) /* {{{ */
528 {
529   lua_script_free (scripts);
530   scripts = NULL;
531
532   return (0);
533 } /* }}} int lua_shutdown */
534
535 void module_register()
536 {
537   plugin_register_complex_config("lua", lua_config);
538   plugin_register_shutdown("lua", lua_shutdown);
539 }
540
541 /* vim: set sw=2 sts=2 et fdm=marker : */