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