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"
66 #if !defined(USE_ITHREADS)
67 # error "Perl does not support ithreads!"
68 #endif /* !defined(USE_ITHREADS) */
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
76 #define PLUGIN_WRITE 2
77 #define PLUGIN_SHUTDOWN 3
79 #define PLUGIN_NOTIF 5
80 #define PLUGIN_FLUSH 6
82 #define PLUGIN_TYPES 7
84 #define PLUGIN_CONFIG 254
85 #define PLUGIN_DATASET 255
92 #define FC_CB_CREATE 0
93 #define FC_CB_DESTROY 1
98 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
99 #define log_info(...) INFO ("perl: " __VA_ARGS__)
100 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
101 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
103 /* this is defined in DynaLoader.a */
104 void boot_DynaLoader (PerlInterpreter *, CV *);
106 static XS (Collectd_plugin_register_ds);
107 static XS (Collectd_plugin_unregister_ds);
108 static XS (Collectd_plugin_dispatch_values);
109 static XS (Collectd_plugin_get_interval);
110 static XS (Collectd__plugin_write);
111 static XS (Collectd__plugin_flush);
112 static XS (Collectd_plugin_dispatch_notification);
113 static XS (Collectd_plugin_log);
114 static XS (Collectd__fc_register);
115 static XS (Collectd_call_by_name);
121 typedef struct c_ithread_s {
122 /* the thread's Perl interpreter */
123 PerlInterpreter *interp;
124 _Bool running; /* thread is inside Perl interpreter */
128 /* double linked list of threads */
129 struct c_ithread_s *prev;
130 struct c_ithread_s *next;
138 /* some usage stats */
139 int number_of_threads;
140 #endif /* COLLECT_DEBUG */
142 pthread_mutex_t mutex;
143 pthread_mutexattr_t mutexattr;
146 /* name / user_data for Perl matches / targets */
152 #define PFC_USER_DATA_FREE(data) \
154 sfree ((data)->name); \
155 if (NULL != (data)->user_data) \
156 sv_free ((data)->user_data); \
163 extern char **environ;
169 /* if perl_threads != NULL perl_threads->head must
170 * point to the "base" thread */
171 static c_ithread_list_t *perl_threads = NULL;
173 /* the key used to store each pthread's ithread */
174 static pthread_key_t perl_thr_key;
176 static int perl_argc = 0;
177 static char **perl_argv = NULL;
179 static char base_name[DATA_MAX_NAME_LEN] = "";
186 { "Collectd::plugin_register_data_set", Collectd_plugin_register_ds },
187 { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
188 { "Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values },
189 { "Collectd::plugin_get_interval", Collectd_plugin_get_interval },
190 { "Collectd::_plugin_write", Collectd__plugin_write },
191 { "Collectd::_plugin_flush", Collectd__plugin_flush },
192 { "Collectd::plugin_dispatch_notification",
193 Collectd_plugin_dispatch_notification },
194 { "Collectd::plugin_log", Collectd_plugin_log },
195 { "Collectd::_fc_register", Collectd__fc_register },
196 { "Collectd::call_by_name", Collectd_call_by_name },
205 { "Collectd::TYPE_INIT", PLUGIN_INIT },
206 { "Collectd::TYPE_READ", PLUGIN_READ },
207 { "Collectd::TYPE_WRITE", PLUGIN_WRITE },
208 { "Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN },
209 { "Collectd::TYPE_LOG", PLUGIN_LOG },
210 { "Collectd::TYPE_NOTIF", PLUGIN_NOTIF },
211 { "Collectd::TYPE_FLUSH", PLUGIN_FLUSH },
212 { "Collectd::TYPE_CONFIG", PLUGIN_CONFIG },
213 { "Collectd::TYPE_DATASET", PLUGIN_DATASET },
214 { "Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER },
215 { "Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE },
216 { "Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE },
217 { "Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE },
218 { "Collectd::LOG_ERR", LOG_ERR },
219 { "Collectd::LOG_WARNING", LOG_WARNING },
220 { "Collectd::LOG_NOTICE", LOG_NOTICE },
221 { "Collectd::LOG_INFO", LOG_INFO },
222 { "Collectd::LOG_DEBUG", LOG_DEBUG },
223 { "Collectd::FC_MATCH", FC_MATCH },
224 { "Collectd::FC_TARGET", FC_TARGET },
225 { "Collectd::FC_CB_CREATE", FC_CB_CREATE },
226 { "Collectd::FC_CB_DESTROY", FC_CB_DESTROY },
227 { "Collectd::FC_CB_EXEC", FC_CB_EXEC },
228 { "Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH },
229 { "Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES },
230 { "Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE },
231 { "Collectd::FC_TARGET_STOP", FC_TARGET_STOP },
232 { "Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN },
233 { "Collectd::NOTIF_FAILURE", NOTIF_FAILURE },
234 { "Collectd::NOTIF_WARNING", NOTIF_WARNING },
235 { "Collectd::NOTIF_OKAY", NOTIF_OKAY },
244 { "Collectd::hostname_g", hostname_g },
249 * Helper functions for data type conversion.
264 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
268 if ((NULL == hash) || (NULL == ds))
271 if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
272 sstrncpy (ds->name, SvPV_nolen (*tmp), sizeof (ds->name));
275 log_err ("hv2data_source: No DS name given.");
279 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
280 ds->type = SvIV (*tmp);
282 if ((DS_TYPE_COUNTER != ds->type)
283 && (DS_TYPE_GAUGE != ds->type)
284 && (DS_TYPE_DERIVE != ds->type)
285 && (DS_TYPE_ABSOLUTE != ds->type)) {
286 log_err ("hv2data_source: Invalid DS type.");
291 ds->type = DS_TYPE_COUNTER;
294 if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
295 ds->min = SvNV (*tmp);
299 if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
300 ds->max = SvNV (*tmp);
304 } /* static int hv2data_source (HV *, data_source_t *) */
306 /* av2value converts at most "len" elements from "array" to "value". Returns the
307 * number of elements converted or zero on error. */
308 static size_t av2value (pTHX_ char *name, AV *array, value_t *value, size_t array_len)
310 const data_set_t *ds;
313 if ((NULL == name) || (NULL == array) || (NULL == value) || (array_len == 0))
316 ds = plugin_get_ds (name);
318 log_err ("av2value: Unknown dataset \"%s\"", name);
322 if (array_len < ds->ds_num) {
323 log_warn ("av2value: array does not contain enough elements for type \"%s\": got %zu, want %zu",
324 name, array_len, ds->ds_num);
326 } else if (array_len > ds->ds_num) {
327 log_warn ("av2value: array contains excess elements for type \"%s\": got %zu, want %zu",
328 name, array_len, ds->ds_num);
331 for (i = 0; i < ds->ds_num; ++i) {
332 SV **tmp = av_fetch (array, i, 0);
335 if (DS_TYPE_COUNTER == ds->ds[i].type)
336 value[i].counter = SvIV (*tmp);
337 else if (DS_TYPE_GAUGE == ds->ds[i].type)
338 value[i].gauge = SvNV (*tmp);
339 else if (DS_TYPE_DERIVE == ds->ds[i].type)
340 value[i].derive = SvIV (*tmp);
341 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
342 value[i].absolute = SvIV (*tmp);
350 } /* static size_t av2value (char *, AV *, value_t *, size_t) */
355 * values => [ @values ],
359 * plugin_instance => $pinstance,
360 * type_instance => $tinstance,
363 static int hv2value_list (pTHX_ HV *hash, value_list_t *vl)
367 if ((NULL == hash) || (NULL == vl))
370 if (NULL == (tmp = hv_fetch (hash, "type", 4, 0))) {
371 log_err ("hv2value_list: No type given.");
375 sstrncpy (vl->type, SvPV_nolen (*tmp), sizeof (vl->type));
377 if ((NULL == (tmp = hv_fetch (hash, "values", 6, 0)))
378 || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
379 log_err ("hv2value_list: No valid values given.");
384 AV *array = (AV *)SvRV (*tmp);
385 /* av_len returns the highest index, not the actual length. */
386 size_t array_len = (size_t) (av_len (array) + 1);
390 vl->values = calloc (array_len, sizeof (*vl->values));
391 vl->values_len = av2value (aTHX_ vl->type, (AV *)SvRV (*tmp), vl->values, array_len);
392 if (vl->values_len == 0) {
398 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
400 double t = SvNV (*tmp);
401 vl->time = DOUBLE_TO_CDTIME_T (t);
404 if (NULL != (tmp = hv_fetch (hash, "interval", 8, 0)))
406 double t = SvNV (*tmp);
407 vl->interval = DOUBLE_TO_CDTIME_T (t);
410 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
411 sstrncpy (vl->host, SvPV_nolen (*tmp), sizeof (vl->host));
413 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
415 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
416 sstrncpy (vl->plugin, SvPV_nolen (*tmp), sizeof (vl->plugin));
418 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
419 sstrncpy (vl->plugin_instance, SvPV_nolen (*tmp),
420 sizeof (vl->plugin_instance));
422 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
423 sstrncpy (vl->type_instance, SvPV_nolen (*tmp),
424 sizeof (vl->type_instance));
426 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
428 static int av2data_set (pTHX_ AV *array, char *name, data_set_t *ds)
432 if ((NULL == array) || (NULL == name) || (NULL == ds))
435 len = av_len (array);
438 log_err ("av2data_set: Invalid data set.");
442 ds->ds = smalloc ((len + 1) * sizeof (*ds->ds));
443 ds->ds_num = len + 1;
445 for (i = 0; i <= len; ++i) {
446 SV **elem = av_fetch (array, i, 0);
449 log_err ("av2data_set: Failed to fetch data source %i.", i);
453 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
454 log_err ("av2data_set: Invalid data source.");
458 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds->ds[i]))
461 log_debug ("av2data_set: "
462 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
463 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
466 sstrncpy (ds->type, name, sizeof (ds->type));
468 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
473 * severity => $severity,
479 * plugin_instance => $instance,
480 * type_instance => $type_instance,
481 * meta => [ { name => <name>, value => <value> }, ... ]
484 static int av2notification_meta (pTHX_ AV *array, notification_meta_t **meta)
486 notification_meta_t **m = meta;
488 int len = av_len (array);
491 for (i = 0; i <= len; ++i) {
492 SV **tmp = av_fetch (array, i, 0);
498 if (! (SvROK (*tmp) && (SVt_PVHV == SvTYPE (SvRV (*tmp))))) {
499 log_warn ("av2notification_meta: Skipping invalid "
500 "meta information.");
504 hash = (HV *)SvRV (*tmp);
506 *m = smalloc (sizeof (**m));
508 if (NULL == (tmp = hv_fetch (hash, "name", 4, 0))) {
509 log_warn ("av2notification_meta: Skipping invalid "
510 "meta information.");
514 sstrncpy ((*m)->name, SvPV_nolen (*tmp), sizeof ((*m)->name));
516 if (NULL == (tmp = hv_fetch (hash, "value", 5, 0))) {
517 log_warn ("av2notification_meta: Skipping invalid "
518 "meta information.");
524 (*m)->nm_value.nm_double = SvNVX (*tmp);
525 (*m)->type = NM_TYPE_DOUBLE;
527 else if (SvUOK (*tmp)) {
528 (*m)->nm_value.nm_unsigned_int = SvUVX (*tmp);
529 (*m)->type = NM_TYPE_UNSIGNED_INT;
531 else if (SvIOK (*tmp)) {
532 (*m)->nm_value.nm_signed_int = SvIVX (*tmp);
533 (*m)->type = NM_TYPE_SIGNED_INT;
536 (*m)->nm_value.nm_string = sstrdup (SvPV_nolen (*tmp));
537 (*m)->type = NM_TYPE_STRING;
544 } /* static int av2notification_meta (AV *, notification_meta_t *) */
546 static int hv2notification (pTHX_ HV *hash, notification_t *n)
550 if ((NULL == hash) || (NULL == n))
553 if (NULL != (tmp = hv_fetch (hash, "severity", 8, 0)))
554 n->severity = SvIV (*tmp);
556 n->severity = NOTIF_FAILURE;
558 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
560 double t = SvNV (*tmp);
561 n->time = DOUBLE_TO_CDTIME_T (t);
566 if (NULL != (tmp = hv_fetch (hash, "message", 7, 0)))
567 sstrncpy (n->message, SvPV_nolen (*tmp), sizeof (n->message));
569 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
570 sstrncpy (n->host, SvPV_nolen (*tmp), sizeof (n->host));
572 sstrncpy (n->host, hostname_g, sizeof (n->host));
574 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
575 sstrncpy (n->plugin, SvPV_nolen (*tmp), sizeof (n->plugin));
577 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
578 sstrncpy (n->plugin_instance, SvPV_nolen (*tmp),
579 sizeof (n->plugin_instance));
581 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0)))
582 sstrncpy (n->type, SvPV_nolen (*tmp), sizeof (n->type));
584 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
585 sstrncpy (n->type_instance, SvPV_nolen (*tmp),
586 sizeof (n->type_instance));
589 while (NULL != (tmp = hv_fetch (hash, "meta", 4, 0))) {
590 if (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp))))) {
591 log_warn ("hv2notification: Ignoring invalid meta information.");
595 if (0 != av2notification_meta (aTHX_ (AV *)SvRV (*tmp), &n->meta)) {
596 plugin_notification_meta_free (n->meta);
603 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
605 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
609 if ((NULL == ds) || (NULL == array))
612 av_extend (array, ds->ds_num);
614 for (i = 0; i < ds->ds_num; ++i) {
615 HV *source = newHV ();
617 if (NULL == hv_store (source, "name", 4,
618 newSVpv (ds->ds[i].name, 0), 0))
621 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
624 if (! isnan (ds->ds[i].min))
625 if (NULL == hv_store (source, "min", 3,
626 newSVnv (ds->ds[i].min), 0))
629 if (! isnan (ds->ds[i].max))
630 if (NULL == hv_store (source, "max", 3,
631 newSVnv (ds->ds[i].max), 0))
634 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
638 } /* static int data_set2av (data_set_t *, AV *) */
640 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
645 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
649 /* av_extend takes the last *index* to which the array should be extended. */
650 av_extend (values, vl->values_len - 1);
652 assert (ds->ds_num == vl->values_len);
653 for (i = 0; i < vl->values_len; ++i) {
656 if (DS_TYPE_COUNTER == ds->ds[i].type)
657 val = newSViv (vl->values[i].counter);
658 else if (DS_TYPE_GAUGE == ds->ds[i].type)
659 val = newSVnv (vl->values[i].gauge);
660 else if (DS_TYPE_DERIVE == ds->ds[i].type)
661 val = newSViv (vl->values[i].derive);
662 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
663 val = newSViv (vl->values[i].absolute);
665 if (NULL == av_store (values, i, val)) {
671 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
676 double t = CDTIME_T_TO_DOUBLE (vl->time);
677 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
682 double t = CDTIME_T_TO_DOUBLE (vl->interval);
683 if (NULL == hv_store (hash, "interval", 8, newSVnv (t), 0))
687 if ('\0' != vl->host[0])
688 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
691 if ('\0' != vl->plugin[0])
692 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
695 if ('\0' != vl->plugin_instance[0])
696 if (NULL == hv_store (hash, "plugin_instance", 15,
697 newSVpv (vl->plugin_instance, 0), 0))
700 if ('\0' != vl->type[0])
701 if (NULL == hv_store (hash, "type", 4, newSVpv (vl->type, 0), 0))
704 if ('\0' != vl->type_instance[0])
705 if (NULL == hv_store (hash, "type_instance", 13,
706 newSVpv (vl->type_instance, 0), 0))
709 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
711 static int notification_meta2av (pTHX_ notification_meta_t *meta, AV *array)
721 av_extend (array, meta_num);
723 for (i = 0; NULL != meta; meta = meta->next, ++i) {
727 if (NULL == hv_store (m, "name", 4, newSVpv (meta->name, 0), 0))
730 if (NM_TYPE_STRING == meta->type)
731 value = newSVpv (meta->nm_value.nm_string, 0);
732 else if (NM_TYPE_SIGNED_INT == meta->type)
733 value = newSViv (meta->nm_value.nm_signed_int);
734 else if (NM_TYPE_UNSIGNED_INT == meta->type)
735 value = newSVuv (meta->nm_value.nm_unsigned_int);
736 else if (NM_TYPE_DOUBLE == meta->type)
737 value = newSVnv (meta->nm_value.nm_double);
738 else if (NM_TYPE_BOOLEAN == meta->type)
739 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
743 if (NULL == hv_store (m, "value", 5, value, 0)) {
748 if (NULL == av_store (array, i, newRV_noinc ((SV *)m))) {
755 } /* static int notification_meta2av (notification_meta_t *, AV *) */
757 static int notification2hv (pTHX_ notification_t *n, HV *hash)
759 if (NULL == hv_store (hash, "severity", 8, newSViv (n->severity), 0))
764 double t = CDTIME_T_TO_DOUBLE (n->time);
765 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
769 if ('\0' != *n->message)
770 if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
773 if ('\0' != *n->host)
774 if (NULL == hv_store (hash, "host", 4, newSVpv (n->host, 0), 0))
777 if ('\0' != *n->plugin)
778 if (NULL == hv_store (hash, "plugin", 6, newSVpv (n->plugin, 0), 0))
781 if ('\0' != *n->plugin_instance)
782 if (NULL == hv_store (hash, "plugin_instance", 15,
783 newSVpv (n->plugin_instance, 0), 0))
786 if ('\0' != *n->type)
787 if (NULL == hv_store (hash, "type", 4, newSVpv (n->type, 0), 0))
790 if ('\0' != *n->type_instance)
791 if (NULL == hv_store (hash, "type_instance", 13,
792 newSVpv (n->type_instance, 0), 0))
795 if (NULL != n->meta) {
797 if ((0 != notification_meta2av (aTHX_ n->meta, meta))
798 || (NULL == hv_store (hash, "meta", 4,
799 newRV_noinc ((SV *)meta), 0))) {
806 } /* static int notification2hv (notification_t *, HV *) */
808 static int oconfig_item2hv (pTHX_ oconfig_item_t *ci, HV *hash)
815 if (NULL == hv_store (hash, "key", 3, newSVpv (ci->key, 0), 0))
819 if (0 < ci->values_num)
820 av_extend (values, ci->values_num);
822 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0)) {
828 for (i = 0; i < ci->values_num; ++i) {
831 switch (ci->values[i].type) {
832 case OCONFIG_TYPE_STRING:
833 value = newSVpv (ci->values[i].value.string, 0);
835 case OCONFIG_TYPE_NUMBER:
836 value = newSVnv ((NV)ci->values[i].value.number);
838 case OCONFIG_TYPE_BOOLEAN:
839 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
842 log_err ("oconfig_item2hv: Invalid value type %i.",
844 value = &PL_sv_undef;
847 if (NULL == av_store (values, i, value)) {
853 /* ignoring 'parent' member which is uninteresting in this case */
856 if (0 < ci->children_num)
857 av_extend (children, ci->children_num);
859 if (NULL == hv_store (hash, "children", 8, newRV_noinc ((SV *)children), 0)) {
865 for (i = 0; i < ci->children_num; ++i) {
866 HV *child = newHV ();
868 if (0 != oconfig_item2hv (aTHX_ ci->children + i, child)) {
874 if (NULL == av_store (children, i, newRV_noinc ((SV *)child))) {
881 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
884 * Internal functions.
887 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
889 if (base_name[0] == '\0')
890 status = ssnprintf (buf, buf_len, "%s", module);
892 status = ssnprintf (buf, buf_len, "%s::%s", base_name, module);
893 if ((status < 0) || ((unsigned int)status >= buf_len))
896 } /* char *get_module_name */
899 * Add a plugin's data set definition.
901 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
907 if ((NULL == name) || (NULL == dataset))
910 if (0 != av2data_set (aTHX_ dataset, name, &ds))
913 ret = plugin_register_data_set (&ds);
917 } /* static int pplugin_register_data_set (char *, SV *) */
920 * Remove a plugin's data set definition.
922 static int pplugin_unregister_data_set (char *name)
926 return plugin_unregister_data_set (name);
927 } /* static int pplugin_unregister_data_set (char *) */
930 * Submit the values to the write functions.
932 static int pplugin_dispatch_values (pTHX_ HV *values)
934 value_list_t vl = VALUE_LIST_INIT;
941 if (0 != hv2value_list (aTHX_ values, &vl))
944 ret = plugin_dispatch_values (&vl);
948 } /* static int pplugin_dispatch_values (char *, HV *) */
951 * Submit the values to a single write function.
953 static int pplugin_write (pTHX_ const char *plugin, AV *data_set, HV *values)
956 value_list_t vl = VALUE_LIST_INIT;
963 if (0 != hv2value_list (aTHX_ values, &vl))
966 if ((NULL != data_set)
967 && (0 != av2data_set (aTHX_ data_set, vl.type, &ds)))
970 ret = plugin_write (plugin, NULL == data_set ? NULL : &ds, &vl);
972 log_warn ("Dispatching value to plugin \"%s\" failed with status %i.",
973 NULL == plugin ? "<any>" : plugin, ret);
975 if (NULL != data_set)
979 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
982 * Dispatch a notification.
984 static int pplugin_dispatch_notification (pTHX_ HV *notif)
993 memset (&n, 0, sizeof (n));
995 if (0 != hv2notification (aTHX_ notif, &n))
998 ret = plugin_dispatch_notification (&n);
999 plugin_notification_meta_free (n.meta);
1001 } /* static int pplugin_dispatch_notification (HV *) */
1004 * Call perl sub with thread locking flags handled.
1006 static int call_pv_locked (pTHX_ const char* sub_name)
1011 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
1012 if (t == NULL) /* thread destroyed */
1015 old_running = t->running;
1019 t->running = old_running;
1023 ret = call_pv (sub_name, G_SCALAR);
1025 t->running = old_running;
1027 } /* static int call_pv_locked (pTHX, *sub_name) */
1030 * Call all working functions of the given type.
1032 static int pplugin_call_all (pTHX_ int type, ...)
1041 if ((type < 0) || (type >= PLUGIN_TYPES))
1044 va_start (ap, type);
1051 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1053 if (PLUGIN_WRITE == type) {
1055 * $_[0] = $plugin_type;
1070 * values => [ $v1, ... ],
1072 * host => $hostname,
1073 * plugin => $plugin,
1075 * plugin_instance => $instance,
1076 * type_instance => $type_instance
1085 ds = va_arg (ap, data_set_t *);
1086 vl = va_arg (ap, value_list_t *);
1088 if (-1 == data_set2av (aTHX_ ds, pds)) {
1091 pds = (AV *)&PL_sv_undef;
1095 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
1098 pvl = (HV *)&PL_sv_undef;
1102 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
1103 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1104 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1106 else if (PLUGIN_LOG == type) {
1112 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1113 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1115 else if (PLUGIN_NOTIF == type) {
1119 * severity => $severity,
1123 * plugin => $plugin,
1125 * plugin_instance => $instance,
1126 * type_instance => $type_instance
1130 HV *notif = newHV ();
1132 n = va_arg (ap, notification_t *);
1134 if (-1 == notification2hv (aTHX_ n, notif)) {
1137 notif = (HV *)&PL_sv_undef;
1141 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
1143 else if (PLUGIN_FLUSH == type) {
1148 * $_[1] = $identifier;
1150 timeout = va_arg (ap, cdtime_t);
1152 XPUSHs (sv_2mortal (newSVnv (CDTIME_T_TO_DOUBLE (timeout))));
1153 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1158 retvals = call_pv_locked (aTHX_ "Collectd::plugin_call_all");
1173 } /* static int pplugin_call_all (int, ...) */
1176 * collectd's Perl interpreter based thread implementation.
1178 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1181 /* must be called with perl_threads->mutex locked */
1182 static void c_ithread_destroy (c_ithread_t *ithread)
1184 dTHXa (ithread->interp);
1186 assert (NULL != perl_threads);
1188 PERL_SET_CONTEXT (aTHX);
1189 log_debug ("Shutting down Perl interpreter %p...", aTHX);
1194 --perl_threads->number_of_threads;
1195 #endif /* COLLECT_DEBUG */
1197 perl_destruct (aTHX);
1200 if (NULL == ithread->prev)
1201 perl_threads->head = ithread->next;
1203 ithread->prev->next = ithread->next;
1205 if (NULL == ithread->next)
1206 perl_threads->tail = ithread->prev;
1208 ithread->next->prev = ithread->prev;
1212 } /* static void c_ithread_destroy (c_ithread_t *) */
1214 static void c_ithread_destructor (void *arg)
1216 c_ithread_t *ithread = (c_ithread_t *)arg;
1217 c_ithread_t *t = NULL;
1219 if (NULL == perl_threads)
1222 pthread_mutex_lock (&perl_threads->mutex);
1224 for (t = perl_threads->head; NULL != t; t = t->next)
1228 /* the ithread no longer exists */
1231 pthread_mutex_unlock (&perl_threads->mutex);
1235 c_ithread_destroy (ithread);
1237 pthread_mutex_unlock (&perl_threads->mutex);
1239 } /* static void c_ithread_destructor (void *) */
1241 /* must be called with perl_threads->mutex locked */
1242 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1244 c_ithread_t *t = NULL;
1247 assert (NULL != perl_threads);
1249 t = smalloc (sizeof (*t));
1250 memset (t, 0, sizeof (c_ithread_t));
1252 t->interp = (NULL == base)
1254 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1258 if ((NULL != base) && (NULL != PL_endav)) {
1259 av_clear (PL_endav);
1260 av_undef (PL_endav);
1265 ++perl_threads->number_of_threads;
1266 #endif /* COLLECT_DEBUG */
1270 if (NULL == perl_threads->tail) {
1271 perl_threads->head = t;
1275 perl_threads->tail->next = t;
1276 t->prev = perl_threads->tail;
1279 t->pthread = pthread_self();
1282 perl_threads->tail = t;
1284 pthread_setspecific (perl_thr_key, (const void *)t);
1286 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1289 * Filter chains implementation.
1292 static int fc_call (pTHX_ int type, int cb_type, pfc_user_data_t *data, ...)
1299 notification_meta_t **meta = NULL;
1304 if ((type < 0) || (type >= FC_TYPES))
1307 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1310 va_start (ap, data);
1317 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1318 XPUSHs (sv_2mortal (newSVpv (data->name, 0)));
1319 XPUSHs (sv_2mortal (newSViv ((IV)cb_type)));
1321 if (FC_CB_CREATE == cb_type) {
1324 * $_[1] = $user_data;
1327 HV *config = newHV ();
1329 ci = va_arg (ap, oconfig_item_t *);
1331 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
1334 config = (HV *)&PL_sv_undef;
1338 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
1340 else if (FC_CB_DESTROY == cb_type) {
1342 * $_[1] = $user_data;
1345 /* nothing to be done - the user data pointer
1346 * is pushed onto the stack later */
1348 else if (FC_CB_EXEC == cb_type) {
1353 * $_[3] = $user_data;
1361 ds = va_arg (ap, data_set_t *);
1362 vl = va_arg (ap, value_list_t *);
1363 meta = va_arg (ap, notification_meta_t **);
1365 if (0 != data_set2av (aTHX_ ds, pds)) {
1368 pds = (AV *)&PL_sv_undef;
1372 if (0 != value_list2hv (aTHX_ vl, ds, pvl)) {
1375 pvl = (HV *)&PL_sv_undef;
1382 if (0 != notification_meta2av (aTHX_ *meta, pmeta)) {
1385 pmeta = (AV *)&PL_sv_undef;
1390 pmeta = (AV *)&PL_sv_undef;
1393 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1394 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1395 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pmeta)));
1398 XPUSHs (sv_2mortal (newRV_inc (data->user_data)));
1402 retvals = call_pv_locked (aTHX_ "Collectd::fc_call");
1404 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1405 assert (pmeta != NULL);
1407 plugin_notification_meta_free (*meta);
1408 av2notification_meta (aTHX_ pmeta, meta);
1415 /* the exec callbacks return a status, while
1416 * the others return a boolean value */
1417 if (FC_CB_EXEC == cb_type)
1419 else if (! SvTRUE (tmp))
1429 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1431 static int fc_create (int type, const oconfig_item_t *ci, void **user_data)
1433 pfc_user_data_t *data;
1439 if (NULL == perl_threads)
1443 c_ithread_t *t = NULL;
1445 pthread_mutex_lock (&perl_threads->mutex);
1446 t = c_ithread_create (perl_threads->head->interp);
1447 pthread_mutex_unlock (&perl_threads->mutex);
1452 log_debug ("fc_create: c_ithread: interp = %p (active threads: %i)",
1453 aTHX, perl_threads->number_of_threads);
1455 if ((1 != ci->values_num)
1456 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1457 log_warn ("A \"%s\" block expects a single string argument.",
1458 (FC_MATCH == type) ? "Match" : "Target");
1462 data = smalloc (sizeof (*data));
1463 data->name = sstrdup (ci->values[0].value.string);
1464 data->user_data = newSV (0);
1466 ret = fc_call (aTHX_ type, FC_CB_CREATE, data, ci);
1469 PFC_USER_DATA_FREE (data);
1473 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1475 static int fc_destroy (int type, void **user_data)
1477 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1483 if ((NULL == perl_threads) || (NULL == data))
1487 c_ithread_t *t = NULL;
1489 pthread_mutex_lock (&perl_threads->mutex);
1490 t = c_ithread_create (perl_threads->head->interp);
1491 pthread_mutex_unlock (&perl_threads->mutex);
1496 log_debug ("fc_destroy: c_ithread: interp = %p (active threads: %i)",
1497 aTHX, perl_threads->number_of_threads);
1499 ret = fc_call (aTHX_ type, FC_CB_DESTROY, data);
1501 PFC_USER_DATA_FREE (data);
1504 } /* static int fc_destroy (int, void **) */
1506 static int fc_exec (int type, const data_set_t *ds, const value_list_t *vl,
1507 notification_meta_t **meta, void **user_data)
1509 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1513 if (NULL == perl_threads)
1516 assert (NULL != data);
1519 c_ithread_t *t = NULL;
1521 pthread_mutex_lock (&perl_threads->mutex);
1522 t = c_ithread_create (perl_threads->head->interp);
1523 pthread_mutex_unlock (&perl_threads->mutex);
1528 log_debug ("fc_exec: c_ithread: interp = %p (active threads: %i)",
1529 aTHX, perl_threads->number_of_threads);
1531 return fc_call (aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1532 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1533 notification_meta_t **, void **) */
1535 static int pmatch_create (const oconfig_item_t *ci, void **user_data)
1537 return fc_create (FC_MATCH, ci, user_data);
1538 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1540 static int pmatch_destroy (void **user_data)
1542 return fc_destroy (FC_MATCH, user_data);
1543 } /* static int pmatch_destroy (void **) */
1545 static int pmatch_match (const data_set_t *ds, const value_list_t *vl,
1546 notification_meta_t **meta, void **user_data)
1548 return fc_exec (FC_MATCH, ds, vl, meta, user_data);
1549 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1550 notification_meta_t **, void **) */
1552 static match_proc_t pmatch = {
1553 pmatch_create, pmatch_destroy, pmatch_match
1556 static int ptarget_create (const oconfig_item_t *ci, void **user_data)
1558 return fc_create (FC_TARGET, ci, user_data);
1559 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1561 static int ptarget_destroy (void **user_data)
1563 return fc_destroy (FC_TARGET, user_data);
1564 } /* static int ptarget_destroy (void **) */
1566 static int ptarget_invoke (const data_set_t *ds, value_list_t *vl,
1567 notification_meta_t **meta, void **user_data)
1569 return fc_exec (FC_TARGET, ds, vl, meta, user_data);
1570 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1571 notification_meta_t **, void **) */
1573 static target_proc_t ptarget = {
1574 ptarget_create, ptarget_destroy, ptarget_invoke
1578 * Exported Perl API.
1582 * Collectd::plugin_register_data_set (type, dataset).
1585 * type of the dataset
1588 * dataset to be registered
1590 static XS (Collectd_plugin_register_ds)
1597 log_warn ("Using plugin_register() to register new data-sets is "
1598 "deprecated - add new entries to a custom types.db instead.");
1601 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1605 log_debug ("Collectd::plugin_register_data_set: "
1606 "type = \"%s\", dataset = \"%s\"",
1607 SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1611 if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1612 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1616 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1624 } /* static XS (Collectd_plugin_register_ds) */
1627 * Collectd::plugin_unregister_data_set (type).
1630 * type of the dataset
1632 static XS (Collectd_plugin_unregister_ds)
1637 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1641 log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1642 SvPV_nolen (ST (0)));
1644 if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1648 } /* static XS (Collectd_plugin_register_ds) */
1651 * Collectd::plugin_dispatch_values (name, values).
1654 * name of the plugin
1657 * value list to submit
1659 static XS (Collectd_plugin_dispatch_values)
1668 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1672 log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1673 SvPV_nolen (ST (/* stack index = */ 0)));
1675 values = ST (/* stack index = */ 0);
1680 /* Make sure the argument is a hash reference. */
1681 if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1682 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1686 ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1692 } /* static XS (Collectd_plugin_dispatch_values) */
1695 * Collectd::plugin_get_interval ().
1697 static XS (Collectd_plugin_get_interval)
1701 /* make sure we don't get any unused variable warnings for 'items';
1702 * don't abort, though */
1704 log_err ("Usage: Collectd::plugin_get_interval()");
1706 XSRETURN_NV ((NV) CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
1707 } /* static XS (Collectd_plugin_get_interval) */
1709 /* Collectd::plugin_write (plugin, ds, vl).
1712 * name of the plugin to call, may be 'undef'
1715 * data-set that describes the submitted values, may be 'undef'
1718 * value-list to be written
1720 static XS (Collectd__plugin_write)
1731 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1735 log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1736 SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1737 SvPV_nolen (ST (2)));
1739 if (! SvOK (ST (0)))
1742 plugin = SvPV_nolen (ST (0));
1745 if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1746 ds_array = (AV *)SvRV (ds);
1747 else if (! SvOK (ds))
1750 log_err ("Collectd::plugin_write: Invalid data-set.");
1755 if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1756 log_err ("Collectd::plugin_write: Invalid value-list.");
1760 ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1766 } /* static XS (Collectd__plugin_write) */
1769 * Collectd::_plugin_flush (plugin, timeout, identifier).
1772 * name of the plugin to flush
1775 * timeout to use when flushing the data
1778 * data-set identifier to flush
1780 static XS (Collectd__plugin_flush)
1782 char *plugin = NULL;
1789 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1794 plugin = SvPV_nolen (ST (0));
1797 timeout = (int)SvIV (ST (1));
1800 id = SvPV_nolen (ST (2));
1802 log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1803 "id = \"%s\"", plugin, timeout, id);
1805 if (0 == plugin_flush (plugin, timeout, id))
1809 } /* static XS (Collectd__plugin_flush) */
1812 * Collectd::plugin_dispatch_notification (notif).
1815 * notification to dispatch
1817 static XS (Collectd_plugin_dispatch_notification)
1826 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
1830 log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1831 SvPV_nolen (ST (0)));
1835 if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
1836 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
1840 ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
1846 } /* static XS (Collectd_plugin_dispatch_notification) */
1849 * Collectd::plugin_log (level, message).
1852 * log level (LOG_DEBUG, ... LOG_ERR)
1857 static XS (Collectd_plugin_log)
1862 log_err ("Usage: Collectd::plugin_log(level, message)");
1866 plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
1868 } /* static XS (Collectd_plugin_log) */
1871 * Collectd::_fc_register (type, name)
1879 static XS (Collectd__fc_register)
1889 log_err ("Usage: Collectd::_fc_register(type, name)");
1893 type = SvIV (ST (0));
1894 name = SvPV_nolen (ST (1));
1896 if (FC_MATCH == type)
1897 ret = fc_register_match (name, pmatch);
1898 else if (FC_TARGET == type)
1899 ret = fc_register_target (name, ptarget);
1905 } /* static XS (Collectd_fc_register) */
1908 * Collectd::call_by_name (...).
1910 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1912 static XS (Collectd_call_by_name)
1917 if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
1918 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
1923 name = SvPV_nolen (tmp);
1925 if (NULL == get_cv (name, 0)) {
1926 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
1931 /* simply pass on the subroutine call without touching the stack,
1932 * thus leaving any arguments and return values in place */
1934 } /* static XS (Collectd_call_by_name) */
1937 * Interface to collectd.
1940 static int perl_init (void)
1945 if (NULL == perl_threads)
1949 c_ithread_t *t = NULL;
1951 pthread_mutex_lock (&perl_threads->mutex);
1952 t = c_ithread_create (perl_threads->head->interp);
1953 pthread_mutex_unlock (&perl_threads->mutex);
1958 log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1959 aTHX, perl_threads->number_of_threads);
1961 /* Lock the base thread to avoid race conditions with c_ithread_create().
1962 * See https://github.com/collectd/collectd/issues/9 and
1963 * https://github.com/collectd/collectd/issues/1706 for details.
1965 assert (aTHX == perl_threads->head->interp);
1966 pthread_mutex_lock (&perl_threads->mutex);
1968 status = pplugin_call_all (aTHX_ PLUGIN_INIT);
1970 pthread_mutex_unlock (&perl_threads->mutex);
1973 } /* static int perl_init (void) */
1975 static int perl_read (void)
1979 if (NULL == perl_threads)
1983 c_ithread_t *t = NULL;
1985 pthread_mutex_lock (&perl_threads->mutex);
1986 t = c_ithread_create (perl_threads->head->interp);
1987 pthread_mutex_unlock (&perl_threads->mutex);
1992 /* Assert that we're not running as the base thread. Otherwise, we might
1993 * run into concurrency issues with c_ithread_create(). See
1994 * https://github.com/collectd/collectd/issues/9 for details. */
1995 assert (aTHX != perl_threads->head->interp);
1997 log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1998 aTHX, perl_threads->number_of_threads);
1999 return pplugin_call_all (aTHX_ PLUGIN_READ);
2000 } /* static int perl_read (void) */
2002 static int perl_write (const data_set_t *ds, const value_list_t *vl,
2003 user_data_t __attribute__((unused)) *user_data)
2008 if (NULL == perl_threads)
2012 c_ithread_t *t = NULL;
2014 pthread_mutex_lock (&perl_threads->mutex);
2015 t = c_ithread_create (perl_threads->head->interp);
2016 pthread_mutex_unlock (&perl_threads->mutex);
2021 /* Lock the base thread if this is not called from one of the read threads
2022 * to avoid race conditions with c_ithread_create(). See
2023 * https://github.com/collectd/collectd/issues/9 for details. */
2024 if (aTHX == perl_threads->head->interp)
2025 pthread_mutex_lock (&perl_threads->mutex);
2027 log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
2028 aTHX, perl_threads->number_of_threads);
2029 status = pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
2031 if (aTHX == perl_threads->head->interp)
2032 pthread_mutex_unlock (&perl_threads->mutex);
2035 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2037 static void perl_log (int level, const char *msg,
2038 user_data_t __attribute__((unused)) *user_data)
2042 if (NULL == perl_threads)
2046 c_ithread_t *t = NULL;
2048 pthread_mutex_lock (&perl_threads->mutex);
2049 t = c_ithread_create (perl_threads->head->interp);
2050 pthread_mutex_unlock (&perl_threads->mutex);
2055 /* Lock the base thread if this is not called from one of the read threads
2056 * to avoid race conditions with c_ithread_create(). See
2057 * https://github.com/collectd/collectd/issues/9 for details.
2060 if (aTHX == perl_threads->head->interp)
2061 pthread_mutex_lock (&perl_threads->mutex);
2063 pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
2065 if (aTHX == perl_threads->head->interp)
2066 pthread_mutex_unlock (&perl_threads->mutex);
2069 } /* static void perl_log (int, const char *) */
2071 static int perl_notify (const notification_t *notif,
2072 user_data_t __attribute__((unused)) *user_data)
2076 if (NULL == perl_threads)
2080 c_ithread_t *t = NULL;
2082 pthread_mutex_lock (&perl_threads->mutex);
2083 t = c_ithread_create (perl_threads->head->interp);
2084 pthread_mutex_unlock (&perl_threads->mutex);
2088 return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
2089 } /* static int perl_notify (const notification_t *) */
2091 static int perl_flush (cdtime_t timeout, const char *identifier,
2092 user_data_t __attribute__((unused)) *user_data)
2096 if (NULL == perl_threads)
2100 c_ithread_t *t = NULL;
2102 pthread_mutex_lock (&perl_threads->mutex);
2103 t = c_ithread_create (perl_threads->head->interp);
2104 pthread_mutex_unlock (&perl_threads->mutex);
2108 return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout, identifier);
2109 } /* static int perl_flush (const int) */
2111 static int perl_shutdown (void)
2118 plugin_unregister_complex_config ("perl");
2120 if (NULL == perl_threads)
2124 pthread_mutex_lock (&perl_threads->mutex);
2125 t = c_ithread_create (perl_threads->head->interp);
2126 pthread_mutex_unlock (&perl_threads->mutex);
2131 log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2132 aTHX, perl_threads->number_of_threads);
2134 plugin_unregister_log ("perl");
2135 plugin_unregister_notification ("perl");
2136 plugin_unregister_init ("perl");
2137 plugin_unregister_read ("perl");
2138 plugin_unregister_write ("perl");
2139 plugin_unregister_flush ("perl");
2141 ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
2143 pthread_mutex_lock (&perl_threads->mutex);
2144 t = perl_threads->tail;
2147 struct timespec ts_wait;
2148 c_ithread_t *thr = t;
2150 /* the pointer has to be advanced before destroying
2151 * the thread as this will free the memory */
2156 /* Give some time to thread to exit from Perl interpreter */
2157 WARNING ("perl shutdown: Thread is running inside Perl. Waiting.");
2159 ts_wait.tv_nsec = 500000;
2160 nanosleep (&ts_wait, NULL);
2163 pthread_kill (thr->pthread, SIGTERM);
2164 ERROR ("perl shutdown: Thread hangs inside Perl. Thread killed.");
2166 c_ithread_destroy (thr);
2169 pthread_mutex_unlock (&perl_threads->mutex);
2170 pthread_mutex_destroy (&perl_threads->mutex);
2171 pthread_mutexattr_destroy (&perl_threads->mutexattr);
2173 sfree (perl_threads);
2175 pthread_key_delete (perl_thr_key);
2179 plugin_unregister_shutdown ("perl");
2181 } /* static void perl_shutdown (void) */
2184 * Access functions for global variables.
2186 * These functions implement the "magic" used to access
2187 * the global variables from Perl.
2190 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
2192 char *pv = mg->mg_ptr;
2195 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2197 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
2199 char *pv = mg->mg_ptr;
2200 sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
2202 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2204 static int g_interval_get (pTHX_ SV *var, MAGIC *mg)
2206 log_warn ("Accessing $interval_g is deprecated (and might not "
2207 "give the desired results) - plugin_get_interval() should "
2208 "be used instead.");
2209 sv_setnv (var, CDTIME_T_TO_DOUBLE (interval_g));
2211 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2213 static int g_interval_set (pTHX_ SV *var, MAGIC *mg)
2215 double nv = (double)SvNV (var);
2216 log_warn ("Accessing $interval_g is deprecated (and might not "
2217 "give the desired results) - plugin_get_interval() should "
2218 "be used instead.");
2219 interval_g = DOUBLE_TO_CDTIME_T (nv);
2221 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2223 static MGVTBL g_pv_vtbl = {
2224 g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2225 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2229 static MGVTBL g_interval_vtbl = {
2230 g_interval_get, g_interval_set, NULL, NULL, NULL, NULL, NULL
2231 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2236 /* bootstrap the Collectd module */
2237 static void xs_init (pTHX)
2241 char *file = __FILE__;
2247 /* enable usage of Perl modules using shared libraries */
2248 newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2251 for (i = 0; NULL != api[i].f; ++i)
2252 newXS (api[i].name, api[i].f, file);
2254 stash = gv_stashpv ("Collectd", 1);
2256 /* export "constants" */
2257 for (i = 0; '\0' != constants[i].name[0]; ++i)
2258 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
2260 /* export global variables
2261 * by adding "magic" to the SV's representing the globale variables
2262 * perl is able to automagically call the get/set function when
2263 * accessing any such variable (this is basically the same as using
2265 /* global strings */
2266 for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
2267 tmp = get_sv (g_strings[i].name, 1);
2268 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
2269 g_strings[i].var, 0);
2272 tmp = get_sv ("Collectd::interval_g", /* create = */ 1);
2273 sv_magicext (tmp, NULL, /* how = */ PERL_MAGIC_ext,
2274 /* vtbl = */ &g_interval_vtbl,
2275 /* name = */ NULL, /* namelen = */ 0);
2278 } /* static void xs_init (pTHX) */
2280 /* Initialize the global Perl interpreter. */
2281 static int init_pi (int argc, char **argv)
2285 if (NULL != perl_threads)
2288 log_info ("Initializing Perl interpreter...");
2293 for (i = 0; i < argc; ++i)
2294 log_debug ("argv[%i] = \"%s\"", i, argv[i]);
2296 #endif /* COLLECT_DEBUG */
2298 if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
2299 log_err ("init_pi: pthread_key_create failed");
2301 /* this must not happen - cowardly giving up if it does */
2306 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2307 * triggers a "value computed is not used" warning by gcc. */
2310 PERL_SYS_INIT3 (&argc, &argv, &environ);
2312 perl_threads = smalloc (sizeof (*perl_threads));
2313 memset (perl_threads, 0, sizeof (c_ithread_list_t));
2315 pthread_mutexattr_init(&perl_threads->mutexattr);
2316 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2317 pthread_mutex_init (&perl_threads->mutex, &perl_threads->mutexattr);
2318 /* locking the mutex should not be necessary at this point
2319 * but let's just do it for the sake of completeness */
2320 pthread_mutex_lock (&perl_threads->mutex);
2322 perl_threads->head = c_ithread_create (NULL);
2323 perl_threads->tail = perl_threads->head;
2325 if (NULL == (perl_threads->head->interp = perl_alloc ())) {
2326 log_err ("init_pi: Not enough memory.");
2330 aTHX = perl_threads->head->interp;
2331 pthread_mutex_unlock (&perl_threads->mutex);
2333 perl_construct (aTHX);
2335 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2337 if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
2338 SV *err = get_sv ("@", 1);
2339 log_err ("init_pi: Unable to bootstrap Collectd: %s",
2342 perl_destruct (perl_threads->head->interp);
2343 perl_free (perl_threads->head->interp);
2344 sfree (perl_threads);
2346 pthread_key_delete (perl_thr_key);
2350 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2351 sv_setpv (get_sv ("0", 0), "collectd");
2355 plugin_register_log ("perl", perl_log, /* user_data = */ NULL);
2356 plugin_register_notification ("perl", perl_notify,
2357 /* user_data = */ NULL);
2358 plugin_register_init ("perl", perl_init);
2360 plugin_register_read ("perl", perl_read);
2362 plugin_register_write ("perl", perl_write, /* user_data = */ NULL);
2363 plugin_register_flush ("perl", perl_flush, /* user_data = */ NULL);
2364 plugin_register_shutdown ("perl", perl_shutdown);
2366 } /* static int init_pi (const char **, const int) */
2369 * LoadPlugin "<Plugin>"
2371 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
2373 char module_name[DATA_MAX_NAME_LEN];
2377 if ((0 != ci->children_num) || (1 != ci->values_num)
2378 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2379 log_err ("LoadPlugin expects a single string argument.");
2383 value = ci->values[0].value.string;
2385 if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
2386 log_err ("Invalid module name %s", value);
2390 if (0 != init_pi (perl_argc, perl_argv))
2393 assert (NULL != perl_threads);
2394 assert (NULL != perl_threads->head);
2396 aTHX = perl_threads->head->interp;
2398 log_debug ("perl_config: Loading Perl plugin \"%s\"", value);
2399 load_module (PERL_LOADMOD_NOIMPORT,
2400 newSVpv (module_name, strlen (module_name)), Nullsv);
2402 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2407 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
2411 if ((0 != ci->children_num) || (1 != ci->values_num)
2412 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2413 log_err ("BaseName expects a single string argument.");
2417 value = ci->values[0].value.string;
2419 log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
2420 sstrncpy (base_name, value, sizeof (base_name));
2422 } /* static int perl_config_basename (oconfig_item_it *) */
2425 * EnableDebugger "<Package>"|""
2427 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
2431 if ((0 != ci->children_num) || (1 != ci->values_num)
2432 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2433 log_err ("EnableDebugger expects a single string argument.");
2437 if (NULL != perl_threads) {
2438 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
2442 value = ci->values[0].value.string;
2444 perl_argv = realloc (perl_argv,
2445 (++perl_argc + 1) * sizeof (char *));
2447 if (NULL == perl_argv) {
2448 log_err ("perl_config: Not enough memory.");
2452 if ('\0' == value[0]) {
2453 perl_argv[perl_argc - 1] = "-d";
2456 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 4);
2457 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
2458 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
2461 perl_argv[perl_argc] = NULL;
2463 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2466 * IncludeDir "<Dir>"
2468 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
2472 if ((0 != ci->children_num) || (1 != ci->values_num)
2473 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2474 log_err ("IncludeDir expects a single string argument.");
2478 value = ci->values[0].value.string;
2481 perl_argv = realloc (perl_argv,
2482 (++perl_argc + 1) * sizeof (char *));
2484 if (NULL == perl_argv) {
2485 log_err ("perl_config: Not enough memory.");
2489 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 3);
2490 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2491 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
2493 perl_argv[perl_argc] = NULL;
2496 /* prepend the directory to @INC */
2497 av_unshift (GvAVn (PL_incgv), 1);
2498 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
2501 } /* static int perl_config_includedir (oconfig_item_it *) */
2506 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2516 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2517 log_err ("LoadPlugin expects a single string argument.");
2521 plugin = ci->values[0].value.string;
2524 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2528 log_err ("Unable to convert configuration to a Perl hash value.");
2529 config = (HV *)&PL_sv_undef;
2537 XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2538 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2542 retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2557 } /* static int perl_config_plugin (oconfig_item_it *) */
2559 static int perl_config (oconfig_item_t *ci)
2566 for (i = 0; i < ci->children_num; ++i) {
2567 oconfig_item_t *c = ci->children + i;
2568 int current_status = 0;
2570 if (NULL != perl_threads)
2572 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2576 if (0 == strcasecmp (c->key, "LoadPlugin"))
2577 current_status = perl_config_loadplugin (aTHX_ c);
2578 else if (0 == strcasecmp (c->key, "BaseName"))
2579 current_status = perl_config_basename (aTHX_ c);
2580 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2581 current_status = perl_config_enabledebugger (aTHX_ c);
2582 else if (0 == strcasecmp (c->key, "IncludeDir"))
2583 current_status = perl_config_includedir (aTHX_ c);
2584 else if (0 == strcasecmp (c->key, "Plugin"))
2585 current_status = perl_config_plugin (aTHX_ c);
2588 log_warn ("Ignoring unknown config key \"%s\".", c->key);
2592 /* fatal error - it's up to perl_config_* to clean up */
2593 if (0 > current_status) {
2594 log_err ("Configuration failed with a fatal error - "
2595 "plugin disabled!");
2596 return current_status;
2599 status += current_status;
2602 } /* static int perl_config (oconfig_item_t *) */
2604 void module_register (void)
2607 perl_argv = smalloc ((perl_argc + 1) * sizeof (*perl_argv));
2609 /* default options for the Perl interpreter */
2611 perl_argv[1] = "-MCollectd";
2612 perl_argv[2] = "-e";
2614 perl_argv[4] = NULL;
2616 plugin_register_complex_config ("perl", perl_config);
2618 } /* void module_register (void) */
2620 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */