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