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