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