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