2 * collectd - src/python.c
3 * Copyright (C) 2009 Sven Trenkel
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
24 * Sven Trenkel <collectd at semidefinite.de>
28 #include <structmember.h>
38 typedef struct cpy_callback_s {
42 struct cpy_callback_s *next;
45 static char log_doc[] = "This function sends a string to all logging plugins.";
47 static char get_ds_doc[] = "get_dataset(name) -> definition\n"
49 "Returns the definition of a dataset specified by name.\n"
51 "'name' is a string specifying the dataset to query.\n"
52 "'definition' is a list of 4-tuples. Every tuple represents a \n"
53 " data source within the data set and its 4 values are the \n"
54 " name, type, min and max value.\n"
55 " 'name' is a string.\n"
56 " 'type' is a string that is equal to either DS_TYPE_COUNTER,\n"
57 " DS_TYPE_GAUGE, DS_TYPE_DERIVE or DS_TYPE_ABSOLUTE.\n"
58 " 'min' and 'max' are either a float or None.";
60 static char flush_doc[] = "flush([plugin][, timeout][, identifier]) -> None\n"
62 "Flushes the cache of another plugin.";
64 static char unregister_doc[] = "Unregisters a callback. This function needs exactly one parameter either\n"
65 "the function to unregister or the callback identifier to unregister.";
67 static char reg_log_doc[] = "register_log(callback[, data][, name]) -> identifier\n"
69 "Register a callback function for log messages.\n"
71 "'callback' is a callable object that will be called every time something\n"
73 "'data' is an optional object that will be passed back to the callback\n"
74 " function every time it is called.\n"
75 "'name' is an optional identifier for this callback. The default name\n"
76 " is 'python.<module>'.\n"
77 " Every callback needs a unique identifier, so if you want to\n"
78 " register this callback multiple time from the same module you need\n"
79 " to specify a name here.\n"
80 "'identifier' is the full identifier assigned to this callback.\n"
82 "The callback function will be called with two or three parameters:\n"
83 "severity: An integer that should be compared to the LOG_ constants.\n"
84 "message: The text to be logged.\n"
85 "data: The optional data parameter passed to the register function.\n"
86 " If the parameter was omitted it will be omitted here, too.";
88 static char reg_init_doc[] = "register_init(callback[, data][, name]) -> identifier\n"
90 "Register a callback function that will be executed once after the config.\n"
91 "file has been read, all plugins heve been loaded and the collectd has\n"
92 "forked into the background.\n"
94 "'callback' is a callable object that will be executed.\n"
95 "'data' is an optional object that will be passed back to the callback\n"
96 " function when it is called.\n"
97 "'name' is an optional identifier for this callback. The default name\n"
98 " is 'python.<module>'.\n"
99 " Every callback needs a unique identifier, so if you want to\n"
100 " register this callback multiple time from the same module you need\n"
101 " to specify a name here.\n"
102 "'identifier' is the full identifier assigned to this callback.\n"
104 "The callback function will be called without parameters, except for\n"
105 "data if it was supplied.";
107 static char reg_config_doc[] = "register_config(callback[, data][, name]) -> identifier\n"
109 "Register a callback function for config file entries.\n"
110 "'callback' is a callable object that will be called for every config block.\n"
111 "'data' is an optional object that will be passed back to the callback\n"
112 " function every time it is called.\n"
113 "'name' is an optional identifier for this callback. The default name\n"
114 " is 'python.<module>'.\n"
115 " Every callback needs a unique identifier, so if you want to\n"
116 " register this callback multiple time from the same module you need\n"
117 " to specify a name here.\n"
118 "'identifier' is the full identifier assigned to this callback.\n"
120 "The callback function will be called with one or two parameters:\n"
121 "config: A Config object.\n"
122 "data: The optional data parameter passed to the register function.\n"
123 " If the parameter was omitted it will be omitted here, too.";
125 static char reg_read_doc[] = "register_read(callback[, interval][, data][, name]) -> identifier\n"
127 "Register a callback function for reading data. It will just be called\n"
128 "in a fixed interval to signal that it's time to dispatch new values.\n"
129 "'callback' is a callable object that will be called every time something\n"
131 "'interval' is the number of seconds between between calls to the callback\n"
132 " function. Full float precision is supported here.\n"
133 "'data' is an optional object that will be passed back to the callback\n"
134 " function every time it is called.\n"
135 "'name' is an optional identifier for this callback. The default name\n"
136 " is 'python.<module>'.\n"
137 " Every callback needs a unique identifier, so if you want to\n"
138 " register this callback multiple time from the same module you need\n"
139 " to specify a name here.\n"
140 "'identifier' is the full identifier assigned to this callback.\n"
142 "The callback function will be called without parameters, except for\n"
143 "data if it was supplied.";
145 static char reg_write_doc[] = "register_write(callback[, data][, name]) -> identifier\n"
147 "Register a callback function to receive values dispatched by other plugins.\n"
148 "'callback' is a callable object that will be called every time a value\n"
150 "'data' is an optional object that will be passed back to the callback\n"
151 " function every time it is called.\n"
152 "'name' is an optional identifier for this callback. The default name\n"
153 " is 'python.<module>'.\n"
154 " Every callback needs a unique identifier, so if you want to\n"
155 " register this callback multiple time from the same module you need\n"
156 " to specify a name here.\n"
157 "'identifier' is the full identifier assigned to this callback.\n"
159 "The callback function will be called with one or two parameters:\n"
160 "values: A Values object which is a copy of the dispatched values.\n"
161 "data: The optional data parameter passed to the register function.\n"
162 " If the parameter was omitted it will be omitted here, too.";
164 static char reg_notification_doc[] = "register_notification(callback[, data][, name]) -> identifier\n"
166 "Register a callback function for notifications.\n"
167 "'callback' is a callable object that will be called every time a notification\n"
169 "'data' is an optional object that will be passed back to the callback\n"
170 " function every time it is called.\n"
171 "'name' is an optional identifier for this callback. The default name\n"
172 " is 'python.<module>'.\n"
173 " Every callback needs a unique identifier, so if you want to\n"
174 " register this callback multiple time from the same module you need\n"
175 " to specify a name here.\n"
176 "'identifier' is the full identifier assigned to this callback.\n"
178 "The callback function will be called with one or two parameters:\n"
179 "notification: A copy of the notification that was dispatched.\n"
180 "data: The optional data parameter passed to the register function.\n"
181 " If the parameter was omitted it will be omitted here, too.";
183 static char reg_flush_doc[] = "register_flush(callback[, data][, name]) -> identifier\n"
185 "Register a callback function for flush messages.\n"
186 "'callback' is a callable object that will be called every time a plugin\n"
187 " requests a flush for either this or all plugins.\n"
188 "'data' is an optional object that will be passed back to the callback\n"
189 " function every time it is called.\n"
190 "'name' is an optional identifier for this callback. The default name\n"
191 " is 'python.<module>'.\n"
192 " Every callback needs a unique identifier, so if you want to\n"
193 " register this callback multiple time from the same module you need\n"
194 " to specify a name here.\n"
195 "'identifier' is the full identifier assigned to this callback.\n"
197 "The callback function will be called with two or three parameters:\n"
198 "timeout: Indicates that only data older than 'timeout' seconds is to\n"
200 "id: Specifies which values are to be flushed.\n"
201 "data: The optional data parameter passed to the register function.\n"
202 " If the parameter was omitted it will be omitted here, too.";
204 static char reg_shutdown_doc[] = "register_shutdown(callback[, data][, name]) -> identifier\n"
206 "Register a callback function for collectd shutdown.\n"
207 "'callback' is a callable object that will be called once collectd is\n"
209 "'data' is an optional object that will be passed back to the callback\n"
210 " function if it is called.\n"
211 "'name' is an optional identifier for this callback. The default name\n"
212 " is 'python.<module>'.\n"
213 " Every callback needs a unique identifier, so if you want to\n"
214 " register this callback multiple time from the same module you need\n"
215 " to specify a name here.\n"
216 "'identifier' is the full identifier assigned to this callback.\n"
218 "The callback function will be called with no parameters except for\n"
219 " data if it was supplied.";
222 static int do_interactive = 0;
224 /* This is our global thread state. Python saves some stuff in thread-local
225 * storage. So if we allow the interpreter to run in the background
226 * (the scriptwriters might have created some threads from python), we have
227 * to save the state so we can resume it later after shutdown. */
229 static PyThreadState *state;
231 static PyObject *sys_path, *cpy_format_exception;
233 static cpy_callback_t *cpy_config_callbacks;
234 static cpy_callback_t *cpy_init_callbacks;
235 static cpy_callback_t *cpy_shutdown_callbacks;
237 static void cpy_destroy_user_data(void *data) {
238 cpy_callback_t *c = data;
240 Py_DECREF(c->callback);
245 /* You must hold the GIL to call this function!
246 * But if you managed to extract the callback parameter then you probably already do. */
248 static void cpy_build_name(char *buf, size_t size, PyObject *callback, const char *name) {
249 const char *module = NULL;
250 PyObject *mod = NULL;
253 snprintf(buf, size, "python.%s", name);
257 mod = PyObject_GetAttrString(callback, "__module__"); /* New reference. */
259 module = cpy_unicode_or_bytes_to_string(&mod);
261 if (module != NULL) {
262 snprintf(buf, size, "python.%s", module);
269 snprintf(buf, size, "python.%p", callback);
273 void cpy_log_exception(const char *context) {
275 const char *typename = NULL, *message = NULL;
276 PyObject *type, *value, *traceback, *tn, *m, *list;
278 PyErr_Fetch(&type, &value, &traceback);
279 PyErr_NormalizeException(&type, &value, &traceback);
280 if (type == NULL) return;
281 tn = PyObject_GetAttrString(type, "__name__"); /* New reference. */
282 m = PyObject_Str(value); /* New reference. */
284 typename = cpy_unicode_or_bytes_to_string(&tn);
286 message = cpy_unicode_or_bytes_to_string(&m);
287 if (typename == NULL)
288 typename = "NamelessException";
291 Py_BEGIN_ALLOW_THREADS
292 ERROR("Unhandled python exception in %s: %s: %s", context, typename, message);
296 if (!cpy_format_exception || !traceback) {
300 Py_XDECREF(traceback);
303 list = PyObject_CallFunction(cpy_format_exception, "NNN", type, value, traceback); /* New reference. Steals references from "type", "value" and "traceback". */
305 l = PyObject_Length(list);
307 for (i = 0; i < l; ++i) {
312 line = PyList_GET_ITEM(list, i); /* Borrowed reference. */
315 msg = cpy_unicode_or_bytes_to_string(&line);
324 if (cpy[strlen(cpy) - 1] == '\n')
325 cpy[strlen(cpy) - 1] = 0;
327 Py_BEGIN_ALLOW_THREADS
338 static int cpy_read_callback(user_data_t *data) {
339 cpy_callback_t *c = data->data;
343 ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0); /* New reference. */
345 cpy_log_exception("read callback");
355 static int cpy_write_callback(const data_set_t *ds, const value_list_t *value_list, user_data_t *data) {
357 cpy_callback_t *c = data->data;
358 PyObject *ret, *list, *temp, *dict = NULL;
362 list = PyList_New(value_list->values_len); /* New reference. */
364 cpy_log_exception("write callback");
365 CPY_RETURN_FROM_THREADS 0;
367 for (i = 0; i < value_list->values_len; ++i) {
368 if (ds->ds[i].type == DS_TYPE_COUNTER) {
369 PyList_SetItem(list, i, PyLong_FromUnsignedLongLong(value_list->values[i].counter));
370 } else if (ds->ds[i].type == DS_TYPE_GAUGE) {
371 PyList_SetItem(list, i, PyFloat_FromDouble(value_list->values[i].gauge));
372 } else if (ds->ds[i].type == DS_TYPE_DERIVE) {
373 PyList_SetItem(list, i, PyLong_FromLongLong(value_list->values[i].derive));
374 } else if (ds->ds[i].type == DS_TYPE_ABSOLUTE) {
375 PyList_SetItem(list, i, PyLong_FromUnsignedLongLong(value_list->values[i].absolute));
377 Py_BEGIN_ALLOW_THREADS
378 ERROR("cpy_write_callback: Unknown value type %d.", ds->ds[i].type);
381 CPY_RETURN_FROM_THREADS 0;
383 if (PyErr_Occurred() != NULL) {
384 cpy_log_exception("value building for write callback");
386 CPY_RETURN_FROM_THREADS 0;
389 dict = PyDict_New(); /* New reference. */
390 if (value_list->meta) {
393 meta_data_t *meta = value_list->meta;
395 num = meta_data_toc(meta, &table);
396 for (i = 0; i < num; ++i) {
404 type = meta_data_type(meta, table[i]);
405 if (type == MD_TYPE_STRING) {
406 if (meta_data_get_string(meta, table[i], &string))
408 temp = cpy_string_to_unicode_or_bytes(string); /* New reference. */
410 PyDict_SetItemString(dict, table[i], temp);
412 } else if (type == MD_TYPE_SIGNED_INT) {
413 if (meta_data_get_signed_int(meta, table[i], &si))
415 temp = PyObject_CallFunctionObjArgs((void *) &SignedType, PyLong_FromLongLong(si), (void *) 0); /* New reference. */
416 PyDict_SetItemString(dict, table[i], temp);
418 } else if (type == MD_TYPE_UNSIGNED_INT) {
419 if (meta_data_get_unsigned_int(meta, table[i], &ui))
421 temp = PyObject_CallFunctionObjArgs((void *) &UnsignedType, PyLong_FromUnsignedLongLong(ui), (void *) 0); /* New reference. */
422 PyDict_SetItemString(dict, table[i], temp);
424 } else if (type == MD_TYPE_DOUBLE) {
425 if (meta_data_get_double(meta, table[i], &d))
427 temp = PyFloat_FromDouble(d); /* New reference. */
428 PyDict_SetItemString(dict, table[i], temp);
430 } else if (type == MD_TYPE_BOOLEAN) {
431 if (meta_data_get_boolean(meta, table[i], &b))
434 PyDict_SetItemString(dict, table[i], Py_True);
436 PyDict_SetItemString(dict, table[i], Py_False);
442 v = (Values *) Values_New(); /* New reference. */
443 sstrncpy(v->data.host, value_list->host, sizeof(v->data.host));
444 sstrncpy(v->data.type, value_list->type, sizeof(v->data.type));
445 sstrncpy(v->data.type_instance, value_list->type_instance, sizeof(v->data.type_instance));
446 sstrncpy(v->data.plugin, value_list->plugin, sizeof(v->data.plugin));
447 sstrncpy(v->data.plugin_instance, value_list->plugin_instance, sizeof(v->data.plugin_instance));
448 v->data.time = CDTIME_T_TO_DOUBLE(value_list->time);
449 v->interval = CDTIME_T_TO_DOUBLE(value_list->interval);
453 v->meta = dict; /* Steals a reference. */
454 ret = PyObject_CallFunctionObjArgs(c->callback, v, c->data, (void *) 0); /* New reference. */
457 cpy_log_exception("write callback");
465 static int cpy_notification_callback(const notification_t *notification, user_data_t *data) {
466 cpy_callback_t *c = data->data;
467 PyObject *ret, *notify;
471 notify = Notification_New(); /* New reference. */
472 n = (Notification *) notify;
473 sstrncpy(n->data.host, notification->host, sizeof(n->data.host));
474 sstrncpy(n->data.type, notification->type, sizeof(n->data.type));
475 sstrncpy(n->data.type_instance, notification->type_instance, sizeof(n->data.type_instance));
476 sstrncpy(n->data.plugin, notification->plugin, sizeof(n->data.plugin));
477 sstrncpy(n->data.plugin_instance, notification->plugin_instance, sizeof(n->data.plugin_instance));
478 n->data.time = CDTIME_T_TO_DOUBLE(notification->time);
479 sstrncpy(n->message, notification->message, sizeof(n->message));
480 n->severity = notification->severity;
481 ret = PyObject_CallFunctionObjArgs(c->callback, n, c->data, (void *) 0); /* New reference. */
484 cpy_log_exception("notification callback");
492 static void cpy_log_callback(int severity, const char *message, user_data_t *data) {
493 cpy_callback_t * c = data->data;
494 PyObject *ret, *text;
497 text = cpy_string_to_unicode_or_bytes(message); /* New reference. */
499 ret = PyObject_CallFunction(c->callback, "iN", severity, text); /* New reference. Steals a reference from "text". */
501 ret = PyObject_CallFunction(c->callback, "iNO", severity, text, c->data); /* New reference. Steals a reference from "text". */
505 /* Do we really want to trigger a log callback because a log callback failed?
508 /* In case someone wanted to be clever, replaced stderr and failed at that. */
516 static void cpy_flush_callback(int timeout, const char *id, user_data_t *data) {
517 cpy_callback_t * c = data->data;
518 PyObject *ret, *text;
521 text = cpy_string_to_unicode_or_bytes(id);
523 ret = PyObject_CallFunction(c->callback, "iN", timeout, text); /* New reference. */
525 ret = PyObject_CallFunction(c->callback, "iNO", timeout, text, c->data); /* New reference. */
528 cpy_log_exception("flush callback");
535 static PyObject *cpy_register_generic(cpy_callback_t **list_head, PyObject *args, PyObject *kwds) {
539 PyObject *callback = NULL, *data = NULL, *mod = NULL;
540 static char *kwlist[] = {"callback", "data", "name", NULL};
542 if (PyArg_ParseTupleAndKeywords(args, kwds, "O|Oet", kwlist, &callback, &data, NULL, &name) == 0) return NULL;
543 if (PyCallable_Check(callback) == 0) {
545 PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
548 cpy_build_name(buf, sizeof(buf), callback, name);
553 c = calloc(1, sizeof(*c));
557 c->name = strdup(buf);
558 c->callback = callback;
560 c->next = *list_head;
564 return cpy_string_to_unicode_or_bytes(buf);
567 static PyObject *float_or_none(float number) {
571 return PyFloat_FromDouble(number);
574 static PyObject *cpy_get_dataset(PyObject *self, PyObject *args) {
577 const data_set_t *ds;
578 PyObject *list, *tuple;
580 if (PyArg_ParseTuple(args, "et", NULL, &name) == 0) return NULL;
581 ds = plugin_get_ds(name);
584 PyErr_Format(PyExc_TypeError, "Dataset %s not found", name);
587 list = PyList_New(ds->ds_num); /* New reference. */
588 for (i = 0; i < ds->ds_num; ++i) {
589 tuple = PyTuple_New(4);
590 PyTuple_SET_ITEM(tuple, 0, cpy_string_to_unicode_or_bytes(ds->ds[i].name));
591 PyTuple_SET_ITEM(tuple, 1, cpy_string_to_unicode_or_bytes(DS_TYPE_TO_STRING(ds->ds[i].type)));
592 PyTuple_SET_ITEM(tuple, 2, float_or_none(ds->ds[i].min));
593 PyTuple_SET_ITEM(tuple, 3, float_or_none(ds->ds[i].max));
594 PyList_SET_ITEM(list, i, tuple);
599 static PyObject *cpy_flush(PyObject *self, PyObject *args, PyObject *kwds) {
601 char *plugin = NULL, *identifier = NULL;
602 static char *kwlist[] = {"plugin", "timeout", "identifier", NULL};
604 if (PyArg_ParseTupleAndKeywords(args, kwds, "|etiet", kwlist, NULL, &plugin, &timeout, NULL, &identifier) == 0) return NULL;
605 Py_BEGIN_ALLOW_THREADS
606 plugin_flush(plugin, timeout, identifier);
609 PyMem_Free(identifier);
613 static PyObject *cpy_register_config(PyObject *self, PyObject *args, PyObject *kwds) {
614 return cpy_register_generic(&cpy_config_callbacks, args, kwds);
617 static PyObject *cpy_register_init(PyObject *self, PyObject *args, PyObject *kwds) {
618 return cpy_register_generic(&cpy_init_callbacks, args, kwds);
621 typedef int reg_function_t(const char *name, void *callback, void *data);
623 static PyObject *cpy_register_generic_userdata(void *reg, void *handler, PyObject *args, PyObject *kwds) {
625 reg_function_t *register_function = (reg_function_t *) reg;
626 cpy_callback_t *c = NULL;
627 user_data_t user_data = { 0 };
629 PyObject *callback = NULL, *data = NULL;
630 static char *kwlist[] = {"callback", "data", "name", NULL};
632 if (PyArg_ParseTupleAndKeywords(args, kwds, "O|Oet", kwlist, &callback, &data, NULL, &name) == 0) return NULL;
633 if (PyCallable_Check(callback) == 0) {
635 PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
638 cpy_build_name(buf, sizeof(buf), callback, name);
644 c = calloc(1, sizeof(*c));
648 c->name = strdup(buf);
649 c->callback = callback;
653 user_data.free_func = cpy_destroy_user_data;
656 register_function(buf, handler, &user_data);
657 return cpy_string_to_unicode_or_bytes(buf);
660 static PyObject *cpy_register_read(PyObject *self, PyObject *args, PyObject *kwds) {
662 cpy_callback_t *c = NULL;
663 user_data_t user_data = { 0 };
666 PyObject *callback = NULL, *data = NULL;
667 static char *kwlist[] = {"callback", "interval", "data", "name", NULL};
669 if (PyArg_ParseTupleAndKeywords(args, kwds, "O|dOet", kwlist, &callback, &interval, &data, NULL, &name) == 0) return NULL;
670 if (PyCallable_Check(callback) == 0) {
672 PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
675 cpy_build_name(buf, sizeof(buf), callback, name);
681 c = calloc(1, sizeof(*c));
685 c->name = strdup(buf);
686 c->callback = callback;
690 user_data.free_func = cpy_destroy_user_data;
693 plugin_register_complex_read(/* group = */ "python", buf,
694 cpy_read_callback, DOUBLE_TO_CDTIME_T (interval), &user_data);
695 return cpy_string_to_unicode_or_bytes(buf);
698 static PyObject *cpy_register_log(PyObject *self, PyObject *args, PyObject *kwds) {
699 return cpy_register_generic_userdata((void *) plugin_register_log,
700 (void *) cpy_log_callback, args, kwds);
703 static PyObject *cpy_register_write(PyObject *self, PyObject *args, PyObject *kwds) {
704 return cpy_register_generic_userdata((void *) plugin_register_write,
705 (void *) cpy_write_callback, args, kwds);
708 static PyObject *cpy_register_notification(PyObject *self, PyObject *args, PyObject *kwds) {
709 return cpy_register_generic_userdata((void *) plugin_register_notification,
710 (void *) cpy_notification_callback, args, kwds);
713 static PyObject *cpy_register_flush(PyObject *self, PyObject *args, PyObject *kwds) {
714 return cpy_register_generic_userdata((void *) plugin_register_flush,
715 (void *) cpy_flush_callback, args, kwds);
718 static PyObject *cpy_register_shutdown(PyObject *self, PyObject *args, PyObject *kwds) {
719 return cpy_register_generic(&cpy_shutdown_callbacks, args, kwds);
722 static PyObject *cpy_error(PyObject *self, PyObject *args) {
724 if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
725 Py_BEGIN_ALLOW_THREADS
726 plugin_log(LOG_ERR, "%s", text);
732 static PyObject *cpy_warning(PyObject *self, PyObject *args) {
734 if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
735 Py_BEGIN_ALLOW_THREADS
736 plugin_log(LOG_WARNING, "%s", text);
742 static PyObject *cpy_notice(PyObject *self, PyObject *args) {
744 if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
745 Py_BEGIN_ALLOW_THREADS
746 plugin_log(LOG_NOTICE, "%s", text);
752 static PyObject *cpy_info(PyObject *self, PyObject *args) {
754 if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
755 Py_BEGIN_ALLOW_THREADS
756 plugin_log(LOG_INFO, "%s", text);
762 static PyObject *cpy_debug(PyObject *self, PyObject *args) {
765 if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
766 Py_BEGIN_ALLOW_THREADS
767 plugin_log(LOG_DEBUG, "%s", text);
774 static PyObject *cpy_unregister_generic(cpy_callback_t **list_head, PyObject *arg, const char *desc) {
777 cpy_callback_t *prev = NULL, *tmp;
780 name = cpy_unicode_or_bytes_to_string(&arg);
783 if (!PyCallable_Check(arg)) {
784 PyErr_SetString(PyExc_TypeError, "This function needs a string or a callable object as its only parameter.");
788 cpy_build_name(buf, sizeof(buf), arg, NULL);
791 for (tmp = *list_head; tmp; prev = tmp, tmp = tmp->next)
792 if (strcmp(name, tmp->name) == 0)
797 PyErr_Format(PyExc_RuntimeError, "Unable to unregister %s callback '%s'.", desc, name);
800 /* Yes, this is actually save. To call this function the caller has to
801 * hold the GIL. Well, save as long as there is only one GIL anyway ... */
803 *list_head = tmp->next;
805 prev->next = tmp->next;
806 cpy_destroy_user_data(tmp);
810 typedef int cpy_unregister_function_t(const char *name);
812 static PyObject *cpy_unregister_generic_userdata(cpy_unregister_function_t *unreg, PyObject *arg, const char *desc) {
817 name = cpy_unicode_or_bytes_to_string(&arg);
820 if (!PyCallable_Check(arg)) {
821 PyErr_SetString(PyExc_TypeError, "This function needs a string or a callable object as its only parameter.");
825 cpy_build_name(buf, sizeof(buf), arg, NULL);
828 if (unreg(name) == 0) {
832 PyErr_Format(PyExc_RuntimeError, "Unable to unregister %s callback '%s'.", desc, name);
837 static PyObject *cpy_unregister_log(PyObject *self, PyObject *arg) {
838 return cpy_unregister_generic_userdata(plugin_unregister_log, arg, "log");
841 static PyObject *cpy_unregister_init(PyObject *self, PyObject *arg) {
842 return cpy_unregister_generic(&cpy_init_callbacks, arg, "init");
845 static PyObject *cpy_unregister_config(PyObject *self, PyObject *arg) {
846 return cpy_unregister_generic(&cpy_config_callbacks, arg, "config");
849 static PyObject *cpy_unregister_read(PyObject *self, PyObject *arg) {
850 return cpy_unregister_generic_userdata(plugin_unregister_read, arg, "read");
853 static PyObject *cpy_unregister_write(PyObject *self, PyObject *arg) {
854 return cpy_unregister_generic_userdata(plugin_unregister_write, arg, "write");
857 static PyObject *cpy_unregister_notification(PyObject *self, PyObject *arg) {
858 return cpy_unregister_generic_userdata(plugin_unregister_notification, arg, "notification");
861 static PyObject *cpy_unregister_flush(PyObject *self, PyObject *arg) {
862 return cpy_unregister_generic_userdata(plugin_unregister_flush, arg, "flush");
865 static PyObject *cpy_unregister_shutdown(PyObject *self, PyObject *arg) {
866 return cpy_unregister_generic(&cpy_shutdown_callbacks, arg, "shutdown");
869 static PyMethodDef cpy_methods[] = {
870 {"debug", cpy_debug, METH_VARARGS, log_doc},
871 {"info", cpy_info, METH_VARARGS, log_doc},
872 {"notice", cpy_notice, METH_VARARGS, log_doc},
873 {"warning", cpy_warning, METH_VARARGS, log_doc},
874 {"error", cpy_error, METH_VARARGS, log_doc},
875 {"get_dataset", (PyCFunction) cpy_get_dataset, METH_VARARGS, get_ds_doc},
876 {"flush", (PyCFunction) cpy_flush, METH_VARARGS | METH_KEYWORDS, flush_doc},
877 {"register_log", (PyCFunction) cpy_register_log, METH_VARARGS | METH_KEYWORDS, reg_log_doc},
878 {"register_init", (PyCFunction) cpy_register_init, METH_VARARGS | METH_KEYWORDS, reg_init_doc},
879 {"register_config", (PyCFunction) cpy_register_config, METH_VARARGS | METH_KEYWORDS, reg_config_doc},
880 {"register_read", (PyCFunction) cpy_register_read, METH_VARARGS | METH_KEYWORDS, reg_read_doc},
881 {"register_write", (PyCFunction) cpy_register_write, METH_VARARGS | METH_KEYWORDS, reg_write_doc},
882 {"register_notification", (PyCFunction) cpy_register_notification, METH_VARARGS | METH_KEYWORDS, reg_notification_doc},
883 {"register_flush", (PyCFunction) cpy_register_flush, METH_VARARGS | METH_KEYWORDS, reg_flush_doc},
884 {"register_shutdown", (PyCFunction) cpy_register_shutdown, METH_VARARGS | METH_KEYWORDS, reg_shutdown_doc},
885 {"unregister_log", cpy_unregister_log, METH_O, unregister_doc},
886 {"unregister_init", cpy_unregister_init, METH_O, unregister_doc},
887 {"unregister_config", cpy_unregister_config, METH_O, unregister_doc},
888 {"unregister_read", cpy_unregister_read, METH_O, unregister_doc},
889 {"unregister_write", cpy_unregister_write, METH_O, unregister_doc},
890 {"unregister_notification", cpy_unregister_notification, METH_O, unregister_doc},
891 {"unregister_flush", cpy_unregister_flush, METH_O, unregister_doc},
892 {"unregister_shutdown", cpy_unregister_shutdown, METH_O, unregister_doc},
896 static int cpy_shutdown(void) {
900 /* This can happen if the module was loaded but not configured. */
902 PyEval_RestoreThread(state);
904 for (c = cpy_shutdown_callbacks; c; c = c->next) {
905 ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0); /* New reference. */
907 cpy_log_exception("shutdown callback");
916 static void cpy_int_handler(int sig) {
920 static void *cpy_interactive(void *data) {
922 struct sigaction old;
924 /* Signal handler in a plugin? Bad stuff, but the best way to
925 * handle it I guess. In an interactive session people will
926 * press Ctrl+C at some time, which will generate a SIGINT.
927 * This will cause collectd to shutdown, thus killing the
928 * interactive interpreter, and leaving the terminal in a
929 * mess. Chances are, this isn't what the user wanted to do.
931 * So this is the plan:
932 * 1. Block SIGINT in the main thread.
933 * 2. Install our own signal handler that does nothing.
934 * 3. Unblock SIGINT in the interactive thread.
936 * This will make sure that SIGINT won't kill collectd but
937 * still interrupt syscalls like sleep and pause.
938 * It does not raise a KeyboardInterrupt exception because so
939 * far nobody managed to figure out how to do that. */
940 struct sigaction sig_int_action = {
941 .sa_handler = cpy_int_handler
943 sigaction (SIGINT, &sig_int_action, &old);
945 sigemptyset(&sigset);
946 sigaddset(&sigset, SIGINT);
947 pthread_sigmask(SIG_UNBLOCK, &sigset, NULL);
948 PyEval_AcquireThread(state);
949 if (PyImport_ImportModule("readline") == NULL) {
950 /* This interactive session will suck. */
951 cpy_log_exception("interactive session init");
953 PyRun_InteractiveLoop(stdin, "<stdin>");
955 PyEval_ReleaseThread(state);
956 NOTICE("python: Interactive interpreter exited, stopping collectd ...");
957 /* Restore the original collectd SIGINT handler and raise SIGINT.
958 * The main thread still has SIGINT blocked and there's nothing we
959 * can do about that so this thread will handle it. But that's not
960 * important, except that it won't interrupt the main loop and so
961 * it might take a few seconds before collectd really shuts down. */
962 sigaction (SIGINT, &old, NULL);
968 static int cpy_init(void) {
971 static pthread_t thread;
974 if (!Py_IsInitialized()) {
975 WARNING("python: Plugin loaded but not configured.");
976 plugin_unregister_shutdown("python");
979 PyEval_InitThreads();
980 /* Now it's finally OK to use python threads. */
981 for (c = cpy_init_callbacks; c; c = c->next) {
982 ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0); /* New reference. */
984 cpy_log_exception("init callback");
988 sigemptyset(&sigset);
989 sigaddset(&sigset, SIGINT);
990 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
991 state = PyEval_SaveThread();
992 if (do_interactive) {
993 if (plugin_thread_create(&thread, NULL, cpy_interactive, NULL)) {
994 ERROR("python: Error creating thread for interactive interpreter.");
1001 static PyObject *cpy_oconfig_to_pyconfig(oconfig_item_t *ci, PyObject *parent) {
1003 PyObject *item, *values, *children, *tmp;
1008 values = PyTuple_New(ci->values_num); /* New reference. */
1009 for (i = 0; i < ci->values_num; ++i) {
1010 if (ci->values[i].type == OCONFIG_TYPE_STRING) {
1011 PyTuple_SET_ITEM(values, i, cpy_string_to_unicode_or_bytes(ci->values[i].value.string));
1012 } else if (ci->values[i].type == OCONFIG_TYPE_NUMBER) {
1013 PyTuple_SET_ITEM(values, i, PyFloat_FromDouble(ci->values[i].value.number));
1014 } else if (ci->values[i].type == OCONFIG_TYPE_BOOLEAN) {
1015 PyTuple_SET_ITEM(values, i, PyBool_FromLong(ci->values[i].value.boolean));
1019 tmp = cpy_string_to_unicode_or_bytes(ci->key);
1020 item = PyObject_CallFunction((void *) &ConfigType, "NONO", tmp, parent, values, Py_None);
1023 children = PyTuple_New(ci->children_num); /* New reference. */
1024 for (i = 0; i < ci->children_num; ++i) {
1025 PyTuple_SET_ITEM(children, i, cpy_oconfig_to_pyconfig(ci->children + i, item));
1027 tmp = ((Config *) item)->children;
1028 ((Config *) item)->children = children;
1034 static struct PyModuleDef collectdmodule = {
1035 PyModuleDef_HEAD_INIT,
1036 "collectd", /* name of module */
1037 "The python interface to collectd", /* module documentation, may be NULL */
1042 PyMODINIT_FUNC PyInit_collectd(void) {
1043 return PyModule_Create(&collectdmodule);
1047 static int cpy_init_python(void) {
1052 wchar_t *argv = L"";
1053 /* Add a builtin module, before Py_Initialize */
1054 PyImport_AppendInittab("collectd", PyInit_collectd);
1061 PyType_Ready(&ConfigType);
1062 PyType_Ready(&PluginDataType);
1063 ValuesType.tp_base = &PluginDataType;
1064 PyType_Ready(&ValuesType);
1065 NotificationType.tp_base = &PluginDataType;
1066 PyType_Ready(&NotificationType);
1067 SignedType.tp_base = &PyLong_Type;
1068 PyType_Ready(&SignedType);
1069 UnsignedType.tp_base = &PyLong_Type;
1070 PyType_Ready(&UnsignedType);
1071 sys = PyImport_ImportModule("sys"); /* New reference. */
1073 cpy_log_exception("python initialization");
1076 sys_path = PyObject_GetAttrString(sys, "path"); /* New reference. */
1078 if (sys_path == NULL) {
1079 cpy_log_exception("python initialization");
1082 PySys_SetArgv(1, &argv);
1083 PyList_SetSlice(sys_path, 0, 1, NULL);
1086 module = PyImport_ImportModule("collectd");
1088 module = Py_InitModule("collectd", cpy_methods); /* Borrowed reference. */
1090 PyModule_AddObject(module, "Config", (void *) &ConfigType); /* Steals a reference. */
1091 PyModule_AddObject(module, "Values", (void *) &ValuesType); /* Steals a reference. */
1092 PyModule_AddObject(module, "Notification", (void *) &NotificationType); /* Steals a reference. */
1093 PyModule_AddObject(module, "Signed", (void *) &SignedType); /* Steals a reference. */
1094 PyModule_AddObject(module, "Unsigned", (void *) &UnsignedType); /* Steals a reference. */
1095 PyModule_AddIntConstant(module, "LOG_DEBUG", LOG_DEBUG);
1096 PyModule_AddIntConstant(module, "LOG_INFO", LOG_INFO);
1097 PyModule_AddIntConstant(module, "LOG_NOTICE", LOG_NOTICE);
1098 PyModule_AddIntConstant(module, "LOG_WARNING", LOG_WARNING);
1099 PyModule_AddIntConstant(module, "LOG_ERROR", LOG_ERR);
1100 PyModule_AddIntConstant(module, "NOTIF_FAILURE", NOTIF_FAILURE);
1101 PyModule_AddIntConstant(module, "NOTIF_WARNING", NOTIF_WARNING);
1102 PyModule_AddIntConstant(module, "NOTIF_OKAY", NOTIF_OKAY);
1103 PyModule_AddStringConstant(module, "DS_TYPE_COUNTER", DS_TYPE_TO_STRING(DS_TYPE_COUNTER));
1104 PyModule_AddStringConstant(module, "DS_TYPE_GAUGE", DS_TYPE_TO_STRING(DS_TYPE_GAUGE));
1105 PyModule_AddStringConstant(module, "DS_TYPE_DERIVE", DS_TYPE_TO_STRING(DS_TYPE_DERIVE));
1106 PyModule_AddStringConstant(module, "DS_TYPE_ABSOLUTE", DS_TYPE_TO_STRING(DS_TYPE_ABSOLUTE));
1110 static int cpy_config(oconfig_item_t *ci) {
1114 /* Ok in theory we shouldn't do initialization at this point
1115 * but we have to. In order to give python scripts a chance
1116 * to register a config callback we need to be able to execute
1117 * python code during the config callback so we have to start
1118 * the interpreter here. */
1119 /* Do *not* use the python "thread" module at this point! */
1121 if (!Py_IsInitialized() && cpy_init_python()) return 1;
1123 for (i = 0; i < ci->children_num; ++i) {
1124 oconfig_item_t *item = ci->children + i;
1126 if (strcasecmp(item->key, "Interactive") == 0) {
1127 if (item->values_num != 1 || item->values[0].type != OCONFIG_TYPE_BOOLEAN)
1129 do_interactive = item->values[0].value.boolean;
1130 } else if (strcasecmp(item->key, "Encoding") == 0) {
1131 if (item->values_num != 1 || item->values[0].type != OCONFIG_TYPE_STRING)
1134 NOTICE("python: \"Encoding\" was used in the config file but Python3 was used, which does not support changing encodings. Ignoring this.");
1136 /* Why is this even necessary? And undocumented? */
1137 if (PyUnicode_SetDefaultEncoding(item->values[0].value.string))
1138 cpy_log_exception("setting default encoding");
1140 } else if (strcasecmp(item->key, "LogTraces") == 0) {
1141 if (item->values_num != 1 || item->values[0].type != OCONFIG_TYPE_BOOLEAN)
1143 if (!item->values[0].value.boolean) {
1144 Py_XDECREF(cpy_format_exception);
1145 cpy_format_exception = NULL;
1148 if (cpy_format_exception)
1150 tb = PyImport_ImportModule("traceback"); /* New reference. */
1152 cpy_log_exception("python initialization");
1155 cpy_format_exception = PyObject_GetAttrString(tb, "format_exception"); /* New reference. */
1157 if (cpy_format_exception == NULL)
1158 cpy_log_exception("python initialization");
1159 } else if (strcasecmp(item->key, "ModulePath") == 0) {
1161 PyObject *dir_object;
1163 if (cf_util_get_string(item, &dir) != 0)
1165 dir_object = cpy_string_to_unicode_or_bytes(dir); /* New reference. */
1166 if (dir_object == NULL) {
1167 ERROR("python plugin: Unable to convert \"%s\" to "
1168 "a python object.", dir);
1170 cpy_log_exception("python initialization");
1173 if (PyList_Insert(sys_path, 0, dir_object) != 0) {
1174 ERROR("python plugin: Unable to prepend \"%s\" to "
1175 "python module path.", dir);
1176 cpy_log_exception("python initialization");
1178 Py_DECREF(dir_object);
1180 } else if (strcasecmp(item->key, "Import") == 0) {
1181 char *module_name = NULL;
1184 if (cf_util_get_string(item, &module_name) != 0)
1186 module = PyImport_ImportModule(module_name); /* New reference. */
1187 if (module == NULL) {
1188 ERROR("python plugin: Error importing module \"%s\".", module_name);
1189 cpy_log_exception("importing module");
1193 } else if (strcasecmp(item->key, "Module") == 0) {
1198 if (cf_util_get_string(item, &name) != 0)
1200 for (c = cpy_config_callbacks; c; c = c->next) {
1201 if (strcasecmp(c->name + 7, name) == 0)
1205 WARNING("python plugin: Found a configuration for the \"%s\" plugin, "
1206 "but the plugin isn't loaded or didn't register "
1207 "a configuration callback.", name);
1212 if (c->data == NULL)
1213 ret = PyObject_CallFunction(c->callback, "N",
1214 cpy_oconfig_to_pyconfig(item, NULL)); /* New reference. */
1216 ret = PyObject_CallFunction(c->callback, "NO",
1217 cpy_oconfig_to_pyconfig(item, NULL), c->data); /* New reference. */
1219 cpy_log_exception("loading module");
1223 WARNING("python plugin: Ignoring unknown config key \"%s\".", item->key);
1229 void module_register(void) {
1230 plugin_register_complex_config("python", cpy_config);
1231 plugin_register_init("python", cpy_init);
1232 plugin_register_shutdown("python", cpy_shutdown);