Merge branch 'collectd-4.2' into collectd-4.3
[collectd.git] / src / perl.c
1 /**
2  * collectd - src/perl.c
3  * Copyright (C) 2007  Sebastian Harl
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Author:
19  *   Sebastian Harl <sh at tokkee.org>
20  **/
21
22 /*
23  * This plugin embeds a Perl interpreter into collectd and provides an
24  * interface for collectd plugins written in perl.
25  */
26
27 /* do not automatically get the thread specific perl interpreter */
28 #define PERL_NO_GET_CONTEXT
29
30 #include "collectd.h"
31
32 #include "configfile.h"
33
34 #include <EXTERN.h>
35 #include <perl.h>
36
37 #include <XSUB.h>
38
39 /* Some versions of Perl define their own version of DEBUG... :-/ */
40 #ifdef DEBUG
41 # undef DEBUG
42 #endif /* DEBUG */
43
44 /* ... while we want the definition found in plugin.h. */
45 #include "plugin.h"
46 #include "common.h"
47
48 #include <pthread.h>
49
50 #if !defined(USE_ITHREADS)
51 # error "Perl does not support ithreads!"
52 #endif /* !defined(USE_ITHREADS) */
53
54 /* clear the Perl sub's stack frame
55  * (this should only be used inside an XSUB) */
56 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
57
58 #define PLUGIN_INIT     0
59 #define PLUGIN_READ     1
60 #define PLUGIN_WRITE    2
61 #define PLUGIN_SHUTDOWN 3
62 #define PLUGIN_LOG      4
63 #define PLUGIN_NOTIF    5
64
65 #define PLUGIN_TYPES    6
66
67 #define PLUGIN_DATASET  255
68
69 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
70 #define log_info(...) INFO ("perl: " __VA_ARGS__)
71 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
72 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
73
74 /* this is defined in DynaLoader.a */
75 void boot_DynaLoader (PerlInterpreter *, CV *);
76
77 static XS (Collectd_plugin_register_ds);
78 static XS (Collectd_plugin_unregister_ds);
79 static XS (Collectd_plugin_dispatch_values);
80 static XS (Collectd_plugin_dispatch_notification);
81 static XS (Collectd_plugin_log);
82 static XS (Collectd_call_by_name);
83
84 /*
85  * private data types
86  */
87
88 typedef struct c_ithread_s {
89         /* the thread's Perl interpreter */
90         PerlInterpreter *interp;
91
92         /* double linked list of threads */
93         struct c_ithread_s *prev;
94         struct c_ithread_s *next;
95 } c_ithread_t;
96
97 typedef struct {
98         c_ithread_t *head;
99         c_ithread_t *tail;
100
101 #if COLLECT_DEBUG
102         /* some usage stats */
103         int number_of_threads;
104 #endif /* COLLECT_DEBUG */
105
106         pthread_mutex_t mutex;
107 } c_ithread_list_t;
108
109 /*
110  * private variables
111  */
112
113 /* if perl_threads != NULL perl_threads->head must
114  * point to the "base" thread */
115 static c_ithread_list_t *perl_threads = NULL;
116
117 /* the key used to store each pthread's ithread */
118 static pthread_key_t perl_thr_key;
119
120 static int    perl_argc = 0;
121 static char **perl_argv = NULL;
122
123 static char base_name[DATA_MAX_NAME_LEN] = "";
124
125 static struct {
126         char name[64];
127         XS ((*f));
128 } api[] =
129 {
130         { "Collectd::plugin_register_data_set",   Collectd_plugin_register_ds },
131         { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
132         { "Collectd::plugin_dispatch_values",     Collectd_plugin_dispatch_values },
133         { "Collectd::plugin_dispatch_notification",
134                 Collectd_plugin_dispatch_notification },
135         { "Collectd::plugin_log",                 Collectd_plugin_log },
136         { "Collectd::call_by_name",               Collectd_call_by_name },
137         { "", NULL }
138 };
139
140 struct {
141         char name[64];
142         int  value;
143 } constants[] =
144 {
145         { "Collectd::TYPE_INIT",       PLUGIN_INIT },
146         { "Collectd::TYPE_READ",       PLUGIN_READ },
147         { "Collectd::TYPE_WRITE",      PLUGIN_WRITE },
148         { "Collectd::TYPE_SHUTDOWN",   PLUGIN_SHUTDOWN },
149         { "Collectd::TYPE_LOG",        PLUGIN_LOG },
150         { "Collectd::TYPE_NOTIF",      PLUGIN_NOTIF },
151         { "Collectd::TYPE_DATASET",    PLUGIN_DATASET },
152         { "Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER },
153         { "Collectd::DS_TYPE_GAUGE",   DS_TYPE_GAUGE },
154         { "Collectd::LOG_ERR",         LOG_ERR },
155         { "Collectd::LOG_WARNING",     LOG_WARNING },
156         { "Collectd::LOG_NOTICE",      LOG_NOTICE },
157         { "Collectd::LOG_INFO",        LOG_INFO },
158         { "Collectd::LOG_DEBUG",       LOG_DEBUG },
159         { "Collectd::NOTIF_FAILURE",   NOTIF_FAILURE },
160         { "Collectd::NOTIF_WARNING",   NOTIF_WARNING },
161         { "Collectd::NOTIF_OKAY",      NOTIF_OKAY },
162         { "", 0 }
163 };
164
165 struct {
166         char  name[64];
167         char *var;
168 } g_strings[] =
169 {
170         { "Collectd::hostname_g", hostname_g },
171         { "", NULL }
172 };
173
174 struct {
175         char  name[64];
176         int  *var;
177 } g_integers[] =
178 {
179         { "Collectd::interval_g", &interval_g },
180         { "", NULL }
181 };
182
183 /*
184  * Helper functions for data type conversion.
185  */
186
187 /*
188  * data source:
189  * [
190  *   {
191  *     name => $ds_name,
192  *     type => $ds_type,
193  *     min  => $ds_min,
194  *     max  => $ds_max
195  *   },
196  *   ...
197  * ]
198  */
199 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
200 {
201         SV **tmp = NULL;
202
203         if ((NULL == hash) || (NULL == ds))
204                 return -1;
205
206         if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
207                 strncpy (ds->name, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
208                 ds->name[DATA_MAX_NAME_LEN - 1] = '\0';
209         }
210         else {
211                 log_err ("hv2data_source: No DS name given.");
212                 return -1;
213         }
214
215         if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
216                 ds->type = SvIV (*tmp);
217
218                 if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type)) {
219                         log_err ("hv2data_source: Invalid DS type.");
220                         return -1;
221                 }
222         }
223         else {
224                 ds->type = DS_TYPE_COUNTER;
225         }
226
227         if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
228                 ds->min = SvNV (*tmp);
229         else
230                 ds->min = NAN;
231
232         if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
233                 ds->max = SvNV (*tmp);
234         else
235                 ds->max = NAN;
236         return 0;
237 } /* static data_source_t *hv2data_source (HV *) */
238
239 static int av2value (pTHX_ char *name, AV *array, value_t *value, int len)
240 {
241         const data_set_t *ds;
242
243         int i = 0;
244
245         if ((NULL == name) || (NULL == array) || (NULL == value))
246                 return -1;
247
248         if (av_len (array) < len - 1)
249                 len = av_len (array) + 1;
250
251         if (0 >= len)
252                 return -1;
253
254         ds = plugin_get_ds (name);
255         if (NULL == ds) {
256                 log_err ("av2value: Unknown dataset \"%s\"", name);
257                 return -1;
258         }
259
260         if (ds->ds_num < len) {
261                 log_warn ("av2value: Value length exceeds data set length.");
262                 len = ds->ds_num;
263         }
264
265         for (i = 0; i < len; ++i) {
266                 SV **tmp = av_fetch (array, i, 0);
267
268                 if (NULL != tmp) {
269                         if (DS_TYPE_COUNTER == ds->ds[i].type)
270                                 value[i].counter = SvIV (*tmp);
271                         else
272                                 value[i].gauge = SvNV (*tmp);
273                 }
274                 else {
275                         return -1;
276                 }
277         }
278         return len;
279 } /* static int av2value (char *, AV *, value_t *, int) */
280
281 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
282 {
283         int i = 0;
284
285         if ((NULL == ds) || (NULL == array))
286                 return -1;
287
288         av_extend (array, ds->ds_num);
289
290         for (i = 0; i < ds->ds_num; ++i) {
291                 HV *source = newHV ();
292
293                 if (NULL == hv_store (source, "name", 4,
294                                 newSVpv (ds->ds[i].name, 0), 0))
295                         return -1;
296
297                 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
298                         return -1;
299
300                 if (! isnan (ds->ds[i].min))
301                         if (NULL == hv_store (source, "min", 3,
302                                         newSVnv (ds->ds[i].min), 0))
303                                 return -1;
304
305                 if (! isnan (ds->ds[i].max))
306                         if (NULL == hv_store (source, "max", 3,
307                                         newSVnv (ds->ds[i].max), 0))
308                                 return -1;
309
310                 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
311                         return -1;
312         }
313         return 0;
314 } /* static int data_set2av (data_set_t *, AV *) */
315
316 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
317 {
318         AV *values = NULL;
319
320         int i   = 0;
321         int len = 0;
322
323         if ((NULL == vl) || (NULL == ds) || (NULL == hash))
324                 return -1;
325
326         len = vl->values_len;
327
328         if (ds->ds_num < len) {
329                 log_warn ("value2av: Value length exceeds data set length.");
330                 len = ds->ds_num;
331         }
332
333         values = newAV ();
334         av_extend (values, len - 1);
335
336         for (i = 0; i < len; ++i) {
337                 SV *val = NULL;
338
339                 if (DS_TYPE_COUNTER == ds->ds[i].type)
340                         val = newSViv (vl->values[i].counter);
341                 else
342                         val = newSVnv (vl->values[i].gauge);
343
344                 if (NULL == av_store (values, i, val)) {
345                         av_undef (values);
346                         return -1;
347                 }
348         }
349
350         if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
351                 return -1;
352
353         if (0 != vl->time)
354                 if (NULL == hv_store (hash, "time", 4, newSViv (vl->time), 0))
355                         return -1;
356
357         if ('\0' != vl->host[0])
358                 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
359                         return -1;
360
361         if ('\0' != vl->plugin[0])
362                 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
363                         return -1;
364
365         if ('\0' != vl->plugin_instance[0])
366                 if (NULL == hv_store (hash, "plugin_instance", 15,
367                                 newSVpv (vl->plugin_instance, 0), 0))
368                         return -1;
369
370         if ('\0' != vl->type_instance[0])
371                 if (NULL == hv_store (hash, "type_instance", 13,
372                                 newSVpv (vl->type_instance, 0), 0))
373                         return -1;
374         return 0;
375 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
376
377 static int notification2hv (pTHX_ notification_t *n, HV *hash)
378 {
379         if (NULL == hv_store (hash, "severity", 8, newSViv (n->severity), 0))
380                 return -1;
381
382         if (0 != n->time)
383                 if (NULL == hv_store (hash, "time", 4, newSViv (n->time), 0))
384                         return -1;
385
386         if ('\0' != *n->message)
387                 if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
388                         return -1;
389
390         if ('\0' != *n->host)
391                 if (NULL == hv_store (hash, "host", 4, newSVpv (n->host, 0), 0))
392                         return -1;
393
394         if ('\0' != *n->plugin)
395                 if (NULL == hv_store (hash, "plugin", 6, newSVpv (n->plugin, 0), 0))
396                         return -1;
397
398         if ('\0' != *n->plugin_instance)
399                 if (NULL == hv_store (hash, "plugin_instance", 15,
400                                 newSVpv (n->plugin_instance, 0), 0))
401                         return -1;
402
403         if ('\0' != *n->type)
404                 if (NULL == hv_store (hash, "type", 4, newSVpv (n->type, 0), 0))
405                         return -1;
406
407         if ('\0' != *n->type_instance)
408                 if (NULL == hv_store (hash, "type_instance", 13,
409                                 newSVpv (n->type_instance, 0), 0))
410                         return -1;
411         return 0;
412 } /* static int notification2hv (notification_t *, HV *) */
413
414 /*
415  * Internal functions.
416  */
417
418 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
419         int status = 0;
420         if (base_name[0] == '\0')
421                 status = snprintf (buf, buf_len, "%s", module);
422         else
423                 status = snprintf (buf, buf_len, "%s::%s", base_name, module);
424         if ((status < 0) || ((unsigned int)status >= buf_len))
425                 return (NULL);
426         buf[buf_len - 1] = '\0';
427         return (buf);
428 } /* char *get_module_name */
429
430 /*
431  * Add a plugin's data set definition.
432  */
433 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
434 {
435         int len = -1;
436         int ret = 0;
437         int i   = 0;
438
439         data_source_t *ds  = NULL;
440         data_set_t    *set = NULL;
441
442         if ((NULL == name) || (NULL == dataset))
443                 return -1;
444
445         len = av_len (dataset);
446
447         if (-1 == len)
448                 return -1;
449
450         ds  = (data_source_t *)smalloc ((len + 1) * sizeof (data_source_t));
451         set = (data_set_t *)smalloc (sizeof (data_set_t));
452
453         for (i = 0; i <= len; ++i) {
454                 SV **elem = av_fetch (dataset, i, 0);
455
456                 if (NULL == elem)
457                         return -1;
458
459                 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
460                         log_err ("pplugin_register_data_set: Invalid data source.");
461                         return -1;
462                 }
463
464                 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds[i]))
465                         return -1;
466
467                 log_debug ("pplugin_register_data_set: "
468                                 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
469                                 ds[i].name, ds[i].type, ds[i].min, ds[i].max);
470         }
471
472         strncpy (set->type, name, DATA_MAX_NAME_LEN);
473         set->type[DATA_MAX_NAME_LEN - 1] = '\0';
474
475         set->ds_num = len + 1;
476         set->ds = ds;
477
478         ret = plugin_register_data_set (set);
479
480         free (ds);
481         free (set);
482         return ret;
483 } /* static int pplugin_register_data_set (char *, SV *) */
484
485 /*
486  * Remove a plugin's data set definition.
487  */
488 static int pplugin_unregister_data_set (char *name)
489 {
490         if (NULL == name)
491                 return 0;
492         return plugin_unregister_data_set (name);
493 } /* static int pplugin_unregister_data_set (char *) */
494
495 /*
496  * Submit the values to the write functions.
497  *
498  * value list:
499  * {
500  *   values => [ @values ],
501  *   time   => $time,
502  *   host   => $host,
503  *   plugin => $plugin,
504  *   plugin_instance => $pinstance,
505  *   type_instance   => $tinstance,
506  * }
507  */
508 static int pplugin_dispatch_values (pTHX_ char *name, HV *values)
509 {
510         value_list_t list = VALUE_LIST_INIT;
511         value_t      *val = NULL;
512
513         SV **tmp = NULL;
514
515         int ret = 0;
516
517         if ((NULL == name) || (NULL == values))
518                 return -1;
519
520         if ((NULL == (tmp = hv_fetch (values, "values", 6, 0)))
521                         || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
522                 log_err ("pplugin_dispatch_values: No valid values given.");
523                 return -1;
524         }
525
526         {
527                 AV  *array = (AV *)SvRV (*tmp);
528                 int len    = av_len (array) + 1;
529
530                 if (len <= 0)
531                         return -1;
532
533                 val = (value_t *)smalloc (len * sizeof (value_t));
534
535                 list.values_len = av2value (aTHX_ name, (AV *)SvRV (*tmp), val, len);
536                 list.values = val;
537
538                 if (-1 == list.values_len) {
539                         sfree (val);
540                         return -1;
541                 }
542         }
543
544         if (NULL != (tmp = hv_fetch (values, "time", 4, 0))) {
545                 list.time = (time_t)SvIV (*tmp);
546         }
547         else {
548                 list.time = time (NULL);
549         }
550
551         if (NULL != (tmp = hv_fetch (values, "host", 4, 0))) {
552                 strncpy (list.host, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
553                 list.host[DATA_MAX_NAME_LEN - 1] = '\0';
554         }
555         else {
556                 strcpy (list.host, hostname_g);
557         }
558
559         if (NULL != (tmp = hv_fetch (values, "plugin", 6, 0))) {
560                 strncpy (list.plugin, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
561                 list.plugin[DATA_MAX_NAME_LEN - 1] = '\0';
562         }
563
564         if (NULL != (tmp = hv_fetch (values, "plugin_instance", 15, 0))) {
565                 strncpy (list.plugin_instance, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
566                 list.plugin_instance[DATA_MAX_NAME_LEN - 1] = '\0';
567         }
568
569         if (NULL != (tmp = hv_fetch (values, "type_instance", 13, 0))) {
570                 strncpy (list.type_instance, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
571                 list.type_instance[DATA_MAX_NAME_LEN - 1] = '\0';
572         }
573
574         ret = plugin_dispatch_values (name, &list);
575
576         sfree (val);
577         return ret;
578 } /* static int pplugin_dispatch_values (char *, HV *) */
579
580 /*
581  * Dispatch a notification.
582  *
583  * notification:
584  * {
585  *   severity => $severity,
586  *   time     => $time,
587  *   message  => $msg,
588  *   host     => $host,
589  *   plugin   => $plugin,
590  *   type     => $type,
591  *   plugin_instance => $instance,
592  *   type_instance   => $type_instance
593  * }
594  */
595 static int pplugin_dispatch_notification (pTHX_ HV *notif)
596 {
597         notification_t n;
598
599         SV **tmp = NULL;
600
601         if (NULL == notif)
602                 return -1;
603
604         memset (&n, 0, sizeof (n));
605
606         if (NULL != (tmp = hv_fetch (notif, "severity", 8, 0)))
607                 n.severity = SvIV (*tmp);
608         else
609                 n.severity = NOTIF_FAILURE;
610
611         if (NULL != (tmp = hv_fetch (notif, "time", 4, 0)))
612                 n.time = (time_t)SvIV (*tmp);
613         else
614                 n.time = time (NULL);
615
616         if (NULL != (tmp = hv_fetch (notif, "message", 7, 0)))
617                 strncpy (n.message, SvPV_nolen (*tmp), sizeof (n.message));
618         n.message[sizeof (n.message) - 1] = '\0';
619
620         if (NULL != (tmp = hv_fetch (notif, "host", 4, 0)))
621                 strncpy (n.host, SvPV_nolen (*tmp), sizeof (n.host));
622         else
623                 strncpy (n.host, hostname_g, sizeof (n.host));
624         n.host[sizeof (n.host) - 1] = '\0';
625
626         if (NULL != (tmp = hv_fetch (notif, "plugin", 6, 0)))
627                 strncpy (n.plugin, SvPV_nolen (*tmp), sizeof (n.plugin));
628         n.plugin[sizeof (n.plugin) - 1] = '\0';
629
630         if (NULL != (tmp = hv_fetch (notif, "plugin_instance", 15, 0)))
631                 strncpy (n.plugin_instance, SvPV_nolen (*tmp),
632                                 sizeof (n.plugin_instance));
633         n.plugin_instance[sizeof (n.plugin_instance) - 1] = '\0';
634
635         if (NULL != (tmp = hv_fetch (notif, "type", 4, 0)))
636                 strncpy (n.type, SvPV_nolen (*tmp), sizeof (n.type));
637         n.type[sizeof (n.type) - 1] = '\0';
638
639         if (NULL != (tmp = hv_fetch (notif, "type_instance", 13, 0)))
640                 strncpy (n.type_instance, SvPV_nolen (*tmp), sizeof (n.type_instance));
641         n.type_instance[sizeof (n.type_instance) - 1] = '\0';
642         return plugin_dispatch_notification (&n);
643 } /* static int pplugin_dispatch_notification (HV *) */
644
645 /*
646  * Call all working functions of the given type.
647  */
648 static int pplugin_call_all (pTHX_ int type, ...)
649 {
650         int retvals = 0;
651
652         va_list ap;
653         int ret = 0;
654
655         dSP;
656
657         if ((type < 0) || (type >= PLUGIN_TYPES))
658                 return -1;
659
660         va_start (ap, type);
661
662         ENTER;
663         SAVETMPS;
664
665         PUSHMARK (SP);
666
667         XPUSHs (sv_2mortal (newSViv ((IV)type)));
668
669         if (PLUGIN_WRITE == type) {
670                 /*
671                  * $_[0] = $plugin_type;
672                  *
673                  * $_[1] =
674                  * [
675                  *   {
676                  *     name => $ds_name,
677                  *     type => $ds_type,
678                  *     min  => $ds_min,
679                  *     max  => $ds_max
680                  *   },
681                  *   ...
682                  * ];
683                  *
684                  * $_[2] =
685                  * {
686                  *   values => [ $v1, ... ],
687                  *   time   => $time,
688                  *   host   => $hostname,
689                  *   plugin => $plugin,
690                  *   plugin_instance => $instance,
691                  *   type_instance   => $type_instance
692                  * };
693                  */
694                 data_set_t   *ds;
695                 value_list_t *vl;
696
697                 AV *pds = newAV ();
698                 HV *pvl = newHV ();
699
700                 ds = va_arg (ap, data_set_t *);
701                 vl = va_arg (ap, value_list_t *);
702
703                 if (-1 == data_set2av (aTHX_ ds, pds)) {
704                         av_clear (pds);
705                         av_undef (pds);
706                         pds = Nullav;
707                         ret = -1;
708                 }
709
710                 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
711                         hv_clear (pvl);
712                         hv_undef (pvl);
713                         pvl = Nullhv;
714                         ret = -1;
715                 }
716
717                 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
718                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
719                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
720         }
721         else if (PLUGIN_LOG == type) {
722                 /*
723                  * $_[0] = $level;
724                  *
725                  * $_[1] = $message;
726                  */
727                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
728                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
729         }
730         else if (PLUGIN_NOTIF == type) {
731                 /*
732                  * $_[0] =
733                  * {
734                  *   severity => $severity,
735                  *   time     => $time,
736                  *   message  => $msg,
737                  *   host     => $host,
738                  *   plugin   => $plugin,
739                  *   type     => $type,
740                  *   plugin_instance => $instance,
741                  *   type_instance   => $type_instance
742                  * };
743                  */
744                 notification_t *n;
745                 HV *notif = newHV ();
746
747                 n = va_arg (ap, notification_t *);
748
749                 if (-1 == notification2hv (aTHX_ n, notif)) {
750                         hv_clear (notif);
751                         hv_undef (notif);
752                         notif = Nullhv;
753                         ret = -1;
754                 }
755
756                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
757         }
758
759         PUTBACK;
760
761         retvals = call_pv ("Collectd::plugin_call_all", G_SCALAR);
762
763         SPAGAIN;
764         if (0 < retvals) {
765                 SV *tmp = POPs;
766                 if (! SvTRUE (tmp))
767                         ret = -1;
768         }
769
770         PUTBACK;
771         FREETMPS;
772         LEAVE;
773
774         va_end (ap);
775         return ret;
776 } /* static int pplugin_call_all (int, ...) */
777
778 /*
779  * Exported Perl API.
780  */
781
782 /*
783  * Collectd::plugin_register_data_set (type, dataset).
784  *
785  * type:
786  *   type of the dataset
787  *
788  * dataset:
789  *   dataset to be registered
790  */
791 static XS (Collectd_plugin_register_ds)
792 {
793         SV  *data = NULL;
794         int ret   = 0;
795
796         dXSARGS;
797
798         if (2 != items) {
799                 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
800                 XSRETURN_EMPTY;
801         }
802
803         log_debug ("Collectd::plugin_register_data_set: "
804                         "type = \"%s\", dataset = \"%s\"",
805                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
806
807         data = ST (1);
808
809         if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
810                 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
811                                 (AV *)SvRV (data));
812         }
813         else {
814                 log_err ("Collectd::plugin_register_data_set: Invalid data.");
815                 XSRETURN_EMPTY;
816         }
817
818         if (0 == ret)
819                 XSRETURN_YES;
820         else
821                 XSRETURN_EMPTY;
822 } /* static XS (Collectd_plugin_register_ds) */
823
824 /*
825  * Collectd::plugin_unregister_data_set (type).
826  *
827  * type:
828  *   type of the dataset
829  */
830 static XS (Collectd_plugin_unregister_ds)
831 {
832         dXSARGS;
833
834         if (1 != items) {
835                 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
836                 XSRETURN_EMPTY;
837         }
838
839         log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
840                         SvPV_nolen (ST (0)));
841
842         if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
843                 XSRETURN_YES;
844         else
845                 XSRETURN_EMPTY;
846 } /* static XS (Collectd_plugin_register_ds) */
847
848 /*
849  * Collectd::plugin_dispatch_values (name, values).
850  *
851  * name:
852  *   name of the plugin
853  *
854  * values:
855  *   value list to submit
856  */
857 static XS (Collectd_plugin_dispatch_values)
858 {
859         SV *values = NULL;
860
861         int ret = 0;
862
863         dXSARGS;
864
865         if (2 != items) {
866                 log_err ("Usage: Collectd::plugin_dispatch_values(name, values)");
867                 XSRETURN_EMPTY;
868         }
869
870         log_debug ("Collectd::plugin_dispatch_values: "
871                         "name = \"%s\", values=\"%s\"",
872                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
873
874         values = ST (1);
875
876         if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
877                 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
878                 XSRETURN_EMPTY;
879         }
880
881         if ((NULL == ST (0)) || (NULL == values))
882                 XSRETURN_EMPTY;
883
884         ret = pplugin_dispatch_values (aTHX_ SvPV_nolen (ST (0)),
885                         (HV *)SvRV (values));
886
887         if (0 == ret)
888                 XSRETURN_YES;
889         else
890                 XSRETURN_EMPTY;
891 } /* static XS (Collectd_plugin_dispatch_values) */
892
893 /*
894  * Collectd::plugin_dispatch_notification (notif).
895  *
896  * notif:
897  *   notification to dispatch
898  */
899 static XS (Collectd_plugin_dispatch_notification)
900 {
901         SV *notif = NULL;
902
903         int ret = 0;
904
905         dXSARGS;
906
907         if (1 != items) {
908                 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
909                 XSRETURN_EMPTY;
910         }
911
912         log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
913                         SvPV_nolen (ST (0)));
914
915         notif = ST (0);
916
917         if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
918                 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
919                 XSRETURN_EMPTY;
920         }
921
922         ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
923
924         if (0 == ret)
925                 XSRETURN_YES;
926         else
927                 XSRETURN_EMPTY;
928 } /* static XS (Collectd_plugin_dispatch_notification) */
929
930 /*
931  * Collectd::plugin_log (level, message).
932  *
933  * level:
934  *   log level (LOG_DEBUG, ... LOG_ERR)
935  *
936  * message:
937  *   log message
938  */
939 static XS (Collectd_plugin_log)
940 {
941         dXSARGS;
942
943         if (2 != items) {
944                 log_err ("Usage: Collectd::plugin_log(level, message)");
945                 XSRETURN_EMPTY;
946         }
947
948         plugin_log (SvIV (ST (0)), SvPV_nolen (ST (1)));
949         XSRETURN_YES;
950 } /* static XS (Collectd_plugin_log) */
951
952 /*
953  * Collectd::call_by_name (...).
954  *
955  * Call a Perl sub identified by its name passed through $Collectd::cb_name.
956  */
957 static XS (Collectd_call_by_name)
958 {
959         SV   *tmp  = NULL;
960         char *name = NULL;
961
962         if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
963                 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
964                 CLEAR_STACK_FRAME;
965                 return;
966         }
967
968         name = SvPV_nolen (tmp);
969
970         if (NULL == get_cv (name, 0)) {
971                 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
972                 CLEAR_STACK_FRAME;
973                 return;
974         }
975
976         /* simply pass on the subroutine call without touching the stack,
977          * thus leaving any arguments and return values in place */
978         call_pv (name, 0);
979 } /* static XS (Collectd_call_by_name) */
980
981 /*
982  * collectd's perl interpreter based thread implementation.
983  *
984  * This has been inspired by Perl's ithreads introduced in version 5.6.0.
985  */
986
987 /* must be called with perl_threads->mutex locked */
988 static void c_ithread_destroy (c_ithread_t *ithread)
989 {
990         dTHXa (ithread->interp);
991
992         assert (NULL != perl_threads);
993
994         PERL_SET_CONTEXT (aTHX);
995         log_debug ("Shutting down Perl interpreter %p...", aTHX);
996
997 #if COLLECT_DEBUG
998         sv_report_used ();
999
1000         --perl_threads->number_of_threads;
1001 #endif /* COLLECT_DEBUG */
1002
1003         perl_destruct (aTHX);
1004         perl_free (aTHX);
1005
1006         if (NULL == ithread->prev)
1007                 perl_threads->head = ithread->next;
1008         else
1009                 ithread->prev->next = ithread->next;
1010
1011         if (NULL == ithread->next)
1012                 perl_threads->tail = ithread->prev;
1013         else
1014                 ithread->next->prev = ithread->prev;
1015
1016         sfree (ithread);
1017         return;
1018 } /* static void c_ithread_destroy (c_ithread_t *) */
1019
1020 static void c_ithread_destructor (void *arg)
1021 {
1022         c_ithread_t *ithread = (c_ithread_t *)arg;
1023         c_ithread_t *t = NULL;
1024
1025         if (NULL == perl_threads)
1026                 return;
1027
1028         pthread_mutex_lock (&perl_threads->mutex);
1029
1030         for (t = perl_threads->head; NULL != t; t = t->next)
1031                 if (t == ithread)
1032                         break;
1033
1034         /* the ithread no longer exists */
1035         if (NULL == t)
1036                 return;
1037
1038         c_ithread_destroy (ithread);
1039
1040         pthread_mutex_unlock (&perl_threads->mutex);
1041         return;
1042 } /* static void c_ithread_destructor (void *) */
1043
1044 /* must be called with perl_threads->mutex locked */
1045 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1046 {
1047         c_ithread_t *t = NULL;
1048         dTHXa (NULL);
1049
1050         assert (NULL != perl_threads);
1051
1052         t = (c_ithread_t *)smalloc (sizeof (c_ithread_t));
1053         memset (t, 0, sizeof (c_ithread_t));
1054
1055         t->interp = (NULL == base)
1056                 ? NULL
1057                 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1058
1059         aTHX = t->interp;
1060
1061         if (NULL != base) {
1062                 av_clear (PL_endav);
1063                 av_undef (PL_endav);
1064                 PL_endav = Nullav;
1065         }
1066
1067 #if COLLECT_DEBUG
1068         ++perl_threads->number_of_threads;
1069 #endif /* COLLECT_DEBUG */
1070
1071         t->next = NULL;
1072
1073         if (NULL == perl_threads->tail) {
1074                 perl_threads->head = t;
1075                 t->prev = NULL;
1076         }
1077         else {
1078                 perl_threads->tail->next = t;
1079                 t->prev = perl_threads->tail;
1080         }
1081
1082         perl_threads->tail = t;
1083
1084         pthread_setspecific (perl_thr_key, (const void *)t);
1085         return t;
1086 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1087
1088 /*
1089  * Interface to collectd.
1090  */
1091
1092 static int perl_init (void)
1093 {
1094         dTHX;
1095
1096         if (NULL == perl_threads)
1097                 return 0;
1098
1099         if (NULL == aTHX) {
1100                 c_ithread_t *t = NULL;
1101
1102                 pthread_mutex_lock (&perl_threads->mutex);
1103                 t = c_ithread_create (perl_threads->head->interp);
1104                 pthread_mutex_unlock (&perl_threads->mutex);
1105
1106                 aTHX = t->interp;
1107         }
1108
1109         log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1110                         aTHX, perl_threads->number_of_threads);
1111         return pplugin_call_all (aTHX_ PLUGIN_INIT);
1112 } /* static int perl_init (void) */
1113
1114 static int perl_read (void)
1115 {
1116         dTHX;
1117
1118         if (NULL == perl_threads)
1119                 return 0;
1120
1121         if (NULL == aTHX) {
1122                 c_ithread_t *t = NULL;
1123
1124                 pthread_mutex_lock (&perl_threads->mutex);
1125                 t = c_ithread_create (perl_threads->head->interp);
1126                 pthread_mutex_unlock (&perl_threads->mutex);
1127
1128                 aTHX = t->interp;
1129         }
1130
1131         log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1132                         aTHX, perl_threads->number_of_threads);
1133         return pplugin_call_all (aTHX_ PLUGIN_READ);
1134 } /* static int perl_read (void) */
1135
1136 static int perl_write (const data_set_t *ds, const value_list_t *vl)
1137 {
1138         dTHX;
1139
1140         if (NULL == perl_threads)
1141                 return 0;
1142
1143         if (NULL == aTHX) {
1144                 c_ithread_t *t = NULL;
1145
1146                 pthread_mutex_lock (&perl_threads->mutex);
1147                 t = c_ithread_create (perl_threads->head->interp);
1148                 pthread_mutex_unlock (&perl_threads->mutex);
1149
1150                 aTHX = t->interp;
1151         }
1152
1153         log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
1154                         aTHX, perl_threads->number_of_threads);
1155         return pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
1156 } /* static int perl_write (const data_set_t *, const value_list_t *) */
1157
1158 static void perl_log (int level, const char *msg)
1159 {
1160         dTHX;
1161
1162         if (NULL == perl_threads)
1163                 return;
1164
1165         if (NULL == aTHX) {
1166                 c_ithread_t *t = NULL;
1167
1168                 pthread_mutex_lock (&perl_threads->mutex);
1169                 t = c_ithread_create (perl_threads->head->interp);
1170                 pthread_mutex_unlock (&perl_threads->mutex);
1171
1172                 aTHX = t->interp;
1173         }
1174
1175         pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
1176         return;
1177 } /* static void perl_log (int, const char *) */
1178
1179 static int perl_notify (const notification_t *notif)
1180 {
1181         dTHX;
1182
1183         if (NULL == perl_threads)
1184                 return 0;
1185
1186         if (NULL == aTHX) {
1187                 c_ithread_t *t = NULL;
1188
1189                 pthread_mutex_lock (&perl_threads->mutex);
1190                 t = c_ithread_create (perl_threads->head->interp);
1191                 pthread_mutex_unlock (&perl_threads->mutex);
1192
1193                 aTHX = t->interp;
1194         }
1195         return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
1196 } /* static int perl_notify (const notification_t *) */
1197
1198 static int perl_shutdown (void)
1199 {
1200         c_ithread_t *t = NULL;
1201
1202         int ret = 0;
1203
1204         dTHX;
1205
1206         plugin_unregister_complex_config ("perl");
1207
1208         if (NULL == perl_threads)
1209                 return 0;
1210
1211         if (NULL == aTHX) {
1212                 c_ithread_t *t = NULL;
1213
1214                 pthread_mutex_lock (&perl_threads->mutex);
1215                 t = c_ithread_create (perl_threads->head->interp);
1216                 pthread_mutex_unlock (&perl_threads->mutex);
1217
1218                 aTHX = t->interp;
1219         }
1220
1221         log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
1222                         aTHX, perl_threads->number_of_threads);
1223
1224         plugin_unregister_log ("perl");
1225         plugin_unregister_notification ("perl");
1226         plugin_unregister_init ("perl");
1227         plugin_unregister_read ("perl");
1228         plugin_unregister_write ("perl");
1229
1230         ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
1231
1232         pthread_mutex_lock (&perl_threads->mutex);
1233         t = perl_threads->tail;
1234
1235         while (NULL != t) {
1236                 c_ithread_t *thr = t;
1237
1238                 /* the pointer has to be advanced before destroying
1239                  * the thread as this will free the memory */
1240                 t = t->prev;
1241
1242                 c_ithread_destroy (thr);
1243         }
1244
1245         pthread_mutex_unlock (&perl_threads->mutex);
1246         pthread_mutex_destroy (&perl_threads->mutex);
1247
1248         sfree (perl_threads);
1249
1250         pthread_key_delete (perl_thr_key);
1251
1252         PERL_SYS_TERM ();
1253
1254         plugin_unregister_shutdown ("perl");
1255         return ret;
1256 } /* static void perl_shutdown (void) */
1257
1258 /*
1259  * Access functions for global variables.
1260  *
1261  * These functions implement the "magic" used to access
1262  * the global variables from Perl.
1263  */
1264
1265 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
1266 {
1267         char *pv = mg->mg_ptr;
1268         sv_setpv (var, pv);
1269         return 0;
1270 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
1271
1272 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
1273 {
1274         char *pv = mg->mg_ptr;
1275         strncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
1276         pv[DATA_MAX_NAME_LEN - 1] = '\0';
1277         return 0;
1278 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
1279
1280 static int g_iv_get (pTHX_ SV *var, MAGIC *mg)
1281 {
1282         int *iv = (int *)mg->mg_ptr;
1283         sv_setiv (var, *iv);
1284         return 0;
1285 } /* static int g_iv_get (pTHX_ SV *, MAGIC *) */
1286
1287 static int g_iv_set (pTHX_ SV *var, MAGIC *mg)
1288 {
1289         int *iv = (int *)mg->mg_ptr;
1290         *iv = (int)SvIV (var);
1291         return 0;
1292 } /* static int g_iv_set (pTHX_ SV *, MAGIC *) */
1293
1294 static MGVTBL g_pv_vtbl = { g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL };
1295 static MGVTBL g_iv_vtbl = { g_iv_get, g_iv_set, NULL, NULL, NULL, NULL, NULL };
1296
1297 /* bootstrap the Collectd module */
1298 static void xs_init (pTHX)
1299 {
1300         HV   *stash = NULL;
1301         SV   *tmp   = NULL;
1302         char *file  = __FILE__;
1303
1304         int i = 0;
1305
1306         dXSUB_SYS;
1307
1308         /* enable usage of Perl modules using shared libraries */
1309         newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
1310
1311         /* register API */
1312         for (i = 0; NULL != api[i].f; ++i)
1313                 newXS (api[i].name, api[i].f, file);
1314
1315         stash = gv_stashpv ("Collectd", 1);
1316
1317         /* export "constants" */
1318         for (i = 0; '\0' != constants[i].name[0]; ++i)
1319                 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
1320
1321         /* export global variables
1322          * by adding "magic" to the SV's representing the globale variables
1323          * perl is able to automagically call the get/set function when
1324          * accessing any such variable (this is basically the same as using
1325          * tie() in Perl) */
1326         /* global strings */
1327         for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
1328                 tmp = get_sv (g_strings[i].name, 1);
1329                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
1330                                 g_strings[i].var, 0);
1331         }
1332
1333         /* global integers */
1334         for (i = 0; '\0' != g_integers[i].name[0]; ++i) {
1335                 tmp = get_sv (g_integers[i].name, 1);
1336                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_iv_vtbl,
1337                                 (char *)g_integers[i].var, 0);
1338         }
1339         return;
1340 } /* static void xs_init (pTHX) */
1341
1342 /* Initialize the global Perl interpreter. */
1343 static int init_pi (int argc, char **argv)
1344 {
1345         dTHXa (NULL);
1346
1347         if (NULL != perl_threads)
1348                 return 0;
1349
1350         log_info ("Initializing Perl interpreter...");
1351 #if COLLECT_DEBUG
1352         {
1353                 int i = 0;
1354
1355                 for (i = 0; i < argc; ++i)
1356                         log_debug ("argv[%i] = \"%s\"", i, argv[i]);
1357         }
1358 #endif /* COLLECT_DEBUG */
1359
1360         if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
1361                 log_err ("init_pi: pthread_key_create failed");
1362
1363                 /* this must not happen - cowardly giving up if it does */
1364                 exit (1);
1365         }
1366
1367         PERL_SYS_INIT3 (&argc, &argv, &environ);
1368
1369         perl_threads = (c_ithread_list_t *)smalloc (sizeof (c_ithread_list_t));
1370         memset (perl_threads, 0, sizeof (c_ithread_list_t));
1371
1372         pthread_mutex_init (&perl_threads->mutex, NULL);
1373         /* locking the mutex should not be necessary at this point
1374          * but let's just do it for the sake of completeness */
1375         pthread_mutex_lock (&perl_threads->mutex);
1376
1377         perl_threads->head = c_ithread_create (NULL);
1378         perl_threads->tail = perl_threads->head;
1379
1380         if (NULL == (perl_threads->head->interp = perl_alloc ())) {
1381                 log_err ("init_pi: Not enough memory.");
1382                 exit (3);
1383         }
1384
1385         aTHX = perl_threads->head->interp;
1386         pthread_mutex_unlock (&perl_threads->mutex);
1387
1388         perl_construct (aTHX);
1389
1390         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1391
1392         if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
1393                 log_err ("init_pi: Unable to bootstrap Collectd.");
1394                 exit (1);
1395         }
1396
1397         /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
1398         sv_setpv (get_sv ("0", 0), "collectd");
1399
1400         perl_run (aTHX);
1401
1402         plugin_register_log ("perl", perl_log);
1403         plugin_register_notification ("perl", perl_notify);
1404         plugin_register_init ("perl", perl_init);
1405
1406         plugin_register_read ("perl", perl_read);
1407
1408         plugin_register_write ("perl", perl_write);
1409         plugin_register_shutdown ("perl", perl_shutdown);
1410         return 0;
1411 } /* static int init_pi (const char **, const int) */
1412
1413 /*
1414  * LoadPlugin "<Plugin>"
1415  */
1416 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
1417 {
1418         char module_name[DATA_MAX_NAME_LEN];
1419
1420         char *value = NULL;
1421
1422         if ((0 != ci->children_num) || (1 != ci->values_num)
1423                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1424                 log_err ("LoadPlugin expects a single string argument.");
1425                 return 1;
1426         }
1427
1428         value = ci->values[0].value.string;
1429
1430         if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
1431                 log_err ("Invalid module name %s", value);
1432                 return (1);
1433         }
1434
1435         init_pi (perl_argc, perl_argv);
1436         assert (NULL != perl_threads);
1437         assert (NULL != perl_threads->head);
1438
1439         aTHX = perl_threads->head->interp;
1440
1441         log_debug ("perl_config: loading perl plugin \"%s\"", value);
1442         load_module (PERL_LOADMOD_NOIMPORT,
1443                         newSVpv (module_name, strlen (module_name)), Nullsv);
1444         return 0;
1445 } /* static int perl_config_loadplugin (oconfig_item_it *) */
1446
1447 /*
1448  * BaseName "<Name>"
1449  */
1450 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
1451 {
1452         char *value = NULL;
1453
1454         if ((0 != ci->children_num) || (1 != ci->values_num)
1455                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1456                 log_err ("BaseName expects a single string argument.");
1457                 return 1;
1458         }
1459
1460         value = ci->values[0].value.string;
1461
1462         log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
1463         strncpy (base_name, value, sizeof (base_name));
1464         base_name[sizeof (base_name) - 1] = '\0';
1465         return 0;
1466 } /* static int perl_config_basename (oconfig_item_it *) */
1467
1468 /*
1469  * EnableDebugger "<Package>"|""
1470  */
1471 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
1472 {
1473         char *value = NULL;
1474
1475         if ((0 != ci->children_num) || (1 != ci->values_num)
1476                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1477                 log_err ("EnableDebugger expects a single string argument.");
1478                 return 1;
1479         }
1480
1481         value = ci->values[0].value.string;
1482
1483         perl_argv = (char **)realloc (perl_argv,
1484                         (++perl_argc + 1) * sizeof (char *));
1485
1486         if (NULL == perl_argv) {
1487                 log_err ("perl_config: Not enough memory.");
1488                 exit (3);
1489         }
1490
1491         if ('\0' == value[0]) {
1492                 perl_argv[perl_argc - 1] = "-d";
1493         }
1494         else {
1495                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 4);
1496                 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
1497                 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
1498         }
1499
1500         perl_argv[perl_argc] = NULL;
1501         return 0;
1502 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
1503
1504 /*
1505  * IncludeDir "<Dir>"
1506  */
1507 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
1508 {
1509         char *value = NULL;
1510
1511         if ((0 != ci->children_num) || (1 != ci->values_num)
1512                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1513                 log_err ("IncludeDir expects a single string argument.");
1514                 return 1;
1515         }
1516
1517         value = ci->values[0].value.string;
1518
1519         if (NULL == aTHX) {
1520                 perl_argv = (char **)realloc (perl_argv,
1521                                 (++perl_argc + 1) * sizeof (char *));
1522
1523                 if (NULL == perl_argv) {
1524                         log_err ("perl_config: Not enough memory.");
1525                         exit (3);
1526                 }
1527
1528                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 3);
1529                 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
1530                 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
1531
1532                 perl_argv[perl_argc] = NULL;
1533         }
1534         else {
1535                 /* prepend the directory to @INC */
1536                 av_unshift (GvAVn (PL_incgv), 1);
1537                 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
1538         }
1539         return 0;
1540 } /* static int perl_config_includedir (oconfig_item_it *) */
1541
1542 static int perl_config (oconfig_item_t *ci)
1543 {
1544         int i = 0;
1545
1546         dTHX;
1547
1548         /* dTHX does not get any valid values in case Perl
1549          * has not been initialized */
1550         if (NULL == perl_threads)
1551                 aTHX = NULL;
1552
1553         for (i = 0; i < ci->children_num; ++i) {
1554                 oconfig_item_t *c = ci->children + i;
1555
1556                 if (0 == strcasecmp (c->key, "LoadPlugin"))
1557                         perl_config_loadplugin (aTHX_ c);
1558                 else if (0 == strcasecmp (c->key, "BaseName"))
1559                         perl_config_basename (aTHX_ c);
1560                 else if (0 == strcasecmp (c->key, "EnableDebugger"))
1561                         perl_config_enabledebugger (aTHX_ c);
1562                 else if (0 == strcasecmp (c->key, "IncludeDir"))
1563                         perl_config_includedir (aTHX_ c);
1564                 else
1565                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
1566         }
1567         return 0;
1568 } /* static int perl_config (oconfig_item_t *) */
1569
1570 void module_register (void)
1571 {
1572         perl_argc = 4;
1573         perl_argv = (char **)smalloc ((perl_argc + 1) * sizeof (char *));
1574
1575         /* default options for the Perl interpreter */
1576         perl_argv[0] = "";
1577         perl_argv[1] = "-MCollectd";
1578         perl_argv[2] = "-e";
1579         perl_argv[3] = "1";
1580         perl_argv[4] = NULL;
1581
1582         plugin_register_complex_config ("perl", perl_config);
1583         return;
1584 } /* void module_register (void) */
1585
1586 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
1587