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