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