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