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