b39250f3053e1f3f3e6891936491d09cdeea07a0
[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   return _plugin_register_generic_userdata(aTHX, PLUGIN_READ, "read");
1655 }
1656
1657 static XS(Collectd_plugin_register_write) {
1658   return _plugin_register_generic_userdata(aTHX, PLUGIN_WRITE, "write");
1659 }
1660
1661 static XS(Collectd_plugin_register_log) {
1662   return _plugin_register_generic_userdata(aTHX, PLUGIN_LOG, "log");
1663 }
1664
1665 static XS(Collectd_plugin_register_notification) {
1666   return _plugin_register_generic_userdata(aTHX, PLUGIN_NOTIF, "notification");
1667 }
1668
1669 static XS(Collectd_plugin_register_flush) {
1670   return _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
1698   return;
1699 } /* static void _plugin_unregister_generic ( ... ) */
1700
1701 /*
1702  * Collectd::plugin_unregister_TYPE (pluginname).
1703  *
1704  * TYPE:
1705  *   type of callback to be unregistered: read, write, log, notification, flush
1706  *
1707  * pluginname:
1708  *   name of the perl plugin
1709  */
1710
1711 static XS(Collectd_plugin_unregister_read) {
1712   return _plugin_unregister_generic(aTHX, plugin_unregister_read, "read");
1713 }
1714
1715 static XS(Collectd_plugin_unregister_write) {
1716   return _plugin_unregister_generic(aTHX, plugin_unregister_write, "write");
1717 }
1718
1719 static XS(Collectd_plugin_unregister_log) {
1720   return _plugin_unregister_generic(aTHX, plugin_unregister_log, "log");
1721 }
1722
1723 static XS(Collectd_plugin_unregister_notification) {
1724   return _plugin_unregister_generic(aTHX, plugin_unregister_notification,
1725                                     "notification");
1726 }
1727
1728 static XS(Collectd_plugin_unregister_flush) {
1729   return _plugin_unregister_generic(aTHX, plugin_unregister_flush, "flush");
1730 }
1731
1732 /*
1733  * Collectd::plugin_register_data_set (type, dataset).
1734  *
1735  * type:
1736  *   type of the dataset
1737  *
1738  * dataset:
1739  *   dataset to be registered
1740  */
1741 static XS(Collectd_plugin_register_ds) {
1742   SV *data = NULL;
1743   int ret = 0;
1744
1745   dXSARGS;
1746
1747   log_warn("Using plugin_register() to register new data-sets is "
1748            "deprecated - add new entries to a custom types.db instead.");
1749
1750   if (2 != items) {
1751     log_err("Usage: Collectd::plugin_register_data_set(type, dataset)");
1752     XSRETURN_EMPTY;
1753   }
1754
1755   log_debug("Collectd::plugin_register_data_set: "
1756             "type = \"%s\", dataset = \"%s\"",
1757             SvPV_nolen(ST(0)), SvPV_nolen(ST(1)));
1758
1759   data = ST(1);
1760
1761   if (SvROK(data) && (SVt_PVAV == SvTYPE(SvRV(data)))) {
1762     ret = pplugin_register_data_set(aTHX_ SvPV_nolen(ST(0)), (AV *)SvRV(data));
1763   } else {
1764     log_err("Collectd::plugin_register_data_set: Invalid data.");
1765     XSRETURN_EMPTY;
1766   }
1767
1768   if (0 == ret)
1769     XSRETURN_YES;
1770   else
1771     XSRETURN_EMPTY;
1772 } /* static XS (Collectd_plugin_register_ds) */
1773
1774 /*
1775  * Collectd::plugin_unregister_data_set (type).
1776  *
1777  * type:
1778  *   type of the dataset
1779  */
1780 static XS(Collectd_plugin_unregister_ds) {
1781   dXSARGS;
1782
1783   if (1 != items) {
1784     log_err("Usage: Collectd::plugin_unregister_data_set(type)");
1785     XSRETURN_EMPTY;
1786   }
1787
1788   log_debug("Collectd::plugin_unregister_data_set: type = \"%s\"",
1789             SvPV_nolen(ST(0)));
1790
1791   if (0 == pplugin_unregister_data_set(SvPV_nolen(ST(0))))
1792     XSRETURN_YES;
1793   else
1794     XSRETURN_EMPTY;
1795 } /* static XS (Collectd_plugin_register_ds) */
1796
1797 /*
1798  * Collectd::plugin_dispatch_values (name, values).
1799  *
1800  * name:
1801  *   name of the plugin
1802  *
1803  * values:
1804  *   value list to submit
1805  */
1806 static XS(Collectd_plugin_dispatch_values) {
1807   SV *values = NULL;
1808
1809   int ret = 0;
1810
1811   dXSARGS;
1812
1813   if (1 != items) {
1814     log_err("Usage: Collectd::plugin_dispatch_values(values)");
1815     XSRETURN_EMPTY;
1816   }
1817
1818   log_debug("Collectd::plugin_dispatch_values: values=\"%s\"",
1819             SvPV_nolen(ST(/* stack index = */ 0)));
1820
1821   values = ST(/* stack index = */ 0);
1822
1823   if (NULL == values)
1824     XSRETURN_EMPTY;
1825
1826   /* Make sure the argument is a hash reference. */
1827   if (!(SvROK(values) && (SVt_PVHV == SvTYPE(SvRV(values))))) {
1828     log_err("Collectd::plugin_dispatch_values: Invalid values.");
1829     XSRETURN_EMPTY;
1830   }
1831
1832   ret = pplugin_dispatch_values(aTHX_(HV *) SvRV(values));
1833
1834   if (0 == ret)
1835     XSRETURN_YES;
1836   else
1837     XSRETURN_EMPTY;
1838 } /* static XS (Collectd_plugin_dispatch_values) */
1839
1840 /*
1841  * Collectd::plugin_get_interval ().
1842  */
1843 static XS(Collectd_plugin_get_interval) {
1844   dXSARGS;
1845
1846   /* make sure we don't get any unused variable warnings for 'items';
1847    * don't abort, though */
1848   if (items)
1849     log_err("Usage: Collectd::plugin_get_interval()");
1850
1851   XSRETURN_NV((NV)CDTIME_T_TO_DOUBLE(plugin_get_interval()));
1852 } /* static XS (Collectd_plugin_get_interval) */
1853
1854 /* Collectd::plugin_write (plugin, ds, vl).
1855  *
1856  * plugin:
1857  *   name of the plugin to call, may be 'undef'
1858  *
1859  * ds:
1860  *   data-set that describes the submitted values, may be 'undef'
1861  *
1862  * vl:
1863  *   value-list to be written
1864  */
1865 static XS(Collectd__plugin_write) {
1866   char *plugin;
1867   SV *ds, *vl;
1868   AV *ds_array;
1869
1870   int ret;
1871
1872   dXSARGS;
1873
1874   if (3 != items) {
1875     log_err("Usage: Collectd::plugin_write(plugin, ds, vl)");
1876     XSRETURN_EMPTY;
1877   }
1878
1879   log_debug("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1880             SvPV_nolen(ST(0)), SvOK(ST(1)) ? SvPV_nolen(ST(1)) : "",
1881             SvPV_nolen(ST(2)));
1882
1883   if (!SvOK(ST(0)))
1884     plugin = NULL;
1885   else
1886     plugin = SvPV_nolen(ST(0));
1887
1888   ds = ST(1);
1889   if (SvROK(ds) && (SVt_PVAV == SvTYPE(SvRV(ds))))
1890     ds_array = (AV *)SvRV(ds);
1891   else if (!SvOK(ds))
1892     ds_array = NULL;
1893   else {
1894     log_err("Collectd::plugin_write: Invalid data-set.");
1895     XSRETURN_EMPTY;
1896   }
1897
1898   vl = ST(2);
1899   if (!(SvROK(vl) && (SVt_PVHV == SvTYPE(SvRV(vl))))) {
1900     log_err("Collectd::plugin_write: Invalid value-list.");
1901     XSRETURN_EMPTY;
1902   }
1903
1904   ret = pplugin_write(aTHX_ plugin, ds_array, (HV *)SvRV(vl));
1905
1906   if (0 == ret)
1907     XSRETURN_YES;
1908   else
1909     XSRETURN_EMPTY;
1910 } /* static XS (Collectd__plugin_write) */
1911
1912 /*
1913  * Collectd::_plugin_flush (plugin, timeout, identifier).
1914  *
1915  * plugin:
1916  *   name of the plugin to flush
1917  *
1918  * timeout:
1919  *   timeout to use when flushing the data
1920  *
1921  * identifier:
1922  *   data-set identifier to flush
1923  */
1924 static XS(Collectd__plugin_flush) {
1925   char *plugin = NULL;
1926   int timeout = -1;
1927   char *id = NULL;
1928
1929   dXSARGS;
1930
1931   if (3 != items) {
1932     log_err("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1933     XSRETURN_EMPTY;
1934   }
1935
1936   if (SvOK(ST(0)))
1937     plugin = SvPV_nolen(ST(0));
1938
1939   if (SvOK(ST(1)))
1940     timeout = (int)SvIV(ST(1));
1941
1942   if (SvOK(ST(2)))
1943     id = SvPV_nolen(ST(2));
1944
1945   log_debug("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1946             "id = \"%s\"",
1947             plugin, timeout, id);
1948
1949   if (0 == plugin_flush(plugin, timeout, id))
1950     XSRETURN_YES;
1951   else
1952     XSRETURN_EMPTY;
1953 } /* static XS (Collectd__plugin_flush) */
1954
1955 /*
1956  * Collectd::plugin_dispatch_notification (notif).
1957  *
1958  * notif:
1959  *   notification to dispatch
1960  */
1961 static XS(Collectd_plugin_dispatch_notification) {
1962   SV *notif = NULL;
1963
1964   int ret = 0;
1965
1966   dXSARGS;
1967
1968   if (1 != items) {
1969     log_err("Usage: Collectd::plugin_dispatch_notification(notif)");
1970     XSRETURN_EMPTY;
1971   }
1972
1973   log_debug("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1974             SvPV_nolen(ST(0)));
1975
1976   notif = ST(0);
1977
1978   if (!(SvROK(notif) && (SVt_PVHV == SvTYPE(SvRV(notif))))) {
1979     log_err("Collectd::plugin_dispatch_notification: Invalid notif.");
1980     XSRETURN_EMPTY;
1981   }
1982
1983   ret = pplugin_dispatch_notification(aTHX_(HV *) SvRV(notif));
1984
1985   if (0 == ret)
1986     XSRETURN_YES;
1987   else
1988     XSRETURN_EMPTY;
1989 } /* static XS (Collectd_plugin_dispatch_notification) */
1990
1991 /*
1992  * Collectd::plugin_log (level, message).
1993  *
1994  * level:
1995  *   log level (LOG_DEBUG, ... LOG_ERR)
1996  *
1997  * message:
1998  *   log message
1999  */
2000 static XS(Collectd_plugin_log) {
2001   dXSARGS;
2002
2003   if (2 != items) {
2004     log_err("Usage: Collectd::plugin_log(level, message)");
2005     XSRETURN_EMPTY;
2006   }
2007
2008   plugin_log(SvIV(ST(0)), "%s", SvPV_nolen(ST(1)));
2009   XSRETURN_YES;
2010 } /* static XS (Collectd_plugin_log) */
2011
2012 /*
2013  * Collectd::_fc_register (type, name)
2014  *
2015  * type:
2016  *   match | target
2017  *
2018  * name:
2019  *   name of the match
2020  */
2021 static XS(Collectd__fc_register) {
2022   int type;
2023   char *name;
2024
2025   int ret = 0;
2026
2027   dXSARGS;
2028
2029   if (2 != items) {
2030     log_err("Usage: Collectd::_fc_register(type, name)");
2031     XSRETURN_EMPTY;
2032   }
2033
2034   type = SvIV(ST(0));
2035   name = SvPV_nolen(ST(1));
2036
2037   if (FC_MATCH == type)
2038     ret = fc_register_match(name, pmatch);
2039   else if (FC_TARGET == type)
2040     ret = fc_register_target(name, ptarget);
2041
2042   if (0 == ret)
2043     XSRETURN_YES;
2044   else
2045     XSRETURN_EMPTY;
2046 } /* static XS (Collectd_fc_register) */
2047
2048 /*
2049  * Collectd::call_by_name (...).
2050  *
2051  * Call a Perl sub identified by its name passed through $Collectd::cb_name.
2052  */
2053 static XS(Collectd_call_by_name) {
2054   SV *tmp = NULL;
2055   char *name = NULL;
2056
2057   if (NULL == (tmp = get_sv("Collectd::cb_name", 0))) {
2058     sv_setpv(get_sv("@", 1), "cb_name has not been set");
2059     CLEAR_STACK_FRAME;
2060     return;
2061   }
2062
2063   name = SvPV_nolen(tmp);
2064
2065   if (NULL == get_cv(name, 0)) {
2066     sv_setpvf(get_sv("@", 1), "unknown callback \"%s\"", name);
2067     CLEAR_STACK_FRAME;
2068     return;
2069   }
2070
2071   /* simply pass on the subroutine call without touching the stack,
2072    * thus leaving any arguments and return values in place */
2073   call_pv(name, 0);
2074 } /* static XS (Collectd_call_by_name) */
2075
2076 /*
2077  * Interface to collectd.
2078  */
2079
2080 static int perl_init(void) {
2081   int status;
2082   dTHX;
2083
2084   if (NULL == perl_threads)
2085     return 0;
2086
2087   if (NULL == aTHX) {
2088     c_ithread_t *t = NULL;
2089
2090     pthread_mutex_lock(&perl_threads->mutex);
2091     t = c_ithread_create(perl_threads->head->interp);
2092     pthread_mutex_unlock(&perl_threads->mutex);
2093
2094     aTHX = t->interp;
2095   }
2096
2097   log_debug("perl_init: c_ithread: interp = %p (active threads: %i)", aTHX,
2098             perl_threads->number_of_threads);
2099
2100   /* Lock the base thread to avoid race conditions with c_ithread_create().
2101    * See https://github.com/collectd/collectd/issues/9 and
2102    *     https://github.com/collectd/collectd/issues/1706 for details.
2103   */
2104   assert(aTHX == perl_threads->head->interp);
2105   pthread_mutex_lock(&perl_threads->mutex);
2106
2107   status = pplugin_call(aTHX_ PLUGIN_INIT);
2108
2109   pthread_mutex_unlock(&perl_threads->mutex);
2110
2111   return status;
2112 } /* static int perl_init (void) */
2113
2114 static int perl_read(user_data_t *user_data) {
2115   dTHX;
2116
2117   if (NULL == perl_threads)
2118     return 0;
2119
2120   if (NULL == aTHX) {
2121     c_ithread_t *t = NULL;
2122
2123     pthread_mutex_lock(&perl_threads->mutex);
2124     t = c_ithread_create(perl_threads->head->interp);
2125     pthread_mutex_unlock(&perl_threads->mutex);
2126
2127     aTHX = t->interp;
2128   }
2129
2130   /* Assert that we're not running as the base thread. Otherwise, we might
2131    * run into concurrency issues with c_ithread_create(). See
2132    * https://github.com/collectd/collectd/issues/9 for details. */
2133   assert(aTHX != perl_threads->head->interp);
2134
2135   log_debug("perl_read: c_ithread: interp = %p (active threads: %i)", aTHX,
2136             perl_threads->number_of_threads);
2137
2138   return pplugin_call(aTHX_ PLUGIN_READ, user_data->data);
2139 } /* static int perl_read (user_data_t *user_data) */
2140
2141 static int perl_write(const data_set_t *ds, const value_list_t *vl,
2142                       user_data_t *user_data) {
2143   int status;
2144   dTHX;
2145
2146   if (NULL == perl_threads)
2147     return 0;
2148
2149   if (NULL == aTHX) {
2150     c_ithread_t *t = NULL;
2151
2152     pthread_mutex_lock(&perl_threads->mutex);
2153     t = c_ithread_create(perl_threads->head->interp);
2154     pthread_mutex_unlock(&perl_threads->mutex);
2155
2156     aTHX = t->interp;
2157   }
2158
2159   /* Lock the base thread if this is not called from one of the read threads
2160    * to avoid race conditions with c_ithread_create(). See
2161    * https://github.com/collectd/collectd/issues/9 for details. */
2162   if (aTHX == perl_threads->head->interp)
2163     pthread_mutex_lock(&perl_threads->mutex);
2164
2165   log_debug("perl_write: c_ithread: interp = %p (active threads: %i)", aTHX,
2166             perl_threads->number_of_threads);
2167   status = pplugin_call(aTHX_ PLUGIN_WRITE, user_data->data, ds, vl);
2168
2169   if (aTHX == perl_threads->head->interp)
2170     pthread_mutex_unlock(&perl_threads->mutex);
2171
2172   return status;
2173 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2174
2175 static void perl_log(int level, const char *msg, user_data_t *user_data) {
2176   dTHX;
2177
2178   if (NULL == perl_threads)
2179     return;
2180
2181   if (NULL == aTHX) {
2182     c_ithread_t *t = NULL;
2183
2184     pthread_mutex_lock(&perl_threads->mutex);
2185     t = c_ithread_create(perl_threads->head->interp);
2186     pthread_mutex_unlock(&perl_threads->mutex);
2187
2188     aTHX = t->interp;
2189   }
2190
2191   /* Lock the base thread if this is not called from one of the read threads
2192    * to avoid race conditions with c_ithread_create(). See
2193    * https://github.com/collectd/collectd/issues/9 for details.
2194   */
2195
2196   if (aTHX == perl_threads->head->interp)
2197     pthread_mutex_lock(&perl_threads->mutex);
2198
2199   pplugin_call(aTHX_ PLUGIN_LOG, user_data->data, level, msg);
2200
2201   if (aTHX == perl_threads->head->interp)
2202     pthread_mutex_unlock(&perl_threads->mutex);
2203
2204   return;
2205 } /* static void perl_log (int, const char *) */
2206
2207 static int perl_notify(const notification_t *notif, user_data_t *user_data) {
2208   dTHX;
2209
2210   if (NULL == perl_threads)
2211     return 0;
2212
2213   if (NULL == aTHX) {
2214     c_ithread_t *t = NULL;
2215
2216     pthread_mutex_lock(&perl_threads->mutex);
2217     t = c_ithread_create(perl_threads->head->interp);
2218     pthread_mutex_unlock(&perl_threads->mutex);
2219
2220     aTHX = t->interp;
2221   }
2222   return pplugin_call(aTHX_ PLUGIN_NOTIF, user_data->data, notif);
2223 } /* static int perl_notify (const notification_t *) */
2224
2225 static int perl_flush(cdtime_t timeout, const char *identifier,
2226                       user_data_t *user_data) {
2227   dTHX;
2228
2229   if (NULL == perl_threads)
2230     return 0;
2231
2232   if (NULL == aTHX) {
2233     c_ithread_t *t = NULL;
2234
2235     pthread_mutex_lock(&perl_threads->mutex);
2236     t = c_ithread_create(perl_threads->head->interp);
2237     pthread_mutex_unlock(&perl_threads->mutex);
2238
2239     aTHX = t->interp;
2240   }
2241
2242   /* For collectd-5.6 only, #1731 */
2243   if (user_data == NULL || user_data->data == NULL)
2244     return pplugin_call(aTHX_ PLUGIN_FLUSH_ALL, timeout, identifier);
2245
2246   return pplugin_call(aTHX_ PLUGIN_FLUSH, user_data->data, timeout, identifier);
2247 } /* static int perl_flush (const int) */
2248
2249 static int perl_shutdown(void) {
2250   c_ithread_t *t;
2251   int ret;
2252
2253   dTHX;
2254
2255   plugin_unregister_complex_config("perl");
2256   plugin_unregister_read_group("perl");
2257
2258   if (NULL == perl_threads)
2259     return 0;
2260
2261   if (NULL == aTHX) {
2262     pthread_mutex_lock(&perl_threads->mutex);
2263     t = c_ithread_create(perl_threads->head->interp);
2264     pthread_mutex_unlock(&perl_threads->mutex);
2265
2266     aTHX = t->interp;
2267   }
2268
2269   log_debug("perl_shutdown: c_ithread: interp = %p (active threads: %i)", aTHX,
2270             perl_threads->number_of_threads);
2271
2272   plugin_unregister_init("perl");
2273   plugin_unregister_flush("perl"); /* For collectd-5.6 only, #1731 */
2274
2275   ret = pplugin_call(aTHX_ PLUGIN_SHUTDOWN);
2276
2277   pthread_mutex_lock(&perl_threads->mutex);
2278   t = perl_threads->tail;
2279
2280   while (NULL != t) {
2281     struct timespec ts_wait;
2282     c_ithread_t *thr = t;
2283
2284     /* the pointer has to be advanced before destroying
2285      * the thread as this will free the memory */
2286     t = t->prev;
2287
2288     thr->shutdown = 1;
2289     if (thr->running) {
2290       /* Give some time to thread to exit from Perl interpreter */
2291       WARNING("perl shutdown: Thread is running inside Perl. Waiting.");
2292       ts_wait.tv_sec = 0;
2293       ts_wait.tv_nsec = 500000;
2294       nanosleep(&ts_wait, NULL);
2295     }
2296     if (thr->running) {
2297       pthread_kill(thr->pthread, SIGTERM);
2298       ERROR("perl shutdown: Thread hangs inside Perl. Thread killed.");
2299     }
2300     c_ithread_destroy(thr);
2301   }
2302
2303   pthread_mutex_unlock(&perl_threads->mutex);
2304   pthread_mutex_destroy(&perl_threads->mutex);
2305   pthread_mutexattr_destroy(&perl_threads->mutexattr);
2306
2307   sfree(perl_threads);
2308
2309   pthread_key_delete(perl_thr_key);
2310
2311   PERL_SYS_TERM();
2312
2313   plugin_unregister_shutdown("perl");
2314   return ret;
2315 } /* static void perl_shutdown (void) */
2316
2317 /*
2318  * Access functions for global variables.
2319  *
2320  * These functions implement the "magic" used to access
2321  * the global variables from Perl.
2322  */
2323
2324 static int g_pv_get(pTHX_ SV *var, MAGIC *mg) {
2325   char *pv = mg->mg_ptr;
2326   sv_setpv(var, pv);
2327   return 0;
2328 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2329
2330 static int g_pv_set(pTHX_ SV *var, MAGIC *mg) {
2331   char *pv = mg->mg_ptr;
2332   sstrncpy(pv, SvPV_nolen(var), DATA_MAX_NAME_LEN);
2333   return 0;
2334 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2335
2336 static int g_interval_get(pTHX_ SV *var, MAGIC *mg) {
2337   log_warn("Accessing $interval_g is deprecated (and might not "
2338            "give the desired results) - plugin_get_interval() should "
2339            "be used instead.");
2340   sv_setnv(var, CDTIME_T_TO_DOUBLE(interval_g));
2341   return 0;
2342 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2343
2344 static int g_interval_set(pTHX_ SV *var, MAGIC *mg) {
2345   double nv = (double)SvNV(var);
2346   log_warn("Accessing $interval_g is deprecated (and might not "
2347            "give the desired results) - plugin_get_interval() should "
2348            "be used instead.");
2349   interval_g = DOUBLE_TO_CDTIME_T(nv);
2350   return 0;
2351 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2352
2353 static MGVTBL g_pv_vtbl = {g_pv_get,
2354                            g_pv_set,
2355                            NULL,
2356                            NULL,
2357                            NULL,
2358                            NULL,
2359                            NULL
2360 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2361                            ,
2362                            NULL
2363 #endif
2364 };
2365 static MGVTBL g_interval_vtbl = {g_interval_get,
2366                                  g_interval_set,
2367                                  NULL,
2368                                  NULL,
2369                                  NULL,
2370                                  NULL,
2371                                  NULL
2372 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2373                                  ,
2374                                  NULL
2375 #endif
2376 };
2377
2378 /* bootstrap the Collectd module */
2379 static void xs_init(pTHX) {
2380   HV *stash = NULL;
2381   SV *tmp = NULL;
2382   char *file = __FILE__;
2383
2384   dXSUB_SYS;
2385
2386   /* enable usage of Perl modules using shared libraries */
2387   newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2388
2389   /* register API */
2390   for (int i = 0; NULL != api[i].f; ++i)
2391     newXS(api[i].name, api[i].f, file);
2392
2393   stash = gv_stashpv("Collectd", 1);
2394
2395   /* export "constants" */
2396   for (int i = 0; '\0' != constants[i].name[0]; ++i)
2397     newCONSTSUB(stash, constants[i].name, newSViv(constants[i].value));
2398
2399   /* export global variables
2400    * by adding "magic" to the SV's representing the globale variables
2401    * perl is able to automagically call the get/set function when
2402    * accessing any such variable (this is basically the same as using
2403    * tie() in Perl) */
2404   /* global strings */
2405   for (int i = 0; '\0' != g_strings[i].name[0]; ++i) {
2406     tmp = get_sv(g_strings[i].name, 1);
2407     sv_magicext(tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl, g_strings[i].var, 0);
2408   }
2409
2410   tmp = get_sv("Collectd::interval_g", /* create = */ 1);
2411   sv_magicext(tmp, NULL, /* how = */ PERL_MAGIC_ext,
2412               /* vtbl = */ &g_interval_vtbl,
2413               /* name = */ NULL, /* namelen = */ 0);
2414
2415   return;
2416 } /* static void xs_init (pTHX) */
2417
2418 /* Initialize the global Perl interpreter. */
2419 static int init_pi(int argc, char **argv) {
2420   dTHXa(NULL);
2421
2422   if (NULL != perl_threads)
2423     return 0;
2424
2425   log_info("Initializing Perl interpreter...");
2426 #if COLLECT_DEBUG
2427   {
2428     for (int i = 0; i < argc; ++i)
2429       log_debug("argv[%i] = \"%s\"", i, argv[i]);
2430   }
2431 #endif /* COLLECT_DEBUG */
2432
2433   if (0 != pthread_key_create(&perl_thr_key, c_ithread_destructor)) {
2434     log_err("init_pi: pthread_key_create failed");
2435
2436     /* this must not happen - cowardly giving up if it does */
2437     return -1;
2438   }
2439
2440 #ifdef __FreeBSD__
2441   /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2442    * triggers a "value computed is not used" warning by gcc. */
2443   (void)
2444 #endif
2445       PERL_SYS_INIT3(&argc, &argv, &environ);
2446
2447   perl_threads = smalloc(sizeof(*perl_threads));
2448   memset(perl_threads, 0, sizeof(c_ithread_list_t));
2449
2450   pthread_mutexattr_init(&perl_threads->mutexattr);
2451   pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2452   pthread_mutex_init(&perl_threads->mutex, &perl_threads->mutexattr);
2453   /* locking the mutex should not be necessary at this point
2454    * but let's just do it for the sake of completeness */
2455   pthread_mutex_lock(&perl_threads->mutex);
2456
2457   perl_threads->head = c_ithread_create(NULL);
2458   perl_threads->tail = perl_threads->head;
2459
2460   if (NULL == (perl_threads->head->interp = perl_alloc())) {
2461     log_err("init_pi: Not enough memory.");
2462     exit(3);
2463   }
2464
2465   aTHX = perl_threads->head->interp;
2466   pthread_mutex_unlock(&perl_threads->mutex);
2467
2468   perl_construct(aTHX);
2469
2470   PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2471
2472   if (0 != perl_parse(aTHX_ xs_init, argc, argv, NULL)) {
2473     SV *err = get_sv("@", 1);
2474     log_err("init_pi: Unable to bootstrap Collectd: %s", SvPV_nolen(err));
2475
2476     perl_destruct(perl_threads->head->interp);
2477     perl_free(perl_threads->head->interp);
2478     sfree(perl_threads);
2479
2480     pthread_key_delete(perl_thr_key);
2481     return -1;
2482   }
2483
2484   /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2485   sv_setpv(get_sv("0", 0), "collectd");
2486
2487   perl_run(aTHX);
2488
2489   plugin_register_init("perl", perl_init);
2490   plugin_register_shutdown("perl", perl_shutdown);
2491   return 0;
2492 } /* static int init_pi (const char **, const int) */
2493
2494 /*
2495  * LoadPlugin "<Plugin>"
2496  */
2497 static int perl_config_loadplugin(pTHX_ oconfig_item_t *ci) {
2498   char module_name[DATA_MAX_NAME_LEN];
2499
2500   char *value = NULL;
2501
2502   if ((0 != ci->children_num) || (1 != ci->values_num) ||
2503       (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2504     log_err("LoadPlugin expects a single string argument.");
2505     return 1;
2506   }
2507
2508   value = ci->values[0].value.string;
2509
2510   if (NULL == get_module_name(module_name, sizeof(module_name), value)) {
2511     log_err("Invalid module name %s", value);
2512     return (1);
2513   }
2514
2515   if (0 != init_pi(perl_argc, perl_argv))
2516     return -1;
2517
2518   assert(NULL != perl_threads);
2519   assert(NULL != perl_threads->head);
2520
2521   aTHX = perl_threads->head->interp;
2522
2523   log_debug("perl_config: Loading Perl plugin \"%s\"", value);
2524   load_module(PERL_LOADMOD_NOIMPORT, newSVpv(module_name, strlen(module_name)),
2525               Nullsv);
2526   return 0;
2527 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2528
2529 /*
2530  * BaseName "<Name>"
2531  */
2532 static int perl_config_basename(pTHX_ oconfig_item_t *ci) {
2533   char *value = NULL;
2534
2535   if ((0 != ci->children_num) || (1 != ci->values_num) ||
2536       (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2537     log_err("BaseName expects a single string argument.");
2538     return 1;
2539   }
2540
2541   value = ci->values[0].value.string;
2542
2543   log_debug("perl_config: Setting plugin basename to \"%s\"", value);
2544   sstrncpy(base_name, value, sizeof(base_name));
2545   return 0;
2546 } /* static int perl_config_basename (oconfig_item_it *) */
2547
2548 /*
2549  * EnableDebugger "<Package>"|""
2550  */
2551 static int perl_config_enabledebugger(pTHX_ oconfig_item_t *ci) {
2552   char *value = NULL;
2553
2554   if ((0 != ci->children_num) || (1 != ci->values_num) ||
2555       (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2556     log_err("EnableDebugger expects a single string argument.");
2557     return 1;
2558   }
2559
2560   if (NULL != perl_threads) {
2561     log_warn("EnableDebugger has no effects if used after LoadPlugin.");
2562     return 1;
2563   }
2564
2565   value = ci->values[0].value.string;
2566
2567   perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2568
2569   if (NULL == perl_argv) {
2570     log_err("perl_config: Not enough memory.");
2571     exit(3);
2572   }
2573
2574   if ('\0' == value[0]) {
2575     perl_argv[perl_argc - 1] = "-d";
2576   } else {
2577     perl_argv[perl_argc - 1] = smalloc(strlen(value) + 4);
2578     sstrncpy(perl_argv[perl_argc - 1], "-d:", 4);
2579     sstrncpy(perl_argv[perl_argc - 1] + 3, value, strlen(value) + 1);
2580   }
2581
2582   perl_argv[perl_argc] = NULL;
2583   return 0;
2584 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2585
2586 /*
2587  * IncludeDir "<Dir>"
2588  */
2589 static int perl_config_includedir(pTHX_ oconfig_item_t *ci) {
2590   char *value = NULL;
2591
2592   if ((0 != ci->children_num) || (1 != ci->values_num) ||
2593       (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2594     log_err("IncludeDir expects a single string argument.");
2595     return 1;
2596   }
2597
2598   value = ci->values[0].value.string;
2599
2600   if (NULL == aTHX) {
2601     perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2602
2603     if (NULL == perl_argv) {
2604       log_err("perl_config: Not enough memory.");
2605       exit(3);
2606     }
2607
2608     perl_argv[perl_argc - 1] = smalloc(strlen(value) + 3);
2609     sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2610     sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen(value) + 1);
2611
2612     perl_argv[perl_argc] = NULL;
2613   } else {
2614     /* prepend the directory to @INC */
2615     av_unshift(GvAVn(PL_incgv), 1);
2616     av_store(GvAVn(PL_incgv), 0, newSVpv(value, strlen(value)));
2617   }
2618   return 0;
2619 } /* static int perl_config_includedir (oconfig_item_it *) */
2620
2621 /*
2622  * <Plugin> block
2623  */
2624 static int perl_config_plugin(pTHX_ oconfig_item_t *ci) {
2625   int retvals = 0;
2626   int ret = 0;
2627
2628   char *plugin;
2629   HV *config;
2630
2631   if (NULL == perl_threads) {
2632     log_err("A `Plugin' block was encountered but no plugin was loaded yet. "
2633             "Put the appropriate `LoadPlugin' option in front of it.");
2634     return -1;
2635   }
2636
2637   dSP;
2638
2639   if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2640     log_err("LoadPlugin expects a single string argument.");
2641     return 1;
2642   }
2643
2644   plugin = ci->values[0].value.string;
2645   config = newHV();
2646
2647   if (0 != oconfig_item2hv(aTHX_ ci, config)) {
2648     hv_clear(config);
2649     hv_undef(config);
2650
2651     log_err("Unable to convert configuration to a Perl hash value.");
2652     config = (HV *)&PL_sv_undef;
2653   }
2654
2655   ENTER;
2656   SAVETMPS;
2657
2658   PUSHMARK(SP);
2659
2660   XPUSHs(sv_2mortal(newSVpv(plugin, 0)));
2661   XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
2662
2663   PUTBACK;
2664
2665   retvals = call_pv("Collectd::_plugin_dispatch_config", G_SCALAR);
2666
2667   SPAGAIN;
2668   if (0 < retvals) {
2669     SV *tmp = POPs;
2670     if (!SvTRUE(tmp))
2671       ret = 1;
2672   } else
2673     ret = 1;
2674
2675   PUTBACK;
2676   FREETMPS;
2677   LEAVE;
2678   return ret;
2679 } /* static int perl_config_plugin (oconfig_item_it *) */
2680
2681 static int perl_config(oconfig_item_t *ci) {
2682   int status = 0;
2683
2684   dTHXa(NULL);
2685
2686   for (int i = 0; i < ci->children_num; ++i) {
2687     oconfig_item_t *c = ci->children + i;
2688     int current_status = 0;
2689
2690     if (NULL != perl_threads) {
2691       if ((aTHX = PERL_GET_CONTEXT) == NULL)
2692         return -1;
2693     }
2694
2695     if (0 == strcasecmp(c->key, "LoadPlugin"))
2696       current_status = perl_config_loadplugin(aTHX_ c);
2697     else if (0 == strcasecmp(c->key, "BaseName"))
2698       current_status = perl_config_basename(aTHX_ c);
2699     else if (0 == strcasecmp(c->key, "EnableDebugger"))
2700       current_status = perl_config_enabledebugger(aTHX_ c);
2701     else if (0 == strcasecmp(c->key, "IncludeDir"))
2702       current_status = perl_config_includedir(aTHX_ c);
2703     else if (0 == strcasecmp(c->key, "Plugin"))
2704       current_status = perl_config_plugin(aTHX_ c);
2705     else if (0 == strcasecmp(c->key, "RegisterLegacyFlush"))
2706       cf_util_get_boolean(c, &register_legacy_flush);
2707     else {
2708       log_warn("Ignoring unknown config key \"%s\".", c->key);
2709       current_status = 0;
2710     }
2711
2712     /* fatal error - it's up to perl_config_* to clean up */
2713     if (0 > current_status) {
2714       log_err("Configuration failed with a fatal error - "
2715               "plugin disabled!");
2716       return current_status;
2717     }
2718
2719     status += current_status;
2720   }
2721   return status;
2722 } /* static int perl_config (oconfig_item_t *) */
2723
2724 void module_register(void) {
2725   perl_argc = 4;
2726   perl_argv = smalloc((perl_argc + 1) * sizeof(*perl_argv));
2727
2728   /* default options for the Perl interpreter */
2729   perl_argv[0] = "";
2730   perl_argv[1] = "-MCollectd";
2731   perl_argv[2] = "-e";
2732   perl_argv[3] = "1";
2733   perl_argv[4] = NULL;
2734
2735   plugin_register_complex_config("perl", perl_config);
2736   return;
2737 } /* void module_register (void) */
2738
2739 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */