perl plugin: Changed pluginname form to allow single perl plugin flush.
[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         log_debug ("Shutting down Perl interpreter %p...", aTHX);
1233
1234 #if COLLECT_DEBUG
1235         sv_report_used ();
1236
1237         --perl_threads->number_of_threads;
1238 #endif /* COLLECT_DEBUG */
1239
1240         perl_destruct (aTHX);
1241         perl_free (aTHX);
1242
1243         if (NULL == ithread->prev)
1244                 perl_threads->head = ithread->next;
1245         else
1246                 ithread->prev->next = ithread->next;
1247
1248         if (NULL == ithread->next)
1249                 perl_threads->tail = ithread->prev;
1250         else
1251                 ithread->next->prev = ithread->prev;
1252
1253         sfree (ithread);
1254         return;
1255 } /* static void c_ithread_destroy (c_ithread_t *) */
1256
1257 static void c_ithread_destructor (void *arg)
1258 {
1259         c_ithread_t *ithread = (c_ithread_t *)arg;
1260         c_ithread_t *t = NULL;
1261
1262         if (NULL == perl_threads)
1263                 return;
1264
1265         pthread_mutex_lock (&perl_threads->mutex);
1266
1267         for (t = perl_threads->head; NULL != t; t = t->next)
1268                 if (t == ithread)
1269                         break;
1270
1271         /* the ithread no longer exists */
1272         if (NULL == t)
1273         {
1274                 pthread_mutex_unlock (&perl_threads->mutex);
1275                 return;
1276         }
1277
1278         c_ithread_destroy (ithread);
1279
1280         pthread_mutex_unlock (&perl_threads->mutex);
1281         return;
1282 } /* static void c_ithread_destructor (void *) */
1283
1284 /* must be called with perl_threads->mutex locked */
1285 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1286 {
1287         c_ithread_t *t = NULL;
1288         dTHXa (NULL);
1289
1290         assert (NULL != perl_threads);
1291
1292         t = smalloc (sizeof (*t));
1293         memset (t, 0, sizeof (c_ithread_t));
1294
1295         t->interp = (NULL == base)
1296                 ? NULL
1297                 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1298
1299         aTHX = t->interp;
1300
1301         if ((NULL != base) && (NULL != PL_endav)) {
1302                 av_clear (PL_endav);
1303                 av_undef (PL_endav);
1304                 PL_endav = Nullav;
1305         }
1306
1307 #if COLLECT_DEBUG
1308         ++perl_threads->number_of_threads;
1309 #endif /* COLLECT_DEBUG */
1310
1311         t->next = NULL;
1312
1313         if (NULL == perl_threads->tail) {
1314                 perl_threads->head = t;
1315                 t->prev = NULL;
1316         }
1317         else {
1318                 perl_threads->tail->next = t;
1319                 t->prev = perl_threads->tail;
1320         }
1321
1322         t->pthread = pthread_self();
1323         t->running = 0;
1324         t->shutdown = 0;
1325         perl_threads->tail = t;
1326
1327         pthread_setspecific (perl_thr_key, (const void *)t);
1328         return t;
1329 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1330
1331 /*
1332  * Filter chains implementation.
1333  */
1334
1335 static int fc_call (pTHX_ int type, int cb_type, pfc_user_data_t *data, ...)
1336 {
1337         int retvals = 0;
1338
1339         va_list ap;
1340         int ret = 0;
1341
1342         notification_meta_t **meta  = NULL;
1343         AV                   *pmeta = NULL;
1344
1345         dSP;
1346
1347         if ((type < 0) || (type >= FC_TYPES))
1348                 return -1;
1349
1350         if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1351                 return -1;
1352
1353         va_start (ap, data);
1354
1355         ENTER;
1356         SAVETMPS;
1357
1358         PUSHMARK (SP);
1359
1360         XPUSHs (sv_2mortal (newSViv ((IV)type)));
1361         XPUSHs (sv_2mortal (newSVpv (data->name, 0)));
1362         XPUSHs (sv_2mortal (newSViv ((IV)cb_type)));
1363
1364         if (FC_CB_CREATE == cb_type) {
1365                 /*
1366                  * $_[0] = $ci;
1367                  * $_[1] = $user_data;
1368                  */
1369                 oconfig_item_t *ci;
1370                 HV *config = newHV ();
1371
1372                 ci = va_arg (ap, oconfig_item_t *);
1373
1374                 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
1375                         hv_clear (config);
1376                         hv_undef (config);
1377                         config = (HV *)&PL_sv_undef;
1378                         ret = -1;
1379                 }
1380
1381                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
1382         }
1383         else if (FC_CB_DESTROY == cb_type) {
1384                 /*
1385                  * $_[1] = $user_data;
1386                  */
1387
1388                 /* nothing to be done - the user data pointer
1389                  * is pushed onto the stack later */
1390         }
1391         else if (FC_CB_EXEC == cb_type) {
1392                 /*
1393                  * $_[0] = $ds;
1394                  * $_[1] = $vl;
1395                  * $_[2] = $meta;
1396                  * $_[3] = $user_data;
1397                  */
1398                 data_set_t   *ds;
1399                 value_list_t *vl;
1400
1401                 AV *pds = newAV ();
1402                 HV *pvl = newHV ();
1403
1404                 ds   = va_arg (ap, data_set_t *);
1405                 vl   = va_arg (ap, value_list_t *);
1406                 meta = va_arg (ap, notification_meta_t **);
1407
1408                 if (0 != data_set2av (aTHX_ ds, pds)) {
1409                         av_clear (pds);
1410                         av_undef (pds);
1411                         pds = (AV *)&PL_sv_undef;
1412                         ret = -1;
1413                 }
1414
1415                 if (0 != value_list2hv (aTHX_ vl, ds, pvl)) {
1416                         hv_clear (pvl);
1417                         hv_undef (pvl);
1418                         pvl = (HV *)&PL_sv_undef;
1419                         ret = -1;
1420                 }
1421
1422                 if (NULL != meta) {
1423                         pmeta = newAV ();
1424
1425                         if (0 != notification_meta2av (aTHX_ *meta, pmeta)) {
1426                                 av_clear (pmeta);
1427                                 av_undef (pmeta);
1428                                 pmeta = (AV *)&PL_sv_undef;
1429                                 ret = -1;
1430                         }
1431                 }
1432                 else {
1433                         pmeta = (AV *)&PL_sv_undef;
1434                 }
1435
1436                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1437                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1438                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pmeta)));
1439         }
1440
1441         XPUSHs (sv_2mortal (newRV_inc (data->user_data)));
1442
1443         PUTBACK;
1444
1445         retvals = call_pv_locked (aTHX_ "Collectd::fc_call");
1446
1447         if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1448                 assert (pmeta != NULL);
1449
1450                 plugin_notification_meta_free (*meta);
1451                 av2notification_meta (aTHX_ pmeta, meta);
1452         }
1453
1454         SPAGAIN;
1455         if (SvTRUE(ERRSV)) {
1456                 ERROR ("perl: Collectd::fc_call error: %s", SvPV_nolen(ERRSV));
1457                 ret = -1;
1458         }
1459         else if (0 < retvals) {
1460                 SV *tmp = POPs;
1461
1462                 /* the exec callbacks return a status, while
1463                  * the others return a boolean value */
1464                 if (FC_CB_EXEC == cb_type)
1465                         ret = SvIV (tmp);
1466                 else if (! SvTRUE (tmp))
1467                         ret = -1;
1468         }
1469
1470         PUTBACK;
1471         FREETMPS;
1472         LEAVE;
1473
1474         va_end (ap);
1475         return ret;
1476 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1477
1478 static int fc_create (int type, const oconfig_item_t *ci, void **user_data)
1479 {
1480         pfc_user_data_t *data;
1481
1482         int ret = 0;
1483
1484         dTHX;
1485
1486         if (NULL == perl_threads)
1487                 return 0;
1488
1489         if (NULL == aTHX) {
1490                 c_ithread_t *t = NULL;
1491
1492                 pthread_mutex_lock (&perl_threads->mutex);
1493                 t = c_ithread_create (perl_threads->head->interp);
1494                 pthread_mutex_unlock (&perl_threads->mutex);
1495
1496                 aTHX = t->interp;
1497         }
1498
1499         log_debug ("fc_create: c_ithread: interp = %p (active threads: %i)",
1500                         aTHX, perl_threads->number_of_threads);
1501
1502         if ((1 != ci->values_num)
1503                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1504                 log_warn ("A \"%s\" block expects a single string argument.",
1505                                 (FC_MATCH == type) ? "Match" : "Target");
1506                 return -1;
1507         }
1508
1509         data = smalloc (sizeof (*data));
1510         data->name      = sstrdup (ci->values[0].value.string);
1511         data->user_data = newSV (0);
1512
1513         ret = fc_call (aTHX_ type, FC_CB_CREATE, data, ci);
1514
1515         if (0 != ret)
1516                 PFC_USER_DATA_FREE (data);
1517         else
1518                 *user_data = data;
1519         return ret;
1520 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1521
1522 static int fc_destroy (int type, void **user_data)
1523 {
1524         pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1525
1526         int ret = 0;
1527
1528         dTHX;
1529
1530         if ((NULL == perl_threads) || (NULL == data))
1531                 return 0;
1532
1533         if (NULL == aTHX) {
1534                 c_ithread_t *t = NULL;
1535
1536                 pthread_mutex_lock (&perl_threads->mutex);
1537                 t = c_ithread_create (perl_threads->head->interp);
1538                 pthread_mutex_unlock (&perl_threads->mutex);
1539
1540                 aTHX = t->interp;
1541         }
1542
1543         log_debug ("fc_destroy: c_ithread: interp = %p (active threads: %i)",
1544                         aTHX, perl_threads->number_of_threads);
1545
1546         ret = fc_call (aTHX_ type, FC_CB_DESTROY, data);
1547
1548         PFC_USER_DATA_FREE (data);
1549         *user_data = NULL;
1550         return ret;
1551 } /* static int fc_destroy (int, void **) */
1552
1553 static int fc_exec (int type, const data_set_t *ds, const value_list_t *vl,
1554                 notification_meta_t **meta, void **user_data)
1555 {
1556         pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1557
1558         dTHX;
1559
1560         if (NULL == perl_threads)
1561                 return 0;
1562
1563         assert (NULL != data);
1564
1565         if (NULL == aTHX) {
1566                 c_ithread_t *t = NULL;
1567
1568                 pthread_mutex_lock (&perl_threads->mutex);
1569                 t = c_ithread_create (perl_threads->head->interp);
1570                 pthread_mutex_unlock (&perl_threads->mutex);
1571
1572                 aTHX = t->interp;
1573         }
1574
1575         log_debug ("fc_exec: c_ithread: interp = %p (active threads: %i)",
1576                         aTHX, perl_threads->number_of_threads);
1577
1578         return fc_call (aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1579 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1580                 notification_meta_t **, void **) */
1581
1582 static int pmatch_create (const oconfig_item_t *ci, void **user_data)
1583 {
1584         return fc_create (FC_MATCH, ci, user_data);
1585 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1586
1587 static int pmatch_destroy (void **user_data)
1588 {
1589         return fc_destroy (FC_MATCH, user_data);
1590 } /* static int pmatch_destroy (void **) */
1591
1592 static int pmatch_match (const data_set_t *ds, const value_list_t *vl,
1593                 notification_meta_t **meta, void **user_data)
1594 {
1595         return fc_exec (FC_MATCH, ds, vl, meta, user_data);
1596 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1597                 notification_meta_t **, void **) */
1598
1599 static match_proc_t pmatch = {
1600         pmatch_create, pmatch_destroy, pmatch_match
1601 };
1602
1603 static int ptarget_create (const oconfig_item_t *ci, void **user_data)
1604 {
1605         return fc_create (FC_TARGET, ci, user_data);
1606 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1607
1608 static int ptarget_destroy (void **user_data)
1609 {
1610         return fc_destroy (FC_TARGET, user_data);
1611 } /* static int ptarget_destroy (void **) */
1612
1613 static int ptarget_invoke (const data_set_t *ds, value_list_t *vl,
1614                 notification_meta_t **meta, void **user_data)
1615 {
1616         return fc_exec (FC_TARGET, ds, vl, meta, user_data);
1617 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1618                 notification_meta_t **, void **) */
1619
1620 static target_proc_t ptarget = {
1621         ptarget_create, ptarget_destroy, ptarget_invoke
1622 };
1623
1624 /*
1625  * Exported Perl API.
1626  */
1627
1628 static void _plugin_register_generic_userdata (pTHX, int type, const char *desc)
1629 {
1630         int ret   = 0;
1631         user_data_t userdata;
1632         char *pluginname;
1633
1634         dXSARGS;
1635
1636         if (2 != items) {
1637                 log_err ("Usage: Collectd::plugin_register_%s(pluginname, subname)",
1638                                         desc);
1639                 XSRETURN_EMPTY;
1640         }
1641
1642         if (! SvOK (ST (0))) {
1643                 log_err ("Collectd::plugin_register_%s(pluginname, subname): "
1644                          "Invalid pluginname", desc);
1645                 XSRETURN_EMPTY;
1646         }
1647         if (! SvOK (ST (1))) {
1648                 log_err ("Collectd::plugin_register_%s(pluginname, subname): "
1649                          "Invalid subname", desc);
1650                 XSRETURN_EMPTY;
1651         }
1652
1653         /* Use pluginname as-is to allow flush a single perl plugin */
1654         pluginname = SvPV_nolen (ST (0));
1655
1656         log_debug ("Collectd::plugin_register_%s: "
1657                         "plugin = \"%s\", sub = \"%s\"",
1658                         desc, pluginname, SvPV_nolen (ST (1)));
1659
1660         memset(&userdata, 0, sizeof(userdata));
1661         userdata.data = strdup(SvPV_nolen (ST (1)));
1662         userdata.free_func = free;
1663
1664         if (PLUGIN_READ == type) {
1665                 ret = plugin_register_complex_read(
1666                         "perl",                /* group */
1667                         pluginname,
1668                         perl_read,
1669                         plugin_get_interval(), /* Default interval */
1670                         &userdata);
1671         }
1672         else if (PLUGIN_WRITE == type) {
1673                 ret = plugin_register_write(pluginname, perl_write, &userdata);
1674         }
1675         else if (PLUGIN_LOG == type) {
1676                 ret = plugin_register_log(pluginname, perl_log, &userdata);
1677         }
1678         else if (PLUGIN_NOTIF == type) {
1679                 ret = plugin_register_notification(pluginname, perl_notify, &userdata);
1680         }
1681         else if (PLUGIN_FLUSH == type) {
1682                 ret = plugin_register_flush(pluginname, perl_flush, &userdata);
1683         }
1684         else {
1685                 ret = -1;
1686         }
1687
1688         if (0 == ret)
1689                 XSRETURN_YES;
1690         else {
1691                 free (userdata.data);
1692                 XSRETURN_EMPTY;
1693         }
1694 } /* static void _plugin_register_generic_userdata ( ... ) */
1695
1696 /*
1697  * Collectd::plugin_register_TYPE (pluginname, subname).
1698  *
1699  * pluginname:
1700  *   name of the perl plugin
1701  *
1702  * subname:
1703  *   name of the plugin's subroutine that does the work
1704  */
1705
1706 static XS (Collectd_plugin_register_read) {
1707         return _plugin_register_generic_userdata(aTHX, PLUGIN_READ, "read");
1708 }
1709
1710 static XS (Collectd_plugin_register_write) {
1711         return _plugin_register_generic_userdata(aTHX, PLUGIN_WRITE, "write");
1712 }
1713
1714 static XS (Collectd_plugin_register_log) {
1715         return _plugin_register_generic_userdata(aTHX, PLUGIN_LOG, "log");
1716 }
1717
1718 static XS (Collectd_plugin_register_notification) {
1719         return _plugin_register_generic_userdata(aTHX, PLUGIN_NOTIF, "notification");
1720 }
1721
1722 static XS (Collectd_plugin_register_flush) {
1723         return _plugin_register_generic_userdata(aTHX, PLUGIN_FLUSH, "flush");
1724 }
1725
1726 typedef int perl_unregister_function_t(const char *name);
1727
1728 static void _plugin_unregister_generic (pTHX,
1729                                 perl_unregister_function_t *unreg, const char *desc)
1730 {
1731         char cb_name[DATA_MAX_NAME_LEN];
1732
1733         dXSARGS;
1734
1735         if (1 != items) {
1736                 log_err ("Usage: Collectd::plugin_unregister_%s(pluginname)", desc);
1737                 XSRETURN_EMPTY;
1738         }
1739
1740         if (! SvOK (ST (0))) {
1741                 log_err ("Collectd::plugin_unregister_%s(pluginname): "
1742                          "Invalid pluginname", desc);
1743                 XSRETURN_EMPTY;
1744         }
1745
1746         log_debug ("Collectd::plugin_unregister_%s: plugin = \"%s\"",
1747                         desc, SvPV_nolen (ST (0)));
1748
1749         ssnprintf (cb_name, sizeof (cb_name), "perl/%s", SvPV_nolen (ST (0)));
1750
1751         unreg(cb_name);
1752
1753         XSRETURN_EMPTY;
1754
1755         return;
1756 } /* static void _plugin_unregister_generic ( ... ) */
1757
1758 /*
1759  * Collectd::plugin_unregister_TYPE (pluginname).
1760  *
1761  * TYPE:
1762  *   type of callback to be unregistered: read, write, log, notification, flush
1763  *
1764  * pluginname:
1765  *   name of the perl plugin
1766  */
1767
1768 static XS (Collectd_plugin_unregister_read) {
1769         return _plugin_unregister_generic(aTHX,
1770                                 plugin_unregister_read, "read");
1771 }
1772
1773 static XS (Collectd_plugin_unregister_write) {
1774         return _plugin_unregister_generic(aTHX,
1775                                 plugin_unregister_write, "write");
1776 }
1777
1778 static XS (Collectd_plugin_unregister_log) {
1779         return _plugin_unregister_generic(aTHX,
1780                                 plugin_unregister_log, "log");
1781 }
1782
1783 static XS (Collectd_plugin_unregister_notification) {
1784         return _plugin_unregister_generic(aTHX,
1785                                 plugin_unregister_notification, "notification");
1786 }
1787
1788 static XS (Collectd_plugin_unregister_flush) {
1789         return _plugin_unregister_generic(aTHX,
1790                                 plugin_unregister_flush, "flush");
1791 }
1792
1793 /*
1794  * Collectd::plugin_register_data_set (type, dataset).
1795  *
1796  * type:
1797  *   type of the dataset
1798  *
1799  * dataset:
1800  *   dataset to be registered
1801  */
1802 static XS (Collectd_plugin_register_ds)
1803 {
1804         SV  *data = NULL;
1805         int ret   = 0;
1806
1807         dXSARGS;
1808
1809         log_warn ("Using plugin_register() to register new data-sets is "
1810                         "deprecated - add new entries to a custom types.db instead.");
1811
1812         if (2 != items) {
1813                 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1814                 XSRETURN_EMPTY;
1815         }
1816
1817         log_debug ("Collectd::plugin_register_data_set: "
1818                         "type = \"%s\", dataset = \"%s\"",
1819                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1820
1821         data = ST (1);
1822
1823         if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1824                 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1825                                 (AV *)SvRV (data));
1826         }
1827         else {
1828                 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1829                 XSRETURN_EMPTY;
1830         }
1831
1832         if (0 == ret)
1833                 XSRETURN_YES;
1834         else
1835                 XSRETURN_EMPTY;
1836 } /* static XS (Collectd_plugin_register_ds) */
1837
1838 /*
1839  * Collectd::plugin_unregister_data_set (type).
1840  *
1841  * type:
1842  *   type of the dataset
1843  */
1844 static XS (Collectd_plugin_unregister_ds)
1845 {
1846         dXSARGS;
1847
1848         if (1 != items) {
1849                 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1850                 XSRETURN_EMPTY;
1851         }
1852
1853         log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1854                         SvPV_nolen (ST (0)));
1855
1856         if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1857                 XSRETURN_YES;
1858         else
1859                 XSRETURN_EMPTY;
1860 } /* static XS (Collectd_plugin_register_ds) */
1861
1862 /*
1863  * Collectd::plugin_dispatch_values (name, values).
1864  *
1865  * name:
1866  *   name of the plugin
1867  *
1868  * values:
1869  *   value list to submit
1870  */
1871 static XS (Collectd_plugin_dispatch_values)
1872 {
1873         SV *values     = NULL;
1874
1875         int ret = 0;
1876
1877         dXSARGS;
1878
1879         if (1 != items) {
1880                 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1881                 XSRETURN_EMPTY;
1882         }
1883
1884         log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1885                         SvPV_nolen (ST (/* stack index = */ 0)));
1886
1887         values = ST (/* stack index = */ 0);
1888
1889         if (NULL == values)
1890                 XSRETURN_EMPTY;
1891
1892         /* Make sure the argument is a hash reference. */
1893         if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1894                 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1895                 XSRETURN_EMPTY;
1896         }
1897
1898         ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1899
1900         if (0 == ret)
1901                 XSRETURN_YES;
1902         else
1903                 XSRETURN_EMPTY;
1904 } /* static XS (Collectd_plugin_dispatch_values) */
1905
1906 /*
1907  * Collectd::plugin_get_interval ().
1908  */
1909 static XS (Collectd_plugin_get_interval)
1910 {
1911         dXSARGS;
1912
1913         /* make sure we don't get any unused variable warnings for 'items';
1914          * don't abort, though */
1915         if (items)
1916                 log_err ("Usage: Collectd::plugin_get_interval()");
1917
1918         XSRETURN_NV ((NV) CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
1919 } /* static XS (Collectd_plugin_get_interval) */
1920
1921 /* Collectd::plugin_write (plugin, ds, vl).
1922  *
1923  * plugin:
1924  *   name of the plugin to call, may be 'undef'
1925  *
1926  * ds:
1927  *   data-set that describes the submitted values, may be 'undef'
1928  *
1929  * vl:
1930  *   value-list to be written
1931  */
1932 static XS (Collectd__plugin_write)
1933 {
1934         char *plugin;
1935         SV   *ds, *vl;
1936         AV   *ds_array;
1937
1938         int ret;
1939
1940         dXSARGS;
1941
1942         if (3 != items) {
1943                 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1944                 XSRETURN_EMPTY;
1945         }
1946
1947         log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1948                         SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1949                         SvPV_nolen (ST (2)));
1950
1951         if (! SvOK (ST (0)))
1952                 plugin = NULL;
1953         else
1954                 plugin = SvPV_nolen (ST (0));
1955
1956         ds = ST (1);
1957         if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1958                 ds_array = (AV *)SvRV (ds);
1959         else if (! SvOK (ds))
1960                 ds_array = NULL;
1961         else {
1962                 log_err ("Collectd::plugin_write: Invalid data-set.");
1963                 XSRETURN_EMPTY;
1964         }
1965
1966         vl = ST (2);
1967         if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1968                 log_err ("Collectd::plugin_write: Invalid value-list.");
1969                 XSRETURN_EMPTY;
1970         }
1971
1972         ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1973
1974         if (0 == ret)
1975                 XSRETURN_YES;
1976         else
1977                 XSRETURN_EMPTY;
1978 } /* static XS (Collectd__plugin_write) */
1979
1980 /*
1981  * Collectd::_plugin_flush (plugin, timeout, identifier).
1982  *
1983  * plugin:
1984  *   name of the plugin to flush
1985  *
1986  * timeout:
1987  *   timeout to use when flushing the data
1988  *
1989  * identifier:
1990  *   data-set identifier to flush
1991  */
1992 static XS (Collectd__plugin_flush)
1993 {
1994         char *plugin  = NULL;
1995         int   timeout = -1;
1996         char *id      = NULL;
1997
1998         dXSARGS;
1999
2000         if (3 != items) {
2001                 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
2002                 XSRETURN_EMPTY;
2003         }
2004
2005         if (SvOK (ST (0)))
2006                 plugin = SvPV_nolen (ST (0));
2007
2008         if (SvOK (ST (1)))
2009                 timeout = (int)SvIV (ST (1));
2010
2011         if (SvOK (ST (2)))
2012                 id = SvPV_nolen (ST (2));
2013
2014         log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
2015                         "id = \"%s\"", plugin, timeout, id);
2016
2017         if (0 == plugin_flush (plugin, timeout, id))
2018                 XSRETURN_YES;
2019         else
2020                 XSRETURN_EMPTY;
2021 } /* static XS (Collectd__plugin_flush) */
2022
2023 /*
2024  * Collectd::plugin_dispatch_notification (notif).
2025  *
2026  * notif:
2027  *   notification to dispatch
2028  */
2029 static XS (Collectd_plugin_dispatch_notification)
2030 {
2031         SV *notif = NULL;
2032
2033         int ret = 0;
2034
2035         dXSARGS;
2036
2037         if (1 != items) {
2038                 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
2039                 XSRETURN_EMPTY;
2040         }
2041
2042         log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
2043                         SvPV_nolen (ST (0)));
2044
2045         notif = ST (0);
2046
2047         if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
2048                 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
2049                 XSRETURN_EMPTY;
2050         }
2051
2052         ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
2053
2054         if (0 == ret)
2055                 XSRETURN_YES;
2056         else
2057                 XSRETURN_EMPTY;
2058 } /* static XS (Collectd_plugin_dispatch_notification) */
2059
2060 /*
2061  * Collectd::plugin_log (level, message).
2062  *
2063  * level:
2064  *   log level (LOG_DEBUG, ... LOG_ERR)
2065  *
2066  * message:
2067  *   log message
2068  */
2069 static XS (Collectd_plugin_log)
2070 {
2071         dXSARGS;
2072
2073         if (2 != items) {
2074                 log_err ("Usage: Collectd::plugin_log(level, message)");
2075                 XSRETURN_EMPTY;
2076         }
2077
2078         plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
2079         XSRETURN_YES;
2080 } /* static XS (Collectd_plugin_log) */
2081
2082 /*
2083  * Collectd::_fc_register (type, name)
2084  *
2085  * type:
2086  *   match | target
2087  *
2088  * name:
2089  *   name of the match
2090  */
2091 static XS (Collectd__fc_register)
2092 {
2093         int   type;
2094         char *name;
2095
2096         int ret = 0;
2097
2098         dXSARGS;
2099
2100         if (2 != items) {
2101                 log_err ("Usage: Collectd::_fc_register(type, name)");
2102                 XSRETURN_EMPTY;
2103         }
2104
2105         type = SvIV (ST (0));
2106         name = SvPV_nolen (ST (1));
2107
2108         if (FC_MATCH == type)
2109                 ret = fc_register_match (name, pmatch);
2110         else if (FC_TARGET == type)
2111                 ret = fc_register_target (name, ptarget);
2112
2113         if (0 == ret)
2114                 XSRETURN_YES;
2115         else
2116                 XSRETURN_EMPTY;
2117 } /* static XS (Collectd_fc_register) */
2118
2119 /*
2120  * Collectd::call_by_name (...).
2121  *
2122  * Call a Perl sub identified by its name passed through $Collectd::cb_name.
2123  */
2124 static XS (Collectd_call_by_name)
2125 {
2126         SV   *tmp  = NULL;
2127         char *name = NULL;
2128
2129         if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
2130                 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
2131                 CLEAR_STACK_FRAME;
2132                 return;
2133         }
2134
2135         name = SvPV_nolen (tmp);
2136
2137         if (NULL == get_cv (name, 0)) {
2138                 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
2139                 CLEAR_STACK_FRAME;
2140                 return;
2141         }
2142
2143         /* simply pass on the subroutine call without touching the stack,
2144          * thus leaving any arguments and return values in place */
2145         call_pv (name, 0);
2146 } /* static XS (Collectd_call_by_name) */
2147
2148 /*
2149  * Interface to collectd.
2150  */
2151
2152 static int perl_init (void)
2153 {
2154         int status;
2155         dTHX;
2156
2157         if (NULL == perl_threads)
2158                 return 0;
2159
2160         if (NULL == aTHX) {
2161                 c_ithread_t *t = NULL;
2162
2163                 pthread_mutex_lock (&perl_threads->mutex);
2164                 t = c_ithread_create (perl_threads->head->interp);
2165                 pthread_mutex_unlock (&perl_threads->mutex);
2166
2167                 aTHX = t->interp;
2168         }
2169
2170         log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
2171                         aTHX, perl_threads->number_of_threads);
2172
2173         /* Lock the base thread to avoid race conditions with c_ithread_create().
2174          * See https://github.com/collectd/collectd/issues/9 and
2175          *     https://github.com/collectd/collectd/issues/1706 for details.
2176         */
2177         assert (aTHX == perl_threads->head->interp);
2178         pthread_mutex_lock (&perl_threads->mutex);
2179
2180         status = pplugin_call (aTHX_ PLUGIN_INIT);
2181
2182         pthread_mutex_unlock (&perl_threads->mutex);
2183
2184         return status;
2185 } /* static int perl_init (void) */
2186
2187 static int perl_read (user_data_t *user_data)
2188 {
2189         dTHX;
2190
2191         if (NULL == perl_threads)
2192                 return 0;
2193
2194         if (NULL == aTHX) {
2195                 c_ithread_t *t = NULL;
2196
2197                 pthread_mutex_lock (&perl_threads->mutex);
2198                 t = c_ithread_create (perl_threads->head->interp);
2199                 pthread_mutex_unlock (&perl_threads->mutex);
2200
2201                 aTHX = t->interp;
2202         }
2203
2204         /* Assert that we're not running as the base thread. Otherwise, we might
2205          * run into concurrency issues with c_ithread_create(). See
2206          * https://github.com/collectd/collectd/issues/9 for details. */
2207         assert (aTHX != perl_threads->head->interp);
2208
2209         log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
2210                         aTHX, perl_threads->number_of_threads);
2211
2212         return pplugin_call (aTHX_ PLUGIN_READ, user_data->data);
2213 } /* static int perl_read (user_data_t *user_data) */
2214
2215 static int perl_write (const data_set_t *ds, const value_list_t *vl,
2216                 user_data_t *user_data)
2217 {
2218         int status;
2219         dTHX;
2220
2221         if (NULL == perl_threads)
2222                 return 0;
2223
2224         if (NULL == aTHX) {
2225                 c_ithread_t *t = NULL;
2226
2227                 pthread_mutex_lock (&perl_threads->mutex);
2228                 t = c_ithread_create (perl_threads->head->interp);
2229                 pthread_mutex_unlock (&perl_threads->mutex);
2230
2231                 aTHX = t->interp;
2232         }
2233
2234         /* Lock the base thread if this is not called from one of the read threads
2235          * to avoid race conditions with c_ithread_create(). See
2236          * https://github.com/collectd/collectd/issues/9 for details. */
2237         if (aTHX == perl_threads->head->interp)
2238                 pthread_mutex_lock (&perl_threads->mutex);
2239
2240         log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
2241                         aTHX, perl_threads->number_of_threads);
2242         status = pplugin_call (aTHX_ PLUGIN_WRITE, user_data->data, ds, vl);
2243
2244         if (aTHX == perl_threads->head->interp)
2245                 pthread_mutex_unlock (&perl_threads->mutex);
2246
2247         return status;
2248 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2249
2250 static void perl_log (int level, const char *msg,
2251                 user_data_t *user_data)
2252 {
2253         dTHX;
2254
2255         if (NULL == perl_threads)
2256                 return;
2257
2258         if (NULL == aTHX) {
2259                 c_ithread_t *t = NULL;
2260
2261                 pthread_mutex_lock (&perl_threads->mutex);
2262                 t = c_ithread_create (perl_threads->head->interp);
2263                 pthread_mutex_unlock (&perl_threads->mutex);
2264
2265                 aTHX = t->interp;
2266         }
2267
2268         /* Lock the base thread if this is not called from one of the read threads
2269          * to avoid race conditions with c_ithread_create(). See
2270          * https://github.com/collectd/collectd/issues/9 for details.
2271         */
2272
2273         if (aTHX == perl_threads->head->interp)
2274                 pthread_mutex_lock (&perl_threads->mutex);
2275
2276         pplugin_call (aTHX_ PLUGIN_LOG, user_data->data, level, msg);
2277
2278         if (aTHX == perl_threads->head->interp)
2279                 pthread_mutex_unlock (&perl_threads->mutex);
2280
2281         return;
2282 } /* static void perl_log (int, const char *) */
2283
2284 static int perl_notify (const notification_t *notif, user_data_t *user_data)
2285 {
2286         dTHX;
2287
2288         if (NULL == perl_threads)
2289                 return 0;
2290
2291         if (NULL == aTHX) {
2292                 c_ithread_t *t = NULL;
2293
2294                 pthread_mutex_lock (&perl_threads->mutex);
2295                 t = c_ithread_create (perl_threads->head->interp);
2296                 pthread_mutex_unlock (&perl_threads->mutex);
2297
2298                 aTHX = t->interp;
2299         }
2300         return pplugin_call (aTHX_ PLUGIN_NOTIF, user_data->data, notif);
2301 } /* static int perl_notify (const notification_t *) */
2302
2303 static int perl_flush (cdtime_t timeout, const char *identifier,
2304                 user_data_t *user_data)
2305 {
2306         dTHX;
2307
2308         if (NULL == perl_threads)
2309                 return 0;
2310
2311         if (NULL == aTHX) {
2312                 c_ithread_t *t = NULL;
2313
2314                 pthread_mutex_lock (&perl_threads->mutex);
2315                 t = c_ithread_create (perl_threads->head->interp);
2316                 pthread_mutex_unlock (&perl_threads->mutex);
2317
2318                 aTHX = t->interp;
2319         }
2320         return pplugin_call (aTHX_ PLUGIN_FLUSH, user_data->data, timeout, identifier);
2321 } /* static int perl_flush (const int) */
2322
2323 static int perl_shutdown (void)
2324 {
2325         c_ithread_t *t;
2326         int ret;
2327
2328         dTHX;
2329
2330         plugin_unregister_complex_config ("perl");
2331         plugin_unregister_read_group ("perl");
2332
2333         if (NULL == perl_threads)
2334                 return 0;
2335
2336         if (NULL == aTHX) {
2337                 pthread_mutex_lock (&perl_threads->mutex);
2338                 t = c_ithread_create (perl_threads->head->interp);
2339                 pthread_mutex_unlock (&perl_threads->mutex);
2340
2341                 aTHX = t->interp;
2342         }
2343
2344         log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2345                         aTHX, perl_threads->number_of_threads);
2346
2347         plugin_unregister_init ("perl");
2348
2349         ret = pplugin_call (aTHX_ PLUGIN_SHUTDOWN);
2350
2351         pthread_mutex_lock (&perl_threads->mutex);
2352         t = perl_threads->tail;
2353
2354         while (NULL != t) {
2355                 struct timespec ts_wait;
2356                 c_ithread_t *thr = t;
2357
2358                 /* the pointer has to be advanced before destroying
2359                  * the thread as this will free the memory */
2360                 t = t->prev;
2361
2362                 thr->shutdown = 1;
2363                 if (thr->running) {
2364                         /* Give some time to thread to exit from Perl interpreter */
2365                         WARNING ("perl shutdown: Thread is running inside Perl. Waiting.");
2366                         ts_wait.tv_sec = 0;
2367                         ts_wait.tv_nsec = 500000;
2368                         nanosleep (&ts_wait, NULL);
2369                 }
2370                 if (thr->running) {
2371                         pthread_kill (thr->pthread, SIGTERM);
2372                         ERROR ("perl shutdown: Thread hangs inside Perl. Thread killed.");
2373                 }
2374                 /* Mark as running to avoid deadlock:
2375                    c_ithread_destroy -> log_debug -> perl_log()
2376                 */
2377                 thr->running = 1; 
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