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