Meh, forgot to pass the userdata back on write callbacks.
[collectd.git] / src / python.c
1 #include <Python.h>
2 #include <structmember.h>
3
4 #include "collectd.h"
5 #include "common.h"
6
7 #include "cpython.h"
8
9 typedef struct cpy_callback_s {
10         char *name;
11         PyObject *callback;
12         PyObject *data;
13         struct cpy_callback_s *next;
14 } cpy_callback_t;
15
16 /* This is our global thread state. Python saves some stuff in thread-local
17  * storage. So if we allow the interpreter to run in the background
18  * (the scriptwriters might have created some threads from python), we have
19  * to save the state so we can resume it later after shutdown. */
20
21 static PyThreadState *state;
22
23 static cpy_callback_t *cpy_config_callbacks;
24 static cpy_callback_t *cpy_init_callbacks;
25 static cpy_callback_t *cpy_shutdown_callbacks;
26
27 static void cpy_destroy_user_data(void *data) {
28         cpy_callback_t *c = data;
29         free(c->name);
30         Py_DECREF(c->callback);
31         Py_XDECREF(c->data);
32         free(c);
33 }
34
35 /* You must hold the GIL to call this function!
36  * But if you managed to extract the callback parameter then you probably already do. */
37
38 static void cpy_build_name(char *buf, size_t size, PyObject *callback, const char *name) {
39         const char *module;
40         PyObject *mod = NULL, *n = NULL;
41         
42         if (name != NULL && strchr(name, '.') != NULL) {
43                 snprintf(buf, size, "python.%s", name);
44                 return;
45         }
46         
47         mod = PyObject_GetAttrString(callback, "__module__"); /* New reference. */
48         if (mod != NULL)
49                 module = PyString_AsString(mod);
50         else
51                 module = "collectd";
52         if (name != NULL) {
53                 snprintf(buf, size, "python.%s.%s", module, name);
54                 Py_XDECREF(mod);
55                 return;
56         }
57         
58         n = PyObject_GetAttrString(callback, "__name__"); /* New reference. */
59         if (n != NULL)
60                 name = PyString_AsString(n);
61         
62         if (name != NULL)
63                 snprintf(buf, size, "python.%s.%s", module, name);
64         else
65                 snprintf(buf, size, "python.%s.%p", module, callback);
66         Py_XDECREF(mod);
67         Py_XDECREF(n);
68 }
69
70 static int cpy_read_callback(user_data_t *data) {
71         cpy_callback_t *c = data->data;
72         PyObject *ret;
73
74         CPY_LOCK_THREADS
75                 if (c->data == NULL)
76                         ret = PyObject_CallFunctionObjArgs(c->callback, (void *) 0);
77                 else
78                         ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0);
79                 if (ret == NULL) {
80                         /* FIXME */
81                         PyErr_Print();
82                 } else {
83                         Py_DECREF(ret);
84                 }
85         CPY_RELEASE_THREADS
86         return 0;
87 }
88
89 static int cpy_write_callback(const data_set_t *ds, const value_list_t *value_list, user_data_t *data) {
90         int i;
91         cpy_callback_t *c = data->data;
92         PyObject *ret, *v, *list;
93
94         CPY_LOCK_THREADS
95                 list = PyList_New(value_list->values_len); /* New reference. */
96                 if (list == NULL) {
97                         PyErr_Print();
98                         CPY_RETURN_FROM_THREADS 0;
99                 }
100                 for (i = 0; i < value_list->values_len; ++i) {
101                         if (ds->ds->type == DS_TYPE_COUNTER) {
102                                 if ((long) value_list->values[i].counter == value_list->values[i].counter)
103                                         PyList_SetItem(list, i, PyInt_FromLong(value_list->values[i].counter));
104                                 else
105                                         PyList_SetItem(list, i, PyLong_FromUnsignedLongLong(value_list->values[i].counter));
106                         } else if (ds->ds->type == DS_TYPE_GAUGE) {
107                                 PyList_SetItem(list, i, PyFloat_FromDouble(value_list->values[i].gauge));
108                         } else if (ds->ds->type == DS_TYPE_DERIVE) {
109                                 if ((long) value_list->values[i].derive == value_list->values[i].derive)
110                                         PyList_SetItem(list, i, PyInt_FromLong(value_list->values[i].derive));
111                                 else
112                                         PyList_SetItem(list, i, PyLong_FromLongLong(value_list->values[i].derive));
113                         } else if (ds->ds->type == DS_TYPE_ABSOLUTE) {
114                                 if ((long) value_list->values[i].absolute == value_list->values[i].absolute)
115                                         PyList_SetItem(list, i, PyInt_FromLong(value_list->values[i].absolute));
116                                 else
117                                         PyList_SetItem(list, i, PyLong_FromUnsignedLongLong(value_list->values[i].absolute));
118                         } else {
119                                 ERROR("cpy_write_callback: Unknown value type %d.", ds->ds->type);
120                                 Py_DECREF(list);
121                                 CPY_RETURN_FROM_THREADS 0;
122                         }
123                         if (PyErr_Occurred() != NULL) {
124                                 PyErr_Print();
125                                 CPY_RETURN_FROM_THREADS 0;
126                         }
127                 }
128                 v = PyObject_CallFunction((PyObject *) &ValuesType, "sOssssdi", value_list->type, list,
129                                 value_list->plugin_instance, value_list->type_instance, value_list->plugin,
130                                 value_list->host, (double) value_list->time, value_list->interval);
131                 Py_DECREF(list);
132                 if (c->data == NULL)
133                         ret = PyObject_CallFunctionObjArgs(c->callback, v, (void *) 0);
134                 else
135                         ret = PyObject_CallFunctionObjArgs(c->callback, v, c->data, (void *) 0);
136                 if (ret == NULL) {
137                         /* FIXME */
138                         PyErr_Print();
139                 } else {
140                         Py_DECREF(ret);
141                 }
142         CPY_RELEASE_THREADS
143         return 0;
144 }
145
146 static void cpy_log_callback(int severity, const char *message, user_data_t *data) {
147         cpy_callback_t * c = data->data;
148         PyObject *ret;
149
150         CPY_LOCK_THREADS
151         if (c->data == NULL)
152                 ret = PyObject_CallFunction(c->callback, "is", severity, message); /* New reference. */
153         else
154                 ret = PyObject_CallFunction(c->callback, "isO", severity, message, c->data); /* New reference. */
155
156         if (ret == NULL) {
157                 /* FIXME */
158                 PyErr_Print();
159         } else {
160                 Py_DECREF(ret);
161         }
162         CPY_RELEASE_THREADS
163 }
164
165 static PyObject *cpy_register_generic(cpy_callback_t **list_head, PyObject *args, PyObject *kwds) {
166         cpy_callback_t *c;
167         const char *name = NULL;
168         PyObject *callback = NULL, *data = NULL, *mod = NULL;
169         static char *kwlist[] = {"callback", "data", "name", NULL};
170         
171         if (PyArg_ParseTupleAndKeywords(args, kwds, "O|Oz", kwlist, &callback, &data, &name) == 0) return NULL;
172         if (PyCallable_Check(callback) == 0) {
173                 PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
174                 return NULL;
175         }
176         if (name == NULL) {
177                 mod = PyObject_GetAttrString(callback, "__module__"); /* New reference. */
178                 if (mod != NULL) name = PyString_AsString(mod);
179                 if (name == NULL) {
180                         Py_XDECREF(mod);
181                         PyErr_SetString(PyExc_ValueError, "No module name specified and "
182                                 "callback function does not have a \"__module__\" attribute.");
183                         return NULL;
184                 }
185         }
186         Py_INCREF(callback);
187         Py_XINCREF(data);
188         c = malloc(sizeof(*c));
189         c->name = strdup(name);
190         c->callback = callback;
191         c->data = data;
192         c->next = *list_head;
193         *list_head = c;
194         Py_XDECREF(mod);
195         Py_RETURN_NONE;
196 }
197
198 static PyObject *cpy_register_config(PyObject *self, PyObject *args, PyObject *kwds) {
199         return cpy_register_generic(&cpy_config_callbacks, args, kwds);
200 }
201
202 static PyObject *cpy_register_init(PyObject *self, PyObject *args, PyObject *kwds) {
203         return cpy_register_generic(&cpy_init_callbacks, args, kwds);
204 }
205
206 typedef int reg_function_t(const char *name, void *callback, void *data);
207
208 static PyObject *cpy_register_generic_userdata(void *reg, void *handler, PyObject *args, PyObject *kwds) {
209         char buf[512];
210         reg_function_t *register_function = (reg_function_t *) reg;
211         cpy_callback_t *c = NULL;
212         user_data_t *user_data = NULL;
213         const char *name = NULL;
214         PyObject *callback = NULL, *data = NULL;
215         static char *kwlist[] = {"callback", "data", "name", NULL};
216         
217         if (PyArg_ParseTupleAndKeywords(args, kwds, "O|Oz", kwlist, &callback, &data, &name) == 0) return NULL;
218         if (PyCallable_Check(callback) == 0) {
219                 PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
220                 return NULL;
221         }
222         cpy_build_name(buf, sizeof(buf), callback, name);
223         
224         Py_INCREF(callback);
225         Py_XINCREF(data);
226         c = malloc(sizeof(*c));
227         c->name = strdup(buf);
228         c->callback = callback;
229         c->data = data;
230         c->next = NULL;
231         user_data = malloc(sizeof(*user_data));
232         user_data->free_func = cpy_destroy_user_data;
233         user_data->data = c;
234         register_function(buf, handler, user_data);
235         return PyString_FromString(buf);
236 }
237
238 static PyObject *cpy_register_read(PyObject *self, PyObject *args, PyObject *kwds) {
239         char buf[512];
240         cpy_callback_t *c = NULL;
241         user_data_t *user_data = NULL;
242         double interval = 0;
243         const char *name = NULL;
244         PyObject *callback = NULL, *data = NULL;
245         struct timespec ts;
246         static char *kwlist[] = {"callback", "interval", "data", "name", NULL};
247         
248         if (PyArg_ParseTupleAndKeywords(args, kwds, "O|dOz", kwlist, &callback, &interval, &data, &name) == 0) return NULL;
249         if (PyCallable_Check(callback) == 0) {
250                 PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
251                 return NULL;
252         }
253         cpy_build_name(buf, sizeof(buf), callback, name);
254         
255         Py_INCREF(callback);
256         Py_XINCREF(data);
257         c = malloc(sizeof(*c));
258         c->name = strdup(buf);
259         c->callback = callback;
260         c->data = data;
261         c->next = NULL;
262         user_data = malloc(sizeof(*user_data));
263         user_data->free_func = cpy_destroy_user_data;
264         user_data->data = c;
265         ts.tv_sec = interval;
266         ts.tv_nsec = (interval - ts.tv_sec) * 1000000000;
267         plugin_register_complex_read(buf, cpy_read_callback, &ts, user_data);
268         return PyString_FromString(buf);
269 }
270
271 static PyObject *cpy_register_log(PyObject *self, PyObject *args, PyObject *kwds) {
272         return cpy_register_generic_userdata(plugin_register_log, cpy_log_callback, args, kwds);
273 }
274
275 static PyObject *cpy_register_write(PyObject *self, PyObject *args, PyObject *kwds) {
276         return cpy_register_generic_userdata(plugin_register_write, cpy_write_callback, args, kwds);
277 }
278
279 static PyObject *cpy_register_shutdown(PyObject *self, PyObject *args, PyObject *kwds) {
280         return cpy_register_generic(&cpy_shutdown_callbacks, args, kwds);
281 }
282
283 static PyObject *cpy_Error(PyObject *self, PyObject *args) {
284         const char *text;
285         if (PyArg_ParseTuple(args, "s", &text) == 0) return NULL;
286         Py_BEGIN_ALLOW_THREADS
287         plugin_log(LOG_ERR, "%s", text);
288         Py_END_ALLOW_THREADS
289         Py_RETURN_NONE;
290 }
291
292 static PyObject *cpy_Warning(PyObject *self, PyObject *args) {
293         const char *text;
294         if (PyArg_ParseTuple(args, "s", &text) == 0) return NULL;
295         Py_BEGIN_ALLOW_THREADS
296         plugin_log(LOG_WARNING, "%s", text);
297         Py_END_ALLOW_THREADS
298         Py_RETURN_NONE;
299 }
300
301 static PyObject *cpy_Notice(PyObject *self, PyObject *args) {
302         const char *text;
303         if (PyArg_ParseTuple(args, "s", &text) == 0) return NULL;
304         Py_BEGIN_ALLOW_THREADS
305         plugin_log(LOG_NOTICE, "%s", text);
306         Py_END_ALLOW_THREADS
307         Py_RETURN_NONE;
308 }
309
310 static PyObject *cpy_Info(PyObject *self, PyObject *args) {
311         const char *text;
312         if (PyArg_ParseTuple(args, "s", &text) == 0) return NULL;
313         Py_BEGIN_ALLOW_THREADS
314         plugin_log(LOG_INFO, "%s", text);
315         Py_END_ALLOW_THREADS
316         Py_RETURN_NONE;
317 }
318
319 static PyObject *cpy_Debug(PyObject *self, PyObject *args) {
320 #ifdef COLLECT_DEBUG
321         const char *text;
322         if (PyArg_ParseTuple(args, "s", &text) == 0) return NULL;
323         plugin_log(LOG_DEBUG, "%s", text);
324 #endif
325         Py_RETURN_NONE;
326 }
327
328 static PyMethodDef cpy_methods[] = {
329         {"Debug", cpy_Debug, METH_VARARGS, "This is an unhelpful text."},
330         {"Info", cpy_Info, METH_VARARGS, "This is an unhelpful text."},
331         {"Notice", cpy_Notice, METH_VARARGS, "This is an unhelpful text."},
332         {"Warning", cpy_Warning, METH_VARARGS, "This is an unhelpful text."},
333         {"Error", cpy_Error, METH_VARARGS, "This is an unhelpful text."},
334         {"register_log", (PyCFunction) cpy_register_log, METH_VARARGS | METH_KEYWORDS, "This is an unhelpful text."},
335         {"register_init", (PyCFunction) cpy_register_init, METH_VARARGS | METH_KEYWORDS, "This is an unhelpful text."},
336         {"register_config", (PyCFunction) cpy_register_config, METH_VARARGS | METH_KEYWORDS, "This is an unhelpful text."},
337         {"register_read", (PyCFunction) cpy_register_read, METH_VARARGS | METH_KEYWORDS, "This is an unhelpful text."},
338         {"register_write", (PyCFunction) cpy_register_write, METH_VARARGS | METH_KEYWORDS, "This is an unhelpful text."},
339         {"register_shutdown", (PyCFunction) cpy_register_shutdown, METH_VARARGS | METH_KEYWORDS, "This is an unhelpful text."},
340         {0, 0, 0, 0}
341 };
342
343 static int cpy_shutdown(void) {
344         cpy_callback_t *c;
345         PyObject *ret;
346         
347         /* This can happen if the module was loaded but not configured. */
348         if (state != NULL)
349                 PyEval_RestoreThread(state);
350
351         for (c = cpy_shutdown_callbacks; c; c = c->next) {
352                 if (c->data == NULL)
353                         ret = PyObject_CallObject(c->callback, NULL); /* New reference. */
354                 else
355                         ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0); /* New reference. */
356                 if (ret == NULL)
357                         PyErr_Print(); /* FIXME */
358                 else
359                         Py_DECREF(ret);
360         }
361         Py_Finalize();
362         return 0;
363 }
364
365 static int cpy_init(void) {
366         cpy_callback_t *c;
367         PyObject *ret;
368         
369         PyEval_InitThreads();
370         /* Now it's finally OK to use python threads. */
371         for (c = cpy_init_callbacks; c; c = c->next) {
372                 if (c->data == NULL)
373                         ret = PyObject_CallObject(c->callback, NULL); /* New reference. */
374                 else
375                         ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0); /* New reference. */
376                 if (ret == NULL)
377                         PyErr_Print(); /* FIXME */
378                 else
379                         Py_DECREF(ret);
380         }
381         state = PyEval_SaveThread();
382         return 0;
383 }
384
385 static PyObject *cpy_oconfig_to_pyconfig(oconfig_item_t *ci, PyObject *parent) {
386         int i;
387         PyObject *item, *values, *children, *tmp;
388         
389         if (parent == NULL)
390                 parent = Py_None;
391         
392         values = PyTuple_New(ci->values_num); /* New reference. */
393         for (i = 0; i < ci->values_num; ++i) {
394                 if (ci->values[i].type == OCONFIG_TYPE_STRING) {
395                         PyTuple_SET_ITEM(values, i, PyString_FromString(ci->values[i].value.string));
396                 } else if (ci->values[i].type == OCONFIG_TYPE_NUMBER) {
397                         PyTuple_SET_ITEM(values, i, PyFloat_FromDouble(ci->values[i].value.number));
398                 } else if (ci->values[i].type == OCONFIG_TYPE_BOOLEAN) {
399                         PyTuple_SET_ITEM(values, i, PyBool_FromLong(ci->values[i].value.boolean));
400                 }
401         }
402         
403         item = PyObject_CallFunction((PyObject *) &ConfigType, "sONO", ci->key, parent, values, Py_None);
404         if (item == NULL)
405                 return NULL;
406         children = PyTuple_New(ci->children_num); /* New reference. */
407         for (i = 0; i < ci->children_num; ++i) {
408                         PyTuple_SET_ITEM(children, i, cpy_oconfig_to_pyconfig(ci->children + i, item));
409         }
410         tmp = ((Config *) item)->children;
411         ((Config *) item)->children = children;
412         Py_XDECREF(tmp);
413         return item;
414 }
415
416 static int cpy_config(oconfig_item_t *ci) {
417         int i;
418         PyObject *sys;
419         PyObject *sys_path;
420         PyObject *module;
421         
422         /* Ok in theory we shouldn't do initialization at this point
423          * but we have to. In order to give python scripts a chance
424          * to register a config callback we need to be able to execute
425          * python code during the config callback so we have to start
426          * the interpreter here. */
427         /* Do *not* use the python "thread" module at this point! */
428         Py_Initialize();
429         
430         PyType_Ready(&ConfigType);
431         PyType_Ready(&ValuesType);
432         sys = PyImport_ImportModule("sys"); /* New reference. */
433         if (sys == NULL) {
434                 ERROR("python module: Unable to import \"sys\" module.");
435                 /* Just print the default python exception text to stderr. */
436                 PyErr_Print();
437                 return 1;
438         }
439         sys_path = PyObject_GetAttrString(sys, "path"); /* New reference. */
440         Py_DECREF(sys);
441         if (sys_path == NULL) {
442                 ERROR("python module: Unable to read \"sys.path\".");
443                 PyErr_Print();
444                 return 1;
445         }
446         module = Py_InitModule("collectd", cpy_methods); /* Borrowed reference. */
447         PyModule_AddObject(module, "Config", (PyObject *) &ConfigType); /* Steals a reference. */
448         PyModule_AddObject(module, "Values", (PyObject *) &ValuesType); /* Steals a reference. */
449         PyModule_AddIntConstant(module, "LOG_DEBUG", LOG_DEBUG);
450         PyModule_AddIntConstant(module, "LOG_INFO", LOG_INFO);
451         PyModule_AddIntConstant(module, "LOG_NOTICE", LOG_NOTICE);
452         PyModule_AddIntConstant(module, "LOG_WARNING", LOG_WARNING);
453         PyModule_AddIntConstant(module, "LOG_ERROR", LOG_ERR);
454         for (i = 0; i < ci->children_num; ++i) {
455                 oconfig_item_t *item = ci->children + i;
456                 
457                 if (strcasecmp(item->key, "ModulePath") == 0) {
458                         char *dir = NULL;
459                         PyObject *dir_object;
460                         
461                         if (cf_util_get_string(item, &dir) != 0) 
462                                 continue;
463                         dir_object = PyString_FromString(dir); /* New reference. */
464                         if (dir_object == NULL) {
465                                 ERROR("python plugin: Unable to convert \"%s\" to "
466                                       "a python object.", dir);
467                                 free(dir);
468                                 PyErr_Print();
469                                 continue;
470                         }
471                         if (PyList_Append(sys_path, dir_object) != 0) {
472                                 ERROR("python plugin: Unable to append \"%s\" to "
473                                       "python module path.", dir);
474                                 PyErr_Print();
475                         }
476                         Py_DECREF(dir_object);
477                         free(dir);
478                 } else if (strcasecmp(item->key, "Import") == 0) {
479                         char *module_name = NULL;
480                         PyObject *module;
481                         
482                         if (cf_util_get_string(item, &module_name) != 0) 
483                                 continue;
484                         module = PyImport_ImportModule(module_name); /* New reference. */
485                         if (module == NULL) {
486                                 ERROR("python plugin: Error importing module \"%s\".", module_name);
487                                 PyErr_Print();
488                         }
489                         free(module_name);
490                         Py_XDECREF(module);
491                 } else if (strcasecmp(item->key, "Module") == 0) {
492                         char *name = NULL;
493                         cpy_callback_t *c;
494                         PyObject *ret;
495                         
496                         if (cf_util_get_string(item, &name) != 0)
497                                 continue;
498                         for (c = cpy_config_callbacks; c; c = c->next) {
499                                 if (strcasecmp(c->name, name) == 0)
500                                         break;
501                         }
502                         if (c == NULL) {
503                                 WARNING("python plugin: Found a configuration for the \"%s\" plugin, "
504                                         "but the plugin isn't loaded or didn't register "
505                                         "a configuration callback.", name);
506                                 free(name);
507                                 continue;
508                         }
509                         free(name);
510                         if (c->data == NULL)
511                                 ret = PyObject_CallFunction(c->callback, "N",
512                                         cpy_oconfig_to_pyconfig(item, NULL)); /* New reference. */
513                         else
514                                 ret = PyObject_CallFunction(c->callback, "NO",
515                                         cpy_oconfig_to_pyconfig(item, NULL), c->data); /* New reference. */
516                         if (ret == NULL)
517                                 PyErr_Print();
518                         else
519                                 Py_DECREF(ret);
520                 } else {
521                         WARNING("python plugin: Ignoring unknown config key \"%s\".", item->key);
522                 }
523         }
524         Py_DECREF(sys_path);
525         return 0;
526 }
527
528 void module_register(void) {
529         plugin_register_complex_config("python", cpy_config);
530         plugin_register_init("python", cpy_init);
531 //      plugin_register_read("python", cna_read);
532         plugin_register_shutdown("python", cpy_shutdown);
533 }