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