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