2 #include <structmember.h>
9 typedef struct cpy_callback_s {
13 struct cpy_callback_s *next;
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. */
21 static PyThreadState *state;
23 static cpy_callback_t *cpy_config_callbacks;
24 static cpy_callback_t *cpy_init_callbacks;
25 static cpy_callback_t *cpy_shutdown_callbacks;
27 static void cpy_destroy_user_data(void *data) {
28 cpy_callback_t *c = data;
30 Py_DECREF(c->callback);
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. */
38 static void cpy_build_name(char *buf, size_t size, PyObject *callback, const char *name) {
40 PyObject *mod = NULL, *n = NULL;
42 if (name != NULL && strchr(name, '.') != NULL) {
43 snprintf(buf, size, "python.%s", name);
47 mod = PyObject_GetAttrString(callback, "__module__"); /* New reference. */
49 module = PyString_AsString(mod);
53 snprintf(buf, size, "python.%s.%s", module, name);
58 n = PyObject_GetAttrString(callback, "__name__"); /* New reference. */
60 name = PyString_AsString(n);
63 snprintf(buf, size, "python.%s.%s", module, name);
65 snprintf(buf, size, "python.%s.%p", module, callback);
70 static int cpy_read_callback(user_data_t *data) {
71 cpy_callback_t *c = data->data;
76 ret = PyObject_CallFunctionObjArgs(c->callback, (void *) 0);
78 ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0);
89 static int cpy_write_callback(const data_set_t *ds, const value_list_t *value_list, user_data_t *data) {
91 cpy_callback_t *c = data->data;
92 PyObject *ret, *v, *list;
95 list = PyList_New(value_list->values_len); /* New reference. */
98 CPY_RETURN_FROM_THREADS 0;
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));
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));
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));
117 PyList_SetItem(list, i, PyLong_FromUnsignedLongLong(value_list->values[i].absolute));
119 ERROR("cpy_write_callback: Unknown value type %d.", ds->ds->type);
121 CPY_RETURN_FROM_THREADS 0;
123 if (PyErr_Occurred() != NULL) {
125 CPY_RETURN_FROM_THREADS 0;
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);
133 ret = PyObject_CallFunctionObjArgs(c->callback, v, (void *) 0);
135 ret = PyObject_CallFunctionObjArgs(c->callback, v, c->data, (void *) 0);
146 static void cpy_log_callback(int severity, const char *message, user_data_t *data) {
147 cpy_callback_t * c = data->data;
152 ret = PyObject_CallFunction(c->callback, "is", severity, message); /* New reference. */
154 ret = PyObject_CallFunction(c->callback, "isO", severity, message, c->data); /* New reference. */
165 static PyObject *cpy_register_generic(cpy_callback_t **list_head, PyObject *args, PyObject *kwds) {
167 const char *name = NULL;
168 PyObject *callback = NULL, *data = NULL, *mod = NULL;
169 static char *kwlist[] = {"callback", "data", "name", NULL};
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.");
177 mod = PyObject_GetAttrString(callback, "__module__"); /* New reference. */
178 if (mod != NULL) name = PyString_AsString(mod);
181 PyErr_SetString(PyExc_ValueError, "No module name specified and "
182 "callback function does not have a \"__module__\" attribute.");
188 c = malloc(sizeof(*c));
189 c->name = strdup(name);
190 c->callback = callback;
192 c->next = *list_head;
198 static PyObject *cpy_register_config(PyObject *self, PyObject *args, PyObject *kwds) {
199 return cpy_register_generic(&cpy_config_callbacks, args, kwds);
202 static PyObject *cpy_register_init(PyObject *self, PyObject *args, PyObject *kwds) {
203 return cpy_register_generic(&cpy_init_callbacks, args, kwds);
206 typedef int reg_function_t(const char *name, void *callback, void *data);
208 static PyObject *cpy_register_generic_userdata(void *reg, void *handler, PyObject *args, PyObject *kwds) {
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};
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.");
222 cpy_build_name(buf, sizeof(buf), callback, name);
226 c = malloc(sizeof(*c));
227 c->name = strdup(buf);
228 c->callback = callback;
231 user_data = malloc(sizeof(*user_data));
232 user_data->free_func = cpy_destroy_user_data;
234 register_function(buf, handler, user_data);
235 return PyString_FromString(buf);
238 static PyObject *cpy_register_read(PyObject *self, PyObject *args, PyObject *kwds) {
240 cpy_callback_t *c = NULL;
241 user_data_t *user_data = NULL;
243 const char *name = NULL;
244 PyObject *callback = NULL, *data = NULL;
246 static char *kwlist[] = {"callback", "interval", "data", "name", NULL};
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.");
253 cpy_build_name(buf, sizeof(buf), callback, name);
257 c = malloc(sizeof(*c));
258 c->name = strdup(buf);
259 c->callback = callback;
262 user_data = malloc(sizeof(*user_data));
263 user_data->free_func = cpy_destroy_user_data;
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);
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);
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);
279 static PyObject *cpy_register_shutdown(PyObject *self, PyObject *args, PyObject *kwds) {
280 return cpy_register_generic(&cpy_shutdown_callbacks, args, kwds);
283 static PyObject *cpy_Error(PyObject *self, PyObject *args) {
285 if (PyArg_ParseTuple(args, "s", &text) == 0) return NULL;
286 Py_BEGIN_ALLOW_THREADS
287 plugin_log(LOG_ERR, "%s", text);
292 static PyObject *cpy_Warning(PyObject *self, PyObject *args) {
294 if (PyArg_ParseTuple(args, "s", &text) == 0) return NULL;
295 Py_BEGIN_ALLOW_THREADS
296 plugin_log(LOG_WARNING, "%s", text);
301 static PyObject *cpy_Notice(PyObject *self, PyObject *args) {
303 if (PyArg_ParseTuple(args, "s", &text) == 0) return NULL;
304 Py_BEGIN_ALLOW_THREADS
305 plugin_log(LOG_NOTICE, "%s", text);
310 static PyObject *cpy_Info(PyObject *self, PyObject *args) {
312 if (PyArg_ParseTuple(args, "s", &text) == 0) return NULL;
313 Py_BEGIN_ALLOW_THREADS
314 plugin_log(LOG_INFO, "%s", text);
319 static PyObject *cpy_Debug(PyObject *self, PyObject *args) {
322 if (PyArg_ParseTuple(args, "s", &text) == 0) return NULL;
323 plugin_log(LOG_DEBUG, "%s", text);
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."},
343 static int cpy_shutdown(void) {
347 /* This can happen if the module was loaded but not configured. */
349 PyEval_RestoreThread(state);
351 for (c = cpy_shutdown_callbacks; c; c = c->next) {
353 ret = PyObject_CallObject(c->callback, NULL); /* New reference. */
355 ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0); /* New reference. */
357 PyErr_Print(); /* FIXME */
365 static int cpy_init(void) {
369 PyEval_InitThreads();
370 /* Now it's finally OK to use python threads. */
371 for (c = cpy_init_callbacks; c; c = c->next) {
373 ret = PyObject_CallObject(c->callback, NULL); /* New reference. */
375 ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0); /* New reference. */
377 PyErr_Print(); /* FIXME */
381 state = PyEval_SaveThread();
385 static PyObject *cpy_oconfig_to_pyconfig(oconfig_item_t *ci, PyObject *parent) {
387 PyObject *item, *values, *children, *tmp;
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));
403 item = PyObject_CallFunction((PyObject *) &ConfigType, "sONO", ci->key, parent, values, Py_None);
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));
410 tmp = ((Config *) item)->children;
411 ((Config *) item)->children = children;
416 static int cpy_config(oconfig_item_t *ci) {
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! */
430 PyType_Ready(&ConfigType);
431 PyType_Ready(&ValuesType);
432 sys = PyImport_ImportModule("sys"); /* New reference. */
434 ERROR("python module: Unable to import \"sys\" module.");
435 /* Just print the default python exception text to stderr. */
439 sys_path = PyObject_GetAttrString(sys, "path"); /* New reference. */
441 if (sys_path == NULL) {
442 ERROR("python module: Unable to read \"sys.path\".");
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;
457 if (strcasecmp(item->key, "ModulePath") == 0) {
459 PyObject *dir_object;
461 if (cf_util_get_string(item, &dir) != 0)
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);
471 if (PyList_Append(sys_path, dir_object) != 0) {
472 ERROR("python plugin: Unable to append \"%s\" to "
473 "python module path.", dir);
476 Py_DECREF(dir_object);
478 } else if (strcasecmp(item->key, "Import") == 0) {
479 char *module_name = NULL;
482 if (cf_util_get_string(item, &module_name) != 0)
484 module = PyImport_ImportModule(module_name); /* New reference. */
485 if (module == NULL) {
486 ERROR("python plugin: Error importing module \"%s\".", module_name);
491 } else if (strcasecmp(item->key, "Module") == 0) {
496 if (cf_util_get_string(item, &name) != 0)
498 for (c = cpy_config_callbacks; c; c = c->next) {
499 if (strcasecmp(c->name, name) == 0)
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);
511 ret = PyObject_CallFunction(c->callback, "N",
512 cpy_oconfig_to_pyconfig(item, NULL)); /* New reference. */
514 ret = PyObject_CallFunction(c->callback, "NO",
515 cpy_oconfig_to_pyconfig(item, NULL), c->data); /* New reference. */
521 WARNING("python plugin: Ignoring unknown config key \"%s\".", item->key);
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);