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