58c96ade6617e60c7da6f656984a5e2af31c9d76
[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 static void lua_script_free (lua_script_t *script) /* {{{ */
235 {
236   lua_script_t *next;
237
238   if (script == NULL)
239     return;
240
241   next = script->next;
242
243   if (script->lua_state != NULL)
244   {
245     lua_close (script->lua_state);
246     script->lua_state = NULL;
247   }
248
249   sfree (script->script_path);
250   sfree (script);
251
252   lua_script_free (next);
253 } /* }}} void lua_script_free */
254
255 static int lua_script_init (lua_script_t *script) /* {{{ */
256 {
257   size_t i;
258
259   memset (script, 0, sizeof (*script));
260   script->script_path = NULL;
261   script->next = NULL;
262
263   /* initialize the lua context */
264   script->lua_state = lua_open();
265   if (script->lua_state == NULL)
266   {
267     ERROR ("lua plugin: lua_open failed.");
268     return (-1);
269   }
270
271   /* Open up all the standard Lua libraries. */
272   luaL_openlibs (script->lua_state);
273
274   /* Register all the functions we implement in C */
275   for (i = 0; i < STATIC_ARRAY_SIZE (lua_c_functions); i++)
276     lua_register (script->lua_state,
277         lua_c_functions[i].name, lua_c_functions[i].func);
278
279   return (0);
280 } /* }}} int lua_script_init */
281
282 static int lua_script_load (const char *script_path) /* {{{ */
283 {
284   lua_script_t *script;
285   int status;
286
287   script = malloc (sizeof (*script));
288   if (script == NULL)
289   {
290     ERROR ("lua plugin: malloc failed.");
291     return (-1);
292   }
293
294   status = lua_script_init (script);
295   if (status != 0)
296   {
297     lua_script_free (script);
298     return (status);
299   }
300
301   script->script_path = strdup (script_path);
302   if (script->script_path == NULL)
303   {
304     ERROR ("lua plugin: strdup failed.");
305     lua_script_free (script);
306     return (-1);
307   }
308
309   status = luaL_loadfile (script->lua_state, script->script_path);
310   if (status != 0)
311   {
312     ERROR ("lua plugin: luaL_loadfile failed with status %i", status);
313     lua_script_free (script);
314     return (-1);
315   }
316
317   status = lua_pcall (script->lua_state,
318       /* nargs = */    0,
319       /* nresults = */ LUA_MULTRET,
320       /* errfunc = */  0);
321   if (status != 0)
322   {
323     const char *errmsg;
324
325     errmsg = lua_tostring (script->lua_state, /* stack pos = */ -1);
326
327     if (errmsg == NULL)
328       ERROR ("lua plugin: lua_pcall failed with status %i. "
329           "In addition, no error message could be retrieved from the stack.",
330           status);
331     else
332       ERROR ("lua plugin: Executing script \"%s\" failed:\n%s",
333           script->script_path, errmsg);
334
335     lua_script_free (script);
336     return (-1);
337   }
338
339   /* Append this script to the global list of scripts. */
340   if (scripts == NULL)
341   {
342     scripts = script;
343   }
344   else
345   {
346     lua_script_t *last;
347
348     last = scripts;
349     while (last->next != NULL)
350       last = last->next;
351
352     last->next = script;
353   }
354
355   return (0);
356 } /* }}} int lua_script_load */
357
358 static int lua_config_base_path (const oconfig_item_t *ci) /* {{{ */
359 {
360   int status;
361   size_t len;
362
363   status = cf_util_get_string_buffer (ci, base_path, sizeof (base_path));
364   if (status != 0)
365     return (status);
366
367   len = strlen (base_path);
368   while ((len > 0) && (base_path[len - 1] == '/'))
369   {
370     len--;
371     base_path[len] = 0;
372   }
373
374   DEBUG ("lua plugin: base_path = \"%s\";", base_path);
375
376   return (0);
377 } /* }}} int lua_config_base_path */
378
379 static int lua_config_script (const oconfig_item_t *ci) /* {{{ */
380 {
381   char rel_path[PATH_MAX + 1];
382   char abs_path[PATH_MAX + 1];
383   int status;
384
385   status = cf_util_get_string_buffer (ci, rel_path, sizeof (rel_path));
386   if (status != 0)
387     return (status);
388
389   if (base_path[0] == 0)
390     sstrncpy (abs_path, rel_path, sizeof (abs_path));
391   else
392     ssnprintf (abs_path, sizeof (abs_path), "%s/%s", base_path, rel_path);
393
394   DEBUG ("lua plugin: abs_path = \"%s\";", abs_path);
395
396   status = lua_script_load (abs_path);
397   if (status != 0)
398     return (status);
399
400   INFO("lua plugin: File \"%s\" loaded succesfully", abs_path);
401   
402   return 0;
403 } /* }}} int lua_config_script */
404
405 /*
406  * <Plugin lua>
407  *   BasePath "/"
408  *   Script "script1.lua"
409  *   Script "script2.lua"
410  * </Plugin>
411  */
412 static int lua_config (oconfig_item_t *ci) /* {{{ */
413 {
414   int i;
415
416   for (i = 0; i < ci->children_num; i++)
417   {
418     oconfig_item_t *child = ci->children + i;
419
420     if (strcasecmp ("BasePath", child->key) == 0) {
421       lua_config_base_path(child);
422     }
423     else if (strcasecmp ("Script", child->key) == 0){
424       lua_config_script(child);
425     }
426     else
427     {
428       WARNING ("network plugin: Option `%s' is not allowed here.",
429           child->key);
430     }
431   }
432   
433   return 0;
434 } /* }}} int lua_config */
435
436 static int lua_shutdown (void) /* {{{ */
437 {
438   lua_script_free (scripts);
439   scripts = NULL;
440
441   return (0);
442 } /* }}} int lua_shutdown */
443
444 void module_register()
445 {
446   plugin_register_complex_config("lua", lua_config);
447   plugin_register_shutdown("lua", lua_shutdown);
448 }
449
450 /* vim: set sw=2 sts=2 et fdm=marker : */