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