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