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