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