perl plugin: Declare the “environ” variable.
[collectd.git] / src / perl.c
1 /**
2  * collectd - src/perl.c
3  * Copyright (C) 2007-2009  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 #define DONT_POISON_SPRINTF_YET 1
31 #include "collectd.h"
32 #undef DONT_POISON_SPRINTF_YET
33
34 #include "configfile.h"
35
36 #include <EXTERN.h>
37 #include <perl.h>
38
39 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
40 # pragma GCC poison sprintf
41 #endif
42
43 #include <XSUB.h>
44
45 /* Some versions of Perl define their own version of DEBUG... :-/ */
46 #ifdef DEBUG
47 # undef DEBUG
48 #endif /* DEBUG */
49
50 /* ... while we want the definition found in plugin.h. */
51 #include "plugin.h"
52 #include "common.h"
53
54 #include "filter_chain.h"
55
56 #include <pthread.h>
57
58 #if !defined(USE_ITHREADS)
59 # error "Perl does not support ithreads!"
60 #endif /* !defined(USE_ITHREADS) */
61
62 /* clear the Perl sub's stack frame
63  * (this should only be used inside an XSUB) */
64 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
65
66 #define PLUGIN_INIT     0
67 #define PLUGIN_READ     1
68 #define PLUGIN_WRITE    2
69 #define PLUGIN_SHUTDOWN 3
70 #define PLUGIN_LOG      4
71 #define PLUGIN_NOTIF    5
72 #define PLUGIN_FLUSH    6
73
74 #define PLUGIN_TYPES    7
75
76 #define PLUGIN_CONFIG   254
77 #define PLUGIN_DATASET  255
78
79 #define FC_MATCH  0
80 #define FC_TARGET 1
81
82 #define FC_TYPES  2
83
84 #define FC_CB_CREATE  0
85 #define FC_CB_DESTROY 1
86 #define FC_CB_EXEC    2
87
88 #define FC_CB_TYPES   3
89
90 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
91 #define log_info(...) INFO ("perl: " __VA_ARGS__)
92 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
93 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
94
95 /* this is defined in DynaLoader.a */
96 void boot_DynaLoader (PerlInterpreter *, CV *);
97
98 static XS (Collectd_plugin_register_ds);
99 static XS (Collectd_plugin_unregister_ds);
100 static XS (Collectd_plugin_dispatch_values);
101 static XS (Collectd__plugin_write);
102 static XS (Collectd__plugin_flush);
103 static XS (Collectd_plugin_dispatch_notification);
104 static XS (Collectd_plugin_log);
105 static XS (Collectd__fc_register);
106 static XS (Collectd_call_by_name);
107
108 /*
109  * private data types
110  */
111
112 typedef struct c_ithread_s {
113         /* the thread's Perl interpreter */
114         PerlInterpreter *interp;
115
116         /* double linked list of threads */
117         struct c_ithread_s *prev;
118         struct c_ithread_s *next;
119 } c_ithread_t;
120
121 typedef struct {
122         c_ithread_t *head;
123         c_ithread_t *tail;
124
125 #if COLLECT_DEBUG
126         /* some usage stats */
127         int number_of_threads;
128 #endif /* COLLECT_DEBUG */
129
130         pthread_mutex_t mutex;
131 } c_ithread_list_t;
132
133 /* name / user_data for Perl matches / targets */
134 typedef struct {
135         char *name;
136         SV   *user_data;
137 } pfc_user_data_t;
138
139 #define PFC_USER_DATA_FREE(data) \
140         do { \
141                 sfree ((data)->name); \
142                 if (NULL != (data)->user_data) \
143                         sv_free ((data)->user_data); \
144                 sfree (data); \
145         } while (0)
146
147 /*
148  * Public variable
149  */
150 extern char **environ;
151
152 /*
153  * private variables
154  */
155
156 /* if perl_threads != NULL perl_threads->head must
157  * point to the "base" thread */
158 static c_ithread_list_t *perl_threads = NULL;
159
160 /* the key used to store each pthread's ithread */
161 static pthread_key_t perl_thr_key;
162
163 static int    perl_argc = 0;
164 static char **perl_argv = NULL;
165
166 static char base_name[DATA_MAX_NAME_LEN] = "";
167
168 static struct {
169         char name[64];
170         XS ((*f));
171 } api[] =
172 {
173         { "Collectd::plugin_register_data_set",   Collectd_plugin_register_ds },
174         { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
175         { "Collectd::plugin_dispatch_values",     Collectd_plugin_dispatch_values },
176         { "Collectd::_plugin_write",              Collectd__plugin_write },
177         { "Collectd::_plugin_flush",              Collectd__plugin_flush },
178         { "Collectd::plugin_dispatch_notification",
179                 Collectd_plugin_dispatch_notification },
180         { "Collectd::plugin_log",                 Collectd_plugin_log },
181         { "Collectd::_fc_register",               Collectd__fc_register },
182         { "Collectd::call_by_name",               Collectd_call_by_name },
183         { "", NULL }
184 };
185
186 struct {
187         char name[64];
188         int  value;
189 } constants[] =
190 {
191         { "Collectd::TYPE_INIT",          PLUGIN_INIT },
192         { "Collectd::TYPE_READ",          PLUGIN_READ },
193         { "Collectd::TYPE_WRITE",         PLUGIN_WRITE },
194         { "Collectd::TYPE_SHUTDOWN",      PLUGIN_SHUTDOWN },
195         { "Collectd::TYPE_LOG",           PLUGIN_LOG },
196         { "Collectd::TYPE_NOTIF",         PLUGIN_NOTIF },
197         { "Collectd::TYPE_FLUSH",         PLUGIN_FLUSH },
198         { "Collectd::TYPE_CONFIG",        PLUGIN_CONFIG },
199         { "Collectd::TYPE_DATASET",       PLUGIN_DATASET },
200         { "Collectd::DS_TYPE_COUNTER",    DS_TYPE_COUNTER },
201         { "Collectd::DS_TYPE_GAUGE",      DS_TYPE_GAUGE },
202         { "Collectd::LOG_ERR",            LOG_ERR },
203         { "Collectd::LOG_WARNING",        LOG_WARNING },
204         { "Collectd::LOG_NOTICE",         LOG_NOTICE },
205         { "Collectd::LOG_INFO",           LOG_INFO },
206         { "Collectd::LOG_DEBUG",          LOG_DEBUG },
207         { "Collectd::FC_MATCH",           FC_MATCH },
208         { "Collectd::FC_TARGET",          FC_TARGET },
209         { "Collectd::FC_CB_CREATE",       FC_CB_CREATE },
210         { "Collectd::FC_CB_DESTROY",      FC_CB_DESTROY },
211         { "Collectd::FC_CB_EXEC",         FC_CB_EXEC },
212         { "Collectd::FC_MATCH_NO_MATCH",  FC_MATCH_NO_MATCH },
213         { "Collectd::FC_MATCH_MATCHES",   FC_MATCH_MATCHES },
214         { "Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE },
215         { "Collectd::FC_TARGET_STOP",     FC_TARGET_STOP },
216         { "Collectd::FC_TARGET_RETURN",   FC_TARGET_RETURN },
217         { "Collectd::NOTIF_FAILURE",      NOTIF_FAILURE },
218         { "Collectd::NOTIF_WARNING",      NOTIF_WARNING },
219         { "Collectd::NOTIF_OKAY",         NOTIF_OKAY },
220         { "", 0 }
221 };
222
223 struct {
224         char  name[64];
225         char *var;
226 } g_strings[] =
227 {
228         { "Collectd::hostname_g", hostname_g },
229         { "", NULL }
230 };
231
232 struct {
233         char  name[64];
234         int  *var;
235 } g_integers[] =
236 {
237         { "Collectd::interval_g", &interval_g },
238         { "", NULL }
239 };
240
241 /*
242  * Helper functions for data type conversion.
243  */
244
245 /*
246  * data source:
247  * [
248  *   {
249  *     name => $ds_name,
250  *     type => $ds_type,
251  *     min  => $ds_min,
252  *     max  => $ds_max
253  *   },
254  *   ...
255  * ]
256  */
257 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
258 {
259         SV **tmp = NULL;
260
261         if ((NULL == hash) || (NULL == ds))
262                 return -1;
263
264         if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
265                 sstrncpy (ds->name, SvPV_nolen (*tmp), sizeof (ds->name));
266         }
267         else {
268                 log_err ("hv2data_source: No DS name given.");
269                 return -1;
270         }
271
272         if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
273                 ds->type = SvIV (*tmp);
274
275                 if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type)) {
276                         log_err ("hv2data_source: Invalid DS type.");
277                         return -1;
278                 }
279         }
280         else {
281                 ds->type = DS_TYPE_COUNTER;
282         }
283
284         if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
285                 ds->min = SvNV (*tmp);
286         else
287                 ds->min = NAN;
288
289         if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
290                 ds->max = SvNV (*tmp);
291         else
292                 ds->max = NAN;
293         return 0;
294 } /* static int hv2data_source (HV *, data_source_t *) */
295
296 static int av2value (pTHX_ char *name, AV *array, value_t *value, int len)
297 {
298         const data_set_t *ds;
299
300         int i = 0;
301
302         if ((NULL == name) || (NULL == array) || (NULL == value))
303                 return -1;
304
305         if (av_len (array) < len - 1)
306                 len = av_len (array) + 1;
307
308         if (0 >= len)
309                 return -1;
310
311         ds = plugin_get_ds (name);
312         if (NULL == ds) {
313                 log_err ("av2value: Unknown dataset \"%s\"", name);
314                 return -1;
315         }
316
317         if (ds->ds_num < len) {
318                 log_warn ("av2value: Value length exceeds data set length.");
319                 len = ds->ds_num;
320         }
321
322         for (i = 0; i < len; ++i) {
323                 SV **tmp = av_fetch (array, i, 0);
324
325                 if (NULL != tmp) {
326                         if (DS_TYPE_COUNTER == ds->ds[i].type)
327                                 value[i].counter = SvIV (*tmp);
328                         else
329                                 value[i].gauge = SvNV (*tmp);
330                 }
331                 else {
332                         return -1;
333                 }
334         }
335         return len;
336 } /* static int av2value (char *, AV *, value_t *, int) */
337
338 /*
339  * value list:
340  * {
341  *   values => [ @values ],
342  *   time   => $time,
343  *   host   => $host,
344  *   plugin => $plugin,
345  *   plugin_instance => $pinstance,
346  *   type_instance   => $tinstance,
347  * }
348  */
349 static int hv2value_list (pTHX_ HV *hash, value_list_t *vl)
350 {
351         SV **tmp;
352
353         if ((NULL == hash) || (NULL == vl))
354                 return -1;
355
356         if (NULL == (tmp = hv_fetch (hash, "type", 4, 0))) {
357                 log_err ("hv2value_list: No type given.");
358                 return -1;
359         }
360
361         sstrncpy (vl->type, SvPV_nolen (*tmp), sizeof (vl->type));
362
363         if ((NULL == (tmp = hv_fetch (hash, "values", 6, 0)))
364                         || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
365                 log_err ("hv2value_list: No valid values given.");
366                 return -1;
367         }
368
369         {
370                 AV  *array = (AV *)SvRV (*tmp);
371                 int len    = av_len (array) + 1;
372
373                 if (len <= 0)
374                         return -1;
375
376                 vl->values     = (value_t *)smalloc (len * sizeof (value_t));
377                 vl->values_len = av2value (aTHX_ vl->type, (AV *)SvRV (*tmp),
378                                 vl->values, len);
379
380                 if (-1 == vl->values_len) {
381                         sfree (vl->values);
382                         return -1;
383                 }
384         }
385
386         if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
387                 vl->time = (time_t)SvIV (*tmp);
388
389         if (NULL != (tmp = hv_fetch (hash, "interval", 8, 0)))
390                 vl->interval = SvIV (*tmp);
391
392         if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
393                 sstrncpy (vl->host, SvPV_nolen (*tmp), sizeof (vl->host));
394         else
395                 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
396
397         if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
398                 sstrncpy (vl->plugin, SvPV_nolen (*tmp), sizeof (vl->plugin));
399
400         if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
401                 sstrncpy (vl->plugin_instance, SvPV_nolen (*tmp),
402                                 sizeof (vl->plugin_instance));
403
404         if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
405                 sstrncpy (vl->type_instance, SvPV_nolen (*tmp),
406                                 sizeof (vl->type_instance));
407         return 0;
408 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
409
410 static int av2data_set (pTHX_ AV *array, char *name, data_set_t *ds)
411 {
412         int len, i;
413
414         if ((NULL == array) || (NULL == name) || (NULL == ds))
415                 return -1;
416
417         len = av_len (array);
418
419         if (-1 == len) {
420                 log_err ("av2data_set: Invalid data set.");
421                 return -1;
422         }
423
424         ds->ds = (data_source_t *)smalloc ((len + 1) * sizeof (data_source_t));
425         ds->ds_num = len + 1;
426
427         for (i = 0; i <= len; ++i) {
428                 SV **elem = av_fetch (array, i, 0);
429
430                 if (NULL == elem) {
431                         log_err ("av2data_set: Failed to fetch data source %i.", i);
432                         return -1;
433                 }
434
435                 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
436                         log_err ("av2data_set: Invalid data source.");
437                         return -1;
438                 }
439
440                 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds->ds[i]))
441                         return -1;
442
443                 log_debug ("av2data_set: "
444                                 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
445                                 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
446         }
447
448         sstrncpy (ds->type, name, sizeof (ds->type));
449         return 0;
450 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
451
452 /*
453  * notification:
454  * {
455  *   severity => $severity,
456  *   time     => $time,
457  *   message  => $msg,
458  *   host     => $host,
459  *   plugin   => $plugin,
460  *   type     => $type,
461  *   plugin_instance => $instance,
462  *   type_instance   => $type_instance,
463  *   meta     => [ { name => <name>, value => <value> }, ... ]
464  * }
465  */
466 static int av2notification_meta (pTHX_ AV *array, notification_meta_t **meta)
467 {
468         notification_meta_t **m = meta;
469
470         int len = av_len (array);
471         int i;
472
473         for (i = 0; i <= len; ++i) {
474                 SV **tmp = av_fetch (array, i, 0);
475                 HV  *hash;
476
477                 if (NULL == tmp)
478                         return -1;
479
480                 if (! (SvROK (*tmp) && (SVt_PVHV == SvTYPE (SvRV (*tmp))))) {
481                         log_warn ("av2notification_meta: Skipping invalid "
482                                         "meta information.");
483                         continue;
484                 }
485
486                 hash = (HV *)SvRV (*tmp);
487
488                 *m = (notification_meta_t *)smalloc (sizeof (**m));
489
490                 if (NULL == (tmp = hv_fetch (hash, "name", 4, 0))) {
491                         log_warn ("av2notification_meta: Skipping invalid "
492                                         "meta information.");
493                         free (*m);
494                         continue;
495                 }
496                 sstrncpy ((*m)->name, SvPV_nolen (*tmp), sizeof ((*m)->name));
497
498                 if (NULL == (tmp = hv_fetch (hash, "value", 5, 0))) {
499                         log_warn ("av2notification_meta: Skipping invalid "
500                                         "meta information.");
501                         free ((*m)->name);
502                         free (*m);
503                         continue;
504                 }
505
506                 if (SvNOK (*tmp)) {
507                         (*m)->nm_value.nm_double = SvNVX (*tmp);
508                         (*m)->type = NM_TYPE_DOUBLE;
509                 }
510                 else if (SvUOK (*tmp)) {
511                         (*m)->nm_value.nm_unsigned_int = SvUVX (*tmp);
512                         (*m)->type = NM_TYPE_UNSIGNED_INT;
513                 }
514                 else if (SvIOK (*tmp)) {
515                         (*m)->nm_value.nm_signed_int = SvIVX (*tmp);
516                         (*m)->type = NM_TYPE_SIGNED_INT;
517                 }
518                 else {
519                         (*m)->nm_value.nm_string = sstrdup (SvPV_nolen (*tmp));
520                         (*m)->type = NM_TYPE_STRING;
521                 }
522
523                 (*m)->next = NULL;
524                 m = &((*m)->next);
525         }
526         return 0;
527 } /* static int av2notification_meta (AV *, notification_meta_t *) */
528
529 static int hv2notification (pTHX_ HV *hash, notification_t *n)
530 {
531         SV **tmp = NULL;
532
533         if ((NULL == hash) || (NULL == n))
534                 return -1;
535
536         if (NULL != (tmp = hv_fetch (hash, "severity", 8, 0)))
537                 n->severity = SvIV (*tmp);
538         else
539                 n->severity = NOTIF_FAILURE;
540
541         if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
542                 n->time = (time_t)SvIV (*tmp);
543         else
544                 n->time = time (NULL);
545
546         if (NULL != (tmp = hv_fetch (hash, "message", 7, 0)))
547                 sstrncpy (n->message, SvPV_nolen (*tmp), sizeof (n->message));
548
549         if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
550                 sstrncpy (n->host, SvPV_nolen (*tmp), sizeof (n->host));
551         else
552                 sstrncpy (n->host, hostname_g, sizeof (n->host));
553
554         if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
555                 sstrncpy (n->plugin, SvPV_nolen (*tmp), sizeof (n->plugin));
556
557         if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
558                 sstrncpy (n->plugin_instance, SvPV_nolen (*tmp),
559                                 sizeof (n->plugin_instance));
560
561         if (NULL != (tmp = hv_fetch (hash, "type", 4, 0)))
562                 sstrncpy (n->type, SvPV_nolen (*tmp), sizeof (n->type));
563
564         if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
565                 sstrncpy (n->type_instance, SvPV_nolen (*tmp),
566                                 sizeof (n->type_instance));
567
568         n->meta = NULL;
569         while (NULL != (tmp = hv_fetch (hash, "meta", 4, 0))) {
570                 if (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp))))) {
571                         log_warn ("hv2notification: Ignoring invalid meta information.");
572                         break;
573                 }
574
575                 if (0 != av2notification_meta (aTHX_ (AV *)SvRV (*tmp), &n->meta)) {
576                         plugin_notification_meta_free (n->meta);
577                         n->meta = NULL;
578                         return -1;
579                 }
580                 break;
581         }
582         return 0;
583 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
584
585 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
586 {
587         int i = 0;
588
589         if ((NULL == ds) || (NULL == array))
590                 return -1;
591
592         av_extend (array, ds->ds_num);
593
594         for (i = 0; i < ds->ds_num; ++i) {
595                 HV *source = newHV ();
596
597                 if (NULL == hv_store (source, "name", 4,
598                                 newSVpv (ds->ds[i].name, 0), 0))
599                         return -1;
600
601                 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
602                         return -1;
603
604                 if (! isnan (ds->ds[i].min))
605                         if (NULL == hv_store (source, "min", 3,
606                                         newSVnv (ds->ds[i].min), 0))
607                                 return -1;
608
609                 if (! isnan (ds->ds[i].max))
610                         if (NULL == hv_store (source, "max", 3,
611                                         newSVnv (ds->ds[i].max), 0))
612                                 return -1;
613
614                 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
615                         return -1;
616         }
617         return 0;
618 } /* static int data_set2av (data_set_t *, AV *) */
619
620 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
621 {
622         AV *values = NULL;
623
624         int i   = 0;
625         int len = 0;
626
627         if ((NULL == vl) || (NULL == ds) || (NULL == hash))
628                 return -1;
629
630         len = vl->values_len;
631
632         if (ds->ds_num < len) {
633                 log_warn ("value2av: Value length exceeds data set length.");
634                 len = ds->ds_num;
635         }
636
637         values = newAV ();
638         av_extend (values, len - 1);
639
640         for (i = 0; i < len; ++i) {
641                 SV *val = NULL;
642
643                 if (DS_TYPE_COUNTER == ds->ds[i].type)
644                         val = newSViv (vl->values[i].counter);
645                 else
646                         val = newSVnv (vl->values[i].gauge);
647
648                 if (NULL == av_store (values, i, val)) {
649                         av_undef (values);
650                         return -1;
651                 }
652         }
653
654         if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
655                 return -1;
656
657         if (0 != vl->time)
658                 if (NULL == hv_store (hash, "time", 4, newSViv (vl->time), 0))
659                         return -1;
660
661         if (NULL == hv_store (hash, "interval", 8, newSViv (vl->interval), 0))
662                 return -1;
663
664         if ('\0' != vl->host[0])
665                 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
666                         return -1;
667
668         if ('\0' != vl->plugin[0])
669                 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
670                         return -1;
671
672         if ('\0' != vl->plugin_instance[0])
673                 if (NULL == hv_store (hash, "plugin_instance", 15,
674                                 newSVpv (vl->plugin_instance, 0), 0))
675                         return -1;
676
677         if ('\0' != vl->type[0])
678                 if (NULL == hv_store (hash, "type", 4, newSVpv (vl->type, 0), 0))
679                         return -1;
680
681         if ('\0' != vl->type_instance[0])
682                 if (NULL == hv_store (hash, "type_instance", 13,
683                                 newSVpv (vl->type_instance, 0), 0))
684                         return -1;
685         return 0;
686 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
687
688 static int notification_meta2av (pTHX_ notification_meta_t *meta, AV *array)
689 {
690         int meta_num = 0;
691         int i;
692
693         while (meta) {
694                 ++meta_num;
695                 meta = meta->next;
696         }
697
698         av_extend (array, meta_num);
699
700         for (i = 0; NULL != meta; meta = meta->next, ++i) {
701                 HV *m = newHV ();
702                 SV *value;
703
704                 if (NULL == hv_store (m, "name", 4, newSVpv (meta->name, 0), 0))
705                         return -1;
706
707                 if (NM_TYPE_STRING == meta->type)
708                         value = newSVpv (meta->nm_value.nm_string, 0);
709                 else if (NM_TYPE_SIGNED_INT == meta->type)
710                         value = newSViv (meta->nm_value.nm_signed_int);
711                 else if (NM_TYPE_UNSIGNED_INT == meta->type)
712                         value = newSVuv (meta->nm_value.nm_unsigned_int);
713                 else if (NM_TYPE_DOUBLE == meta->type)
714                         value = newSVnv (meta->nm_value.nm_double);
715                 else if (NM_TYPE_BOOLEAN == meta->type)
716                         value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
717                 else
718                         return -1;
719
720                 if (NULL == hv_store (m, "value", 5, value, 0)) {
721                         sv_free (value);
722                         return -1;
723                 }
724
725                 if (NULL == av_store (array, i, newRV_noinc ((SV *)m))) {
726                         hv_clear (m);
727                         hv_undef (m);
728                         return -1;
729                 }
730         }
731         return 0;
732 } /* static int notification_meta2av (notification_meta_t *, AV *) */
733
734 static int notification2hv (pTHX_ notification_t *n, HV *hash)
735 {
736         if (NULL == hv_store (hash, "severity", 8, newSViv (n->severity), 0))
737                 return -1;
738
739         if (0 != n->time)
740                 if (NULL == hv_store (hash, "time", 4, newSViv (n->time), 0))
741                         return -1;
742
743         if ('\0' != *n->message)
744                 if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
745                         return -1;
746
747         if ('\0' != *n->host)
748                 if (NULL == hv_store (hash, "host", 4, newSVpv (n->host, 0), 0))
749                         return -1;
750
751         if ('\0' != *n->plugin)
752                 if (NULL == hv_store (hash, "plugin", 6, newSVpv (n->plugin, 0), 0))
753                         return -1;
754
755         if ('\0' != *n->plugin_instance)
756                 if (NULL == hv_store (hash, "plugin_instance", 15,
757                                 newSVpv (n->plugin_instance, 0), 0))
758                         return -1;
759
760         if ('\0' != *n->type)
761                 if (NULL == hv_store (hash, "type", 4, newSVpv (n->type, 0), 0))
762                         return -1;
763
764         if ('\0' != *n->type_instance)
765                 if (NULL == hv_store (hash, "type_instance", 13,
766                                 newSVpv (n->type_instance, 0), 0))
767                         return -1;
768
769         if (NULL != n->meta) {
770                 AV *meta = newAV ();
771                 if ((0 != notification_meta2av (aTHX_ n->meta, meta))
772                                 || (NULL == hv_store (hash, "meta", 4,
773                                                 newRV_noinc ((SV *)meta), 0))) {
774                         av_clear (meta);
775                         av_undef (meta);
776                         return -1;
777                 }
778         }
779         return 0;
780 } /* static int notification2hv (notification_t *, HV *) */
781
782 static int oconfig_item2hv (pTHX_ oconfig_item_t *ci, HV *hash)
783 {
784         int i;
785
786         AV *values;
787         AV *children;
788
789         if (NULL == hv_store (hash, "key", 3, newSVpv (ci->key, 0), 0))
790                 return -1;
791
792         values = newAV ();
793         if (0 < ci->values_num)
794                 av_extend (values, ci->values_num);
795
796         if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0)) {
797                 av_clear (values);
798                 av_undef (values);
799                 return -1;
800         }
801
802         for (i = 0; i < ci->values_num; ++i) {
803                 SV *value;
804
805                 switch (ci->values[i].type) {
806                         case OCONFIG_TYPE_STRING:
807                                 value = newSVpv (ci->values[i].value.string, 0);
808                                 break;
809                         case OCONFIG_TYPE_NUMBER:
810                                 value = newSVnv ((NV)ci->values[i].value.number);
811                                 break;
812                         case OCONFIG_TYPE_BOOLEAN:
813                                 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
814                                 break;
815                         default:
816                                 log_err ("oconfig_item2hv: Invalid value type %i.",
817                                                 ci->values[i].type);
818                                 value = &PL_sv_undef;
819                 }
820
821                 if (NULL == av_store (values, i, value)) {
822                         sv_free (value);
823                         return -1;
824                 }
825         }
826
827         /* ignoring 'parent' member which is uninteresting in this case */
828
829         children = newAV ();
830         if (0 < ci->children_num)
831                 av_extend (children, ci->children_num);
832
833         if (NULL == hv_store (hash, "children", 8, newRV_noinc ((SV *)children), 0)) {
834                 av_clear (children);
835                 av_undef (children);
836                 return -1;
837         }
838
839         for (i = 0; i < ci->children_num; ++i) {
840                 HV *child = newHV ();
841
842                 if (0 != oconfig_item2hv (aTHX_ ci->children + i, child)) {
843                         hv_clear (child);
844                         hv_undef (child);
845                         return -1;
846                 }
847
848                 if (NULL == av_store (children, i, newRV_noinc ((SV *)child))) {
849                         hv_clear (child);
850                         hv_undef (child);
851                         return -1;
852                 }
853         }
854         return 0;
855 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
856
857 /*
858  * Internal functions.
859  */
860
861 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
862         int status = 0;
863         if (base_name[0] == '\0')
864                 status = ssnprintf (buf, buf_len, "%s", module);
865         else
866                 status = ssnprintf (buf, buf_len, "%s::%s", base_name, module);
867         if ((status < 0) || ((unsigned int)status >= buf_len))
868                 return (NULL);
869         return (buf);
870 } /* char *get_module_name */
871
872 /*
873  * Add a plugin's data set definition.
874  */
875 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
876 {
877         int ret = 0;
878
879         data_set_t ds;
880
881         if ((NULL == name) || (NULL == dataset))
882                 return -1;
883
884         if (0 != av2data_set (aTHX_ dataset, name, &ds))
885                 return -1;
886
887         ret = plugin_register_data_set (&ds);
888
889         free (ds.ds);
890         return ret;
891 } /* static int pplugin_register_data_set (char *, SV *) */
892
893 /*
894  * Remove a plugin's data set definition.
895  */
896 static int pplugin_unregister_data_set (char *name)
897 {
898         if (NULL == name)
899                 return 0;
900         return plugin_unregister_data_set (name);
901 } /* static int pplugin_unregister_data_set (char *) */
902
903 /*
904  * Submit the values to the write functions.
905  */
906 static int pplugin_dispatch_values (pTHX_ HV *values)
907 {
908         value_list_t vl = VALUE_LIST_INIT;
909
910         int ret = 0;
911
912         if (NULL == values)
913                 return -1;
914
915         if (0 != hv2value_list (aTHX_ values, &vl))
916                 return -1;
917
918         ret = plugin_dispatch_values (&vl);
919
920         sfree (vl.values);
921         return ret;
922 } /* static int pplugin_dispatch_values (char *, HV *) */
923
924 /*
925  * Submit the values to a single write function.
926  */
927 static int pplugin_write (pTHX_ const char *plugin, AV *data_set, HV *values)
928 {
929         data_set_t   ds;
930         value_list_t vl = VALUE_LIST_INIT;
931
932         int ret;
933
934         if (NULL == values)
935                 return -1;
936
937         if (0 != hv2value_list (aTHX_ values, &vl))
938                 return -1;
939
940         if ((NULL != data_set)
941                         && (0 != av2data_set (aTHX_ data_set, vl.type, &ds)))
942                 return -1;
943
944         ret = plugin_write (plugin, NULL == data_set ? NULL : &ds, &vl);
945         if (0 != ret)
946                 log_warn ("Dispatching value to plugin \"%s\" failed with status %i.",
947                                 NULL == plugin ? "<any>" : plugin, ret);
948
949         if (NULL != data_set)
950                 sfree (ds.ds);
951         sfree (vl.values);
952         return ret;
953 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
954
955 /*
956  * Dispatch a notification.
957  */
958 static int pplugin_dispatch_notification (pTHX_ HV *notif)
959 {
960         notification_t n;
961
962         int ret;
963
964         if (NULL == notif)
965                 return -1;
966
967         memset (&n, 0, sizeof (n));
968
969         if (0 != hv2notification (aTHX_ notif, &n))
970                 return -1;
971
972         ret = plugin_dispatch_notification (&n);
973         plugin_notification_meta_free (n.meta);
974         return ret;
975 } /* static int pplugin_dispatch_notification (HV *) */
976
977 /*
978  * Call all working functions of the given type.
979  */
980 static int pplugin_call_all (pTHX_ int type, ...)
981 {
982         int retvals = 0;
983
984         va_list ap;
985         int ret = 0;
986
987         dSP;
988
989         if ((type < 0) || (type >= PLUGIN_TYPES))
990                 return -1;
991
992         va_start (ap, type);
993
994         ENTER;
995         SAVETMPS;
996
997         PUSHMARK (SP);
998
999         XPUSHs (sv_2mortal (newSViv ((IV)type)));
1000
1001         if (PLUGIN_WRITE == type) {
1002                 /*
1003                  * $_[0] = $plugin_type;
1004                  *
1005                  * $_[1] =
1006                  * [
1007                  *   {
1008                  *     name => $ds_name,
1009                  *     type => $ds_type,
1010                  *     min  => $ds_min,
1011                  *     max  => $ds_max
1012                  *   },
1013                  *   ...
1014                  * ];
1015                  *
1016                  * $_[2] =
1017                  * {
1018                  *   values => [ $v1, ... ],
1019                  *   time   => $time,
1020                  *   host   => $hostname,
1021                  *   plugin => $plugin,
1022                  *   type   => $type,
1023                  *   plugin_instance => $instance,
1024                  *   type_instance   => $type_instance
1025                  * };
1026                  */
1027                 data_set_t   *ds;
1028                 value_list_t *vl;
1029
1030                 AV *pds = newAV ();
1031                 HV *pvl = newHV ();
1032
1033                 ds = va_arg (ap, data_set_t *);
1034                 vl = va_arg (ap, value_list_t *);
1035
1036                 if (-1 == data_set2av (aTHX_ ds, pds)) {
1037                         av_clear (pds);
1038                         av_undef (pds);
1039                         pds = (AV *)&PL_sv_undef;
1040                         ret = -1;
1041                 }
1042
1043                 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
1044                         hv_clear (pvl);
1045                         hv_undef (pvl);
1046                         pvl = (HV *)&PL_sv_undef;
1047                         ret = -1;
1048                 }
1049
1050                 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
1051                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1052                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1053         }
1054         else if (PLUGIN_LOG == type) {
1055                 /*
1056                  * $_[0] = $level;
1057                  *
1058                  * $_[1] = $message;
1059                  */
1060                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1061                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1062         }
1063         else if (PLUGIN_NOTIF == type) {
1064                 /*
1065                  * $_[0] =
1066                  * {
1067                  *   severity => $severity,
1068                  *   time     => $time,
1069                  *   message  => $msg,
1070                  *   host     => $host,
1071                  *   plugin   => $plugin,
1072                  *   type     => $type,
1073                  *   plugin_instance => $instance,
1074                  *   type_instance   => $type_instance
1075                  * };
1076                  */
1077                 notification_t *n;
1078                 HV *notif = newHV ();
1079
1080                 n = va_arg (ap, notification_t *);
1081
1082                 if (-1 == notification2hv (aTHX_ n, notif)) {
1083                         hv_clear (notif);
1084                         hv_undef (notif);
1085                         notif = (HV *)&PL_sv_undef;
1086                         ret = -1;
1087                 }
1088
1089                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
1090         }
1091         else if (PLUGIN_FLUSH == type) {
1092                 /*
1093                  * $_[0] = $timeout;
1094                  * $_[1] = $identifier;
1095                  */
1096                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1097                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1098         }
1099
1100         PUTBACK;
1101
1102         retvals = call_pv ("Collectd::plugin_call_all", G_SCALAR);
1103
1104         SPAGAIN;
1105         if (0 < retvals) {
1106                 SV *tmp = POPs;
1107                 if (! SvTRUE (tmp))
1108                         ret = -1;
1109         }
1110
1111         PUTBACK;
1112         FREETMPS;
1113         LEAVE;
1114
1115         va_end (ap);
1116         return ret;
1117 } /* static int pplugin_call_all (int, ...) */
1118
1119 /*
1120  * collectd's perl interpreter based thread implementation.
1121  *
1122  * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1123  */
1124
1125 /* must be called with perl_threads->mutex locked */
1126 static void c_ithread_destroy (c_ithread_t *ithread)
1127 {
1128         dTHXa (ithread->interp);
1129
1130         assert (NULL != perl_threads);
1131
1132         PERL_SET_CONTEXT (aTHX);
1133         log_debug ("Shutting down Perl interpreter %p...", aTHX);
1134
1135 #if COLLECT_DEBUG
1136         sv_report_used ();
1137
1138         --perl_threads->number_of_threads;
1139 #endif /* COLLECT_DEBUG */
1140
1141         perl_destruct (aTHX);
1142         perl_free (aTHX);
1143
1144         if (NULL == ithread->prev)
1145                 perl_threads->head = ithread->next;
1146         else
1147                 ithread->prev->next = ithread->next;
1148
1149         if (NULL == ithread->next)
1150                 perl_threads->tail = ithread->prev;
1151         else
1152                 ithread->next->prev = ithread->prev;
1153
1154         sfree (ithread);
1155         return;
1156 } /* static void c_ithread_destroy (c_ithread_t *) */
1157
1158 static void c_ithread_destructor (void *arg)
1159 {
1160         c_ithread_t *ithread = (c_ithread_t *)arg;
1161         c_ithread_t *t = NULL;
1162
1163         if (NULL == perl_threads)
1164                 return;
1165
1166         pthread_mutex_lock (&perl_threads->mutex);
1167
1168         for (t = perl_threads->head; NULL != t; t = t->next)
1169                 if (t == ithread)
1170                         break;
1171
1172         /* the ithread no longer exists */
1173         if (NULL == t)
1174                 return;
1175
1176         c_ithread_destroy (ithread);
1177
1178         pthread_mutex_unlock (&perl_threads->mutex);
1179         return;
1180 } /* static void c_ithread_destructor (void *) */
1181
1182 /* must be called with perl_threads->mutex locked */
1183 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1184 {
1185         c_ithread_t *t = NULL;
1186         dTHXa (NULL);
1187
1188         assert (NULL != perl_threads);
1189
1190         t = (c_ithread_t *)smalloc (sizeof (c_ithread_t));
1191         memset (t, 0, sizeof (c_ithread_t));
1192
1193         t->interp = (NULL == base)
1194                 ? NULL
1195                 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1196
1197         aTHX = t->interp;
1198
1199         if ((NULL != base) && (NULL != PL_endav)) {
1200                 av_clear (PL_endav);
1201                 av_undef (PL_endav);
1202                 PL_endav = Nullav;
1203         }
1204
1205 #if COLLECT_DEBUG
1206         ++perl_threads->number_of_threads;
1207 #endif /* COLLECT_DEBUG */
1208
1209         t->next = NULL;
1210
1211         if (NULL == perl_threads->tail) {
1212                 perl_threads->head = t;
1213                 t->prev = NULL;
1214         }
1215         else {
1216                 perl_threads->tail->next = t;
1217                 t->prev = perl_threads->tail;
1218         }
1219
1220         perl_threads->tail = t;
1221
1222         pthread_setspecific (perl_thr_key, (const void *)t);
1223         return t;
1224 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1225
1226 /*
1227  * Filter chains implementation.
1228  */
1229
1230 static int fc_call (pTHX_ int type, int cb_type, pfc_user_data_t *data, ...)
1231 {
1232         int retvals = 0;
1233
1234         va_list ap;
1235         int ret = 0;
1236
1237         notification_meta_t **meta  = NULL;
1238         AV                   *pmeta = NULL;
1239
1240         dSP;
1241
1242         if ((type < 0) || (type >= FC_TYPES))
1243                 return -1;
1244
1245         if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1246                 return -1;
1247
1248         va_start (ap, data);
1249
1250         ENTER;
1251         SAVETMPS;
1252
1253         PUSHMARK (SP);
1254
1255         XPUSHs (sv_2mortal (newSViv ((IV)type)));
1256         XPUSHs (sv_2mortal (newSVpv (data->name, 0)));
1257         XPUSHs (sv_2mortal (newSViv ((IV)cb_type)));
1258
1259         if (FC_CB_CREATE == cb_type) {
1260                 /*
1261                  * $_[0] = $ci;
1262                  * $_[1] = $user_data;
1263                  */
1264                 oconfig_item_t *ci;
1265                 HV *config = newHV ();
1266
1267                 ci = va_arg (ap, oconfig_item_t *);
1268
1269                 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
1270                         hv_clear (config);
1271                         hv_undef (config);
1272                         config = (HV *)&PL_sv_undef;
1273                         ret = -1;
1274                 }
1275
1276                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
1277         }
1278         else if (FC_CB_DESTROY == cb_type) {
1279                 /*
1280                  * $_[1] = $user_data;
1281                  */
1282
1283                 /* nothing to be done - the user data pointer
1284                  * is pushed onto the stack later */
1285         }
1286         else if (FC_CB_EXEC == cb_type) {
1287                 /*
1288                  * $_[0] = $ds;
1289                  * $_[1] = $vl;
1290                  * $_[2] = $meta;
1291                  * $_[3] = $user_data;
1292                  */
1293                 data_set_t   *ds;
1294                 value_list_t *vl;
1295
1296                 AV *pds = newAV ();
1297                 HV *pvl = newHV ();
1298
1299                 ds   = va_arg (ap, data_set_t *);
1300                 vl   = va_arg (ap, value_list_t *);
1301                 meta = va_arg (ap, notification_meta_t **);
1302
1303                 if (0 != data_set2av (aTHX_ ds, pds)) {
1304                         av_clear (pds);
1305                         av_undef (pds);
1306                         pds = (AV *)&PL_sv_undef;
1307                         ret = -1;
1308                 }
1309
1310                 if (0 != value_list2hv (aTHX_ vl, ds, pvl)) {
1311                         hv_clear (pvl);
1312                         hv_undef (pvl);
1313                         pvl = (HV *)&PL_sv_undef;
1314                         ret = -1;
1315                 }
1316
1317                 if (NULL != meta) {
1318                         pmeta = newAV ();
1319
1320                         if (0 != notification_meta2av (aTHX_ *meta, pmeta)) {
1321                                 av_clear (pmeta);
1322                                 av_undef (pmeta);
1323                                 pmeta = (AV *)&PL_sv_undef;
1324                                 ret = -1;
1325                         }
1326                 }
1327                 else {
1328                         pmeta = (AV *)&PL_sv_undef;
1329                 }
1330
1331                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1332                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1333                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pmeta)));
1334         }
1335
1336         XPUSHs (sv_2mortal (newRV_inc (data->user_data)));
1337
1338         PUTBACK;
1339
1340         retvals = call_pv ("Collectd::fc_call", G_SCALAR);
1341
1342         if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1343                 assert (pmeta != NULL);
1344
1345                 plugin_notification_meta_free (*meta);
1346                 av2notification_meta (aTHX_ pmeta, meta);
1347         }
1348
1349         SPAGAIN;
1350         if (0 < retvals) {
1351                 SV *tmp = POPs;
1352
1353                 /* the exec callbacks return a status, while
1354                  * the others return a boolean value */
1355                 if (FC_CB_EXEC == cb_type)
1356                         ret = SvIV (tmp);
1357                 else if (! SvTRUE (tmp))
1358                         ret = -1;
1359         }
1360
1361         PUTBACK;
1362         FREETMPS;
1363         LEAVE;
1364
1365         va_end (ap);
1366         return ret;
1367 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1368
1369 static int fc_create (int type, const oconfig_item_t *ci, void **user_data)
1370 {
1371         pfc_user_data_t *data;
1372
1373         int ret = 0;
1374
1375         dTHX;
1376
1377         if (NULL == perl_threads)
1378                 return 0;
1379
1380         if (NULL == aTHX) {
1381                 c_ithread_t *t = NULL;
1382
1383                 pthread_mutex_lock (&perl_threads->mutex);
1384                 t = c_ithread_create (perl_threads->head->interp);
1385                 pthread_mutex_unlock (&perl_threads->mutex);
1386
1387                 aTHX = t->interp;
1388         }
1389
1390         log_debug ("fc_create: c_ithread: interp = %p (active threads: %i)",
1391                         aTHX, perl_threads->number_of_threads);
1392
1393         if ((1 != ci->values_num)
1394                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1395                 log_warn ("A \"%s\" block expects a single string argument.",
1396                                 (FC_MATCH == type) ? "Match" : "Target");
1397                 return -1;
1398         }
1399
1400         data = (pfc_user_data_t *)smalloc (sizeof (*data));
1401         data->name      = sstrdup (ci->values[0].value.string);
1402         data->user_data = newSV (0);
1403
1404         ret = fc_call (aTHX_ type, FC_CB_CREATE, data, ci);
1405
1406         if (0 != ret)
1407                 PFC_USER_DATA_FREE (data);
1408         else
1409                 *user_data = data;
1410         return ret;
1411 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1412
1413 static int fc_destroy (int type, void **user_data)
1414 {
1415         pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1416
1417         int ret = 0;
1418
1419         dTHX;
1420
1421         if ((NULL == perl_threads) || (NULL == data))
1422                 return 0;
1423
1424         if (NULL == aTHX) {
1425                 c_ithread_t *t = NULL;
1426
1427                 pthread_mutex_lock (&perl_threads->mutex);
1428                 t = c_ithread_create (perl_threads->head->interp);
1429                 pthread_mutex_unlock (&perl_threads->mutex);
1430
1431                 aTHX = t->interp;
1432         }
1433
1434         log_debug ("fc_destroy: c_ithread: interp = %p (active threads: %i)",
1435                         aTHX, perl_threads->number_of_threads);
1436
1437         ret = fc_call (aTHX_ type, FC_CB_DESTROY, data);
1438
1439         PFC_USER_DATA_FREE (data);
1440         *user_data = NULL;
1441         return ret;
1442 } /* static int fc_destroy (int, void **) */
1443
1444 static int fc_exec (int type, const data_set_t *ds, const value_list_t *vl,
1445                 notification_meta_t **meta, void **user_data)
1446 {
1447         pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1448
1449         dTHX;
1450
1451         if (NULL == perl_threads)
1452                 return 0;
1453
1454         assert (NULL != data);
1455
1456         if (NULL == aTHX) {
1457                 c_ithread_t *t = NULL;
1458
1459                 pthread_mutex_lock (&perl_threads->mutex);
1460                 t = c_ithread_create (perl_threads->head->interp);
1461                 pthread_mutex_unlock (&perl_threads->mutex);
1462
1463                 aTHX = t->interp;
1464         }
1465
1466         log_debug ("fc_exec: c_ithread: interp = %p (active threads: %i)",
1467                         aTHX, perl_threads->number_of_threads);
1468
1469         return fc_call (aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1470 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1471                 notification_meta_t **, void **) */
1472
1473 static int pmatch_create (const oconfig_item_t *ci, void **user_data)
1474 {
1475         return fc_create (FC_MATCH, ci, user_data);
1476 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1477
1478 static int pmatch_destroy (void **user_data)
1479 {
1480         return fc_destroy (FC_MATCH, user_data);
1481 } /* static int pmatch_destroy (void **) */
1482
1483 static int pmatch_match (const data_set_t *ds, const value_list_t *vl,
1484                 notification_meta_t **meta, void **user_data)
1485 {
1486         return fc_exec (FC_MATCH, ds, vl, meta, user_data);
1487 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1488                 notification_meta_t **, void **) */
1489
1490 static match_proc_t pmatch = {
1491         pmatch_create, pmatch_destroy, pmatch_match
1492 };
1493
1494 static int ptarget_create (const oconfig_item_t *ci, void **user_data)
1495 {
1496         return fc_create (FC_TARGET, ci, user_data);
1497 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1498
1499 static int ptarget_destroy (void **user_data)
1500 {
1501         return fc_destroy (FC_TARGET, user_data);
1502 } /* static int ptarget_destroy (void **) */
1503
1504 static int ptarget_invoke (const data_set_t *ds, value_list_t *vl,
1505                 notification_meta_t **meta, void **user_data)
1506 {
1507         return fc_exec (FC_TARGET, ds, vl, meta, user_data);
1508 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1509                 notification_meta_t **, void **) */
1510
1511 static target_proc_t ptarget = {
1512         ptarget_create, ptarget_destroy, ptarget_invoke
1513 };
1514
1515 /*
1516  * Exported Perl API.
1517  */
1518
1519 /*
1520  * Collectd::plugin_register_data_set (type, dataset).
1521  *
1522  * type:
1523  *   type of the dataset
1524  *
1525  * dataset:
1526  *   dataset to be registered
1527  */
1528 static XS (Collectd_plugin_register_ds)
1529 {
1530         SV  *data = NULL;
1531         int ret   = 0;
1532
1533         dXSARGS;
1534
1535         log_warn ("Using plugin_register() to register new data-sets is "
1536                         "deprecated - add new entries to a custom types.db instead.");
1537
1538         if (2 != items) {
1539                 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1540                 XSRETURN_EMPTY;
1541         }
1542
1543         log_debug ("Collectd::plugin_register_data_set: "
1544                         "type = \"%s\", dataset = \"%s\"",
1545                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1546
1547         data = ST (1);
1548
1549         if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1550                 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1551                                 (AV *)SvRV (data));
1552         }
1553         else {
1554                 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1555                 XSRETURN_EMPTY;
1556         }
1557
1558         if (0 == ret)
1559                 XSRETURN_YES;
1560         else
1561                 XSRETURN_EMPTY;
1562 } /* static XS (Collectd_plugin_register_ds) */
1563
1564 /*
1565  * Collectd::plugin_unregister_data_set (type).
1566  *
1567  * type:
1568  *   type of the dataset
1569  */
1570 static XS (Collectd_plugin_unregister_ds)
1571 {
1572         dXSARGS;
1573
1574         if (1 != items) {
1575                 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1576                 XSRETURN_EMPTY;
1577         }
1578
1579         log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1580                         SvPV_nolen (ST (0)));
1581
1582         if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1583                 XSRETURN_YES;
1584         else
1585                 XSRETURN_EMPTY;
1586 } /* static XS (Collectd_plugin_register_ds) */
1587
1588 /*
1589  * Collectd::plugin_dispatch_values (name, values).
1590  *
1591  * name:
1592  *   name of the plugin
1593  *
1594  * values:
1595  *   value list to submit
1596  */
1597 static XS (Collectd_plugin_dispatch_values)
1598 {
1599         SV *values     = NULL;
1600         int values_idx = 0;
1601
1602         int ret = 0;
1603
1604         dXSARGS;
1605
1606         if (2 == items) {
1607                 log_warn ("Collectd::plugin_dispatch_values with two arguments "
1608                                 "is deprecated - pass the type through values->{type}.");
1609                 values_idx = 1;
1610         }
1611         else if (1 != items) {
1612                 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1613                 XSRETURN_EMPTY;
1614         }
1615
1616         log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1617                         SvPV_nolen (ST (values_idx)));
1618
1619         values = ST (values_idx);
1620
1621         if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1622                 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1623                 XSRETURN_EMPTY;
1624         }
1625
1626         if (((2 == items) && (NULL == ST (0))) || (NULL == values))
1627                 XSRETURN_EMPTY;
1628
1629         if ((2 == items) && (NULL == hv_store ((HV *)SvRV (values), "type", 4,
1630                         newSVsv (ST (0)), 0))) {
1631                 log_err ("Collectd::plugin_dispatch_values: Could not store type.");
1632                 XSRETURN_EMPTY;
1633         }
1634
1635         ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1636
1637         if (0 == ret)
1638                 XSRETURN_YES;
1639         else
1640                 XSRETURN_EMPTY;
1641 } /* static XS (Collectd_plugin_dispatch_values) */
1642
1643 /* Collectd::plugin_write (plugin, ds, vl).
1644  *
1645  * plugin:
1646  *   name of the plugin to call, may be 'undef'
1647  *
1648  * ds:
1649  *   data-set that describes the submitted values, may be 'undef'
1650  *
1651  * vl:
1652  *   value-list to be written
1653  */
1654 static XS (Collectd__plugin_write)
1655 {
1656         char *plugin;
1657         SV   *ds, *vl;
1658         AV   *ds_array;
1659
1660         int ret;
1661
1662         dXSARGS;
1663
1664         if (3 != items) {
1665                 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1666                 XSRETURN_EMPTY;
1667         }
1668
1669         log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1670                         SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1671                         SvPV_nolen (ST (2)));
1672
1673         if (! SvOK (ST (0)))
1674                 plugin = NULL;
1675         else
1676                 plugin = SvPV_nolen (ST (0));
1677
1678         ds = ST (1);
1679         if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1680                 ds_array = (AV *)SvRV (ds);
1681         else if (! SvOK (ds))
1682                 ds_array = NULL;
1683         else {
1684                 log_err ("Collectd::plugin_write: Invalid data-set.");
1685                 XSRETURN_EMPTY;
1686         }
1687
1688         vl = ST (2);
1689         if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1690                 log_err ("Collectd::plugin_write: Invalid value-list.");
1691                 XSRETURN_EMPTY;
1692         }
1693
1694         ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1695
1696         if (0 == ret)
1697                 XSRETURN_YES;
1698         else
1699                 XSRETURN_EMPTY;
1700 } /* static XS (Collectd__plugin_write) */
1701
1702 /*
1703  * Collectd::_plugin_flush (plugin, timeout, identifier).
1704  *
1705  * plugin:
1706  *   name of the plugin to flush
1707  *
1708  * timeout:
1709  *   timeout to use when flushing the data
1710  *
1711  * identifier:
1712  *   data-set identifier to flush
1713  */
1714 static XS (Collectd__plugin_flush)
1715 {
1716         char *plugin  = NULL;
1717         int   timeout = -1;
1718         char *id      = NULL;
1719
1720         dXSARGS;
1721
1722         if (3 != items) {
1723                 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1724                 XSRETURN_EMPTY;
1725         }
1726
1727         if (SvOK (ST (0)))
1728                 plugin = SvPV_nolen (ST (0));
1729
1730         if (SvOK (ST (1)))
1731                 timeout = (int)SvIV (ST (1));
1732
1733         if (SvOK (ST (2)))
1734                 id = SvPV_nolen (ST (2));
1735
1736         log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1737                         "id = \"%s\"", plugin, timeout, id);
1738
1739         if (0 == plugin_flush (plugin, timeout, id))
1740                 XSRETURN_YES;
1741         else
1742                 XSRETURN_EMPTY;
1743 } /* static XS (Collectd__plugin_flush) */
1744
1745 /*
1746  * Collectd::plugin_dispatch_notification (notif).
1747  *
1748  * notif:
1749  *   notification to dispatch
1750  */
1751 static XS (Collectd_plugin_dispatch_notification)
1752 {
1753         SV *notif = NULL;
1754
1755         int ret = 0;
1756
1757         dXSARGS;
1758
1759         if (1 != items) {
1760                 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
1761                 XSRETURN_EMPTY;
1762         }
1763
1764         log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1765                         SvPV_nolen (ST (0)));
1766
1767         notif = ST (0);
1768
1769         if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
1770                 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
1771                 XSRETURN_EMPTY;
1772         }
1773
1774         ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
1775
1776         if (0 == ret)
1777                 XSRETURN_YES;
1778         else
1779                 XSRETURN_EMPTY;
1780 } /* static XS (Collectd_plugin_dispatch_notification) */
1781
1782 /*
1783  * Collectd::plugin_log (level, message).
1784  *
1785  * level:
1786  *   log level (LOG_DEBUG, ... LOG_ERR)
1787  *
1788  * message:
1789  *   log message
1790  */
1791 static XS (Collectd_plugin_log)
1792 {
1793         dXSARGS;
1794
1795         if (2 != items) {
1796                 log_err ("Usage: Collectd::plugin_log(level, message)");
1797                 XSRETURN_EMPTY;
1798         }
1799
1800         plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
1801         XSRETURN_YES;
1802 } /* static XS (Collectd_plugin_log) */
1803
1804 /*
1805  * Collectd::_fc_register (type, name)
1806  *
1807  * type:
1808  *   match | target
1809  *
1810  * name:
1811  *   name of the match
1812  */
1813 static XS (Collectd__fc_register)
1814 {
1815         int   type;
1816         char *name;
1817
1818         int ret = 0;
1819
1820         dXSARGS;
1821
1822         if (2 != items) {
1823                 log_err ("Usage: Collectd::_fc_register(type, name)");
1824                 XSRETURN_EMPTY;
1825         }
1826
1827         type = SvIV (ST (0));
1828         name = SvPV_nolen (ST (1));
1829
1830         if (FC_MATCH == type)
1831                 ret = fc_register_match (name, pmatch);
1832         else if (FC_TARGET == type)
1833                 ret = fc_register_target (name, ptarget);
1834
1835         if (0 == ret)
1836                 XSRETURN_YES;
1837         else
1838                 XSRETURN_EMPTY;
1839 } /* static XS (Collectd_fc_register) */
1840
1841 /*
1842  * Collectd::call_by_name (...).
1843  *
1844  * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1845  */
1846 static XS (Collectd_call_by_name)
1847 {
1848         SV   *tmp  = NULL;
1849         char *name = NULL;
1850
1851         if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
1852                 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
1853                 CLEAR_STACK_FRAME;
1854                 return;
1855         }
1856
1857         name = SvPV_nolen (tmp);
1858
1859         if (NULL == get_cv (name, 0)) {
1860                 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
1861                 CLEAR_STACK_FRAME;
1862                 return;
1863         }
1864
1865         /* simply pass on the subroutine call without touching the stack,
1866          * thus leaving any arguments and return values in place */
1867         call_pv (name, 0);
1868 } /* static XS (Collectd_call_by_name) */
1869
1870 /*
1871  * Interface to collectd.
1872  */
1873
1874 static int perl_init (void)
1875 {
1876         dTHX;
1877
1878         if (NULL == perl_threads)
1879                 return 0;
1880
1881         if (NULL == aTHX) {
1882                 c_ithread_t *t = NULL;
1883
1884                 pthread_mutex_lock (&perl_threads->mutex);
1885                 t = c_ithread_create (perl_threads->head->interp);
1886                 pthread_mutex_unlock (&perl_threads->mutex);
1887
1888                 aTHX = t->interp;
1889         }
1890
1891         log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1892                         aTHX, perl_threads->number_of_threads);
1893         return pplugin_call_all (aTHX_ PLUGIN_INIT);
1894 } /* static int perl_init (void) */
1895
1896 static int perl_read (void)
1897 {
1898         dTHX;
1899
1900         if (NULL == perl_threads)
1901                 return 0;
1902
1903         if (NULL == aTHX) {
1904                 c_ithread_t *t = NULL;
1905
1906                 pthread_mutex_lock (&perl_threads->mutex);
1907                 t = c_ithread_create (perl_threads->head->interp);
1908                 pthread_mutex_unlock (&perl_threads->mutex);
1909
1910                 aTHX = t->interp;
1911         }
1912
1913         log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1914                         aTHX, perl_threads->number_of_threads);
1915         return pplugin_call_all (aTHX_ PLUGIN_READ);
1916 } /* static int perl_read (void) */
1917
1918 static int perl_write (const data_set_t *ds, const value_list_t *vl,
1919                 user_data_t __attribute__((unused)) *user_data)
1920 {
1921         dTHX;
1922
1923         if (NULL == perl_threads)
1924                 return 0;
1925
1926         if (NULL == aTHX) {
1927                 c_ithread_t *t = NULL;
1928
1929                 pthread_mutex_lock (&perl_threads->mutex);
1930                 t = c_ithread_create (perl_threads->head->interp);
1931                 pthread_mutex_unlock (&perl_threads->mutex);
1932
1933                 aTHX = t->interp;
1934         }
1935
1936         log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
1937                         aTHX, perl_threads->number_of_threads);
1938         return pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
1939 } /* static int perl_write (const data_set_t *, const value_list_t *) */
1940
1941 static void perl_log (int level, const char *msg,
1942                 user_data_t __attribute__((unused)) *user_data)
1943 {
1944         dTHX;
1945
1946         if (NULL == perl_threads)
1947                 return;
1948
1949         if (NULL == aTHX) {
1950                 c_ithread_t *t = NULL;
1951
1952                 pthread_mutex_lock (&perl_threads->mutex);
1953                 t = c_ithread_create (perl_threads->head->interp);
1954                 pthread_mutex_unlock (&perl_threads->mutex);
1955
1956                 aTHX = t->interp;
1957         }
1958
1959         pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
1960         return;
1961 } /* static void perl_log (int, const char *) */
1962
1963 static int perl_notify (const notification_t *notif,
1964                 user_data_t __attribute__((unused)) *user_data)
1965 {
1966         dTHX;
1967
1968         if (NULL == perl_threads)
1969                 return 0;
1970
1971         if (NULL == aTHX) {
1972                 c_ithread_t *t = NULL;
1973
1974                 pthread_mutex_lock (&perl_threads->mutex);
1975                 t = c_ithread_create (perl_threads->head->interp);
1976                 pthread_mutex_unlock (&perl_threads->mutex);
1977
1978                 aTHX = t->interp;
1979         }
1980         return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
1981 } /* static int perl_notify (const notification_t *) */
1982
1983 static int perl_flush (int timeout, const char *identifier,
1984                 user_data_t __attribute__((unused)) *user_data)
1985 {
1986         dTHX;
1987
1988         if (NULL == perl_threads)
1989                 return 0;
1990
1991         if (NULL == aTHX) {
1992                 c_ithread_t *t = NULL;
1993
1994                 pthread_mutex_lock (&perl_threads->mutex);
1995                 t = c_ithread_create (perl_threads->head->interp);
1996                 pthread_mutex_unlock (&perl_threads->mutex);
1997
1998                 aTHX = t->interp;
1999         }
2000         return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout, identifier);
2001 } /* static int perl_flush (const int) */
2002
2003 static int perl_shutdown (void)
2004 {
2005         c_ithread_t *t = NULL;
2006
2007         int ret = 0;
2008
2009         dTHX;
2010
2011         plugin_unregister_complex_config ("perl");
2012
2013         if (NULL == perl_threads)
2014                 return 0;
2015
2016         if (NULL == aTHX) {
2017                 c_ithread_t *t = NULL;
2018
2019                 pthread_mutex_lock (&perl_threads->mutex);
2020                 t = c_ithread_create (perl_threads->head->interp);
2021                 pthread_mutex_unlock (&perl_threads->mutex);
2022
2023                 aTHX = t->interp;
2024         }
2025
2026         log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2027                         aTHX, perl_threads->number_of_threads);
2028
2029         plugin_unregister_log ("perl");
2030         plugin_unregister_notification ("perl");
2031         plugin_unregister_init ("perl");
2032         plugin_unregister_read ("perl");
2033         plugin_unregister_write ("perl");
2034         plugin_unregister_flush ("perl");
2035
2036         ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
2037
2038         pthread_mutex_lock (&perl_threads->mutex);
2039         t = perl_threads->tail;
2040
2041         while (NULL != t) {
2042                 c_ithread_t *thr = t;
2043
2044                 /* the pointer has to be advanced before destroying
2045                  * the thread as this will free the memory */
2046                 t = t->prev;
2047
2048                 c_ithread_destroy (thr);
2049         }
2050
2051         pthread_mutex_unlock (&perl_threads->mutex);
2052         pthread_mutex_destroy (&perl_threads->mutex);
2053
2054         sfree (perl_threads);
2055
2056         pthread_key_delete (perl_thr_key);
2057
2058         PERL_SYS_TERM ();
2059
2060         plugin_unregister_shutdown ("perl");
2061         return ret;
2062 } /* static void perl_shutdown (void) */
2063
2064 /*
2065  * Access functions for global variables.
2066  *
2067  * These functions implement the "magic" used to access
2068  * the global variables from Perl.
2069  */
2070
2071 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
2072 {
2073         char *pv = mg->mg_ptr;
2074         sv_setpv (var, pv);
2075         return 0;
2076 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2077
2078 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
2079 {
2080         char *pv = mg->mg_ptr;
2081         sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
2082         return 0;
2083 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2084
2085 static int g_iv_get (pTHX_ SV *var, MAGIC *mg)
2086 {
2087         int *iv = (int *)mg->mg_ptr;
2088         sv_setiv (var, *iv);
2089         return 0;
2090 } /* static int g_iv_get (pTHX_ SV *, MAGIC *) */
2091
2092 static int g_iv_set (pTHX_ SV *var, MAGIC *mg)
2093 {
2094         int *iv = (int *)mg->mg_ptr;
2095         *iv = (int)SvIV (var);
2096         return 0;
2097 } /* static int g_iv_set (pTHX_ SV *, MAGIC *) */
2098
2099 static MGVTBL g_pv_vtbl = {
2100         g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2101 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2102                 , NULL
2103 #endif
2104 };
2105 static MGVTBL g_iv_vtbl = {
2106         g_iv_get, g_iv_set, NULL, NULL, NULL, NULL, NULL
2107 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2108                 , NULL
2109 #endif
2110 };
2111
2112 /* bootstrap the Collectd module */
2113 static void xs_init (pTHX)
2114 {
2115         HV   *stash = NULL;
2116         SV   *tmp   = NULL;
2117         char *file  = __FILE__;
2118
2119         int i = 0;
2120
2121         dXSUB_SYS;
2122
2123         /* enable usage of Perl modules using shared libraries */
2124         newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2125
2126         /* register API */
2127         for (i = 0; NULL != api[i].f; ++i)
2128                 newXS (api[i].name, api[i].f, file);
2129
2130         stash = gv_stashpv ("Collectd", 1);
2131
2132         /* export "constants" */
2133         for (i = 0; '\0' != constants[i].name[0]; ++i)
2134                 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
2135
2136         /* export global variables
2137          * by adding "magic" to the SV's representing the globale variables
2138          * perl is able to automagically call the get/set function when
2139          * accessing any such variable (this is basically the same as using
2140          * tie() in Perl) */
2141         /* global strings */
2142         for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
2143                 tmp = get_sv (g_strings[i].name, 1);
2144                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
2145                                 g_strings[i].var, 0);
2146         }
2147
2148         /* global integers */
2149         for (i = 0; '\0' != g_integers[i].name[0]; ++i) {
2150                 tmp = get_sv (g_integers[i].name, 1);
2151                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_iv_vtbl,
2152                                 (char *)g_integers[i].var, 0);
2153         }
2154         return;
2155 } /* static void xs_init (pTHX) */
2156
2157 /* Initialize the global Perl interpreter. */
2158 static int init_pi (int argc, char **argv)
2159 {
2160         dTHXa (NULL);
2161
2162         if (NULL != perl_threads)
2163                 return 0;
2164
2165         log_info ("Initializing Perl interpreter...");
2166 #if COLLECT_DEBUG
2167         {
2168                 int i = 0;
2169
2170                 for (i = 0; i < argc; ++i)
2171                         log_debug ("argv[%i] = \"%s\"", i, argv[i]);
2172         }
2173 #endif /* COLLECT_DEBUG */
2174
2175         if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
2176                 log_err ("init_pi: pthread_key_create failed");
2177
2178                 /* this must not happen - cowardly giving up if it does */
2179                 return -1;
2180         }
2181
2182 #ifdef __FreeBSD__
2183         /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2184          * triggers a "value computed is not used" warning by gcc. */
2185         (void)
2186 #endif
2187         PERL_SYS_INIT3 (&argc, &argv, &environ);
2188
2189         perl_threads = (c_ithread_list_t *)smalloc (sizeof (c_ithread_list_t));
2190         memset (perl_threads, 0, sizeof (c_ithread_list_t));
2191
2192         pthread_mutex_init (&perl_threads->mutex, NULL);
2193         /* locking the mutex should not be necessary at this point
2194          * but let's just do it for the sake of completeness */
2195         pthread_mutex_lock (&perl_threads->mutex);
2196
2197         perl_threads->head = c_ithread_create (NULL);
2198         perl_threads->tail = perl_threads->head;
2199
2200         if (NULL == (perl_threads->head->interp = perl_alloc ())) {
2201                 log_err ("init_pi: Not enough memory.");
2202                 exit (3);
2203         }
2204
2205         aTHX = perl_threads->head->interp;
2206         pthread_mutex_unlock (&perl_threads->mutex);
2207
2208         perl_construct (aTHX);
2209
2210         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2211
2212         if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
2213                 SV *err = get_sv ("@", 1);
2214                 log_err ("init_pi: Unable to bootstrap Collectd: %s",
2215                                 SvPV_nolen (err));
2216
2217                 perl_destruct (perl_threads->head->interp);
2218                 perl_free (perl_threads->head->interp);
2219                 sfree (perl_threads);
2220
2221                 pthread_key_delete (perl_thr_key);
2222                 return -1;
2223         }
2224
2225         /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2226         sv_setpv (get_sv ("0", 0), "collectd");
2227
2228         perl_run (aTHX);
2229
2230         plugin_register_log ("perl", perl_log, /* user_data = */ NULL);
2231         plugin_register_notification ("perl", perl_notify,
2232                         /* user_data = */ NULL);
2233         plugin_register_init ("perl", perl_init);
2234
2235         plugin_register_read ("perl", perl_read);
2236
2237         plugin_register_write ("perl", perl_write, /* user_data = */ NULL);
2238         plugin_register_flush ("perl", perl_flush, /* user_data = */ NULL);
2239         plugin_register_shutdown ("perl", perl_shutdown);
2240         return 0;
2241 } /* static int init_pi (const char **, const int) */
2242
2243 /*
2244  * LoadPlugin "<Plugin>"
2245  */
2246 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
2247 {
2248         char module_name[DATA_MAX_NAME_LEN];
2249
2250         char *value = NULL;
2251
2252         if ((0 != ci->children_num) || (1 != ci->values_num)
2253                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2254                 log_err ("LoadPlugin expects a single string argument.");
2255                 return 1;
2256         }
2257
2258         value = ci->values[0].value.string;
2259
2260         if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
2261                 log_err ("Invalid module name %s", value);
2262                 return (1);
2263         }
2264
2265         if (0 != init_pi (perl_argc, perl_argv))
2266                 return -1;
2267
2268         assert (NULL != perl_threads);
2269         assert (NULL != perl_threads->head);
2270
2271         aTHX = perl_threads->head->interp;
2272
2273         log_debug ("perl_config: loading perl plugin \"%s\"", value);
2274         load_module (PERL_LOADMOD_NOIMPORT,
2275                         newSVpv (module_name, strlen (module_name)), Nullsv);
2276         return 0;
2277 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2278
2279 /*
2280  * BaseName "<Name>"
2281  */
2282 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
2283 {
2284         char *value = NULL;
2285
2286         if ((0 != ci->children_num) || (1 != ci->values_num)
2287                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2288                 log_err ("BaseName expects a single string argument.");
2289                 return 1;
2290         }
2291
2292         value = ci->values[0].value.string;
2293
2294         log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
2295         sstrncpy (base_name, value, sizeof (base_name));
2296         return 0;
2297 } /* static int perl_config_basename (oconfig_item_it *) */
2298
2299 /*
2300  * EnableDebugger "<Package>"|""
2301  */
2302 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
2303 {
2304         char *value = NULL;
2305
2306         if ((0 != ci->children_num) || (1 != ci->values_num)
2307                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2308                 log_err ("EnableDebugger expects a single string argument.");
2309                 return 1;
2310         }
2311
2312         if (NULL != perl_threads) {
2313                 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
2314                 return 1;
2315         }
2316
2317         value = ci->values[0].value.string;
2318
2319         perl_argv = (char **)realloc (perl_argv,
2320                         (++perl_argc + 1) * sizeof (char *));
2321
2322         if (NULL == perl_argv) {
2323                 log_err ("perl_config: Not enough memory.");
2324                 exit (3);
2325         }
2326
2327         if ('\0' == value[0]) {
2328                 perl_argv[perl_argc - 1] = "-d";
2329         }
2330         else {
2331                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 4);
2332                 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
2333                 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
2334         }
2335
2336         perl_argv[perl_argc] = NULL;
2337         return 0;
2338 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2339
2340 /*
2341  * IncludeDir "<Dir>"
2342  */
2343 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
2344 {
2345         char *value = NULL;
2346
2347         if ((0 != ci->children_num) || (1 != ci->values_num)
2348                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2349                 log_err ("IncludeDir expects a single string argument.");
2350                 return 1;
2351         }
2352
2353         value = ci->values[0].value.string;
2354
2355         if (NULL == aTHX) {
2356                 perl_argv = (char **)realloc (perl_argv,
2357                                 (++perl_argc + 1) * sizeof (char *));
2358
2359                 if (NULL == perl_argv) {
2360                         log_err ("perl_config: Not enough memory.");
2361                         exit (3);
2362                 }
2363
2364                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 3);
2365                 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2366                 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
2367
2368                 perl_argv[perl_argc] = NULL;
2369         }
2370         else {
2371                 /* prepend the directory to @INC */
2372                 av_unshift (GvAVn (PL_incgv), 1);
2373                 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
2374         }
2375         return 0;
2376 } /* static int perl_config_includedir (oconfig_item_it *) */
2377
2378 /*
2379  * <Plugin> block
2380  */
2381 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2382 {
2383         int retvals = 0;
2384         int ret     = 0;
2385
2386         char *plugin;
2387         HV   *config;
2388
2389         dSP;
2390
2391         if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2392                 log_err ("LoadPlugin expects a single string argument.");
2393                 return 1;
2394         }
2395
2396         plugin = ci->values[0].value.string;
2397         config = newHV ();
2398
2399         if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2400                 hv_clear (config);
2401                 hv_undef (config);
2402
2403                 log_err ("Unable to convert configuration to a Perl hash value.");
2404                 config = (HV *)&PL_sv_undef;
2405         }
2406
2407         ENTER;
2408         SAVETMPS;
2409
2410         PUSHMARK (SP);
2411
2412         XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2413         XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2414
2415         PUTBACK;
2416
2417         retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2418
2419         SPAGAIN;
2420         if (0 < retvals) {
2421                 SV *tmp = POPs;
2422                 if (! SvTRUE (tmp))
2423                         ret = 1;
2424         }
2425         else
2426                 ret = 1;
2427
2428         PUTBACK;
2429         FREETMPS;
2430         LEAVE;
2431         return ret;
2432 } /* static int perl_config_plugin (oconfig_item_it *) */
2433
2434 static int perl_config (oconfig_item_t *ci)
2435 {
2436         int status = 0;
2437         int i = 0;
2438
2439         dTHXa (NULL);
2440
2441         for (i = 0; i < ci->children_num; ++i) {
2442                 oconfig_item_t *c = ci->children + i;
2443                 int current_status = 0;
2444
2445                 if (NULL != perl_threads)
2446                         aTHX = PERL_GET_CONTEXT;
2447
2448                 if (0 == strcasecmp (c->key, "LoadPlugin"))
2449                         current_status = perl_config_loadplugin (aTHX_ c);
2450                 else if (0 == strcasecmp (c->key, "BaseName"))
2451                         current_status = perl_config_basename (aTHX_ c);
2452                 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2453                         current_status = perl_config_enabledebugger (aTHX_ c);
2454                 else if (0 == strcasecmp (c->key, "IncludeDir"))
2455                         current_status = perl_config_includedir (aTHX_ c);
2456                 else if (0 == strcasecmp (c->key, "Plugin"))
2457                         current_status = perl_config_plugin (aTHX_ c);
2458                 else
2459                 {
2460                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
2461                         current_status = 0;
2462                 }
2463
2464                 /* fatal error - it's up to perl_config_* to clean up */
2465                 if (0 > current_status) {
2466                         log_err ("Configuration failed with a fatal error - "
2467                                         "plugin disabled!");
2468                         return current_status;
2469                 }
2470
2471                 status += current_status;
2472         }
2473         return status;
2474 } /* static int perl_config (oconfig_item_t *) */
2475
2476 void module_register (void)
2477 {
2478         perl_argc = 4;
2479         perl_argv = (char **)smalloc ((perl_argc + 1) * sizeof (char *));
2480
2481         /* default options for the Perl interpreter */
2482         perl_argv[0] = "";
2483         perl_argv[1] = "-MCollectd";
2484         perl_argv[2] = "-e";
2485         perl_argv[3] = "1";
2486         perl_argv[4] = NULL;
2487
2488         plugin_register_complex_config ("perl", perl_config);
2489         return;
2490 } /* void module_register (void) */
2491
2492 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
2493