Forráskód Böngészése

app_python: Moved all python scripts to 'python_examples' folder.
app_python: Applied a few recent patches for better stack trace.
app_python: Fixed a possible segfault on double free.
app_python: Added python abstraction layers Router.Core, Router.Ranks, Router.Logger.
app_python: Moved all logging stuff to layer Router.Logger, e.g., Router.Logger.LM_ERR(...).
app_python: Added 'ranks' constants and moved to Router.Ranks, e.g., Router.Ranks.PROC_MAIN.

Konstantin Mosesov 12 éve
szülő
commit
230919ad2e

+ 70 - 0
modules/app_python/mod_Core.c

@@ -0,0 +1,70 @@
+/**
+ * $Id$
+ *
+ * Copyright (C) 2012 Konstantin Mosesov
+ *
+ * This file is part of Kamailio, a free SIP server.
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version
+ *
+ *
+ * This file is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ */
+
+// Python includes
+#include <Python.h>
+#include "structmember.h"
+
+// Other/system includes
+#include <libgen.h>
+
+// router includes
+#include "../../str.h"
+#include "../../sr_module.h"
+
+// local includes
+#include "python_exec.h"
+#include "python_mod.h"
+#include "python_iface.h"
+#include "python_msgobj.h"
+#include "python_support.h"
+
+#include "mod_Router.h"
+#include "mod_Core.h"
+
+PyMethodDef CoreMethods[] = {
+    {NULL, NULL, 0, NULL}
+};
+
+void init_mod_Core(void)
+{
+    core_module = Py_InitModule("Router.Core", CoreMethods);
+    PyDict_SetItemString(main_module_dict, "Core", core_module);
+
+    Py_INCREF(&core_module);
+
+#ifdef WITH_EXTRA_DEBUG
+    LM_ERR("Module 'Router.Core' has been initialized\n");
+#endif
+
+}
+
+void destroy_mod_Core(void)
+{
+    Py_XDECREF(core_module);
+#ifdef WITH_EXTRA_DEBUG
+    LM_ERR("Module 'Router.Core' has been destroyed\n");
+#endif
+
+}

+ 38 - 0
modules/app_python/mod_Core.h

@@ -0,0 +1,38 @@
+/**
+ * $Id$
+ *
+ * Copyright (C) 2012 Konstantin Mosesov
+ *
+ * This file is part of Kamailio, a free SIP server.
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version
+ *
+ *
+ * This file is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ */
+
+#ifndef	__API__MOD_CORE_H__
+#define	__API__MOD_CORE_H__
+
+#include <Python.h>
+#include <libgen.h>
+
+PyObject *core_module;
+
+extern PyMethodDef CoreMethods[];
+
+void init_mod_Core(void);
+void destroy_mod_Core(void);
+
+#endif

+ 249 - 0
modules/app_python/mod_Logger.c

@@ -0,0 +1,249 @@
+/**
+ * $Id$
+ *
+ * Copyright (C) 2012 Konstantin Mosesov
+ *
+ * This file is part of Kamailio, a free SIP server.
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version
+ *
+ *
+ * This file is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ */
+
+// Python includes
+#include <Python.h>
+#include "structmember.h"
+
+// Other/system includes
+#include <libgen.h>
+
+// router includes
+#include "../../str.h"
+#include "../../sr_module.h"
+
+// local includes
+#include "python_exec.h"
+#include "python_mod.h"
+#include "python_iface.h"
+#include "python_msgobj.h"
+#include "python_support.h"
+
+#include "mod_Router.h"
+#include "mod_Logger.h"
+
+/*
+ * Python method: LM_GEN1(self, int log_level, str msg)
+ */
+static PyObject *logger_LM_GEN1(PyObject *self, PyObject *args)
+{
+    int log_level;
+    char *msg;
+
+    if (!PyArg_ParseTuple(args, "is:LM_GEN1", &log_level, &msg))
+        return NULL;
+
+    LM_GEN1(log_level, "%s", msg);
+
+    Py_INCREF(Py_None);
+    return Py_None;
+}
+
+/*
+ * Python method: LM_GEN2(self, int log_facility, int log_level, str msg)
+ */
+static PyObject *logger_LM_GEN2(PyObject *self, PyObject *args)
+{
+    int log_facility;
+    int log_level;
+    char *msg;
+
+    if(!PyArg_ParseTuple(args, "iis:LM_GEN2", &log_facility, &log_level, &msg))
+        return NULL;
+
+    LM_GEN2(log_facility, log_level, "%s", msg);
+
+    Py_INCREF(Py_None);
+    return Py_None;
+}
+
+/*
+ * Python method: LM_ALERT(self, str msg)
+ */
+static PyObject *logger_LM_ALERT(PyObject *self, PyObject *args)
+{
+    char *msg;
+
+    if(!PyArg_ParseTuple(args, "s:LM_ALERT", &msg))
+        return NULL;
+
+    LM_ALERT("%s", msg);
+
+    Py_INCREF(Py_None);
+    return Py_None;
+}
+
+
+/*
+ * Python method: LM_CRIT(self, str msg)
+ */
+static PyObject *logger_LM_CRIT(PyObject *self, PyObject *args)
+{
+    char *msg;
+
+    if(!PyArg_ParseTuple(args, "s:LM_CRIT", &msg))
+        return NULL;
+
+    LM_CRIT("%s", msg);
+
+    Py_INCREF(Py_None);
+    return Py_None;
+}
+
+/*
+ * Python method: LM_WARN(self, str msg)
+ */
+static PyObject *logger_LM_WARN(PyObject *self, PyObject *args)
+{
+    char *msg;
+
+    if(!PyArg_ParseTuple(args, "s:LM_WARN", &msg))
+        return NULL;
+
+    LM_WARN("%s", msg);
+
+    Py_INCREF(Py_None);
+    return Py_None;
+}
+
+/*
+ * Python method: LM_NOTICE(self, str msg)
+ */
+static PyObject *logger_LM_NOTICE(PyObject *self, PyObject *args)
+{
+    char *msg;
+
+    if(!PyArg_ParseTuple(args, "s:LM_NOTICE", &msg))
+        return NULL;
+
+    LM_NOTICE("%s", msg);
+
+    Py_INCREF(Py_None);
+    return Py_None;
+}
+
+/*
+ * Python method: LM_ERR(self, str msg)
+ */
+static PyObject *logger_LM_ERR(PyObject *self, PyObject *args)
+{
+    char *msg;
+
+    if(!PyArg_ParseTuple(args, "s:LM_ERR", &msg))
+        return NULL;
+
+    LM_ERR("%s", msg);
+
+    Py_INCREF(Py_None);
+    return Py_None;
+}
+
+/*
+ * Python method: LM_INFO(self, str msg)
+ */
+static PyObject *logger_LM_INFO(PyObject *self, PyObject *args)
+{
+    char *msg;
+
+    if(!PyArg_ParseTuple(args, "s:LM_INFO", &msg))
+        return NULL;
+
+    LM_INFO("%s", msg);
+
+    Py_INCREF(Py_None);
+    return Py_None;
+}
+
+/*
+ * Python method: LM_DBG(self, str msg)
+ */
+static PyObject *logger_LM_DBG(PyObject *self, PyObject *args)
+{
+    char *msg;
+
+    if(!PyArg_ParseTuple(args, "s:LM_DBG", &msg))
+        return NULL;
+
+    LM_DBG("%s", msg);
+
+    Py_INCREF(Py_None);
+    return Py_None;
+}
+
+PyMethodDef LoggerMethods[] = {
+    {"LM_GEN1",		(PyCFunction)logger_LM_GEN1,		METH_VARARGS, "Print GEN1 message."},
+    {"LM_GEN2",		(PyCFunction)logger_LM_GEN2,		METH_VARARGS, "Print GEN2 message."},
+    {"LM_ALERT",	(PyCFunction)logger_LM_ALERT,		METH_VARARGS, "Print alert message."},
+    {"LM_CRIT",		(PyCFunction)logger_LM_CRIT,		METH_VARARGS, "Print critical message."},
+    {"LM_ERR",		(PyCFunction)logger_LM_ERR,		METH_VARARGS, "Print error message."},
+    {"LM_WARN",		(PyCFunction)logger_LM_WARN,		METH_VARARGS, "Print warning message."},
+    {"LM_NOTICE",	(PyCFunction)logger_LM_NOTICE,		METH_VARARGS, "Print notice message."},
+    {"LM_INFO",		(PyCFunction)logger_LM_INFO,		METH_VARARGS, "Print info message."},
+    {"LM_DBG",		(PyCFunction)logger_LM_DBG,		METH_VARARGS, "Print debug message."},
+    {NULL, 		NULL, 			0, 		NULL}
+};
+
+void init_mod_Logger(void)
+{
+    logger_module = Py_InitModule("Router.Logger", LoggerMethods);
+    PyDict_SetItemString(main_module_dict, "Logger", logger_module);
+
+    /*
+    * Log levels
+    * Reference: dprint.h
+    */
+    PyModule_AddObject(logger_module, "L_ALERT",  PyInt_FromLong((long)L_ALERT));
+    PyModule_AddObject(logger_module, "L_BUG",    PyInt_FromLong((long)L_BUG));
+    PyModule_AddObject(logger_module, "L_CRIT2",  PyInt_FromLong((long)L_CRIT2)); /* like L_CRIT, but adds prefix */
+    PyModule_AddObject(logger_module, "L_CRIT",   PyInt_FromLong((long)L_CRIT));  /* no prefix added */
+    PyModule_AddObject(logger_module, "L_ERR",    PyInt_FromLong((long)L_ERR));
+    PyModule_AddObject(logger_module, "L_WARN",   PyInt_FromLong((long)L_WARN));
+    PyModule_AddObject(logger_module, "L_NOTICE", PyInt_FromLong((long)L_NOTICE));
+    PyModule_AddObject(logger_module, "L_INFO",   PyInt_FromLong((long)L_INFO));
+    PyModule_AddObject(logger_module, "L_DBG",    PyInt_FromLong((long)L_DBG));
+
+    /*
+    * Facility
+    * Reference: dprint.h
+    */
+    PyModule_AddObject(logger_module, "DEFAULT_FACILITY", PyInt_FromLong((long)DEFAULT_FACILITY));
+
+    Py_INCREF(&logger_module);
+
+#ifdef WITH_EXTRA_DEBUG
+    LM_ERR("Module 'Router.Logger' has been initialized\n");
+#endif
+
+}
+
+void destroy_mod_Logger(void)
+{
+    Py_XDECREF(logger_module);
+
+#ifdef WITH_EXTRA_DEBUG
+    LM_ERR("Module 'Router.Logger' has been destroyed\n");
+#endif
+
+}
+

+ 39 - 0
modules/app_python/mod_Logger.h

@@ -0,0 +1,39 @@
+/**
+ * $Id$
+ *
+ * Copyright (C) 2012 Konstantin Mosesov
+ *
+ * This file is part of Kamailio, a free SIP server.
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version
+ *
+ *
+ * This file is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ */
+
+#ifndef	__API__MOD_LOGGER_H__
+#define	__API__MOD_LOGGER_H__
+
+#include <Python.h>
+#include <libgen.h>
+
+PyObject *logger_module;
+
+extern PyMethodDef LoggerMethods[];
+
+void init_mod_Logger(void);
+void destroy_mod_Logger(void);
+
+
+#endif

+ 85 - 0
modules/app_python/mod_Ranks.c

@@ -0,0 +1,85 @@
+/**
+ * $Id$
+ *
+ * Copyright (C) 2012 Konstantin Mosesov
+ *
+ * This file is part of Kamailio, a free SIP server.
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version
+ *
+ *
+ * This file is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ */
+
+// Python includes
+#include <Python.h>
+#include "structmember.h"
+
+// Other/system includes
+#include <libgen.h>
+
+// router includes
+#include "../../str.h"
+#include "../../sr_module.h"
+
+// local includes
+#include "python_exec.h"
+#include "python_mod.h"
+#include "python_iface.h"
+#include "python_msgobj.h"
+#include "python_support.h"
+
+#include "mod_Router.h"
+#include "mod_Ranks.h"
+
+PyMethodDef RanksMethods[] = {
+    {NULL, NULL, 0, NULL}
+};
+
+void init_mod_Ranks(void)
+{
+    ranks_module = Py_InitModule("Router.Ranks", RanksMethods);
+    PyDict_SetItemString(main_module_dict, "Ranks", ranks_module);
+
+    PyModule_AddObject(ranks_module, "PROC_MAIN",		PyInt_FromLong((long)PROC_MAIN));		
+    PyModule_AddObject(ranks_module, "PROC_TIMER",		PyInt_FromLong((long)PROC_TIMER));
+    PyModule_AddObject(ranks_module, "PROC_RPC",		PyInt_FromLong((long)PROC_RPC));
+    PyModule_AddObject(ranks_module, "PROC_FIFO",		PyInt_FromLong((long)PROC_FIFO));
+    PyModule_AddObject(ranks_module, "PROC_TCP_MAIN",		PyInt_FromLong((long)PROC_TCP_MAIN));
+    PyModule_AddObject(ranks_module, "PROC_UNIXSOCK",		PyInt_FromLong((long)PROC_UNIXSOCK));
+    PyModule_AddObject(ranks_module, "PROC_ATTENDANT",		PyInt_FromLong((long)PROC_ATTENDANT));
+    PyModule_AddObject(ranks_module, "PROC_INIT",		PyInt_FromLong((long)PROC_INIT));
+    PyModule_AddObject(ranks_module, "PROC_NOCHLDINIT",		PyInt_FromLong((long)PROC_NOCHLDINIT));
+    PyModule_AddObject(ranks_module, "PROC_SIPINIT",		PyInt_FromLong((long)PROC_SIPINIT));
+    PyModule_AddObject(ranks_module, "PROC_SIPRPC",		PyInt_FromLong((long)PROC_SIPRPC));
+    PyModule_AddObject(ranks_module, "PROC_MIN",		PyInt_FromLong((long)PROC_MIN));
+
+    Py_INCREF(&ranks_module);
+
+#ifdef WITH_EXTRA_DEBUG
+    LM_ERR("Module 'Router.Ranks' has been initialized\n");
+#endif
+
+}
+
+void destroy_mod_Ranks(void)
+{
+    Py_XDECREF(ranks_module);
+
+#ifdef WITH_EXTRA_DEBUG
+    LM_ERR("Module 'Router.Ranks' has been destroyed\n");
+#endif
+
+}
+

+ 38 - 0
modules/app_python/mod_Ranks.h

@@ -0,0 +1,38 @@
+/**
+ * $Id$
+ *
+ * Copyright (C) 2012 Konstantin Mosesov
+ *
+ * This file is part of Kamailio, a free SIP server.
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version
+ *
+ *
+ * This file is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ */
+
+#ifndef	__API__MOD_RANKS_H__
+#define	__API__MOD_RANKS_H__
+
+#include <Python.h>
+#include <libgen.h>
+
+PyObject *ranks_module;
+
+extern PyMethodDef RanksMethods[];
+
+void init_mod_Ranks(void);
+void destroy_mod_Ranks(void);
+
+#endif

+ 72 - 0
modules/app_python/mod_Router.c

@@ -0,0 +1,72 @@
+/**
+ * $Id$
+ *
+ * Copyright (C) 2012 Konstantin Mosesov
+ *
+ * This file is part of Kamailio, a free SIP server.
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version
+ *
+ *
+ * This file is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ */
+
+// Python includes
+#include <Python.h>
+#include "structmember.h"
+
+// Other/system includes
+#include <libgen.h>
+
+// router includes
+#include "../../str.h"
+#include "../../sr_module.h"
+
+// local includes
+#include "python_exec.h"
+#include "python_mod.h"
+#include "python_iface.h"
+#include "python_msgobj.h"
+#include "python_support.h"
+
+#include "mod_Router.h"
+
+
+PyMethodDef RouterMethods[] = {
+    {NULL, NULL, 0, NULL}
+};
+
+void init_mod_Router(void)
+{
+    main_module = Py_InitModule("Router", RouterMethods);
+    main_module_dict = PyModule_GetDict(main_module);
+    Py_INCREF(&main_module);
+
+#ifdef WITH_EXTRA_DEBUG
+    LM_ERR("Module 'Router' has been initialized\n");
+#endif
+
+}
+
+void destroy_mod_Router(void)
+{
+    Py_XDECREF(main_module);
+    Py_XDECREF(main_module_dict);
+
+#ifdef WITH_EXTRA_DEBUG
+    LM_ERR("Module 'Router' has been destroyed\n");
+#endif
+
+}
+

+ 39 - 0
modules/app_python/mod_Router.h

@@ -0,0 +1,39 @@
+/**
+ * $Id$
+ *
+ * Copyright (C) 2012 Konstantin Mosesov
+ *
+ * This file is part of Kamailio, a free SIP server.
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version
+ *
+ *
+ * This file is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ */
+
+#ifndef	__API__MOD_ROUTER_H__
+#define	__API__MOD_ROUTER_H__
+
+#include <Python.h>
+#include <libgen.h>
+
+PyObject *main_module;
+PyObject *main_module_dict;
+
+extern PyMethodDef RouterMethods[];
+
+void init_mod_Router(void);
+void destroy_mod_Router(void);
+
+#endif

+ 0 - 0
modules/app_python/Loggers.py → modules/app_python/python_examples/Loggers.py


+ 0 - 0
modules/app_python/TestCase_Traceback.py → modules/app_python/python_examples/TestCase_Traceback.py


+ 0 - 0
modules/app_python/handler.py → modules/app_python/python_examples/handler.py


+ 21 - 184
modules/app_python/python_iface.c

@@ -20,199 +20,36 @@
  *
  *
 */
 */
 
 
+/*
+ * Changed
+ *	2012-12-10 ez: Moved a part of functional to mod_Core.c, mod_Logger.c, mod_Ranks.c, mod_Router.c
+ *
+*/
+
+// Python includes
 #include <Python.h>
 #include <Python.h>
 
 
+// router includes
 #include "../../action.h"
 #include "../../action.h"
 #include "../../dprint.h"
 #include "../../dprint.h"
 #include "../../route_struct.h"
 #include "../../route_struct.h"
-#include "python_exec.h"
-
-
-/*
- * Python method: LM_GEN1(self, int log_level, str msg)
- */
-static PyObject *router_LM_GEN1(PyObject *self, PyObject *args)
-{
-    int log_level;
-    char *msg;
-
-    if (!PyArg_ParseTuple(args, "is:LM_GEN1", &log_level, &msg))
-        return NULL;
-
-    LM_GEN1(log_level, "%s", msg);
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-/*
- * Python method: LM_GEN2(self, int log_facility, int log_level, str msg)
- */
-static PyObject *router_LM_GEN2(PyObject *self, PyObject *args)
-{
-    int log_facility;
-    int log_level;
-    char *msg;
-
-    if(!PyArg_ParseTuple(args, "iis:LM_GEN2", &log_facility, &log_level, &msg))
-        return NULL;
-
-    LM_GEN2(log_facility, log_level, "%s", msg);
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-/*
- * Python method: LM_ALERT(self, str msg)
- */
-static PyObject *router_LM_ALERT(PyObject *self, PyObject *args)
-{
-    char *msg;
-
-    if(!PyArg_ParseTuple(args, "s:LM_ALERT", &msg))
-        return NULL;
-
-    LM_ALERT("%s", msg);
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-
-/*
- * Python method: LM_CRIT(self, str msg)
- */
-static PyObject *router_LM_CRIT(PyObject *self, PyObject *args)
-{
-    char *msg;
-
-    if(!PyArg_ParseTuple(args, "s:LM_CRIT", &msg))
-        return NULL;
-
-    LM_CRIT("%s", msg);
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-/*
- * Python method: LM_WARN(self, str msg)
- */
-static PyObject *router_LM_WARN(PyObject *self, PyObject *args)
-{
-    char *msg;
-
-    if(!PyArg_ParseTuple(args, "s:LM_WARN", &msg))
-        return NULL;
-
-    LM_WARN("%s", msg);
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-/*
- * Python method: LM_NOTICE(self, str msg)
- */
-static PyObject *router_LM_NOTICE(PyObject *self, PyObject *args)
-{
-    char *msg;
+#include "../../str.h"
+#include "../../sr_module.h"
 
 
-    if(!PyArg_ParseTuple(args, "s:LM_NOTICE", &msg))
-        return NULL;
+// local includes
+#include "mod_Router.h"
+#include "mod_Core.h"
+#include "mod_Ranks.h"
+#include "mod_Logger.h"
 
 
-    LM_NOTICE("%s", msg);
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-/*
- * Python method: LM_ERR(self, str msg)
- */
-static PyObject *router_LM_ERR(PyObject *self, PyObject *args)
-{
-    char *msg;
-
-    if(!PyArg_ParseTuple(args, "s:LM_ERR", &msg))
-        return NULL;
-
-    LM_ERR("%s", msg);
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
 
 
-/*
- * Python method: LM_INFO(self, str msg)
- */
-static PyObject *router_LM_INFO(PyObject *self, PyObject *args)
-{
-    char *msg;
-
-    if(!PyArg_ParseTuple(args, "s:LM_INFO", &msg))
-        return NULL;
-
-    LM_INFO("%s", msg);
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-/*
- * Python method: LM_DBG(self, str msg)
- */
-static PyObject *router_LM_DBG(PyObject *self, PyObject *args)
-{
-    char *msg;
-
-    if(!PyArg_ParseTuple(args, "s:LM_DBG", &msg))
-        return NULL;
-
-    LM_DBG("%s", msg);
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-
-PyMethodDef RouterMethods[] = {
-    {"LM_GEN1",		router_LM_GEN1,		METH_VARARGS, "Print GEN1 message."},
-    {"LM_GEN2",		router_LM_GEN2,		METH_VARARGS, "Print GEN2 message."},
-    {"LM_ALERT",	router_LM_ALERT,	METH_VARARGS, "Print alert message."},
-    {"LM_CRIT",		router_LM_CRIT,		METH_VARARGS, "Print critical message."},
-    {"LM_ERR",		router_LM_ERR,		METH_VARARGS, "Print error message."},
-    {"LM_WARN",		router_LM_WARN,		METH_VARARGS, "Print warning message."},
-    {"LM_NOTICE",	router_LM_NOTICE,	METH_VARARGS, "Print notice message."},
-    {"LM_INFO",		router_LM_INFO,		METH_VARARGS, "Print info message."},
-    {"LM_DBG",		router_LM_DBG,		METH_VARARGS, "Print debug message."},
-    {NULL, 		NULL, 			0, 		NULL}
-};
-
-/*
- * Default module properties
- */
-void RouterAddProperties(PyObject *m)
+int init_modules(void)
 {
 {
-    /*
-    * Log levels
-    * Reference: dprint.h
-    */
-    PyModule_AddObject(m, "L_ALERT",  PyInt_FromLong((long)L_ALERT));
-    PyModule_AddObject(m, "L_BUG",    PyInt_FromLong((long)L_BUG));
-    PyModule_AddObject(m, "L_CRIT2",  PyInt_FromLong((long)L_CRIT2)); /* like L_CRIT, but adds prefix */
-    PyModule_AddObject(m, "L_CRIT",   PyInt_FromLong((long)L_CRIT));  /* no prefix added */
-    PyModule_AddObject(m, "L_ERR",    PyInt_FromLong((long)L_ERR));
-    PyModule_AddObject(m, "L_WARN",   PyInt_FromLong((long)L_WARN));
-    PyModule_AddObject(m, "L_NOTICE", PyInt_FromLong((long)L_NOTICE));
-    PyModule_AddObject(m, "L_INFO",   PyInt_FromLong((long)L_INFO));
-    PyModule_AddObject(m, "L_DBG",    PyInt_FromLong((long)L_DBG));
+    init_mod_Router();
+    init_mod_Core();
+    init_mod_Ranks();
+    init_mod_Logger();
 
 
-    /*
-    * Facility
-    * Reference: dprint.h
-    */
-    PyModule_AddObject(m, "DEFAULT_FACILITY", PyInt_FromLong((long)DEFAULT_FACILITY));
+    return 0;
 }
 }
 
 

+ 1 - 1
modules/app_python/python_iface.h

@@ -26,6 +26,6 @@
 #include <Python.h>
 #include <Python.h>
 
 
 extern PyMethodDef RouterMethods[];
 extern PyMethodDef RouterMethods[];
-void RouterAddProperties(PyObject *);
+int init_modules(void);
 
 
 #endif
 #endif

+ 156 - 56
modules/app_python/python_mod.c

@@ -30,18 +30,27 @@
 #include "python_iface.h"
 #include "python_iface.h"
 #include "python_msgobj.h"
 #include "python_msgobj.h"
 #include "python_support.h"
 #include "python_support.h"
+#include "python_mod.h"
+
+#include "mod_Router.h"
+#include "mod_Core.h"
+#include "mod_Ranks.h"
+#include "mod_Logger.h"
 
 
 MODULE_VERSION
 MODULE_VERSION
 
 
-static int mod_init(void);
-static int child_init(int rank);
-static void mod_destroy(void);
 
 
 static str script_name = {.s = "/usr/local/etc/sip-router/handler.py", .len = 0};
 static str script_name = {.s = "/usr/local/etc/sip-router/handler.py", .len = 0};
 static str mod_init_fname = { .s = "mod_init", .len = 0};
 static str mod_init_fname = { .s = "mod_init", .len = 0};
 static str child_init_mname = { .s = "child_init", .len = 0};
 static str child_init_mname = { .s = "child_init", .len = 0};
+
+static int mod_init(void);
+static int child_init(int rank);
+static void mod_destroy(void);
+
 PyObject *handler_obj;
 PyObject *handler_obj;
-PyObject *format_exc_obj;
+
+char *dname = NULL, *bname = NULL;
 
 
 PyThreadState *myThreadState;
 PyThreadState *myThreadState;
 
 
@@ -57,12 +66,8 @@ static param_export_t params[]={
  * Exported functions
  * Exported functions
  */
  */
 static cmd_export_t cmds[] = {
 static cmd_export_t cmds[] = {
-    { "python_exec", (cmd_function)python_exec1, 1,  NULL, 0,
-      REQUEST_ROUTE | FAILURE_ROUTE
-      | ONREPLY_ROUTE | BRANCH_ROUTE },
-    { "python_exec", (cmd_function)python_exec2, 2,  NULL, 0,
-      REQUEST_ROUTE | FAILURE_ROUTE
-      | ONREPLY_ROUTE | BRANCH_ROUTE },
+    { "python_exec", (cmd_function)python_exec1, 1,  NULL, 0,	REQUEST_ROUTE | FAILURE_ROUTE  | ONREPLY_ROUTE | BRANCH_ROUTE },
+    { "python_exec", (cmd_function)python_exec2, 2,  NULL, 0,	REQUEST_ROUTE | FAILURE_ROUTE  | ONREPLY_ROUTE | BRANCH_ROUTE },
     { 0, 0, 0, 0, 0, 0 }
     { 0, 0, 0, 0, 0, 0 }
 };
 };
 
 
@@ -84,9 +89,10 @@ struct module_exports exports = {
 
 
 static int mod_init(void)
 static int mod_init(void)
 {
 {
-    char *dname, *bname, *dname_src, *bname_src;
+    char *dname_src, *bname_src;
+
     int i;
     int i;
-    PyObject *sys_path, *pDir, *pModule, *pFunc, *pArgs, *m;
+    PyObject *sys_path, *pDir, *pModule, *pFunc, *pArgs;
     PyThreadState *mainThreadState;
     PyThreadState *mainThreadState;
 
 
     if (script_name.len == 0) {
     if (script_name.len == 0) {
@@ -101,16 +107,17 @@ static int mod_init(void)
 
 
     dname_src = as_asciiz(&script_name);
     dname_src = as_asciiz(&script_name);
     bname_src = as_asciiz(&script_name);
     bname_src = as_asciiz(&script_name);
+
     if(dname_src==NULL || bname_src==NULL)
     if(dname_src==NULL || bname_src==NULL)
     {
     {
-            LM_ERR("no more pkg memory\n");
-            return -1;
+        LM_ERR("no more pkg memory\n");
+        return -1;
     }
     }
 
 
-    dname = dirname(dname_src);
+    dname = strdup(dirname(dname_src));
     if (strlen(dname) == 0)
     if (strlen(dname) == 0)
         dname = ".";
         dname = ".";
-    bname = basename(bname_src);
+    bname = strdup(basename(bname_src));
     i = strlen(bname);
     i = strlen(bname);
     if (bname[i - 1] == 'c' || bname[i - 1] == 'o')
     if (bname[i - 1] == 'c' || bname[i - 1] == 'o')
         i -= 1;
         i -= 1;
@@ -126,36 +133,63 @@ static int mod_init(void)
     PyEval_InitThreads();
     PyEval_InitThreads();
     mainThreadState = PyThreadState_Get();
     mainThreadState = PyThreadState_Get();
 
 
-    m = Py_InitModule("Router", RouterMethods);
+    format_exc_obj = InitTracebackModule();
 
 
-    if (python_msgobj_init() != 0) {
-        LM_ERR("python_msgobj_init() has failed\n");
+    if (format_exc_obj == NULL || !PyCallable_Check(format_exc_obj))
+    {
+        Py_XDECREF(format_exc_obj);
         PyEval_ReleaseLock();
         PyEval_ReleaseLock();
         return -1;
         return -1;
     }
     }
 
 
-    RouterAddProperties(m);
-
     sys_path = PySys_GetObject("path");
     sys_path = PySys_GetObject("path");
     /* PySys_GetObject doesn't pass reference! No need to DEREF */
     /* PySys_GetObject doesn't pass reference! No need to DEREF */
     if (sys_path == NULL) {
     if (sys_path == NULL) {
-        LM_ERR("cannot import sys.path\n");
+	if (!PyErr_Occurred())
+	    PyErr_Format(PyExc_AttributeError, "'module' object 'sys' has no attribute 'path'");
+	python_handle_exception("mod_init");
+	Py_DECREF(format_exc_obj);
         PyEval_ReleaseLock();
         PyEval_ReleaseLock();
         return -1;
         return -1;
     }
     }
 
 
     pDir = PyString_FromString(dname);
     pDir = PyString_FromString(dname);
     if (pDir == NULL) {
     if (pDir == NULL) {
-        LM_ERR("PyString_FromString() has filed\n");
+	if (!PyErr_Occurred())
+	    PyErr_Format(PyExc_AttributeError, "PyString_FromString() has failed");
+	python_handle_exception("mod_init");
+	Py_DECREF(format_exc_obj);
         PyEval_ReleaseLock();
         PyEval_ReleaseLock();
         return -1;
         return -1;
     }
     }
+
     PyList_Insert(sys_path, 0, pDir);
     PyList_Insert(sys_path, 0, pDir);
     Py_DECREF(pDir);
     Py_DECREF(pDir);
 
 
+    if (init_modules() != 0) {
+	if (!PyErr_Occurred())
+	    PyErr_SetString(PyExc_AttributeError, "init_modules() has failed");
+	python_handle_exception("mod_init");
+	Py_DECREF(format_exc_obj);
+        PyEval_ReleaseLock();
+        return -1;
+    }
+
+    if (python_msgobj_init() != 0) {
+	if (!PyErr_Occurred())
+	    PyErr_SetString(PyExc_AttributeError, "python_msgobj_init() has failed");
+	python_handle_exception("mod_init");
+	Py_DECREF(format_exc_obj);
+        PyEval_ReleaseLock();
+        return -1;
+    }
+
     pModule = PyImport_ImportModule(bname);
     pModule = PyImport_ImportModule(bname);
     if (pModule == NULL) {
     if (pModule == NULL) {
-        LM_ERR("cannot import %s\n", bname);
+	if (!PyErr_Occurred())
+	    PyErr_Format(PyExc_ImportError, "No module named '%s'", bname);
+	python_handle_exception("mod_init");
+	Py_DECREF(format_exc_obj);
         PyEval_ReleaseLock();
         PyEval_ReleaseLock();
         return -1;
         return -1;
     }
     }
@@ -165,46 +199,52 @@ static int mod_init(void)
 
 
     pFunc = PyObject_GetAttrString(pModule, mod_init_fname.s);
     pFunc = PyObject_GetAttrString(pModule, mod_init_fname.s);
     Py_DECREF(pModule);
     Py_DECREF(pModule);
+
     /* pFunc is a new reference */
     /* pFunc is a new reference */
-    if (pFunc == NULL || !PyCallable_Check(pFunc)) {
-        LM_ERR("cannot locate %s function in %s module\n",
-          mod_init_fname.s, script_name.s);
+
+    if (pFunc == NULL) {
+	if (!PyErr_Occurred())
+	    PyErr_Format(PyExc_AttributeError, "'module' object '%s' has no attribute '%s'",  bname, mod_init_fname.s);
+	python_handle_exception("mod_init");
+	Py_DECREF(format_exc_obj);
         Py_XDECREF(pFunc);
         Py_XDECREF(pFunc);
         PyEval_ReleaseLock();
         PyEval_ReleaseLock();
         return -1;
         return -1;
     }
     }
 
 
-    pModule = PyImport_ImportModule("traceback");
-    if (pModule == NULL) {
-        LM_ERR("cannot import traceback module\n");
-        Py_DECREF(pFunc);
+    if (!PyCallable_Check(pFunc)) {
+	if (!PyErr_Occurred())
+	    PyErr_Format(PyExc_AttributeError, "module object '%s' has is not callable attribute '%s'", bname, mod_init_fname.s);
+	python_handle_exception("mod_init");
+	Py_DECREF(format_exc_obj);
+        Py_XDECREF(pFunc);
         PyEval_ReleaseLock();
         PyEval_ReleaseLock();
         return -1;
         return -1;
     }
     }
 
 
-    format_exc_obj = PyObject_GetAttrString(pModule, "format_exception");
-    Py_DECREF(pModule);
-    if (format_exc_obj == NULL || !PyCallable_Check(format_exc_obj)) {
-        LM_ERR("cannot locate format_exception function in" \
-          " traceback module\n");
-        Py_XDECREF(format_exc_obj);
-        Py_DECREF(pFunc);
-        PyEval_ReleaseLock();
-        return -1;
-    }
 
 
     pArgs = PyTuple_New(0);
     pArgs = PyTuple_New(0);
     if (pArgs == NULL) {
     if (pArgs == NULL) {
-        LM_ERR("PyTuple_New() has failed\n");
-        Py_DECREF(pFunc);
+	python_handle_exception("mod_init");
         Py_DECREF(format_exc_obj);
         Py_DECREF(format_exc_obj);
+        Py_DECREF(pFunc);
         PyEval_ReleaseLock();
         PyEval_ReleaseLock();
         return -1;
         return -1;
     }
     }
 
 
     handler_obj = PyObject_CallObject(pFunc, pArgs);
     handler_obj = PyObject_CallObject(pFunc, pArgs);
-    Py_DECREF(pFunc);
-    Py_DECREF(pArgs);
+
+    Py_XDECREF(pFunc);
+    Py_XDECREF(pArgs);
+
+    if (handler_obj == Py_None) {
+	if (!PyErr_Occurred())
+	    PyErr_Format(PyExc_TypeError, "Function '%s' of module '%s' has returned None. Should be a class instance.", mod_init_fname.s, bname);
+	python_handle_exception("mod_init");
+        Py_DECREF(format_exc_obj);
+        PyEval_ReleaseLock();
+        return -1;
+    }
 
 
     if (PyErr_Occurred()) {
     if (PyErr_Occurred()) {
         python_handle_exception("mod_init");
         python_handle_exception("mod_init");
@@ -215,8 +255,10 @@ static int mod_init(void)
     }
     }
 
 
     if (handler_obj == NULL) {
     if (handler_obj == NULL) {
-        LM_ERR("%s function has not returned object\n",
-          mod_init_fname.s);
+        LM_ERR("PyObject_CallObject() returned NULL but no exception!\n");
+	if (!PyErr_Occurred())
+	    PyErr_Format(PyExc_TypeError, "Function '%s' of module '%s' has returned not returned object. Should be a class instance.", mod_init_fname.s, bname);
+	python_handle_exception("mod_init");
         Py_DECREF(format_exc_obj);
         Py_DECREF(format_exc_obj);
         PyEval_ReleaseLock();
         PyEval_ReleaseLock();
         return -1;
         return -1;
@@ -232,16 +274,43 @@ static int child_init(int rank)
 {
 {
     PyObject *pFunc, *pArgs, *pValue, *pResult;
     PyObject *pFunc, *pArgs, *pValue, *pResult;
     int rval;
     int rval;
+    char *classname;
 
 
     PyEval_AcquireLock();
     PyEval_AcquireLock();
     PyThreadState_Swap(myThreadState);
     PyThreadState_Swap(myThreadState);
 
 
+    // get instance class name
+    classname = get_instance_class_name(handler_obj);
+    if (classname == NULL)
+    {
+	if (!PyErr_Occurred())
+	    PyErr_Format(PyExc_AttributeError, "'module' instance has no class name");
+	python_handle_exception("child_init");
+	Py_DECREF(format_exc_obj);
+	Py_XDECREF(classname);
+	PyThreadState_Swap(NULL);
+	PyEval_ReleaseLock();
+	return -1;
+    }
+
     pFunc = PyObject_GetAttrString(handler_obj, child_init_mname.s);
     pFunc = PyObject_GetAttrString(handler_obj, child_init_mname.s);
-    if (pFunc == NULL || !PyCallable_Check(pFunc)) {
-        LM_ERR("cannot locate %s function\n", child_init_mname.s);
-        if (pFunc != NULL) {
-            Py_DECREF(pFunc);
-        }
+
+    if (pFunc == NULL) {
+	python_handle_exception("child_init");
+	Py_XDECREF(pFunc);
+	Py_DECREF(format_exc_obj);
+        PyThreadState_Swap(NULL);
+        PyEval_ReleaseLock();
+        return -1;
+    }
+
+    if (!PyCallable_Check(pFunc)) {
+	if (!PyErr_Occurred())
+	    PyErr_Format(PyExc_AttributeError, "class object '%s' has is not callable attribute '%s'", !classname ? "None" : classname, mod_init_fname.s);
+	python_handle_exception("child_init");
+	Py_DECREF(format_exc_obj);
+	Py_XDECREF(classname);
+	Py_XDECREF(pFunc);
         PyThreadState_Swap(NULL);
         PyThreadState_Swap(NULL);
         PyEval_ReleaseLock();
         PyEval_ReleaseLock();
         return -1;
         return -1;
@@ -249,16 +318,19 @@ static int child_init(int rank)
 
 
     pArgs = PyTuple_New(1);
     pArgs = PyTuple_New(1);
     if (pArgs == NULL) {
     if (pArgs == NULL) {
-        LM_ERR("PyTuple_New() has failed\n");
+	python_handle_exception("child_init");
+	Py_DECREF(format_exc_obj);
+	Py_XDECREF(classname);
         Py_DECREF(pFunc);
         Py_DECREF(pFunc);
         PyThreadState_Swap(NULL);
         PyThreadState_Swap(NULL);
         PyEval_ReleaseLock();
         PyEval_ReleaseLock();
         return -1;
         return -1;
     }
     }
 
 
-    pValue = PyInt_FromLong(rank);
+    pValue = PyInt_FromLong((long)rank);
     if (pValue == NULL) {
     if (pValue == NULL) {
-        LM_ERR("PyInt_FromLong() has failed\n");
+	python_handle_exception("child_init");
+	Py_DECREF(format_exc_obj);
         Py_DECREF(pArgs);
         Py_DECREF(pArgs);
         Py_DECREF(pFunc);
         Py_DECREF(pFunc);
         PyThreadState_Swap(NULL);
         PyThreadState_Swap(NULL);
@@ -272,8 +344,12 @@ static int child_init(int rank)
     Py_DECREF(pFunc);
     Py_DECREF(pFunc);
     Py_DECREF(pArgs);
     Py_DECREF(pArgs);
 
 
+    
+
+
     if (PyErr_Occurred()) {
     if (PyErr_Occurred()) {
         python_handle_exception("child_init");
         python_handle_exception("child_init");
+	Py_DECREF(format_exc_obj);
         Py_XDECREF(pResult);
         Py_XDECREF(pResult);
         PyThreadState_Swap(NULL);
         PyThreadState_Swap(NULL);
         PyEval_ReleaseLock();
         PyEval_ReleaseLock();
@@ -287,14 +363,38 @@ static int child_init(int rank)
         return -1;
         return -1;
     }
     }
 
 
+    if (!PyInt_Check(pResult))
+    {
+	if (!PyErr_Occurred())
+	    PyErr_Format(PyExc_TypeError, "method '%s' of class '%s' should return 'int' type", child_init_mname.s, !classname ? "None" : classname);
+	python_handle_exception("child_init");
+	Py_DECREF(format_exc_obj);
+	Py_XDECREF(pResult);
+	Py_XDECREF(classname);
+	PyThreadState_Swap(NULL);
+	PyEval_ReleaseLock();
+	return -1;
+    }
+
+
     rval = PyInt_AsLong(pResult);
     rval = PyInt_AsLong(pResult);
     Py_DECREF(pResult);
     Py_DECREF(pResult);
+    Py_XDECREF(classname);
     PyThreadState_Swap(NULL);
     PyThreadState_Swap(NULL);
     PyEval_ReleaseLock();
     PyEval_ReleaseLock();
+
     return rval;
     return rval;
 }
 }
 
 
 static void mod_destroy(void)
 static void mod_destroy(void)
 {
 {
-    return;
+    if (dname)
+	free(dname);	// dname was strdup'ed
+    if (bname)
+	free(bname);	// bname was strdup'ed
+
+    destroy_mod_Core();
+    destroy_mod_Ranks();
+    destroy_mod_Logger();
+    destroy_mod_Router();
 }
 }

+ 44 - 80
modules/app_python/python_msgobj.c

@@ -39,8 +39,7 @@ static PyTypeObject MSGtype;
 
 
 #define is_msgobject(v)         ((v)->ob_type == &MSGtype)
 #define is_msgobject(v)         ((v)->ob_type == &MSGtype)
 
 
-msgobject *
-newmsgobject(struct sip_msg *msg)
+msgobject *newmsgobject(struct sip_msg *msg)
 {
 {
     msgobject *msgp;
     msgobject *msgp;
 
 
@@ -52,22 +51,17 @@ newmsgobject(struct sip_msg *msg)
     return msgp;
     return msgp;
 }
 }
 
 
-void
-msg_invalidate(msgobject *self)
+void msg_invalidate(msgobject *self)
 {
 {
-
     self->msg = NULL;
     self->msg = NULL;
 }
 }
 
 
-static void
-msg_dealloc(msgobject *msgp)
+static void msg_dealloc(msgobject *msgp)
 {
 {
-
     PyObject_Del(msgp);
     PyObject_Del(msgp);
 }
 }
 
 
-static PyObject *
-msg_copy(msgobject *self)
+static PyObject *msg_copy(msgobject *self)
 {
 {
     msgobject *msgp;
     msgobject *msgp;
 
 
@@ -77,8 +71,7 @@ msg_copy(msgobject *self)
     return (PyObject *)msgp;
     return (PyObject *)msgp;
 }
 }
 
 
-static PyObject *
-msg_rewrite_ruri(msgobject *self, PyObject *args)
+static PyObject *msg_rewrite_ruri(msgobject *self, PyObject *args)
 {
 {
     char *ruri;
     char *ruri;
     struct action act;
     struct action act;
@@ -91,8 +84,7 @@ msg_rewrite_ruri(msgobject *self, PyObject *args)
     }
     }
 
 
     if ((self->msg->first_line).type != SIP_REQUEST) {
     if ((self->msg->first_line).type != SIP_REQUEST) {
-        PyErr_SetString(PyExc_RuntimeError, "Not a request message - "
-          "rewrite is not possible.\n");
+        PyErr_SetString(PyExc_RuntimeError, "Not a request message - rewrite is not possible.\n");
         Py_INCREF(Py_None);
         Py_INCREF(Py_None);
         return Py_None;
         return Py_None;
     }
     }
@@ -117,8 +109,7 @@ msg_rewrite_ruri(msgobject *self, PyObject *args)
     return Py_None;
     return Py_None;
 }
 }
 
 
-static PyObject *
-msg_set_dst_uri(msgobject *self, PyObject *args)
+static PyObject *msg_set_dst_uri(msgobject *self, PyObject *args)
 {
 {
     str ruri;
     str ruri;
 
 
@@ -129,8 +120,7 @@ msg_set_dst_uri(msgobject *self, PyObject *args)
     }
     }
 
 
     if ((self->msg->first_line).type != SIP_REQUEST) {
     if ((self->msg->first_line).type != SIP_REQUEST) {
-        PyErr_SetString(PyExc_RuntimeError, "Not a request message - "
-          "set destination is not possible.\n");
+        PyErr_SetString(PyExc_RuntimeError, "Not a request message - set destination is not possible.\n");
         Py_INCREF(Py_None);
         Py_INCREF(Py_None);
         return Py_None;
         return Py_None;
     }
     }
@@ -152,8 +142,7 @@ msg_set_dst_uri(msgobject *self, PyObject *args)
     return Py_None;
     return Py_None;
 }
 }
 
 
-static PyObject *
-msg_getHeader(msgobject *self, PyObject *args)
+static PyObject *msg_getHeader(msgobject *self, PyObject *args)
 {
 {
     struct hdr_field *hf;
     struct hdr_field *hf;
     str hname, *hbody;
     str hname, *hbody;
@@ -186,8 +175,7 @@ msg_getHeader(msgobject *self, PyObject *args)
     return PyString_FromStringAndSize(hbody->s, hbody->len);
     return PyString_FromStringAndSize(hbody->s, hbody->len);
 }
 }
 
 
-static PyObject *
-msg_call_function(msgobject *self, PyObject *args)
+static PyObject *msg_call_function(msgobject *self, PyObject *args)
 {
 {
     int i, rval;
     int i, rval;
     char *fname, *arg1, *arg2;
     char *fname, *arg1, *arg2;
@@ -285,20 +273,15 @@ PyDoc_STRVAR(copy_doc,
 Return a copy (``clone'') of the msg object.");
 Return a copy (``clone'') of the msg object.");
 
 
 static PyMethodDef msg_methods[] = {
 static PyMethodDef msg_methods[] = {
-    {"copy",          (PyCFunction)msg_copy,          METH_NOARGS,  copy_doc},
-    {"rewrite_ruri",  (PyCFunction)msg_rewrite_ruri,  METH_VARARGS,
-      "Rewrite Request-URI."},
-    {"set_dst_uri",   (PyCFunction)msg_set_dst_uri,   METH_VARARGS,
-      "Set destination URI."},
-    {"getHeader",     (PyCFunction)msg_getHeader,     METH_VARARGS,
-      "Get SIP header field by name."},
-    {"call_function", (PyCFunction)msg_call_function, METH_VARARGS,
-      "Invoke function exported by the other module."},
-    {NULL, NULL, 0, NULL}                              /* sentinel */
+    {"copy",          (PyCFunction)msg_copy,          METH_NOARGS,		copy_doc},
+    {"rewrite_ruri",  (PyCFunction)msg_rewrite_ruri,  METH_VARARGS,		"Rewrite Request-URI."},
+    {"set_dst_uri",   (PyCFunction)msg_set_dst_uri,   METH_VARARGS,		"Set destination URI."},
+    {"getHeader",     (PyCFunction)msg_getHeader,     METH_VARARGS,		"Get SIP header field by name."},
+    {"call_function", (PyCFunction)msg_call_function, METH_VARARGS,		"Invoke function exported by the other module."},
+    {NULL, NULL, 0, NULL} /* sentinel */
 };
 };
 
 
-static PyObject *
-msg_getType(msgobject *self, PyObject *unused)
+static PyObject *msg_getType(msgobject *self, PyObject *unused)
 {
 {
     const char *rval;
     const char *rval;
 
 
@@ -308,24 +291,25 @@ msg_getType(msgobject *self, PyObject *unused)
         return Py_None;
         return Py_None;
     }
     }
 
 
-    switch ((self->msg->first_line).type) {
-    case SIP_REQUEST:
-       rval = "SIP_REQUEST";
-       break;
+    switch ((self->msg->first_line).type)
+    {
+	case SIP_REQUEST:
+	    rval = "SIP_REQUEST";
+	    break;
 
 
-    case SIP_REPLY:
-       rval = "SIP_REPLY";
-       break;
+	case SIP_REPLY:
+	    rval = "SIP_REPLY";
+	    break;
 
 
-    default:
-       /* Shouldn't happen */
-       abort();
+	default:
+    	    /* Shouldn't happen */
+	    abort();
     }
     }
+
     return PyString_FromString(rval);
     return PyString_FromString(rval);
 }
 }
 
 
-static PyObject *
-msg_getMethod(msgobject *self, PyObject *unused)
+static PyObject *msg_getMethod(msgobject *self, PyObject *unused)
 {
 {
     str *rval;
     str *rval;
 
 
@@ -336,8 +320,7 @@ msg_getMethod(msgobject *self, PyObject *unused)
     }
     }
 
 
     if ((self->msg->first_line).type != SIP_REQUEST) {
     if ((self->msg->first_line).type != SIP_REQUEST) {
-        PyErr_SetString(PyExc_RuntimeError, "Not a request message - "
-          "no method available.\n");
+        PyErr_SetString(PyExc_RuntimeError, "Not a request message - no method available.\n");
         Py_INCREF(Py_None);
         Py_INCREF(Py_None);
         return Py_None;
         return Py_None;
     }
     }
@@ -345,8 +328,7 @@ msg_getMethod(msgobject *self, PyObject *unused)
     return PyString_FromStringAndSize(rval->s, rval->len);
     return PyString_FromStringAndSize(rval->s, rval->len);
 }
 }
 
 
-static PyObject *
-msg_getStatus(msgobject *self, PyObject *unused)
+static PyObject *msg_getStatus(msgobject *self, PyObject *unused)
 {
 {
     str *rval;
     str *rval;
 
 
@@ -357,8 +339,7 @@ msg_getStatus(msgobject *self, PyObject *unused)
     }
     }
 
 
     if ((self->msg->first_line).type != SIP_REPLY) {
     if ((self->msg->first_line).type != SIP_REPLY) {
-        PyErr_SetString(PyExc_RuntimeError, "Not a non-reply message - "
-          "no status available.\n");
+        PyErr_SetString(PyExc_RuntimeError, "Not a non-reply message - no status available.\n");
         Py_INCREF(Py_None);
         Py_INCREF(Py_None);
         return Py_None;
         return Py_None;
     }
     }
@@ -367,8 +348,7 @@ msg_getStatus(msgobject *self, PyObject *unused)
     return PyString_FromStringAndSize(rval->s, rval->len);
     return PyString_FromStringAndSize(rval->s, rval->len);
 }
 }
 
 
-static PyObject *
-msg_getRURI(msgobject *self, PyObject *unused)
+static PyObject *msg_getRURI(msgobject *self, PyObject *unused)
 {
 {
     str *rval;
     str *rval;
 
 
@@ -379,8 +359,7 @@ msg_getRURI(msgobject *self, PyObject *unused)
     }
     }
 
 
     if ((self->msg->first_line).type != SIP_REQUEST) {
     if ((self->msg->first_line).type != SIP_REQUEST) {
-        PyErr_SetString(PyExc_RuntimeError, "Not a request message - "
-          "RURI is not available.\n");
+        PyErr_SetString(PyExc_RuntimeError, "Not a request message - RURI is not available.\n");
         Py_INCREF(Py_None);
         Py_INCREF(Py_None);
         return Py_None;
         return Py_None;
     }
     }
@@ -389,8 +368,7 @@ msg_getRURI(msgobject *self, PyObject *unused)
     return PyString_FromStringAndSize(rval->s, rval->len);
     return PyString_FromStringAndSize(rval->s, rval->len);
 }
 }
 
 
-static PyObject *
-msg_get_src_address(msgobject *self, PyObject *unused)
+static PyObject *msg_get_src_address(msgobject *self, PyObject *unused)
 {
 {
     PyObject *src_ip, *src_port, *pyRval;
     PyObject *src_ip, *src_port, *pyRval;
 
 
@@ -424,8 +402,7 @@ msg_get_src_address(msgobject *self, PyObject *unused)
     return pyRval;
     return pyRval;
 }
 }
 
 
-static PyObject *
-msg_get_dst_address(msgobject *self, PyObject *unused)
+static PyObject *msg_get_dst_address(msgobject *self, PyObject *unused)
 {
 {
     PyObject *dst_ip, *dst_port, *pyRval;
     PyObject *dst_ip, *dst_port, *pyRval;
 
 
@@ -460,24 +437,12 @@ msg_get_dst_address(msgobject *self, PyObject *unused)
 }
 }
 
 
 static PyGetSetDef msg_getseters[] = {
 static PyGetSetDef msg_getseters[] = {
-    {"Type",
-     (getter)msg_getType, NULL, NULL,
-     "Get message type - \"SIP_REQUEST\" or \"SIP_REPLY\"."},
-    {"Method",
-     (getter)msg_getMethod, NULL, NULL,
-     "Get SIP method name."},
-    {"Status",
-     (getter)msg_getStatus, NULL, NULL,
-     "Get SIP status code string."},
-    {"RURI",
-     (getter)msg_getRURI, NULL, NULL,
-     "Get SIP Request-URI."},
-    {"src_address",
-     (getter)msg_get_src_address, NULL, NULL,
-     "Get (IP, port) tuple representing source address of the message."},
-    {"dst_address",
-     (getter)msg_get_dst_address, NULL, NULL,
-     "Get (IP, port) tuple representing destination address of the message."},
+    {"Type",		(getter)msg_getType, NULL, NULL,		"Get message type - \"SIP_REQUEST\" or \"SIP_REPLY\"."},
+    {"Method",		(getter)msg_getMethod, NULL, NULL,		"Get SIP method name."},
+    {"Status",		(getter)msg_getStatus, NULL, NULL,		"Get SIP status code string."},
+    {"RURI",		(getter)msg_getRURI, NULL, NULL,		"Get SIP Request-URI."},
+    {"src_address",	(getter)msg_get_src_address, NULL, NULL,	"Get (IP, port) tuple representing source address of the message."},
+    {"dst_address",	(getter)msg_get_dst_address, NULL, NULL,	"Get (IP, port) tuple representing destination address of the message."},
     {NULL, NULL, NULL, NULL, NULL}  /* Sentinel */
     {NULL, NULL, NULL, NULL, NULL}  /* Sentinel */
 };
 };
 
 
@@ -520,8 +485,7 @@ static PyTypeObject MSGtype = {
     msg_getseters,            /*tp_getset*/
     msg_getseters,            /*tp_getset*/
 };
 };
 
 
-int
-python_msgobj_init(void)
+int python_msgobj_init(void)
 {
 {
     MSGtype.ob_type = &PyType_Type;
     MSGtype.ob_type = &PyType_Type;
     if (PyType_Ready(&MSGtype) < 0)
     if (PyType_Ready(&MSGtype) < 0)

+ 165 - 17
modules/app_python/python_support.c

@@ -22,62 +22,76 @@
 
 
 #include <Python.h>
 #include <Python.h>
 #include <stdio.h>
 #include <stdio.h>
+#include <stdarg.h>
 
 
 #include "../../dprint.h"
 #include "../../dprint.h"
 #include "../../mem/mem.h"
 #include "../../mem/mem.h"
 
 
 #include "python_mod.h"
 #include "python_mod.h"
+#include "python_support.h"
 
 
-void
-python_handle_exception(const char *fname)
+void python_handle_exception(const char *fmt, ...)
 {
 {
     PyObject *pResult;
     PyObject *pResult;
     const char *msg;
     const char *msg;
     char *buf;
     char *buf;
-    size_t buflen;
+    size_t buflen, msglen;
     PyObject *exception, *v, *tb, *args;
     PyObject *exception, *v, *tb, *args;
     PyObject *line;
     PyObject *line;
     int i;
     int i;
+    char *srcbuf;
+
+    // We don't want to generate traceback when no errors occured
+    if (!PyErr_Occurred())
+	return;
+
+    if (fmt == NULL)
+	srcbuf = NULL;
+    else
+	srcbuf = make_message(fmt);
 
 
     PyErr_Fetch(&exception, &v, &tb);
     PyErr_Fetch(&exception, &v, &tb);
     PyErr_Clear();
     PyErr_Clear();
     if (exception == NULL) {
     if (exception == NULL) {
-        LM_ERR("can't get traceback, PyErr_Fetch() has failed\n");
+        LM_ERR("python_handle_exception(): Can't get traceback, PyErr_Fetch() has failed.\n");
         return;
         return;
     }
     }
+
     PyErr_NormalizeException(&exception, &v, &tb);
     PyErr_NormalizeException(&exception, &v, &tb);
     if (exception == NULL) {
     if (exception == NULL) {
-        LM_ERR("can't get traceback, PyErr_NormalizeException() has failed\n");
+        LM_ERR("python_handle_exception(): Can't get traceback, PyErr_NormalizeException() has failed.\n");
         return;
         return;
     }
     }
+
     args = PyTuple_Pack(3, exception, v, tb ? tb : Py_None);
     args = PyTuple_Pack(3, exception, v, tb ? tb : Py_None);
     Py_XDECREF(exception);
     Py_XDECREF(exception);
     Py_XDECREF(v);
     Py_XDECREF(v);
     Py_XDECREF(tb);
     Py_XDECREF(tb);
     if (args == NULL) {
     if (args == NULL) {
-        LM_ERR("can't get traceback, PyTuple_Pack() has failed\n");
+        LM_ERR("python_handle_exception(): Can't get traceback, PyTuple_Pack() has failed.\n");
         return;
         return;
     }
     }
+
     pResult = PyObject_CallObject(format_exc_obj, args);
     pResult = PyObject_CallObject(format_exc_obj, args);
     Py_DECREF(args);
     Py_DECREF(args);
     if (pResult == NULL) {
     if (pResult == NULL) {
-        LM_ERR("can't get traceback, traceback.format_exception() has failed\n");
+        LM_ERR("python_handle_exception(): Can't get traceback, traceback.format_exception() has failed.\n");
         return;
         return;
     }
     }
 
 
     buflen = 1;
     buflen = 1;
-    buf = (char *)pkg_malloc(buflen * sizeof(char *));
+    buf = (char *)pkg_realloc(NULL, buflen * sizeof(char *));
     if (!buf)
     if (!buf)
     {
     {
-	LM_ERR("python_handle_exception(): Not enough memory\n");
+	LM_ERR("python_handle_exception(): Can't allocate memory (%d bytes), pkg_realloc() has failed. Not enough memory.\n", buflen * sizeof(char *));
 	return;
 	return;
     }
     }
-    memset(&buf, 0, buflen * sizeof(char *));
+    memset(buf, 0, sizeof(char *));
 
 
     for (i = 0; i < PySequence_Size(pResult); i++) {
     for (i = 0; i < PySequence_Size(pResult); i++) {
         line = PySequence_GetItem(pResult, i);
         line = PySequence_GetItem(pResult, i);
         if (line == NULL) {
         if (line == NULL) {
-            LM_ERR("can't get traceback, PySequence_GetItem() has failed\n");
+            LM_ERR("python_handle_exception(): Can't get traceback, PySequence_GetItem() has failed.\n");
             Py_DECREF(pResult);
             Py_DECREF(pResult);
 	    if (buf)
 	    if (buf)
 		pkg_free(buf);
 		pkg_free(buf);
@@ -87,7 +101,7 @@ python_handle_exception(const char *fname)
         msg = PyString_AsString(line);
         msg = PyString_AsString(line);
 
 
         if (msg == NULL) {
         if (msg == NULL) {
-            LM_ERR("can't get traceback, PyString_AsString() has failed\n");
+            LM_ERR("python_handle_exception(): Can't get traceback, PyString_AsString() has failed.\n");
             Py_DECREF(line);
             Py_DECREF(line);
             Py_DECREF(pResult);
             Py_DECREF(pResult);
 	    if (buf)
 	    if (buf)
@@ -95,25 +109,159 @@ python_handle_exception(const char *fname)
             return;
             return;
         }
         }
 
 
-	buflen += strlen(msg);
-	buf = (char *)pkg_realloc(buf, (buflen + 1) * sizeof(char *));
+	msglen = strlen(msg);
+	buflen += ++msglen;
+
+	buf = (char *)pkg_realloc(buf, buflen * sizeof(char *));
 	if (!buf)
 	if (!buf)
 	{
 	{
-	    LM_ERR("python_handle_exception(): Not enough memory\n");
+	    LM_ERR("python_handle_exception(): Can't allocate memory (%d bytes), pkg_realloc() has failed. Not enough memory.\n", buflen * sizeof(char *));
 	    Py_DECREF(line);
 	    Py_DECREF(line);
 	    Py_DECREF(pResult);
 	    Py_DECREF(pResult);
 	    return;
 	    return;
 	}
 	}
 
 
-	strcat(buf, msg);
+	strncat(buf, msg, msglen >= buflen ? buflen-1 : msglen);
 
 
         Py_DECREF(line);
         Py_DECREF(line);
     }
     }
 
 
-    LM_ERR("%s: Unhandled exception in the Python code:\n%s", fname, buf);
+    if (srcbuf == NULL)
+	LM_ERR("Unhandled exception in the Python code:\n%s", buf);
+    else
+	LM_ERR("%s: Unhandled exception in the Python code:\n%s", srcbuf, buf);
 
 
     if (buf)
     if (buf)
 	pkg_free(buf);
 	pkg_free(buf);
 
 
+    if (srcbuf)
+	pkg_free(srcbuf);
+
     Py_DECREF(pResult);
     Py_DECREF(pResult);
 }
 }
+
+
+PyObject *InitTracebackModule()
+{
+    PyObject *pModule, *pTracebackObject;
+
+    pModule = PyImport_ImportModule("traceback");
+    if (pModule == NULL) {
+        LM_ERR("InitTracebackModule(): Cannot import module 'traceback'.\n");
+        return NULL;
+    }
+
+    pTracebackObject = PyObject_GetAttrString(pModule, "format_exception");
+    Py_DECREF(pModule);
+    if (pTracebackObject == NULL || !PyCallable_Check(pTracebackObject)) {
+        LM_ERR("InitTracebackModule(): AttributeError: 'module' object 'traceback' has no attribute 'format_exception'.\n");
+        Py_XDECREF(pTracebackObject);
+        return NULL;
+    }
+
+    return pTracebackObject;
+}
+
+
+char *make_message(const char *fmt, ...)
+{
+    int n;
+    size_t size;
+    char *p, *np;
+    va_list ap;
+
+    size = 100;     /* Guess we need no more than 100 bytes. */
+    p = (char *)pkg_realloc(NULL, size * sizeof(char *));
+    if (!p)
+    {
+	LM_ERR("make_message(): Can't allocate memory (%d bytes), pkg_malloc() has failed: Not enough memory.\n", size * sizeof(char *));
+	return NULL;
+    }
+    memset(p, 0, size * sizeof(char *));
+    
+    while (1)
+    {
+        va_start(ap, fmt);
+        n = vsnprintf(p, size, fmt, ap);
+        va_end(ap);
+
+        if (n > -1 && n < size)
+    	    return p;
+
+        if (n > -1)    /* glibc 2.1 */
+    	    size = n+1;
+        else           /* glibc 2.0 */
+    	    size *= 2;
+
+	np = (char *)pkg_realloc(p, size * sizeof(char *));
+        if (!np)
+	{
+	    LM_ERR("make_message(): Can't allocate memory (%d bytes), pkg_realloc() has failed: Not enough memory.\n", size * sizeof(char *));
+	    if (p)
+    		pkg_free(p);
+    	    return NULL;
+        }
+	else
+    	    p = np;
+    }
+
+    return NULL;	// shall not happened, but who knows ;)
+}
+
+char *get_class_name(PyObject *y)
+{
+    PyObject *p;
+    char *name;
+
+    p = PyObject_GetAttrString(y, "__name__");
+    if (p == NULL || p == Py_None)
+    {
+	Py_XDECREF(p);
+	return NULL;
+    }
+
+    name = PyString_AsString(p);
+    Py_XDECREF(p);
+
+    if (name == NULL)
+    {
+	Py_XDECREF(name);
+	return NULL;
+    }
+    else
+	return name;
+}
+
+
+char *get_instance_class_name(PyObject *y)
+{
+    PyObject *p, *n;
+    char *name;
+
+    n = PyObject_GetAttrString(y, "__class__");
+    if (n == NULL || n == Py_None)
+    {
+	Py_XDECREF(n);
+	return NULL;
+    }
+
+    p = PyObject_GetAttrString(n, "__name__");
+    if (p == NULL || p == Py_None)
+    {
+	Py_XDECREF(p);
+	return NULL;
+    }
+
+    name = PyString_AsString(p);
+    Py_XDECREF(p);
+    Py_XDECREF(n);
+
+    if (name == NULL)
+    {
+	Py_XDECREF(name);
+	return NULL;
+    }
+    else
+	return name;
+}
+

+ 11 - 1
modules/app_python/python_support.h

@@ -23,6 +23,16 @@
 #ifndef _PYTHON_SUPPORT_H
 #ifndef _PYTHON_SUPPORT_H
 #define  _PYTHON_SUPPORT_H
 #define  _PYTHON_SUPPORT_H
 
 
-void python_handle_exception(const char *);
+#include <Python.h>
+#include <stdarg.h>
+
+PyObject *format_exc_obj;
+
+void python_handle_exception(const char *, ...);
+char *make_message(const char *fmt, ...);
+
+PyObject *InitTracebackModule(void);
+char *get_class_name(PyObject *);
+char *get_instance_class_name(PyObject *);
 
 
 #endif
 #endif