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