2 * collectd - src/perl.c
3 * Copyright (C) 2007-2009 Sebastian Harl
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:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
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.
24 * Sebastian Harl <sh at tokkee.org>
28 * This plugin embeds a Perl interpreter into collectd and provides an
29 * interface for collectd plugins written in perl.
32 /* do not automatically get the thread specific Perl interpreter */
33 #define PERL_NO_GET_CONTEXT
35 #define DONT_POISON_SPRINTF_YET 1
37 #undef DONT_POISON_SPRINTF_YET
39 #include "configfile.h"
48 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
50 # pragma GCC poison sprintf
55 /* Some versions of Perl define their own version of DEBUG... :-/ */
60 /* ... while we want the definition found in plugin.h. */
64 #include "filter_chain.h"
68 #if !defined(USE_ITHREADS)
69 # error "Perl does not support ithreads!"
70 #endif /* !defined(USE_ITHREADS) */
72 /* clear the Perl sub's stack frame
73 * (this should only be used inside an XSUB) */
74 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
78 #define PLUGIN_WRITE 2
79 #define PLUGIN_SHUTDOWN 3
81 #define PLUGIN_NOTIF 5
82 #define PLUGIN_FLUSH 6
84 #define PLUGIN_TYPES 7
86 #define PLUGIN_CONFIG 254
87 #define PLUGIN_DATASET 255
94 #define FC_CB_CREATE 0
95 #define FC_CB_DESTROY 1
100 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
101 #define log_info(...) INFO ("perl: " __VA_ARGS__)
102 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
103 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
105 /* this is defined in DynaLoader.a */
106 void boot_DynaLoader (PerlInterpreter *, CV *);
108 static XS (Collectd_plugin_register_ds);
109 static XS (Collectd_plugin_unregister_ds);
110 static XS (Collectd_plugin_dispatch_values);
111 static XS (Collectd_plugin_get_interval);
112 static XS (Collectd__plugin_write);
113 static XS (Collectd__plugin_flush);
114 static XS (Collectd_plugin_dispatch_notification);
115 static XS (Collectd_plugin_log);
116 static XS (Collectd__fc_register);
117 static XS (Collectd_call_by_name);
123 typedef struct c_ithread_s {
124 /* the thread's Perl interpreter */
125 PerlInterpreter *interp;
126 _Bool running; /* thread is inside Perl interpreter */
130 /* double linked list of threads */
131 struct c_ithread_s *prev;
132 struct c_ithread_s *next;
140 /* some usage stats */
141 int number_of_threads;
142 #endif /* COLLECT_DEBUG */
144 pthread_mutex_t mutex;
145 pthread_mutexattr_t mutexattr;
148 /* name / user_data for Perl matches / targets */
154 #define PFC_USER_DATA_FREE(data) \
156 sfree ((data)->name); \
157 if (NULL != (data)->user_data) \
158 sv_free ((data)->user_data); \
165 extern char **environ;
171 /* if perl_threads != NULL perl_threads->head must
172 * point to the "base" thread */
173 static c_ithread_list_t *perl_threads = NULL;
175 /* the key used to store each pthread's ithread */
176 static pthread_key_t perl_thr_key;
178 static int perl_argc = 0;
179 static char **perl_argv = NULL;
181 static char base_name[DATA_MAX_NAME_LEN] = "";
188 { "Collectd::plugin_register_data_set", Collectd_plugin_register_ds },
189 { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
190 { "Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values },
191 { "Collectd::plugin_get_interval", Collectd_plugin_get_interval },
192 { "Collectd::_plugin_write", Collectd__plugin_write },
193 { "Collectd::_plugin_flush", Collectd__plugin_flush },
194 { "Collectd::plugin_dispatch_notification",
195 Collectd_plugin_dispatch_notification },
196 { "Collectd::plugin_log", Collectd_plugin_log },
197 { "Collectd::_fc_register", Collectd__fc_register },
198 { "Collectd::call_by_name", Collectd_call_by_name },
207 { "Collectd::TYPE_INIT", PLUGIN_INIT },
208 { "Collectd::TYPE_READ", PLUGIN_READ },
209 { "Collectd::TYPE_WRITE", PLUGIN_WRITE },
210 { "Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN },
211 { "Collectd::TYPE_LOG", PLUGIN_LOG },
212 { "Collectd::TYPE_NOTIF", PLUGIN_NOTIF },
213 { "Collectd::TYPE_FLUSH", PLUGIN_FLUSH },
214 { "Collectd::TYPE_CONFIG", PLUGIN_CONFIG },
215 { "Collectd::TYPE_DATASET", PLUGIN_DATASET },
216 { "Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER },
217 { "Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE },
218 { "Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE },
219 { "Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE },
220 { "Collectd::LOG_ERR", LOG_ERR },
221 { "Collectd::LOG_WARNING", LOG_WARNING },
222 { "Collectd::LOG_NOTICE", LOG_NOTICE },
223 { "Collectd::LOG_INFO", LOG_INFO },
224 { "Collectd::LOG_DEBUG", LOG_DEBUG },
225 { "Collectd::FC_MATCH", FC_MATCH },
226 { "Collectd::FC_TARGET", FC_TARGET },
227 { "Collectd::FC_CB_CREATE", FC_CB_CREATE },
228 { "Collectd::FC_CB_DESTROY", FC_CB_DESTROY },
229 { "Collectd::FC_CB_EXEC", FC_CB_EXEC },
230 { "Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH },
231 { "Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES },
232 { "Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE },
233 { "Collectd::FC_TARGET_STOP", FC_TARGET_STOP },
234 { "Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN },
235 { "Collectd::NOTIF_FAILURE", NOTIF_FAILURE },
236 { "Collectd::NOTIF_WARNING", NOTIF_WARNING },
237 { "Collectd::NOTIF_OKAY", NOTIF_OKAY },
246 { "Collectd::hostname_g", hostname_g },
251 * Helper functions for data type conversion.
266 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
270 if ((NULL == hash) || (NULL == ds))
273 if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
274 sstrncpy (ds->name, SvPV_nolen (*tmp), sizeof (ds->name));
277 log_err ("hv2data_source: No DS name given.");
281 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
282 ds->type = SvIV (*tmp);
284 if ((DS_TYPE_COUNTER != ds->type)
285 && (DS_TYPE_GAUGE != ds->type)
286 && (DS_TYPE_DERIVE != ds->type)
287 && (DS_TYPE_ABSOLUTE != ds->type)) {
288 log_err ("hv2data_source: Invalid DS type.");
293 ds->type = DS_TYPE_COUNTER;
296 if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
297 ds->min = SvNV (*tmp);
301 if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
302 ds->max = SvNV (*tmp);
306 } /* static int hv2data_source (HV *, data_source_t *) */
308 static int av2value (pTHX_ char *name, AV *array, value_t *value, int len)
310 const data_set_t *ds;
314 if ((NULL == name) || (NULL == array) || (NULL == value))
317 if (av_len (array) < len - 1)
318 len = av_len (array) + 1;
323 ds = plugin_get_ds (name);
325 log_err ("av2value: Unknown dataset \"%s\"", name);
329 if (ds->ds_num < len) {
330 log_warn ("av2value: Value length exceeds data set length.");
334 for (i = 0; i < len; ++i) {
335 SV **tmp = av_fetch (array, i, 0);
338 if (DS_TYPE_COUNTER == ds->ds[i].type)
339 value[i].counter = SvIV (*tmp);
340 else if (DS_TYPE_GAUGE == ds->ds[i].type)
341 value[i].gauge = SvNV (*tmp);
342 else if (DS_TYPE_DERIVE == ds->ds[i].type)
343 value[i].derive = SvIV (*tmp);
344 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
345 value[i].absolute = SvIV (*tmp);
352 } /* static int av2value (char *, AV *, value_t *, int) */
357 * values => [ @values ],
361 * plugin_instance => $pinstance,
362 * type_instance => $tinstance,
365 static int hv2value_list (pTHX_ HV *hash, value_list_t *vl)
369 if ((NULL == hash) || (NULL == vl))
372 if (NULL == (tmp = hv_fetch (hash, "type", 4, 0))) {
373 log_err ("hv2value_list: No type given.");
377 sstrncpy (vl->type, SvPV_nolen (*tmp), sizeof (vl->type));
379 if ((NULL == (tmp = hv_fetch (hash, "values", 6, 0)))
380 || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
381 log_err ("hv2value_list: No valid values given.");
386 AV *array = (AV *)SvRV (*tmp);
387 int len = av_len (array) + 1;
392 vl->values = (value_t *)smalloc (len * sizeof (value_t));
393 vl->values_len = av2value (aTHX_ vl->type, (AV *)SvRV (*tmp),
396 if (-1 == vl->values_len) {
402 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
404 double t = SvNV (*tmp);
405 vl->time = DOUBLE_TO_CDTIME_T (t);
408 if (NULL != (tmp = hv_fetch (hash, "interval", 8, 0)))
410 double t = SvNV (*tmp);
411 vl->interval = DOUBLE_TO_CDTIME_T (t);
414 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
415 sstrncpy (vl->host, SvPV_nolen (*tmp), sizeof (vl->host));
417 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
419 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
420 sstrncpy (vl->plugin, SvPV_nolen (*tmp), sizeof (vl->plugin));
422 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
423 sstrncpy (vl->plugin_instance, SvPV_nolen (*tmp),
424 sizeof (vl->plugin_instance));
426 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
427 sstrncpy (vl->type_instance, SvPV_nolen (*tmp),
428 sizeof (vl->type_instance));
430 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
432 static int av2data_set (pTHX_ AV *array, char *name, data_set_t *ds)
436 if ((NULL == array) || (NULL == name) || (NULL == ds))
439 len = av_len (array);
442 log_err ("av2data_set: Invalid data set.");
446 ds->ds = (data_source_t *)smalloc ((len + 1) * sizeof (data_source_t));
447 ds->ds_num = len + 1;
449 for (i = 0; i <= len; ++i) {
450 SV **elem = av_fetch (array, i, 0);
453 log_err ("av2data_set: Failed to fetch data source %i.", i);
457 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
458 log_err ("av2data_set: Invalid data source.");
462 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds->ds[i]))
465 log_debug ("av2data_set: "
466 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
467 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
470 sstrncpy (ds->type, name, sizeof (ds->type));
472 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
477 * severity => $severity,
483 * plugin_instance => $instance,
484 * type_instance => $type_instance,
485 * meta => [ { name => <name>, value => <value> }, ... ]
488 static int av2notification_meta (pTHX_ AV *array, notification_meta_t **meta)
490 notification_meta_t **m = meta;
492 int len = av_len (array);
495 for (i = 0; i <= len; ++i) {
496 SV **tmp = av_fetch (array, i, 0);
502 if (! (SvROK (*tmp) && (SVt_PVHV == SvTYPE (SvRV (*tmp))))) {
503 log_warn ("av2notification_meta: Skipping invalid "
504 "meta information.");
508 hash = (HV *)SvRV (*tmp);
510 *m = (notification_meta_t *)smalloc (sizeof (**m));
512 if (NULL == (tmp = hv_fetch (hash, "name", 4, 0))) {
513 log_warn ("av2notification_meta: Skipping invalid "
514 "meta information.");
518 sstrncpy ((*m)->name, SvPV_nolen (*tmp), sizeof ((*m)->name));
520 if (NULL == (tmp = hv_fetch (hash, "value", 5, 0))) {
521 log_warn ("av2notification_meta: Skipping invalid "
522 "meta information.");
528 (*m)->nm_value.nm_double = SvNVX (*tmp);
529 (*m)->type = NM_TYPE_DOUBLE;
531 else if (SvUOK (*tmp)) {
532 (*m)->nm_value.nm_unsigned_int = SvUVX (*tmp);
533 (*m)->type = NM_TYPE_UNSIGNED_INT;
535 else if (SvIOK (*tmp)) {
536 (*m)->nm_value.nm_signed_int = SvIVX (*tmp);
537 (*m)->type = NM_TYPE_SIGNED_INT;
540 (*m)->nm_value.nm_string = sstrdup (SvPV_nolen (*tmp));
541 (*m)->type = NM_TYPE_STRING;
548 } /* static int av2notification_meta (AV *, notification_meta_t *) */
550 static int hv2notification (pTHX_ HV *hash, notification_t *n)
554 if ((NULL == hash) || (NULL == n))
557 if (NULL != (tmp = hv_fetch (hash, "severity", 8, 0)))
558 n->severity = SvIV (*tmp);
560 n->severity = NOTIF_FAILURE;
562 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
564 double t = SvNV (*tmp);
565 n->time = DOUBLE_TO_CDTIME_T (t);
570 if (NULL != (tmp = hv_fetch (hash, "message", 7, 0)))
571 sstrncpy (n->message, SvPV_nolen (*tmp), sizeof (n->message));
573 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
574 sstrncpy (n->host, SvPV_nolen (*tmp), sizeof (n->host));
576 sstrncpy (n->host, hostname_g, sizeof (n->host));
578 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
579 sstrncpy (n->plugin, SvPV_nolen (*tmp), sizeof (n->plugin));
581 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
582 sstrncpy (n->plugin_instance, SvPV_nolen (*tmp),
583 sizeof (n->plugin_instance));
585 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0)))
586 sstrncpy (n->type, SvPV_nolen (*tmp), sizeof (n->type));
588 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
589 sstrncpy (n->type_instance, SvPV_nolen (*tmp),
590 sizeof (n->type_instance));
593 while (NULL != (tmp = hv_fetch (hash, "meta", 4, 0))) {
594 if (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp))))) {
595 log_warn ("hv2notification: Ignoring invalid meta information.");
599 if (0 != av2notification_meta (aTHX_ (AV *)SvRV (*tmp), &n->meta)) {
600 plugin_notification_meta_free (n->meta);
607 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
609 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
613 if ((NULL == ds) || (NULL == array))
616 av_extend (array, ds->ds_num);
618 for (i = 0; i < ds->ds_num; ++i) {
619 HV *source = newHV ();
621 if (NULL == hv_store (source, "name", 4,
622 newSVpv (ds->ds[i].name, 0), 0))
625 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
628 if (! isnan (ds->ds[i].min))
629 if (NULL == hv_store (source, "min", 3,
630 newSVnv (ds->ds[i].min), 0))
633 if (! isnan (ds->ds[i].max))
634 if (NULL == hv_store (source, "max", 3,
635 newSVnv (ds->ds[i].max), 0))
638 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
642 } /* static int data_set2av (data_set_t *, AV *) */
644 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
651 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
654 len = vl->values_len;
656 if (ds->ds_num < len) {
657 log_warn ("value2av: Value length exceeds data set length.");
662 av_extend (values, len - 1);
664 for (i = 0; i < len; ++i) {
667 if (DS_TYPE_COUNTER == ds->ds[i].type)
668 val = newSViv (vl->values[i].counter);
669 else if (DS_TYPE_GAUGE == ds->ds[i].type)
670 val = newSVnv (vl->values[i].gauge);
671 else if (DS_TYPE_DERIVE == ds->ds[i].type)
672 val = newSViv (vl->values[i].derive);
673 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
674 val = newSViv (vl->values[i].absolute);
676 if (NULL == av_store (values, i, val)) {
682 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
687 double t = CDTIME_T_TO_DOUBLE (vl->time);
688 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
693 double t = CDTIME_T_TO_DOUBLE (vl->interval);
694 if (NULL == hv_store (hash, "interval", 8, newSVnv (t), 0))
698 if ('\0' != vl->host[0])
699 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
702 if ('\0' != vl->plugin[0])
703 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
706 if ('\0' != vl->plugin_instance[0])
707 if (NULL == hv_store (hash, "plugin_instance", 15,
708 newSVpv (vl->plugin_instance, 0), 0))
711 if ('\0' != vl->type[0])
712 if (NULL == hv_store (hash, "type", 4, newSVpv (vl->type, 0), 0))
715 if ('\0' != vl->type_instance[0])
716 if (NULL == hv_store (hash, "type_instance", 13,
717 newSVpv (vl->type_instance, 0), 0))
720 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
722 static int notification_meta2av (pTHX_ notification_meta_t *meta, AV *array)
732 av_extend (array, meta_num);
734 for (i = 0; NULL != meta; meta = meta->next, ++i) {
738 if (NULL == hv_store (m, "name", 4, newSVpv (meta->name, 0), 0))
741 if (NM_TYPE_STRING == meta->type)
742 value = newSVpv (meta->nm_value.nm_string, 0);
743 else if (NM_TYPE_SIGNED_INT == meta->type)
744 value = newSViv (meta->nm_value.nm_signed_int);
745 else if (NM_TYPE_UNSIGNED_INT == meta->type)
746 value = newSVuv (meta->nm_value.nm_unsigned_int);
747 else if (NM_TYPE_DOUBLE == meta->type)
748 value = newSVnv (meta->nm_value.nm_double);
749 else if (NM_TYPE_BOOLEAN == meta->type)
750 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
754 if (NULL == hv_store (m, "value", 5, value, 0)) {
759 if (NULL == av_store (array, i, newRV_noinc ((SV *)m))) {
766 } /* static int notification_meta2av (notification_meta_t *, AV *) */
768 static int notification2hv (pTHX_ notification_t *n, HV *hash)
770 if (NULL == hv_store (hash, "severity", 8, newSViv (n->severity), 0))
775 double t = CDTIME_T_TO_DOUBLE (n->time);
776 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
780 if ('\0' != *n->message)
781 if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
784 if ('\0' != *n->host)
785 if (NULL == hv_store (hash, "host", 4, newSVpv (n->host, 0), 0))
788 if ('\0' != *n->plugin)
789 if (NULL == hv_store (hash, "plugin", 6, newSVpv (n->plugin, 0), 0))
792 if ('\0' != *n->plugin_instance)
793 if (NULL == hv_store (hash, "plugin_instance", 15,
794 newSVpv (n->plugin_instance, 0), 0))
797 if ('\0' != *n->type)
798 if (NULL == hv_store (hash, "type", 4, newSVpv (n->type, 0), 0))
801 if ('\0' != *n->type_instance)
802 if (NULL == hv_store (hash, "type_instance", 13,
803 newSVpv (n->type_instance, 0), 0))
806 if (NULL != n->meta) {
808 if ((0 != notification_meta2av (aTHX_ n->meta, meta))
809 || (NULL == hv_store (hash, "meta", 4,
810 newRV_noinc ((SV *)meta), 0))) {
817 } /* static int notification2hv (notification_t *, HV *) */
819 static int oconfig_item2hv (pTHX_ oconfig_item_t *ci, HV *hash)
826 if (NULL == hv_store (hash, "key", 3, newSVpv (ci->key, 0), 0))
830 if (0 < ci->values_num)
831 av_extend (values, ci->values_num);
833 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0)) {
839 for (i = 0; i < ci->values_num; ++i) {
842 switch (ci->values[i].type) {
843 case OCONFIG_TYPE_STRING:
844 value = newSVpv (ci->values[i].value.string, 0);
846 case OCONFIG_TYPE_NUMBER:
847 value = newSVnv ((NV)ci->values[i].value.number);
849 case OCONFIG_TYPE_BOOLEAN:
850 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
853 log_err ("oconfig_item2hv: Invalid value type %i.",
855 value = &PL_sv_undef;
858 if (NULL == av_store (values, i, value)) {
864 /* ignoring 'parent' member which is uninteresting in this case */
867 if (0 < ci->children_num)
868 av_extend (children, ci->children_num);
870 if (NULL == hv_store (hash, "children", 8, newRV_noinc ((SV *)children), 0)) {
876 for (i = 0; i < ci->children_num; ++i) {
877 HV *child = newHV ();
879 if (0 != oconfig_item2hv (aTHX_ ci->children + i, child)) {
885 if (NULL == av_store (children, i, newRV_noinc ((SV *)child))) {
892 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
895 * Internal functions.
898 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
900 if (base_name[0] == '\0')
901 status = ssnprintf (buf, buf_len, "%s", module);
903 status = ssnprintf (buf, buf_len, "%s::%s", base_name, module);
904 if ((status < 0) || ((unsigned int)status >= buf_len))
907 } /* char *get_module_name */
910 * Add a plugin's data set definition.
912 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
918 if ((NULL == name) || (NULL == dataset))
921 if (0 != av2data_set (aTHX_ dataset, name, &ds))
924 ret = plugin_register_data_set (&ds);
928 } /* static int pplugin_register_data_set (char *, SV *) */
931 * Remove a plugin's data set definition.
933 static int pplugin_unregister_data_set (char *name)
937 return plugin_unregister_data_set (name);
938 } /* static int pplugin_unregister_data_set (char *) */
941 * Submit the values to the write functions.
943 static int pplugin_dispatch_values (pTHX_ HV *values)
945 value_list_t vl = VALUE_LIST_INIT;
952 if (0 != hv2value_list (aTHX_ values, &vl))
955 ret = plugin_dispatch_values (&vl);
959 } /* static int pplugin_dispatch_values (char *, HV *) */
962 * Submit the values to a single write function.
964 static int pplugin_write (pTHX_ const char *plugin, AV *data_set, HV *values)
967 value_list_t vl = VALUE_LIST_INIT;
974 if (0 != hv2value_list (aTHX_ values, &vl))
977 if ((NULL != data_set)
978 && (0 != av2data_set (aTHX_ data_set, vl.type, &ds)))
981 ret = plugin_write (plugin, NULL == data_set ? NULL : &ds, &vl);
983 log_warn ("Dispatching value to plugin \"%s\" failed with status %i.",
984 NULL == plugin ? "<any>" : plugin, ret);
986 if (NULL != data_set)
990 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
993 * Dispatch a notification.
995 static int pplugin_dispatch_notification (pTHX_ HV *notif)
1004 memset (&n, 0, sizeof (n));
1006 if (0 != hv2notification (aTHX_ notif, &n))
1009 ret = plugin_dispatch_notification (&n);
1010 plugin_notification_meta_free (n.meta);
1012 } /* static int pplugin_dispatch_notification (HV *) */
1015 * Call perl sub with thread locking flags handled.
1017 static int call_pv_locked (pTHX_ const char* sub_name)
1022 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
1023 if (t == NULL) /* thread destroyed */
1026 old_running = t->running;
1030 t->running = old_running;
1034 ret = call_pv (sub_name, G_SCALAR);
1036 t->running = old_running;
1038 } /* static int call_pv_locked (pTHX, *sub_name) */
1041 * Call all working functions of the given type.
1043 static int pplugin_call_all (pTHX_ int type, ...)
1052 if ((type < 0) || (type >= PLUGIN_TYPES))
1055 va_start (ap, type);
1062 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1064 if (PLUGIN_WRITE == type) {
1066 * $_[0] = $plugin_type;
1081 * values => [ $v1, ... ],
1083 * host => $hostname,
1084 * plugin => $plugin,
1086 * plugin_instance => $instance,
1087 * type_instance => $type_instance
1096 ds = va_arg (ap, data_set_t *);
1097 vl = va_arg (ap, value_list_t *);
1099 if (-1 == data_set2av (aTHX_ ds, pds)) {
1102 pds = (AV *)&PL_sv_undef;
1106 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
1109 pvl = (HV *)&PL_sv_undef;
1113 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
1114 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1115 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1117 else if (PLUGIN_LOG == type) {
1123 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1124 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1126 else if (PLUGIN_NOTIF == type) {
1130 * severity => $severity,
1134 * plugin => $plugin,
1136 * plugin_instance => $instance,
1137 * type_instance => $type_instance
1141 HV *notif = newHV ();
1143 n = va_arg (ap, notification_t *);
1145 if (-1 == notification2hv (aTHX_ n, notif)) {
1148 notif = (HV *)&PL_sv_undef;
1152 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
1154 else if (PLUGIN_FLUSH == type) {
1159 * $_[1] = $identifier;
1161 timeout = va_arg (ap, cdtime_t);
1163 XPUSHs (sv_2mortal (newSVnv (CDTIME_T_TO_DOUBLE (timeout))));
1164 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1169 retvals = call_pv_locked (aTHX_ "Collectd::plugin_call_all");
1184 } /* static int pplugin_call_all (int, ...) */
1187 * collectd's Perl interpreter based thread implementation.
1189 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1192 /* must be called with perl_threads->mutex locked */
1193 static void c_ithread_destroy (c_ithread_t *ithread)
1195 dTHXa (ithread->interp);
1197 assert (NULL != perl_threads);
1199 PERL_SET_CONTEXT (aTHX);
1200 log_debug ("Shutting down Perl interpreter %p...", aTHX);
1205 --perl_threads->number_of_threads;
1206 #endif /* COLLECT_DEBUG */
1208 perl_destruct (aTHX);
1211 if (NULL == ithread->prev)
1212 perl_threads->head = ithread->next;
1214 ithread->prev->next = ithread->next;
1216 if (NULL == ithread->next)
1217 perl_threads->tail = ithread->prev;
1219 ithread->next->prev = ithread->prev;
1223 } /* static void c_ithread_destroy (c_ithread_t *) */
1225 static void c_ithread_destructor (void *arg)
1227 c_ithread_t *ithread = (c_ithread_t *)arg;
1228 c_ithread_t *t = NULL;
1230 if (NULL == perl_threads)
1233 pthread_mutex_lock (&perl_threads->mutex);
1235 for (t = perl_threads->head; NULL != t; t = t->next)
1239 /* the ithread no longer exists */
1242 pthread_mutex_unlock (&perl_threads->mutex);
1246 c_ithread_destroy (ithread);
1248 pthread_mutex_unlock (&perl_threads->mutex);
1250 } /* static void c_ithread_destructor (void *) */
1252 /* must be called with perl_threads->mutex locked */
1253 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1255 c_ithread_t *t = NULL;
1258 assert (NULL != perl_threads);
1260 t = (c_ithread_t *)smalloc (sizeof (c_ithread_t));
1261 memset (t, 0, sizeof (c_ithread_t));
1263 t->interp = (NULL == base)
1265 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1269 if ((NULL != base) && (NULL != PL_endav)) {
1270 av_clear (PL_endav);
1271 av_undef (PL_endav);
1276 ++perl_threads->number_of_threads;
1277 #endif /* COLLECT_DEBUG */
1281 if (NULL == perl_threads->tail) {
1282 perl_threads->head = t;
1286 perl_threads->tail->next = t;
1287 t->prev = perl_threads->tail;
1290 t->pthread = pthread_self();
1293 perl_threads->tail = t;
1295 pthread_setspecific (perl_thr_key, (const void *)t);
1297 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1300 * Filter chains implementation.
1303 static int fc_call (pTHX_ int type, int cb_type, pfc_user_data_t *data, ...)
1310 notification_meta_t **meta = NULL;
1315 if ((type < 0) || (type >= FC_TYPES))
1318 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1321 va_start (ap, data);
1328 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1329 XPUSHs (sv_2mortal (newSVpv (data->name, 0)));
1330 XPUSHs (sv_2mortal (newSViv ((IV)cb_type)));
1332 if (FC_CB_CREATE == cb_type) {
1335 * $_[1] = $user_data;
1338 HV *config = newHV ();
1340 ci = va_arg (ap, oconfig_item_t *);
1342 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
1345 config = (HV *)&PL_sv_undef;
1349 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
1351 else if (FC_CB_DESTROY == cb_type) {
1353 * $_[1] = $user_data;
1356 /* nothing to be done - the user data pointer
1357 * is pushed onto the stack later */
1359 else if (FC_CB_EXEC == cb_type) {
1364 * $_[3] = $user_data;
1372 ds = va_arg (ap, data_set_t *);
1373 vl = va_arg (ap, value_list_t *);
1374 meta = va_arg (ap, notification_meta_t **);
1376 if (0 != data_set2av (aTHX_ ds, pds)) {
1379 pds = (AV *)&PL_sv_undef;
1383 if (0 != value_list2hv (aTHX_ vl, ds, pvl)) {
1386 pvl = (HV *)&PL_sv_undef;
1393 if (0 != notification_meta2av (aTHX_ *meta, pmeta)) {
1396 pmeta = (AV *)&PL_sv_undef;
1401 pmeta = (AV *)&PL_sv_undef;
1404 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1405 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1406 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pmeta)));
1409 XPUSHs (sv_2mortal (newRV_inc (data->user_data)));
1413 retvals = call_pv_locked (aTHX_ "Collectd::fc_call");
1415 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1416 assert (pmeta != NULL);
1418 plugin_notification_meta_free (*meta);
1419 av2notification_meta (aTHX_ pmeta, meta);
1426 /* the exec callbacks return a status, while
1427 * the others return a boolean value */
1428 if (FC_CB_EXEC == cb_type)
1430 else if (! SvTRUE (tmp))
1440 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1442 static int fc_create (int type, const oconfig_item_t *ci, void **user_data)
1444 pfc_user_data_t *data;
1450 if (NULL == perl_threads)
1454 c_ithread_t *t = NULL;
1456 pthread_mutex_lock (&perl_threads->mutex);
1457 t = c_ithread_create (perl_threads->head->interp);
1458 pthread_mutex_unlock (&perl_threads->mutex);
1463 log_debug ("fc_create: c_ithread: interp = %p (active threads: %i)",
1464 aTHX, perl_threads->number_of_threads);
1466 if ((1 != ci->values_num)
1467 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1468 log_warn ("A \"%s\" block expects a single string argument.",
1469 (FC_MATCH == type) ? "Match" : "Target");
1473 data = (pfc_user_data_t *)smalloc (sizeof (*data));
1474 data->name = sstrdup (ci->values[0].value.string);
1475 data->user_data = newSV (0);
1477 ret = fc_call (aTHX_ type, FC_CB_CREATE, data, ci);
1480 PFC_USER_DATA_FREE (data);
1484 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1486 static int fc_destroy (int type, void **user_data)
1488 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1494 if ((NULL == perl_threads) || (NULL == data))
1498 c_ithread_t *t = NULL;
1500 pthread_mutex_lock (&perl_threads->mutex);
1501 t = c_ithread_create (perl_threads->head->interp);
1502 pthread_mutex_unlock (&perl_threads->mutex);
1507 log_debug ("fc_destroy: c_ithread: interp = %p (active threads: %i)",
1508 aTHX, perl_threads->number_of_threads);
1510 ret = fc_call (aTHX_ type, FC_CB_DESTROY, data);
1512 PFC_USER_DATA_FREE (data);
1515 } /* static int fc_destroy (int, void **) */
1517 static int fc_exec (int type, const data_set_t *ds, const value_list_t *vl,
1518 notification_meta_t **meta, void **user_data)
1520 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1524 if (NULL == perl_threads)
1527 assert (NULL != data);
1530 c_ithread_t *t = NULL;
1532 pthread_mutex_lock (&perl_threads->mutex);
1533 t = c_ithread_create (perl_threads->head->interp);
1534 pthread_mutex_unlock (&perl_threads->mutex);
1539 log_debug ("fc_exec: c_ithread: interp = %p (active threads: %i)",
1540 aTHX, perl_threads->number_of_threads);
1542 return fc_call (aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1543 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1544 notification_meta_t **, void **) */
1546 static int pmatch_create (const oconfig_item_t *ci, void **user_data)
1548 return fc_create (FC_MATCH, ci, user_data);
1549 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1551 static int pmatch_destroy (void **user_data)
1553 return fc_destroy (FC_MATCH, user_data);
1554 } /* static int pmatch_destroy (void **) */
1556 static int pmatch_match (const data_set_t *ds, const value_list_t *vl,
1557 notification_meta_t **meta, void **user_data)
1559 return fc_exec (FC_MATCH, ds, vl, meta, user_data);
1560 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1561 notification_meta_t **, void **) */
1563 static match_proc_t pmatch = {
1564 pmatch_create, pmatch_destroy, pmatch_match
1567 static int ptarget_create (const oconfig_item_t *ci, void **user_data)
1569 return fc_create (FC_TARGET, ci, user_data);
1570 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1572 static int ptarget_destroy (void **user_data)
1574 return fc_destroy (FC_TARGET, user_data);
1575 } /* static int ptarget_destroy (void **) */
1577 static int ptarget_invoke (const data_set_t *ds, value_list_t *vl,
1578 notification_meta_t **meta, void **user_data)
1580 return fc_exec (FC_TARGET, ds, vl, meta, user_data);
1581 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1582 notification_meta_t **, void **) */
1584 static target_proc_t ptarget = {
1585 ptarget_create, ptarget_destroy, ptarget_invoke
1589 * Exported Perl API.
1593 * Collectd::plugin_register_data_set (type, dataset).
1596 * type of the dataset
1599 * dataset to be registered
1601 static XS (Collectd_plugin_register_ds)
1608 log_warn ("Using plugin_register() to register new data-sets is "
1609 "deprecated - add new entries to a custom types.db instead.");
1612 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1616 log_debug ("Collectd::plugin_register_data_set: "
1617 "type = \"%s\", dataset = \"%s\"",
1618 SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1622 if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1623 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1627 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1635 } /* static XS (Collectd_plugin_register_ds) */
1638 * Collectd::plugin_unregister_data_set (type).
1641 * type of the dataset
1643 static XS (Collectd_plugin_unregister_ds)
1648 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1652 log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1653 SvPV_nolen (ST (0)));
1655 if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1659 } /* static XS (Collectd_plugin_register_ds) */
1662 * Collectd::plugin_dispatch_values (name, values).
1665 * name of the plugin
1668 * value list to submit
1670 static XS (Collectd_plugin_dispatch_values)
1679 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1683 log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1684 SvPV_nolen (ST (/* stack index = */ 0)));
1686 values = ST (/* stack index = */ 0);
1691 /* Make sure the argument is a hash reference. */
1692 if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1693 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1697 ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1703 } /* static XS (Collectd_plugin_dispatch_values) */
1706 * Collectd::plugin_get_interval ().
1708 static XS (Collectd_plugin_get_interval)
1712 /* make sure we don't get any unused variable warnings for 'items';
1713 * don't abort, though */
1715 log_err ("Usage: Collectd::plugin_get_interval()");
1717 XSRETURN_NV ((NV) CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
1718 } /* static XS (Collectd_plugin_get_interval) */
1720 /* Collectd::plugin_write (plugin, ds, vl).
1723 * name of the plugin to call, may be 'undef'
1726 * data-set that describes the submitted values, may be 'undef'
1729 * value-list to be written
1731 static XS (Collectd__plugin_write)
1742 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1746 log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1747 SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1748 SvPV_nolen (ST (2)));
1750 if (! SvOK (ST (0)))
1753 plugin = SvPV_nolen (ST (0));
1756 if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1757 ds_array = (AV *)SvRV (ds);
1758 else if (! SvOK (ds))
1761 log_err ("Collectd::plugin_write: Invalid data-set.");
1766 if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1767 log_err ("Collectd::plugin_write: Invalid value-list.");
1771 ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1777 } /* static XS (Collectd__plugin_write) */
1780 * Collectd::_plugin_flush (plugin, timeout, identifier).
1783 * name of the plugin to flush
1786 * timeout to use when flushing the data
1789 * data-set identifier to flush
1791 static XS (Collectd__plugin_flush)
1793 char *plugin = NULL;
1800 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1805 plugin = SvPV_nolen (ST (0));
1808 timeout = (int)SvIV (ST (1));
1811 id = SvPV_nolen (ST (2));
1813 log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1814 "id = \"%s\"", plugin, timeout, id);
1816 if (0 == plugin_flush (plugin, timeout, id))
1820 } /* static XS (Collectd__plugin_flush) */
1823 * Collectd::plugin_dispatch_notification (notif).
1826 * notification to dispatch
1828 static XS (Collectd_plugin_dispatch_notification)
1837 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
1841 log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1842 SvPV_nolen (ST (0)));
1846 if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
1847 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
1851 ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
1857 } /* static XS (Collectd_plugin_dispatch_notification) */
1860 * Collectd::plugin_log (level, message).
1863 * log level (LOG_DEBUG, ... LOG_ERR)
1868 static XS (Collectd_plugin_log)
1873 log_err ("Usage: Collectd::plugin_log(level, message)");
1877 plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
1879 } /* static XS (Collectd_plugin_log) */
1882 * Collectd::_fc_register (type, name)
1890 static XS (Collectd__fc_register)
1900 log_err ("Usage: Collectd::_fc_register(type, name)");
1904 type = SvIV (ST (0));
1905 name = SvPV_nolen (ST (1));
1907 if (FC_MATCH == type)
1908 ret = fc_register_match (name, pmatch);
1909 else if (FC_TARGET == type)
1910 ret = fc_register_target (name, ptarget);
1916 } /* static XS (Collectd_fc_register) */
1919 * Collectd::call_by_name (...).
1921 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1923 static XS (Collectd_call_by_name)
1928 if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
1929 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
1934 name = SvPV_nolen (tmp);
1936 if (NULL == get_cv (name, 0)) {
1937 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
1942 /* simply pass on the subroutine call without touching the stack,
1943 * thus leaving any arguments and return values in place */
1945 } /* static XS (Collectd_call_by_name) */
1948 * Interface to collectd.
1951 static int perl_init (void)
1956 if (NULL == perl_threads)
1960 c_ithread_t *t = NULL;
1962 pthread_mutex_lock (&perl_threads->mutex);
1963 t = c_ithread_create (perl_threads->head->interp);
1964 pthread_mutex_unlock (&perl_threads->mutex);
1969 log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1970 aTHX, perl_threads->number_of_threads);
1972 /* Lock the base thread to avoid race conditions with c_ithread_create().
1973 * See https://github.com/collectd/collectd/issues/9 and
1974 * https://github.com/collectd/collectd/issues/1706 for details.
1976 assert (aTHX == perl_threads->head->interp);
1977 pthread_mutex_lock (&perl_threads->mutex);
1979 status = pplugin_call_all (aTHX_ PLUGIN_INIT);
1981 pthread_mutex_unlock (&perl_threads->mutex);
1984 } /* static int perl_init (void) */
1986 static int perl_read (void)
1990 if (NULL == perl_threads)
1994 c_ithread_t *t = NULL;
1996 pthread_mutex_lock (&perl_threads->mutex);
1997 t = c_ithread_create (perl_threads->head->interp);
1998 pthread_mutex_unlock (&perl_threads->mutex);
2003 /* Assert that we're not running as the base thread. Otherwise, we might
2004 * run into concurrency issues with c_ithread_create(). See
2005 * https://github.com/collectd/collectd/issues/9 for details. */
2006 assert (aTHX != perl_threads->head->interp);
2008 log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
2009 aTHX, perl_threads->number_of_threads);
2010 return pplugin_call_all (aTHX_ PLUGIN_READ);
2011 } /* static int perl_read (void) */
2013 static int perl_write (const data_set_t *ds, const value_list_t *vl,
2014 user_data_t __attribute__((unused)) *user_data)
2019 if (NULL == perl_threads)
2023 c_ithread_t *t = NULL;
2025 pthread_mutex_lock (&perl_threads->mutex);
2026 t = c_ithread_create (perl_threads->head->interp);
2027 pthread_mutex_unlock (&perl_threads->mutex);
2032 /* Lock the base thread if this is not called from one of the read threads
2033 * to avoid race conditions with c_ithread_create(). See
2034 * https://github.com/collectd/collectd/issues/9 for details. */
2035 if (aTHX == perl_threads->head->interp)
2036 pthread_mutex_lock (&perl_threads->mutex);
2038 log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
2039 aTHX, perl_threads->number_of_threads);
2040 status = pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
2042 if (aTHX == perl_threads->head->interp)
2043 pthread_mutex_unlock (&perl_threads->mutex);
2046 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2048 static void perl_log (int level, const char *msg,
2049 user_data_t __attribute__((unused)) *user_data)
2053 if (NULL == perl_threads)
2057 c_ithread_t *t = NULL;
2059 pthread_mutex_lock (&perl_threads->mutex);
2060 t = c_ithread_create (perl_threads->head->interp);
2061 pthread_mutex_unlock (&perl_threads->mutex);
2066 /* Lock the base thread if this is not called from one of the read threads
2067 * to avoid race conditions with c_ithread_create(). See
2068 * https://github.com/collectd/collectd/issues/9 for details.
2071 if (aTHX == perl_threads->head->interp)
2072 pthread_mutex_lock (&perl_threads->mutex);
2074 pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
2076 if (aTHX == perl_threads->head->interp)
2077 pthread_mutex_unlock (&perl_threads->mutex);
2080 } /* static void perl_log (int, const char *) */
2082 static int perl_notify (const notification_t *notif,
2083 user_data_t __attribute__((unused)) *user_data)
2087 if (NULL == perl_threads)
2091 c_ithread_t *t = NULL;
2093 pthread_mutex_lock (&perl_threads->mutex);
2094 t = c_ithread_create (perl_threads->head->interp);
2095 pthread_mutex_unlock (&perl_threads->mutex);
2099 return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
2100 } /* static int perl_notify (const notification_t *) */
2102 static int perl_flush (cdtime_t timeout, const char *identifier,
2103 user_data_t __attribute__((unused)) *user_data)
2107 if (NULL == perl_threads)
2111 c_ithread_t *t = NULL;
2113 pthread_mutex_lock (&perl_threads->mutex);
2114 t = c_ithread_create (perl_threads->head->interp);
2115 pthread_mutex_unlock (&perl_threads->mutex);
2119 return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout, identifier);
2120 } /* static int perl_flush (const int) */
2122 static int perl_shutdown (void)
2124 c_ithread_t *t = NULL;
2130 plugin_unregister_complex_config ("perl");
2132 if (NULL == perl_threads)
2138 pthread_mutex_lock (&perl_threads->mutex);
2139 t = c_ithread_create (perl_threads->head->interp);
2140 pthread_mutex_unlock (&perl_threads->mutex);
2145 log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2146 aTHX, perl_threads->number_of_threads);
2148 plugin_unregister_log ("perl");
2149 plugin_unregister_notification ("perl");
2150 plugin_unregister_init ("perl");
2151 plugin_unregister_read ("perl");
2152 plugin_unregister_write ("perl");
2153 plugin_unregister_flush ("perl");
2155 ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
2157 pthread_mutex_lock (&perl_threads->mutex);
2158 t = perl_threads->tail;
2161 struct timespec ts_wait;
2162 c_ithread_t *thr = t;
2164 /* the pointer has to be advanced before destroying
2165 * the thread as this will free the memory */
2170 /* Give some time to thread to exit from Perl interpreter */
2171 WARNING ("perl shutdown: Thread is running inside Perl. Waiting.");
2173 ts_wait.tv_nsec = 500000;
2174 nanosleep (&ts_wait, NULL);
2177 pthread_kill (thr->pthread, SIGTERM);
2178 ERROR ("perl shutdown: Thread hangs inside Perl. Thread killed.");
2180 c_ithread_destroy (thr);
2183 pthread_mutex_unlock (&perl_threads->mutex);
2184 pthread_mutex_destroy (&perl_threads->mutex);
2185 pthread_mutexattr_destroy (&perl_threads->mutexattr);
2187 sfree (perl_threads);
2189 pthread_key_delete (perl_thr_key);
2193 plugin_unregister_shutdown ("perl");
2195 } /* static void perl_shutdown (void) */
2198 * Access functions for global variables.
2200 * These functions implement the "magic" used to access
2201 * the global variables from Perl.
2204 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
2206 char *pv = mg->mg_ptr;
2209 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2211 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
2213 char *pv = mg->mg_ptr;
2214 sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
2216 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2218 static int g_interval_get (pTHX_ SV *var, MAGIC *mg)
2220 log_warn ("Accessing $interval_g is deprecated (and might not "
2221 "give the desired results) - plugin_get_interval() should "
2222 "be used instead.");
2223 sv_setnv (var, CDTIME_T_TO_DOUBLE (interval_g));
2225 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2227 static int g_interval_set (pTHX_ SV *var, MAGIC *mg)
2229 double nv = (double)SvNV (var);
2230 log_warn ("Accessing $interval_g is deprecated (and might not "
2231 "give the desired results) - plugin_get_interval() should "
2232 "be used instead.");
2233 interval_g = DOUBLE_TO_CDTIME_T (nv);
2235 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2237 static MGVTBL g_pv_vtbl = {
2238 g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2239 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2243 static MGVTBL g_interval_vtbl = {
2244 g_interval_get, g_interval_set, NULL, NULL, NULL, NULL, NULL
2245 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2250 /* bootstrap the Collectd module */
2251 static void xs_init (pTHX)
2255 char *file = __FILE__;
2261 /* enable usage of Perl modules using shared libraries */
2262 newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2265 for (i = 0; NULL != api[i].f; ++i)
2266 newXS (api[i].name, api[i].f, file);
2268 stash = gv_stashpv ("Collectd", 1);
2270 /* export "constants" */
2271 for (i = 0; '\0' != constants[i].name[0]; ++i)
2272 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
2274 /* export global variables
2275 * by adding "magic" to the SV's representing the globale variables
2276 * perl is able to automagically call the get/set function when
2277 * accessing any such variable (this is basically the same as using
2279 /* global strings */
2280 for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
2281 tmp = get_sv (g_strings[i].name, 1);
2282 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
2283 g_strings[i].var, 0);
2286 tmp = get_sv ("Collectd::interval_g", /* create = */ 1);
2287 sv_magicext (tmp, NULL, /* how = */ PERL_MAGIC_ext,
2288 /* vtbl = */ &g_interval_vtbl,
2289 /* name = */ NULL, /* namelen = */ 0);
2292 } /* static void xs_init (pTHX) */
2294 /* Initialize the global Perl interpreter. */
2295 static int init_pi (int argc, char **argv)
2299 if (NULL != perl_threads)
2302 log_info ("Initializing Perl interpreter...");
2307 for (i = 0; i < argc; ++i)
2308 log_debug ("argv[%i] = \"%s\"", i, argv[i]);
2310 #endif /* COLLECT_DEBUG */
2312 if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
2313 log_err ("init_pi: pthread_key_create failed");
2315 /* this must not happen - cowardly giving up if it does */
2320 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2321 * triggers a "value computed is not used" warning by gcc. */
2324 PERL_SYS_INIT3 (&argc, &argv, &environ);
2326 perl_threads = (c_ithread_list_t *)smalloc (sizeof (c_ithread_list_t));
2327 memset (perl_threads, 0, sizeof (c_ithread_list_t));
2329 pthread_mutexattr_init(&perl_threads->mutexattr);
2330 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2331 pthread_mutex_init (&perl_threads->mutex, &perl_threads->mutexattr);
2332 /* locking the mutex should not be necessary at this point
2333 * but let's just do it for the sake of completeness */
2334 pthread_mutex_lock (&perl_threads->mutex);
2336 perl_threads->head = c_ithread_create (NULL);
2337 perl_threads->tail = perl_threads->head;
2339 if (NULL == (perl_threads->head->interp = perl_alloc ())) {
2340 log_err ("init_pi: Not enough memory.");
2344 aTHX = perl_threads->head->interp;
2345 pthread_mutex_unlock (&perl_threads->mutex);
2347 perl_construct (aTHX);
2349 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2351 if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
2352 SV *err = get_sv ("@", 1);
2353 log_err ("init_pi: Unable to bootstrap Collectd: %s",
2356 perl_destruct (perl_threads->head->interp);
2357 perl_free (perl_threads->head->interp);
2358 sfree (perl_threads);
2360 pthread_key_delete (perl_thr_key);
2364 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2365 sv_setpv (get_sv ("0", 0), "collectd");
2369 plugin_register_log ("perl", perl_log, /* user_data = */ NULL);
2370 plugin_register_notification ("perl", perl_notify,
2371 /* user_data = */ NULL);
2372 plugin_register_init ("perl", perl_init);
2374 plugin_register_read ("perl", perl_read);
2376 plugin_register_write ("perl", perl_write, /* user_data = */ NULL);
2377 plugin_register_flush ("perl", perl_flush, /* user_data = */ NULL);
2378 plugin_register_shutdown ("perl", perl_shutdown);
2380 } /* static int init_pi (const char **, const int) */
2383 * LoadPlugin "<Plugin>"
2385 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
2387 char module_name[DATA_MAX_NAME_LEN];
2391 if ((0 != ci->children_num) || (1 != ci->values_num)
2392 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2393 log_err ("LoadPlugin expects a single string argument.");
2397 value = ci->values[0].value.string;
2399 if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
2400 log_err ("Invalid module name %s", value);
2404 if (0 != init_pi (perl_argc, perl_argv))
2407 assert (NULL != perl_threads);
2408 assert (NULL != perl_threads->head);
2410 aTHX = perl_threads->head->interp;
2412 log_debug ("perl_config: Loading Perl plugin \"%s\"", value);
2413 load_module (PERL_LOADMOD_NOIMPORT,
2414 newSVpv (module_name, strlen (module_name)), Nullsv);
2416 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2421 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
2425 if ((0 != ci->children_num) || (1 != ci->values_num)
2426 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2427 log_err ("BaseName expects a single string argument.");
2431 value = ci->values[0].value.string;
2433 log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
2434 sstrncpy (base_name, value, sizeof (base_name));
2436 } /* static int perl_config_basename (oconfig_item_it *) */
2439 * EnableDebugger "<Package>"|""
2441 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
2445 if ((0 != ci->children_num) || (1 != ci->values_num)
2446 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2447 log_err ("EnableDebugger expects a single string argument.");
2451 if (NULL != perl_threads) {
2452 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
2456 value = ci->values[0].value.string;
2458 perl_argv = (char **)realloc (perl_argv,
2459 (++perl_argc + 1) * sizeof (char *));
2461 if (NULL == perl_argv) {
2462 log_err ("perl_config: Not enough memory.");
2466 if ('\0' == value[0]) {
2467 perl_argv[perl_argc - 1] = "-d";
2470 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 4);
2471 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
2472 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
2475 perl_argv[perl_argc] = NULL;
2477 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2480 * IncludeDir "<Dir>"
2482 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
2486 if ((0 != ci->children_num) || (1 != ci->values_num)
2487 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2488 log_err ("IncludeDir expects a single string argument.");
2492 value = ci->values[0].value.string;
2495 perl_argv = (char **)realloc (perl_argv,
2496 (++perl_argc + 1) * sizeof (char *));
2498 if (NULL == perl_argv) {
2499 log_err ("perl_config: Not enough memory.");
2503 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 3);
2504 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2505 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
2507 perl_argv[perl_argc] = NULL;
2510 /* prepend the directory to @INC */
2511 av_unshift (GvAVn (PL_incgv), 1);
2512 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
2515 } /* static int perl_config_includedir (oconfig_item_it *) */
2520 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2530 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2531 log_err ("LoadPlugin expects a single string argument.");
2535 plugin = ci->values[0].value.string;
2538 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2542 log_err ("Unable to convert configuration to a Perl hash value.");
2543 config = (HV *)&PL_sv_undef;
2551 XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2552 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2556 retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2571 } /* static int perl_config_plugin (oconfig_item_it *) */
2573 static int perl_config (oconfig_item_t *ci)
2580 for (i = 0; i < ci->children_num; ++i) {
2581 oconfig_item_t *c = ci->children + i;
2582 int current_status = 0;
2584 if (NULL != perl_threads)
2586 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2590 if (0 == strcasecmp (c->key, "LoadPlugin"))
2591 current_status = perl_config_loadplugin (aTHX_ c);
2592 else if (0 == strcasecmp (c->key, "BaseName"))
2593 current_status = perl_config_basename (aTHX_ c);
2594 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2595 current_status = perl_config_enabledebugger (aTHX_ c);
2596 else if (0 == strcasecmp (c->key, "IncludeDir"))
2597 current_status = perl_config_includedir (aTHX_ c);
2598 else if (0 == strcasecmp (c->key, "Plugin"))
2599 current_status = perl_config_plugin (aTHX_ c);
2602 log_warn ("Ignoring unknown config key \"%s\".", c->key);
2606 /* fatal error - it's up to perl_config_* to clean up */
2607 if (0 > current_status) {
2608 log_err ("Configuration failed with a fatal error - "
2609 "plugin disabled!");
2610 return current_status;
2613 status += current_status;
2616 } /* static int perl_config (oconfig_item_t *) */
2618 void module_register (void)
2621 perl_argv = (char **)smalloc ((perl_argc + 1) * sizeof (char *));
2623 /* default options for the Perl interpreter */
2625 perl_argv[1] = "-MCollectd";
2626 perl_argv[2] = "-e";
2628 perl_argv[4] = NULL;
2630 plugin_register_complex_config ("perl", perl_config);
2632 } /* void module_register (void) */
2634 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */