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