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