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