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