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