提交 8d5a6ce7 authored 作者: Leon de Rooij's avatar Leon de Rooij

cleanup day

上级 ebd646b5
ENVIRONMENT_NAME= luamod
DRIVER_NAME= template
FS_ROOT = ../../../..
PREFIX= /usr/local
LUA_LIBDIR= $(PREFIX)/lib/lua/5.1
LUA_DIR= $(PREFIX)/share/lua/5.1
LIB_OPTION= -shared #for Linux
#LIB_OPTION= -bundle -undefined dynamic_lookup #for MacOS X
LIBNAME= $(DRIVER_NAME).so
#DRIVER_LIBS= -L/usr/lib64 -L/opt/freeswitch/lib
DRIVER_LIBS= -L/usr/lib64
INCS= -I/usr/include -I$(FS_ROOT)/src/mod/languages/mod_lua/lua -I $(FS_ROOT)/src/include -I$(FS_ROOT)/libs/libteletone/src
CFLAGS= -O2 -fPIC -Wall -ansi -pedantic $(INCS)
CPPFLAGS= -O2 -x c++ -fPIC -Wall -ansi -pedantic $(INCS)
CC= gcc
OBJS= luamod.o $(DRIVER_NAME).o
SRCS= luamod.h luamod.c $(DRIVER_NAME).c
AR= ar rcu
RANLIB= ranlib
#--
#lib: $(LIBNAME)
$(LIBNAME): $(OBJS)
$(CC) $(CPPFLAGS) -o $@ $(LIB_OPTION) $(OBJS) $(DRIVER_LIBS)
$(LIBNAME):
$(CC) $(CFLAGS) -o $@ $(LIB_OPTION) $(OBJS) $(DRIVER_LIBS)
install:
mkdir -p $(LUA_LIBDIR)/$(ENVIRONMENT_NAME)
cp $(LIBNAME) $(LUA_LIBDIR)/$(ENVIRONMENT_NAME)
clean:
rm -f $(LIBNAME) *.o $(COMPAT_O)
LuaMod is a simplification of the module / driver loading mechanism as written for LuaSQL.
I will try to see if I can make this template as generic as possible,
and ready for making use of the facilities provided by FreeSWITCH.
/*
** LuaMod: A simplification of the LuaSQL Module / Driver loading mechanism
** LuaSQL Credits: http://www.keplerproject.org/luasql/index.html#credits
*/
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "luamod.h"
/*
** Typical error situation
*/
LUAMOD_API int luamod_faildirect (lua_State *L, const char *err) {
lua_pushnil(L);
lua_pushstring(L, err);
return 2;
}
/*
** Return the name of the object's metatable.
** This function is used by `tostring'.
*/
static int luamod_tostring (lua_State *L) {
char buff[100];
pseudo_data *obj = (pseudo_data *)lua_touserdata (L, 1);
if (obj->closed)
strcpy (buff, "closed");
else
sprintf (buff, "%p", (void *)obj);
lua_pushfstring (L, "%s (%s)", lua_tostring(L,lua_upvalueindex(1)), buff);
return 1;
}
/*
** Create a metatable and leave it on top of the stack.
*/
LUAMOD_API int luamod_createmeta (lua_State *L, const char *name, const luaL_reg *methods) {
if (!luaL_newmetatable (L, name))
return 0;
/* define methods */
luaL_openlib (L, NULL, methods, 0);
/* define metamethods */
lua_pushliteral (L, "__gc");
lua_pushcfunction (L, methods->func);
lua_settable (L, -3);
lua_pushliteral (L, "__index");
lua_pushvalue (L, -2);
lua_settable (L, -3);
lua_pushliteral (L, "__tostring");
lua_pushstring (L, name);
lua_pushcclosure (L, luamod_tostring, 1);
lua_settable (L, -3);
lua_pushliteral (L, "__metatable");
lua_pushliteral (L, LUAMOD_PREFIX"you're not allowed to get this metatable");
lua_settable (L, -3);
return 1;
}
/*
** Define the metatable for the object on top of the stack
*/
LUAMOD_API void luamod_setmeta (lua_State *L, const char *name) {
luaL_getmetatable (L, name);
lua_setmetatable (L, -2);
}
/*
** Assumes the table is on top of the stack.
*/
LUAMOD_API void luamod_set_info (lua_State *L) {
lua_pushliteral (L, "_COPYRIGHT");
lua_pushliteral (L, "Copyright (C) 2003-2007 Kepler Project");
lua_settable (L, -3);
lua_pushliteral (L, "_DESCRIPTION");
lua_pushliteral (L, "LuaMod is an simplification of the LuaSQL module / driver implementation");
lua_settable (L, -3);
lua_pushliteral (L, "_VERSION");
lua_pushliteral (L, "LuaMod 1.0.0");
lua_settable (L, -3);
}
/*
** LuaMod: A simplification of the LuaSQL Module / Driver loading mechanism
** LuaSQL Credits: http://www.keplerproject.org/luasql/index.html#credits
*/
#ifndef _LUAMOD_
#define _LUAMOD_
#ifndef LUAMOD_API
#define LUAMOD_API
#endif
#define LUAMOD_PREFIX "LuaMod: "
#define LUAMOD_TABLENAME "luamod"
typedef struct {
short closed;
} pseudo_data;
LUAMOD_API int luamod_faildirect (lua_State *L, const char *err);
LUAMOD_API int luamod_createmeta (lua_State *L, const char *name, const luaL_reg *methods);
LUAMOD_API void luamod_setmeta (lua_State *L, const char *name);
LUAMOD_API void luamod_set_info (lua_State *L);
#endif
/*
** LuaMod: A simplification of the LuaSQL Module / Driver loading mechanism
** LuaSQL Credits: http://www.keplerproject.org/luasql/index.html#credits
*/
#include <switch.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#if defined(_WIN32)
#include <windows.h>
#endif
#include "lua.h"
#include "lauxlib.h"
#include "luamod.h"
#define DRIVER_PREFIX "Test: "
#define DRIVER_ENV "Driver Environment"
#define DRIVER_OBJ "Driver Object"
typedef struct {
short closed;
int obj_counter;
} env_t;
typedef struct {
short closed;
int env; /* reference to environment */
char *mandatory_property;
char *optional_property;
} obj_t;
LUAMOD_API int luaopen_luamod_test (lua_State *L);
/*
** Check for valid env.
*/
static env_t *get_env (lua_State *L)
{
env_t *env = (env_t *) luaL_checkudata (L, 1, DRIVER_ENV);
luaL_argcheck (L, env != NULL, 1, LUAMOD_PREFIX"env expected");
luaL_argcheck (L, !env->closed, 1, LUAMOD_PREFIX"env is closed");
return env;
}
/*
** Check for valid obj.
*/
static obj_t *get_obj (lua_State *L)
{
obj_t *obj = (obj_t *) luaL_checkudata (L, 1, DRIVER_ENV);
luaL_argcheck (L, obj != NULL, 1, LUAMOD_PREFIX"obj expected");
luaL_argcheck (L, !obj->closed, 1, LUAMOD_PREFIX"obj is closed");
return obj;
}
/*
** Pushes true and returns 1
*/
static int pass(lua_State *L)
{
lua_pushboolean (L, 1);
return 1;
}
/*
** Closes an object
*/
static int obj_close (lua_State *L)
{
env_t *env;
obj_t *obj = (obj_t *) luaL_checkudata (L,1,DRIVER_OBJ);
luaL_argcheck (L, obj != NULL, 1, LUAMOD_PREFIX"object expected");
if (obj->closed) {
lua_pushboolean (L, 0);
return 1;
}
/* Decrement objection counter on environment object */
lua_rawgeti (L, LUA_REGISTRYINDEX, obj->env);
env = (env_t *) lua_touserdata (L, -1);
env->obj_counter--;
/* Nullify structure fields. */
obj->closed = 1;
obj->mandatory_property = NULL; /* perhaps do some free'ing here if necessary */
obj->optional_property = NULL;
luaL_unref (L, LUA_REGISTRYINDEX, obj->env);
return pass(L);
}
static int obj_method (lua_State *L)
{
obj_t *obj = (obj_t *) get_obj (L);
if (strcmp(obj->mandatory_property, "the right value")) /* or do something more interesting */
return luamod_faildirect (L, LUAMOD_PREFIX"your mandatory_property doesn't have the right value");
return 1; /* ok */
}
/*
** Instantiates a new object
** Lua Input: mandatory [, optional]
** mandatory: you must supply this argument
** optional: you may leave this argument out
** Lua Returns:
** object if successfull
** nil and error message otherwise.
*/
static int env_inst_obj (lua_State *L)
{
env_t *env = (env_t *) get_env (L);
const char *mandatory = luaL_checkstring (L, 2);
const char *optional = luaL_optstring (L, 3, NULL);
obj_t *obj = (obj_t *) lua_newuserdata (L, sizeof (obj_t));
luamod_setmeta (L, DRIVER_OBJ);
obj->closed = 0;
obj->env = LUA_NOREF;
obj->mandatory_property = (char *) mandatory;
obj->optional_property = (char *) optional;
lua_pushvalue (L, 1);
obj->env = luaL_ref (L, LUA_REGISTRYINDEX);
env->obj_counter++;
return 1;
}
/*
** Closes an env object - this function is automatically called on 1st gc try
*/
static int env_close (lua_State *L)
{
env_t *env = (env_t *) luaL_checkudata (L, 1, DRIVER_ENV);
luaL_argcheck (L, env != NULL, 1, LUAMOD_PREFIX"env expected");
if (env->closed) {
lua_pushboolean (L, 0);
return 1;
}
if (env->obj_counter > 0)
return luaL_error (L, LUAMOD_PREFIX"there are open objects");
env->closed = 1;
return pass(L);
}
/*
** Create metatables for each class of object.
*/
static void create_metatables (lua_State *L)
{
struct luaL_reg env_methods[] = {
{"close", env_close},
{"obj", env_inst_obj},
{NULL, NULL},
};
struct luaL_reg obj_methods[] = {
{"close", obj_close},
{"method", obj_method},
{NULL, NULL},
};
luamod_createmeta (L, DRIVER_ENV, env_methods);
luamod_createmeta (L, DRIVER_OBJ, obj_methods);
lua_pop (L, 2); /* 2 for the amount of metatables created */
}
/*
** Creates an Environment and returns it.
*/
static int create_env (lua_State *L)
{
env_t *env;
create_metatables (L);
env = (env_t *) lua_newuserdata (L, sizeof (env_t));
luamod_setmeta (L, DRIVER_ENV);
/* fill in structure */
env->closed = 0;
env->obj_counter = 0;
return 1;
}
/*
** Creates the metatables for the objects and registers the
** driver open method.
*/
LUAMOD_API int luaopen_luamod_template (lua_State *L)
{
struct luaL_reg driver[] = {
{"my_env", create_env},
{NULL, NULL},
};
luaL_openlib (L, LUAMOD_TABLENAME, driver, 0);
luamod_set_info (L);
return 1;
}
mod_lua_dbh - a different implementation from mod_lua_luasql for accessing switch_cache_sqldb from inside Lua.
This time it's done through SWIG. Syntax is different and it has the added benefit of using callback function, so the result doesn't necessarilty have to balloon in memory. Another nicety is that the function is available from the freeswitch table, to keep it more in line with existing functions (also implementation wise).
Syntax:
local dbh = freeswitch.Dbh("dsn","user","pass")
dbh:query("select 1 as foo", function(row) stream:write("Foo = " .. row.foo) end)
-- so the anonymous function is called for each row returned
-- to get previous (mod_odbc_query or mod_lua_luasql) functionality, you can do this:
local res = {}
dbh:query("select 1 as foo", function(row) table.insert(res, row) end)
--
Just use the diff from the root of your FreeSWITCH tree. Enjoy :)
diff --git a/src/mod/languages/mod_lua/freeswitch.i b/src/mod/languages/mod_lua/freeswitch.i
index 3631aca..49db372 100644
--- a/src/mod/languages/mod_lua/freeswitch.i
+++ b/src/mod/languages/mod_lua/freeswitch.i
@@ -18,6 +18,10 @@
%}
+/* Lua function typemap */
+%typemap(in,checkfn="lua_isfunction") SWIGLUA_FN
+%{ $1.L=L; $1.idx=$input; %}
+
%ignore SwitchToMempool;
%newobject EventConsumer::pop;
@@ -25,6 +29,7 @@
%newobject CoreSession;
%newobject Event;
%newobject Stream;
+%newobject Dbh;
/**
* tell swig to grok everything defined in these header files and
@@ -66,9 +71,18 @@ class Session : public CoreSession {
void setLUA(lua_State *state);
};
-}
-
-
+class Dbh {
+ private:
+ switch_cache_db_handle_t *dbh;
+ bool connected;
+ static int query_callback(void *pArg, int argc, char **argv, char **cargv);
+ public:
+ Dbh(char *dsn, char *user = NULL, char *pass = NULL);
+ ~Dbh();
+ bool release();
+ bool query(char *sql, SWIGLUA_FN lua_fun);
+};
+}
diff --git a/src/mod/languages/mod_lua/freeswitch_lua.cpp b/src/mod/languages/mod_lua/freeswitch_lua.cpp
index c73c88c..17d12bc 100644
--- a/src/mod/languages/mod_lua/freeswitch_lua.cpp
+++ b/src/mod/languages/mod_lua/freeswitch_lua.cpp
@@ -308,3 +308,69 @@ switch_status_t Session::run_dtmf_callback(void *input, switch_input_type_t ityp
return SWITCH_STATUS_SUCCESS;
}
+
+Dbh::Dbh(char *dsn, char *user, char *pass)
+{
+ switch_cache_db_connection_options_t options = { {0} };
+
+ options.odbc_options.dsn = dsn;
+ options.odbc_options.user = user;
+ options.odbc_options.pass = pass;
+
+ if (switch_cache_db_get_db_handle(&dbh, SCDB_TYPE_ODBC, &options) == SWITCH_STATUS_SUCCESS) {
+ connected = true;
+ } else {
+ connected = false;
+ }
+}
+
+Dbh::~Dbh()
+{
+ release();
+}
+
+bool Dbh::release()
+{
+ if (connected) {
+ switch_cache_db_release_db_handle(&dbh);
+ connected = false;
+ return true;
+ }
+ return false;
+}
+
+int Dbh::query_callback(void *pArg, int argc, char **argv, char **cargv)
+{
+ SWIGLUA_FN *lua_fun = (SWIGLUA_FN *)pArg;
+
+ lua_pushvalue(lua_fun->L, lua_fun->idx); /* get the lua callback function onto the stack */
+
+ lua_newtable(lua_fun->L); /* push a row (table) */
+
+ for (int i = 0; i < argc; i++) {
+ lua_pushstring(lua_fun->L, switch_str_nil(cargv[i]));
+ lua_pushstring(lua_fun->L, switch_str_nil(argv[i]));
+ lua_settable(lua_fun->L, -3);
+ }
+
+ lua_call(lua_fun->L, 1, 1); /* 1 in, 1 out */
+
+ if (lua_isnumber(lua_fun->L, -1)) {
+ if (lua_tonumber(lua_fun->L, -1) != 0) {
+ return 1;
+ }
+ }
+
+ return 0; /* 0 to continue with next row */
+}
+
+bool Dbh::query(char *sql, SWIGLUA_FN lua_fun)
+{
+ if (connected) {
+ if (switch_cache_db_execute_sql_callback(dbh, sql, query_callback, &lua_fun, NULL) == SWITCH_STATUS_SUCCESS) {
+ return true;
+ }
+ }
+ switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "no workie workie :(\n");
+ return false;
+}
diff --git a/src/mod/languages/mod_lua/freeswitch_lua.h b/src/mod/languages/mod_lua/freeswitch_lua.h
index a1f4a85..a0780b1 100644
--- a/src/mod/languages/mod_lua/freeswitch_lua.h
+++ b/src/mod/languages/mod_lua/freeswitch_lua.h
@@ -8,6 +8,16 @@ extern "C" {
#include "mod_lua_extra.h"
}
#include <switch_cpp.h>
+
+
+typedef struct{
+ lua_State* L;
+ int idx;
+}SWIGLUA_FN;
+
+#define SWIGLUA_FN_GET(fn) {lua_pushvalue(fn.L,fn.idx);}
+
+
namespace LUA {
class Session:public CoreSession {
private:
@@ -41,5 +51,17 @@ namespace LUA {
void setLUA(lua_State * state);
};
+
+ class Dbh {
+ protected:
+ switch_cache_db_handle_t *dbh;
+ bool connected;
+ static int query_callback(void *pArg, int argc, char **argv, char **cargv);
+ public:
+ Dbh(char *dsn, char *user = NULL, char *pass = NULL);
+ ~Dbh();
+ bool release();
+ bool query(char *sql, SWIGLUA_FN lua_fun);
+ };
}
#endif
diff --git a/src/mod/languages/mod_lua/hack.diff b/src/mod/languages/mod_lua/hack.diff
index afd37b0..fc33ddb 100644
--- a/src/mod/languages/mod_lua/hack.diff
+++ b/src/mod/languages/mod_lua/hack.diff
@@ -1,38 +1,38 @@
---- mod_lua_wrap.cpp 2008-07-16 16:58:58.000000000 -0400
-+++ old.cpp 2008-07-16 16:58:42.000000000 -0400
-@@ -6731,7 +6731,7 @@
- SWIG_check_num_args("LUA::Session",0,0)
+--- mod_lua_wrap.cpp.orig 2010-09-05 16:39:26.000000000 +0200
++++ mod_lua_wrap.cpp 2010-09-05 16:39:44.000000000 +0200
+@@ -4913,7 +4913,7 @@
+
result = (LUA::Session *)new LUA::Session();
SWIG_arg=0;
- SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++;
+ SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++; result->setLUA(L);
return SWIG_arg;
- if(0) SWIG_fail;
-@@ -6759,7 +6759,7 @@
-
+ fail:
+@@ -4934,7 +4934,7 @@
+ arg2=(CoreSession *)SWIG_MustGetPtr(L,2,SWIGTYPE_p_CoreSession,0,2,"new_Session");
result = (LUA::Session *)new LUA::Session(arg1,arg2);
SWIG_arg=0;
- SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++;
+ SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++; result->setLUA(L);
return SWIG_arg;
- if(0) SWIG_fail;
-@@ -6780,7 +6780,7 @@
- arg1 = (char *)lua_tostring(L, 1);
+ fail:
+@@ -4952,7 +4952,7 @@
+ arg1 = (char*)lua_tostring(L, 1);
result = (LUA::Session *)new LUA::Session(arg1);
SWIG_arg=0;
- SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++;
+ SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++; result->setLUA(L);
return SWIG_arg;
- if(0) SWIG_fail;
-@@ -6805,7 +6805,7 @@
-
+ fail:
+@@ -4970,7 +4970,7 @@
+ arg1=(switch_core_session_t *)SWIG_MustGetPtr(L,1,SWIGTYPE_p_switch_core_session_t,0,1,"new_Session");
result = (LUA::Session *)new LUA::Session(arg1);
SWIG_arg=0;
- SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++;
+ SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++; result->setLUA(L);
return SWIG_arg;
- if(0) SWIG_fail;
+ fail:
diff --git a/src/mod/languages/mod_lua/my_swigable_cpp.h b/src/mod/languages/mod_lua/my_swigable_cpp.h
index d4d3168..ebe5972 100644
--- a/src/mod/languages/mod_lua/my_swigable_cpp.h
+++ b/src/mod/languages/mod_lua/my_swigable_cpp.h
@@ -49,6 +49,19 @@ class Event {
};
+class Dbh {
+ protected:
+ switch_cache_db_handle_t *dbh;
+ bool connected;
+ static int query_callback(void *pArg, int argc, char **argv, char **cargv);
+ public:
+ Dbh(char *dsn, char *user = NULL, char *pass = NULL);
+ ~Dbh();
+ bool release();
+ bool query(char *sql, SWIGLUA_FN lua_fun);
+};
+
+
class CoreSession {
protected:
switch_input_args_t args;
This patch includes LuaSQL with an 'scdb' driver into the mod_lua FreeSWITCH module.
Result is that it can make use of the connection pooling facilities provided by switch_core_sqldb.
Note that this version of the scdb driver does not have the following functions implemented: execute, commit, rollback, setautocommit.
This is because there is currently no support in switch_core_sqldb to get a single row from a cursor (hstmt).
I hope I can still implement this functionality soon(ish).
However, there is a new function available called exec2table, that takes an SQL statement
as argument and returns a table containing the entire result set.
To try it out, patch FreeSWITCH from the root of the source tree like this:
cd /usr/src/freeswitch
patch -p1 < contrib/ledr/c/mod_lua_luasql/mod_lua_luasql_20100828_1912.patch
The patch applies cleanly to git rev 540ee0123de4119b1df10ce752a5891248215a8b - Fri Aug 27 14:04:45 2010 -0500
Then re-build and install your mod_lua module:
make mod_lua-install
You can use it almost as how you'd use LuaSQL with ODBC driver, but you don't have to 'require' it as it's compiled into mod_lua:
-- DataDumper from here: http://lua-users.org/wiki/DataDumper --
require "DataDumper"
local env = assert(luasql.scdb())
local con = assert(env:connect("dsn", "user", "pass"))
local res = assert(con:exec2table("select * from routes"))
con:close() -- optional, connection (dbh) is automatically released
env:close() -- optional, environment is automatically closed
stream:write(DataDumper(res))
-- end of script --
And execute the script from your cli:
freeswitch@fs-dev> lua test.lua
return {
{
account_id="1",
date_end="2030-12-31 00:00:00",
date_start="1970-01-01 00:00:00",
digits="31320",
enabled="1",
id="4",
lead_strip="0",
prefix="",
quality="0.000000",
rate="0.000000",
reliability="0.000000",
suffix="",
trail_strip="0"
},
{
account_id="999",
date_end="2030-12-31 00:00:00",
date_start="1970-01-01 00:00:00",
digits="31321",
enabled="1",
id="6",
lead_strip="0",
prefix="",
quality="0.000000",
rate="0.000000",
reliability="0.000000",
suffix="",
trail_strip="0"
}
}
-- example.lua - just put this script in scripts/ and run it from you fs_cli
local env = assert(luasql.scdb()) -- same as regular luasql
local con = assert(env:connect("dsn","user","pass")) -- same as regular luasql
local res = assert(con:exec2table("select 1 as foo, 2 as bar")) -- all your rows in a single table
--[[ now res will contain this :
{
[1] = {
["foo"] = "1";
["bar"] = "2";
};
};
]]
for i = 1, table.getn(res) do -- loop through rows
for key, val in pairs(res[i]) do -- loop through columns
stream:write(string.format("%25s : %s\n", key, val))
end
stream:write("\n")
end
con:close(); -- optional, it is also closed at first gc run,
-- although it does release the dbh for re-use by another thread so can be efficient to do it early
env:close(); -- optional, (same reason) just don't close your env before closing the con !
--[[ output on your fs_cli should be :
freeswitch@internal> lua example.lua
bar : 2
foo : 1
]]
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论