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