lua plugin: First take at a "dispatch_values" function.
[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 static int ltoc_string_buffer (lua_State *l, /* {{{ */
115     char *buffer, size_t buffer_size,
116     _Bool consume)
117 {
118   const char *str;
119
120   str = lua_tostring (l, /* stack pos = */ -1);
121   if (str != NULL)
122     sstrncpy (buffer, str, buffer_size);
123
124   if (consume)
125     lua_pop (l, /* nelem = */ 1);
126
127   return ((str != NULL) ? 0 : -1);
128 } /* }}} int ltoc_string_buffer */
129
130 static int ltoc_table_string_buffer (lua_State *l, /* {{{ */
131     const char *table_key,
132     char *buffer, size_t buffer_size)
133 {
134   lua_pushstring (l, table_key);
135   lua_gettable (l, -2);
136
137   if (!lua_isstring (l, /* stack pos = */ -1))
138   {
139     lua_pop (l, /* nelem = */ 1);
140     return (-1);
141   }
142
143   return (ltoc_string_buffer (l, buffer, buffer_size, /* consume = */ 1));
144 } /* }}} int ltoc_table_string_buffer */
145
146 static int ltoc_table_cdtime (lua_State *l, /* {{{ */
147     const char *table_key, cdtime_t *ret_time)
148 {
149   double d;
150
151   lua_pushstring (l, table_key);
152   lua_gettable (l, -2);
153
154   if (!lua_isnumber (l, /* stack pos = */ -1))
155   {
156     lua_pop (l, /* nelem = */ 1);
157     return (-1);
158   }
159
160   d = (double) lua_tonumber (l, -1);
161   lua_pop (l, /* nelem = */ 1);
162
163   *ret_time = DOUBLE_TO_CDTIME_T (d);
164   return (0);
165 } /* }}} int ltoc_table_cdtime */
166
167 static value_list_t *ltoc_value_list (lua_State *l) /* {{{ */
168 {
169   value_list_t *vl;
170   int status;
171
172   vl = malloc (sizeof (*vl));
173   if (vl == NULL)
174     return (NULL);
175   memset (vl, 0, sizeof (*vl));
176   vl->values = NULL;
177   vl->meta = NULL;
178
179 #define COPY_FIELD(field,def) do {                                              \
180   status = ltoc_table_string_buffer (l, #field, vl->field, sizeof (vl->field)); \
181   if (status != 0) {                                                            \
182     if ((def) == NULL)                                                          \
183       return (NULL);                                                            \
184     else                                                                        \
185       sstrncpy (vl->field, (def), sizeof (vl->field));                          \
186   }                                                                             \
187 } while (0)
188
189   COPY_FIELD (host, hostname_g);
190   COPY_FIELD (plugin, NULL);
191   COPY_FIELD (plugin_instance, "");
192   COPY_FIELD (type, NULL);
193   COPY_FIELD (type_instance, "");
194
195 #undef COPY_FIELD
196
197   status = ltoc_table_cdtime (l, "time", &vl->time);
198   if (status != 0)
199     vl->time = cdtime ();
200
201   status = ltoc_table_cdtime (l, "interval", &vl->interval);
202   if (status != 0)
203     vl->interval = interval_g;
204
205   /* TODO: values */
206
207   return (vl);
208 } /* }}} value_list_t *ltoc_value_list */
209
210 /*
211  * Exported functions
212  */
213 static int lua_cb_log (lua_State *l) /* {{{ */
214 {
215   int nargs = lua_gettop (l); /* number of arguments */
216   int severity;
217   const char *msg;
218
219   if (nargs != 2)
220   {
221     WARNING ("lua plugin: collectd_log() called with an invalid number of arguments (%i).",
222         nargs);
223     RETURN_LUA (l, -1);
224   }
225
226   if (!lua_isnumber (l, 1))
227   {
228     WARNING ("lua plugin: The first argument to collectd_log() must be a number.");
229     RETURN_LUA (l, -1);
230   }
231
232   if (!lua_isstring (l, 2))
233   {
234     WARNING ("lua plugin: The second argument to collectd_log() must be a string.");
235     RETURN_LUA (l, -1);
236   }
237
238   severity = (int) lua_tonumber (l, /* stack pos = */ 1);
239   if ((severity != LOG_ERR)
240       && (severity != LOG_WARNING)
241       && (severity != LOG_NOTICE)
242       && (severity != LOG_INFO)
243       && (severity != LOG_DEBUG))
244     severity = LOG_ERR;
245
246   msg = lua_tostring (l, 2);
247   if (msg == NULL)
248   {
249     ERROR ("lua plugin: lua_tostring failed.");
250     RETURN_LUA (l, -1);
251   }
252
253   plugin_log (severity, "%s", msg);
254
255   RETURN_LUA (l, 0);
256 } /* }}} int lua_cb_log */
257
258 static int lua_cb_dispatch_values (lua_State *l) /* {{{ */
259 {
260   value_list_t *vl;
261   int nargs = lua_gettop (l); /* number of arguments */
262   char identifier[6 * DATA_MAX_NAME_LEN];
263
264   if (nargs != 1)
265   {
266     WARNING ("lua plugin: collectd_dispatch_values() called "
267         "with an invalid number of arguments (%i).", nargs);
268     RETURN_LUA (l, -1);
269   }
270
271   if (!lua_istable (l, 1))
272   {
273     WARNING ("lua plugin: The first argument to collectd_dispatch_values() "
274         "must be a table.");
275     RETURN_LUA (l, -1);
276   }
277
278   vl = ltoc_value_list (l);
279   if (vl == NULL)
280   {
281     WARNING ("lua plugin: ltoc_value_list failed.");
282     RETURN_LUA (l, -1);
283   }
284
285   FORMAT_VL (identifier, sizeof (identifier), vl);
286
287   DEBUG ("lua plugin: collectd_dispatch_values: Received value list \"%s\", time %.3f, interval %.3f.",
288       identifier, CDTIME_T_TO_DOUBLE (vl->time), CDTIME_T_TO_DOUBLE (vl->interval));
289
290   sfree (vl);
291   RETURN_LUA (l, 0);
292 } /* }}} lua_cb_dispatch_values */
293
294 static int lua_cb_register_read (lua_State *l) /* {{{ */
295 {
296   static int count = 0;
297   int nargs = lua_gettop (l); /* number of arguments */
298   clua_read_function_t *rf;
299
300   int num = count++; /* XXX FIXME: Not thread-safe! */
301   char function_name[64];
302
303   if (nargs != 1)
304   {
305     WARNING ("lua plugin: collectd_register_read() called with an invalid "
306         "number of arguments (%i).", nargs);
307     RETURN_LUA (l, -1);
308   }
309
310   /* If the argument is a string, assume it's a global function and try to look
311    * it up. */
312   if (lua_isstring (l, /* stack pos = */ 1))
313     lua_gettable (l, LUA_GLOBALSINDEX);
314
315   if (!lua_isfunction (l, /* stack pos = */ 1))
316   {
317     WARNING ("lua plugin: The first argument of collectd_register_read() "
318         "must be a function.");
319     RETURN_LUA (l, -1);
320   }
321
322   ssnprintf (function_name, sizeof (function_name), "collectd.read_func_%i", num);
323
324   /* Push the name of the global variable */
325   lua_pushstring (l, function_name);
326   /* Push the name down to the first position */
327   lua_insert (l, 1);
328   /* Now set the global variable called "collectd". */
329   lua_settable (l, LUA_REGISTRYINDEX);
330
331   rf = malloc (sizeof (*rf));
332   if (rf == NULL)
333   {
334     ERROR ("lua plugin: malloc failed.");
335     RETURN_LUA (l, -1);
336   }
337   else
338   {
339     user_data_t ud = { rf, /* free func */ NULL /* FIXME */ };
340     char cb_name[DATA_MAX_NAME_LEN];
341
342     memset (rf, 0, sizeof (*rf));
343     rf->lua_state = l;
344     rf->lua_function_name = strdup (function_name);
345
346     ssnprintf (cb_name, sizeof (cb_name), "lua/read_func_%i", num);
347
348     plugin_register_complex_read (/* group = */ "lua",
349         /* name      = */ cb_name,
350         /* callback  = */ clua_read,
351         /* interval  = */ NULL,
352         /* user_data = */ &ud);
353   }
354
355   DEBUG ("lua plugin: Successful call to lua_cb_register_read().");
356
357   RETURN_LUA (l, 0);
358 } /* }}} int lua_cb_register_read */
359
360 static lua_c_functions_t lua_c_functions[] =
361 {
362   { "collectd_log", lua_cb_log },
363   { "collectd_dispatch_values", lua_cb_dispatch_values },
364   { "collectd_register_read", lua_cb_register_read }
365 };
366
367 static void lua_script_free (lua_script_t *script) /* {{{ */
368 {
369   lua_script_t *next;
370
371   if (script == NULL)
372     return;
373
374   next = script->next;
375
376   if (script->lua_state != NULL)
377   {
378     lua_close (script->lua_state);
379     script->lua_state = NULL;
380   }
381
382   sfree (script->script_path);
383   sfree (script);
384
385   lua_script_free (next);
386 } /* }}} void lua_script_free */
387
388 static int lua_script_init (lua_script_t *script) /* {{{ */
389 {
390   size_t i;
391
392   memset (script, 0, sizeof (*script));
393   script->script_path = NULL;
394   script->next = NULL;
395
396   /* initialize the lua context */
397   script->lua_state = lua_open();
398   if (script->lua_state == NULL)
399   {
400     ERROR ("lua plugin: lua_open failed.");
401     return (-1);
402   }
403
404   /* Open up all the standard Lua libraries. */
405   luaL_openlibs (script->lua_state);
406
407   /* Register all the functions we implement in C */
408   for (i = 0; i < STATIC_ARRAY_SIZE (lua_c_functions); i++)
409     lua_register (script->lua_state,
410         lua_c_functions[i].name, lua_c_functions[i].func);
411
412   return (0);
413 } /* }}} int lua_script_init */
414
415 static int lua_script_load (const char *script_path) /* {{{ */
416 {
417   lua_script_t *script;
418   int status;
419
420   script = malloc (sizeof (*script));
421   if (script == NULL)
422   {
423     ERROR ("lua plugin: malloc failed.");
424     return (-1);
425   }
426
427   status = lua_script_init (script);
428   if (status != 0)
429   {
430     lua_script_free (script);
431     return (status);
432   }
433
434   script->script_path = strdup (script_path);
435   if (script->script_path == NULL)
436   {
437     ERROR ("lua plugin: strdup failed.");
438     lua_script_free (script);
439     return (-1);
440   }
441
442   status = luaL_loadfile (script->lua_state, script->script_path);
443   if (status != 0)
444   {
445     ERROR ("lua plugin: luaL_loadfile failed with status %i", status);
446     lua_script_free (script);
447     return (-1);
448   }
449
450   status = lua_pcall (script->lua_state,
451       /* nargs = */    0,
452       /* nresults = */ LUA_MULTRET,
453       /* errfunc = */  0);
454   if (status != 0)
455   {
456     const char *errmsg;
457
458     errmsg = lua_tostring (script->lua_state, /* stack pos = */ -1);
459
460     if (errmsg == NULL)
461       ERROR ("lua plugin: lua_pcall failed with status %i. "
462           "In addition, no error message could be retrieved from the stack.",
463           status);
464     else
465       ERROR ("lua plugin: Executing script \"%s\" failed:\n%s",
466           script->script_path, errmsg);
467
468     lua_script_free (script);
469     return (-1);
470   }
471
472   /* Append this script to the global list of scripts. */
473   if (scripts == NULL)
474   {
475     scripts = script;
476   }
477   else
478   {
479     lua_script_t *last;
480
481     last = scripts;
482     while (last->next != NULL)
483       last = last->next;
484
485     last->next = script;
486   }
487
488   return (0);
489 } /* }}} int lua_script_load */
490
491 static int lua_config_base_path (const oconfig_item_t *ci) /* {{{ */
492 {
493   int status;
494   size_t len;
495
496   status = cf_util_get_string_buffer (ci, base_path, sizeof (base_path));
497   if (status != 0)
498     return (status);
499
500   len = strlen (base_path);
501   while ((len > 0) && (base_path[len - 1] == '/'))
502   {
503     len--;
504     base_path[len] = 0;
505   }
506
507   DEBUG ("lua plugin: base_path = \"%s\";", base_path);
508
509   return (0);
510 } /* }}} int lua_config_base_path */
511
512 static int lua_config_script (const oconfig_item_t *ci) /* {{{ */
513 {
514   char rel_path[PATH_MAX + 1];
515   char abs_path[PATH_MAX + 1];
516   int status;
517
518   status = cf_util_get_string_buffer (ci, rel_path, sizeof (rel_path));
519   if (status != 0)
520     return (status);
521
522   if (base_path[0] == 0)
523     sstrncpy (abs_path, rel_path, sizeof (abs_path));
524   else
525     ssnprintf (abs_path, sizeof (abs_path), "%s/%s", base_path, rel_path);
526
527   DEBUG ("lua plugin: abs_path = \"%s\";", abs_path);
528
529   status = lua_script_load (abs_path);
530   if (status != 0)
531     return (status);
532
533   INFO("lua plugin: File \"%s\" loaded succesfully", abs_path);
534   
535   return 0;
536 } /* }}} int lua_config_script */
537
538 /*
539  * <Plugin lua>
540  *   BasePath "/"
541  *   Script "script1.lua"
542  *   Script "script2.lua"
543  * </Plugin>
544  */
545 static int lua_config (oconfig_item_t *ci) /* {{{ */
546 {
547   int i;
548
549   for (i = 0; i < ci->children_num; i++)
550   {
551     oconfig_item_t *child = ci->children + i;
552
553     if (strcasecmp ("BasePath", child->key) == 0) {
554       lua_config_base_path(child);
555     }
556     else if (strcasecmp ("Script", child->key) == 0){
557       lua_config_script(child);
558     }
559     else
560     {
561       WARNING ("network plugin: Option `%s' is not allowed here.",
562           child->key);
563     }
564   }
565   
566   return 0;
567 } /* }}} int lua_config */
568
569 static int lua_shutdown (void) /* {{{ */
570 {
571   lua_script_free (scripts);
572   scripts = NULL;
573
574   return (0);
575 } /* }}} int lua_shutdown */
576
577 void module_register()
578 {
579   plugin_register_complex_config("lua", lua_config);
580   plugin_register_shutdown("lua", lua_shutdown);
581 }
582
583 /* vim: set sw=2 sts=2 et fdm=marker : */