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