Merge pull request #1821 from rubenk/memset
[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 = { 0 };
987
988         int ret;
989
990         if (NULL == notif)
991                 return -1;
992
993         if (0 != hv2notification (aTHX_ notif, &n))
994                 return -1;
995
996         ret = plugin_dispatch_notification (&n);
997         plugin_notification_meta_free (n.meta);
998         return ret;
999 } /* static int pplugin_dispatch_notification (HV *) */
1000
1001 /*
1002  * Call perl sub with thread locking flags handled.
1003  */
1004 static int call_pv_locked (pTHX_ const char* sub_name)
1005 {
1006         _Bool old_running;
1007         int ret;
1008
1009         c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
1010         if (t == NULL) /* thread destroyed */
1011                 return 0;
1012
1013         old_running = t->running;
1014         t->running = 1;
1015
1016         if (t->shutdown) {
1017                 t->running = old_running;
1018                 return 0;
1019         }
1020
1021         ret = call_pv (sub_name, G_SCALAR);
1022
1023         t->running = old_running;
1024         return ret;
1025 } /* static int call_pv_locked (pTHX, *sub_name) */
1026
1027 /*
1028  * Call all working functions of the given type.
1029  */
1030 static int pplugin_call_all (pTHX_ int type, ...)
1031 {
1032         int retvals = 0;
1033
1034         va_list ap;
1035         int ret = 0;
1036
1037         dSP;
1038
1039         if ((type < 0) || (type >= PLUGIN_TYPES))
1040                 return -1;
1041
1042         va_start (ap, type);
1043
1044         ENTER;
1045         SAVETMPS;
1046
1047         PUSHMARK (SP);
1048
1049         XPUSHs (sv_2mortal (newSViv ((IV)type)));
1050
1051         if (PLUGIN_WRITE == type) {
1052                 /*
1053                  * $_[0] = $plugin_type;
1054                  *
1055                  * $_[1] =
1056                  * [
1057                  *   {
1058                  *     name => $ds_name,
1059                  *     type => $ds_type,
1060                  *     min  => $ds_min,
1061                  *     max  => $ds_max
1062                  *   },
1063                  *   ...
1064                  * ];
1065                  *
1066                  * $_[2] =
1067                  * {
1068                  *   values => [ $v1, ... ],
1069                  *   time   => $time,
1070                  *   host   => $hostname,
1071                  *   plugin => $plugin,
1072                  *   type   => $type,
1073                  *   plugin_instance => $instance,
1074                  *   type_instance   => $type_instance
1075                  * };
1076                  */
1077                 data_set_t   *ds;
1078                 value_list_t *vl;
1079
1080                 AV *pds = newAV ();
1081                 HV *pvl = newHV ();
1082
1083                 ds = va_arg (ap, data_set_t *);
1084                 vl = va_arg (ap, value_list_t *);
1085
1086                 if (-1 == data_set2av (aTHX_ ds, pds)) {
1087                         av_clear (pds);
1088                         av_undef (pds);
1089                         pds = (AV *)&PL_sv_undef;
1090                         ret = -1;
1091                 }
1092
1093                 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
1094                         hv_clear (pvl);
1095                         hv_undef (pvl);
1096                         pvl = (HV *)&PL_sv_undef;
1097                         ret = -1;
1098                 }
1099
1100                 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
1101                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1102                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1103         }
1104         else if (PLUGIN_LOG == type) {
1105                 /*
1106                  * $_[0] = $level;
1107                  *
1108                  * $_[1] = $message;
1109                  */
1110                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1111                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1112         }
1113         else if (PLUGIN_NOTIF == type) {
1114                 /*
1115                  * $_[0] =
1116                  * {
1117                  *   severity => $severity,
1118                  *   time     => $time,
1119                  *   message  => $msg,
1120                  *   host     => $host,
1121                  *   plugin   => $plugin,
1122                  *   type     => $type,
1123                  *   plugin_instance => $instance,
1124                  *   type_instance   => $type_instance
1125                  * };
1126                  */
1127                 notification_t *n;
1128                 HV *notif = newHV ();
1129
1130                 n = va_arg (ap, notification_t *);
1131
1132                 if (-1 == notification2hv (aTHX_ n, notif)) {
1133                         hv_clear (notif);
1134                         hv_undef (notif);
1135                         notif = (HV *)&PL_sv_undef;
1136                         ret = -1;
1137                 }
1138
1139                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
1140         }
1141         else if (PLUGIN_FLUSH == type) {
1142                 cdtime_t timeout;
1143
1144                 /*
1145                  * $_[0] = $timeout;
1146                  * $_[1] = $identifier;
1147                  */
1148                 timeout = va_arg (ap, cdtime_t);
1149
1150                 XPUSHs (sv_2mortal (newSVnv (CDTIME_T_TO_DOUBLE (timeout))));
1151                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1152         }
1153
1154         PUTBACK;
1155
1156         retvals = call_pv_locked (aTHX_ "Collectd::plugin_call_all");
1157
1158         SPAGAIN;
1159         if (0 < retvals) {
1160                 SV *tmp = POPs;
1161                 if (! SvTRUE (tmp))
1162                         ret = -1;
1163         }
1164
1165         PUTBACK;
1166         FREETMPS;
1167         LEAVE;
1168
1169         va_end (ap);
1170         return ret;
1171 } /* static int pplugin_call_all (int, ...) */
1172
1173 /*
1174  * collectd's Perl interpreter based thread implementation.
1175  *
1176  * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1177  */
1178
1179 /* must be called with perl_threads->mutex locked */
1180 static void c_ithread_destroy (c_ithread_t *ithread)
1181 {
1182         dTHXa (ithread->interp);
1183
1184         assert (NULL != perl_threads);
1185
1186         PERL_SET_CONTEXT (aTHX);
1187         log_debug ("Shutting down Perl interpreter %p...", aTHX);
1188
1189 #if COLLECT_DEBUG
1190         sv_report_used ();
1191
1192         --perl_threads->number_of_threads;
1193 #endif /* COLLECT_DEBUG */
1194
1195         perl_destruct (aTHX);
1196         perl_free (aTHX);
1197
1198         if (NULL == ithread->prev)
1199                 perl_threads->head = ithread->next;
1200         else
1201                 ithread->prev->next = ithread->next;
1202
1203         if (NULL == ithread->next)
1204                 perl_threads->tail = ithread->prev;
1205         else
1206                 ithread->next->prev = ithread->prev;
1207
1208         sfree (ithread);
1209         return;
1210 } /* static void c_ithread_destroy (c_ithread_t *) */
1211
1212 static void c_ithread_destructor (void *arg)
1213 {
1214         c_ithread_t *ithread = (c_ithread_t *)arg;
1215         c_ithread_t *t = NULL;
1216
1217         if (NULL == perl_threads)
1218                 return;
1219
1220         pthread_mutex_lock (&perl_threads->mutex);
1221
1222         for (t = perl_threads->head; NULL != t; t = t->next)
1223                 if (t == ithread)
1224                         break;
1225
1226         /* the ithread no longer exists */
1227         if (NULL == t)
1228         {
1229                 pthread_mutex_unlock (&perl_threads->mutex);
1230                 return;
1231         }
1232
1233         c_ithread_destroy (ithread);
1234
1235         pthread_mutex_unlock (&perl_threads->mutex);
1236         return;
1237 } /* static void c_ithread_destructor (void *) */
1238
1239 /* must be called with perl_threads->mutex locked */
1240 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1241 {
1242         c_ithread_t *t = NULL;
1243         dTHXa (NULL);
1244
1245         assert (NULL != perl_threads);
1246
1247         t = smalloc (sizeof (*t));
1248         memset (t, 0, sizeof (c_ithread_t));
1249
1250         t->interp = (NULL == base)
1251                 ? NULL
1252                 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1253
1254         aTHX = t->interp;
1255
1256         if ((NULL != base) && (NULL != PL_endav)) {
1257                 av_clear (PL_endav);
1258                 av_undef (PL_endav);
1259                 PL_endav = Nullav;
1260         }
1261
1262 #if COLLECT_DEBUG
1263         ++perl_threads->number_of_threads;
1264 #endif /* COLLECT_DEBUG */
1265
1266         t->next = NULL;
1267
1268         if (NULL == perl_threads->tail) {
1269                 perl_threads->head = t;
1270                 t->prev = NULL;
1271         }
1272         else {
1273                 perl_threads->tail->next = t;
1274                 t->prev = perl_threads->tail;
1275         }
1276
1277         t->pthread = pthread_self();
1278         t->running = 0;
1279         t->shutdown = 0;
1280         perl_threads->tail = t;
1281
1282         pthread_setspecific (perl_thr_key, (const void *)t);
1283         return t;
1284 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1285
1286 /*
1287  * Filter chains implementation.
1288  */
1289
1290 static int fc_call (pTHX_ int type, int cb_type, pfc_user_data_t *data, ...)
1291 {
1292         int retvals = 0;
1293
1294         va_list ap;
1295         int ret = 0;
1296
1297         notification_meta_t **meta  = NULL;
1298         AV                   *pmeta = NULL;
1299
1300         dSP;
1301
1302         if ((type < 0) || (type >= FC_TYPES))
1303                 return -1;
1304
1305         if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1306                 return -1;
1307
1308         va_start (ap, data);
1309
1310         ENTER;
1311         SAVETMPS;
1312
1313         PUSHMARK (SP);
1314
1315         XPUSHs (sv_2mortal (newSViv ((IV)type)));
1316         XPUSHs (sv_2mortal (newSVpv (data->name, 0)));
1317         XPUSHs (sv_2mortal (newSViv ((IV)cb_type)));
1318
1319         if (FC_CB_CREATE == cb_type) {
1320                 /*
1321                  * $_[0] = $ci;
1322                  * $_[1] = $user_data;
1323                  */
1324                 oconfig_item_t *ci;
1325                 HV *config = newHV ();
1326
1327                 ci = va_arg (ap, oconfig_item_t *);
1328
1329                 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
1330                         hv_clear (config);
1331                         hv_undef (config);
1332                         config = (HV *)&PL_sv_undef;
1333                         ret = -1;
1334                 }
1335
1336                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
1337         }
1338         else if (FC_CB_DESTROY == cb_type) {
1339                 /*
1340                  * $_[1] = $user_data;
1341                  */
1342
1343                 /* nothing to be done - the user data pointer
1344                  * is pushed onto the stack later */
1345         }
1346         else if (FC_CB_EXEC == cb_type) {
1347                 /*
1348                  * $_[0] = $ds;
1349                  * $_[1] = $vl;
1350                  * $_[2] = $meta;
1351                  * $_[3] = $user_data;
1352                  */
1353                 data_set_t   *ds;
1354                 value_list_t *vl;
1355
1356                 AV *pds = newAV ();
1357                 HV *pvl = newHV ();
1358
1359                 ds   = va_arg (ap, data_set_t *);
1360                 vl   = va_arg (ap, value_list_t *);
1361                 meta = va_arg (ap, notification_meta_t **);
1362
1363                 if (0 != data_set2av (aTHX_ ds, pds)) {
1364                         av_clear (pds);
1365                         av_undef (pds);
1366                         pds = (AV *)&PL_sv_undef;
1367                         ret = -1;
1368                 }
1369
1370                 if (0 != value_list2hv (aTHX_ vl, ds, pvl)) {
1371                         hv_clear (pvl);
1372                         hv_undef (pvl);
1373                         pvl = (HV *)&PL_sv_undef;
1374                         ret = -1;
1375                 }
1376
1377                 if (NULL != meta) {
1378                         pmeta = newAV ();
1379
1380                         if (0 != notification_meta2av (aTHX_ *meta, pmeta)) {
1381                                 av_clear (pmeta);
1382                                 av_undef (pmeta);
1383                                 pmeta = (AV *)&PL_sv_undef;
1384                                 ret = -1;
1385                         }
1386                 }
1387                 else {
1388                         pmeta = (AV *)&PL_sv_undef;
1389                 }
1390
1391                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1392                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1393                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pmeta)));
1394         }
1395
1396         XPUSHs (sv_2mortal (newRV_inc (data->user_data)));
1397
1398         PUTBACK;
1399
1400         retvals = call_pv_locked (aTHX_ "Collectd::fc_call");
1401
1402         if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1403                 assert (pmeta != NULL);
1404
1405                 plugin_notification_meta_free (*meta);
1406                 av2notification_meta (aTHX_ pmeta, meta);
1407         }
1408
1409         SPAGAIN;
1410         if (0 < retvals) {
1411                 SV *tmp = POPs;
1412
1413                 /* the exec callbacks return a status, while
1414                  * the others return a boolean value */
1415                 if (FC_CB_EXEC == cb_type)
1416                         ret = SvIV (tmp);
1417                 else if (! SvTRUE (tmp))
1418                         ret = -1;
1419         }
1420
1421         PUTBACK;
1422         FREETMPS;
1423         LEAVE;
1424
1425         va_end (ap);
1426         return ret;
1427 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1428
1429 static int fc_create (int type, const oconfig_item_t *ci, void **user_data)
1430 {
1431         pfc_user_data_t *data;
1432
1433         int ret = 0;
1434
1435         dTHX;
1436
1437         if (NULL == perl_threads)
1438                 return 0;
1439
1440         if (NULL == aTHX) {
1441                 c_ithread_t *t = NULL;
1442
1443                 pthread_mutex_lock (&perl_threads->mutex);
1444                 t = c_ithread_create (perl_threads->head->interp);
1445                 pthread_mutex_unlock (&perl_threads->mutex);
1446
1447                 aTHX = t->interp;
1448         }
1449
1450         log_debug ("fc_create: c_ithread: interp = %p (active threads: %i)",
1451                         aTHX, perl_threads->number_of_threads);
1452
1453         if ((1 != ci->values_num)
1454                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1455                 log_warn ("A \"%s\" block expects a single string argument.",
1456                                 (FC_MATCH == type) ? "Match" : "Target");
1457                 return -1;
1458         }
1459
1460         data = smalloc (sizeof (*data));
1461         data->name      = sstrdup (ci->values[0].value.string);
1462         data->user_data = newSV (0);
1463
1464         ret = fc_call (aTHX_ type, FC_CB_CREATE, data, ci);
1465
1466         if (0 != ret)
1467                 PFC_USER_DATA_FREE (data);
1468         else
1469                 *user_data = data;
1470         return ret;
1471 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1472
1473 static int fc_destroy (int type, void **user_data)
1474 {
1475         pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1476
1477         int ret = 0;
1478
1479         dTHX;
1480
1481         if ((NULL == perl_threads) || (NULL == data))
1482                 return 0;
1483
1484         if (NULL == aTHX) {
1485                 c_ithread_t *t = NULL;
1486
1487                 pthread_mutex_lock (&perl_threads->mutex);
1488                 t = c_ithread_create (perl_threads->head->interp);
1489                 pthread_mutex_unlock (&perl_threads->mutex);
1490
1491                 aTHX = t->interp;
1492         }
1493
1494         log_debug ("fc_destroy: c_ithread: interp = %p (active threads: %i)",
1495                         aTHX, perl_threads->number_of_threads);
1496
1497         ret = fc_call (aTHX_ type, FC_CB_DESTROY, data);
1498
1499         PFC_USER_DATA_FREE (data);
1500         *user_data = NULL;
1501         return ret;
1502 } /* static int fc_destroy (int, void **) */
1503
1504 static int fc_exec (int type, const data_set_t *ds, const value_list_t *vl,
1505                 notification_meta_t **meta, void **user_data)
1506 {
1507         pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1508
1509         dTHX;
1510
1511         if (NULL == perl_threads)
1512                 return 0;
1513
1514         assert (NULL != data);
1515
1516         if (NULL == aTHX) {
1517                 c_ithread_t *t = NULL;
1518
1519                 pthread_mutex_lock (&perl_threads->mutex);
1520                 t = c_ithread_create (perl_threads->head->interp);
1521                 pthread_mutex_unlock (&perl_threads->mutex);
1522
1523                 aTHX = t->interp;
1524         }
1525
1526         log_debug ("fc_exec: c_ithread: interp = %p (active threads: %i)",
1527                         aTHX, perl_threads->number_of_threads);
1528
1529         return fc_call (aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1530 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1531                 notification_meta_t **, void **) */
1532
1533 static int pmatch_create (const oconfig_item_t *ci, void **user_data)
1534 {
1535         return fc_create (FC_MATCH, ci, user_data);
1536 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1537
1538 static int pmatch_destroy (void **user_data)
1539 {
1540         return fc_destroy (FC_MATCH, user_data);
1541 } /* static int pmatch_destroy (void **) */
1542
1543 static int pmatch_match (const data_set_t *ds, const value_list_t *vl,
1544                 notification_meta_t **meta, void **user_data)
1545 {
1546         return fc_exec (FC_MATCH, ds, vl, meta, user_data);
1547 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1548                 notification_meta_t **, void **) */
1549
1550 static match_proc_t pmatch = {
1551         pmatch_create, pmatch_destroy, pmatch_match
1552 };
1553
1554 static int ptarget_create (const oconfig_item_t *ci, void **user_data)
1555 {
1556         return fc_create (FC_TARGET, ci, user_data);
1557 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1558
1559 static int ptarget_destroy (void **user_data)
1560 {
1561         return fc_destroy (FC_TARGET, user_data);
1562 } /* static int ptarget_destroy (void **) */
1563
1564 static int ptarget_invoke (const data_set_t *ds, value_list_t *vl,
1565                 notification_meta_t **meta, void **user_data)
1566 {
1567         return fc_exec (FC_TARGET, ds, vl, meta, user_data);
1568 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1569                 notification_meta_t **, void **) */
1570
1571 static target_proc_t ptarget = {
1572         ptarget_create, ptarget_destroy, ptarget_invoke
1573 };
1574
1575 /*
1576  * Exported Perl API.
1577  */
1578
1579 /*
1580  * Collectd::plugin_register_data_set (type, dataset).
1581  *
1582  * type:
1583  *   type of the dataset
1584  *
1585  * dataset:
1586  *   dataset to be registered
1587  */
1588 static XS (Collectd_plugin_register_ds)
1589 {
1590         SV  *data = NULL;
1591         int ret   = 0;
1592
1593         dXSARGS;
1594
1595         log_warn ("Using plugin_register() to register new data-sets is "
1596                         "deprecated - add new entries to a custom types.db instead.");
1597
1598         if (2 != items) {
1599                 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1600                 XSRETURN_EMPTY;
1601         }
1602
1603         log_debug ("Collectd::plugin_register_data_set: "
1604                         "type = \"%s\", dataset = \"%s\"",
1605                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1606
1607         data = ST (1);
1608
1609         if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1610                 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1611                                 (AV *)SvRV (data));
1612         }
1613         else {
1614                 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1615                 XSRETURN_EMPTY;
1616         }
1617
1618         if (0 == ret)
1619                 XSRETURN_YES;
1620         else
1621                 XSRETURN_EMPTY;
1622 } /* static XS (Collectd_plugin_register_ds) */
1623
1624 /*
1625  * Collectd::plugin_unregister_data_set (type).
1626  *
1627  * type:
1628  *   type of the dataset
1629  */
1630 static XS (Collectd_plugin_unregister_ds)
1631 {
1632         dXSARGS;
1633
1634         if (1 != items) {
1635                 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1636                 XSRETURN_EMPTY;
1637         }
1638
1639         log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1640                         SvPV_nolen (ST (0)));
1641
1642         if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1643                 XSRETURN_YES;
1644         else
1645                 XSRETURN_EMPTY;
1646 } /* static XS (Collectd_plugin_register_ds) */
1647
1648 /*
1649  * Collectd::plugin_dispatch_values (name, values).
1650  *
1651  * name:
1652  *   name of the plugin
1653  *
1654  * values:
1655  *   value list to submit
1656  */
1657 static XS (Collectd_plugin_dispatch_values)
1658 {
1659         SV *values     = NULL;
1660
1661         int ret = 0;
1662
1663         dXSARGS;
1664
1665         if (1 != items) {
1666                 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1667                 XSRETURN_EMPTY;
1668         }
1669
1670         log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1671                         SvPV_nolen (ST (/* stack index = */ 0)));
1672
1673         values = ST (/* stack index = */ 0);
1674
1675         if (NULL == values)
1676                 XSRETURN_EMPTY;
1677
1678         /* Make sure the argument is a hash reference. */
1679         if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1680                 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1681                 XSRETURN_EMPTY;
1682         }
1683
1684         ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1685
1686         if (0 == ret)
1687                 XSRETURN_YES;
1688         else
1689                 XSRETURN_EMPTY;
1690 } /* static XS (Collectd_plugin_dispatch_values) */
1691
1692 /*
1693  * Collectd::plugin_get_interval ().
1694  */
1695 static XS (Collectd_plugin_get_interval)
1696 {
1697         dXSARGS;
1698
1699         /* make sure we don't get any unused variable warnings for 'items';
1700          * don't abort, though */
1701         if (items)
1702                 log_err ("Usage: Collectd::plugin_get_interval()");
1703
1704         XSRETURN_NV ((NV) CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
1705 } /* static XS (Collectd_plugin_get_interval) */
1706
1707 /* Collectd::plugin_write (plugin, ds, vl).
1708  *
1709  * plugin:
1710  *   name of the plugin to call, may be 'undef'
1711  *
1712  * ds:
1713  *   data-set that describes the submitted values, may be 'undef'
1714  *
1715  * vl:
1716  *   value-list to be written
1717  */
1718 static XS (Collectd__plugin_write)
1719 {
1720         char *plugin;
1721         SV   *ds, *vl;
1722         AV   *ds_array;
1723
1724         int ret;
1725
1726         dXSARGS;
1727
1728         if (3 != items) {
1729                 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1730                 XSRETURN_EMPTY;
1731         }
1732
1733         log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1734                         SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1735                         SvPV_nolen (ST (2)));
1736
1737         if (! SvOK (ST (0)))
1738                 plugin = NULL;
1739         else
1740                 plugin = SvPV_nolen (ST (0));
1741
1742         ds = ST (1);
1743         if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1744                 ds_array = (AV *)SvRV (ds);
1745         else if (! SvOK (ds))
1746                 ds_array = NULL;
1747         else {
1748                 log_err ("Collectd::plugin_write: Invalid data-set.");
1749                 XSRETURN_EMPTY;
1750         }
1751
1752         vl = ST (2);
1753         if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1754                 log_err ("Collectd::plugin_write: Invalid value-list.");
1755                 XSRETURN_EMPTY;
1756         }
1757
1758         ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1759
1760         if (0 == ret)
1761                 XSRETURN_YES;
1762         else
1763                 XSRETURN_EMPTY;
1764 } /* static XS (Collectd__plugin_write) */
1765
1766 /*
1767  * Collectd::_plugin_flush (plugin, timeout, identifier).
1768  *
1769  * plugin:
1770  *   name of the plugin to flush
1771  *
1772  * timeout:
1773  *   timeout to use when flushing the data
1774  *
1775  * identifier:
1776  *   data-set identifier to flush
1777  */
1778 static XS (Collectd__plugin_flush)
1779 {
1780         char *plugin  = NULL;
1781         int   timeout = -1;
1782         char *id      = NULL;
1783
1784         dXSARGS;
1785
1786         if (3 != items) {
1787                 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1788                 XSRETURN_EMPTY;
1789         }
1790
1791         if (SvOK (ST (0)))
1792                 plugin = SvPV_nolen (ST (0));
1793
1794         if (SvOK (ST (1)))
1795                 timeout = (int)SvIV (ST (1));
1796
1797         if (SvOK (ST (2)))
1798                 id = SvPV_nolen (ST (2));
1799
1800         log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1801                         "id = \"%s\"", plugin, timeout, id);
1802
1803         if (0 == plugin_flush (plugin, timeout, id))
1804                 XSRETURN_YES;
1805         else
1806                 XSRETURN_EMPTY;
1807 } /* static XS (Collectd__plugin_flush) */
1808
1809 /*
1810  * Collectd::plugin_dispatch_notification (notif).
1811  *
1812  * notif:
1813  *   notification to dispatch
1814  */
1815 static XS (Collectd_plugin_dispatch_notification)
1816 {
1817         SV *notif = NULL;
1818
1819         int ret = 0;
1820
1821         dXSARGS;
1822
1823         if (1 != items) {
1824                 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
1825                 XSRETURN_EMPTY;
1826         }
1827
1828         log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1829                         SvPV_nolen (ST (0)));
1830
1831         notif = ST (0);
1832
1833         if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
1834                 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
1835                 XSRETURN_EMPTY;
1836         }
1837
1838         ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
1839
1840         if (0 == ret)
1841                 XSRETURN_YES;
1842         else
1843                 XSRETURN_EMPTY;
1844 } /* static XS (Collectd_plugin_dispatch_notification) */
1845
1846 /*
1847  * Collectd::plugin_log (level, message).
1848  *
1849  * level:
1850  *   log level (LOG_DEBUG, ... LOG_ERR)
1851  *
1852  * message:
1853  *   log message
1854  */
1855 static XS (Collectd_plugin_log)
1856 {
1857         dXSARGS;
1858
1859         if (2 != items) {
1860                 log_err ("Usage: Collectd::plugin_log(level, message)");
1861                 XSRETURN_EMPTY;
1862         }
1863
1864         plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
1865         XSRETURN_YES;
1866 } /* static XS (Collectd_plugin_log) */
1867
1868 /*
1869  * Collectd::_fc_register (type, name)
1870  *
1871  * type:
1872  *   match | target
1873  *
1874  * name:
1875  *   name of the match
1876  */
1877 static XS (Collectd__fc_register)
1878 {
1879         int   type;
1880         char *name;
1881
1882         int ret = 0;
1883
1884         dXSARGS;
1885
1886         if (2 != items) {
1887                 log_err ("Usage: Collectd::_fc_register(type, name)");
1888                 XSRETURN_EMPTY;
1889         }
1890
1891         type = SvIV (ST (0));
1892         name = SvPV_nolen (ST (1));
1893
1894         if (FC_MATCH == type)
1895                 ret = fc_register_match (name, pmatch);
1896         else if (FC_TARGET == type)
1897                 ret = fc_register_target (name, ptarget);
1898
1899         if (0 == ret)
1900                 XSRETURN_YES;
1901         else
1902                 XSRETURN_EMPTY;
1903 } /* static XS (Collectd_fc_register) */
1904
1905 /*
1906  * Collectd::call_by_name (...).
1907  *
1908  * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1909  */
1910 static XS (Collectd_call_by_name)
1911 {
1912         SV   *tmp  = NULL;
1913         char *name = NULL;
1914
1915         if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
1916                 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
1917                 CLEAR_STACK_FRAME;
1918                 return;
1919         }
1920
1921         name = SvPV_nolen (tmp);
1922
1923         if (NULL == get_cv (name, 0)) {
1924                 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
1925                 CLEAR_STACK_FRAME;
1926                 return;
1927         }
1928
1929         /* simply pass on the subroutine call without touching the stack,
1930          * thus leaving any arguments and return values in place */
1931         call_pv (name, 0);
1932 } /* static XS (Collectd_call_by_name) */
1933
1934 /*
1935  * Interface to collectd.
1936  */
1937
1938 static int perl_init (void)
1939 {
1940         int status;
1941         dTHX;
1942
1943         if (NULL == perl_threads)
1944                 return 0;
1945
1946         if (NULL == aTHX) {
1947                 c_ithread_t *t = NULL;
1948
1949                 pthread_mutex_lock (&perl_threads->mutex);
1950                 t = c_ithread_create (perl_threads->head->interp);
1951                 pthread_mutex_unlock (&perl_threads->mutex);
1952
1953                 aTHX = t->interp;
1954         }
1955
1956         log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1957                         aTHX, perl_threads->number_of_threads);
1958
1959         /* Lock the base thread to avoid race conditions with c_ithread_create().
1960          * See https://github.com/collectd/collectd/issues/9 and
1961          *     https://github.com/collectd/collectd/issues/1706 for details.
1962         */
1963         assert (aTHX == perl_threads->head->interp);
1964         pthread_mutex_lock (&perl_threads->mutex);
1965
1966         status = pplugin_call_all (aTHX_ PLUGIN_INIT);
1967
1968         pthread_mutex_unlock (&perl_threads->mutex);
1969
1970         return status;
1971 } /* static int perl_init (void) */
1972
1973 static int perl_read (void)
1974 {
1975         dTHX;
1976
1977         if (NULL == perl_threads)
1978                 return 0;
1979
1980         if (NULL == aTHX) {
1981                 c_ithread_t *t = NULL;
1982
1983                 pthread_mutex_lock (&perl_threads->mutex);
1984                 t = c_ithread_create (perl_threads->head->interp);
1985                 pthread_mutex_unlock (&perl_threads->mutex);
1986
1987                 aTHX = t->interp;
1988         }
1989
1990         /* Assert that we're not running as the base thread. Otherwise, we might
1991          * run into concurrency issues with c_ithread_create(). See
1992          * https://github.com/collectd/collectd/issues/9 for details. */
1993         assert (aTHX != perl_threads->head->interp);
1994
1995         log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1996                         aTHX, perl_threads->number_of_threads);
1997         return pplugin_call_all (aTHX_ PLUGIN_READ);
1998 } /* static int perl_read (void) */
1999
2000 static int perl_write (const data_set_t *ds, const value_list_t *vl,
2001                 user_data_t __attribute__((unused)) *user_data)
2002 {
2003         int status;
2004         dTHX;
2005
2006         if (NULL == perl_threads)
2007                 return 0;
2008
2009         if (NULL == aTHX) {
2010                 c_ithread_t *t = NULL;
2011
2012                 pthread_mutex_lock (&perl_threads->mutex);
2013                 t = c_ithread_create (perl_threads->head->interp);
2014                 pthread_mutex_unlock (&perl_threads->mutex);
2015
2016                 aTHX = t->interp;
2017         }
2018
2019         /* Lock the base thread if this is not called from one of the read threads
2020          * to avoid race conditions with c_ithread_create(). See
2021          * https://github.com/collectd/collectd/issues/9 for details. */
2022         if (aTHX == perl_threads->head->interp)
2023                 pthread_mutex_lock (&perl_threads->mutex);
2024
2025         log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
2026                         aTHX, perl_threads->number_of_threads);
2027         status = pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
2028
2029         if (aTHX == perl_threads->head->interp)
2030                 pthread_mutex_unlock (&perl_threads->mutex);
2031
2032         return status;
2033 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2034
2035 static void perl_log (int level, const char *msg,
2036                 user_data_t __attribute__((unused)) *user_data)
2037 {
2038         dTHX;
2039
2040         if (NULL == perl_threads)
2041                 return;
2042
2043         if (NULL == aTHX) {
2044                 c_ithread_t *t = NULL;
2045
2046                 pthread_mutex_lock (&perl_threads->mutex);
2047                 t = c_ithread_create (perl_threads->head->interp);
2048                 pthread_mutex_unlock (&perl_threads->mutex);
2049
2050                 aTHX = t->interp;
2051         }
2052
2053         /* Lock the base thread if this is not called from one of the read threads
2054          * to avoid race conditions with c_ithread_create(). See
2055          * https://github.com/collectd/collectd/issues/9 for details.
2056         */
2057
2058         if (aTHX == perl_threads->head->interp)
2059                 pthread_mutex_lock (&perl_threads->mutex);
2060
2061         pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
2062
2063         if (aTHX == perl_threads->head->interp)
2064                 pthread_mutex_unlock (&perl_threads->mutex);
2065
2066         return;
2067 } /* static void perl_log (int, const char *) */
2068
2069 static int perl_notify (const notification_t *notif,
2070                 user_data_t __attribute__((unused)) *user_data)
2071 {
2072         dTHX;
2073
2074         if (NULL == perl_threads)
2075                 return 0;
2076
2077         if (NULL == aTHX) {
2078                 c_ithread_t *t = NULL;
2079
2080                 pthread_mutex_lock (&perl_threads->mutex);
2081                 t = c_ithread_create (perl_threads->head->interp);
2082                 pthread_mutex_unlock (&perl_threads->mutex);
2083
2084                 aTHX = t->interp;
2085         }
2086         return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
2087 } /* static int perl_notify (const notification_t *) */
2088
2089 static int perl_flush (cdtime_t timeout, const char *identifier,
2090                 user_data_t __attribute__((unused)) *user_data)
2091 {
2092         dTHX;
2093
2094         if (NULL == perl_threads)
2095                 return 0;
2096
2097         if (NULL == aTHX) {
2098                 c_ithread_t *t = NULL;
2099
2100                 pthread_mutex_lock (&perl_threads->mutex);
2101                 t = c_ithread_create (perl_threads->head->interp);
2102                 pthread_mutex_unlock (&perl_threads->mutex);
2103
2104                 aTHX = t->interp;
2105         }
2106         return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout, identifier);
2107 } /* static int perl_flush (const int) */
2108
2109 static int perl_shutdown (void)
2110 {
2111         c_ithread_t *t;
2112         int ret;
2113
2114         dTHX;
2115
2116         plugin_unregister_complex_config ("perl");
2117
2118         if (NULL == perl_threads)
2119                 return 0;
2120
2121         if (NULL == aTHX) {
2122                 pthread_mutex_lock (&perl_threads->mutex);
2123                 t = c_ithread_create (perl_threads->head->interp);
2124                 pthread_mutex_unlock (&perl_threads->mutex);
2125
2126                 aTHX = t->interp;
2127         }
2128
2129         log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2130                         aTHX, perl_threads->number_of_threads);
2131
2132         plugin_unregister_log ("perl");
2133         plugin_unregister_notification ("perl");
2134         plugin_unregister_init ("perl");
2135         plugin_unregister_read ("perl");
2136         plugin_unregister_write ("perl");
2137         plugin_unregister_flush ("perl");
2138
2139         ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
2140
2141         pthread_mutex_lock (&perl_threads->mutex);
2142         t = perl_threads->tail;
2143
2144         while (NULL != t) {
2145                 struct timespec ts_wait;
2146                 c_ithread_t *thr = t;
2147
2148                 /* the pointer has to be advanced before destroying
2149                  * the thread as this will free the memory */
2150                 t = t->prev;
2151
2152                 thr->shutdown = 1;
2153                 if (thr->running) {
2154                         /* Give some time to thread to exit from Perl interpreter */
2155                         WARNING ("perl shutdown: Thread is running inside Perl. Waiting.");
2156                         ts_wait.tv_sec = 0;
2157                         ts_wait.tv_nsec = 500000;
2158                         nanosleep (&ts_wait, NULL);
2159                 }
2160                 if (thr->running) {
2161                         pthread_kill (thr->pthread, SIGTERM);
2162                         ERROR ("perl shutdown: Thread hangs inside Perl. Thread killed.");
2163                 }
2164                 c_ithread_destroy (thr);
2165         }
2166
2167         pthread_mutex_unlock (&perl_threads->mutex);
2168         pthread_mutex_destroy (&perl_threads->mutex);
2169         pthread_mutexattr_destroy (&perl_threads->mutexattr);
2170
2171         sfree (perl_threads);
2172
2173         pthread_key_delete (perl_thr_key);
2174
2175         PERL_SYS_TERM ();
2176
2177         plugin_unregister_shutdown ("perl");
2178         return ret;
2179 } /* static void perl_shutdown (void) */
2180
2181 /*
2182  * Access functions for global variables.
2183  *
2184  * These functions implement the "magic" used to access
2185  * the global variables from Perl.
2186  */
2187
2188 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
2189 {
2190         char *pv = mg->mg_ptr;
2191         sv_setpv (var, pv);
2192         return 0;
2193 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2194
2195 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
2196 {
2197         char *pv = mg->mg_ptr;
2198         sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
2199         return 0;
2200 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2201
2202 static int g_interval_get (pTHX_ SV *var, MAGIC *mg)
2203 {
2204         log_warn ("Accessing $interval_g is deprecated (and might not "
2205                         "give the desired results) - plugin_get_interval() should "
2206                         "be used instead.");
2207         sv_setnv (var, CDTIME_T_TO_DOUBLE (interval_g));
2208         return 0;
2209 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2210
2211 static int g_interval_set (pTHX_ SV *var, MAGIC *mg)
2212 {
2213         double nv = (double)SvNV (var);
2214         log_warn ("Accessing $interval_g is deprecated (and might not "
2215                         "give the desired results) - plugin_get_interval() should "
2216                         "be used instead.");
2217         interval_g = DOUBLE_TO_CDTIME_T (nv);
2218         return 0;
2219 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2220
2221 static MGVTBL g_pv_vtbl = {
2222         g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2223 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2224                 , NULL
2225 #endif
2226 };
2227 static MGVTBL g_interval_vtbl = {
2228         g_interval_get, g_interval_set, NULL, NULL, NULL, NULL, NULL
2229 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2230                 , NULL
2231 #endif
2232 };
2233
2234 /* bootstrap the Collectd module */
2235 static void xs_init (pTHX)
2236 {
2237         HV   *stash = NULL;
2238         SV   *tmp   = NULL;
2239         char *file  = __FILE__;
2240
2241         int i = 0;
2242
2243         dXSUB_SYS;
2244
2245         /* enable usage of Perl modules using shared libraries */
2246         newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2247
2248         /* register API */
2249         for (i = 0; NULL != api[i].f; ++i)
2250                 newXS (api[i].name, api[i].f, file);
2251
2252         stash = gv_stashpv ("Collectd", 1);
2253
2254         /* export "constants" */
2255         for (i = 0; '\0' != constants[i].name[0]; ++i)
2256                 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
2257
2258         /* export global variables
2259          * by adding "magic" to the SV's representing the globale variables
2260          * perl is able to automagically call the get/set function when
2261          * accessing any such variable (this is basically the same as using
2262          * tie() in Perl) */
2263         /* global strings */
2264         for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
2265                 tmp = get_sv (g_strings[i].name, 1);
2266                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
2267                                 g_strings[i].var, 0);
2268         }
2269
2270         tmp = get_sv ("Collectd::interval_g", /* create = */ 1);
2271         sv_magicext (tmp, NULL, /* how = */ PERL_MAGIC_ext,
2272                         /* vtbl = */ &g_interval_vtbl,
2273                         /* name = */ NULL, /* namelen = */ 0);
2274
2275         return;
2276 } /* static void xs_init (pTHX) */
2277
2278 /* Initialize the global Perl interpreter. */
2279 static int init_pi (int argc, char **argv)
2280 {
2281         dTHXa (NULL);
2282
2283         if (NULL != perl_threads)
2284                 return 0;
2285
2286         log_info ("Initializing Perl interpreter...");
2287 #if COLLECT_DEBUG
2288         {
2289                 int i = 0;
2290
2291                 for (i = 0; i < argc; ++i)
2292                         log_debug ("argv[%i] = \"%s\"", i, argv[i]);
2293         }
2294 #endif /* COLLECT_DEBUG */
2295
2296         if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
2297                 log_err ("init_pi: pthread_key_create failed");
2298
2299                 /* this must not happen - cowardly giving up if it does */
2300                 return -1;
2301         }
2302
2303 #ifdef __FreeBSD__
2304         /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2305          * triggers a "value computed is not used" warning by gcc. */
2306         (void)
2307 #endif
2308         PERL_SYS_INIT3 (&argc, &argv, &environ);
2309
2310         perl_threads = smalloc (sizeof (*perl_threads));
2311         memset (perl_threads, 0, sizeof (c_ithread_list_t));
2312
2313         pthread_mutexattr_init(&perl_threads->mutexattr);
2314         pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2315         pthread_mutex_init (&perl_threads->mutex, &perl_threads->mutexattr);
2316         /* locking the mutex should not be necessary at this point
2317          * but let's just do it for the sake of completeness */
2318         pthread_mutex_lock (&perl_threads->mutex);
2319
2320         perl_threads->head = c_ithread_create (NULL);
2321         perl_threads->tail = perl_threads->head;
2322
2323         if (NULL == (perl_threads->head->interp = perl_alloc ())) {
2324                 log_err ("init_pi: Not enough memory.");
2325                 exit (3);
2326         }
2327
2328         aTHX = perl_threads->head->interp;
2329         pthread_mutex_unlock (&perl_threads->mutex);
2330
2331         perl_construct (aTHX);
2332
2333         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2334
2335         if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
2336                 SV *err = get_sv ("@", 1);
2337                 log_err ("init_pi: Unable to bootstrap Collectd: %s",
2338                                 SvPV_nolen (err));
2339
2340                 perl_destruct (perl_threads->head->interp);
2341                 perl_free (perl_threads->head->interp);
2342                 sfree (perl_threads);
2343
2344                 pthread_key_delete (perl_thr_key);
2345                 return -1;
2346         }
2347
2348         /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2349         sv_setpv (get_sv ("0", 0), "collectd");
2350
2351         perl_run (aTHX);
2352
2353         plugin_register_log ("perl", perl_log, /* user_data = */ NULL);
2354         plugin_register_notification ("perl", perl_notify,
2355                         /* user_data = */ NULL);
2356         plugin_register_init ("perl", perl_init);
2357
2358         plugin_register_read ("perl", perl_read);
2359
2360         plugin_register_write ("perl", perl_write, /* user_data = */ NULL);
2361         plugin_register_flush ("perl", perl_flush, /* user_data = */ NULL);
2362         plugin_register_shutdown ("perl", perl_shutdown);
2363         return 0;
2364 } /* static int init_pi (const char **, const int) */
2365
2366 /*
2367  * LoadPlugin "<Plugin>"
2368  */
2369 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
2370 {
2371         char module_name[DATA_MAX_NAME_LEN];
2372
2373         char *value = NULL;
2374
2375         if ((0 != ci->children_num) || (1 != ci->values_num)
2376                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2377                 log_err ("LoadPlugin expects a single string argument.");
2378                 return 1;
2379         }
2380
2381         value = ci->values[0].value.string;
2382
2383         if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
2384                 log_err ("Invalid module name %s", value);
2385                 return (1);
2386         }
2387
2388         if (0 != init_pi (perl_argc, perl_argv))
2389                 return -1;
2390
2391         assert (NULL != perl_threads);
2392         assert (NULL != perl_threads->head);
2393
2394         aTHX = perl_threads->head->interp;
2395
2396         log_debug ("perl_config: Loading Perl plugin \"%s\"", value);
2397         load_module (PERL_LOADMOD_NOIMPORT,
2398                         newSVpv (module_name, strlen (module_name)), Nullsv);
2399         return 0;
2400 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2401
2402 /*
2403  * BaseName "<Name>"
2404  */
2405 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
2406 {
2407         char *value = NULL;
2408
2409         if ((0 != ci->children_num) || (1 != ci->values_num)
2410                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2411                 log_err ("BaseName expects a single string argument.");
2412                 return 1;
2413         }
2414
2415         value = ci->values[0].value.string;
2416
2417         log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
2418         sstrncpy (base_name, value, sizeof (base_name));
2419         return 0;
2420 } /* static int perl_config_basename (oconfig_item_it *) */
2421
2422 /*
2423  * EnableDebugger "<Package>"|""
2424  */
2425 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
2426 {
2427         char *value = NULL;
2428
2429         if ((0 != ci->children_num) || (1 != ci->values_num)
2430                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2431                 log_err ("EnableDebugger expects a single string argument.");
2432                 return 1;
2433         }
2434
2435         if (NULL != perl_threads) {
2436                 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
2437                 return 1;
2438         }
2439
2440         value = ci->values[0].value.string;
2441
2442         perl_argv = realloc (perl_argv,
2443                         (++perl_argc + 1) * sizeof (char *));
2444
2445         if (NULL == perl_argv) {
2446                 log_err ("perl_config: Not enough memory.");
2447                 exit (3);
2448         }
2449
2450         if ('\0' == value[0]) {
2451                 perl_argv[perl_argc - 1] = "-d";
2452         }
2453         else {
2454                 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 4);
2455                 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
2456                 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
2457         }
2458
2459         perl_argv[perl_argc] = NULL;
2460         return 0;
2461 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2462
2463 /*
2464  * IncludeDir "<Dir>"
2465  */
2466 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
2467 {
2468         char *value = NULL;
2469
2470         if ((0 != ci->children_num) || (1 != ci->values_num)
2471                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2472                 log_err ("IncludeDir expects a single string argument.");
2473                 return 1;
2474         }
2475
2476         value = ci->values[0].value.string;
2477
2478         if (NULL == aTHX) {
2479                 perl_argv = realloc (perl_argv,
2480                                 (++perl_argc + 1) * sizeof (char *));
2481
2482                 if (NULL == perl_argv) {
2483                         log_err ("perl_config: Not enough memory.");
2484                         exit (3);
2485                 }
2486
2487                 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 3);
2488                 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2489                 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
2490
2491                 perl_argv[perl_argc] = NULL;
2492         }
2493         else {
2494                 /* prepend the directory to @INC */
2495                 av_unshift (GvAVn (PL_incgv), 1);
2496                 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
2497         }
2498         return 0;
2499 } /* static int perl_config_includedir (oconfig_item_it *) */
2500
2501 /*
2502  * <Plugin> block
2503  */
2504 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2505 {
2506         int retvals = 0;
2507         int ret     = 0;
2508
2509         char *plugin;
2510         HV   *config;
2511
2512         dSP;
2513
2514         if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2515                 log_err ("LoadPlugin expects a single string argument.");
2516                 return 1;
2517         }
2518
2519         plugin = ci->values[0].value.string;
2520         config = newHV ();
2521
2522         if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2523                 hv_clear (config);
2524                 hv_undef (config);
2525
2526                 log_err ("Unable to convert configuration to a Perl hash value.");
2527                 config = (HV *)&PL_sv_undef;
2528         }
2529
2530         ENTER;
2531         SAVETMPS;
2532
2533         PUSHMARK (SP);
2534
2535         XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2536         XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2537
2538         PUTBACK;
2539
2540         retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2541
2542         SPAGAIN;
2543         if (0 < retvals) {
2544                 SV *tmp = POPs;
2545                 if (! SvTRUE (tmp))
2546                         ret = 1;
2547         }
2548         else
2549                 ret = 1;
2550
2551         PUTBACK;
2552         FREETMPS;
2553         LEAVE;
2554         return ret;
2555 } /* static int perl_config_plugin (oconfig_item_it *) */
2556
2557 static int perl_config (oconfig_item_t *ci)
2558 {
2559         int status = 0;
2560         int i = 0;
2561
2562         dTHXa (NULL);
2563
2564         for (i = 0; i < ci->children_num; ++i) {
2565                 oconfig_item_t *c = ci->children + i;
2566                 int current_status = 0;
2567
2568                 if (NULL != perl_threads)
2569                 {
2570                         if ((aTHX = PERL_GET_CONTEXT) == NULL)
2571                                 return -1;
2572                 }
2573
2574                 if (0 == strcasecmp (c->key, "LoadPlugin"))
2575                         current_status = perl_config_loadplugin (aTHX_ c);
2576                 else if (0 == strcasecmp (c->key, "BaseName"))
2577                         current_status = perl_config_basename (aTHX_ c);
2578                 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2579                         current_status = perl_config_enabledebugger (aTHX_ c);
2580                 else if (0 == strcasecmp (c->key, "IncludeDir"))
2581                         current_status = perl_config_includedir (aTHX_ c);
2582                 else if (0 == strcasecmp (c->key, "Plugin"))
2583                         current_status = perl_config_plugin (aTHX_ c);
2584                 else
2585                 {
2586                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
2587                         current_status = 0;
2588                 }
2589
2590                 /* fatal error - it's up to perl_config_* to clean up */
2591                 if (0 > current_status) {
2592                         log_err ("Configuration failed with a fatal error - "
2593                                         "plugin disabled!");
2594                         return current_status;
2595                 }
2596
2597                 status += current_status;
2598         }
2599         return status;
2600 } /* static int perl_config (oconfig_item_t *) */
2601
2602 void module_register (void)
2603 {
2604         perl_argc = 4;
2605         perl_argv = smalloc ((perl_argc + 1) * sizeof (*perl_argv));
2606
2607         /* default options for the Perl interpreter */
2608         perl_argv[0] = "";
2609         perl_argv[1] = "-MCollectd";
2610         perl_argv[2] = "-e";
2611         perl_argv[3] = "1";
2612         perl_argv[4] = NULL;
2613
2614         plugin_register_complex_config ("perl", perl_config);
2615         return;
2616 } /* void module_register (void) */
2617
2618 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
2619