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