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         log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1933                         aTHX, perl_threads->number_of_threads);
1934         return pplugin_call_all (aTHX_ PLUGIN_READ);
1935 } /* static int perl_read (void) */
1936
1937 static int perl_write (const data_set_t *ds, const value_list_t *vl,
1938                 user_data_t __attribute__((unused)) *user_data)
1939 {
1940         dTHX;
1941
1942         if (NULL == perl_threads)
1943                 return 0;
1944
1945         if (NULL == aTHX) {
1946                 c_ithread_t *t = NULL;
1947
1948                 pthread_mutex_lock (&perl_threads->mutex);
1949                 t = c_ithread_create (perl_threads->head->interp);
1950                 pthread_mutex_unlock (&perl_threads->mutex);
1951
1952                 aTHX = t->interp;
1953         }
1954
1955         log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
1956                         aTHX, perl_threads->number_of_threads);
1957         return pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
1958 } /* static int perl_write (const data_set_t *, const value_list_t *) */
1959
1960 static void perl_log (int level, const char *msg,
1961                 user_data_t __attribute__((unused)) *user_data)
1962 {
1963         dTHX;
1964
1965         if (NULL == perl_threads)
1966                 return;
1967
1968         if (NULL == aTHX) {
1969                 c_ithread_t *t = NULL;
1970
1971                 pthread_mutex_lock (&perl_threads->mutex);
1972                 t = c_ithread_create (perl_threads->head->interp);
1973                 pthread_mutex_unlock (&perl_threads->mutex);
1974
1975                 aTHX = t->interp;
1976         }
1977
1978         pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
1979         return;
1980 } /* static void perl_log (int, const char *) */
1981
1982 static int perl_notify (const notification_t *notif,
1983                 user_data_t __attribute__((unused)) *user_data)
1984 {
1985         dTHX;
1986
1987         if (NULL == perl_threads)
1988                 return 0;
1989
1990         if (NULL == aTHX) {
1991                 c_ithread_t *t = NULL;
1992
1993                 pthread_mutex_lock (&perl_threads->mutex);
1994                 t = c_ithread_create (perl_threads->head->interp);
1995                 pthread_mutex_unlock (&perl_threads->mutex);
1996
1997                 aTHX = t->interp;
1998         }
1999         return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
2000 } /* static int perl_notify (const notification_t *) */
2001
2002 static int perl_flush (cdtime_t timeout, const char *identifier,
2003                 user_data_t __attribute__((unused)) *user_data)
2004 {
2005         dTHX;
2006
2007         if (NULL == perl_threads)
2008                 return 0;
2009
2010         if (NULL == aTHX) {
2011                 c_ithread_t *t = NULL;
2012
2013                 pthread_mutex_lock (&perl_threads->mutex);
2014                 t = c_ithread_create (perl_threads->head->interp);
2015                 pthread_mutex_unlock (&perl_threads->mutex);
2016
2017                 aTHX = t->interp;
2018         }
2019         return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout, identifier);
2020 } /* static int perl_flush (const int) */
2021
2022 static int perl_shutdown (void)
2023 {
2024         c_ithread_t *t = NULL;
2025
2026         int ret = 0;
2027
2028         dTHX;
2029
2030         plugin_unregister_complex_config ("perl");
2031
2032         if (NULL == perl_threads)
2033                 return 0;
2034
2035         if (NULL == aTHX) {
2036                 c_ithread_t *t = NULL;
2037
2038                 pthread_mutex_lock (&perl_threads->mutex);
2039                 t = c_ithread_create (perl_threads->head->interp);
2040                 pthread_mutex_unlock (&perl_threads->mutex);
2041
2042                 aTHX = t->interp;
2043         }
2044
2045         log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2046                         aTHX, perl_threads->number_of_threads);
2047
2048         plugin_unregister_log ("perl");
2049         plugin_unregister_notification ("perl");
2050         plugin_unregister_init ("perl");
2051         plugin_unregister_read ("perl");
2052         plugin_unregister_write ("perl");
2053         plugin_unregister_flush ("perl");
2054
2055         ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
2056
2057         pthread_mutex_lock (&perl_threads->mutex);
2058         t = perl_threads->tail;
2059
2060         while (NULL != t) {
2061                 c_ithread_t *thr = t;
2062
2063                 /* the pointer has to be advanced before destroying
2064                  * the thread as this will free the memory */
2065                 t = t->prev;
2066
2067                 c_ithread_destroy (thr);
2068         }
2069
2070         pthread_mutex_unlock (&perl_threads->mutex);
2071         pthread_mutex_destroy (&perl_threads->mutex);
2072
2073         sfree (perl_threads);
2074
2075         pthread_key_delete (perl_thr_key);
2076
2077         PERL_SYS_TERM ();
2078
2079         plugin_unregister_shutdown ("perl");
2080         return ret;
2081 } /* static void perl_shutdown (void) */
2082
2083 /*
2084  * Access functions for global variables.
2085  *
2086  * These functions implement the "magic" used to access
2087  * the global variables from Perl.
2088  */
2089
2090 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
2091 {
2092         char *pv = mg->mg_ptr;
2093         sv_setpv (var, pv);
2094         return 0;
2095 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2096
2097 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
2098 {
2099         char *pv = mg->mg_ptr;
2100         sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
2101         return 0;
2102 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2103
2104 static int g_interval_get (pTHX_ SV *var, MAGIC *mg)
2105 {
2106         cdtime_t *interval = (cdtime_t *)mg->mg_ptr;
2107         double nv;
2108
2109         nv = CDTIME_T_TO_DOUBLE (*interval);
2110
2111         sv_setnv (var, nv);
2112         return 0;
2113 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2114
2115 static int g_interval_set (pTHX_ SV *var, MAGIC *mg)
2116 {
2117         cdtime_t *interval = (cdtime_t *)mg->mg_ptr;
2118         double nv;
2119
2120         nv = (double)SvNV (var);
2121
2122         *interval = DOUBLE_TO_CDTIME_T (nv);
2123         return 0;
2124 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2125
2126 static MGVTBL g_pv_vtbl = {
2127         g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2128 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2129                 , NULL
2130 #endif
2131 };
2132 static MGVTBL g_interval_vtbl = {
2133         g_interval_get, g_interval_set, NULL, NULL, NULL, NULL, NULL
2134 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2135                 , NULL
2136 #endif
2137 };
2138
2139 /* bootstrap the Collectd module */
2140 static void xs_init (pTHX)
2141 {
2142         HV   *stash = NULL;
2143         SV   *tmp   = NULL;
2144         char *file  = __FILE__;
2145
2146         int i = 0;
2147
2148         dXSUB_SYS;
2149
2150         /* enable usage of Perl modules using shared libraries */
2151         newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2152
2153         /* register API */
2154         for (i = 0; NULL != api[i].f; ++i)
2155                 newXS (api[i].name, api[i].f, file);
2156
2157         stash = gv_stashpv ("Collectd", 1);
2158
2159         /* export "constants" */
2160         for (i = 0; '\0' != constants[i].name[0]; ++i)
2161                 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
2162
2163         /* export global variables
2164          * by adding "magic" to the SV's representing the globale variables
2165          * perl is able to automagically call the get/set function when
2166          * accessing any such variable (this is basically the same as using
2167          * tie() in Perl) */
2168         /* global strings */
2169         for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
2170                 tmp = get_sv (g_strings[i].name, 1);
2171                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
2172                                 g_strings[i].var, 0);
2173         }
2174
2175         tmp = get_sv ("Collectd::interval_g", /* create = */ 1);
2176         sv_magicext (tmp, NULL, /* how = */ PERL_MAGIC_ext,
2177                         /* vtbl = */ &g_interval_vtbl,
2178                         /* name = */ (char *) &interval_g, /* namelen = */ 0);
2179
2180         return;
2181 } /* static void xs_init (pTHX) */
2182
2183 /* Initialize the global Perl interpreter. */
2184 static int init_pi (int argc, char **argv)
2185 {
2186         dTHXa (NULL);
2187
2188         if (NULL != perl_threads)
2189                 return 0;
2190
2191         log_info ("Initializing Perl interpreter...");
2192 #if COLLECT_DEBUG
2193         {
2194                 int i = 0;
2195
2196                 for (i = 0; i < argc; ++i)
2197                         log_debug ("argv[%i] = \"%s\"", i, argv[i]);
2198         }
2199 #endif /* COLLECT_DEBUG */
2200
2201         if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
2202                 log_err ("init_pi: pthread_key_create failed");
2203
2204                 /* this must not happen - cowardly giving up if it does */
2205                 return -1;
2206         }
2207
2208 #ifdef __FreeBSD__
2209         /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2210          * triggers a "value computed is not used" warning by gcc. */
2211         (void)
2212 #endif
2213         PERL_SYS_INIT3 (&argc, &argv, &environ);
2214
2215         perl_threads = (c_ithread_list_t *)smalloc (sizeof (c_ithread_list_t));
2216         memset (perl_threads, 0, sizeof (c_ithread_list_t));
2217
2218         pthread_mutex_init (&perl_threads->mutex, NULL);
2219         /* locking the mutex should not be necessary at this point
2220          * but let's just do it for the sake of completeness */
2221         pthread_mutex_lock (&perl_threads->mutex);
2222
2223         perl_threads->head = c_ithread_create (NULL);
2224         perl_threads->tail = perl_threads->head;
2225
2226         if (NULL == (perl_threads->head->interp = perl_alloc ())) {
2227                 log_err ("init_pi: Not enough memory.");
2228                 exit (3);
2229         }
2230
2231         aTHX = perl_threads->head->interp;
2232         pthread_mutex_unlock (&perl_threads->mutex);
2233
2234         perl_construct (aTHX);
2235
2236         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2237
2238         if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
2239                 SV *err = get_sv ("@", 1);
2240                 log_err ("init_pi: Unable to bootstrap Collectd: %s",
2241                                 SvPV_nolen (err));
2242
2243                 perl_destruct (perl_threads->head->interp);
2244                 perl_free (perl_threads->head->interp);
2245                 sfree (perl_threads);
2246
2247                 pthread_key_delete (perl_thr_key);
2248                 return -1;
2249         }
2250
2251         /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2252         sv_setpv (get_sv ("0", 0), "collectd");
2253
2254         perl_run (aTHX);
2255
2256         plugin_register_log ("perl", perl_log, /* user_data = */ NULL);
2257         plugin_register_notification ("perl", perl_notify,
2258                         /* user_data = */ NULL);
2259         plugin_register_init ("perl", perl_init);
2260
2261         plugin_register_read ("perl", perl_read);
2262
2263         plugin_register_write ("perl", perl_write, /* user_data = */ NULL);
2264         plugin_register_flush ("perl", perl_flush, /* user_data = */ NULL);
2265         plugin_register_shutdown ("perl", perl_shutdown);
2266         return 0;
2267 } /* static int init_pi (const char **, const int) */
2268
2269 /*
2270  * LoadPlugin "<Plugin>"
2271  */
2272 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
2273 {
2274         char module_name[DATA_MAX_NAME_LEN];
2275
2276         char *value = NULL;
2277
2278         if ((0 != ci->children_num) || (1 != ci->values_num)
2279                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2280                 log_err ("LoadPlugin expects a single string argument.");
2281                 return 1;
2282         }
2283
2284         value = ci->values[0].value.string;
2285
2286         if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
2287                 log_err ("Invalid module name %s", value);
2288                 return (1);
2289         }
2290
2291         if (0 != init_pi (perl_argc, perl_argv))
2292                 return -1;
2293
2294         assert (NULL != perl_threads);
2295         assert (NULL != perl_threads->head);
2296
2297         aTHX = perl_threads->head->interp;
2298
2299         log_debug ("perl_config: loading perl plugin \"%s\"", value);
2300         load_module (PERL_LOADMOD_NOIMPORT,
2301                         newSVpv (module_name, strlen (module_name)), Nullsv);
2302         return 0;
2303 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2304
2305 /*
2306  * BaseName "<Name>"
2307  */
2308 static int perl_config_basename (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 ("BaseName expects a single string argument.");
2315                 return 1;
2316         }
2317
2318         value = ci->values[0].value.string;
2319
2320         log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
2321         sstrncpy (base_name, value, sizeof (base_name));
2322         return 0;
2323 } /* static int perl_config_basename (oconfig_item_it *) */
2324
2325 /*
2326  * EnableDebugger "<Package>"|""
2327  */
2328 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
2329 {
2330         char *value = NULL;
2331
2332         if ((0 != ci->children_num) || (1 != ci->values_num)
2333                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2334                 log_err ("EnableDebugger expects a single string argument.");
2335                 return 1;
2336         }
2337
2338         if (NULL != perl_threads) {
2339                 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
2340                 return 1;
2341         }
2342
2343         value = ci->values[0].value.string;
2344
2345         perl_argv = (char **)realloc (perl_argv,
2346                         (++perl_argc + 1) * sizeof (char *));
2347
2348         if (NULL == perl_argv) {
2349                 log_err ("perl_config: Not enough memory.");
2350                 exit (3);
2351         }
2352
2353         if ('\0' == value[0]) {
2354                 perl_argv[perl_argc - 1] = "-d";
2355         }
2356         else {
2357                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 4);
2358                 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
2359                 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
2360         }
2361
2362         perl_argv[perl_argc] = NULL;
2363         return 0;
2364 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2365
2366 /*
2367  * IncludeDir "<Dir>"
2368  */
2369 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
2370 {
2371         char *value = NULL;
2372
2373         if ((0 != ci->children_num) || (1 != ci->values_num)
2374                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2375                 log_err ("IncludeDir expects a single string argument.");
2376                 return 1;
2377         }
2378
2379         value = ci->values[0].value.string;
2380
2381         if (NULL == aTHX) {
2382                 perl_argv = (char **)realloc (perl_argv,
2383                                 (++perl_argc + 1) * sizeof (char *));
2384
2385                 if (NULL == perl_argv) {
2386                         log_err ("perl_config: Not enough memory.");
2387                         exit (3);
2388                 }
2389
2390                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 3);
2391                 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2392                 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
2393
2394                 perl_argv[perl_argc] = NULL;
2395         }
2396         else {
2397                 /* prepend the directory to @INC */
2398                 av_unshift (GvAVn (PL_incgv), 1);
2399                 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
2400         }
2401         return 0;
2402 } /* static int perl_config_includedir (oconfig_item_it *) */
2403
2404 /*
2405  * <Plugin> block
2406  */
2407 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2408 {
2409         int retvals = 0;
2410         int ret     = 0;
2411
2412         char *plugin;
2413         HV   *config;
2414
2415         dSP;
2416
2417         if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2418                 log_err ("LoadPlugin expects a single string argument.");
2419                 return 1;
2420         }
2421
2422         plugin = ci->values[0].value.string;
2423         config = newHV ();
2424
2425         if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2426                 hv_clear (config);
2427                 hv_undef (config);
2428
2429                 log_err ("Unable to convert configuration to a Perl hash value.");
2430                 config = (HV *)&PL_sv_undef;
2431         }
2432
2433         ENTER;
2434         SAVETMPS;
2435
2436         PUSHMARK (SP);
2437
2438         XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2439         XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2440
2441         PUTBACK;
2442
2443         retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2444
2445         SPAGAIN;
2446         if (0 < retvals) {
2447                 SV *tmp = POPs;
2448                 if (! SvTRUE (tmp))
2449                         ret = 1;
2450         }
2451         else
2452                 ret = 1;
2453
2454         PUTBACK;
2455         FREETMPS;
2456         LEAVE;
2457         return ret;
2458 } /* static int perl_config_plugin (oconfig_item_it *) */
2459
2460 static int perl_config (oconfig_item_t *ci)
2461 {
2462         int status = 0;
2463         int i = 0;
2464
2465         dTHXa (NULL);
2466
2467         for (i = 0; i < ci->children_num; ++i) {
2468                 oconfig_item_t *c = ci->children + i;
2469                 int current_status = 0;
2470
2471                 if (NULL != perl_threads)
2472                         aTHX = PERL_GET_CONTEXT;
2473
2474                 if (0 == strcasecmp (c->key, "LoadPlugin"))
2475                         current_status = perl_config_loadplugin (aTHX_ c);
2476                 else if (0 == strcasecmp (c->key, "BaseName"))
2477                         current_status = perl_config_basename (aTHX_ c);
2478                 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2479                         current_status = perl_config_enabledebugger (aTHX_ c);
2480                 else if (0 == strcasecmp (c->key, "IncludeDir"))
2481                         current_status = perl_config_includedir (aTHX_ c);
2482                 else if (0 == strcasecmp (c->key, "Plugin"))
2483                         current_status = perl_config_plugin (aTHX_ c);
2484                 else
2485                 {
2486                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
2487                         current_status = 0;
2488                 }
2489
2490                 /* fatal error - it's up to perl_config_* to clean up */
2491                 if (0 > current_status) {
2492                         log_err ("Configuration failed with a fatal error - "
2493                                         "plugin disabled!");
2494                         return current_status;
2495                 }
2496
2497                 status += current_status;
2498         }
2499         return status;
2500 } /* static int perl_config (oconfig_item_t *) */
2501
2502 void module_register (void)
2503 {
2504         perl_argc = 4;
2505         perl_argv = (char **)smalloc ((perl_argc + 1) * sizeof (char *));
2506
2507         /* default options for the Perl interpreter */
2508         perl_argv[0] = "";
2509         perl_argv[1] = "-MCollectd";
2510         perl_argv[2] = "-e";
2511         perl_argv[3] = "1";
2512         perl_argv[4] = NULL;
2513
2514         plugin_register_complex_config ("perl", perl_config);
2515         return;
2516 } /* void module_register (void) */
2517
2518 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
2519