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