1 /**
2 * collectd - src/python.c
3 * Copyright (C) 2009 Sven Trenkel
4 *
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:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
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.
22 *
23 * Authors:
24 * Sven Trenkel <collectd at semidefinite.de>
25 **/
27 #include <Python.h>
28 #include <structmember.h>
30 #include <signal.h>
32 #include "collectd.h"
33 #include "common.h"
35 #include "cpython.h"
37 typedef struct cpy_callback_s {
38 char *name;
39 PyObject *callback;
40 PyObject *data;
41 struct cpy_callback_s *next;
42 } cpy_callback_t;
44 static char log_doc[] = "This function sends a string to all logging plugins.";
46 static char get_ds_doc[] = "get_dataset(name) -> definition\n"
47 "\n"
48 "Returns the definition of a dataset specified by name.\n"
49 "\n"
50 "'name' is a string specifying the dataset to query.\n"
51 "'definition' is a list of 4-tuples. Every tuple represents a \n"
52 " data source within the data set and its 4 values are the \n"
53 " name, type, min and max value.\n"
54 " 'name' is a string.\n"
55 " 'type' is a string that is equal to either DS_TYPE_COUNTER,\n"
56 " DS_TYPE_GAUGE, DS_TYPE_DERIVE or DS_TYPE_ABSOLUTE.\n"
57 " 'min' and 'max' are either a float or None.";
59 static char flush_doc[] = "flush([plugin][, timeout][, identifier]) -> None\n"
60 "\n"
61 "Flushes the cache of another plugin.";
63 static char unregister_doc[] = "Unregisters a callback. This function needs exactly one parameter either\n"
64 "the function to unregister or the callback identifier to unregister.";
66 static char reg_log_doc[] = "register_log(callback[, data][, name]) -> identifier\n"
67 "\n"
68 "Register a callback function for log messages.\n"
69 "\n"
70 "'callback' is a callable object that will be called every time something\n"
71 " is logged.\n"
72 "'data' is an optional object that will be passed back to the callback\n"
73 " function every time it is called.\n"
74 "'name' is an optional identifier for this callback. The default name\n"
75 " is 'python.<module>'.\n"
76 " Every callback needs a unique identifier, so if you want to\n"
77 " register this callback multiple time from the same module you need\n"
78 " to specify a name here.\n"
79 "'identifier' is the full identifier assigned to this callback.\n"
80 "\n"
81 "The callback function will be called with two or three parameters:\n"
82 "severity: An integer that should be compared to the LOG_ constants.\n"
83 "message: The text to be logged.\n"
84 "data: The optional data parameter passed to the register function.\n"
85 " If the parameter was omitted it will be omitted here, too.";
87 static char reg_init_doc[] = "register_init(callback[, data][, name]) -> identifier\n"
88 "\n"
89 "Register a callback function that will be executed once after the config.\n"
90 "file has been read, all plugins heve been loaded and the collectd has\n"
91 "forked into the background.\n"
92 "\n"
93 "'callback' is a callable object that will be executed.\n"
94 "'data' is an optional object that will be passed back to the callback\n"
95 " function when it is called.\n"
96 "'name' is an optional identifier for this callback. The default name\n"
97 " is 'python.<module>'.\n"
98 " Every callback needs a unique identifier, so if you want to\n"
99 " register this callback multiple time from the same module you need\n"
100 " to specify a name here.\n"
101 "'identifier' is the full identifier assigned to this callback.\n"
102 "\n"
103 "The callback function will be called without parameters, except for\n"
104 "data if it was supplied.";
106 static char reg_config_doc[] = "register_config(callback[, data][, name]) -> identifier\n"
107 "\n"
108 "Register a callback function for config file entries.\n"
109 "'callback' is a callable object that will be called for every config block.\n"
110 "'data' is an optional object that will be passed back to the callback\n"
111 " function every time it is called.\n"
112 "'name' is an optional identifier for this callback. The default name\n"
113 " is 'python.<module>'.\n"
114 " Every callback needs a unique identifier, so if you want to\n"
115 " register this callback multiple time from the same module you need\n"
116 " to specify a name here.\n"
117 "'identifier' is the full identifier assigned to this callback.\n"
118 "\n"
119 "The callback function will be called with one or two parameters:\n"
120 "config: A Config object.\n"
121 "data: The optional data parameter passed to the register function.\n"
122 " If the parameter was omitted it will be omitted here, too.";
124 static char reg_read_doc[] = "register_read(callback[, interval][, data][, name]) -> identifier\n"
125 "\n"
126 "Register a callback function for reading data. It will just be called\n"
127 "in a fixed interval to signal that it's time to dispatch new values.\n"
128 "'callback' is a callable object that will be called every time something\n"
129 " is logged.\n"
130 "'interval' is the number of seconds between between calls to the callback\n"
131 " function. Full float precision is supported here.\n"
132 "'data' is an optional object that will be passed back to the callback\n"
133 " function every time it is called.\n"
134 "'name' is an optional identifier for this callback. The default name\n"
135 " is 'python.<module>'.\n"
136 " Every callback needs a unique identifier, so if you want to\n"
137 " register this callback multiple time from the same module you need\n"
138 " to specify a name here.\n"
139 "'identifier' is the full identifier assigned to this callback.\n"
140 "\n"
141 "The callback function will be called without parameters, except for\n"
142 "data if it was supplied.";
144 static char reg_write_doc[] = "register_write(callback[, data][, name]) -> identifier\n"
145 "\n"
146 "Register a callback function to receive values dispatched by other plugins.\n"
147 "'callback' is a callable object that will be called every time a value\n"
148 " is dispatched.\n"
149 "'data' is an optional object that will be passed back to the callback\n"
150 " function every time it is called.\n"
151 "'name' is an optional identifier for this callback. The default name\n"
152 " is 'python.<module>'.\n"
153 " Every callback needs a unique identifier, so if you want to\n"
154 " register this callback multiple time from the same module you need\n"
155 " to specify a name here.\n"
156 "'identifier' is the full identifier assigned to this callback.\n"
157 "\n"
158 "The callback function will be called with one or two parameters:\n"
159 "values: A Values object which is a copy of the dispatched values.\n"
160 "data: The optional data parameter passed to the register function.\n"
161 " If the parameter was omitted it will be omitted here, too.";
163 static char reg_notification_doc[] = "register_notification(callback[, data][, name]) -> identifier\n"
164 "\n"
165 "Register a callback function for notifications.\n"
166 "'callback' is a callable object that will be called every time a notification\n"
167 " is dispatched.\n"
168 "'data' is an optional object that will be passed back to the callback\n"
169 " function every time it is called.\n"
170 "'name' is an optional identifier for this callback. The default name\n"
171 " is 'python.<module>'.\n"
172 " Every callback needs a unique identifier, so if you want to\n"
173 " register this callback multiple time from the same module you need\n"
174 " to specify a name here.\n"
175 "'identifier' is the full identifier assigned to this callback.\n"
176 "\n"
177 "The callback function will be called with one or two parameters:\n"
178 "notification: A copy of the notification that was dispatched.\n"
179 "data: The optional data parameter passed to the register function.\n"
180 " If the parameter was omitted it will be omitted here, too.";
182 static char reg_flush_doc[] = "register_flush(callback[, data][, name]) -> identifier\n"
183 "\n"
184 "Register a callback function for flush messages.\n"
185 "'callback' is a callable object that will be called every time a plugin\n"
186 " requests a flush for either this or all plugins.\n"
187 "'data' is an optional object that will be passed back to the callback\n"
188 " function every time it is called.\n"
189 "'name' is an optional identifier for this callback. The default name\n"
190 " is 'python.<module>'.\n"
191 " Every callback needs a unique identifier, so if you want to\n"
192 " register this callback multiple time from the same module you need\n"
193 " to specify a name here.\n"
194 "'identifier' is the full identifier assigned to this callback.\n"
195 "\n"
196 "The callback function will be called with two or three parameters:\n"
197 "timeout: Indicates that only data older than 'timeout' seconds is to\n"
198 " be flushed.\n"
199 "id: Specifies which values are to be flushed.\n"
200 "data: The optional data parameter passed to the register function.\n"
201 " If the parameter was omitted it will be omitted here, too.";
203 static char reg_shutdown_doc[] = "register_shutdown(callback[, data][, name]) -> identifier\n"
204 "\n"
205 "Register a callback function for collectd shutdown.\n"
206 "'callback' is a callable object that will be called once collectd is\n"
207 " shutting down.\n"
208 "'data' is an optional object that will be passed back to the callback\n"
209 " function if it is called.\n"
210 "'name' is an optional identifier for this callback. The default name\n"
211 " is 'python.<module>'.\n"
212 " Every callback needs a unique identifier, so if you want to\n"
213 " register this callback multiple time from the same module you need\n"
214 " to specify a name here.\n"
215 "'identifier' is the full identifier assigned to this callback.\n"
216 "\n"
217 "The callback function will be called with no parameters except for\n"
218 " data if it was supplied.";
221 static int do_interactive = 0;
223 /* This is our global thread state. Python saves some stuff in thread-local
224 * storage. So if we allow the interpreter to run in the background
225 * (the scriptwriters might have created some threads from python), we have
226 * to save the state so we can resume it later after shutdown. */
228 static PyThreadState *state;
230 static PyObject *sys_path, *cpy_format_exception;
232 static cpy_callback_t *cpy_config_callbacks;
233 static cpy_callback_t *cpy_init_callbacks;
234 static cpy_callback_t *cpy_shutdown_callbacks;
236 static void cpy_destroy_user_data(void *data) {
237 cpy_callback_t *c = data;
238 free(c->name);
239 Py_DECREF(c->callback);
240 Py_XDECREF(c->data);
241 free(c);
242 }
244 /* You must hold the GIL to call this function!
245 * But if you managed to extract the callback parameter then you probably already do. */
247 static void cpy_build_name(char *buf, size_t size, PyObject *callback, const char *name) {
248 const char *module = NULL;
249 PyObject *mod = NULL;
251 if (name != NULL) {
252 snprintf(buf, size, "python.%s", name);
253 return;
254 }
256 mod = PyObject_GetAttrString(callback, "__module__"); /* New reference. */
257 if (mod != NULL)
258 module = cpy_unicode_or_bytes_to_string(&mod);
260 if (module != NULL) {
261 snprintf(buf, size, "python.%s", module);
262 Py_XDECREF(mod);
263 PyErr_Clear();
264 return;
265 }
266 Py_XDECREF(mod);
268 snprintf(buf, size, "python.%p", callback);
269 PyErr_Clear();
270 }
272 void cpy_log_exception(const char *context) {
273 int l = 0, i;
274 const char *typename = NULL, *message = NULL;
275 PyObject *type, *value, *traceback, *tn, *m, *list;
277 PyErr_Fetch(&type, &value, &traceback);
278 PyErr_NormalizeException(&type, &value, &traceback);
279 if (type == NULL) return;
280 tn = PyObject_GetAttrString(type, "__name__"); /* New reference. */
281 m = PyObject_Str(value); /* New reference. */
282 if (tn != NULL)
283 typename = cpy_unicode_or_bytes_to_string(&tn);
284 if (m != NULL)
285 message = cpy_unicode_or_bytes_to_string(&m);
286 if (typename == NULL)
287 typename = "NamelessException";
288 if (message == NULL)
289 message = "N/A";
290 Py_BEGIN_ALLOW_THREADS
291 ERROR("Unhandled python exception in %s: %s: %s", context, typename, message);
292 Py_END_ALLOW_THREADS
293 Py_XDECREF(tn);
294 Py_XDECREF(m);
295 if (!cpy_format_exception || !traceback) {
296 PyErr_Clear();
297 Py_DECREF(type);
298 Py_XDECREF(value);
299 Py_XDECREF(traceback);
300 return;
301 }
302 list = PyObject_CallFunction(cpy_format_exception, "NNN", type, value, traceback); /* New reference. Steals references from "type", "value" and "traceback". */
303 if (list)
304 l = PyObject_Length(list);
306 for (i = 0; i < l; ++i) {
307 PyObject *line;
308 char const *msg;
309 char *cpy;
311 line = PyList_GET_ITEM(list, i); /* Borrowed reference. */
312 Py_INCREF(line);
314 msg = cpy_unicode_or_bytes_to_string(&line);
315 Py_DECREF(line);
316 if (msg == NULL)
317 continue;
319 cpy = strdup(msg);
320 if (cpy == NULL)
321 continue;
323 if (cpy[strlen(cpy) - 1] == '\n')
324 cpy[strlen(cpy) - 1] = 0;
326 Py_BEGIN_ALLOW_THREADS
327 ERROR("%s", cpy);
328 Py_END_ALLOW_THREADS
330 free(cpy);
331 }
333 Py_XDECREF(list);
334 PyErr_Clear();
335 }
337 static int cpy_read_callback(user_data_t *data) {
338 cpy_callback_t *c = data->data;
339 PyObject *ret;
341 CPY_LOCK_THREADS
342 ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0); /* New reference. */
343 if (ret == NULL) {
344 cpy_log_exception("read callback");
345 } else {
346 Py_DECREF(ret);
347 }
348 CPY_RELEASE_THREADS
349 if (ret == NULL)
350 return 1;
351 return 0;
352 }
354 static int cpy_write_callback(const data_set_t *ds, const value_list_t *value_list, user_data_t *data) {
355 size_t i;
356 cpy_callback_t *c = data->data;
357 PyObject *ret, *list, *temp, *dict = NULL;
358 Values *v;
360 CPY_LOCK_THREADS
361 list = PyList_New(value_list->values_len); /* New reference. */
362 if (list == NULL) {
363 cpy_log_exception("write callback");
364 CPY_RETURN_FROM_THREADS 0;
365 }
366 for (i = 0; i < value_list->values_len; ++i) {
367 if (ds->ds[i].type == DS_TYPE_COUNTER) {
368 PyList_SetItem(list, i, PyLong_FromUnsignedLongLong(value_list->values[i].counter));
369 } else if (ds->ds[i].type == DS_TYPE_GAUGE) {
370 PyList_SetItem(list, i, PyFloat_FromDouble(value_list->values[i].gauge));
371 } else if (ds->ds[i].type == DS_TYPE_DERIVE) {
372 PyList_SetItem(list, i, PyLong_FromLongLong(value_list->values[i].derive));
373 } else if (ds->ds[i].type == DS_TYPE_ABSOLUTE) {
374 PyList_SetItem(list, i, PyLong_FromUnsignedLongLong(value_list->values[i].absolute));
375 } else {
376 Py_BEGIN_ALLOW_THREADS
377 ERROR("cpy_write_callback: Unknown value type %d.", ds->ds[i].type);
378 Py_END_ALLOW_THREADS
379 Py_DECREF(list);
380 CPY_RETURN_FROM_THREADS 0;
381 }
382 if (PyErr_Occurred() != NULL) {
383 cpy_log_exception("value building for write callback");
384 Py_DECREF(list);
385 CPY_RETURN_FROM_THREADS 0;
386 }
387 }
388 dict = PyDict_New(); /* New reference. */
389 if (value_list->meta) {
390 int num;
391 char **table;
392 meta_data_t *meta = value_list->meta;
394 num = meta_data_toc(meta, &table);
395 for (i = 0; i < num; ++i) {
396 int type;
397 char *string;
398 int64_t si;
399 uint64_t ui;
400 double d;
401 _Bool b;
403 type = meta_data_type(meta, table[i]);
404 if (type == MD_TYPE_STRING) {
405 if (meta_data_get_string(meta, table[i], &string))
406 continue;
407 temp = cpy_string_to_unicode_or_bytes(string); /* New reference. */
408 free(string);
409 PyDict_SetItemString(dict, table[i], temp);
410 Py_XDECREF(temp);
411 } else if (type == MD_TYPE_SIGNED_INT) {
412 if (meta_data_get_signed_int(meta, table[i], &si))
413 continue;
414 temp = PyObject_CallFunctionObjArgs((void *) &SignedType, PyLong_FromLongLong(si), (void *) 0); /* New reference. */
415 PyDict_SetItemString(dict, table[i], temp);
416 Py_XDECREF(temp);
417 } else if (type == MD_TYPE_UNSIGNED_INT) {
418 if (meta_data_get_unsigned_int(meta, table[i], &ui))
419 continue;
420 temp = PyObject_CallFunctionObjArgs((void *) &UnsignedType, PyLong_FromUnsignedLongLong(ui), (void *) 0); /* New reference. */
421 PyDict_SetItemString(dict, table[i], temp);
422 Py_XDECREF(temp);
423 } else if (type == MD_TYPE_DOUBLE) {
424 if (meta_data_get_double(meta, table[i], &d))
425 continue;
426 temp = PyFloat_FromDouble(d); /* New reference. */
427 PyDict_SetItemString(dict, table[i], temp);
428 Py_XDECREF(temp);
429 } else if (type == MD_TYPE_BOOLEAN) {
430 if (meta_data_get_boolean(meta, table[i], &b))
431 continue;
432 if (b)
433 PyDict_SetItemString(dict, table[i], Py_True);
434 else
435 PyDict_SetItemString(dict, table[i], Py_False);
436 }
437 free(table[i]);
438 }
439 free(table);
440 }
441 v = (Values *) Values_New(); /* New reference. */
442 sstrncpy(v->data.host, value_list->host, sizeof(v->data.host));
443 sstrncpy(v->data.type, value_list->type, sizeof(v->data.type));
444 sstrncpy(v->data.type_instance, value_list->type_instance, sizeof(v->data.type_instance));
445 sstrncpy(v->data.plugin, value_list->plugin, sizeof(v->data.plugin));
446 sstrncpy(v->data.plugin_instance, value_list->plugin_instance, sizeof(v->data.plugin_instance));
447 v->data.time = CDTIME_T_TO_DOUBLE(value_list->time);
448 v->interval = CDTIME_T_TO_DOUBLE(value_list->interval);
449 Py_CLEAR(v->values);
450 v->values = list;
451 Py_CLEAR(v->meta);
452 v->meta = dict; /* Steals a reference. */
453 ret = PyObject_CallFunctionObjArgs(c->callback, v, c->data, (void *) 0); /* New reference. */
454 Py_XDECREF(v);
455 if (ret == NULL) {
456 cpy_log_exception("write callback");
457 } else {
458 Py_DECREF(ret);
459 }
460 CPY_RELEASE_THREADS
461 return 0;
462 }
464 static int cpy_notification_callback(const notification_t *notification, user_data_t *data) {
465 cpy_callback_t *c = data->data;
466 PyObject *ret, *notify;
467 Notification *n;
469 CPY_LOCK_THREADS
470 notify = Notification_New(); /* New reference. */
471 n = (Notification *) notify;
472 sstrncpy(n->data.host, notification->host, sizeof(n->data.host));
473 sstrncpy(n->data.type, notification->type, sizeof(n->data.type));
474 sstrncpy(n->data.type_instance, notification->type_instance, sizeof(n->data.type_instance));
475 sstrncpy(n->data.plugin, notification->plugin, sizeof(n->data.plugin));
476 sstrncpy(n->data.plugin_instance, notification->plugin_instance, sizeof(n->data.plugin_instance));
477 n->data.time = CDTIME_T_TO_DOUBLE(notification->time);
478 sstrncpy(n->message, notification->message, sizeof(n->message));
479 n->severity = notification->severity;
480 ret = PyObject_CallFunctionObjArgs(c->callback, n, c->data, (void *) 0); /* New reference. */
481 Py_XDECREF(notify);
482 if (ret == NULL) {
483 cpy_log_exception("notification callback");
484 } else {
485 Py_DECREF(ret);
486 }
487 CPY_RELEASE_THREADS
488 return 0;
489 }
491 static void cpy_log_callback(int severity, const char *message, user_data_t *data) {
492 cpy_callback_t * c = data->data;
493 PyObject *ret, *text;
495 CPY_LOCK_THREADS
496 text = cpy_string_to_unicode_or_bytes(message); /* New reference. */
497 if (c->data == NULL)
498 ret = PyObject_CallFunction(c->callback, "iN", severity, text); /* New reference. Steals a reference from "text". */
499 else
500 ret = PyObject_CallFunction(c->callback, "iNO", severity, text, c->data); /* New reference. Steals a reference from "text". */
502 if (ret == NULL) {
503 /* FIXME */
504 /* Do we really want to trigger a log callback because a log callback failed?
505 * Probably not. */
506 PyErr_Print();
507 /* In case someone wanted to be clever, replaced stderr and failed at that. */
508 PyErr_Clear();
509 } else {
510 Py_DECREF(ret);
511 }
512 CPY_RELEASE_THREADS
513 }
515 static void cpy_flush_callback(int timeout, const char *id, user_data_t *data) {
516 cpy_callback_t * c = data->data;
517 PyObject *ret, *text;
519 CPY_LOCK_THREADS
520 text = cpy_string_to_unicode_or_bytes(id);
521 if (c->data == NULL)
522 ret = PyObject_CallFunction(c->callback, "iN", timeout, text); /* New reference. */
523 else
524 ret = PyObject_CallFunction(c->callback, "iNO", timeout, text, c->data); /* New reference. */
526 if (ret == NULL) {
527 cpy_log_exception("flush callback");
528 } else {
529 Py_DECREF(ret);
530 }
531 CPY_RELEASE_THREADS
532 }
534 static PyObject *cpy_register_generic(cpy_callback_t **list_head, PyObject *args, PyObject *kwds) {
535 char buf[512];
536 cpy_callback_t *c;
537 char *name = NULL;
538 PyObject *callback = NULL, *data = NULL, *mod = NULL;
539 static char *kwlist[] = {"callback", "data", "name", NULL};
541 if (PyArg_ParseTupleAndKeywords(args, kwds, "O|Oet", kwlist, &callback, &data, NULL, &name) == 0) return NULL;
542 if (PyCallable_Check(callback) == 0) {
543 PyMem_Free(name);
544 PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
545 return NULL;
546 }
547 cpy_build_name(buf, sizeof(buf), callback, name);
549 Py_INCREF(callback);
550 Py_XINCREF(data);
552 c = calloc(1, sizeof(*c));
553 if (c == NULL)
554 return NULL;
556 c->name = strdup(buf);
557 c->callback = callback;
558 c->data = data;
559 c->next = *list_head;
560 *list_head = c;
561 Py_XDECREF(mod);
562 PyMem_Free(name);
563 return cpy_string_to_unicode_or_bytes(buf);
564 }
566 static PyObject *float_or_none(float number) {
567 if (isnan(number)) {
568 Py_RETURN_NONE;
569 }
570 return PyFloat_FromDouble(number);
571 }
573 static PyObject *cpy_get_dataset(PyObject *self, PyObject *args) {
574 size_t i;
575 char *name;
576 const data_set_t *ds;
577 PyObject *list, *tuple;
579 if (PyArg_ParseTuple(args, "et", NULL, &name) == 0) return NULL;
580 ds = plugin_get_ds(name);
581 PyMem_Free(name);
582 if (ds == NULL) {
583 PyErr_Format(PyExc_TypeError, "Dataset %s not found", name);
584 return NULL;
585 }
586 list = PyList_New(ds->ds_num); /* New reference. */
587 for (i = 0; i < ds->ds_num; ++i) {
588 tuple = PyTuple_New(4);
589 PyTuple_SET_ITEM(tuple, 0, cpy_string_to_unicode_or_bytes(ds->ds[i].name));
590 PyTuple_SET_ITEM(tuple, 1, cpy_string_to_unicode_or_bytes(DS_TYPE_TO_STRING(ds->ds[i].type)));
591 PyTuple_SET_ITEM(tuple, 2, float_or_none(ds->ds[i].min));
592 PyTuple_SET_ITEM(tuple, 3, float_or_none(ds->ds[i].max));
593 PyList_SET_ITEM(list, i, tuple);
594 }
595 return list;
596 }
598 static PyObject *cpy_flush(PyObject *self, PyObject *args, PyObject *kwds) {
599 int timeout = -1;
600 char *plugin = NULL, *identifier = NULL;
601 static char *kwlist[] = {"plugin", "timeout", "identifier", NULL};
603 if (PyArg_ParseTupleAndKeywords(args, kwds, "|etiet", kwlist, NULL, &plugin, &timeout, NULL, &identifier) == 0) return NULL;
604 Py_BEGIN_ALLOW_THREADS
605 plugin_flush(plugin, timeout, identifier);
606 Py_END_ALLOW_THREADS
607 PyMem_Free(plugin);
608 PyMem_Free(identifier);
609 Py_RETURN_NONE;
610 }
612 static PyObject *cpy_register_config(PyObject *self, PyObject *args, PyObject *kwds) {
613 return cpy_register_generic(&cpy_config_callbacks, args, kwds);
614 }
616 static PyObject *cpy_register_init(PyObject *self, PyObject *args, PyObject *kwds) {
617 return cpy_register_generic(&cpy_init_callbacks, args, kwds);
618 }
620 typedef int reg_function_t(const char *name, void *callback, void *data);
622 static PyObject *cpy_register_generic_userdata(void *reg, void *handler, PyObject *args, PyObject *kwds) {
623 char buf[512];
624 reg_function_t *register_function = (reg_function_t *) reg;
625 cpy_callback_t *c = NULL;
626 user_data_t user_data = { 0 };
627 char *name = NULL;
628 PyObject *callback = NULL, *data = NULL;
629 static char *kwlist[] = {"callback", "data", "name", NULL};
631 if (PyArg_ParseTupleAndKeywords(args, kwds, "O|Oet", kwlist, &callback, &data, NULL, &name) == 0) return NULL;
632 if (PyCallable_Check(callback) == 0) {
633 PyMem_Free(name);
634 PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
635 return NULL;
636 }
637 cpy_build_name(buf, sizeof(buf), callback, name);
638 PyMem_Free(name);
640 Py_INCREF(callback);
641 Py_XINCREF(data);
643 c = calloc(1, sizeof(*c));
644 if (c == NULL)
645 return NULL;
647 c->name = strdup(buf);
648 c->callback = callback;
649 c->data = data;
650 c->next = NULL;
652 user_data.free_func = cpy_destroy_user_data;
653 user_data.data = c;
655 register_function(buf, handler, &user_data);
656 return cpy_string_to_unicode_or_bytes(buf);
657 }
659 static PyObject *cpy_register_read(PyObject *self, PyObject *args, PyObject *kwds) {
660 char buf[512];
661 cpy_callback_t *c = NULL;
662 user_data_t user_data = { 0 };
663 double interval = 0;
664 char *name = NULL;
665 PyObject *callback = NULL, *data = NULL;
666 static char *kwlist[] = {"callback", "interval", "data", "name", NULL};
668 if (PyArg_ParseTupleAndKeywords(args, kwds, "O|dOet", kwlist, &callback, &interval, &data, NULL, &name) == 0) return NULL;
669 if (PyCallable_Check(callback) == 0) {
670 PyMem_Free(name);
671 PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
672 return NULL;
673 }
674 cpy_build_name(buf, sizeof(buf), callback, name);
675 PyMem_Free(name);
677 Py_INCREF(callback);
678 Py_XINCREF(data);
680 c = calloc(1, sizeof(*c));
681 if (c == NULL)
682 return NULL;
684 c->name = strdup(buf);
685 c->callback = callback;
686 c->data = data;
687 c->next = NULL;
689 user_data.free_func = cpy_destroy_user_data;
690 user_data.data = c;
692 plugin_register_complex_read(/* group = */ "python", buf,
693 cpy_read_callback, DOUBLE_TO_CDTIME_T (interval), &user_data);
694 return cpy_string_to_unicode_or_bytes(buf);
695 }
697 static PyObject *cpy_register_log(PyObject *self, PyObject *args, PyObject *kwds) {
698 return cpy_register_generic_userdata((void *) plugin_register_log,
699 (void *) cpy_log_callback, args, kwds);
700 }
702 static PyObject *cpy_register_write(PyObject *self, PyObject *args, PyObject *kwds) {
703 return cpy_register_generic_userdata((void *) plugin_register_write,
704 (void *) cpy_write_callback, args, kwds);
705 }
707 static PyObject *cpy_register_notification(PyObject *self, PyObject *args, PyObject *kwds) {
708 return cpy_register_generic_userdata((void *) plugin_register_notification,
709 (void *) cpy_notification_callback, args, kwds);
710 }
712 static PyObject *cpy_register_flush(PyObject *self, PyObject *args, PyObject *kwds) {
713 return cpy_register_generic_userdata((void *) plugin_register_flush,
714 (void *) cpy_flush_callback, args, kwds);
715 }
717 static PyObject *cpy_register_shutdown(PyObject *self, PyObject *args, PyObject *kwds) {
718 return cpy_register_generic(&cpy_shutdown_callbacks, args, kwds);
719 }
721 static PyObject *cpy_error(PyObject *self, PyObject *args) {
722 char *text;
723 if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
724 Py_BEGIN_ALLOW_THREADS
725 plugin_log(LOG_ERR, "%s", text);
726 Py_END_ALLOW_THREADS
727 PyMem_Free(text);
728 Py_RETURN_NONE;
729 }
731 static PyObject *cpy_warning(PyObject *self, PyObject *args) {
732 char *text;
733 if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
734 Py_BEGIN_ALLOW_THREADS
735 plugin_log(LOG_WARNING, "%s", text);
736 Py_END_ALLOW_THREADS
737 PyMem_Free(text);
738 Py_RETURN_NONE;
739 }
741 static PyObject *cpy_notice(PyObject *self, PyObject *args) {
742 char *text;
743 if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
744 Py_BEGIN_ALLOW_THREADS
745 plugin_log(LOG_NOTICE, "%s", text);
746 Py_END_ALLOW_THREADS
747 PyMem_Free(text);
748 Py_RETURN_NONE;
749 }
751 static PyObject *cpy_info(PyObject *self, PyObject *args) {
752 char *text;
753 if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
754 Py_BEGIN_ALLOW_THREADS
755 plugin_log(LOG_INFO, "%s", text);
756 Py_END_ALLOW_THREADS
757 PyMem_Free(text);
758 Py_RETURN_NONE;
759 }
761 static PyObject *cpy_debug(PyObject *self, PyObject *args) {
762 #ifdef COLLECT_DEBUG
763 char *text;
764 if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
765 Py_BEGIN_ALLOW_THREADS
766 plugin_log(LOG_DEBUG, "%s", text);
767 Py_END_ALLOW_THREADS
768 PyMem_Free(text);
769 #endif
770 Py_RETURN_NONE;
771 }
773 static PyObject *cpy_unregister_generic(cpy_callback_t **list_head, PyObject *arg, const char *desc) {
774 char buf[512];
775 const char *name;
776 cpy_callback_t *prev = NULL, *tmp;
778 Py_INCREF(arg);
779 name = cpy_unicode_or_bytes_to_string(&arg);
780 if (name == NULL) {
781 PyErr_Clear();
782 if (!PyCallable_Check(arg)) {
783 PyErr_SetString(PyExc_TypeError, "This function needs a string or a callable object as its only parameter.");
784 Py_DECREF(arg);
785 return NULL;
786 }
787 cpy_build_name(buf, sizeof(buf), arg, NULL);
788 name = buf;
789 }
790 for (tmp = *list_head; tmp; prev = tmp, tmp = tmp->next)
791 if (strcmp(name, tmp->name) == 0)
792 break;
794 Py_DECREF(arg);
795 if (tmp == NULL) {
796 PyErr_Format(PyExc_RuntimeError, "Unable to unregister %s callback '%s'.", desc, name);
797 return NULL;
798 }
799 /* Yes, this is actually save. To call this function the caller has to
800 * hold the GIL. Well, save as long as there is only one GIL anyway ... */
801 if (prev == NULL)
802 *list_head = tmp->next;
803 else
804 prev->next = tmp->next;
805 cpy_destroy_user_data(tmp);
806 Py_RETURN_NONE;
807 }
809 typedef int cpy_unregister_function_t(const char *name);
811 static PyObject *cpy_unregister_generic_userdata(cpy_unregister_function_t *unreg, PyObject *arg, const char *desc) {
812 char buf[512];
813 const char *name;
815 Py_INCREF(arg);
816 name = cpy_unicode_or_bytes_to_string(&arg);
817 if (name == NULL) {
818 PyErr_Clear();
819 if (!PyCallable_Check(arg)) {
820 PyErr_SetString(PyExc_TypeError, "This function needs a string or a callable object as its only parameter.");
821 Py_DECREF(arg);
822 return NULL;
823 }
824 cpy_build_name(buf, sizeof(buf), arg, NULL);
825 name = buf;
826 }
827 if (unreg(name) == 0) {
828 Py_DECREF(arg);
829 Py_RETURN_NONE;
830 }
831 PyErr_Format(PyExc_RuntimeError, "Unable to unregister %s callback '%s'.", desc, name);
832 Py_DECREF(arg);
833 return NULL;
834 }
836 static PyObject *cpy_unregister_log(PyObject *self, PyObject *arg) {
837 return cpy_unregister_generic_userdata(plugin_unregister_log, arg, "log");
838 }
840 static PyObject *cpy_unregister_init(PyObject *self, PyObject *arg) {
841 return cpy_unregister_generic(&cpy_init_callbacks, arg, "init");
842 }
844 static PyObject *cpy_unregister_config(PyObject *self, PyObject *arg) {
845 return cpy_unregister_generic(&cpy_config_callbacks, arg, "config");
846 }
848 static PyObject *cpy_unregister_read(PyObject *self, PyObject *arg) {
849 return cpy_unregister_generic_userdata(plugin_unregister_read, arg, "read");
850 }
852 static PyObject *cpy_unregister_write(PyObject *self, PyObject *arg) {
853 return cpy_unregister_generic_userdata(plugin_unregister_write, arg, "write");
854 }
856 static PyObject *cpy_unregister_notification(PyObject *self, PyObject *arg) {
857 return cpy_unregister_generic_userdata(plugin_unregister_notification, arg, "notification");
858 }
860 static PyObject *cpy_unregister_flush(PyObject *self, PyObject *arg) {
861 return cpy_unregister_generic_userdata(plugin_unregister_flush, arg, "flush");
862 }
864 static PyObject *cpy_unregister_shutdown(PyObject *self, PyObject *arg) {
865 return cpy_unregister_generic(&cpy_shutdown_callbacks, arg, "shutdown");
866 }
868 static PyMethodDef cpy_methods[] = {
869 {"debug", cpy_debug, METH_VARARGS, log_doc},
870 {"info", cpy_info, METH_VARARGS, log_doc},
871 {"notice", cpy_notice, METH_VARARGS, log_doc},
872 {"warning", cpy_warning, METH_VARARGS, log_doc},
873 {"error", cpy_error, METH_VARARGS, log_doc},
874 {"get_dataset", (PyCFunction) cpy_get_dataset, METH_VARARGS, get_ds_doc},
875 {"flush", (PyCFunction) cpy_flush, METH_VARARGS | METH_KEYWORDS, flush_doc},
876 {"register_log", (PyCFunction) cpy_register_log, METH_VARARGS | METH_KEYWORDS, reg_log_doc},
877 {"register_init", (PyCFunction) cpy_register_init, METH_VARARGS | METH_KEYWORDS, reg_init_doc},
878 {"register_config", (PyCFunction) cpy_register_config, METH_VARARGS | METH_KEYWORDS, reg_config_doc},
879 {"register_read", (PyCFunction) cpy_register_read, METH_VARARGS | METH_KEYWORDS, reg_read_doc},
880 {"register_write", (PyCFunction) cpy_register_write, METH_VARARGS | METH_KEYWORDS, reg_write_doc},
881 {"register_notification", (PyCFunction) cpy_register_notification, METH_VARARGS | METH_KEYWORDS, reg_notification_doc},
882 {"register_flush", (PyCFunction) cpy_register_flush, METH_VARARGS | METH_KEYWORDS, reg_flush_doc},
883 {"register_shutdown", (PyCFunction) cpy_register_shutdown, METH_VARARGS | METH_KEYWORDS, reg_shutdown_doc},
884 {"unregister_log", cpy_unregister_log, METH_O, unregister_doc},
885 {"unregister_init", cpy_unregister_init, METH_O, unregister_doc},
886 {"unregister_config", cpy_unregister_config, METH_O, unregister_doc},
887 {"unregister_read", cpy_unregister_read, METH_O, unregister_doc},
888 {"unregister_write", cpy_unregister_write, METH_O, unregister_doc},
889 {"unregister_notification", cpy_unregister_notification, METH_O, unregister_doc},
890 {"unregister_flush", cpy_unregister_flush, METH_O, unregister_doc},
891 {"unregister_shutdown", cpy_unregister_shutdown, METH_O, unregister_doc},
892 {0, 0, 0, 0}
893 };
895 static int cpy_shutdown(void) {
896 cpy_callback_t *c;
897 PyObject *ret;
899 /* This can happen if the module was loaded but not configured. */
900 if (state != NULL)
901 PyEval_RestoreThread(state);
903 for (c = cpy_shutdown_callbacks; c; c = c->next) {
904 ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0); /* New reference. */
905 if (ret == NULL)
906 cpy_log_exception("shutdown callback");
907 else
908 Py_DECREF(ret);
909 }
910 PyErr_Print();
911 Py_Finalize();
912 return 0;
913 }
915 static void cpy_int_handler(int sig) {
916 return;
917 }
919 static void *cpy_interactive(void *data) {
920 sigset_t sigset;
921 struct sigaction old;
923 /* Signal handler in a plugin? Bad stuff, but the best way to
924 * handle it I guess. In an interactive session people will
925 * press Ctrl+C at some time, which will generate a SIGINT.
926 * This will cause collectd to shutdown, thus killing the
927 * interactive interpreter, and leaving the terminal in a
928 * mess. Chances are, this isn't what the user wanted to do.
929 *
930 * So this is the plan:
931 * 1. Block SIGINT in the main thread.
932 * 2. Install our own signal handler that does nothing.
933 * 3. Unblock SIGINT in the interactive thread.
934 *
935 * This will make sure that SIGINT won't kill collectd but
936 * still interrupt syscalls like sleep and pause.
937 * It does not raise a KeyboardInterrupt exception because so
938 * far nobody managed to figure out how to do that. */
939 struct sigaction sig_int_action = {
940 .sa_handler = cpy_int_handler
941 };
942 sigaction (SIGINT, &sig_int_action, &old);
944 sigemptyset(&sigset);
945 sigaddset(&sigset, SIGINT);
946 pthread_sigmask(SIG_UNBLOCK, &sigset, NULL);
947 PyEval_AcquireThread(state);
948 if (PyImport_ImportModule("readline") == NULL) {
949 /* This interactive session will suck. */
950 cpy_log_exception("interactive session init");
951 }
952 PyRun_InteractiveLoop(stdin, "<stdin>");
953 PyErr_Print();
954 PyEval_ReleaseThread(state);
955 NOTICE("python: Interactive interpreter exited, stopping collectd ...");
956 /* Restore the original collectd SIGINT handler and raise SIGINT.
957 * The main thread still has SIGINT blocked and there's nothing we
958 * can do about that so this thread will handle it. But that's not
959 * important, except that it won't interrupt the main loop and so
960 * it might take a few seconds before collectd really shuts down. */
961 sigaction (SIGINT, &old, NULL);
962 raise(SIGINT);
963 pause();
964 return NULL;
965 }
967 static int cpy_init(void) {
968 cpy_callback_t *c;
969 PyObject *ret;
970 static pthread_t thread;
971 sigset_t sigset;
973 if (!Py_IsInitialized()) {
974 WARNING("python: Plugin loaded but not configured.");
975 plugin_unregister_shutdown("python");
976 return 0;
977 }
978 PyEval_InitThreads();
979 /* Now it's finally OK to use python threads. */
980 for (c = cpy_init_callbacks; c; c = c->next) {
981 ret = PyObject_CallFunctionObjArgs(c->callback, c->data, (void *) 0); /* New reference. */
982 if (ret == NULL)
983 cpy_log_exception("init callback");
984 else
985 Py_DECREF(ret);
986 }
987 sigemptyset(&sigset);
988 sigaddset(&sigset, SIGINT);
989 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
990 state = PyEval_SaveThread();
991 if (do_interactive) {
992 if (plugin_thread_create(&thread, NULL, cpy_interactive, NULL)) {
993 ERROR("python: Error creating thread for interactive interpreter.");
994 }
995 }
997 return 0;
998 }
1000 static PyObject *cpy_oconfig_to_pyconfig(oconfig_item_t *ci, PyObject *parent) {
1001 int i;
1002 PyObject *item, *values, *children, *tmp;
1004 if (parent == NULL)
1005 parent = Py_None;
1007 values = PyTuple_New(ci->values_num); /* New reference. */
1008 for (i = 0; i < ci->values_num; ++i) {
1009 if (ci->values[i].type == OCONFIG_TYPE_STRING) {
1010 PyTuple_SET_ITEM(values, i, cpy_string_to_unicode_or_bytes(ci->values[i].value.string));
1011 } else if (ci->values[i].type == OCONFIG_TYPE_NUMBER) {
1012 PyTuple_SET_ITEM(values, i, PyFloat_FromDouble(ci->values[i].value.number));
1013 } else if (ci->values[i].type == OCONFIG_TYPE_BOOLEAN) {
1014 PyTuple_SET_ITEM(values, i, PyBool_FromLong(ci->values[i].value.boolean));
1015 }
1016 }
1018 tmp = cpy_string_to_unicode_or_bytes(ci->key);
1019 item = PyObject_CallFunction((void *) &ConfigType, "NONO", tmp, parent, values, Py_None);
1020 if (item == NULL)
1021 return NULL;
1022 children = PyTuple_New(ci->children_num); /* New reference. */
1023 for (i = 0; i < ci->children_num; ++i) {
1024 PyTuple_SET_ITEM(children, i, cpy_oconfig_to_pyconfig(ci->children + i, item));
1025 }
1026 tmp = ((Config *) item)->children;
1027 ((Config *) item)->children = children;
1028 Py_XDECREF(tmp);
1029 return item;
1030 }
1032 #ifdef IS_PY3K
1033 static struct PyModuleDef collectdmodule = {
1034 PyModuleDef_HEAD_INIT,
1035 "collectd", /* name of module */
1036 "The python interface to collectd", /* module documentation, may be NULL */
1037 -1,
1038 cpy_methods
1039 };
1041 PyMODINIT_FUNC PyInit_collectd(void) {
1042 return PyModule_Create(&collectdmodule);
1043 }
1044 #endif
1046 static int cpy_init_python(void) {
1047 PyObject *sys;
1048 PyObject *module;
1050 #ifdef IS_PY3K
1051 wchar_t *argv = L"";
1052 /* Add a builtin module, before Py_Initialize */
1053 PyImport_AppendInittab("collectd", PyInit_collectd);
1054 #else
1055 char *argv = "";
1056 #endif
1058 Py_Initialize();
1060 PyType_Ready(&ConfigType);
1061 PyType_Ready(&PluginDataType);
1062 ValuesType.tp_base = &PluginDataType;
1063 PyType_Ready(&ValuesType);
1064 NotificationType.tp_base = &PluginDataType;
1065 PyType_Ready(&NotificationType);
1066 SignedType.tp_base = &PyLong_Type;
1067 PyType_Ready(&SignedType);
1068 UnsignedType.tp_base = &PyLong_Type;
1069 PyType_Ready(&UnsignedType);
1070 sys = PyImport_ImportModule("sys"); /* New reference. */
1071 if (sys == NULL) {
1072 cpy_log_exception("python initialization");
1073 return 1;
1074 }
1075 sys_path = PyObject_GetAttrString(sys, "path"); /* New reference. */
1076 Py_DECREF(sys);
1077 if (sys_path == NULL) {
1078 cpy_log_exception("python initialization");
1079 return 1;
1080 }
1081 PySys_SetArgv(1, &argv);
1082 PyList_SetSlice(sys_path, 0, 1, NULL);
1084 #ifdef IS_PY3K
1085 module = PyImport_ImportModule("collectd");
1086 #else
1087 module = Py_InitModule("collectd", cpy_methods); /* Borrowed reference. */
1088 #endif
1089 PyModule_AddObject(module, "Config", (void *) &ConfigType); /* Steals a reference. */
1090 PyModule_AddObject(module, "Values", (void *) &ValuesType); /* Steals a reference. */
1091 PyModule_AddObject(module, "Notification", (void *) &NotificationType); /* Steals a reference. */
1092 PyModule_AddObject(module, "Signed", (void *) &SignedType); /* Steals a reference. */
1093 PyModule_AddObject(module, "Unsigned", (void *) &UnsignedType); /* Steals a reference. */
1094 PyModule_AddIntConstant(module, "LOG_DEBUG", LOG_DEBUG);
1095 PyModule_AddIntConstant(module, "LOG_INFO", LOG_INFO);
1096 PyModule_AddIntConstant(module, "LOG_NOTICE", LOG_NOTICE);
1097 PyModule_AddIntConstant(module, "LOG_WARNING", LOG_WARNING);
1098 PyModule_AddIntConstant(module, "LOG_ERROR", LOG_ERR);
1099 PyModule_AddIntConstant(module, "NOTIF_FAILURE", NOTIF_FAILURE);
1100 PyModule_AddIntConstant(module, "NOTIF_WARNING", NOTIF_WARNING);
1101 PyModule_AddIntConstant(module, "NOTIF_OKAY", NOTIF_OKAY);
1102 PyModule_AddStringConstant(module, "DS_TYPE_COUNTER", DS_TYPE_TO_STRING(DS_TYPE_COUNTER));
1103 PyModule_AddStringConstant(module, "DS_TYPE_GAUGE", DS_TYPE_TO_STRING(DS_TYPE_GAUGE));
1104 PyModule_AddStringConstant(module, "DS_TYPE_DERIVE", DS_TYPE_TO_STRING(DS_TYPE_DERIVE));
1105 PyModule_AddStringConstant(module, "DS_TYPE_ABSOLUTE", DS_TYPE_TO_STRING(DS_TYPE_ABSOLUTE));
1106 return 0;
1107 }
1109 static int cpy_config(oconfig_item_t *ci) {
1110 int i;
1111 PyObject *tb;
1113 /* Ok in theory we shouldn't do initialization at this point
1114 * but we have to. In order to give python scripts a chance
1115 * to register a config callback we need to be able to execute
1116 * python code during the config callback so we have to start
1117 * the interpreter here. */
1118 /* Do *not* use the python "thread" module at this point! */
1120 if (!Py_IsInitialized() && cpy_init_python()) return 1;
1122 for (i = 0; i < ci->children_num; ++i) {
1123 oconfig_item_t *item = ci->children + i;
1125 if (strcasecmp(item->key, "Interactive") == 0) {
1126 if (item->values_num != 1 || item->values[0].type != OCONFIG_TYPE_BOOLEAN)
1127 continue;
1128 do_interactive = item->values[0].value.boolean;
1129 } else if (strcasecmp(item->key, "Encoding") == 0) {
1130 if (item->values_num != 1 || item->values[0].type != OCONFIG_TYPE_STRING)
1131 continue;
1132 #ifdef IS_PY3K
1133 NOTICE("python: \"Encoding\" was used in the config file but Python3 was used, which does not support changing encodings. Ignoring this.");
1134 #else
1135 /* Why is this even necessary? And undocumented? */
1136 if (PyUnicode_SetDefaultEncoding(item->values[0].value.string))
1137 cpy_log_exception("setting default encoding");
1138 #endif
1139 } else if (strcasecmp(item->key, "LogTraces") == 0) {
1140 if (item->values_num != 1 || item->values[0].type != OCONFIG_TYPE_BOOLEAN)
1141 continue;
1142 if (!item->values[0].value.boolean) {
1143 Py_XDECREF(cpy_format_exception);
1144 cpy_format_exception = NULL;
1145 continue;
1146 }
1147 if (cpy_format_exception)
1148 continue;
1149 tb = PyImport_ImportModule("traceback"); /* New reference. */
1150 if (tb == NULL) {
1151 cpy_log_exception("python initialization");
1152 continue;
1153 }
1154 cpy_format_exception = PyObject_GetAttrString(tb, "format_exception"); /* New reference. */
1155 Py_DECREF(tb);
1156 if (cpy_format_exception == NULL)
1157 cpy_log_exception("python initialization");
1158 } else if (strcasecmp(item->key, "ModulePath") == 0) {
1159 char *dir = NULL;
1160 PyObject *dir_object;
1162 if (cf_util_get_string(item, &dir) != 0)
1163 continue;
1164 dir_object = cpy_string_to_unicode_or_bytes(dir); /* New reference. */
1165 if (dir_object == NULL) {
1166 ERROR("python plugin: Unable to convert \"%s\" to "
1167 "a python object.", dir);
1168 free(dir);
1169 cpy_log_exception("python initialization");
1170 continue;
1171 }
1172 if (PyList_Insert(sys_path, 0, dir_object) != 0) {
1173 ERROR("python plugin: Unable to prepend \"%s\" to "
1174 "python module path.", dir);
1175 cpy_log_exception("python initialization");
1176 }
1177 Py_DECREF(dir_object);
1178 free(dir);
1179 } else if (strcasecmp(item->key, "Import") == 0) {
1180 char *module_name = NULL;
1181 PyObject *module;
1183 if (cf_util_get_string(item, &module_name) != 0)
1184 continue;
1185 module = PyImport_ImportModule(module_name); /* New reference. */
1186 if (module == NULL) {
1187 ERROR("python plugin: Error importing module \"%s\".", module_name);
1188 cpy_log_exception("importing module");
1189 }
1190 free(module_name);
1191 Py_XDECREF(module);
1192 } else if (strcasecmp(item->key, "Module") == 0) {
1193 char *name = NULL;
1194 cpy_callback_t *c;
1195 PyObject *ret;
1197 if (cf_util_get_string(item, &name) != 0)
1198 continue;
1199 for (c = cpy_config_callbacks; c; c = c->next) {
1200 if (strcasecmp(c->name + 7, name) == 0)
1201 break;
1202 }
1203 if (c == NULL) {
1204 WARNING("python plugin: Found a configuration for the \"%s\" plugin, "
1205 "but the plugin isn't loaded or didn't register "
1206 "a configuration callback.", name);
1207 free(name);
1208 continue;
1209 }
1210 free(name);
1211 if (c->data == NULL)
1212 ret = PyObject_CallFunction(c->callback, "N",
1213 cpy_oconfig_to_pyconfig(item, NULL)); /* New reference. */
1214 else
1215 ret = PyObject_CallFunction(c->callback, "NO",
1216 cpy_oconfig_to_pyconfig(item, NULL), c->data); /* New reference. */
1217 if (ret == NULL)
1218 cpy_log_exception("loading module");
1219 else
1220 Py_DECREF(ret);
1221 } else {
1222 WARNING("python plugin: Ignoring unknown config key \"%s\".", item->key);
1223 }
1224 }
1225 return 0;
1226 }
1228 void module_register(void) {
1229 plugin_register_complex_config("python", cpy_config);
1230 plugin_register_init("python", cpy_init);
1231 plugin_register_shutdown("python", cpy_shutdown);
1232 }