lua plugin: Implement write callbacks.
[collectd.git] / src / lua.c
index 294aa89..8e1534e 100644 (file)
--- a/src/lua.c
+++ b/src/lua.c
@@ -1,6 +1,7 @@
 /**
  * collectd - src/lua.c
  * Copyright (C) 2010       Julien Ammous
+ * Copyright (C) 2010       Florian Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as published by
  *
  * Authors:
  *   Julien Ammous
+ *   Florian Forster <octo at collectd.org>
  **/
 
-#include <unistd.h> // access
-
-/* Include the Lua API header files. */
-#define lua_c
-#include <lua.h>
-#include <lauxlib.h>
-#include <lualib.h>
+/* <lua5.1/luaconf.h> defines a macro using "sprintf". Although not used here,
+ * GCC will complain about the macro definition. */
+#define DONT_POISON_SPRINTF_YET
 
 #include "collectd.h"
 #include "plugin.h"
 #include "configfile.h"
 #include "utils_cache.h"
 
-#include "lua_exports.c"
+/* Include the Lua API header files. */
+#include <lua.h>
+#include <lauxlib.h>
+#include <lualib.h>
+#include "utils_lua.h"
+
+#include <pthread.h>
+
+#if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
+# undef sprintf
+# pragma GCC poison sprintf
+#endif
 
-typedef struct lua_script_s {
+struct lua_script_s;
+typedef struct lua_script_s lua_script_t;
+struct lua_script_s
+{
   char          *script_path;
   lua_State     *lua_state;
   
-  struct lua_script_s  *next;
-} lua_script_t;
+  lua_script_t  *next;
+};
+
+struct clua_callback_data_s
+{
+  lua_State *lua_state;
+  char *lua_function_name;
+  pthread_mutex_t lock;
+  int callback_id;
+};
+typedef struct clua_callback_data_s clua_callback_data_t;
+
+struct lua_c_functions_s
+{
+  char         *name;
+  lua_CFunction func;
+};
+typedef struct lua_c_functions_s lua_c_functions_t;
+
+static char           base_path[PATH_MAX + 1] = "";
+static lua_script_t  *scripts = NULL;
+
+static int clua_store_callback (lua_State *l, int idx) /* {{{ */
+{
+  static int callback_num = 0;
+  int callback_id;
+
+  /* XXX FIXME: Not thread-safe! */
+  callback_id = callback_num++;
+
+  if (idx < 0)
+    idx += lua_gettop (l) + 1;
+
+  lua_getfield (l, LUA_REGISTRYINDEX, "collectd_callbacks"); /* +1 = 1 */
+  if (!lua_istable (l, /* idx = */ -1))
+  {
+    lua_pop (l, /* nelems = */ 1); /* -1 = 0 */
+    lua_newtable (l); /* +1 = 1 */
+    lua_pushvalue (l, -1); /* +1 = 2 */
+    lua_setfield (l, LUA_REGISTRYINDEX, "collectd_callbacks"); /* -1 = 1 */
+  }
 
+  /* The table is now on top of the stack */
+  lua_pushinteger (l, (lua_Integer) callback_id); /* +1 = 2 */
 
-static char           base_path[MAXPATHLEN];
-static lua_script_t   scripts;
+  /* Copy the function pointer */
+  lua_pushvalue (l, idx); /* +1 = 3 */
+  /* Lookup function if it's a string */
+  if (lua_isstring (l, /* idx = */ -1))
+    lua_gettable (l, LUA_GLOBALSINDEX); /* +-0 = 3 */
 
+  if (!lua_isfunction (l, /* idx = */ -1))
+  {
+    lua_pop (l, /* nelems = */ 3); /* -3 = 0 */
+    return (-1);
+  }
 
+  lua_settable (l, /* idx = */ -3); /* -2 = 1 */
+  lua_pop (l, /* nelems = */ 1); /* -1 = 0 */
+  return (callback_id);
+} /* }}} int clua_store_callback */
 
-/* Declare the Lua libraries we wish to use. */
-/* Note: If you are opening and running a file containing Lua code */
-/* using 'lua_dofile(l, "myfile.lua") - you must delcare all the libraries */
-/* used in that file here also. */
-static const luaL_reg lualibs[] =
+static int clua_load_callback (lua_State *l, int callback_id) /* {{{ */
 {
-        // { "base",       luaopen_base },
-        { NULL,         NULL }
-};
+  lua_getfield (l, LUA_REGISTRYINDEX, "collectd_callbacks"); /* +1 */
+  if (!lua_istable (l, /* idx = */ -1))
+  {
+    lua_pop (l, /* nelems = */ 1); /* -1 */
+    return (-1);
+  }
+
+  lua_pushinteger (l, (lua_Integer) callback_id); /* + 1 */
+  lua_gettable (l, /* idx = */ -2); /* +-0 */
+
+  if (!lua_isfunction (l, -1))
+  {
+    lua_pop (l, /* nelems = */ 2); /* -2 */
+    return (-1);
+  }
 
-/* A function to open up all the Lua libraries you declared above. */
-static void openlualibs(lua_State *l)
+  /* Remove table */
+  lua_remove (l, /* idx = */ -2); /* -1 */
+  return (0);
+} /* }}} int clua_load_callback */
+
+static int clua_read (user_data_t *ud) /* {{{ */
 {
-  const luaL_reg *lib;
-  for( lib = lualibs; lib->func != NULL; lib++) {
-    lib->func(l);
-    lua_settop(l, 0);
+  clua_callback_data_t *cb = ud->data;
+  int status;
+
+  status = clua_load_callback (cb->lua_state, cb->callback_id);
+  if (status != 0)
+  {
+    ERROR ("lua plugin: Unable to load callback \"%s\" (id %i).",
+        cb->lua_function_name, cb->callback_id);
+    return (-1);
   }
-}
+  /* +1 */
 
+  lua_call (cb->lua_state, /* nargs = */ 0, /* nresults = */ 1); /* +1 */
 
+  if (lua_isnumber (cb->lua_state, /* idx = */ -1))
+  {
+    status = (int) lua_tointeger (cb->lua_state, /* idx = */ -1);
+  }
+  else
+  {
+    ERROR ("lua plugin: Read function \"%s\" (id %i) did not return a numeric status.",
+        cb->lua_function_name, cb->callback_id);
+    status = -1;
+  }
+  /* pop return value and function */
+  lua_settop (cb->lua_state, /* idx = */ -2); /* -2 */
 
+  return (status);
+} /* }}} int clua_read */
 
+static int clua_write (const data_set_t *ds, const value_list_t *vl, /* {{{ */
+    user_data_t *ud)
+{
+  clua_callback_data_t *cb = ud->data;
+  int status;
 
-static int lua_config_base_path (const oconfig_item_t *ci)
+  pthread_mutex_lock (&cb->lock);
+
+  status = clua_load_callback (cb->lua_state, cb->callback_id);
+  if (status != 0)
+  {
+    ERROR ("lua plugin: Unable to load callback \"%s\" (id %i).",
+        cb->lua_function_name, cb->callback_id);
+    pthread_mutex_unlock (&cb->lock);
+    return (-1);
+  }
+  /* +1 = 1 */
+
+  status = luaC_pushvaluelist (cb->lua_state, ds, vl);
+  if (status != 0)
+  {
+    lua_pop (cb->lua_state, /* nelems = */ 1); /* -1 = 0 */
+    pthread_mutex_unlock (&cb->lock);
+    ERROR ("lua plugin: luaC_pushvaluelist failed.");
+    return (-1);
+  }
+  /* +1 = 2 */
+
+  status = lua_pcall (cb->lua_state,
+      /* nargs    = */ 1,
+      /* nresults = */ 1,
+      /* errfunc  = */ 0); /* -2+1 = 1 */
+  if (status != 0)
+  {
+    const char *errmsg = lua_tostring (cb->lua_state, /* idx = */ -1);
+    if (errmsg == NULL)
+      ERROR ("lua plugin: Calling the write callback failed. "
+          "In addition, retrieving the error message failed.");
+    else
+      ERROR ("lua plugin: Calling the write callback failed:\n%s", errmsg);
+    lua_pop (cb->lua_state, /* nelems = */ 1); /* -1 = 0 */
+    pthread_mutex_unlock (&cb->lock);
+    return (-1);
+  }
+
+  if (!lua_isnumber (cb->lua_state, /* idx = */ -1))
+  {
+    ERROR ("lua plugin: Write function \"%s\" (id %i) did not return a numeric value.",
+        cb->lua_function_name, cb->callback_id);
+    status = -1;
+  }
+  else
+  {
+    status = (int) lua_tointeger (cb->lua_state, /* idx = */ -1);
+  }
+
+  lua_pop (cb->lua_state, /* nelems = */ 1); /* -1 = 0 */
+  pthread_mutex_unlock (&cb->lock);
+  return (status);
+} /* }}} int clua_write */
+
+/* Cleans up the stack, pushes the return value as a number onto the stack and
+ * returns the number of values returned (1). */
+#define RETURN_LUA(l,status) do {                    \
+  lua_State *_l_state = (l);                         \
+  lua_settop (_l_state, 0);                          \
+  lua_pushnumber (_l_state, (lua_Number) (status));  \
+  return (1);                                        \
+} while (0)
+
+/*
+ * Exported functions
+ */
+static int lua_cb_log (lua_State *l) /* {{{ */
 {
-  if( (ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING) ){
-    ERROR("lua plugin: The '%s' config option requires a single string argument", ci->key);
-    return -1;
+  int nargs = lua_gettop (l); /* number of arguments */
+  int severity;
+  const char *msg;
+
+  if (nargs != 2)
+  {
+    WARNING ("lua plugin: collectd_log() called with an invalid number of arguments (%i).",
+        nargs);
+    RETURN_LUA (l, -1);
   }
-  
-  strncpy(base_path, ci->values[0].value.string, sizeof(base_path));
-  
-  /* add ending slash if not provided */
-  if( base_path[strlen(base_path) - 1] != '/' ){
-    base_path[strlen(base_path)] = '/';
+
+  if (!lua_isnumber (l, 1))
+  {
+    WARNING ("lua plugin: The first argument to collectd_log() must be a number.");
+    RETURN_LUA (l, -1);
   }
-  
-  INFO("lua plugin: BasePath = '%s'", base_path);
-  return 0;
-}
 
-static int lua_config_script (const oconfig_item_t *ci)
+  if (!lua_isstring (l, 2))
+  {
+    WARNING ("lua plugin: The second argument to collectd_log() must be a string.");
+    RETURN_LUA (l, -1);
+  }
+
+  severity = (int) lua_tonumber (l, /* stack pos = */ 1);
+  if ((severity != LOG_ERR)
+      && (severity != LOG_WARNING)
+      && (severity != LOG_NOTICE)
+      && (severity != LOG_INFO)
+      && (severity != LOG_DEBUG))
+    severity = LOG_ERR;
+
+  msg = lua_tostring (l, 2);
+  if (msg == NULL)
+  {
+    ERROR ("lua plugin: lua_tostring failed.");
+    RETURN_LUA (l, -1);
+  }
+
+  plugin_log (severity, "%s", msg);
+
+  RETURN_LUA (l, 0);
+} /* }}} int lua_cb_log */
+
+static int lua_cb_dispatch_values (lua_State *l) /* {{{ */
 {
-  lua_script_t *script = &scripts;
-  
-  if( (ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING) ){
-    ERROR("lua plugin: The '%s' config option requires a single string argument", ci->key);
-    return -1;
+  value_list_t *vl;
+  int nargs = lua_gettop (l); /* number of arguments */
+  char identifier[6 * DATA_MAX_NAME_LEN];
+
+  if (nargs != 1)
+  {
+    WARNING ("lua plugin: collectd_dispatch_values() called "
+        "with an invalid number of arguments (%i).", nargs);
+    RETURN_LUA (l, -1);
   }
-  
-  /* find a free slot for the structure */
-  while( script->next != NULL ){
-    script = script->next;
+
+  if (!lua_istable (l, 1))
+  {
+    WARNING ("lua plugin: The first argument to collectd_dispatch_values() "
+        "must be a \"value list\" (i.e. a table).");
+    RETURN_LUA (l, -1);
   }
-  
-  /* build full path : base_path + given path + \0 */
-  script->script_path = malloc(
-      strlen(base_path) +
-      strlen(ci->values[0].value.string) + 1
-    );
-  
-  strncpy(script->script_path, base_path, sizeof(script->script_path));
-  strncpy(script->script_path + strlen(base_path), ci->values[0].value.string, sizeof(script->script_path));
-  
-  /* check if the file exists and we can read it */
-  if( access(script->script_path, R_OK) == -1 ) {
-    ERROR("lua plugin: Cannot read file '%s' : %s", script->script_path, strerror(errno));
-    free(script->script_path);
-    return -1;
+
+  vl = luaC_tovaluelist (l, /* idx = */ -1);
+  if (vl == NULL)
+  {
+    WARNING ("lua plugin: ltoc_value_list failed.");
+    RETURN_LUA (l, -1);
   }
-  
+
+  FORMAT_VL (identifier, sizeof (identifier), vl);
+
+  DEBUG ("lua plugin: collectd_dispatch_values: Received value list \"%s\", time %.3f, interval %.3f.",
+      identifier, CDTIME_T_TO_DOUBLE (vl->time), CDTIME_T_TO_DOUBLE (vl->interval));
+
+  sfree (vl->values);
+  sfree (vl);
+  RETURN_LUA (l, 0);
+} /* }}} lua_cb_dispatch_values */
+
+static int lua_cb_register_read (lua_State *l) /* {{{ */
+{
+  int nargs = lua_gettop (l); /* number of arguments */
+  clua_callback_data_t *cb;
+  user_data_t ud;
+
+  int callback_id;
+  char function_name[DATA_MAX_NAME_LEN] = "";
+
+  if (nargs != 1)
+  {
+    WARNING ("lua plugin: collectd_register_read() called with an invalid "
+        "number of arguments (%i).", nargs);
+    RETURN_LUA (l, -1);
+  }
+
+  if (lua_isstring (l, /* stack pos = */ 1))
+  {
+    const char *tmp = lua_tostring (l, /* idx = */ 1);
+    ssnprintf (function_name, sizeof (function_name), "lua/%s", tmp);
+  }
+
+  callback_id = clua_store_callback (l, /* idx = */ 1);
+  if (callback_id < 0)
+  {
+    ERROR ("lua plugin: Storing callback function failed.");
+    RETURN_LUA (l, -1);
+  }
+
+  if (function_name[0] == 0)
+    ssnprintf (function_name, sizeof (function_name), "lua/callback_%i", callback_id);
+
+  cb = malloc (sizeof (*cb));
+  if (cb == NULL)
+  {
+    ERROR ("lua plugin: malloc failed.");
+    RETURN_LUA (l, -1);
+  }
+
+  memset (cb, 0, sizeof (*cb));
+  cb->lua_state = l;
+  cb->callback_id = callback_id;
+  cb->lua_function_name = strdup (function_name);
+
+  ud.data = cb;
+  ud.free_func = NULL; /* FIXME */
+
+  plugin_register_complex_read (/* group = */ "lua",
+      /* name      = */ function_name,
+      /* callback  = */ clua_read,
+      /* interval  = */ NULL,
+      /* user_data = */ &ud);
+
+  DEBUG ("lua plugin: Successful call to lua_cb_register_read().");
+
+  RETURN_LUA (l, 0);
+} /* }}} int lua_cb_register_read */
+
+static int lua_cb_register_write (lua_State *l) /* {{{ */
+{
+  int nargs = lua_gettop (l); /* number of arguments */
+  clua_callback_data_t *cb;
+  user_data_t ud;
+
+  int callback_id;
+  char function_name[DATA_MAX_NAME_LEN] = "";
+
+  if (nargs != 1)
+  {
+    WARNING ("lua plugin: collectd_register_read() called with an invalid "
+        "number of arguments (%i).", nargs);
+    RETURN_LUA (l, -1);
+  }
+
+  if (lua_isstring (l, /* stack pos = */ 1))
+  {
+    const char *tmp = lua_tostring (l, /* idx = */ 1);
+    ssnprintf (function_name, sizeof (function_name), "lua/%s", tmp);
+  }
+
+  callback_id = clua_store_callback (l, /* idx = */ 1);
+  if (callback_id < 0)
+  {
+    ERROR ("lua plugin: Storing callback function failed.");
+    RETURN_LUA (l, -1);
+  }
+
+  if (function_name[0] == 0)
+    ssnprintf (function_name, sizeof (function_name), "lua/callback_%i", callback_id);
+
+  cb = malloc (sizeof (*cb));
+  if (cb == NULL)
+  {
+    ERROR ("lua plugin: malloc failed.");
+    RETURN_LUA (l, -1);
+  }
+
+  memset (cb, 0, sizeof (*cb));
+  cb->lua_state = l;
+  cb->callback_id = callback_id;
+  cb->lua_function_name = strdup (function_name);
+  pthread_mutex_init (&cb->lock, /* attr = */ NULL);
+
+  ud.data = cb;
+  ud.free_func = NULL; /* FIXME */
+
+  plugin_register_write (/* name = */ function_name,
+      /* callback  = */ clua_write,
+      /* user_data = */ &ud);
+
+  DEBUG ("lua plugin: Successful call to lua_cb_register_write().");
+
+  RETURN_LUA (l, 0);
+} /* }}} int lua_cb_register_write */
+
+static lua_c_functions_t lua_c_functions[] =
+{
+  { "collectd_log", lua_cb_log },
+  { "collectd_dispatch_values", lua_cb_dispatch_values },
+  { "collectd_register_read", lua_cb_register_read },
+  { "collectd_register_write", lua_cb_register_write }
+};
+
+static void lua_script_free (lua_script_t *script) /* {{{ */
+{
+  lua_script_t *next;
+
+  if (script == NULL)
+    return;
+
+  next = script->next;
+
+  if (script->lua_state != NULL)
+  {
+    lua_close (script->lua_state);
+    script->lua_state = NULL;
+  }
+
+  sfree (script->script_path);
+  sfree (script);
+
+  lua_script_free (next);
+} /* }}} void lua_script_free */
+
+static int lua_script_init (lua_script_t *script) /* {{{ */
+{
+  size_t i;
+
+  memset (script, 0, sizeof (*script));
+  script->script_path = NULL;
+  script->next = NULL;
+
   /* initialize the lua context */
   script->lua_state = lua_open();
-  
-  openlualibs(script->lua_state);
-  
-  if( register_exported_functions(script->lua_state) != 0 ) {
-    ERROR("lua plugin: Cannot register exported functions, aborting");
-    free(script->script_path);
-    return -1;
+  if (script->lua_state == NULL)
+  {
+    ERROR ("lua plugin: lua_open failed.");
+    return (-1);
   }
-  
-  /* and try to load the file */
-  if( luaL_dofile(script->lua_state, "script.lua") != 0 ) {
-    ERROR("lua plugin: error while loading '%s' => %s\n", script->script_path, lua_tostring(script->lua_state, -1));
-    free(script->script_path);
-    return -1;
+
+  /* Open up all the standard Lua libraries. */
+  luaL_openlibs (script->lua_state);
+
+  /* Register all the functions we implement in C */
+  for (i = 0; i < STATIC_ARRAY_SIZE (lua_c_functions); i++)
+    lua_register (script->lua_state,
+        lua_c_functions[i].name, lua_c_functions[i].func);
+
+  return (0);
+} /* }}} int lua_script_init */
+
+static int lua_script_load (const char *script_path) /* {{{ */
+{
+  lua_script_t *script;
+  int status;
+
+  script = malloc (sizeof (*script));
+  if (script == NULL)
+  {
+    ERROR ("lua plugin: malloc failed.");
+    return (-1);
   }
-  
-  INFO("lua plugin: file '%s' loaded succesfully", script->script_path);
+
+  status = lua_script_init (script);
+  if (status != 0)
+  {
+    lua_script_free (script);
+    return (status);
+  }
+
+  script->script_path = strdup (script_path);
+  if (script->script_path == NULL)
+  {
+    ERROR ("lua plugin: strdup failed.");
+    lua_script_free (script);
+    return (-1);
+  }
+
+  status = luaL_loadfile (script->lua_state, script->script_path);
+  if (status != 0)
+  {
+    ERROR ("lua plugin: luaL_loadfile failed with status %i", status);
+    lua_script_free (script);
+    return (-1);
+  }
+
+  status = lua_pcall (script->lua_state,
+      /* nargs = */    0,
+      /* nresults = */ LUA_MULTRET,
+      /* errfunc = */  0);
+  if (status != 0)
+  {
+    const char *errmsg;
+
+    errmsg = lua_tostring (script->lua_state, /* stack pos = */ -1);
+
+    if (errmsg == NULL)
+      ERROR ("lua plugin: lua_pcall failed with status %i. "
+          "In addition, no error message could be retrieved from the stack.",
+          status);
+    else
+      ERROR ("lua plugin: Executing script \"%s\" failed:\n%s",
+          script->script_path, errmsg);
+
+    lua_script_free (script);
+    return (-1);
+  }
+
+  /* Append this script to the global list of scripts. */
+  if (scripts == NULL)
+  {
+    scripts = script;
+  }
+  else
+  {
+    lua_script_t *last;
+
+    last = scripts;
+    while (last->next != NULL)
+      last = last->next;
+
+    last->next = script;
+  }
+
+  return (0);
+} /* }}} int lua_script_load */
+
+static int lua_config_base_path (const oconfig_item_t *ci) /* {{{ */
+{
+  int status;
+  size_t len;
+
+  status = cf_util_get_string_buffer (ci, base_path, sizeof (base_path));
+  if (status != 0)
+    return (status);
+
+  len = strlen (base_path);
+  while ((len > 0) && (base_path[len - 1] == '/'))
+  {
+    len--;
+    base_path[len] = 0;
+  }
+
+  DEBUG ("lua plugin: base_path = \"%s\";", base_path);
+
+  return (0);
+} /* }}} int lua_config_base_path */
+
+static int lua_config_script (const oconfig_item_t *ci) /* {{{ */
+{
+  char rel_path[PATH_MAX + 1];
+  char abs_path[PATH_MAX + 1];
+  int status;
+
+  status = cf_util_get_string_buffer (ci, rel_path, sizeof (rel_path));
+  if (status != 0)
+    return (status);
+
+  if (base_path[0] == 0)
+    sstrncpy (abs_path, rel_path, sizeof (abs_path));
+  else
+    ssnprintf (abs_path, sizeof (abs_path), "%s/%s", base_path, rel_path);
+
+  DEBUG ("lua plugin: abs_path = \"%s\";", abs_path);
+
+  status = lua_script_load (abs_path);
+  if (status != 0)
+    return (status);
+
+  INFO("lua plugin: File \"%s\" loaded succesfully", abs_path);
   
   return 0;
-}
+} /* }}} int lua_config_script */
 
-// <Plugin lua>
-//   BasePath /
-//   Script script1.lua
-//   Script script2.lua
-// </Plugin>
-static int lua_config(oconfig_item_t *ci)
+/*
+ * <Plugin lua>
+ *   BasePath "/"
+ *   Script "script1.lua"
+ *   Script "script2.lua"
+ * </Plugin>
+ */
+static int lua_config (oconfig_item_t *ci) /* {{{ */
 {
   int i;
 
@@ -171,20 +647,20 @@ static int lua_config(oconfig_item_t *ci)
   }
   
   return 0;
-}
+} /* }}} int lua_config */
 
-static int lua_init()
+static int lua_shutdown (void) /* {{{ */
 {
-  INFO("Lua plugin loaded.");
-  
-  return 0;
-}
+  lua_script_free (scripts);
+  scripts = NULL;
+
+  return (0);
+} /* }}} int lua_shutdown */
 
 void module_register()
 {
   plugin_register_complex_config("lua", lua_config);
-  plugin_register_init("lua", lua_init);
+  plugin_register_shutdown("lua", lua_shutdown);
 }
 
-
-
+/* vim: set sw=2 sts=2 et fdm=marker : */