lua plugin: A first and very simple take at read callbacks.
[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 #include "collectd.h"
26 #include "plugin.h"
27 #include "common.h"
28 #include "configfile.h"
29 #include "utils_cache.h"
30
31 /* Include the Lua API header files. */
32 #include <lua.h>
33 #include <lauxlib.h>
34 #include <lualib.h>
35
36 typedef struct lua_script_s {
37   char          *script_path;
38   lua_State     *lua_state;
39   
40   struct lua_script_s  *next;
41 } lua_script_t;
42
43 struct clua_read_function_s
44 {
45   lua_State *lua_state;
46   char *lua_function_name;
47 };
48 typedef struct clua_read_function_s clua_read_function_t;
49
50 struct lua_c_functions_s
51 {
52   char         *name;
53   lua_CFunction func;
54 };
55 typedef struct lua_c_functions_s lua_c_functions_t;
56
57 static char           base_path[PATH_MAX + 1] = "";
58 static lua_script_t  *scripts = NULL;
59
60 static int clua_read (user_data_t *ud) /* {{{ */
61 {
62   clua_read_function_t *rf = ud->data;
63   int status;
64
65   /* Load the function to the stack */
66   lua_pushstring (rf->lua_state, rf->lua_function_name);
67   lua_gettable (rf->lua_state, LUA_REGISTRYINDEX);
68
69   if (!lua_isfunction (rf->lua_state, /* stack pos = */ -1))
70   {
71     ERROR ("lua plugin: Unable to lookup the read function \"%s\".",
72         rf->lua_function_name);
73     /* pop the value again */
74     lua_settop (rf->lua_state, -2);
75     return (-1);
76   }
77
78   lua_call (rf->lua_state, /* nargs = */ 0, /* nresults = */ 1);
79
80   if (lua_isnumber (rf->lua_state, -1))
81   {
82     status = (int) lua_tonumber (rf->lua_state, -1);
83   }
84   else
85   {
86     ERROR ("lua plugin: Read function \"%s\" did not return a numeric status.",
87         rf->lua_function_name);
88     status = -1;
89   }
90   /* pop the value */
91   lua_settop (rf->lua_state, -2);
92
93   return (status);
94 } /* }}} int clua_read */
95
96 /* Cleans up the stack, pushes the return value as a number onto the stack and
97  * returns the number of values returned (1). */
98 #define RETURN_LUA(l,status) do {                    \
99   lua_State *_l_state = (l);                         \
100   lua_settop (_l_state, 0);                          \
101   lua_pushnumber (_l_state, (lua_Number) (status));  \
102   return (1);                                        \
103 } while (0)
104
105 /*
106  * Exported functions
107  */
108 static int lua_cb_log (lua_State *l) /* {{{ */
109 {
110   int nargs = lua_gettop (l); /* number of arguments */
111   int severity;
112   const char *msg;
113
114   if (nargs != 2)
115   {
116     WARNING ("lua plugin: collectd_log() called with an invalid number of arguments (%i).",
117         nargs);
118     RETURN_LUA (l, -1);
119   }
120
121   if (!lua_isnumber (l, 1))
122   {
123     WARNING ("lua plugin: The first argument to collectd_log() must be a number.");
124     RETURN_LUA (l, -1);
125   }
126
127   if (!lua_isstring (l, 2))
128   {
129     WARNING ("lua plugin: The second argument to collectd_log() must be a string.");
130     RETURN_LUA (l, -1);
131   }
132
133   severity = (int) lua_tonumber (l, /* stack pos = */ 1);
134   if ((severity != LOG_ERR)
135       && (severity != LOG_WARNING)
136       && (severity != LOG_NOTICE)
137       && (severity != LOG_INFO)
138       && (severity != LOG_DEBUG))
139     severity = LOG_ERR;
140
141   msg = lua_tostring (l, 2);
142   if (msg == NULL)
143   {
144     ERROR ("lua plugin: lua_tostring failed.");
145     RETURN_LUA (l, -1);
146   }
147
148   plugin_log (severity, "%s", msg);
149
150   RETURN_LUA (l, 0);
151 } /* }}} int lua_cb_log */
152
153 static int lua_cb_register_read (lua_State *l) /* {{{ */
154 {
155   static int count = 0;
156   int nargs = lua_gettop (l); /* number of arguments */
157   clua_read_function_t *rf;
158
159   int num = count++; /* XXX FIXME: Not thread-safe! */
160   char function_name[64];
161
162   if (nargs != 1)
163   {
164     WARNING ("lua plugin: collectd_register_read() called with an invalid "
165         "number of arguments (%i).", nargs);
166     RETURN_LUA (l, -1);
167   }
168
169   /* If the argument is a string, assume it's a global function and try to look
170    * it up. */
171   if (lua_isstring (l, /* stack pos = */ 1))
172     lua_gettable (l, LUA_GLOBALSINDEX);
173
174   if (!lua_isfunction (l, /* stack pos = */ 1))
175   {
176     WARNING ("lua plugin: The first argument of collectd_register_read() "
177         "must be a function.");
178     RETURN_LUA (l, -1);
179   }
180
181   ssnprintf (function_name, sizeof (function_name), "collectd.read_func_%i", num);
182
183   /* Push the name of the global variable */
184   lua_pushstring (l, function_name);
185   /* Push the name down to the first position */
186   lua_insert (l, 1);
187   /* Now set the global variable called "collectd". */
188   lua_settable (l, LUA_REGISTRYINDEX);
189
190   rf = malloc (sizeof (*rf));
191   if (rf == NULL)
192   {
193     ERROR ("lua plugin: malloc failed.");
194     RETURN_LUA (l, -1);
195   }
196   else
197   {
198     user_data_t ud = { rf, /* free func */ NULL /* FIXME */ };
199     char cb_name[DATA_MAX_NAME_LEN];
200
201     memset (rf, 0, sizeof (*rf));
202     rf->lua_state = l;
203     rf->lua_function_name = strdup (function_name);
204
205     ssnprintf (cb_name, sizeof (cb_name), "lua/read_func_%i", num);
206
207     plugin_register_complex_read (/* group = */ "lua",
208         /* name      = */ cb_name,
209         /* callback  = */ clua_read,
210         /* interval  = */ NULL,
211         /* user_data = */ &ud);
212   }
213
214   DEBUG ("lua plugin: Successful call to lua_cb_register_read().");
215
216   RETURN_LUA (l, 0);
217 } /* }}} int lua_cb_register_read */
218
219 static lua_c_functions_t lua_c_functions[] =
220 {
221   { "collectd_log", lua_cb_log },
222   { "collectd_register_read", lua_cb_register_read }
223 };
224
225 /* Declare the Lua libraries we wish to use.
226  * Note: If you are opening and running a file containing Lua code using
227  * 'lua_dofile(l, "myfile.lua") - you must delcare all the libraries used in
228  * that file here also. */
229 static const luaL_reg lua_load_libs[] =
230 {
231   { LUA_COLIBNAME,   luaopen_base   },
232   /* { "luaopen_loadlib", luaopen_loadlib }, */
233 #if COLLECT_DEBUG
234   { LUA_DBLIBNAME,   luaopen_debug  },
235 #endif
236   { LUA_TABLIBNAME,  luaopen_table  },
237   { LUA_IOLIBNAME,   luaopen_io     },
238   { LUA_STRLIBNAME,  luaopen_string },
239   { LUA_MATHLIBNAME, luaopen_math   }
240 };
241
242 static void lua_script_free (lua_script_t *script) /* {{{ */
243 {
244   lua_script_t *next;
245
246   if (script == NULL)
247     return;
248
249   next = script->next;
250
251   if (script->lua_state != NULL)
252   {
253     lua_close (script->lua_state);
254     script->lua_state = NULL;
255   }
256
257   sfree (script->script_path);
258   sfree (script);
259
260   lua_script_free (next);
261 } /* }}} void lua_script_free */
262
263 static int lua_script_init (lua_script_t *script) /* {{{ */
264 {
265   size_t i;
266
267   memset (script, 0, sizeof (*script));
268   script->script_path = NULL;
269   script->next = NULL;
270
271   /* initialize the lua context */
272   script->lua_state = lua_open();
273   if (script->lua_state == NULL)
274   {
275     ERROR ("lua plugin: lua_open failed.");
276     return (-1);
277   }
278
279   /* Open up all the Lua libraries declared above. */
280   for (i = 0; i < STATIC_ARRAY_SIZE (lua_load_libs); i++)
281   {
282     int status;
283
284     status = (*lua_load_libs[i].func) (script->lua_state);
285     if (status != 0)
286       WARNING ("lua plugin: Loading library \"%s\" failed.",
287           lua_load_libs[i].name);
288   }
289
290   /* Register all the functions we implement in C */
291   for (i = 0; i < STATIC_ARRAY_SIZE (lua_c_functions); i++)
292     lua_register (script->lua_state,
293         lua_c_functions[i].name, lua_c_functions[i].func);
294
295   return (0);
296 } /* }}} int lua_script_init */
297
298 static int lua_script_load (const char *script_path) /* {{{ */
299 {
300   lua_script_t *script;
301   int status;
302
303   script = malloc (sizeof (*script));
304   if (script == NULL)
305   {
306     ERROR ("lua plugin: malloc failed.");
307     return (-1);
308   }
309
310   status = lua_script_init (script);
311   if (status != 0)
312   {
313     lua_script_free (script);
314     return (status);
315   }
316
317   script->script_path = strdup (script_path);
318   if (script->script_path == NULL)
319   {
320     ERROR ("lua plugin: strdup failed.");
321     lua_script_free (script);
322     return (-1);
323   }
324
325   status = lua_dofile (script->lua_state, script->script_path);
326   if (status != 0)
327   {
328     const char *errmsg;
329
330     switch (status)
331     {
332       case LUA_ERRSYNTAX: errmsg = "Syntax error"; break;
333       case LUA_ERRFILE:   errmsg = "File I/O error"; break;
334       case LUA_ERRMEM:    errmsg = "Memory allocation error"; break;
335       default:            errmsg = "Unexpected error";
336     }
337
338     ERROR ("lua plugin: Loading script \"%s\" failed: %s",
339         script->script_path, errmsg);
340
341     lua_script_free (script);
342     return (-1);
343   }
344
345   /* Append this script to the global list of scripts. */
346   if (scripts == NULL)
347   {
348     scripts = script;
349   }
350   else
351   {
352     lua_script_t *last;
353
354     last = scripts;
355     while (last->next != NULL)
356       last = last->next;
357
358     last->next = script;
359   }
360
361   return (0);
362 } /* }}} int lua_script_load */
363
364 static int lua_config_base_path (const oconfig_item_t *ci) /* {{{ */
365 {
366   int status;
367   size_t len;
368
369   status = cf_util_get_string_buffer (ci, base_path, sizeof (base_path));
370   if (status != 0)
371     return (status);
372
373   len = strlen (base_path);
374   while ((len > 0) && (base_path[len - 1] == '/'))
375   {
376     len--;
377     base_path[len] = 0;
378   }
379
380   DEBUG ("lua plugin: base_path = \"%s\";", base_path);
381
382   return (0);
383 } /* }}} int lua_config_base_path */
384
385 static int lua_config_script (const oconfig_item_t *ci) /* {{{ */
386 {
387   char rel_path[PATH_MAX + 1];
388   char abs_path[PATH_MAX + 1];
389   int status;
390
391   status = cf_util_get_string_buffer (ci, rel_path, sizeof (rel_path));
392   if (status != 0)
393     return (status);
394
395   if (base_path[0] == 0)
396     sstrncpy (abs_path, rel_path, sizeof (abs_path));
397   else
398     ssnprintf (abs_path, sizeof (abs_path), "%s/%s", base_path, rel_path);
399
400   DEBUG ("lua plugin: abs_path = \"%s\";", abs_path);
401
402   status = lua_script_load (abs_path);
403   if (status != 0)
404     return (status);
405
406   INFO("lua plugin: File \"%s\" loaded succesfully", abs_path);
407   
408   return 0;
409 } /* }}} int lua_config_script */
410
411 /*
412  * <Plugin lua>
413  *   BasePath "/"
414  *   Script "script1.lua"
415  *   Script "script2.lua"
416  * </Plugin>
417  */
418 static int lua_config (oconfig_item_t *ci) /* {{{ */
419 {
420   int i;
421
422   for (i = 0; i < ci->children_num; i++)
423   {
424     oconfig_item_t *child = ci->children + i;
425
426     if (strcasecmp ("BasePath", child->key) == 0) {
427       lua_config_base_path(child);
428     }
429     else if (strcasecmp ("Script", child->key) == 0){
430       lua_config_script(child);
431     }
432     else
433     {
434       WARNING ("network plugin: Option `%s' is not allowed here.",
435           child->key);
436     }
437   }
438   
439   return 0;
440 } /* }}} int lua_config */
441
442 static int lua_shutdown (void) /* {{{ */
443 {
444   lua_script_free (scripts);
445   scripts = NULL;
446
447   return (0);
448 } /* }}} int lua_shutdown */
449
450 void module_register()
451 {
452   plugin_register_complex_config("lua", lua_config);
453   plugin_register_shutdown("lua", lua_shutdown);
454 }
455
456 /* vim: set sw=2 sts=2 et fdm=marker : */