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