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