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