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