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