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