{GPL, other}: Relicense to MIT license.
[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 # pragma GCC poison sprintf
50 #endif
51
52 #include <XSUB.h>
53
54 /* Some versions of Perl define their own version of DEBUG... :-/ */
55 #ifdef DEBUG
56 # undef DEBUG
57 #endif /* DEBUG */
58
59 /* ... while we want the definition found in plugin.h. */
60 #include "plugin.h"
61 #include "common.h"
62
63 #include "filter_chain.h"
64
65 #include <pthread.h>
66
67 #if !defined(USE_ITHREADS)
68 # error "Perl does not support ithreads!"
69 #endif /* !defined(USE_ITHREADS) */
70
71 /* clear the Perl sub's stack frame
72  * (this should only be used inside an XSUB) */
73 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
74
75 #define PLUGIN_INIT     0
76 #define PLUGIN_READ     1
77 #define PLUGIN_WRITE    2
78 #define PLUGIN_SHUTDOWN 3
79 #define PLUGIN_LOG      4
80 #define PLUGIN_NOTIF    5
81 #define PLUGIN_FLUSH    6
82
83 #define PLUGIN_TYPES    7
84
85 #define PLUGIN_CONFIG   254
86 #define PLUGIN_DATASET  255
87
88 #define FC_MATCH  0
89 #define FC_TARGET 1
90
91 #define FC_TYPES  2
92
93 #define FC_CB_CREATE  0
94 #define FC_CB_DESTROY 1
95 #define FC_CB_EXEC    2
96
97 #define FC_CB_TYPES   3
98
99 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
100 #define log_info(...) INFO ("perl: " __VA_ARGS__)
101 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
102 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
103
104 /* this is defined in DynaLoader.a */
105 void boot_DynaLoader (PerlInterpreter *, CV *);
106
107 static XS (Collectd_plugin_register_ds);
108 static XS (Collectd_plugin_unregister_ds);
109 static XS (Collectd_plugin_dispatch_values);
110 static XS (Collectd_plugin_get_interval);
111 static XS (Collectd__plugin_write);
112 static XS (Collectd__plugin_flush);
113 static XS (Collectd_plugin_dispatch_notification);
114 static XS (Collectd_plugin_log);
115 static XS (Collectd__fc_register);
116 static XS (Collectd_call_by_name);
117
118 /*
119  * private data types
120  */
121
122 typedef struct c_ithread_s {
123         /* the thread's Perl interpreter */
124         PerlInterpreter *interp;
125
126         /* double linked list of threads */
127         struct c_ithread_s *prev;
128         struct c_ithread_s *next;
129 } c_ithread_t;
130
131 typedef struct {
132         c_ithread_t *head;
133         c_ithread_t *tail;
134
135 #if COLLECT_DEBUG
136         /* some usage stats */
137         int number_of_threads;
138 #endif /* COLLECT_DEBUG */
139
140         pthread_mutex_t mutex;
141 } c_ithread_list_t;
142
143 /* name / user_data for Perl matches / targets */
144 typedef struct {
145         char *name;
146         SV   *user_data;
147 } pfc_user_data_t;
148
149 #define PFC_USER_DATA_FREE(data) \
150         do { \
151                 sfree ((data)->name); \
152                 if (NULL != (data)->user_data) \
153                         sv_free ((data)->user_data); \
154                 sfree (data); \
155         } while (0)
156
157 /*
158  * Public variable
159  */
160 extern char **environ;
161
162 /*
163  * private variables
164  */
165
166 /* if perl_threads != NULL perl_threads->head must
167  * point to the "base" thread */
168 static c_ithread_list_t *perl_threads = NULL;
169
170 /* the key used to store each pthread's ithread */
171 static pthread_key_t perl_thr_key;
172
173 static int    perl_argc = 0;
174 static char **perl_argv = NULL;
175
176 static char base_name[DATA_MAX_NAME_LEN] = "";
177
178 static struct {
179         char name[64];
180         XS ((*f));
181 } api[] =
182 {
183         { "Collectd::plugin_register_data_set",   Collectd_plugin_register_ds },
184         { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
185         { "Collectd::plugin_dispatch_values",     Collectd_plugin_dispatch_values },
186         { "Collectd::plugin_get_interval",        Collectd_plugin_get_interval },
187         { "Collectd::_plugin_write",              Collectd__plugin_write },
188         { "Collectd::_plugin_flush",              Collectd__plugin_flush },
189         { "Collectd::plugin_dispatch_notification",
190                 Collectd_plugin_dispatch_notification },
191         { "Collectd::plugin_log",                 Collectd_plugin_log },
192         { "Collectd::_fc_register",               Collectd__fc_register },
193         { "Collectd::call_by_name",               Collectd_call_by_name },
194         { "", NULL }
195 };
196
197 struct {
198         char name[64];
199         int  value;
200 } constants[] =
201 {
202         { "Collectd::TYPE_INIT",          PLUGIN_INIT },
203         { "Collectd::TYPE_READ",          PLUGIN_READ },
204         { "Collectd::TYPE_WRITE",         PLUGIN_WRITE },
205         { "Collectd::TYPE_SHUTDOWN",      PLUGIN_SHUTDOWN },
206         { "Collectd::TYPE_LOG",           PLUGIN_LOG },
207         { "Collectd::TYPE_NOTIF",         PLUGIN_NOTIF },
208         { "Collectd::TYPE_FLUSH",         PLUGIN_FLUSH },
209         { "Collectd::TYPE_CONFIG",        PLUGIN_CONFIG },
210         { "Collectd::TYPE_DATASET",       PLUGIN_DATASET },
211         { "Collectd::DS_TYPE_COUNTER",    DS_TYPE_COUNTER },
212         { "Collectd::DS_TYPE_GAUGE",      DS_TYPE_GAUGE },
213         { "Collectd::DS_TYPE_DERIVE",     DS_TYPE_DERIVE },
214         { "Collectd::DS_TYPE_ABSOLUTE",   DS_TYPE_ABSOLUTE },
215         { "Collectd::LOG_ERR",            LOG_ERR },
216         { "Collectd::LOG_WARNING",        LOG_WARNING },
217         { "Collectd::LOG_NOTICE",         LOG_NOTICE },
218         { "Collectd::LOG_INFO",           LOG_INFO },
219         { "Collectd::LOG_DEBUG",          LOG_DEBUG },
220         { "Collectd::FC_MATCH",           FC_MATCH },
221         { "Collectd::FC_TARGET",          FC_TARGET },
222         { "Collectd::FC_CB_CREATE",       FC_CB_CREATE },
223         { "Collectd::FC_CB_DESTROY",      FC_CB_DESTROY },
224         { "Collectd::FC_CB_EXEC",         FC_CB_EXEC },
225         { "Collectd::FC_MATCH_NO_MATCH",  FC_MATCH_NO_MATCH },
226         { "Collectd::FC_MATCH_MATCHES",   FC_MATCH_MATCHES },
227         { "Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE },
228         { "Collectd::FC_TARGET_STOP",     FC_TARGET_STOP },
229         { "Collectd::FC_TARGET_RETURN",   FC_TARGET_RETURN },
230         { "Collectd::NOTIF_FAILURE",      NOTIF_FAILURE },
231         { "Collectd::NOTIF_WARNING",      NOTIF_WARNING },
232         { "Collectd::NOTIF_OKAY",         NOTIF_OKAY },
233         { "", 0 }
234 };
235
236 struct {
237         char  name[64];
238         char *var;
239 } g_strings[] =
240 {
241         { "Collectd::hostname_g", hostname_g },
242         { "", NULL }
243 };
244
245 /*
246  * Helper functions for data type conversion.
247  */
248
249 /*
250  * data source:
251  * [
252  *   {
253  *     name => $ds_name,
254  *     type => $ds_type,
255  *     min  => $ds_min,
256  *     max  => $ds_max
257  *   },
258  *   ...
259  * ]
260  */
261 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
262 {
263         SV **tmp = NULL;
264
265         if ((NULL == hash) || (NULL == ds))
266                 return -1;
267
268         if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
269                 sstrncpy (ds->name, SvPV_nolen (*tmp), sizeof (ds->name));
270         }
271         else {
272                 log_err ("hv2data_source: No DS name given.");
273                 return -1;
274         }
275
276         if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
277                 ds->type = SvIV (*tmp);
278
279                 if ((DS_TYPE_COUNTER != ds->type)
280                                 && (DS_TYPE_GAUGE != ds->type)
281                                 && (DS_TYPE_DERIVE != ds->type)
282                                 && (DS_TYPE_ABSOLUTE != ds->type)) {
283                         log_err ("hv2data_source: Invalid DS type.");
284                         return -1;
285                 }
286         }
287         else {
288                 ds->type = DS_TYPE_COUNTER;
289         }
290
291         if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
292                 ds->min = SvNV (*tmp);
293         else
294                 ds->min = NAN;
295
296         if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
297                 ds->max = SvNV (*tmp);
298         else
299                 ds->max = NAN;
300         return 0;
301 } /* static int hv2data_source (HV *, data_source_t *) */
302
303 static int av2value (pTHX_ char *name, AV *array, value_t *value, int len)
304 {
305         const data_set_t *ds;
306
307         int i = 0;
308
309         if ((NULL == name) || (NULL == array) || (NULL == value))
310                 return -1;
311
312         if (av_len (array) < len - 1)
313                 len = av_len (array) + 1;
314
315         if (0 >= len)
316                 return -1;
317
318         ds = plugin_get_ds (name);
319         if (NULL == ds) {
320                 log_err ("av2value: Unknown dataset \"%s\"", name);
321                 return -1;
322         }
323
324         if (ds->ds_num < len) {
325                 log_warn ("av2value: Value length exceeds data set length.");
326                 len = ds->ds_num;
327         }
328
329         for (i = 0; i < len; ++i) {
330                 SV **tmp = av_fetch (array, i, 0);
331
332                 if (NULL != tmp) {
333                         if (DS_TYPE_COUNTER == ds->ds[i].type)
334                                 value[i].counter = SvIV (*tmp);
335                         else if (DS_TYPE_GAUGE == ds->ds[i].type)
336                                 value[i].gauge = SvNV (*tmp);
337                         else if (DS_TYPE_DERIVE == ds->ds[i].type)
338                                 value[i].derive = SvIV (*tmp);
339                         else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
340                                 value[i].absolute = SvIV (*tmp);
341                 }
342                 else {
343                         return -1;
344                 }
345         }
346         return len;
347 } /* static int av2value (char *, AV *, value_t *, int) */
348
349 /*
350  * value list:
351  * {
352  *   values => [ @values ],
353  *   time   => $time,
354  *   host   => $host,
355  *   plugin => $plugin,
356  *   plugin_instance => $pinstance,
357  *   type_instance   => $tinstance,
358  * }
359  */
360 static int hv2value_list (pTHX_ HV *hash, value_list_t *vl)
361 {
362         SV **tmp;
363
364         if ((NULL == hash) || (NULL == vl))
365                 return -1;
366
367         if (NULL == (tmp = hv_fetch (hash, "type", 4, 0))) {
368                 log_err ("hv2value_list: No type given.");
369                 return -1;
370         }
371
372         sstrncpy (vl->type, SvPV_nolen (*tmp), sizeof (vl->type));
373
374         if ((NULL == (tmp = hv_fetch (hash, "values", 6, 0)))
375                         || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
376                 log_err ("hv2value_list: No valid values given.");
377                 return -1;
378         }
379
380         {
381                 AV  *array = (AV *)SvRV (*tmp);
382                 int len    = av_len (array) + 1;
383
384                 if (len <= 0)
385                         return -1;
386
387                 vl->values     = (value_t *)smalloc (len * sizeof (value_t));
388                 vl->values_len = av2value (aTHX_ vl->type, (AV *)SvRV (*tmp),
389                                 vl->values, len);
390
391                 if (-1 == vl->values_len) {
392                         sfree (vl->values);
393                         return -1;
394                 }
395         }
396
397         if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
398         {
399                 double t = SvNV (*tmp);
400                 vl->time = DOUBLE_TO_CDTIME_T (t);
401         }
402
403         if (NULL != (tmp = hv_fetch (hash, "interval", 8, 0)))
404         {
405                 double t = SvNV (*tmp);
406                 vl->interval = DOUBLE_TO_CDTIME_T (t);
407         }
408
409         if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
410                 sstrncpy (vl->host, SvPV_nolen (*tmp), sizeof (vl->host));
411         else
412                 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
413
414         if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
415                 sstrncpy (vl->plugin, SvPV_nolen (*tmp), sizeof (vl->plugin));
416
417         if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
418                 sstrncpy (vl->plugin_instance, SvPV_nolen (*tmp),
419                                 sizeof (vl->plugin_instance));
420
421         if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
422                 sstrncpy (vl->type_instance, SvPV_nolen (*tmp),
423                                 sizeof (vl->type_instance));
424         return 0;
425 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
426
427 static int av2data_set (pTHX_ AV *array, char *name, data_set_t *ds)
428 {
429         int len, i;
430
431         if ((NULL == array) || (NULL == name) || (NULL == ds))
432                 return -1;
433
434         len = av_len (array);
435
436         if (-1 == len) {
437                 log_err ("av2data_set: Invalid data set.");
438                 return -1;
439         }
440
441         ds->ds = (data_source_t *)smalloc ((len + 1) * sizeof (data_source_t));
442         ds->ds_num = len + 1;
443
444         for (i = 0; i <= len; ++i) {
445                 SV **elem = av_fetch (array, i, 0);
446
447                 if (NULL == elem) {
448                         log_err ("av2data_set: Failed to fetch data source %i.", i);
449                         return -1;
450                 }
451
452                 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
453                         log_err ("av2data_set: Invalid data source.");
454                         return -1;
455                 }
456
457                 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds->ds[i]))
458                         return -1;
459
460                 log_debug ("av2data_set: "
461                                 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
462                                 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
463         }
464
465         sstrncpy (ds->type, name, sizeof (ds->type));
466         return 0;
467 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
468
469 /*
470  * notification:
471  * {
472  *   severity => $severity,
473  *   time     => $time,
474  *   message  => $msg,
475  *   host     => $host,
476  *   plugin   => $plugin,
477  *   type     => $type,
478  *   plugin_instance => $instance,
479  *   type_instance   => $type_instance,
480  *   meta     => [ { name => <name>, value => <value> }, ... ]
481  * }
482  */
483 static int av2notification_meta (pTHX_ AV *array, notification_meta_t **meta)
484 {
485         notification_meta_t **m = meta;
486
487         int len = av_len (array);
488         int i;
489
490         for (i = 0; i <= len; ++i) {
491                 SV **tmp = av_fetch (array, i, 0);
492                 HV  *hash;
493
494                 if (NULL == tmp)
495                         return -1;
496
497                 if (! (SvROK (*tmp) && (SVt_PVHV == SvTYPE (SvRV (*tmp))))) {
498                         log_warn ("av2notification_meta: Skipping invalid "
499                                         "meta information.");
500                         continue;
501                 }
502
503                 hash = (HV *)SvRV (*tmp);
504
505                 *m = (notification_meta_t *)smalloc (sizeof (**m));
506
507                 if (NULL == (tmp = hv_fetch (hash, "name", 4, 0))) {
508                         log_warn ("av2notification_meta: Skipping invalid "
509                                         "meta information.");
510                         free (*m);
511                         continue;
512                 }
513                 sstrncpy ((*m)->name, SvPV_nolen (*tmp), sizeof ((*m)->name));
514
515                 if (NULL == (tmp = hv_fetch (hash, "value", 5, 0))) {
516                         log_warn ("av2notification_meta: Skipping invalid "
517                                         "meta information.");
518                         free ((*m)->name);
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                 return;
1212
1213         c_ithread_destroy (ithread);
1214
1215         pthread_mutex_unlock (&perl_threads->mutex);
1216         return;
1217 } /* static void c_ithread_destructor (void *) */
1218
1219 /* must be called with perl_threads->mutex locked */
1220 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1221 {
1222         c_ithread_t *t = NULL;
1223         dTHXa (NULL);
1224
1225         assert (NULL != perl_threads);
1226
1227         t = (c_ithread_t *)smalloc (sizeof (c_ithread_t));
1228         memset (t, 0, sizeof (c_ithread_t));
1229
1230         t->interp = (NULL == base)
1231                 ? NULL
1232                 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1233
1234         aTHX = t->interp;
1235
1236         if ((NULL != base) && (NULL != PL_endav)) {
1237                 av_clear (PL_endav);
1238                 av_undef (PL_endav);
1239                 PL_endav = Nullav;
1240         }
1241
1242 #if COLLECT_DEBUG
1243         ++perl_threads->number_of_threads;
1244 #endif /* COLLECT_DEBUG */
1245
1246         t->next = NULL;
1247
1248         if (NULL == perl_threads->tail) {
1249                 perl_threads->head = t;
1250                 t->prev = NULL;
1251         }
1252         else {
1253                 perl_threads->tail->next = t;
1254                 t->prev = perl_threads->tail;
1255         }
1256
1257         perl_threads->tail = t;
1258
1259         pthread_setspecific (perl_thr_key, (const void *)t);
1260         return t;
1261 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1262
1263 /*
1264  * Filter chains implementation.
1265  */
1266
1267 static int fc_call (pTHX_ int type, int cb_type, pfc_user_data_t *data, ...)
1268 {
1269         int retvals = 0;
1270
1271         va_list ap;
1272         int ret = 0;
1273
1274         notification_meta_t **meta  = NULL;
1275         AV                   *pmeta = NULL;
1276
1277         dSP;
1278
1279         if ((type < 0) || (type >= FC_TYPES))
1280                 return -1;
1281
1282         if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1283                 return -1;
1284
1285         va_start (ap, data);
1286
1287         ENTER;
1288         SAVETMPS;
1289
1290         PUSHMARK (SP);
1291
1292         XPUSHs (sv_2mortal (newSViv ((IV)type)));
1293         XPUSHs (sv_2mortal (newSVpv (data->name, 0)));
1294         XPUSHs (sv_2mortal (newSViv ((IV)cb_type)));
1295
1296         if (FC_CB_CREATE == cb_type) {
1297                 /*
1298                  * $_[0] = $ci;
1299                  * $_[1] = $user_data;
1300                  */
1301                 oconfig_item_t *ci;
1302                 HV *config = newHV ();
1303
1304                 ci = va_arg (ap, oconfig_item_t *);
1305
1306                 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
1307                         hv_clear (config);
1308                         hv_undef (config);
1309                         config = (HV *)&PL_sv_undef;
1310                         ret = -1;
1311                 }
1312
1313                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
1314         }
1315         else if (FC_CB_DESTROY == cb_type) {
1316                 /*
1317                  * $_[1] = $user_data;
1318                  */
1319
1320                 /* nothing to be done - the user data pointer
1321                  * is pushed onto the stack later */
1322         }
1323         else if (FC_CB_EXEC == cb_type) {
1324                 /*
1325                  * $_[0] = $ds;
1326                  * $_[1] = $vl;
1327                  * $_[2] = $meta;
1328                  * $_[3] = $user_data;
1329                  */
1330                 data_set_t   *ds;
1331                 value_list_t *vl;
1332
1333                 AV *pds = newAV ();
1334                 HV *pvl = newHV ();
1335
1336                 ds   = va_arg (ap, data_set_t *);
1337                 vl   = va_arg (ap, value_list_t *);
1338                 meta = va_arg (ap, notification_meta_t **);
1339
1340                 if (0 != data_set2av (aTHX_ ds, pds)) {
1341                         av_clear (pds);
1342                         av_undef (pds);
1343                         pds = (AV *)&PL_sv_undef;
1344                         ret = -1;
1345                 }
1346
1347                 if (0 != value_list2hv (aTHX_ vl, ds, pvl)) {
1348                         hv_clear (pvl);
1349                         hv_undef (pvl);
1350                         pvl = (HV *)&PL_sv_undef;
1351                         ret = -1;
1352                 }
1353
1354                 if (NULL != meta) {
1355                         pmeta = newAV ();
1356
1357                         if (0 != notification_meta2av (aTHX_ *meta, pmeta)) {
1358                                 av_clear (pmeta);
1359                                 av_undef (pmeta);
1360                                 pmeta = (AV *)&PL_sv_undef;
1361                                 ret = -1;
1362                         }
1363                 }
1364                 else {
1365                         pmeta = (AV *)&PL_sv_undef;
1366                 }
1367
1368                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1369                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1370                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pmeta)));
1371         }
1372
1373         XPUSHs (sv_2mortal (newRV_inc (data->user_data)));
1374
1375         PUTBACK;
1376
1377         retvals = call_pv ("Collectd::fc_call", G_SCALAR);
1378
1379         if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1380                 assert (pmeta != NULL);
1381
1382                 plugin_notification_meta_free (*meta);
1383                 av2notification_meta (aTHX_ pmeta, meta);
1384         }
1385
1386         SPAGAIN;
1387         if (0 < retvals) {
1388                 SV *tmp = POPs;
1389
1390                 /* the exec callbacks return a status, while
1391                  * the others return a boolean value */
1392                 if (FC_CB_EXEC == cb_type)
1393                         ret = SvIV (tmp);
1394                 else if (! SvTRUE (tmp))
1395                         ret = -1;
1396         }
1397
1398         PUTBACK;
1399         FREETMPS;
1400         LEAVE;
1401
1402         va_end (ap);
1403         return ret;
1404 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1405
1406 static int fc_create (int type, const oconfig_item_t *ci, void **user_data)
1407 {
1408         pfc_user_data_t *data;
1409
1410         int ret = 0;
1411
1412         dTHX;
1413
1414         if (NULL == perl_threads)
1415                 return 0;
1416
1417         if (NULL == aTHX) {
1418                 c_ithread_t *t = NULL;
1419
1420                 pthread_mutex_lock (&perl_threads->mutex);
1421                 t = c_ithread_create (perl_threads->head->interp);
1422                 pthread_mutex_unlock (&perl_threads->mutex);
1423
1424                 aTHX = t->interp;
1425         }
1426
1427         log_debug ("fc_create: c_ithread: interp = %p (active threads: %i)",
1428                         aTHX, perl_threads->number_of_threads);
1429
1430         if ((1 != ci->values_num)
1431                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1432                 log_warn ("A \"%s\" block expects a single string argument.",
1433                                 (FC_MATCH == type) ? "Match" : "Target");
1434                 return -1;
1435         }
1436
1437         data = (pfc_user_data_t *)smalloc (sizeof (*data));
1438         data->name      = sstrdup (ci->values[0].value.string);
1439         data->user_data = newSV (0);
1440
1441         ret = fc_call (aTHX_ type, FC_CB_CREATE, data, ci);
1442
1443         if (0 != ret)
1444                 PFC_USER_DATA_FREE (data);
1445         else
1446                 *user_data = data;
1447         return ret;
1448 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1449
1450 static int fc_destroy (int type, void **user_data)
1451 {
1452         pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1453
1454         int ret = 0;
1455
1456         dTHX;
1457
1458         if ((NULL == perl_threads) || (NULL == data))
1459                 return 0;
1460
1461         if (NULL == aTHX) {
1462                 c_ithread_t *t = NULL;
1463
1464                 pthread_mutex_lock (&perl_threads->mutex);
1465                 t = c_ithread_create (perl_threads->head->interp);
1466                 pthread_mutex_unlock (&perl_threads->mutex);
1467
1468                 aTHX = t->interp;
1469         }
1470
1471         log_debug ("fc_destroy: c_ithread: interp = %p (active threads: %i)",
1472                         aTHX, perl_threads->number_of_threads);
1473
1474         ret = fc_call (aTHX_ type, FC_CB_DESTROY, data);
1475
1476         PFC_USER_DATA_FREE (data);
1477         *user_data = NULL;
1478         return ret;
1479 } /* static int fc_destroy (int, void **) */
1480
1481 static int fc_exec (int type, const data_set_t *ds, const value_list_t *vl,
1482                 notification_meta_t **meta, void **user_data)
1483 {
1484         pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1485
1486         dTHX;
1487
1488         if (NULL == perl_threads)
1489                 return 0;
1490
1491         assert (NULL != data);
1492
1493         if (NULL == aTHX) {
1494                 c_ithread_t *t = NULL;
1495
1496                 pthread_mutex_lock (&perl_threads->mutex);
1497                 t = c_ithread_create (perl_threads->head->interp);
1498                 pthread_mutex_unlock (&perl_threads->mutex);
1499
1500                 aTHX = t->interp;
1501         }
1502
1503         log_debug ("fc_exec: c_ithread: interp = %p (active threads: %i)",
1504                         aTHX, perl_threads->number_of_threads);
1505
1506         return fc_call (aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1507 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1508                 notification_meta_t **, void **) */
1509
1510 static int pmatch_create (const oconfig_item_t *ci, void **user_data)
1511 {
1512         return fc_create (FC_MATCH, ci, user_data);
1513 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1514
1515 static int pmatch_destroy (void **user_data)
1516 {
1517         return fc_destroy (FC_MATCH, user_data);
1518 } /* static int pmatch_destroy (void **) */
1519
1520 static int pmatch_match (const data_set_t *ds, const value_list_t *vl,
1521                 notification_meta_t **meta, void **user_data)
1522 {
1523         return fc_exec (FC_MATCH, ds, vl, meta, user_data);
1524 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1525                 notification_meta_t **, void **) */
1526
1527 static match_proc_t pmatch = {
1528         pmatch_create, pmatch_destroy, pmatch_match
1529 };
1530
1531 static int ptarget_create (const oconfig_item_t *ci, void **user_data)
1532 {
1533         return fc_create (FC_TARGET, ci, user_data);
1534 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1535
1536 static int ptarget_destroy (void **user_data)
1537 {
1538         return fc_destroy (FC_TARGET, user_data);
1539 } /* static int ptarget_destroy (void **) */
1540
1541 static int ptarget_invoke (const data_set_t *ds, value_list_t *vl,
1542                 notification_meta_t **meta, void **user_data)
1543 {
1544         return fc_exec (FC_TARGET, ds, vl, meta, user_data);
1545 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1546                 notification_meta_t **, void **) */
1547
1548 static target_proc_t ptarget = {
1549         ptarget_create, ptarget_destroy, ptarget_invoke
1550 };
1551
1552 /*
1553  * Exported Perl API.
1554  */
1555
1556 /*
1557  * Collectd::plugin_register_data_set (type, dataset).
1558  *
1559  * type:
1560  *   type of the dataset
1561  *
1562  * dataset:
1563  *   dataset to be registered
1564  */
1565 static XS (Collectd_plugin_register_ds)
1566 {
1567         SV  *data = NULL;
1568         int ret   = 0;
1569
1570         dXSARGS;
1571
1572         log_warn ("Using plugin_register() to register new data-sets is "
1573                         "deprecated - add new entries to a custom types.db instead.");
1574
1575         if (2 != items) {
1576                 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1577                 XSRETURN_EMPTY;
1578         }
1579
1580         log_debug ("Collectd::plugin_register_data_set: "
1581                         "type = \"%s\", dataset = \"%s\"",
1582                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1583
1584         data = ST (1);
1585
1586         if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1587                 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1588                                 (AV *)SvRV (data));
1589         }
1590         else {
1591                 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1592                 XSRETURN_EMPTY;
1593         }
1594
1595         if (0 == ret)
1596                 XSRETURN_YES;
1597         else
1598                 XSRETURN_EMPTY;
1599 } /* static XS (Collectd_plugin_register_ds) */
1600
1601 /*
1602  * Collectd::plugin_unregister_data_set (type).
1603  *
1604  * type:
1605  *   type of the dataset
1606  */
1607 static XS (Collectd_plugin_unregister_ds)
1608 {
1609         dXSARGS;
1610
1611         if (1 != items) {
1612                 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1613                 XSRETURN_EMPTY;
1614         }
1615
1616         log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1617                         SvPV_nolen (ST (0)));
1618
1619         if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1620                 XSRETURN_YES;
1621         else
1622                 XSRETURN_EMPTY;
1623 } /* static XS (Collectd_plugin_register_ds) */
1624
1625 /*
1626  * Collectd::plugin_dispatch_values (name, values).
1627  *
1628  * name:
1629  *   name of the plugin
1630  *
1631  * values:
1632  *   value list to submit
1633  */
1634 static XS (Collectd_plugin_dispatch_values)
1635 {
1636         SV *values     = NULL;
1637
1638         int ret = 0;
1639
1640         dXSARGS;
1641
1642         if (1 != items) {
1643                 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1644                 XSRETURN_EMPTY;
1645         }
1646
1647         log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1648                         SvPV_nolen (ST (/* stack index = */ 0)));
1649
1650         values = ST (/* stack index = */ 0);
1651
1652         /* Make sure the argument is a hash reference. */
1653         if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1654                 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1655                 XSRETURN_EMPTY;
1656         }
1657
1658         if (NULL == values)
1659                 XSRETURN_EMPTY;
1660
1661         ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1662
1663         if (0 == ret)
1664                 XSRETURN_YES;
1665         else
1666                 XSRETURN_EMPTY;
1667 } /* static XS (Collectd_plugin_dispatch_values) */
1668
1669 /*
1670  * Collectd::plugin_get_interval ().
1671  */
1672 static XS (Collectd_plugin_get_interval)
1673 {
1674         dXSARGS;
1675
1676         /* make sure we don't get any unused variable warnings for 'items';
1677          * don't abort, though */
1678         if (items)
1679                 log_err ("Usage: Collectd::plugin_get_interval()");
1680
1681         XSRETURN_NV ((NV) CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
1682 } /* static XS (Collectd_plugin_get_interval) */
1683
1684 /* Collectd::plugin_write (plugin, ds, vl).
1685  *
1686  * plugin:
1687  *   name of the plugin to call, may be 'undef'
1688  *
1689  * ds:
1690  *   data-set that describes the submitted values, may be 'undef'
1691  *
1692  * vl:
1693  *   value-list to be written
1694  */
1695 static XS (Collectd__plugin_write)
1696 {
1697         char *plugin;
1698         SV   *ds, *vl;
1699         AV   *ds_array;
1700
1701         int ret;
1702
1703         dXSARGS;
1704
1705         if (3 != items) {
1706                 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1707                 XSRETURN_EMPTY;
1708         }
1709
1710         log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1711                         SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1712                         SvPV_nolen (ST (2)));
1713
1714         if (! SvOK (ST (0)))
1715                 plugin = NULL;
1716         else
1717                 plugin = SvPV_nolen (ST (0));
1718
1719         ds = ST (1);
1720         if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1721                 ds_array = (AV *)SvRV (ds);
1722         else if (! SvOK (ds))
1723                 ds_array = NULL;
1724         else {
1725                 log_err ("Collectd::plugin_write: Invalid data-set.");
1726                 XSRETURN_EMPTY;
1727         }
1728
1729         vl = ST (2);
1730         if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1731                 log_err ("Collectd::plugin_write: Invalid value-list.");
1732                 XSRETURN_EMPTY;
1733         }
1734
1735         ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1736
1737         if (0 == ret)
1738                 XSRETURN_YES;
1739         else
1740                 XSRETURN_EMPTY;
1741 } /* static XS (Collectd__plugin_write) */
1742
1743 /*
1744  * Collectd::_plugin_flush (plugin, timeout, identifier).
1745  *
1746  * plugin:
1747  *   name of the plugin to flush
1748  *
1749  * timeout:
1750  *   timeout to use when flushing the data
1751  *
1752  * identifier:
1753  *   data-set identifier to flush
1754  */
1755 static XS (Collectd__plugin_flush)
1756 {
1757         char *plugin  = NULL;
1758         int   timeout = -1;
1759         char *id      = NULL;
1760
1761         dXSARGS;
1762
1763         if (3 != items) {
1764                 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1765                 XSRETURN_EMPTY;
1766         }
1767
1768         if (SvOK (ST (0)))
1769                 plugin = SvPV_nolen (ST (0));
1770
1771         if (SvOK (ST (1)))
1772                 timeout = (int)SvIV (ST (1));
1773
1774         if (SvOK (ST (2)))
1775                 id = SvPV_nolen (ST (2));
1776
1777         log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1778                         "id = \"%s\"", plugin, timeout, id);
1779
1780         if (0 == plugin_flush (plugin, timeout, id))
1781                 XSRETURN_YES;
1782         else
1783                 XSRETURN_EMPTY;
1784 } /* static XS (Collectd__plugin_flush) */
1785
1786 /*
1787  * Collectd::plugin_dispatch_notification (notif).
1788  *
1789  * notif:
1790  *   notification to dispatch
1791  */
1792 static XS (Collectd_plugin_dispatch_notification)
1793 {
1794         SV *notif = NULL;
1795
1796         int ret = 0;
1797
1798         dXSARGS;
1799
1800         if (1 != items) {
1801                 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
1802                 XSRETURN_EMPTY;
1803         }
1804
1805         log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1806                         SvPV_nolen (ST (0)));
1807
1808         notif = ST (0);
1809
1810         if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
1811                 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
1812                 XSRETURN_EMPTY;
1813         }
1814
1815         ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
1816
1817         if (0 == ret)
1818                 XSRETURN_YES;
1819         else
1820                 XSRETURN_EMPTY;
1821 } /* static XS (Collectd_plugin_dispatch_notification) */
1822
1823 /*
1824  * Collectd::plugin_log (level, message).
1825  *
1826  * level:
1827  *   log level (LOG_DEBUG, ... LOG_ERR)
1828  *
1829  * message:
1830  *   log message
1831  */
1832 static XS (Collectd_plugin_log)
1833 {
1834         dXSARGS;
1835
1836         if (2 != items) {
1837                 log_err ("Usage: Collectd::plugin_log(level, message)");
1838                 XSRETURN_EMPTY;
1839         }
1840
1841         plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
1842         XSRETURN_YES;
1843 } /* static XS (Collectd_plugin_log) */
1844
1845 /*
1846  * Collectd::_fc_register (type, name)
1847  *
1848  * type:
1849  *   match | target
1850  *
1851  * name:
1852  *   name of the match
1853  */
1854 static XS (Collectd__fc_register)
1855 {
1856         int   type;
1857         char *name;
1858
1859         int ret = 0;
1860
1861         dXSARGS;
1862
1863         if (2 != items) {
1864                 log_err ("Usage: Collectd::_fc_register(type, name)");
1865                 XSRETURN_EMPTY;
1866         }
1867
1868         type = SvIV (ST (0));
1869         name = SvPV_nolen (ST (1));
1870
1871         if (FC_MATCH == type)
1872                 ret = fc_register_match (name, pmatch);
1873         else if (FC_TARGET == type)
1874                 ret = fc_register_target (name, ptarget);
1875
1876         if (0 == ret)
1877                 XSRETURN_YES;
1878         else
1879                 XSRETURN_EMPTY;
1880 } /* static XS (Collectd_fc_register) */
1881
1882 /*
1883  * Collectd::call_by_name (...).
1884  *
1885  * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1886  */
1887 static XS (Collectd_call_by_name)
1888 {
1889         SV   *tmp  = NULL;
1890         char *name = NULL;
1891
1892         if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
1893                 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
1894                 CLEAR_STACK_FRAME;
1895                 return;
1896         }
1897
1898         name = SvPV_nolen (tmp);
1899
1900         if (NULL == get_cv (name, 0)) {
1901                 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
1902                 CLEAR_STACK_FRAME;
1903                 return;
1904         }
1905
1906         /* simply pass on the subroutine call without touching the stack,
1907          * thus leaving any arguments and return values in place */
1908         call_pv (name, 0);
1909 } /* static XS (Collectd_call_by_name) */
1910
1911 /*
1912  * Interface to collectd.
1913  */
1914
1915 static int perl_init (void)
1916 {
1917         dTHX;
1918
1919         if (NULL == perl_threads)
1920                 return 0;
1921
1922         if (NULL == aTHX) {
1923                 c_ithread_t *t = NULL;
1924
1925                 pthread_mutex_lock (&perl_threads->mutex);
1926                 t = c_ithread_create (perl_threads->head->interp);
1927                 pthread_mutex_unlock (&perl_threads->mutex);
1928
1929                 aTHX = t->interp;
1930         }
1931
1932         log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1933                         aTHX, perl_threads->number_of_threads);
1934         return pplugin_call_all (aTHX_ PLUGIN_INIT);
1935 } /* static int perl_init (void) */
1936
1937 static int perl_read (void)
1938 {
1939         dTHX;
1940
1941         if (NULL == perl_threads)
1942                 return 0;
1943
1944         if (NULL == aTHX) {
1945                 c_ithread_t *t = NULL;
1946
1947                 pthread_mutex_lock (&perl_threads->mutex);
1948                 t = c_ithread_create (perl_threads->head->interp);
1949                 pthread_mutex_unlock (&perl_threads->mutex);
1950
1951                 aTHX = t->interp;
1952         }
1953
1954         /* Assert that we're not running as the base thread. Otherwise, we might
1955          * run into concurrency issues with c_ithread_create(). See
1956          * https://github.com/collectd/collectd/issues/9 for details. */
1957         assert (aTHX != perl_threads->head->interp);
1958
1959         log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1960                         aTHX, perl_threads->number_of_threads);
1961         return pplugin_call_all (aTHX_ PLUGIN_READ);
1962 } /* static int perl_read (void) */
1963
1964 static int perl_write (const data_set_t *ds, const value_list_t *vl,
1965                 user_data_t __attribute__((unused)) *user_data)
1966 {
1967         int status;
1968         dTHX;
1969
1970         if (NULL == perl_threads)
1971                 return 0;
1972
1973         if (NULL == aTHX) {
1974                 c_ithread_t *t = NULL;
1975
1976                 pthread_mutex_lock (&perl_threads->mutex);
1977                 t = c_ithread_create (perl_threads->head->interp);
1978                 pthread_mutex_unlock (&perl_threads->mutex);
1979
1980                 aTHX = t->interp;
1981         }
1982
1983         /* Lock the base thread if this is not called from one of the read threads
1984          * to avoid race conditions with c_ithread_create(). See
1985          * https://github.com/collectd/collectd/issues/9 for details. */
1986         if (aTHX == perl_threads->head->interp)
1987                 pthread_mutex_lock (&perl_threads->mutex);
1988
1989         log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
1990                         aTHX, perl_threads->number_of_threads);
1991         status = pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
1992
1993         if (aTHX == perl_threads->head->interp)
1994                 pthread_mutex_unlock (&perl_threads->mutex);
1995
1996         return status;
1997 } /* static int perl_write (const data_set_t *, const value_list_t *) */
1998
1999 static void perl_log (int level, const char *msg,
2000                 user_data_t __attribute__((unused)) *user_data)
2001 {
2002         dTHX;
2003
2004         if (NULL == perl_threads)
2005                 return;
2006
2007         if (NULL == aTHX) {
2008                 c_ithread_t *t = NULL;
2009
2010                 pthread_mutex_lock (&perl_threads->mutex);
2011                 t = c_ithread_create (perl_threads->head->interp);
2012                 pthread_mutex_unlock (&perl_threads->mutex);
2013
2014                 aTHX = t->interp;
2015         }
2016
2017         /* Lock the base thread if this is not called from one of the read threads
2018          * to avoid race conditions with c_ithread_create(). See
2019          * https://github.com/collectd/collectd/issues/9 for details. */
2020         if (aTHX == perl_threads->head->interp)
2021                 pthread_mutex_lock (&perl_threads->mutex);
2022
2023         pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
2024
2025         if (aTHX == perl_threads->head->interp)
2026                 pthread_mutex_unlock (&perl_threads->mutex);
2027
2028         return;
2029 } /* static void perl_log (int, const char *) */
2030
2031 static int perl_notify (const notification_t *notif,
2032                 user_data_t __attribute__((unused)) *user_data)
2033 {
2034         dTHX;
2035
2036         if (NULL == perl_threads)
2037                 return 0;
2038
2039         if (NULL == aTHX) {
2040                 c_ithread_t *t = NULL;
2041
2042                 pthread_mutex_lock (&perl_threads->mutex);
2043                 t = c_ithread_create (perl_threads->head->interp);
2044                 pthread_mutex_unlock (&perl_threads->mutex);
2045
2046                 aTHX = t->interp;
2047         }
2048         return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
2049 } /* static int perl_notify (const notification_t *) */
2050
2051 static int perl_flush (cdtime_t timeout, const char *identifier,
2052                 user_data_t __attribute__((unused)) *user_data)
2053 {
2054         dTHX;
2055
2056         if (NULL == perl_threads)
2057                 return 0;
2058
2059         if (NULL == aTHX) {
2060                 c_ithread_t *t = NULL;
2061
2062                 pthread_mutex_lock (&perl_threads->mutex);
2063                 t = c_ithread_create (perl_threads->head->interp);
2064                 pthread_mutex_unlock (&perl_threads->mutex);
2065
2066                 aTHX = t->interp;
2067         }
2068         return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout, identifier);
2069 } /* static int perl_flush (const int) */
2070
2071 static int perl_shutdown (void)
2072 {
2073         c_ithread_t *t = NULL;
2074
2075         int ret = 0;
2076
2077         dTHX;
2078
2079         plugin_unregister_complex_config ("perl");
2080
2081         if (NULL == perl_threads)
2082                 return 0;
2083
2084         if (NULL == aTHX) {
2085                 c_ithread_t *t = NULL;
2086
2087                 pthread_mutex_lock (&perl_threads->mutex);
2088                 t = c_ithread_create (perl_threads->head->interp);
2089                 pthread_mutex_unlock (&perl_threads->mutex);
2090
2091                 aTHX = t->interp;
2092         }
2093
2094         log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2095                         aTHX, perl_threads->number_of_threads);
2096
2097         plugin_unregister_log ("perl");
2098         plugin_unregister_notification ("perl");
2099         plugin_unregister_init ("perl");
2100         plugin_unregister_read ("perl");
2101         plugin_unregister_write ("perl");
2102         plugin_unregister_flush ("perl");
2103
2104         ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
2105
2106         pthread_mutex_lock (&perl_threads->mutex);
2107         t = perl_threads->tail;
2108
2109         while (NULL != t) {
2110                 c_ithread_t *thr = t;
2111
2112                 /* the pointer has to be advanced before destroying
2113                  * the thread as this will free the memory */
2114                 t = t->prev;
2115
2116                 c_ithread_destroy (thr);
2117         }
2118
2119         pthread_mutex_unlock (&perl_threads->mutex);
2120         pthread_mutex_destroy (&perl_threads->mutex);
2121
2122         sfree (perl_threads);
2123
2124         pthread_key_delete (perl_thr_key);
2125
2126         PERL_SYS_TERM ();
2127
2128         plugin_unregister_shutdown ("perl");
2129         return ret;
2130 } /* static void perl_shutdown (void) */
2131
2132 /*
2133  * Access functions for global variables.
2134  *
2135  * These functions implement the "magic" used to access
2136  * the global variables from Perl.
2137  */
2138
2139 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
2140 {
2141         char *pv = mg->mg_ptr;
2142         sv_setpv (var, pv);
2143         return 0;
2144 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2145
2146 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
2147 {
2148         char *pv = mg->mg_ptr;
2149         sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
2150         return 0;
2151 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2152
2153 static int g_interval_get (pTHX_ SV *var, MAGIC *mg)
2154 {
2155         log_warn ("Accessing $interval_g is deprecated (and might not "
2156                         "give the desired results) - plugin_get_interval() should "
2157                         "be used instead.");
2158         sv_setnv (var, CDTIME_T_TO_DOUBLE (interval_g));
2159         return 0;
2160 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2161
2162 static int g_interval_set (pTHX_ SV *var, MAGIC *mg)
2163 {
2164         double nv = (double)SvNV (var);
2165         log_warn ("Accessing $interval_g is deprecated (and might not "
2166                         "give the desired results) - plugin_get_interval() should "
2167                         "be used instead.");
2168         interval_g = DOUBLE_TO_CDTIME_T (nv);
2169         return 0;
2170 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2171
2172 static MGVTBL g_pv_vtbl = {
2173         g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2174 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2175                 , NULL
2176 #endif
2177 };
2178 static MGVTBL g_interval_vtbl = {
2179         g_interval_get, g_interval_set, NULL, NULL, NULL, NULL, NULL
2180 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2181                 , NULL
2182 #endif
2183 };
2184
2185 /* bootstrap the Collectd module */
2186 static void xs_init (pTHX)
2187 {
2188         HV   *stash = NULL;
2189         SV   *tmp   = NULL;
2190         char *file  = __FILE__;
2191
2192         int i = 0;
2193
2194         dXSUB_SYS;
2195
2196         /* enable usage of Perl modules using shared libraries */
2197         newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2198
2199         /* register API */
2200         for (i = 0; NULL != api[i].f; ++i)
2201                 newXS (api[i].name, api[i].f, file);
2202
2203         stash = gv_stashpv ("Collectd", 1);
2204
2205         /* export "constants" */
2206         for (i = 0; '\0' != constants[i].name[0]; ++i)
2207                 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
2208
2209         /* export global variables
2210          * by adding "magic" to the SV's representing the globale variables
2211          * perl is able to automagically call the get/set function when
2212          * accessing any such variable (this is basically the same as using
2213          * tie() in Perl) */
2214         /* global strings */
2215         for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
2216                 tmp = get_sv (g_strings[i].name, 1);
2217                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
2218                                 g_strings[i].var, 0);
2219         }
2220
2221         tmp = get_sv ("Collectd::interval_g", /* create = */ 1);
2222         sv_magicext (tmp, NULL, /* how = */ PERL_MAGIC_ext,
2223                         /* vtbl = */ &g_interval_vtbl,
2224                         /* name = */ NULL, /* namelen = */ 0);
2225
2226         return;
2227 } /* static void xs_init (pTHX) */
2228
2229 /* Initialize the global Perl interpreter. */
2230 static int init_pi (int argc, char **argv)
2231 {
2232         dTHXa (NULL);
2233
2234         if (NULL != perl_threads)
2235                 return 0;
2236
2237         log_info ("Initializing Perl interpreter...");
2238 #if COLLECT_DEBUG
2239         {
2240                 int i = 0;
2241
2242                 for (i = 0; i < argc; ++i)
2243                         log_debug ("argv[%i] = \"%s\"", i, argv[i]);
2244         }
2245 #endif /* COLLECT_DEBUG */
2246
2247         if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
2248                 log_err ("init_pi: pthread_key_create failed");
2249
2250                 /* this must not happen - cowardly giving up if it does */
2251                 return -1;
2252         }
2253
2254 #ifdef __FreeBSD__
2255         /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2256          * triggers a "value computed is not used" warning by gcc. */
2257         (void)
2258 #endif
2259         PERL_SYS_INIT3 (&argc, &argv, &environ);
2260
2261         perl_threads = (c_ithread_list_t *)smalloc (sizeof (c_ithread_list_t));
2262         memset (perl_threads, 0, sizeof (c_ithread_list_t));
2263
2264         pthread_mutex_init (&perl_threads->mutex, NULL);
2265         /* locking the mutex should not be necessary at this point
2266          * but let's just do it for the sake of completeness */
2267         pthread_mutex_lock (&perl_threads->mutex);
2268
2269         perl_threads->head = c_ithread_create (NULL);
2270         perl_threads->tail = perl_threads->head;
2271
2272         if (NULL == (perl_threads->head->interp = perl_alloc ())) {
2273                 log_err ("init_pi: Not enough memory.");
2274                 exit (3);
2275         }
2276
2277         aTHX = perl_threads->head->interp;
2278         pthread_mutex_unlock (&perl_threads->mutex);
2279
2280         perl_construct (aTHX);
2281
2282         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2283
2284         if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
2285                 SV *err = get_sv ("@", 1);
2286                 log_err ("init_pi: Unable to bootstrap Collectd: %s",
2287                                 SvPV_nolen (err));
2288
2289                 perl_destruct (perl_threads->head->interp);
2290                 perl_free (perl_threads->head->interp);
2291                 sfree (perl_threads);
2292
2293                 pthread_key_delete (perl_thr_key);
2294                 return -1;
2295         }
2296
2297         /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2298         sv_setpv (get_sv ("0", 0), "collectd");
2299
2300         perl_run (aTHX);
2301
2302         plugin_register_log ("perl", perl_log, /* user_data = */ NULL);
2303         plugin_register_notification ("perl", perl_notify,
2304                         /* user_data = */ NULL);
2305         plugin_register_init ("perl", perl_init);
2306
2307         plugin_register_read ("perl", perl_read);
2308
2309         plugin_register_write ("perl", perl_write, /* user_data = */ NULL);
2310         plugin_register_flush ("perl", perl_flush, /* user_data = */ NULL);
2311         plugin_register_shutdown ("perl", perl_shutdown);
2312         return 0;
2313 } /* static int init_pi (const char **, const int) */
2314
2315 /*
2316  * LoadPlugin "<Plugin>"
2317  */
2318 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
2319 {
2320         char module_name[DATA_MAX_NAME_LEN];
2321
2322         char *value = NULL;
2323
2324         if ((0 != ci->children_num) || (1 != ci->values_num)
2325                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2326                 log_err ("LoadPlugin expects a single string argument.");
2327                 return 1;
2328         }
2329
2330         value = ci->values[0].value.string;
2331
2332         if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
2333                 log_err ("Invalid module name %s", value);
2334                 return (1);
2335         }
2336
2337         if (0 != init_pi (perl_argc, perl_argv))
2338                 return -1;
2339
2340         assert (NULL != perl_threads);
2341         assert (NULL != perl_threads->head);
2342
2343         aTHX = perl_threads->head->interp;
2344
2345         log_debug ("perl_config: loading perl plugin \"%s\"", value);
2346         load_module (PERL_LOADMOD_NOIMPORT,
2347                         newSVpv (module_name, strlen (module_name)), Nullsv);
2348         return 0;
2349 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2350
2351 /*
2352  * BaseName "<Name>"
2353  */
2354 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
2355 {
2356         char *value = NULL;
2357
2358         if ((0 != ci->children_num) || (1 != ci->values_num)
2359                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2360                 log_err ("BaseName expects a single string argument.");
2361                 return 1;
2362         }
2363
2364         value = ci->values[0].value.string;
2365
2366         log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
2367         sstrncpy (base_name, value, sizeof (base_name));
2368         return 0;
2369 } /* static int perl_config_basename (oconfig_item_it *) */
2370
2371 /*
2372  * EnableDebugger "<Package>"|""
2373  */
2374 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
2375 {
2376         char *value = NULL;
2377
2378         if ((0 != ci->children_num) || (1 != ci->values_num)
2379                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2380                 log_err ("EnableDebugger expects a single string argument.");
2381                 return 1;
2382         }
2383
2384         if (NULL != perl_threads) {
2385                 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
2386                 return 1;
2387         }
2388
2389         value = ci->values[0].value.string;
2390
2391         perl_argv = (char **)realloc (perl_argv,
2392                         (++perl_argc + 1) * sizeof (char *));
2393
2394         if (NULL == perl_argv) {
2395                 log_err ("perl_config: Not enough memory.");
2396                 exit (3);
2397         }
2398
2399         if ('\0' == value[0]) {
2400                 perl_argv[perl_argc - 1] = "-d";
2401         }
2402         else {
2403                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 4);
2404                 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
2405                 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
2406         }
2407
2408         perl_argv[perl_argc] = NULL;
2409         return 0;
2410 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2411
2412 /*
2413  * IncludeDir "<Dir>"
2414  */
2415 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
2416 {
2417         char *value = NULL;
2418
2419         if ((0 != ci->children_num) || (1 != ci->values_num)
2420                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2421                 log_err ("IncludeDir expects a single string argument.");
2422                 return 1;
2423         }
2424
2425         value = ci->values[0].value.string;
2426
2427         if (NULL == aTHX) {
2428                 perl_argv = (char **)realloc (perl_argv,
2429                                 (++perl_argc + 1) * sizeof (char *));
2430
2431                 if (NULL == perl_argv) {
2432                         log_err ("perl_config: Not enough memory.");
2433                         exit (3);
2434                 }
2435
2436                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 3);
2437                 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2438                 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
2439
2440                 perl_argv[perl_argc] = NULL;
2441         }
2442         else {
2443                 /* prepend the directory to @INC */
2444                 av_unshift (GvAVn (PL_incgv), 1);
2445                 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
2446         }
2447         return 0;
2448 } /* static int perl_config_includedir (oconfig_item_it *) */
2449
2450 /*
2451  * <Plugin> block
2452  */
2453 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2454 {
2455         int retvals = 0;
2456         int ret     = 0;
2457
2458         char *plugin;
2459         HV   *config;
2460
2461         dSP;
2462
2463         if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2464                 log_err ("LoadPlugin expects a single string argument.");
2465                 return 1;
2466         }
2467
2468         plugin = ci->values[0].value.string;
2469         config = newHV ();
2470
2471         if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2472                 hv_clear (config);
2473                 hv_undef (config);
2474
2475                 log_err ("Unable to convert configuration to a Perl hash value.");
2476                 config = (HV *)&PL_sv_undef;
2477         }
2478
2479         ENTER;
2480         SAVETMPS;
2481
2482         PUSHMARK (SP);
2483
2484         XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2485         XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2486
2487         PUTBACK;
2488
2489         retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2490
2491         SPAGAIN;
2492         if (0 < retvals) {
2493                 SV *tmp = POPs;
2494                 if (! SvTRUE (tmp))
2495                         ret = 1;
2496         }
2497         else
2498                 ret = 1;
2499
2500         PUTBACK;
2501         FREETMPS;
2502         LEAVE;
2503         return ret;
2504 } /* static int perl_config_plugin (oconfig_item_it *) */
2505
2506 static int perl_config (oconfig_item_t *ci)
2507 {
2508         int status = 0;
2509         int i = 0;
2510
2511         dTHXa (NULL);
2512
2513         for (i = 0; i < ci->children_num; ++i) {
2514                 oconfig_item_t *c = ci->children + i;
2515                 int current_status = 0;
2516
2517                 if (NULL != perl_threads)
2518                         aTHX = PERL_GET_CONTEXT;
2519
2520                 if (0 == strcasecmp (c->key, "LoadPlugin"))
2521                         current_status = perl_config_loadplugin (aTHX_ c);
2522                 else if (0 == strcasecmp (c->key, "BaseName"))
2523                         current_status = perl_config_basename (aTHX_ c);
2524                 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2525                         current_status = perl_config_enabledebugger (aTHX_ c);
2526                 else if (0 == strcasecmp (c->key, "IncludeDir"))
2527                         current_status = perl_config_includedir (aTHX_ c);
2528                 else if (0 == strcasecmp (c->key, "Plugin"))
2529                         current_status = perl_config_plugin (aTHX_ c);
2530                 else
2531                 {
2532                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
2533                         current_status = 0;
2534                 }
2535
2536                 /* fatal error - it's up to perl_config_* to clean up */
2537                 if (0 > current_status) {
2538                         log_err ("Configuration failed with a fatal error - "
2539                                         "plugin disabled!");
2540                         return current_status;
2541                 }
2542
2543                 status += current_status;
2544         }
2545         return status;
2546 } /* static int perl_config (oconfig_item_t *) */
2547
2548 void module_register (void)
2549 {
2550         perl_argc = 4;
2551         perl_argv = (char **)smalloc ((perl_argc + 1) * sizeof (char *));
2552
2553         /* default options for the Perl interpreter */
2554         perl_argv[0] = "";
2555         perl_argv[1] = "-MCollectd";
2556         perl_argv[2] = "-e";
2557         perl_argv[3] = "1";
2558         perl_argv[4] = NULL;
2559
2560         plugin_register_complex_config ("perl", perl_config);
2561         return;
2562 } /* void module_register (void) */
2563
2564 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
2565