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