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