Added shutdown callback.
[collectd.git] / src / python.c
1 #include <Python.h>
2 #include <structmember.h>
3
4 #include "collectd.h"
5 #include "common.h"
6
7 typedef struct cpy_callback_s {
8         char *name;
9         PyObject *callback;
10         PyObject *data;
11         struct cpy_callback_s *next;
12 } cpy_callback_t;
13
14 /* This is our global thread state. Python saves some stuff in thread-local
15  * storage. So if we allow the interpreter to run in the background
16  * (the scriptwriters might have created some threads from python), we have
17  * to save the state so we can resume it later from a different thread.
18
19  * Technically the Global Interpreter Lock (GIL) and thread states can be
20  * manipulated independently. But to keep stuff from getting too complex
21  * we'll just use PyEval_SaveTread and PyEval_RestoreThreas which takes
22  * care of the thread states as well as the GIL. */
23
24 static PyThreadState *state;
25
26 static cpy_callback_t *cpy_config_callbacks;
27 static cpy_callback_t *cpy_init_callbacks;
28 static cpy_callback_t *cpy_shutdown_callbacks;
29
30 typedef struct {
31         PyObject_HEAD      /* No semicolon! */
32         PyObject *parent;
33         PyObject *key;
34         PyObject *values;
35         PyObject *children;
36 } Config;
37
38 static void Config_dealloc(PyObject *s) {
39         Config *self = (Config *) s;
40         
41         Py_XDECREF(self->parent);
42         Py_XDECREF(self->key);
43         Py_XDECREF(self->values);
44         Py_XDECREF(self->children);
45         self->ob_type->tp_free(s);
46 }
47
48 static PyObject *Config_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
49         Config *self;
50         
51         self = (Config *) type->tp_alloc(type, 0);
52         if (self == NULL)
53                 return NULL;
54         
55         self->parent = NULL;
56         self->key = NULL;
57         self->values = NULL;
58         self->children = NULL;
59         return (PyObject *) self;
60 }
61
62 static int Config_init(PyObject *s, PyObject *args, PyObject *kwds) {
63         PyObject *key = NULL, *parent = NULL, *values = NULL, *children = NULL, *tmp;
64         Config *self = (Config *) s;
65         static char *kwlist[] = {"key", "parent", "values", "children", NULL};
66         
67         if (!PyArg_ParseTupleAndKeywords(args, kwds, "S|OOO", kwlist,
68                         &key, &parent, &values, &children))
69                 return -1;
70         
71         if (values == NULL) {
72                 values = PyTuple_New(0);
73                 PyErr_Clear();
74         }
75         if (children == NULL) {
76                 children = PyTuple_New(0);
77                 PyErr_Clear();
78         }
79         tmp = self->key;
80         Py_INCREF(key);
81         self->key = key;
82         Py_XDECREF(tmp);
83         if (parent != NULL) {
84                 tmp = self->parent;
85                 Py_INCREF(parent);
86                 self->parent = parent;
87                 Py_XDECREF(tmp);
88         }
89         if (values != NULL) {
90                 tmp = self->values;
91                 Py_INCREF(values);
92                 self->values = values;
93                 Py_XDECREF(tmp);
94         }
95         if (children != NULL) {
96                 tmp = self->children;
97                 Py_INCREF(children);
98                 self->children = children;
99                 Py_XDECREF(tmp);
100         }
101         return 0;
102 }
103
104 static PyMemberDef Config_members[] = {
105     {"Parent", T_OBJECT, offsetof(Config, parent), 0, "Parent node"},
106     {"Key", T_OBJECT_EX, offsetof(Config, key), 0, "Keyword of this node"},
107     {"Values", T_OBJECT_EX, offsetof(Config, values), 0, "Values after the key"},
108     {"Children", T_OBJECT_EX, offsetof(Config, children), 0, "Childnodes of this node"},
109     {NULL}
110 };
111
112 static PyTypeObject ConfigType = {
113     PyObject_HEAD_INIT(NULL)
114     0,                         /* Always 0 */
115     "collectd.Config",         /* tp_name */
116     sizeof(Config),            /* tp_basicsize */
117     0,                         /* Will be filled in later */
118     Config_dealloc,            /* tp_dealloc */
119     0,                         /* tp_print */
120     0,                         /* tp_getattr */
121     0,                         /* tp_setattr */
122     0,                         /* tp_compare */
123     0,                         /* tp_repr */
124     0,                         /* tp_as_number */
125     0,                         /* tp_as_sequence */
126     0,                         /* tp_as_mapping */
127     0,                         /* tp_hash */
128     0,                         /* tp_call */
129     0,                         /* tp_str */
130     0,                         /* tp_getattro */
131     0,                         /* tp_setattro */
132     0,                         /* tp_as_buffer */
133     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
134     "Cool help text later",    /* tp_doc */
135     0,                         /* tp_traverse */
136     0,                         /* tp_clear */
137     0,                         /* tp_richcompare */
138     0,                         /* tp_weaklistoffset */
139     0,                         /* tp_iter */
140     0,                         /* tp_iternext */
141     0,                         /* tp_methods */
142     Config_members,            /* tp_members */
143     0,                         /* tp_getset */
144     0,                         /* tp_base */
145     0,                         /* tp_dict */
146     0,                         /* tp_descr_get */
147     0,                         /* tp_descr_set */
148     0,                         /* tp_dictoffset */
149     Config_init,               /* tp_init */
150     0,                         /* tp_alloc */
151     Config_new                 /* tp_new */
152 };
153
154 static PyObject *cpy_register_generic(cpy_callback_t **list_head, PyObject *args, PyObject *kwds) {
155         cpy_callback_t *c;
156         const char *name = NULL;
157         PyObject *callback = NULL, *data = NULL;
158         static char *kwlist[] = {"callback", "data", "name", NULL};
159         
160         if (PyArg_ParseTupleAndKeywords(args, kwds, "O|Oz", kwlist, &callback, &data, &name) == 0) return NULL;
161         if (PyCallable_Check(callback) == 0) {
162                 PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
163                 return NULL;
164         }
165         if (name == NULL) {
166                 PyObject *mod;
167                 
168                 mod = PyObject_GetAttrString(callback, "__module__");
169                 if (mod != NULL) name = PyString_AsString(mod);
170                 if (name == NULL) {
171                         PyErr_SetString(PyExc_ValueError, "No module name specified and "
172                                 "callback function does not have a \"__module__\" attribute.");
173                         return NULL;
174                 }
175         }
176         Py_INCREF(callback);
177         Py_XINCREF(data);
178         c = malloc(sizeof(*c));
179         c->name = strdup(name);
180         c->callback = callback;
181         c->data = data;
182         c->next = *list_head;
183         *list_head = c;
184         Py_RETURN_NONE;
185 }
186
187 static PyObject *cpy_register_config(PyObject *self, PyObject *args, PyObject *kwds) {
188         return cpy_register_generic(&cpy_config_callbacks, args, kwds);
189 }
190
191 static PyObject *cpy_register_init(PyObject *self, PyObject *args, PyObject *kwds) {
192         return cpy_register_generic(&cpy_init_callbacks, args, kwds);
193 }
194
195 static PyObject *cpy_register_shutdown(PyObject *self, PyObject *args, PyObject *kwds) {
196         return cpy_register_generic(&cpy_shutdown_callbacks, args, kwds);
197 }
198
199 static PyMethodDef cpy_methods[] = {
200         {"register_init", (PyCFunction) cpy_register_init, METH_VARARGS | METH_KEYWORDS, "This is an unhelpful text."},
201         {"register_config", (PyCFunction) cpy_register_config, METH_VARARGS | METH_KEYWORDS, "This is an unhelpful text."},
202         {"register_shutdown", (PyCFunction) cpy_register_shutdown, METH_VARARGS | METH_KEYWORDS, "This is an unhelpful text."},
203         {0, 0, 0, 0}
204 };
205
206 static int cpy_shutdown(void) {
207         cpy_callback_t *c;
208         PyObject *ret;
209         
210         /* This can happen if the module was loaded but not configured. */
211         if (state != NULL)
212                 PyEval_RestoreThread(state);
213
214         for (c = cpy_shutdown_callbacks; c; c = c->next) {
215                 if (c->data == NULL)
216                         ret = PyObject_CallObject(c->callback, NULL); /* New reference. */
217                 else
218                         ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0); /* New reference. */
219                 if (ret == NULL)
220                         PyErr_Print(); /* FIXME */
221                 else
222                         Py_DECREF(ret);
223         }
224         Py_Finalize();
225         return 0;
226 }
227
228 static int cpy_init(void) {
229         cpy_callback_t *c;
230         PyObject *ret;
231         
232         PyEval_InitThreads();
233         /* Now it's finally OK to use python threads. */
234         for (c = cpy_init_callbacks; c; c = c->next) {
235                 if (c->data == NULL)
236                         ret = PyObject_CallObject(c->callback, NULL); /* New reference. */
237                 else
238                         ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0); /* New reference. */
239                 if (ret == NULL)
240                         PyErr_Print(); /* FIXME */
241                 else
242                         Py_DECREF(ret);
243         }
244         state = PyEval_SaveThread();
245         return 0;
246 }
247
248 static PyObject *cpy_oconfig_to_pyconfig(oconfig_item_t *ci, PyObject *parent) {
249         int i;
250         PyObject *item, *values, *children, *tmp;
251         
252         if (parent == NULL)
253                 parent = Py_None;
254         
255         values = PyTuple_New(ci->values_num); /* New reference. */
256         for (i = 0; i < ci->values_num; ++i) {
257                 if (ci->values[i].type == OCONFIG_TYPE_STRING) {
258                         PyTuple_SET_ITEM(values, i, PyString_FromString(ci->values[i].value.string));
259                 } else if (ci->values[i].type == OCONFIG_TYPE_NUMBER) {
260                         PyTuple_SET_ITEM(values, i, PyFloat_FromDouble(ci->values[i].value.number));
261                 } else if (ci->values[i].type == OCONFIG_TYPE_BOOLEAN) {
262                         PyTuple_SET_ITEM(values, i, PyBool_FromLong(ci->values[i].value.boolean));
263                 }
264         }
265         
266         item = PyObject_CallFunction((PyObject *) &ConfigType, "sONO", ci->key, parent, values, Py_None);
267         if (item == NULL)
268                 return NULL;
269         children = PyTuple_New(ci->children_num); /* New reference. */
270         for (i = 0; i < ci->children_num; ++i) {
271                         PyTuple_SET_ITEM(children, i, cpy_oconfig_to_pyconfig(ci->children + i, item));
272         }
273         tmp = ((Config *) item)->children;
274         ((Config *) item)->children = children;
275         Py_XDECREF(tmp);
276         return item;
277 }
278
279 static int cpy_config(oconfig_item_t *ci) {
280         int i;
281         PyObject *sys;
282         PyObject *sys_path;
283         PyObject *module;
284         
285         /* Ok in theory we shouldn't do initialization at this point
286          * but we have to. In order to give python scripts a chance
287          * to register a config callback we need to be able to execute
288          * python code during the config callback so we have to start
289          * the interpreter here. */
290         /* Do *not* use the python "thread" module at this point! */
291         Py_Initialize();
292         
293         PyType_Ready(&ConfigType);
294         sys = PyImport_ImportModule("sys"); /* New reference. */
295         if (sys == NULL) {
296                 ERROR("python module: Unable to import \"sys\" module.");
297                 /* Just print the default python exception text to stderr. */
298                 PyErr_Print();
299                 return 1;
300         }
301         sys_path = PyObject_GetAttrString(sys, "path"); /* New reference. */
302         Py_DECREF(sys);
303         if (sys_path == NULL) {
304                 ERROR("python module: Unable to read \"sys.path\".");
305                 PyErr_Print();
306                 return 1;
307         }
308         module = Py_InitModule("collectd", cpy_methods); /* Borrowed reference. */
309         PyModule_AddObject(module, "Config", (PyObject *) &ConfigType); /* Steals a reference. */
310         for (i = 0; i < ci->children_num; ++i) {
311                 oconfig_item_t *item = ci->children + i;
312                 
313                 if (strcasecmp(item->key, "ModulePath") == 0) {
314                         char *dir = NULL;
315                         PyObject *dir_object;
316                         
317                         if (cf_util_get_string(item, &dir) != 0) 
318                                 continue;
319                         dir_object = PyString_FromString(dir); /* New reference. */
320                         if (dir_object == NULL) {
321                                 ERROR("python plugin: Unable to convert \"%s\" to "
322                                       "a python object.", dir);
323                                 free(dir);
324                                 PyErr_Print();
325                                 continue;
326                         }
327                         if (PyList_Append(sys_path, dir_object) != 0) {
328                                 ERROR("python plugin: Unable to append \"%s\" to "
329                                       "python module path.", dir);
330                                 PyErr_Print();
331                         }
332                         Py_DECREF(dir_object);
333                         free(dir);
334                 } else if (strcasecmp(item->key, "Import") == 0) {
335                         char *module_name = NULL;
336                         PyObject *module;
337                         
338                         if (cf_util_get_string(item, &module_name) != 0) 
339                                 continue;
340                         module = PyImport_ImportModule(module_name); /* New reference. */
341                         if (module == NULL) {
342                                 ERROR("python plugin: Error importing module \"%s\".", module_name);
343                                 PyErr_Print();
344                         }
345                         free(module_name);
346                         Py_XDECREF(module);
347                 } else if (strcasecmp(item->key, "Module") == 0) {
348                         char *name = NULL;
349                         cpy_callback_t *c;
350                         PyObject *ret;
351                         
352                         if (cf_util_get_string(item, &name) != 0)
353                                 continue;
354                         for (c = cpy_config_callbacks; c; c = c->next) {
355                                 if (strcasecmp(c->name, name) == 0)
356                                         break;
357                         }
358                         if (c == NULL) {
359                                 WARNING("python plugin: Found a configuration for the \"%s\" plugin, "
360                                         "but the plugin isn't loaded or didn't register "
361                                         "a configuration callback.", name);
362                                 free(name);
363                                 continue;
364                         }
365                         free(name);
366                         if (c->data == NULL)
367                                 ret = PyObject_CallFunction(c->callback, "N",
368                                         cpy_oconfig_to_pyconfig(item, NULL)); /* New reference. */
369                         else
370                                 ret = PyObject_CallFunction(c->callback, "NO",
371                                         cpy_oconfig_to_pyconfig(item, NULL), c->data); /* New reference. */
372                         if (ret == NULL)
373                                 PyErr_Print();
374                         else
375                                 Py_DECREF(ret);
376                 } else {
377                         WARNING("python plugin: Ignoring unknown config key \"%s\".", item->key);
378                 }
379         }
380         Py_DECREF(sys_path);
381         return 0;
382 }
383
384 void module_register(void) {
385         plugin_register_complex_config("python", cpy_config);
386         plugin_register_init("python", cpy_init);
387 //      plugin_register_read("python", cna_read);
388         plugin_register_shutdown("python", cpy_shutdown);
389 }