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