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