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