Code

7ab45d8d758dd7841554ff22fe3d2cd3fe563b7e
[collectd.git] / src / perl.c
1 /**
2  * collectd - src/perl.c
3  * Copyright (C) 2007-2009  Sebastian Harl
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Author:
19  *   Sebastian Harl <sh at tokkee.org>
20  **/
22 /*
23  * This plugin embeds a Perl interpreter into collectd and provides an
24  * interface for collectd plugins written in perl.
25  */
27 /* do not automatically get the thread specific perl interpreter */
28 #define PERL_NO_GET_CONTEXT
30 #define DONT_POISON_SPRINTF_YET 1
31 #include "collectd.h"
32 #undef DONT_POISON_SPRINTF_YET
34 #include "configfile.h"
36 #include <EXTERN.h>
37 #include <perl.h>
39 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
40 # pragma GCC poison sprintf
41 #endif
43 #include <XSUB.h>
45 /* Some versions of Perl define their own version of DEBUG... :-/ */
46 #ifdef DEBUG
47 # undef DEBUG
48 #endif /* DEBUG */
50 /* ... while we want the definition found in plugin.h. */
51 #include "plugin.h"
52 #include "common.h"
54 #include "filter_chain.h"
56 #include <pthread.h>
58 #if !defined(USE_ITHREADS)
59 # error "Perl does not support ithreads!"
60 #endif /* !defined(USE_ITHREADS) */
62 /* clear the Perl sub's stack frame
63  * (this should only be used inside an XSUB) */
64 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
66 #define PLUGIN_INIT     0
67 #define PLUGIN_READ     1
68 #define PLUGIN_WRITE    2
69 #define PLUGIN_SHUTDOWN 3
70 #define PLUGIN_LOG      4
71 #define PLUGIN_NOTIF    5
72 #define PLUGIN_FLUSH    6
74 #define PLUGIN_TYPES    7
76 #define PLUGIN_CONFIG   254
77 #define PLUGIN_DATASET  255
79 #define FC_MATCH  0
80 #define FC_TARGET 1
82 #define FC_TYPES  2
84 #define FC_CB_CREATE  0
85 #define FC_CB_DESTROY 1
86 #define FC_CB_EXEC    2
88 #define FC_CB_TYPES   3
90 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
91 #define log_info(...) INFO ("perl: " __VA_ARGS__)
92 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
93 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
95 /* this is defined in DynaLoader.a */
96 void boot_DynaLoader (PerlInterpreter *, CV *);
98 static XS (Collectd_plugin_register_ds);
99 static XS (Collectd_plugin_unregister_ds);
100 static XS (Collectd_plugin_dispatch_values);
101 static XS (Collectd__plugin_write);
102 static XS (Collectd__plugin_flush);
103 static XS (Collectd_plugin_dispatch_notification);
104 static XS (Collectd_plugin_log);
105 static XS (Collectd__fc_register);
106 static XS (Collectd_call_by_name);
108 /*
109  * private data types
110  */
112 typedef struct c_ithread_s {
113         /* the thread's Perl interpreter */
114         PerlInterpreter *interp;
115         _Bool running;  /* thread is inside pi */
116         _Bool shutdown;
117         pthread_t pthread;
119         /* double linked list of threads */
120         struct c_ithread_s *prev;
121         struct c_ithread_s *next;
122 } c_ithread_t;
124 typedef struct {
125         c_ithread_t *head;
126         c_ithread_t *tail;
128 #if COLLECT_DEBUG
129         /* some usage stats */
130         int number_of_threads;
131 #endif /* COLLECT_DEBUG */
133         pthread_mutex_t mutex;
134 } c_ithread_list_t;
136 /* name / user_data for Perl matches / targets */
137 typedef struct {
138         char *name;
139         SV   *user_data;
140 } pfc_user_data_t;
142 #define PFC_USER_DATA_FREE(data) \
143         do { \
144                 sfree ((data)->name); \
145                 if (NULL != (data)->user_data) \
146                         sv_free ((data)->user_data); \
147                 sfree (data); \
148         } while (0)
150 /*
151  * Public variable
152  */
153 extern char **environ;
155 /*
156  * private variables
157  */
159 /* if perl_threads != NULL perl_threads->head must
160  * point to the "base" thread */
161 static c_ithread_list_t *perl_threads = NULL;
163 /* the key used to store each pthread's ithread */
164 static pthread_key_t perl_thr_key;
166 static int    perl_argc = 0;
167 static char **perl_argv = NULL;
169 static char base_name[DATA_MAX_NAME_LEN] = "";
171 static struct {
172         char name[64];
173         XS ((*f));
174 } api[] =
176         { "Collectd::plugin_register_data_set",   Collectd_plugin_register_ds },
177         { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
178         { "Collectd::plugin_dispatch_values",     Collectd_plugin_dispatch_values },
179         { "Collectd::_plugin_write",              Collectd__plugin_write },
180         { "Collectd::_plugin_flush",              Collectd__plugin_flush },
181         { "Collectd::plugin_dispatch_notification",
182                 Collectd_plugin_dispatch_notification },
183         { "Collectd::plugin_log",                 Collectd_plugin_log },
184         { "Collectd::_fc_register",               Collectd__fc_register },
185         { "Collectd::call_by_name",               Collectd_call_by_name },
186         { "", NULL }
187 };
189 struct {
190         char name[64];
191         int  value;
192 } constants[] =
194         { "Collectd::TYPE_INIT",          PLUGIN_INIT },
195         { "Collectd::TYPE_READ",          PLUGIN_READ },
196         { "Collectd::TYPE_WRITE",         PLUGIN_WRITE },
197         { "Collectd::TYPE_SHUTDOWN",      PLUGIN_SHUTDOWN },
198         { "Collectd::TYPE_LOG",           PLUGIN_LOG },
199         { "Collectd::TYPE_NOTIF",         PLUGIN_NOTIF },
200         { "Collectd::TYPE_FLUSH",         PLUGIN_FLUSH },
201         { "Collectd::TYPE_CONFIG",        PLUGIN_CONFIG },
202         { "Collectd::TYPE_DATASET",       PLUGIN_DATASET },
203         { "Collectd::DS_TYPE_COUNTER",    DS_TYPE_COUNTER },
204         { "Collectd::DS_TYPE_GAUGE",      DS_TYPE_GAUGE },
205         { "Collectd::DS_TYPE_DERIVE",     DS_TYPE_DERIVE },
206         { "Collectd::DS_TYPE_ABSOLUTE",   DS_TYPE_ABSOLUTE },
207         { "Collectd::LOG_ERR",            LOG_ERR },
208         { "Collectd::LOG_WARNING",        LOG_WARNING },
209         { "Collectd::LOG_NOTICE",         LOG_NOTICE },
210         { "Collectd::LOG_INFO",           LOG_INFO },
211         { "Collectd::LOG_DEBUG",          LOG_DEBUG },
212         { "Collectd::FC_MATCH",           FC_MATCH },
213         { "Collectd::FC_TARGET",          FC_TARGET },
214         { "Collectd::FC_CB_CREATE",       FC_CB_CREATE },
215         { "Collectd::FC_CB_DESTROY",      FC_CB_DESTROY },
216         { "Collectd::FC_CB_EXEC",         FC_CB_EXEC },
217         { "Collectd::FC_MATCH_NO_MATCH",  FC_MATCH_NO_MATCH },
218         { "Collectd::FC_MATCH_MATCHES",   FC_MATCH_MATCHES },
219         { "Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE },
220         { "Collectd::FC_TARGET_STOP",     FC_TARGET_STOP },
221         { "Collectd::FC_TARGET_RETURN",   FC_TARGET_RETURN },
222         { "Collectd::NOTIF_FAILURE",      NOTIF_FAILURE },
223         { "Collectd::NOTIF_WARNING",      NOTIF_WARNING },
224         { "Collectd::NOTIF_OKAY",         NOTIF_OKAY },
225         { "", 0 }
226 };
228 struct {
229         char  name[64];
230         char *var;
231 } g_strings[] =
233         { "Collectd::hostname_g", hostname_g },
234         { "", NULL }
235 };
237 struct {
238         char  name[64];
239         int  *var;
240 } g_integers[] =
242         { "Collectd::interval_g", &interval_g },
243         { "", NULL }
244 };
246 /*
247  * Helper functions for data type conversion.
248  */
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)
264         SV **tmp = NULL;
266         if ((NULL == hash) || (NULL == ds))
267                 return -1;
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         }
277         if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
278                 ds->type = SvIV (*tmp);
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         }
292         if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
293                 ds->min = SvNV (*tmp);
294         else
295                 ds->min = NAN;
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 *) */
304 static int av2value (pTHX_ char *name, AV *array, value_t *value, int len)
306         const data_set_t *ds;
308         int i = 0;
310         if ((NULL == name) || (NULL == array) || (NULL == value))
311                 return -1;
313         if (av_len (array) < len - 1)
314                 len = av_len (array) + 1;
316         if (0 >= len)
317                 return -1;
319         ds = plugin_get_ds (name);
320         if (NULL == ds) {
321                 log_err ("av2value: Unknown dataset \"%s\"", name);
322                 return -1;
323         }
325         if (ds->ds_num < len) {
326                 log_warn ("av2value: Value length exceeds data set length.");
327                 len = ds->ds_num;
328         }
330         for (i = 0; i < len; ++i) {
331                 SV **tmp = av_fetch (array, i, 0);
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) */
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)
363         SV **tmp;
365         if ((NULL == hash) || (NULL == vl))
366                 return -1;
368         if (NULL == (tmp = hv_fetch (hash, "type", 4, 0))) {
369                 log_err ("hv2value_list: No type given.");
370                 return -1;
371         }
373         sstrncpy (vl->type, SvPV_nolen (*tmp), sizeof (vl->type));
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         }
381         {
382                 AV  *array = (AV *)SvRV (*tmp);
383                 int len    = av_len (array) + 1;
385                 if (len <= 0)
386                         return -1;
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);
392                 if (-1 == vl->values_len) {
393                         sfree (vl->values);
394                         return -1;
395                 }
396         }
398         if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
399                 vl->time = (time_t)SvIV (*tmp);
401         if (NULL != (tmp = hv_fetch (hash, "interval", 8, 0)))
402                 vl->interval = SvIV (*tmp);
404         if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
405                 sstrncpy (vl->host, SvPV_nolen (*tmp), sizeof (vl->host));
406         else
407                 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
409         if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
410                 sstrncpy (vl->plugin, SvPV_nolen (*tmp), sizeof (vl->plugin));
412         if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
413                 sstrncpy (vl->plugin_instance, SvPV_nolen (*tmp),
414                                 sizeof (vl->plugin_instance));
416         if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
417                 sstrncpy (vl->type_instance, SvPV_nolen (*tmp),
418                                 sizeof (vl->type_instance));
419         return 0;
420 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
422 static int av2data_set (pTHX_ AV *array, char *name, data_set_t *ds)
424         int len, i;
426         if ((NULL == array) || (NULL == name) || (NULL == ds))
427                 return -1;
429         len = av_len (array);
431         if (-1 == len) {
432                 log_err ("av2data_set: Invalid data set.");
433                 return -1;
434         }
436         ds->ds = (data_source_t *)smalloc ((len + 1) * sizeof (data_source_t));
437         ds->ds_num = len + 1;
439         for (i = 0; i <= len; ++i) {
440                 SV **elem = av_fetch (array, i, 0);
442                 if (NULL == elem) {
443                         log_err ("av2data_set: Failed to fetch data source %i.", i);
444                         return -1;
445                 }
447                 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
448                         log_err ("av2data_set: Invalid data source.");
449                         return -1;
450                 }
452                 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds->ds[i]))
453                         return -1;
455                 log_debug ("av2data_set: "
456                                 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
457                                 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
458         }
460         sstrncpy (ds->type, name, sizeof (ds->type));
461         return 0;
462 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
464 /*
465  * notification:
466  * {
467  *   severity => $severity,
468  *   time     => $time,
469  *   message  => $msg,
470  *   host     => $host,
471  *   plugin   => $plugin,
472  *   type     => $type,
473  *   plugin_instance => $instance,
474  *   type_instance   => $type_instance,
475  *   meta     => [ { name => <name>, value => <value> }, ... ]
476  * }
477  */
478 static int av2notification_meta (pTHX_ AV *array, notification_meta_t **meta)
480         notification_meta_t **m = meta;
482         int len = av_len (array);
483         int i;
485         for (i = 0; i <= len; ++i) {
486                 SV **tmp = av_fetch (array, i, 0);
487                 HV  *hash;
489                 if (NULL == tmp)
490                         return -1;
492                 if (! (SvROK (*tmp) && (SVt_PVHV == SvTYPE (SvRV (*tmp))))) {
493                         log_warn ("av2notification_meta: Skipping invalid "
494                                         "meta information.");
495                         continue;
496                 }
498                 hash = (HV *)SvRV (*tmp);
500                 *m = (notification_meta_t *)smalloc (sizeof (**m));
502                 if (NULL == (tmp = hv_fetch (hash, "name", 4, 0))) {
503                         log_warn ("av2notification_meta: Skipping invalid "
504                                         "meta information.");
505                         free (*m);
506                         continue;
507                 }
508                 sstrncpy ((*m)->name, SvPV_nolen (*tmp), sizeof ((*m)->name));
510                 if (NULL == (tmp = hv_fetch (hash, "value", 5, 0))) {
511                         log_warn ("av2notification_meta: Skipping invalid "
512                                         "meta information.");
513                         free ((*m)->name);
514                         free (*m);
515                         continue;
516                 }
518                 if (SvNOK (*tmp)) {
519                         (*m)->nm_value.nm_double = SvNVX (*tmp);
520                         (*m)->type = NM_TYPE_DOUBLE;
521                 }
522                 else if (SvUOK (*tmp)) {
523                         (*m)->nm_value.nm_unsigned_int = SvUVX (*tmp);
524                         (*m)->type = NM_TYPE_UNSIGNED_INT;
525                 }
526                 else if (SvIOK (*tmp)) {
527                         (*m)->nm_value.nm_signed_int = SvIVX (*tmp);
528                         (*m)->type = NM_TYPE_SIGNED_INT;
529                 }
530                 else {
531                         (*m)->nm_value.nm_string = sstrdup (SvPV_nolen (*tmp));
532                         (*m)->type = NM_TYPE_STRING;
533                 }
535                 (*m)->next = NULL;
536                 m = &((*m)->next);
537         }
538         return 0;
539 } /* static int av2notification_meta (AV *, notification_meta_t *) */
541 static int hv2notification (pTHX_ HV *hash, notification_t *n)
543         SV **tmp = NULL;
545         if ((NULL == hash) || (NULL == n))
546                 return -1;
548         if (NULL != (tmp = hv_fetch (hash, "severity", 8, 0)))
549                 n->severity = SvIV (*tmp);
550         else
551                 n->severity = NOTIF_FAILURE;
553         if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
554                 n->time = (time_t)SvIV (*tmp);
555         else
556                 n->time = time (NULL);
558         if (NULL != (tmp = hv_fetch (hash, "message", 7, 0)))
559                 sstrncpy (n->message, SvPV_nolen (*tmp), sizeof (n->message));
561         if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
562                 sstrncpy (n->host, SvPV_nolen (*tmp), sizeof (n->host));
563         else
564                 sstrncpy (n->host, hostname_g, sizeof (n->host));
566         if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
567                 sstrncpy (n->plugin, SvPV_nolen (*tmp), sizeof (n->plugin));
569         if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
570                 sstrncpy (n->plugin_instance, SvPV_nolen (*tmp),
571                                 sizeof (n->plugin_instance));
573         if (NULL != (tmp = hv_fetch (hash, "type", 4, 0)))
574                 sstrncpy (n->type, SvPV_nolen (*tmp), sizeof (n->type));
576         if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
577                 sstrncpy (n->type_instance, SvPV_nolen (*tmp),
578                                 sizeof (n->type_instance));
580         n->meta = NULL;
581         while (NULL != (tmp = hv_fetch (hash, "meta", 4, 0))) {
582                 if (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp))))) {
583                         log_warn ("hv2notification: Ignoring invalid meta information.");
584                         break;
585                 }
587                 if (0 != av2notification_meta (aTHX_ (AV *)SvRV (*tmp), &n->meta)) {
588                         plugin_notification_meta_free (n->meta);
589                         n->meta = NULL;
590                         return -1;
591                 }
592                 break;
593         }
594         return 0;
595 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
597 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
599         int i = 0;
601         if ((NULL == ds) || (NULL == array))
602                 return -1;
604         av_extend (array, ds->ds_num);
606         for (i = 0; i < ds->ds_num; ++i) {
607                 HV *source = newHV ();
609                 if (NULL == hv_store (source, "name", 4,
610                                 newSVpv (ds->ds[i].name, 0), 0))
611                         return -1;
613                 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
614                         return -1;
616                 if (! isnan (ds->ds[i].min))
617                         if (NULL == hv_store (source, "min", 3,
618                                         newSVnv (ds->ds[i].min), 0))
619                                 return -1;
621                 if (! isnan (ds->ds[i].max))
622                         if (NULL == hv_store (source, "max", 3,
623                                         newSVnv (ds->ds[i].max), 0))
624                                 return -1;
626                 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
627                         return -1;
628         }
629         return 0;
630 } /* static int data_set2av (data_set_t *, AV *) */
632 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
634         AV *values = NULL;
636         int i   = 0;
637         int len = 0;
639         if ((NULL == vl) || (NULL == ds) || (NULL == hash))
640                 return -1;
642         len = vl->values_len;
644         if (ds->ds_num < len) {
645                 log_warn ("value2av: Value length exceeds data set length.");
646                 len = ds->ds_num;
647         }
649         values = newAV ();
650         av_extend (values, len - 1);
652         for (i = 0; i < len; ++i) {
653                 SV *val = NULL;
655                 if (DS_TYPE_COUNTER == ds->ds[i].type)
656                         val = newSViv (vl->values[i].counter);
657                 else if (DS_TYPE_GAUGE == ds->ds[i].type)
658                         val = newSVnv (vl->values[i].gauge);
659                 else if (DS_TYPE_DERIVE == ds->ds[i].type)
660                         val = newSViv (vl->values[i].derive);
661                 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
662                         val = newSViv (vl->values[i].absolute);
664                 if (NULL == av_store (values, i, val)) {
665                         av_undef (values);
666                         return -1;
667                 }
668         }
670         if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
671                 return -1;
673         if (0 != vl->time)
674                 if (NULL == hv_store (hash, "time", 4, newSViv (vl->time), 0))
675                         return -1;
677         if (NULL == hv_store (hash, "interval", 8, newSViv (vl->interval), 0))
678                 return -1;
680         if ('\0' != vl->host[0])
681                 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
682                         return -1;
684         if ('\0' != vl->plugin[0])
685                 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
686                         return -1;
688         if ('\0' != vl->plugin_instance[0])
689                 if (NULL == hv_store (hash, "plugin_instance", 15,
690                                 newSVpv (vl->plugin_instance, 0), 0))
691                         return -1;
693         if ('\0' != vl->type[0])
694                 if (NULL == hv_store (hash, "type", 4, newSVpv (vl->type, 0), 0))
695                         return -1;
697         if ('\0' != vl->type_instance[0])
698                 if (NULL == hv_store (hash, "type_instance", 13,
699                                 newSVpv (vl->type_instance, 0), 0))
700                         return -1;
701         return 0;
702 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
704 static int notification_meta2av (pTHX_ notification_meta_t *meta, AV *array)
706         int meta_num = 0;
707         int i;
709         while (meta) {
710                 ++meta_num;
711                 meta = meta->next;
712         }
714         av_extend (array, meta_num);
716         for (i = 0; NULL != meta; meta = meta->next, ++i) {
717                 HV *m = newHV ();
718                 SV *value;
720                 if (NULL == hv_store (m, "name", 4, newSVpv (meta->name, 0), 0))
721                         return -1;
723                 if (NM_TYPE_STRING == meta->type)
724                         value = newSVpv (meta->nm_value.nm_string, 0);
725                 else if (NM_TYPE_SIGNED_INT == meta->type)
726                         value = newSViv (meta->nm_value.nm_signed_int);
727                 else if (NM_TYPE_UNSIGNED_INT == meta->type)
728                         value = newSVuv (meta->nm_value.nm_unsigned_int);
729                 else if (NM_TYPE_DOUBLE == meta->type)
730                         value = newSVnv (meta->nm_value.nm_double);
731                 else if (NM_TYPE_BOOLEAN == meta->type)
732                         value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
733                 else
734                         return -1;
736                 if (NULL == hv_store (m, "value", 5, value, 0)) {
737                         sv_free (value);
738                         return -1;
739                 }
741                 if (NULL == av_store (array, i, newRV_noinc ((SV *)m))) {
742                         hv_clear (m);
743                         hv_undef (m);
744                         return -1;
745                 }
746         }
747         return 0;
748 } /* static int notification_meta2av (notification_meta_t *, AV *) */
750 static int notification2hv (pTHX_ notification_t *n, HV *hash)
752         if (NULL == hv_store (hash, "severity", 8, newSViv (n->severity), 0))
753                 return -1;
755         if (0 != n->time)
756                 if (NULL == hv_store (hash, "time", 4, newSViv (n->time), 0))
757                         return -1;
759         if ('\0' != *n->message)
760                 if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
761                         return -1;
763         if ('\0' != *n->host)
764                 if (NULL == hv_store (hash, "host", 4, newSVpv (n->host, 0), 0))
765                         return -1;
767         if ('\0' != *n->plugin)
768                 if (NULL == hv_store (hash, "plugin", 6, newSVpv (n->plugin, 0), 0))
769                         return -1;
771         if ('\0' != *n->plugin_instance)
772                 if (NULL == hv_store (hash, "plugin_instance", 15,
773                                 newSVpv (n->plugin_instance, 0), 0))
774                         return -1;
776         if ('\0' != *n->type)
777                 if (NULL == hv_store (hash, "type", 4, newSVpv (n->type, 0), 0))
778                         return -1;
780         if ('\0' != *n->type_instance)
781                 if (NULL == hv_store (hash, "type_instance", 13,
782                                 newSVpv (n->type_instance, 0), 0))
783                         return -1;
785         if (NULL != n->meta) {
786                 AV *meta = newAV ();
787                 if ((0 != notification_meta2av (aTHX_ n->meta, meta))
788                                 || (NULL == hv_store (hash, "meta", 4,
789                                                 newRV_noinc ((SV *)meta), 0))) {
790                         av_clear (meta);
791                         av_undef (meta);
792                         return -1;
793                 }
794         }
795         return 0;
796 } /* static int notification2hv (notification_t *, HV *) */
798 static int oconfig_item2hv (pTHX_ oconfig_item_t *ci, HV *hash)
800         int i;
802         AV *values;
803         AV *children;
805         if (NULL == hv_store (hash, "key", 3, newSVpv (ci->key, 0), 0))
806                 return -1;
808         values = newAV ();
809         if (0 < ci->values_num)
810                 av_extend (values, ci->values_num);
812         if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0)) {
813                 av_clear (values);
814                 av_undef (values);
815                 return -1;
816         }
818         for (i = 0; i < ci->values_num; ++i) {
819                 SV *value;
821                 switch (ci->values[i].type) {
822                         case OCONFIG_TYPE_STRING:
823                                 value = newSVpv (ci->values[i].value.string, 0);
824                                 break;
825                         case OCONFIG_TYPE_NUMBER:
826                                 value = newSVnv ((NV)ci->values[i].value.number);
827                                 break;
828                         case OCONFIG_TYPE_BOOLEAN:
829                                 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
830                                 break;
831                         default:
832                                 log_err ("oconfig_item2hv: Invalid value type %i.",
833                                                 ci->values[i].type);
834                                 value = &PL_sv_undef;
835                 }
837                 if (NULL == av_store (values, i, value)) {
838                         sv_free (value);
839                         return -1;
840                 }
841         }
843         /* ignoring 'parent' member which is uninteresting in this case */
845         children = newAV ();
846         if (0 < ci->children_num)
847                 av_extend (children, ci->children_num);
849         if (NULL == hv_store (hash, "children", 8, newRV_noinc ((SV *)children), 0)) {
850                 av_clear (children);
851                 av_undef (children);
852                 return -1;
853         }
855         for (i = 0; i < ci->children_num; ++i) {
856                 HV *child = newHV ();
858                 if (0 != oconfig_item2hv (aTHX_ ci->children + i, child)) {
859                         hv_clear (child);
860                         hv_undef (child);
861                         return -1;
862                 }
864                 if (NULL == av_store (children, i, newRV_noinc ((SV *)child))) {
865                         hv_clear (child);
866                         hv_undef (child);
867                         return -1;
868                 }
869         }
870         return 0;
871 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
873 /*
874  * Internal functions.
875  */
877 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
878         int status = 0;
879         if (base_name[0] == '\0')
880                 status = ssnprintf (buf, buf_len, "%s", module);
881         else
882                 status = ssnprintf (buf, buf_len, "%s::%s", base_name, module);
883         if ((status < 0) || ((unsigned int)status >= buf_len))
884                 return (NULL);
885         return (buf);
886 } /* char *get_module_name */
888 /*
889  * Add a plugin's data set definition.
890  */
891 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
893         int ret = 0;
895         data_set_t ds;
897         if ((NULL == name) || (NULL == dataset))
898                 return -1;
900         if (0 != av2data_set (aTHX_ dataset, name, &ds))
901                 return -1;
903         ret = plugin_register_data_set (&ds);
905         free (ds.ds);
906         return ret;
907 } /* static int pplugin_register_data_set (char *, SV *) */
909 /*
910  * Remove a plugin's data set definition.
911  */
912 static int pplugin_unregister_data_set (char *name)
914         if (NULL == name)
915                 return 0;
916         return plugin_unregister_data_set (name);
917 } /* static int pplugin_unregister_data_set (char *) */
919 /*
920  * Submit the values to the write functions.
921  */
922 static int pplugin_dispatch_values (pTHX_ HV *values)
924         value_list_t vl = VALUE_LIST_INIT;
926         int ret = 0;
928         if (NULL == values)
929                 return -1;
931         if (0 != hv2value_list (aTHX_ values, &vl))
932                 return -1;
934         ret = plugin_dispatch_values (&vl);
936         sfree (vl.values);
937         return ret;
938 } /* static int pplugin_dispatch_values (char *, HV *) */
940 /*
941  * Submit the values to a single write function.
942  */
943 static int pplugin_write (pTHX_ const char *plugin, AV *data_set, HV *values)
945         data_set_t   ds;
946         value_list_t vl = VALUE_LIST_INIT;
948         int ret;
950         if (NULL == values)
951                 return -1;
953         if (0 != hv2value_list (aTHX_ values, &vl))
954                 return -1;
956         if ((NULL != data_set)
957                         && (0 != av2data_set (aTHX_ data_set, vl.type, &ds)))
958                 return -1;
960         ret = plugin_write (plugin, NULL == data_set ? NULL : &ds, &vl);
961         if (0 != ret)
962                 log_warn ("Dispatching value to plugin \"%s\" failed with status %i.",
963                                 NULL == plugin ? "<any>" : plugin, ret);
965         if (NULL != data_set)
966                 sfree (ds.ds);
967         sfree (vl.values);
968         return ret;
969 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
971 /*
972  * Dispatch a notification.
973  */
974 static int pplugin_dispatch_notification (pTHX_ HV *notif)
976         notification_t n;
978         int ret;
980         if (NULL == notif)
981                 return -1;
983         memset (&n, 0, sizeof (n));
985         if (0 != hv2notification (aTHX_ notif, &n))
986                 return -1;
988         ret = plugin_dispatch_notification (&n);
989         plugin_notification_meta_free (n.meta);
990         return ret;
991 } /* static int pplugin_dispatch_notification (HV *) */
993 /*
994  * Call all working functions of the given type.
995  */
996 static int pplugin_call_all (pTHX_ int type, ...)
998         int retvals = 0;
1000         _Bool old_running;
1001         va_list ap;
1002         int ret = 0;
1004         dSP;
1006         c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
1007         if (t == NULL) /* thread destroyed ( c_ithread_destroy*() -> log_debug() ) */
1008                 return 0;
1010         old_running = t->running;
1011         t->running = 1;
1012         
1013         if (t->shutdown) {
1014                 t->running = old_running;
1015                 return 0;
1016         }
1018         if ((type < 0) || (type >= PLUGIN_TYPES))
1019                 return -1;
1021         va_start (ap, type);
1023         ENTER;
1024         SAVETMPS;
1026         PUSHMARK (SP);
1028         XPUSHs (sv_2mortal (newSViv ((IV)type)));
1030         if (PLUGIN_WRITE == type) {
1031                 /*
1032                  * $_[0] = $plugin_type;
1033                  *
1034                  * $_[1] =
1035                  * [
1036                  *   {
1037                  *     name => $ds_name,
1038                  *     type => $ds_type,
1039                  *     min  => $ds_min,
1040                  *     max  => $ds_max
1041                  *   },
1042                  *   ...
1043                  * ];
1044                  *
1045                  * $_[2] =
1046                  * {
1047                  *   values => [ $v1, ... ],
1048                  *   time   => $time,
1049                  *   host   => $hostname,
1050                  *   plugin => $plugin,
1051                  *   type   => $type,
1052                  *   plugin_instance => $instance,
1053                  *   type_instance   => $type_instance
1054                  * };
1055                  */
1056                 data_set_t   *ds;
1057                 value_list_t *vl;
1059                 AV *pds = newAV ();
1060                 HV *pvl = newHV ();
1062                 ds = va_arg (ap, data_set_t *);
1063                 vl = va_arg (ap, value_list_t *);
1065                 if (-1 == data_set2av (aTHX_ ds, pds)) {
1066                         av_clear (pds);
1067                         av_undef (pds);
1068                         pds = (AV *)&PL_sv_undef;
1069                         ret = -1;
1070                 }
1072                 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
1073                         hv_clear (pvl);
1074                         hv_undef (pvl);
1075                         pvl = (HV *)&PL_sv_undef;
1076                         ret = -1;
1077                 }
1079                 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
1080                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1081                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1082         }
1083         else if (PLUGIN_LOG == type) {
1084                 /*
1085                  * $_[0] = $level;
1086                  *
1087                  * $_[1] = $message;
1088                  */
1089                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1090                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1091         }
1092         else if (PLUGIN_NOTIF == type) {
1093                 /*
1094                  * $_[0] =
1095                  * {
1096                  *   severity => $severity,
1097                  *   time     => $time,
1098                  *   message  => $msg,
1099                  *   host     => $host,
1100                  *   plugin   => $plugin,
1101                  *   type     => $type,
1102                  *   plugin_instance => $instance,
1103                  *   type_instance   => $type_instance
1104                  * };
1105                  */
1106                 notification_t *n;
1107                 HV *notif = newHV ();
1109                 n = va_arg (ap, notification_t *);
1111                 if (-1 == notification2hv (aTHX_ n, notif)) {
1112                         hv_clear (notif);
1113                         hv_undef (notif);
1114                         notif = (HV *)&PL_sv_undef;
1115                         ret = -1;
1116                 }
1118                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
1119         }
1120         else if (PLUGIN_FLUSH == type) {
1121                 /*
1122                  * $_[0] = $timeout;
1123                  * $_[1] = $identifier;
1124                  */
1125                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1126                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1127         }
1129         PUTBACK;
1131         retvals = call_pv ("Collectd::plugin_call_all", G_SCALAR);
1133         SPAGAIN;
1134         if (0 < retvals) {
1135                 SV *tmp = POPs;
1136                 if (! SvTRUE (tmp))
1137                         ret = -1;
1138         }
1140         PUTBACK;
1141         FREETMPS;
1142         LEAVE;
1144         t->running = old_running;
1145         va_end (ap);
1146         return ret;
1147 } /* static int pplugin_call_all (int, ...) */
1149 /*
1150  * collectd's perl interpreter based thread implementation.
1151  *
1152  * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1153  */
1155 /* must be called with perl_threads->mutex locked */
1156 static void c_ithread_destroy (c_ithread_t *ithread)
1158         dTHXa (ithread->interp);
1160         assert (NULL != perl_threads);
1162         PERL_SET_CONTEXT (aTHX);
1163         log_debug ("Shutting down Perl interpreter %p...", aTHX);
1165 #if COLLECT_DEBUG
1166         sv_report_used ();
1168         --perl_threads->number_of_threads;
1169 #endif /* COLLECT_DEBUG */
1171         perl_destruct (aTHX);
1172         perl_free (aTHX);
1174         if (NULL == ithread->prev)
1175                 perl_threads->head = ithread->next;
1176         else
1177                 ithread->prev->next = ithread->next;
1179         if (NULL == ithread->next)
1180                 perl_threads->tail = ithread->prev;
1181         else
1182                 ithread->next->prev = ithread->prev;
1184         sfree (ithread);
1185         return;
1186 } /* static void c_ithread_destroy (c_ithread_t *) */
1188 static void c_ithread_destructor (void *arg)
1190         c_ithread_t *ithread = (c_ithread_t *)arg;
1191         c_ithread_t *t = NULL;
1193         if (NULL == perl_threads)
1194                 return;
1196         pthread_mutex_lock (&perl_threads->mutex);
1198         for (t = perl_threads->head; NULL != t; t = t->next)
1199                 if (t == ithread)
1200                         break;
1202         /* the ithread no longer exists */
1203         if (NULL == t)
1204                 return;
1206         c_ithread_destroy (ithread);
1208         pthread_mutex_unlock (&perl_threads->mutex);
1209         return;
1210 } /* static void c_ithread_destructor (void *) */
1212 /* must be called with perl_threads->mutex locked */
1213 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1215         c_ithread_t *t = NULL;
1216         dTHXa (NULL);
1218         assert (NULL != perl_threads);
1220         t = (c_ithread_t *)smalloc (sizeof (c_ithread_t));
1221         memset (t, 0, sizeof (c_ithread_t));
1223         t->interp = (NULL == base)
1224                 ? NULL
1225                 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1227         aTHX = t->interp;
1229         if ((NULL != base) && (NULL != PL_endav)) {
1230                 av_clear (PL_endav);
1231                 av_undef (PL_endav);
1232                 PL_endav = Nullav;
1233         }
1235 #if COLLECT_DEBUG
1236         ++perl_threads->number_of_threads;
1237 #endif /* COLLECT_DEBUG */
1239         t->next = NULL;
1241         if (NULL == perl_threads->tail) {
1242                 perl_threads->head = t;
1243                 t->prev = NULL;
1244         }
1245         else {
1246                 perl_threads->tail->next = t;
1247                 t->prev = perl_threads->tail;
1248         }
1250         t->pthread = pthread_self();
1251         t->running = 0;
1252         t->shutdown = 0;
1253         perl_threads->tail = t;
1255         pthread_setspecific (perl_thr_key, (const void *)t);
1256         return t;
1257 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1259 /*
1260  * Filter chains implementation.
1261  */
1263 static int fc_call (pTHX_ int type, int cb_type, pfc_user_data_t *data, ...)
1265         int retvals = 0;
1267         _Bool old_running;
1268         va_list ap;
1269         int ret = 0;
1271         notification_meta_t **meta  = NULL;
1272         AV                   *pmeta = NULL;
1274         dSP;
1276         c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
1277         if (t == NULL) /* thread destroyed */
1278                 return 0;
1280         old_running = t->running;
1281         t->running = 1;
1283         if (t->shutdown) {
1284                 t->running = old_running;
1285                 return 0;
1286         }
1288         if ((type < 0) || (type >= FC_TYPES))
1289                 return -1;
1291         if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1292                 return -1;
1294         va_start (ap, data);
1296         ENTER;
1297         SAVETMPS;
1299         PUSHMARK (SP);
1301         XPUSHs (sv_2mortal (newSViv ((IV)type)));
1302         XPUSHs (sv_2mortal (newSVpv (data->name, 0)));
1303         XPUSHs (sv_2mortal (newSViv ((IV)cb_type)));
1305         if (FC_CB_CREATE == cb_type) {
1306                 /*
1307                  * $_[0] = $ci;
1308                  * $_[1] = $user_data;
1309                  */
1310                 oconfig_item_t *ci;
1311                 HV *config = newHV ();
1313                 ci = va_arg (ap, oconfig_item_t *);
1315                 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
1316                         hv_clear (config);
1317                         hv_undef (config);
1318                         config = (HV *)&PL_sv_undef;
1319                         ret = -1;
1320                 }
1322                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
1323         }
1324         else if (FC_CB_DESTROY == cb_type) {
1325                 /*
1326                  * $_[1] = $user_data;
1327                  */
1329                 /* nothing to be done - the user data pointer
1330                  * is pushed onto the stack later */
1331         }
1332         else if (FC_CB_EXEC == cb_type) {
1333                 /*
1334                  * $_[0] = $ds;
1335                  * $_[1] = $vl;
1336                  * $_[2] = $meta;
1337                  * $_[3] = $user_data;
1338                  */
1339                 data_set_t   *ds;
1340                 value_list_t *vl;
1342                 AV *pds = newAV ();
1343                 HV *pvl = newHV ();
1345                 ds   = va_arg (ap, data_set_t *);
1346                 vl   = va_arg (ap, value_list_t *);
1347                 meta = va_arg (ap, notification_meta_t **);
1349                 if (0 != data_set2av (aTHX_ ds, pds)) {
1350                         av_clear (pds);
1351                         av_undef (pds);
1352                         pds = (AV *)&PL_sv_undef;
1353                         ret = -1;
1354                 }
1356                 if (0 != value_list2hv (aTHX_ vl, ds, pvl)) {
1357                         hv_clear (pvl);
1358                         hv_undef (pvl);
1359                         pvl = (HV *)&PL_sv_undef;
1360                         ret = -1;
1361                 }
1363                 if (NULL != meta) {
1364                         pmeta = newAV ();
1366                         if (0 != notification_meta2av (aTHX_ *meta, pmeta)) {
1367                                 av_clear (pmeta);
1368                                 av_undef (pmeta);
1369                                 pmeta = (AV *)&PL_sv_undef;
1370                                 ret = -1;
1371                         }
1372                 }
1373                 else {
1374                         pmeta = (AV *)&PL_sv_undef;
1375                 }
1377                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1378                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1379                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pmeta)));
1380         }
1382         XPUSHs (sv_2mortal (newRV_inc (data->user_data)));
1384         PUTBACK;
1386         retvals = call_pv ("Collectd::fc_call", G_SCALAR);
1388         if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1389                 assert (pmeta != NULL);
1391                 plugin_notification_meta_free (*meta);
1392                 av2notification_meta (aTHX_ pmeta, meta);
1393         }
1395         SPAGAIN;
1396         if (0 < retvals) {
1397                 SV *tmp = POPs;
1399                 /* the exec callbacks return a status, while
1400                  * the others return a boolean value */
1401                 if (FC_CB_EXEC == cb_type)
1402                         ret = SvIV (tmp);
1403                 else if (! SvTRUE (tmp))
1404                         ret = -1;
1405         }
1407         PUTBACK;
1408         FREETMPS;
1409         LEAVE;
1411         t->running = old_running;
1412         va_end (ap);
1413         return ret;
1414 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1416 static int fc_create (int type, const oconfig_item_t *ci, void **user_data)
1418         pfc_user_data_t *data;
1420         int ret = 0;
1422         dTHX;
1424         if (NULL == perl_threads)
1425                 return 0;
1427         if (NULL == aTHX) {
1428                 c_ithread_t *t = NULL;
1430                 pthread_mutex_lock (&perl_threads->mutex);
1431                 t = c_ithread_create (perl_threads->head->interp);
1432                 pthread_mutex_unlock (&perl_threads->mutex);
1434                 aTHX = t->interp;
1435         }
1437         log_debug ("fc_create: c_ithread: interp = %p (active threads: %i)",
1438                         aTHX, perl_threads->number_of_threads);
1440         if ((1 != ci->values_num)
1441                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1442                 log_warn ("A \"%s\" block expects a single string argument.",
1443                                 (FC_MATCH == type) ? "Match" : "Target");
1444                 return -1;
1445         }
1447         data = (pfc_user_data_t *)smalloc (sizeof (*data));
1448         data->name      = sstrdup (ci->values[0].value.string);
1449         data->user_data = newSV (0);
1451         ret = fc_call (aTHX_ type, FC_CB_CREATE, data, ci);
1453         if (0 != ret)
1454                 PFC_USER_DATA_FREE (data);
1455         else
1456                 *user_data = data;
1457         return ret;
1458 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1460 static int fc_destroy (int type, void **user_data)
1462         pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1464         int ret = 0;
1466         dTHX;
1468         if ((NULL == perl_threads) || (NULL == data))
1469                 return 0;
1471         if (NULL == aTHX) {
1472                 c_ithread_t *t = NULL;
1474                 pthread_mutex_lock (&perl_threads->mutex);
1475                 t = c_ithread_create (perl_threads->head->interp);
1476                 pthread_mutex_unlock (&perl_threads->mutex);
1478                 aTHX = t->interp;
1479         }
1481         log_debug ("fc_destroy: c_ithread: interp = %p (active threads: %i)",
1482                         aTHX, perl_threads->number_of_threads);
1484         ret = fc_call (aTHX_ type, FC_CB_DESTROY, data);
1486         PFC_USER_DATA_FREE (data);
1487         *user_data = NULL;
1488         return ret;
1489 } /* static int fc_destroy (int, void **) */
1491 static int fc_exec (int type, const data_set_t *ds, const value_list_t *vl,
1492                 notification_meta_t **meta, void **user_data)
1494         pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1496         dTHX;
1498         if (NULL == perl_threads)
1499                 return 0;
1501         assert (NULL != data);
1503         if (NULL == aTHX) {
1504                 c_ithread_t *t = NULL;
1506                 pthread_mutex_lock (&perl_threads->mutex);
1507                 t = c_ithread_create (perl_threads->head->interp);
1508                 pthread_mutex_unlock (&perl_threads->mutex);
1510                 aTHX = t->interp;
1511         }
1513         log_debug ("fc_exec: c_ithread: interp = %p (active threads: %i)",
1514                         aTHX, perl_threads->number_of_threads);
1516         return fc_call (aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1517 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1518                 notification_meta_t **, void **) */
1520 static int pmatch_create (const oconfig_item_t *ci, void **user_data)
1522         return fc_create (FC_MATCH, ci, user_data);
1523 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1525 static int pmatch_destroy (void **user_data)
1527         return fc_destroy (FC_MATCH, user_data);
1528 } /* static int pmatch_destroy (void **) */
1530 static int pmatch_match (const data_set_t *ds, const value_list_t *vl,
1531                 notification_meta_t **meta, void **user_data)
1533         return fc_exec (FC_MATCH, ds, vl, meta, user_data);
1534 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1535                 notification_meta_t **, void **) */
1537 static match_proc_t pmatch = {
1538         pmatch_create, pmatch_destroy, pmatch_match
1539 };
1541 static int ptarget_create (const oconfig_item_t *ci, void **user_data)
1543         return fc_create (FC_TARGET, ci, user_data);
1544 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1546 static int ptarget_destroy (void **user_data)
1548         return fc_destroy (FC_TARGET, user_data);
1549 } /* static int ptarget_destroy (void **) */
1551 static int ptarget_invoke (const data_set_t *ds, value_list_t *vl,
1552                 notification_meta_t **meta, void **user_data)
1554         return fc_exec (FC_TARGET, ds, vl, meta, user_data);
1555 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1556                 notification_meta_t **, void **) */
1558 static target_proc_t ptarget = {
1559         ptarget_create, ptarget_destroy, ptarget_invoke
1560 };
1562 /*
1563  * Exported Perl API.
1564  */
1566 /*
1567  * Collectd::plugin_register_data_set (type, dataset).
1568  *
1569  * type:
1570  *   type of the dataset
1571  *
1572  * dataset:
1573  *   dataset to be registered
1574  */
1575 static XS (Collectd_plugin_register_ds)
1577         SV  *data = NULL;
1578         int ret   = 0;
1580         dXSARGS;
1582         log_warn ("Using plugin_register() to register new data-sets is "
1583                         "deprecated - add new entries to a custom types.db instead.");
1585         if (2 != items) {
1586                 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1587                 XSRETURN_EMPTY;
1588         }
1590         log_debug ("Collectd::plugin_register_data_set: "
1591                         "type = \"%s\", dataset = \"%s\"",
1592                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1594         data = ST (1);
1596         if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1597                 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1598                                 (AV *)SvRV (data));
1599         }
1600         else {
1601                 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1602                 XSRETURN_EMPTY;
1603         }
1605         if (0 == ret)
1606                 XSRETURN_YES;
1607         else
1608                 XSRETURN_EMPTY;
1609 } /* static XS (Collectd_plugin_register_ds) */
1611 /*
1612  * Collectd::plugin_unregister_data_set (type).
1613  *
1614  * type:
1615  *   type of the dataset
1616  */
1617 static XS (Collectd_plugin_unregister_ds)
1619         dXSARGS;
1621         if (1 != items) {
1622                 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1623                 XSRETURN_EMPTY;
1624         }
1626         log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1627                         SvPV_nolen (ST (0)));
1629         if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1630                 XSRETURN_YES;
1631         else
1632                 XSRETURN_EMPTY;
1633 } /* static XS (Collectd_plugin_register_ds) */
1635 /*
1636  * Collectd::plugin_dispatch_values (name, values).
1637  *
1638  * name:
1639  *   name of the plugin
1640  *
1641  * values:
1642  *   value list to submit
1643  */
1644 static XS (Collectd_plugin_dispatch_values)
1646         SV *values     = NULL;
1647         int values_idx = 0;
1649         int ret = 0;
1651         dXSARGS;
1653         if (2 == items) {
1654                 log_warn ("Collectd::plugin_dispatch_values with two arguments "
1655                                 "is deprecated - pass the type through values->{type}.");
1656                 values_idx = 1;
1657         }
1658         else if (1 != items) {
1659                 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1660                 XSRETURN_EMPTY;
1661         }
1663         log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1664                         SvPV_nolen (ST (values_idx)));
1666         values = ST (values_idx);
1668         if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1669                 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1670                 XSRETURN_EMPTY;
1671         }
1673         if (((2 == items) && (NULL == ST (0))) || (NULL == values))
1674                 XSRETURN_EMPTY;
1676         if ((2 == items) && (NULL == hv_store ((HV *)SvRV (values), "type", 4,
1677                         newSVsv (ST (0)), 0))) {
1678                 log_err ("Collectd::plugin_dispatch_values: Could not store type.");
1679                 XSRETURN_EMPTY;
1680         }
1682         ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1684         if (0 == ret)
1685                 XSRETURN_YES;
1686         else
1687                 XSRETURN_EMPTY;
1688 } /* static XS (Collectd_plugin_dispatch_values) */
1690 /* Collectd::plugin_write (plugin, ds, vl).
1691  *
1692  * plugin:
1693  *   name of the plugin to call, may be 'undef'
1694  *
1695  * ds:
1696  *   data-set that describes the submitted values, may be 'undef'
1697  *
1698  * vl:
1699  *   value-list to be written
1700  */
1701 static XS (Collectd__plugin_write)
1703         char *plugin;
1704         SV   *ds, *vl;
1705         AV   *ds_array;
1707         int ret;
1709         dXSARGS;
1711         if (3 != items) {
1712                 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1713                 XSRETURN_EMPTY;
1714         }
1716         log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1717                         SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1718                         SvPV_nolen (ST (2)));
1720         if (! SvOK (ST (0)))
1721                 plugin = NULL;
1722         else
1723                 plugin = SvPV_nolen (ST (0));
1725         ds = ST (1);
1726         if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1727                 ds_array = (AV *)SvRV (ds);
1728         else if (! SvOK (ds))
1729                 ds_array = NULL;
1730         else {
1731                 log_err ("Collectd::plugin_write: Invalid data-set.");
1732                 XSRETURN_EMPTY;
1733         }
1735         vl = ST (2);
1736         if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1737                 log_err ("Collectd::plugin_write: Invalid value-list.");
1738                 XSRETURN_EMPTY;
1739         }
1741         ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1743         if (0 == ret)
1744                 XSRETURN_YES;
1745         else
1746                 XSRETURN_EMPTY;
1747 } /* static XS (Collectd__plugin_write) */
1749 /*
1750  * Collectd::_plugin_flush (plugin, timeout, identifier).
1751  *
1752  * plugin:
1753  *   name of the plugin to flush
1754  *
1755  * timeout:
1756  *   timeout to use when flushing the data
1757  *
1758  * identifier:
1759  *   data-set identifier to flush
1760  */
1761 static XS (Collectd__plugin_flush)
1763         char *plugin  = NULL;
1764         int   timeout = -1;
1765         char *id      = NULL;
1767         dXSARGS;
1769         if (3 != items) {
1770                 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1771                 XSRETURN_EMPTY;
1772         }
1774         if (SvOK (ST (0)))
1775                 plugin = SvPV_nolen (ST (0));
1777         if (SvOK (ST (1)))
1778                 timeout = (int)SvIV (ST (1));
1780         if (SvOK (ST (2)))
1781                 id = SvPV_nolen (ST (2));
1783         log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1784                         "id = \"%s\"", plugin, timeout, id);
1786         if (0 == plugin_flush (plugin, timeout, id))
1787                 XSRETURN_YES;
1788         else
1789                 XSRETURN_EMPTY;
1790 } /* static XS (Collectd__plugin_flush) */
1792 /*
1793  * Collectd::plugin_dispatch_notification (notif).
1794  *
1795  * notif:
1796  *   notification to dispatch
1797  */
1798 static XS (Collectd_plugin_dispatch_notification)
1800         SV *notif = NULL;
1802         int ret = 0;
1804         dXSARGS;
1806         if (1 != items) {
1807                 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
1808                 XSRETURN_EMPTY;
1809         }
1811         log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1812                         SvPV_nolen (ST (0)));
1814         notif = ST (0);
1816         if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
1817                 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
1818                 XSRETURN_EMPTY;
1819         }
1821         ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
1823         if (0 == ret)
1824                 XSRETURN_YES;
1825         else
1826                 XSRETURN_EMPTY;
1827 } /* static XS (Collectd_plugin_dispatch_notification) */
1829 /*
1830  * Collectd::plugin_log (level, message).
1831  *
1832  * level:
1833  *   log level (LOG_DEBUG, ... LOG_ERR)
1834  *
1835  * message:
1836  *   log message
1837  */
1838 static XS (Collectd_plugin_log)
1840         dXSARGS;
1842         if (2 != items) {
1843                 log_err ("Usage: Collectd::plugin_log(level, message)");
1844                 XSRETURN_EMPTY;
1845         }
1847         plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
1848         XSRETURN_YES;
1849 } /* static XS (Collectd_plugin_log) */
1851 /*
1852  * Collectd::_fc_register (type, name)
1853  *
1854  * type:
1855  *   match | target
1856  *
1857  * name:
1858  *   name of the match
1859  */
1860 static XS (Collectd__fc_register)
1862         int   type;
1863         char *name;
1865         int ret = 0;
1867         dXSARGS;
1869         if (2 != items) {
1870                 log_err ("Usage: Collectd::_fc_register(type, name)");
1871                 XSRETURN_EMPTY;
1872         }
1874         type = SvIV (ST (0));
1875         name = SvPV_nolen (ST (1));
1877         if (FC_MATCH == type)
1878                 ret = fc_register_match (name, pmatch);
1879         else if (FC_TARGET == type)
1880                 ret = fc_register_target (name, ptarget);
1882         if (0 == ret)
1883                 XSRETURN_YES;
1884         else
1885                 XSRETURN_EMPTY;
1886 } /* static XS (Collectd_fc_register) */
1888 /*
1889  * Collectd::call_by_name (...).
1890  *
1891  * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1892  */
1893 static XS (Collectd_call_by_name)
1895         SV   *tmp  = NULL;
1896         char *name = NULL;
1898         if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
1899                 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
1900                 CLEAR_STACK_FRAME;
1901                 return;
1902         }
1904         name = SvPV_nolen (tmp);
1906         if (NULL == get_cv (name, 0)) {
1907                 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
1908                 CLEAR_STACK_FRAME;
1909                 return;
1910         }
1912         /* simply pass on the subroutine call without touching the stack,
1913          * thus leaving any arguments and return values in place */
1914         call_pv (name, 0);
1915 } /* static XS (Collectd_call_by_name) */
1917 /*
1918  * Interface to collectd.
1919  */
1921 static int perl_init (void)
1923         int status;
1924         dTHX;
1926         if (NULL == perl_threads)
1927                 return 0;
1929         if (NULL == aTHX) {
1930                 c_ithread_t *t = NULL;
1932                 pthread_mutex_lock (&perl_threads->mutex);
1933                 t = c_ithread_create (perl_threads->head->interp);
1934                 pthread_mutex_unlock (&perl_threads->mutex);
1936                 aTHX = t->interp;
1937         }
1939         log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1940                         aTHX, perl_threads->number_of_threads);
1942         /* Lock the base thread to avoid race conditions with c_ithread_create().
1943          * See https://github.com/collectd/collectd/issues/9 and
1944          *     https://github.com/collectd/collectd/issues/1706 for details.
1945          * Locking here requires additional check in perl_log() to avoid deadlock.
1946         */
1947         assert (aTHX == perl_threads->head->interp);
1948         pthread_mutex_lock (&perl_threads->mutex);
1950         status = pplugin_call_all (aTHX_ PLUGIN_INIT);
1952         pthread_mutex_unlock (&perl_threads->mutex);
1954         return status;
1955 } /* static int perl_init (void) */
1957 static int perl_read (void)
1959         dTHX;
1961         if (NULL == perl_threads)
1962                 return 0;
1964         if (NULL == aTHX) {
1965                 c_ithread_t *t = NULL;
1967                 pthread_mutex_lock (&perl_threads->mutex);
1968                 t = c_ithread_create (perl_threads->head->interp);
1969                 pthread_mutex_unlock (&perl_threads->mutex);
1971                 aTHX = t->interp;
1972         }
1974         /* Assert that we're not running as the base thread. Otherwise, we might
1975          * run into concurrency issues with c_ithread_create(). See
1976          * https://github.com/collectd/collectd/issues/9 for details. */
1977         assert (aTHX != perl_threads->head->interp);
1979         log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1980                         aTHX, perl_threads->number_of_threads);
1981         return pplugin_call_all (aTHX_ PLUGIN_READ);
1982 } /* static int perl_read (void) */
1984 static int perl_write (const data_set_t *ds, const value_list_t *vl,
1985                 user_data_t __attribute__((unused)) *user_data)
1987         int status;
1988         dTHX;
1990         if (NULL == perl_threads)
1991                 return 0;
1993         if (NULL == aTHX) {
1994                 c_ithread_t *t = NULL;
1996                 pthread_mutex_lock (&perl_threads->mutex);
1997                 t = c_ithread_create (perl_threads->head->interp);
1998                 pthread_mutex_unlock (&perl_threads->mutex);
2000                 aTHX = t->interp;
2001         }
2003         /* Lock the base thread if this is not called from one of the read threads
2004          * to avoid race conditions with c_ithread_create(). See
2005          * https://github.com/collectd/collectd/issues/9 for details. */
2006         if (aTHX == perl_threads->head->interp)
2007                 pthread_mutex_lock (&perl_threads->mutex);
2009         log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
2010                         aTHX, perl_threads->number_of_threads);
2011         status = pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
2013         if (aTHX == perl_threads->head->interp)
2014                 pthread_mutex_unlock (&perl_threads->mutex);
2016         return status;
2017 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2019 static void perl_log (int level, const char *msg,
2020                 user_data_t __attribute__((unused)) *user_data)
2022         dTHX;
2023         int locked = 0;
2025         if (NULL == perl_threads)
2026                 return;
2028         if (NULL == aTHX) {
2029                 c_ithread_t *t = NULL;
2031                 pthread_mutex_lock (&perl_threads->mutex);
2032                 t = c_ithread_create (perl_threads->head->interp);
2033                 pthread_mutex_unlock (&perl_threads->mutex);
2035                 aTHX = t->interp;
2036         }
2038         /* Lock the base thread if this is not called from one of the read threads
2039          * to avoid race conditions with c_ithread_create(). See
2040          * https://github.com/collectd/collectd/issues/9 for details.
2041          * Additionally check, if we are called from perl interpreter.
2042          * Maybe PTHREAD_MUTEX_RECURSIVE mutex type will be more appropriate?
2043         */
2045         if (aTHX == perl_threads->head->interp && !perl_threads->head->running) {
2046                 pthread_mutex_lock (&perl_threads->mutex);
2047                 locked = 1;
2048         }
2050         pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
2052         if (locked)
2053                 pthread_mutex_unlock (&perl_threads->mutex);
2055         return;
2056 } /* static void perl_log (int, const char *) */
2058 static int perl_notify (const notification_t *notif,
2059                 user_data_t __attribute__((unused)) *user_data)
2061         dTHX;
2063         if (NULL == perl_threads)
2064                 return 0;
2066         if (NULL == aTHX) {
2067                 c_ithread_t *t = NULL;
2069                 pthread_mutex_lock (&perl_threads->mutex);
2070                 t = c_ithread_create (perl_threads->head->interp);
2071                 pthread_mutex_unlock (&perl_threads->mutex);
2073                 aTHX = t->interp;
2074         }
2075         return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
2076 } /* static int perl_notify (const notification_t *) */
2078 static int perl_flush (int timeout, const char *identifier,
2079                 user_data_t __attribute__((unused)) *user_data)
2081         dTHX;
2083         if (NULL == perl_threads)
2084                 return 0;
2086         if (NULL == aTHX) {
2087                 c_ithread_t *t = NULL;
2089                 pthread_mutex_lock (&perl_threads->mutex);
2090                 t = c_ithread_create (perl_threads->head->interp);
2091                 pthread_mutex_unlock (&perl_threads->mutex);
2093                 aTHX = t->interp;
2094         }
2095         return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout, identifier);
2096 } /* static int perl_flush (const int) */
2098 static int perl_shutdown (void)
2100         c_ithread_t *t = NULL;
2102         int ret = 0;
2104         dTHX;
2106         plugin_unregister_complex_config ("perl");
2108         if (NULL == perl_threads)
2109                 return 0;
2111         if (NULL == aTHX) {
2112                 c_ithread_t *t = NULL;
2114                 pthread_mutex_lock (&perl_threads->mutex);
2115                 t = c_ithread_create (perl_threads->head->interp);
2116                 pthread_mutex_unlock (&perl_threads->mutex);
2118                 aTHX = t->interp;
2119         }
2121         log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2122                         aTHX, perl_threads->number_of_threads);
2124         plugin_unregister_log ("perl");
2125         plugin_unregister_notification ("perl");
2126         plugin_unregister_init ("perl");
2127         plugin_unregister_read ("perl");
2128         plugin_unregister_write ("perl");
2129         plugin_unregister_flush ("perl");
2131         ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
2133         pthread_mutex_lock (&perl_threads->mutex);
2134         t = perl_threads->tail;
2136         while (NULL != t) {
2137                 struct timespec ts_wait;
2138                 c_ithread_t *thr = t;
2140                 /* the pointer has to be advanced before destroying
2141                  * the thread as this will free the memory */
2142                 t = t->prev;
2144                 thr->shutdown = 1;
2145                 if (thr->running) {
2146                         /* Give some time to thread to exit from pi */
2147                         WARNING ("perl shutdown: thread is running inside perl. Waiting.");
2148                         ts_wait.tv_sec = 0;
2149                         ts_wait.tv_nsec = 500000;
2150                         nanosleep (&ts_wait, NULL);
2151                 }
2152                 if (thr->running) {
2153                         /* This will crash collectd process later due to PERL_SYS_TERM() */
2154                         //ERROR ("perl shutdown: thread hangs inside perl. "
2155                         //       "Skipped perl interpreter destroy.");
2156                         //continue;
2157                         
2158                         ERROR ("perl shutdown: thread hangs inside perl. Thread killed.");
2159                         pthread_kill (thr->pthread, SIGTERM);
2160                 }
2161                 c_ithread_destroy (thr);
2162         }
2164         pthread_mutex_unlock (&perl_threads->mutex);
2165         pthread_mutex_destroy (&perl_threads->mutex);
2167         sfree (perl_threads);
2169         pthread_key_delete (perl_thr_key);
2171         PERL_SYS_TERM ();
2173         plugin_unregister_shutdown ("perl");
2174         return ret;
2175 } /* static void perl_shutdown (void) */
2177 /*
2178  * Access functions for global variables.
2179  *
2180  * These functions implement the "magic" used to access
2181  * the global variables from Perl.
2182  */
2184 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
2186         char *pv = mg->mg_ptr;
2187         sv_setpv (var, pv);
2188         return 0;
2189 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2191 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
2193         char *pv = mg->mg_ptr;
2194         sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
2195         return 0;
2196 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2198 static int g_iv_get (pTHX_ SV *var, MAGIC *mg)
2200         int *iv = (int *)mg->mg_ptr;
2201         sv_setiv (var, *iv);
2202         return 0;
2203 } /* static int g_iv_get (pTHX_ SV *, MAGIC *) */
2205 static int g_iv_set (pTHX_ SV *var, MAGIC *mg)
2207         int *iv = (int *)mg->mg_ptr;
2208         *iv = (int)SvIV (var);
2209         return 0;
2210 } /* static int g_iv_set (pTHX_ SV *, MAGIC *) */
2212 static MGVTBL g_pv_vtbl = {
2213         g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2214 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2215                 , NULL
2216 #endif
2217 };
2218 static MGVTBL g_iv_vtbl = {
2219         g_iv_get, g_iv_set, NULL, NULL, NULL, NULL, NULL
2220 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2221                 , NULL
2222 #endif
2223 };
2225 /* bootstrap the Collectd module */
2226 static void xs_init (pTHX)
2228         HV   *stash = NULL;
2229         SV   *tmp   = NULL;
2230         char *file  = __FILE__;
2232         int i = 0;
2234         dXSUB_SYS;
2236         /* enable usage of Perl modules using shared libraries */
2237         newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2239         /* register API */
2240         for (i = 0; NULL != api[i].f; ++i)
2241                 newXS (api[i].name, api[i].f, file);
2243         stash = gv_stashpv ("Collectd", 1);
2245         /* export "constants" */
2246         for (i = 0; '\0' != constants[i].name[0]; ++i)
2247                 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
2249         /* export global variables
2250          * by adding "magic" to the SV's representing the globale variables
2251          * perl is able to automagically call the get/set function when
2252          * accessing any such variable (this is basically the same as using
2253          * tie() in Perl) */
2254         /* global strings */
2255         for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
2256                 tmp = get_sv (g_strings[i].name, 1);
2257                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
2258                                 g_strings[i].var, 0);
2259         }
2261         /* global integers */
2262         for (i = 0; '\0' != g_integers[i].name[0]; ++i) {
2263                 tmp = get_sv (g_integers[i].name, 1);
2264                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_iv_vtbl,
2265                                 (char *)g_integers[i].var, 0);
2266         }
2267         return;
2268 } /* static void xs_init (pTHX) */
2270 /* Initialize the global Perl interpreter. */
2271 static int init_pi (int argc, char **argv)
2273         dTHXa (NULL);
2275         if (NULL != perl_threads)
2276                 return 0;
2278         log_info ("Initializing Perl interpreter...");
2279 #if COLLECT_DEBUG
2280         {
2281                 int i = 0;
2283                 for (i = 0; i < argc; ++i)
2284                         log_debug ("argv[%i] = \"%s\"", i, argv[i]);
2285         }
2286 #endif /* COLLECT_DEBUG */
2288         if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
2289                 log_err ("init_pi: pthread_key_create failed");
2291                 /* this must not happen - cowardly giving up if it does */
2292                 return -1;
2293         }
2295 #ifdef __FreeBSD__
2296         /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2297          * triggers a "value computed is not used" warning by gcc. */
2298         (void)
2299 #endif
2300         PERL_SYS_INIT3 (&argc, &argv, &environ);
2302         perl_threads = (c_ithread_list_t *)smalloc (sizeof (c_ithread_list_t));
2303         memset (perl_threads, 0, sizeof (c_ithread_list_t));
2305         pthread_mutex_init (&perl_threads->mutex, NULL);
2306         /* locking the mutex should not be necessary at this point
2307          * but let's just do it for the sake of completeness */
2308         pthread_mutex_lock (&perl_threads->mutex);
2310         perl_threads->head = c_ithread_create (NULL);
2311         perl_threads->tail = perl_threads->head;
2313         if (NULL == (perl_threads->head->interp = perl_alloc ())) {
2314                 log_err ("init_pi: Not enough memory.");
2315                 exit (3);
2316         }
2318         aTHX = perl_threads->head->interp;
2319         pthread_mutex_unlock (&perl_threads->mutex);
2321         perl_construct (aTHX);
2323         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2325         if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
2326                 SV *err = get_sv ("@", 1);
2327                 log_err ("init_pi: Unable to bootstrap Collectd: %s",
2328                                 SvPV_nolen (err));
2330                 perl_destruct (perl_threads->head->interp);
2331                 perl_free (perl_threads->head->interp);
2332                 sfree (perl_threads);
2334                 pthread_key_delete (perl_thr_key);
2335                 return -1;
2336         }
2338         /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2339         sv_setpv (get_sv ("0", 0), "collectd");
2341         perl_run (aTHX);
2343         plugin_register_log ("perl", perl_log, /* user_data = */ NULL);
2344         plugin_register_notification ("perl", perl_notify,
2345                         /* user_data = */ NULL);
2346         plugin_register_init ("perl", perl_init);
2348         plugin_register_read ("perl", perl_read);
2350         plugin_register_write ("perl", perl_write, /* user_data = */ NULL);
2351         plugin_register_flush ("perl", perl_flush, /* user_data = */ NULL);
2352         plugin_register_shutdown ("perl", perl_shutdown);
2353         return 0;
2354 } /* static int init_pi (const char **, const int) */
2356 /*
2357  * LoadPlugin "<Plugin>"
2358  */
2359 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
2361         char module_name[DATA_MAX_NAME_LEN];
2363         char *value = NULL;
2365         if ((0 != ci->children_num) || (1 != ci->values_num)
2366                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2367                 log_err ("LoadPlugin expects a single string argument.");
2368                 return 1;
2369         }
2371         value = ci->values[0].value.string;
2373         if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
2374                 log_err ("Invalid module name %s", value);
2375                 return (1);
2376         }
2378         if (0 != init_pi (perl_argc, perl_argv))
2379                 return -1;
2381         assert (NULL != perl_threads);
2382         assert (NULL != perl_threads->head);
2384         aTHX = perl_threads->head->interp;
2386         log_debug ("perl_config: loading perl plugin \"%s\"", value);
2387         load_module (PERL_LOADMOD_NOIMPORT,
2388                         newSVpv (module_name, strlen (module_name)), Nullsv);
2389         return 0;
2390 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2392 /*
2393  * BaseName "<Name>"
2394  */
2395 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
2397         char *value = NULL;
2399         if ((0 != ci->children_num) || (1 != ci->values_num)
2400                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2401                 log_err ("BaseName expects a single string argument.");
2402                 return 1;
2403         }
2405         value = ci->values[0].value.string;
2407         log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
2408         sstrncpy (base_name, value, sizeof (base_name));
2409         return 0;
2410 } /* static int perl_config_basename (oconfig_item_it *) */
2412 /*
2413  * EnableDebugger "<Package>"|""
2414  */
2415 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
2417         char *value = NULL;
2419         if ((0 != ci->children_num) || (1 != ci->values_num)
2420                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2421                 log_err ("EnableDebugger expects a single string argument.");
2422                 return 1;
2423         }
2425         if (NULL != perl_threads) {
2426                 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
2427                 return 1;
2428         }
2430         value = ci->values[0].value.string;
2432         perl_argv = (char **)realloc (perl_argv,
2433                         (++perl_argc + 1) * sizeof (char *));
2435         if (NULL == perl_argv) {
2436                 log_err ("perl_config: Not enough memory.");
2437                 exit (3);
2438         }
2440         if ('\0' == value[0]) {
2441                 perl_argv[perl_argc - 1] = "-d";
2442         }
2443         else {
2444                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 4);
2445                 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
2446                 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
2447         }
2449         perl_argv[perl_argc] = NULL;
2450         return 0;
2451 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2453 /*
2454  * IncludeDir "<Dir>"
2455  */
2456 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
2458         char *value = NULL;
2460         if ((0 != ci->children_num) || (1 != ci->values_num)
2461                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2462                 log_err ("IncludeDir expects a single string argument.");
2463                 return 1;
2464         }
2466         value = ci->values[0].value.string;
2468         if (NULL == aTHX) {
2469                 perl_argv = (char **)realloc (perl_argv,
2470                                 (++perl_argc + 1) * sizeof (char *));
2472                 if (NULL == perl_argv) {
2473                         log_err ("perl_config: Not enough memory.");
2474                         exit (3);
2475                 }
2477                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 3);
2478                 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2479                 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
2481                 perl_argv[perl_argc] = NULL;
2482         }
2483         else {
2484                 /* prepend the directory to @INC */
2485                 av_unshift (GvAVn (PL_incgv), 1);
2486                 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
2487         }
2488         return 0;
2489 } /* static int perl_config_includedir (oconfig_item_it *) */
2491 /*
2492  * <Plugin> block
2493  */
2494 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2496         int retvals = 0;
2497         int ret     = 0;
2499         char *plugin;
2500         HV   *config;
2502         dSP;
2504         if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2505                 log_err ("LoadPlugin expects a single string argument.");
2506                 return 1;
2507         }
2509         plugin = ci->values[0].value.string;
2510         config = newHV ();
2512         if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2513                 hv_clear (config);
2514                 hv_undef (config);
2516                 log_err ("Unable to convert configuration to a Perl hash value.");
2517                 config = (HV *)&PL_sv_undef;
2518         }
2520         ENTER;
2521         SAVETMPS;
2523         PUSHMARK (SP);
2525         XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2526         XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2528         PUTBACK;
2530         retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2532         SPAGAIN;
2533         if (0 < retvals) {
2534                 SV *tmp = POPs;
2535                 if (! SvTRUE (tmp))
2536                         ret = 1;
2537         }
2538         else
2539                 ret = 1;
2541         PUTBACK;
2542         FREETMPS;
2543         LEAVE;
2544         return ret;
2545 } /* static int perl_config_plugin (oconfig_item_it *) */
2547 static int perl_config (oconfig_item_t *ci)
2549         int status = 0;
2550         int i = 0;
2552         dTHXa (NULL);
2554         for (i = 0; i < ci->children_num; ++i) {
2555                 oconfig_item_t *c = ci->children + i;
2556                 int current_status = 0;
2558                 if (NULL != perl_threads)
2559                         aTHX = PERL_GET_CONTEXT;
2561                 if (0 == strcasecmp (c->key, "LoadPlugin"))
2562                         current_status = perl_config_loadplugin (aTHX_ c);
2563                 else if (0 == strcasecmp (c->key, "BaseName"))
2564                         current_status = perl_config_basename (aTHX_ c);
2565                 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2566                         current_status = perl_config_enabledebugger (aTHX_ c);
2567                 else if (0 == strcasecmp (c->key, "IncludeDir"))
2568                         current_status = perl_config_includedir (aTHX_ c);
2569                 else if (0 == strcasecmp (c->key, "Plugin"))
2570                         current_status = perl_config_plugin (aTHX_ c);
2571                 else
2572                 {
2573                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
2574                         current_status = 0;
2575                 }
2577                 /* fatal error - it's up to perl_config_* to clean up */
2578                 if (0 > current_status) {
2579                         log_err ("Configuration failed with a fatal error - "
2580                                         "plugin disabled!");
2581                         return current_status;
2582                 }
2584                 status += current_status;
2585         }
2586         return status;
2587 } /* static int perl_config (oconfig_item_t *) */
2589 void module_register (void)
2591         perl_argc = 4;
2592         perl_argv = (char **)smalloc ((perl_argc + 1) * sizeof (char *));
2594         /* default options for the Perl interpreter */
2595         perl_argv[0] = "";
2596         perl_argv[1] = "-MCollectd";
2597         perl_argv[2] = "-e";
2598         perl_argv[3] = "1";
2599         perl_argv[4] = NULL;
2601         plugin_register_complex_config ("perl", perl_config);
2602         return;
2603 } /* void module_register (void) */
2605 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */