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