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
38 #undef DONT_POISON_SPRINTF_YET
40 #include "configfile.h"
49 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
51 # pragma GCC poison sprintf
56 /* Some versions of Perl define their own version of DEBUG... :-/ */
61 /* ... while we want the definition found in plugin.h. */
65 #include "filter_chain.h"
67 #if !defined(USE_ITHREADS)
68 # error "Perl does not support ithreads!"
69 #endif /* !defined(USE_ITHREADS) */
71 /* clear the Perl sub's stack frame
72 * (this should only be used inside an XSUB) */
73 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
77 #define PLUGIN_WRITE 2
78 #define PLUGIN_SHUTDOWN 3
80 #define PLUGIN_NOTIF 5
81 #define PLUGIN_FLUSH 6
83 #define PLUGIN_TYPES 7
85 #define PLUGIN_CONFIG 254
86 #define PLUGIN_DATASET 255
93 #define FC_CB_CREATE 0
94 #define FC_CB_DESTROY 1
99 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
100 #define log_info(...) INFO ("perl: " __VA_ARGS__)
101 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
102 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
104 /* this is defined in DynaLoader.a */
105 void boot_DynaLoader (PerlInterpreter *, CV *);
107 static XS (Collectd_plugin_register_ds);
108 static XS (Collectd_plugin_unregister_ds);
109 static XS (Collectd_plugin_dispatch_values);
110 static XS (Collectd_plugin_get_interval);
111 static XS (Collectd__plugin_write);
112 static XS (Collectd__plugin_flush);
113 static XS (Collectd_plugin_dispatch_notification);
114 static XS (Collectd_plugin_log);
115 static XS (Collectd__fc_register);
116 static XS (Collectd_call_by_name);
122 typedef struct c_ithread_s {
123 /* the thread's Perl interpreter */
124 PerlInterpreter *interp;
125 _Bool running; /* thread is inside Perl interpreter */
129 /* double linked list of threads */
130 struct c_ithread_s *prev;
131 struct c_ithread_s *next;
139 /* some usage stats */
140 int number_of_threads;
141 #endif /* COLLECT_DEBUG */
143 pthread_mutex_t mutex;
144 pthread_mutexattr_t mutexattr;
147 /* name / user_data for Perl matches / targets */
153 #define PFC_USER_DATA_FREE(data) \
155 sfree ((data)->name); \
156 if (NULL != (data)->user_data) \
157 sv_free ((data)->user_data); \
164 extern char **environ;
170 /* if perl_threads != NULL perl_threads->head must
171 * point to the "base" thread */
172 static c_ithread_list_t *perl_threads = NULL;
174 /* the key used to store each pthread's ithread */
175 static pthread_key_t perl_thr_key;
177 static int perl_argc = 0;
178 static char **perl_argv = NULL;
180 static char base_name[DATA_MAX_NAME_LEN] = "";
187 { "Collectd::plugin_register_data_set", Collectd_plugin_register_ds },
188 { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
189 { "Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values },
190 { "Collectd::plugin_get_interval", Collectd_plugin_get_interval },
191 { "Collectd::_plugin_write", Collectd__plugin_write },
192 { "Collectd::_plugin_flush", Collectd__plugin_flush },
193 { "Collectd::plugin_dispatch_notification",
194 Collectd_plugin_dispatch_notification },
195 { "Collectd::plugin_log", Collectd_plugin_log },
196 { "Collectd::_fc_register", Collectd__fc_register },
197 { "Collectd::call_by_name", Collectd_call_by_name },
206 { "Collectd::TYPE_INIT", PLUGIN_INIT },
207 { "Collectd::TYPE_READ", PLUGIN_READ },
208 { "Collectd::TYPE_WRITE", PLUGIN_WRITE },
209 { "Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN },
210 { "Collectd::TYPE_LOG", PLUGIN_LOG },
211 { "Collectd::TYPE_NOTIF", PLUGIN_NOTIF },
212 { "Collectd::TYPE_FLUSH", PLUGIN_FLUSH },
213 { "Collectd::TYPE_CONFIG", PLUGIN_CONFIG },
214 { "Collectd::TYPE_DATASET", PLUGIN_DATASET },
215 { "Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER },
216 { "Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE },
217 { "Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE },
218 { "Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE },
219 { "Collectd::LOG_ERR", LOG_ERR },
220 { "Collectd::LOG_WARNING", LOG_WARNING },
221 { "Collectd::LOG_NOTICE", LOG_NOTICE },
222 { "Collectd::LOG_INFO", LOG_INFO },
223 { "Collectd::LOG_DEBUG", LOG_DEBUG },
224 { "Collectd::FC_MATCH", FC_MATCH },
225 { "Collectd::FC_TARGET", FC_TARGET },
226 { "Collectd::FC_CB_CREATE", FC_CB_CREATE },
227 { "Collectd::FC_CB_DESTROY", FC_CB_DESTROY },
228 { "Collectd::FC_CB_EXEC", FC_CB_EXEC },
229 { "Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH },
230 { "Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES },
231 { "Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE },
232 { "Collectd::FC_TARGET_STOP", FC_TARGET_STOP },
233 { "Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN },
234 { "Collectd::NOTIF_FAILURE", NOTIF_FAILURE },
235 { "Collectd::NOTIF_WARNING", NOTIF_WARNING },
236 { "Collectd::NOTIF_OKAY", NOTIF_OKAY },
245 { "Collectd::hostname_g", hostname_g },
250 * Helper functions for data type conversion.
265 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
269 if ((NULL == hash) || (NULL == ds))
272 if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
273 sstrncpy (ds->name, SvPV_nolen (*tmp), sizeof (ds->name));
276 log_err ("hv2data_source: No DS name given.");
280 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
281 ds->type = SvIV (*tmp);
283 if ((DS_TYPE_COUNTER != ds->type)
284 && (DS_TYPE_GAUGE != ds->type)
285 && (DS_TYPE_DERIVE != ds->type)
286 && (DS_TYPE_ABSOLUTE != ds->type)) {
287 log_err ("hv2data_source: Invalid DS type.");
292 ds->type = DS_TYPE_COUNTER;
295 if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
296 ds->min = SvNV (*tmp);
300 if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
301 ds->max = SvNV (*tmp);
305 } /* static int hv2data_source (HV *, data_source_t *) */
307 /* av2value converts at most "len" elements from "array" to "value". Returns the
308 * number of elements converted or zero on error. */
309 static size_t av2value (pTHX_ char *name, AV *array, value_t *value, size_t array_len)
311 const data_set_t *ds;
314 if ((NULL == name) || (NULL == array) || (NULL == value) || (array_len == 0))
317 ds = plugin_get_ds (name);
319 log_err ("av2value: Unknown dataset \"%s\"", name);
323 if (array_len < ds->ds_num) {
324 log_warn ("av2value: array does not contain enough elements for type \"%s\": got %zu, want %zu",
325 name, array_len, ds->ds_num);
327 } else if (array_len > ds->ds_num) {
328 log_warn ("av2value: array contains excess elements for type \"%s\": got %zu, want %zu",
329 name, array_len, ds->ds_num);
332 for (i = 0; i < ds->ds_num; ++i) {
333 SV **tmp = av_fetch (array, i, 0);
336 if (DS_TYPE_COUNTER == ds->ds[i].type)
337 value[i].counter = SvIV (*tmp);
338 else if (DS_TYPE_GAUGE == ds->ds[i].type)
339 value[i].gauge = SvNV (*tmp);
340 else if (DS_TYPE_DERIVE == ds->ds[i].type)
341 value[i].derive = SvIV (*tmp);
342 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
343 value[i].absolute = SvIV (*tmp);
351 } /* static size_t av2value (char *, AV *, value_t *, size_t) */
356 * values => [ @values ],
360 * plugin_instance => $pinstance,
361 * type_instance => $tinstance,
364 static int hv2value_list (pTHX_ HV *hash, value_list_t *vl)
368 if ((NULL == hash) || (NULL == vl))
371 if (NULL == (tmp = hv_fetch (hash, "type", 4, 0))) {
372 log_err ("hv2value_list: No type given.");
376 sstrncpy (vl->type, SvPV_nolen (*tmp), sizeof (vl->type));
378 if ((NULL == (tmp = hv_fetch (hash, "values", 6, 0)))
379 || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
380 log_err ("hv2value_list: No valid values given.");
385 AV *array = (AV *)SvRV (*tmp);
386 /* av_len returns the highest index, not the actual length. */
387 size_t array_len = (size_t) (av_len (array) + 1);
391 vl->values = calloc (array_len, sizeof (*vl->values));
392 vl->values_len = av2value (aTHX_ vl->type, (AV *)SvRV (*tmp), vl->values, array_len);
393 if (vl->values_len == 0) {
399 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
401 double t = SvNV (*tmp);
402 vl->time = DOUBLE_TO_CDTIME_T (t);
405 if (NULL != (tmp = hv_fetch (hash, "interval", 8, 0)))
407 double t = SvNV (*tmp);
408 vl->interval = DOUBLE_TO_CDTIME_T (t);
411 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
412 sstrncpy (vl->host, SvPV_nolen (*tmp), sizeof (vl->host));
414 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
416 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
417 sstrncpy (vl->plugin, SvPV_nolen (*tmp), sizeof (vl->plugin));
419 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
420 sstrncpy (vl->plugin_instance, SvPV_nolen (*tmp),
421 sizeof (vl->plugin_instance));
423 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
424 sstrncpy (vl->type_instance, SvPV_nolen (*tmp),
425 sizeof (vl->type_instance));
427 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
429 static int av2data_set (pTHX_ AV *array, char *name, data_set_t *ds)
433 if ((NULL == array) || (NULL == name) || (NULL == ds))
436 len = av_len (array);
439 log_err ("av2data_set: Invalid data set.");
443 ds->ds = smalloc ((len + 1) * sizeof (*ds->ds));
444 ds->ds_num = len + 1;
446 for (i = 0; i <= len; ++i) {
447 SV **elem = av_fetch (array, i, 0);
450 log_err ("av2data_set: Failed to fetch data source %i.", i);
454 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
455 log_err ("av2data_set: Invalid data source.");
459 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds->ds[i]))
462 log_debug ("av2data_set: "
463 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
464 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
467 sstrncpy (ds->type, name, sizeof (ds->type));
469 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
474 * severity => $severity,
480 * plugin_instance => $instance,
481 * type_instance => $type_instance,
482 * meta => [ { name => <name>, value => <value> }, ... ]
485 static int av2notification_meta (pTHX_ AV *array, notification_meta_t **meta)
487 notification_meta_t **m = meta;
489 int len = av_len (array);
492 for (i = 0; i <= len; ++i) {
493 SV **tmp = av_fetch (array, i, 0);
499 if (! (SvROK (*tmp) && (SVt_PVHV == SvTYPE (SvRV (*tmp))))) {
500 log_warn ("av2notification_meta: Skipping invalid "
501 "meta information.");
505 hash = (HV *)SvRV (*tmp);
507 *m = smalloc (sizeof (**m));
509 if (NULL == (tmp = hv_fetch (hash, "name", 4, 0))) {
510 log_warn ("av2notification_meta: Skipping invalid "
511 "meta information.");
515 sstrncpy ((*m)->name, SvPV_nolen (*tmp), sizeof ((*m)->name));
517 if (NULL == (tmp = hv_fetch (hash, "value", 5, 0))) {
518 log_warn ("av2notification_meta: Skipping invalid "
519 "meta information.");
525 (*m)->nm_value.nm_double = SvNVX (*tmp);
526 (*m)->type = NM_TYPE_DOUBLE;
528 else if (SvUOK (*tmp)) {
529 (*m)->nm_value.nm_unsigned_int = SvUVX (*tmp);
530 (*m)->type = NM_TYPE_UNSIGNED_INT;
532 else if (SvIOK (*tmp)) {
533 (*m)->nm_value.nm_signed_int = SvIVX (*tmp);
534 (*m)->type = NM_TYPE_SIGNED_INT;
537 (*m)->nm_value.nm_string = sstrdup (SvPV_nolen (*tmp));
538 (*m)->type = NM_TYPE_STRING;
545 } /* static int av2notification_meta (AV *, notification_meta_t *) */
547 static int hv2notification (pTHX_ HV *hash, notification_t *n)
551 if ((NULL == hash) || (NULL == n))
554 if (NULL != (tmp = hv_fetch (hash, "severity", 8, 0)))
555 n->severity = SvIV (*tmp);
557 n->severity = NOTIF_FAILURE;
559 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
561 double t = SvNV (*tmp);
562 n->time = DOUBLE_TO_CDTIME_T (t);
567 if (NULL != (tmp = hv_fetch (hash, "message", 7, 0)))
568 sstrncpy (n->message, SvPV_nolen (*tmp), sizeof (n->message));
570 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
571 sstrncpy (n->host, SvPV_nolen (*tmp), sizeof (n->host));
573 sstrncpy (n->host, hostname_g, sizeof (n->host));
575 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
576 sstrncpy (n->plugin, SvPV_nolen (*tmp), sizeof (n->plugin));
578 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
579 sstrncpy (n->plugin_instance, SvPV_nolen (*tmp),
580 sizeof (n->plugin_instance));
582 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0)))
583 sstrncpy (n->type, SvPV_nolen (*tmp), sizeof (n->type));
585 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
586 sstrncpy (n->type_instance, SvPV_nolen (*tmp),
587 sizeof (n->type_instance));
590 while (NULL != (tmp = hv_fetch (hash, "meta", 4, 0))) {
591 if (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp))))) {
592 log_warn ("hv2notification: Ignoring invalid meta information.");
596 if (0 != av2notification_meta (aTHX_ (AV *)SvRV (*tmp), &n->meta)) {
597 plugin_notification_meta_free (n->meta);
604 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
606 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
610 if ((NULL == ds) || (NULL == array))
613 av_extend (array, ds->ds_num);
615 for (i = 0; i < ds->ds_num; ++i) {
616 HV *source = newHV ();
618 if (NULL == hv_store (source, "name", 4,
619 newSVpv (ds->ds[i].name, 0), 0))
622 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
625 if (! isnan (ds->ds[i].min))
626 if (NULL == hv_store (source, "min", 3,
627 newSVnv (ds->ds[i].min), 0))
630 if (! isnan (ds->ds[i].max))
631 if (NULL == hv_store (source, "max", 3,
632 newSVnv (ds->ds[i].max), 0))
635 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
639 } /* static int data_set2av (data_set_t *, AV *) */
641 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
646 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
650 /* av_extend takes the last *index* to which the array should be extended. */
651 av_extend (values, vl->values_len - 1);
653 assert (ds->ds_num == vl->values_len);
654 for (i = 0; i < vl->values_len; ++i) {
657 if (DS_TYPE_COUNTER == ds->ds[i].type)
658 val = newSViv (vl->values[i].counter);
659 else if (DS_TYPE_GAUGE == ds->ds[i].type)
660 val = newSVnv (vl->values[i].gauge);
661 else if (DS_TYPE_DERIVE == ds->ds[i].type)
662 val = newSViv (vl->values[i].derive);
663 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
664 val = newSViv (vl->values[i].absolute);
666 if (NULL == av_store (values, i, val)) {
672 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
677 double t = CDTIME_T_TO_DOUBLE (vl->time);
678 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
683 double t = CDTIME_T_TO_DOUBLE (vl->interval);
684 if (NULL == hv_store (hash, "interval", 8, newSVnv (t), 0))
688 if ('\0' != vl->host[0])
689 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
692 if ('\0' != vl->plugin[0])
693 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
696 if ('\0' != vl->plugin_instance[0])
697 if (NULL == hv_store (hash, "plugin_instance", 15,
698 newSVpv (vl->plugin_instance, 0), 0))
701 if ('\0' != vl->type[0])
702 if (NULL == hv_store (hash, "type", 4, newSVpv (vl->type, 0), 0))
705 if ('\0' != vl->type_instance[0])
706 if (NULL == hv_store (hash, "type_instance", 13,
707 newSVpv (vl->type_instance, 0), 0))
710 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
712 static int notification_meta2av (pTHX_ notification_meta_t *meta, AV *array)
722 av_extend (array, meta_num);
724 for (i = 0; NULL != meta; meta = meta->next, ++i) {
728 if (NULL == hv_store (m, "name", 4, newSVpv (meta->name, 0), 0))
731 if (NM_TYPE_STRING == meta->type)
732 value = newSVpv (meta->nm_value.nm_string, 0);
733 else if (NM_TYPE_SIGNED_INT == meta->type)
734 value = newSViv (meta->nm_value.nm_signed_int);
735 else if (NM_TYPE_UNSIGNED_INT == meta->type)
736 value = newSVuv (meta->nm_value.nm_unsigned_int);
737 else if (NM_TYPE_DOUBLE == meta->type)
738 value = newSVnv (meta->nm_value.nm_double);
739 else if (NM_TYPE_BOOLEAN == meta->type)
740 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
744 if (NULL == hv_store (m, "value", 5, value, 0)) {
749 if (NULL == av_store (array, i, newRV_noinc ((SV *)m))) {
756 } /* static int notification_meta2av (notification_meta_t *, AV *) */
758 static int notification2hv (pTHX_ notification_t *n, HV *hash)
760 if (NULL == hv_store (hash, "severity", 8, newSViv (n->severity), 0))
765 double t = CDTIME_T_TO_DOUBLE (n->time);
766 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
770 if ('\0' != *n->message)
771 if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
774 if ('\0' != *n->host)
775 if (NULL == hv_store (hash, "host", 4, newSVpv (n->host, 0), 0))
778 if ('\0' != *n->plugin)
779 if (NULL == hv_store (hash, "plugin", 6, newSVpv (n->plugin, 0), 0))
782 if ('\0' != *n->plugin_instance)
783 if (NULL == hv_store (hash, "plugin_instance", 15,
784 newSVpv (n->plugin_instance, 0), 0))
787 if ('\0' != *n->type)
788 if (NULL == hv_store (hash, "type", 4, newSVpv (n->type, 0), 0))
791 if ('\0' != *n->type_instance)
792 if (NULL == hv_store (hash, "type_instance", 13,
793 newSVpv (n->type_instance, 0), 0))
796 if (NULL != n->meta) {
798 if ((0 != notification_meta2av (aTHX_ n->meta, meta))
799 || (NULL == hv_store (hash, "meta", 4,
800 newRV_noinc ((SV *)meta), 0))) {
807 } /* static int notification2hv (notification_t *, HV *) */
809 static int oconfig_item2hv (pTHX_ oconfig_item_t *ci, HV *hash)
816 if (NULL == hv_store (hash, "key", 3, newSVpv (ci->key, 0), 0))
820 if (0 < ci->values_num)
821 av_extend (values, ci->values_num);
823 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0)) {
829 for (i = 0; i < ci->values_num; ++i) {
832 switch (ci->values[i].type) {
833 case OCONFIG_TYPE_STRING:
834 value = newSVpv (ci->values[i].value.string, 0);
836 case OCONFIG_TYPE_NUMBER:
837 value = newSVnv ((NV)ci->values[i].value.number);
839 case OCONFIG_TYPE_BOOLEAN:
840 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
843 log_err ("oconfig_item2hv: Invalid value type %i.",
845 value = &PL_sv_undef;
848 if (NULL == av_store (values, i, value)) {
854 /* ignoring 'parent' member which is uninteresting in this case */
857 if (0 < ci->children_num)
858 av_extend (children, ci->children_num);
860 if (NULL == hv_store (hash, "children", 8, newRV_noinc ((SV *)children), 0)) {
866 for (i = 0; i < ci->children_num; ++i) {
867 HV *child = newHV ();
869 if (0 != oconfig_item2hv (aTHX_ ci->children + i, child)) {
875 if (NULL == av_store (children, i, newRV_noinc ((SV *)child))) {
882 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
885 * Internal functions.
888 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
890 if (base_name[0] == '\0')
891 status = ssnprintf (buf, buf_len, "%s", module);
893 status = ssnprintf (buf, buf_len, "%s::%s", base_name, module);
894 if ((status < 0) || ((unsigned int)status >= buf_len))
897 } /* char *get_module_name */
900 * Add a plugin's data set definition.
902 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
908 if ((NULL == name) || (NULL == dataset))
911 if (0 != av2data_set (aTHX_ dataset, name, &ds))
914 ret = plugin_register_data_set (&ds);
918 } /* static int pplugin_register_data_set (char *, SV *) */
921 * Remove a plugin's data set definition.
923 static int pplugin_unregister_data_set (char *name)
927 return plugin_unregister_data_set (name);
928 } /* static int pplugin_unregister_data_set (char *) */
931 * Submit the values to the write functions.
933 static int pplugin_dispatch_values (pTHX_ HV *values)
935 value_list_t vl = VALUE_LIST_INIT;
942 if (0 != hv2value_list (aTHX_ values, &vl))
945 ret = plugin_dispatch_values (&vl);
949 } /* static int pplugin_dispatch_values (char *, HV *) */
952 * Submit the values to a single write function.
954 static int pplugin_write (pTHX_ const char *plugin, AV *data_set, HV *values)
957 value_list_t vl = VALUE_LIST_INIT;
964 if (0 != hv2value_list (aTHX_ values, &vl))
967 if ((NULL != data_set)
968 && (0 != av2data_set (aTHX_ data_set, vl.type, &ds)))
971 ret = plugin_write (plugin, NULL == data_set ? NULL : &ds, &vl);
973 log_warn ("Dispatching value to plugin \"%s\" failed with status %i.",
974 NULL == plugin ? "<any>" : plugin, ret);
976 if (NULL != data_set)
980 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
983 * Dispatch a notification.
985 static int pplugin_dispatch_notification (pTHX_ HV *notif)
987 notification_t n = { 0 };
994 if (0 != hv2notification (aTHX_ notif, &n))
997 ret = plugin_dispatch_notification (&n);
998 plugin_notification_meta_free (n.meta);
1000 } /* static int pplugin_dispatch_notification (HV *) */
1003 * Call perl sub with thread locking flags handled.
1005 static int call_pv_locked (pTHX_ const char* sub_name)
1010 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
1011 if (t == NULL) /* thread destroyed */
1014 old_running = t->running;
1018 t->running = old_running;
1022 ret = call_pv (sub_name, G_SCALAR);
1024 t->running = old_running;
1026 } /* static int call_pv_locked (pTHX, *sub_name) */
1029 * Call all working functions of the given type.
1031 static int pplugin_call_all (pTHX_ int type, ...)
1040 if ((type < 0) || (type >= PLUGIN_TYPES))
1043 va_start (ap, type);
1050 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1052 if (PLUGIN_WRITE == type) {
1054 * $_[0] = $plugin_type;
1069 * values => [ $v1, ... ],
1071 * host => $hostname,
1072 * plugin => $plugin,
1074 * plugin_instance => $instance,
1075 * type_instance => $type_instance
1084 ds = va_arg (ap, data_set_t *);
1085 vl = va_arg (ap, value_list_t *);
1087 if (-1 == data_set2av (aTHX_ ds, pds)) {
1090 pds = (AV *)&PL_sv_undef;
1094 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
1097 pvl = (HV *)&PL_sv_undef;
1101 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
1102 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1103 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1105 else if (PLUGIN_LOG == type) {
1111 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1112 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1114 else if (PLUGIN_NOTIF == type) {
1118 * severity => $severity,
1122 * plugin => $plugin,
1124 * plugin_instance => $instance,
1125 * type_instance => $type_instance
1129 HV *notif = newHV ();
1131 n = va_arg (ap, notification_t *);
1133 if (-1 == notification2hv (aTHX_ n, notif)) {
1136 notif = (HV *)&PL_sv_undef;
1140 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
1142 else if (PLUGIN_FLUSH == type) {
1147 * $_[1] = $identifier;
1149 timeout = va_arg (ap, cdtime_t);
1151 XPUSHs (sv_2mortal (newSVnv (CDTIME_T_TO_DOUBLE (timeout))));
1152 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1157 retvals = call_pv_locked (aTHX_ "Collectd::plugin_call_all");
1172 } /* static int pplugin_call_all (int, ...) */
1175 * collectd's Perl interpreter based thread implementation.
1177 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1180 /* must be called with perl_threads->mutex locked */
1181 static void c_ithread_destroy (c_ithread_t *ithread)
1183 dTHXa (ithread->interp);
1185 assert (NULL != perl_threads);
1187 PERL_SET_CONTEXT (aTHX);
1188 log_debug ("Shutting down Perl interpreter %p...", aTHX);
1193 --perl_threads->number_of_threads;
1194 #endif /* COLLECT_DEBUG */
1196 perl_destruct (aTHX);
1199 if (NULL == ithread->prev)
1200 perl_threads->head = ithread->next;
1202 ithread->prev->next = ithread->next;
1204 if (NULL == ithread->next)
1205 perl_threads->tail = ithread->prev;
1207 ithread->next->prev = ithread->prev;
1211 } /* static void c_ithread_destroy (c_ithread_t *) */
1213 static void c_ithread_destructor (void *arg)
1215 c_ithread_t *ithread = (c_ithread_t *)arg;
1216 c_ithread_t *t = NULL;
1218 if (NULL == perl_threads)
1221 pthread_mutex_lock (&perl_threads->mutex);
1223 for (t = perl_threads->head; NULL != t; t = t->next)
1227 /* the ithread no longer exists */
1230 pthread_mutex_unlock (&perl_threads->mutex);
1234 c_ithread_destroy (ithread);
1236 pthread_mutex_unlock (&perl_threads->mutex);
1238 } /* static void c_ithread_destructor (void *) */
1240 /* must be called with perl_threads->mutex locked */
1241 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1243 c_ithread_t *t = NULL;
1246 assert (NULL != perl_threads);
1248 t = smalloc (sizeof (*t));
1249 memset (t, 0, sizeof (c_ithread_t));
1251 t->interp = (NULL == base)
1253 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1257 if ((NULL != base) && (NULL != PL_endav)) {
1258 av_clear (PL_endav);
1259 av_undef (PL_endav);
1264 ++perl_threads->number_of_threads;
1265 #endif /* COLLECT_DEBUG */
1269 if (NULL == perl_threads->tail) {
1270 perl_threads->head = t;
1274 perl_threads->tail->next = t;
1275 t->prev = perl_threads->tail;
1278 t->pthread = pthread_self();
1281 perl_threads->tail = t;
1283 pthread_setspecific (perl_thr_key, (const void *)t);
1285 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1288 * Filter chains implementation.
1291 static int fc_call (pTHX_ int type, int cb_type, pfc_user_data_t *data, ...)
1298 notification_meta_t **meta = NULL;
1303 if ((type < 0) || (type >= FC_TYPES))
1306 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1309 va_start (ap, data);
1316 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1317 XPUSHs (sv_2mortal (newSVpv (data->name, 0)));
1318 XPUSHs (sv_2mortal (newSViv ((IV)cb_type)));
1320 if (FC_CB_CREATE == cb_type) {
1323 * $_[1] = $user_data;
1326 HV *config = newHV ();
1328 ci = va_arg (ap, oconfig_item_t *);
1330 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
1333 config = (HV *)&PL_sv_undef;
1337 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
1339 else if (FC_CB_DESTROY == cb_type) {
1341 * $_[1] = $user_data;
1344 /* nothing to be done - the user data pointer
1345 * is pushed onto the stack later */
1347 else if (FC_CB_EXEC == cb_type) {
1352 * $_[3] = $user_data;
1360 ds = va_arg (ap, data_set_t *);
1361 vl = va_arg (ap, value_list_t *);
1362 meta = va_arg (ap, notification_meta_t **);
1364 if (0 != data_set2av (aTHX_ ds, pds)) {
1367 pds = (AV *)&PL_sv_undef;
1371 if (0 != value_list2hv (aTHX_ vl, ds, pvl)) {
1374 pvl = (HV *)&PL_sv_undef;
1381 if (0 != notification_meta2av (aTHX_ *meta, pmeta)) {
1384 pmeta = (AV *)&PL_sv_undef;
1389 pmeta = (AV *)&PL_sv_undef;
1392 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1393 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1394 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pmeta)));
1397 XPUSHs (sv_2mortal (newRV_inc (data->user_data)));
1401 retvals = call_pv_locked (aTHX_ "Collectd::fc_call");
1403 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1404 assert (pmeta != NULL);
1406 plugin_notification_meta_free (*meta);
1407 av2notification_meta (aTHX_ pmeta, meta);
1414 /* the exec callbacks return a status, while
1415 * the others return a boolean value */
1416 if (FC_CB_EXEC == cb_type)
1418 else if (! SvTRUE (tmp))
1428 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1430 static int fc_create (int type, const oconfig_item_t *ci, void **user_data)
1432 pfc_user_data_t *data;
1438 if (NULL == perl_threads)
1442 c_ithread_t *t = NULL;
1444 pthread_mutex_lock (&perl_threads->mutex);
1445 t = c_ithread_create (perl_threads->head->interp);
1446 pthread_mutex_unlock (&perl_threads->mutex);
1451 log_debug ("fc_create: c_ithread: interp = %p (active threads: %i)",
1452 aTHX, perl_threads->number_of_threads);
1454 if ((1 != ci->values_num)
1455 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1456 log_warn ("A \"%s\" block expects a single string argument.",
1457 (FC_MATCH == type) ? "Match" : "Target");
1461 data = smalloc (sizeof (*data));
1462 data->name = sstrdup (ci->values[0].value.string);
1463 data->user_data = newSV (0);
1465 ret = fc_call (aTHX_ type, FC_CB_CREATE, data, ci);
1468 PFC_USER_DATA_FREE (data);
1472 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1474 static int fc_destroy (int type, void **user_data)
1476 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1482 if ((NULL == perl_threads) || (NULL == data))
1486 c_ithread_t *t = NULL;
1488 pthread_mutex_lock (&perl_threads->mutex);
1489 t = c_ithread_create (perl_threads->head->interp);
1490 pthread_mutex_unlock (&perl_threads->mutex);
1495 log_debug ("fc_destroy: c_ithread: interp = %p (active threads: %i)",
1496 aTHX, perl_threads->number_of_threads);
1498 ret = fc_call (aTHX_ type, FC_CB_DESTROY, data);
1500 PFC_USER_DATA_FREE (data);
1503 } /* static int fc_destroy (int, void **) */
1505 static int fc_exec (int type, const data_set_t *ds, const value_list_t *vl,
1506 notification_meta_t **meta, void **user_data)
1508 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1512 if (NULL == perl_threads)
1515 assert (NULL != data);
1518 c_ithread_t *t = NULL;
1520 pthread_mutex_lock (&perl_threads->mutex);
1521 t = c_ithread_create (perl_threads->head->interp);
1522 pthread_mutex_unlock (&perl_threads->mutex);
1527 log_debug ("fc_exec: c_ithread: interp = %p (active threads: %i)",
1528 aTHX, perl_threads->number_of_threads);
1530 return fc_call (aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1531 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1532 notification_meta_t **, void **) */
1534 static int pmatch_create (const oconfig_item_t *ci, void **user_data)
1536 return fc_create (FC_MATCH, ci, user_data);
1537 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1539 static int pmatch_destroy (void **user_data)
1541 return fc_destroy (FC_MATCH, user_data);
1542 } /* static int pmatch_destroy (void **) */
1544 static int pmatch_match (const data_set_t *ds, const value_list_t *vl,
1545 notification_meta_t **meta, void **user_data)
1547 return fc_exec (FC_MATCH, ds, vl, meta, user_data);
1548 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1549 notification_meta_t **, void **) */
1551 static match_proc_t pmatch = {
1552 pmatch_create, pmatch_destroy, pmatch_match
1555 static int ptarget_create (const oconfig_item_t *ci, void **user_data)
1557 return fc_create (FC_TARGET, ci, user_data);
1558 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1560 static int ptarget_destroy (void **user_data)
1562 return fc_destroy (FC_TARGET, user_data);
1563 } /* static int ptarget_destroy (void **) */
1565 static int ptarget_invoke (const data_set_t *ds, value_list_t *vl,
1566 notification_meta_t **meta, void **user_data)
1568 return fc_exec (FC_TARGET, ds, vl, meta, user_data);
1569 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1570 notification_meta_t **, void **) */
1572 static target_proc_t ptarget = {
1573 ptarget_create, ptarget_destroy, ptarget_invoke
1577 * Exported Perl API.
1581 * Collectd::plugin_register_data_set (type, dataset).
1584 * type of the dataset
1587 * dataset to be registered
1589 static XS (Collectd_plugin_register_ds)
1596 log_warn ("Using plugin_register() to register new data-sets is "
1597 "deprecated - add new entries to a custom types.db instead.");
1600 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1604 log_debug ("Collectd::plugin_register_data_set: "
1605 "type = \"%s\", dataset = \"%s\"",
1606 SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1610 if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1611 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1615 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1623 } /* static XS (Collectd_plugin_register_ds) */
1626 * Collectd::plugin_unregister_data_set (type).
1629 * type of the dataset
1631 static XS (Collectd_plugin_unregister_ds)
1636 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1640 log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1641 SvPV_nolen (ST (0)));
1643 if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1647 } /* static XS (Collectd_plugin_register_ds) */
1650 * Collectd::plugin_dispatch_values (name, values).
1653 * name of the plugin
1656 * value list to submit
1658 static XS (Collectd_plugin_dispatch_values)
1667 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1671 log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1672 SvPV_nolen (ST (/* stack index = */ 0)));
1674 values = ST (/* stack index = */ 0);
1679 /* Make sure the argument is a hash reference. */
1680 if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1681 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1685 ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1691 } /* static XS (Collectd_plugin_dispatch_values) */
1694 * Collectd::plugin_get_interval ().
1696 static XS (Collectd_plugin_get_interval)
1700 /* make sure we don't get any unused variable warnings for 'items';
1701 * don't abort, though */
1703 log_err ("Usage: Collectd::plugin_get_interval()");
1705 XSRETURN_NV ((NV) CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
1706 } /* static XS (Collectd_plugin_get_interval) */
1708 /* Collectd::plugin_write (plugin, ds, vl).
1711 * name of the plugin to call, may be 'undef'
1714 * data-set that describes the submitted values, may be 'undef'
1717 * value-list to be written
1719 static XS (Collectd__plugin_write)
1730 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1734 log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1735 SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1736 SvPV_nolen (ST (2)));
1738 if (! SvOK (ST (0)))
1741 plugin = SvPV_nolen (ST (0));
1744 if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1745 ds_array = (AV *)SvRV (ds);
1746 else if (! SvOK (ds))
1749 log_err ("Collectd::plugin_write: Invalid data-set.");
1754 if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1755 log_err ("Collectd::plugin_write: Invalid value-list.");
1759 ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1765 } /* static XS (Collectd__plugin_write) */
1768 * Collectd::_plugin_flush (plugin, timeout, identifier).
1771 * name of the plugin to flush
1774 * timeout to use when flushing the data
1777 * data-set identifier to flush
1779 static XS (Collectd__plugin_flush)
1781 char *plugin = NULL;
1788 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1793 plugin = SvPV_nolen (ST (0));
1796 timeout = (int)SvIV (ST (1));
1799 id = SvPV_nolen (ST (2));
1801 log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1802 "id = \"%s\"", plugin, timeout, id);
1804 if (0 == plugin_flush (plugin, timeout, id))
1808 } /* static XS (Collectd__plugin_flush) */
1811 * Collectd::plugin_dispatch_notification (notif).
1814 * notification to dispatch
1816 static XS (Collectd_plugin_dispatch_notification)
1825 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
1829 log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1830 SvPV_nolen (ST (0)));
1834 if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
1835 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
1839 ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
1845 } /* static XS (Collectd_plugin_dispatch_notification) */
1848 * Collectd::plugin_log (level, message).
1851 * log level (LOG_DEBUG, ... LOG_ERR)
1856 static XS (Collectd_plugin_log)
1861 log_err ("Usage: Collectd::plugin_log(level, message)");
1865 plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
1867 } /* static XS (Collectd_plugin_log) */
1870 * Collectd::_fc_register (type, name)
1878 static XS (Collectd__fc_register)
1888 log_err ("Usage: Collectd::_fc_register(type, name)");
1892 type = SvIV (ST (0));
1893 name = SvPV_nolen (ST (1));
1895 if (FC_MATCH == type)
1896 ret = fc_register_match (name, pmatch);
1897 else if (FC_TARGET == type)
1898 ret = fc_register_target (name, ptarget);
1904 } /* static XS (Collectd_fc_register) */
1907 * Collectd::call_by_name (...).
1909 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1911 static XS (Collectd_call_by_name)
1916 if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
1917 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
1922 name = SvPV_nolen (tmp);
1924 if (NULL == get_cv (name, 0)) {
1925 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
1930 /* simply pass on the subroutine call without touching the stack,
1931 * thus leaving any arguments and return values in place */
1933 } /* static XS (Collectd_call_by_name) */
1936 * Interface to collectd.
1939 static int perl_init (void)
1944 if (NULL == perl_threads)
1948 c_ithread_t *t = NULL;
1950 pthread_mutex_lock (&perl_threads->mutex);
1951 t = c_ithread_create (perl_threads->head->interp);
1952 pthread_mutex_unlock (&perl_threads->mutex);
1957 log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1958 aTHX, perl_threads->number_of_threads);
1960 /* Lock the base thread to avoid race conditions with c_ithread_create().
1961 * See https://github.com/collectd/collectd/issues/9 and
1962 * https://github.com/collectd/collectd/issues/1706 for details.
1964 assert (aTHX == perl_threads->head->interp);
1965 pthread_mutex_lock (&perl_threads->mutex);
1967 status = pplugin_call_all (aTHX_ PLUGIN_INIT);
1969 pthread_mutex_unlock (&perl_threads->mutex);
1972 } /* static int perl_init (void) */
1974 static int perl_read (void)
1978 if (NULL == perl_threads)
1982 c_ithread_t *t = NULL;
1984 pthread_mutex_lock (&perl_threads->mutex);
1985 t = c_ithread_create (perl_threads->head->interp);
1986 pthread_mutex_unlock (&perl_threads->mutex);
1991 /* Assert that we're not running as the base thread. Otherwise, we might
1992 * run into concurrency issues with c_ithread_create(). See
1993 * https://github.com/collectd/collectd/issues/9 for details. */
1994 assert (aTHX != perl_threads->head->interp);
1996 log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1997 aTHX, perl_threads->number_of_threads);
1998 return pplugin_call_all (aTHX_ PLUGIN_READ);
1999 } /* static int perl_read (void) */
2001 static int perl_write (const data_set_t *ds, const value_list_t *vl,
2002 user_data_t __attribute__((unused)) *user_data)
2007 if (NULL == perl_threads)
2011 c_ithread_t *t = NULL;
2013 pthread_mutex_lock (&perl_threads->mutex);
2014 t = c_ithread_create (perl_threads->head->interp);
2015 pthread_mutex_unlock (&perl_threads->mutex);
2020 /* Lock the base thread if this is not called from one of the read threads
2021 * to avoid race conditions with c_ithread_create(). See
2022 * https://github.com/collectd/collectd/issues/9 for details. */
2023 if (aTHX == perl_threads->head->interp)
2024 pthread_mutex_lock (&perl_threads->mutex);
2026 log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
2027 aTHX, perl_threads->number_of_threads);
2028 status = pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
2030 if (aTHX == perl_threads->head->interp)
2031 pthread_mutex_unlock (&perl_threads->mutex);
2034 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2036 static void perl_log (int level, const char *msg,
2037 user_data_t __attribute__((unused)) *user_data)
2041 if (NULL == perl_threads)
2045 c_ithread_t *t = NULL;
2047 pthread_mutex_lock (&perl_threads->mutex);
2048 t = c_ithread_create (perl_threads->head->interp);
2049 pthread_mutex_unlock (&perl_threads->mutex);
2054 /* Lock the base thread if this is not called from one of the read threads
2055 * to avoid race conditions with c_ithread_create(). See
2056 * https://github.com/collectd/collectd/issues/9 for details.
2059 if (aTHX == perl_threads->head->interp)
2060 pthread_mutex_lock (&perl_threads->mutex);
2062 pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
2064 if (aTHX == perl_threads->head->interp)
2065 pthread_mutex_unlock (&perl_threads->mutex);
2068 } /* static void perl_log (int, const char *) */
2070 static int perl_notify (const notification_t *notif,
2071 user_data_t __attribute__((unused)) *user_data)
2075 if (NULL == perl_threads)
2079 c_ithread_t *t = NULL;
2081 pthread_mutex_lock (&perl_threads->mutex);
2082 t = c_ithread_create (perl_threads->head->interp);
2083 pthread_mutex_unlock (&perl_threads->mutex);
2087 return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
2088 } /* static int perl_notify (const notification_t *) */
2090 static int perl_flush (cdtime_t timeout, const char *identifier,
2091 user_data_t __attribute__((unused)) *user_data)
2095 if (NULL == perl_threads)
2099 c_ithread_t *t = NULL;
2101 pthread_mutex_lock (&perl_threads->mutex);
2102 t = c_ithread_create (perl_threads->head->interp);
2103 pthread_mutex_unlock (&perl_threads->mutex);
2107 return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout, identifier);
2108 } /* static int perl_flush (const int) */
2110 static int perl_shutdown (void)
2117 plugin_unregister_complex_config ("perl");
2119 if (NULL == perl_threads)
2123 pthread_mutex_lock (&perl_threads->mutex);
2124 t = c_ithread_create (perl_threads->head->interp);
2125 pthread_mutex_unlock (&perl_threads->mutex);
2130 log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2131 aTHX, perl_threads->number_of_threads);
2133 plugin_unregister_log ("perl");
2134 plugin_unregister_notification ("perl");
2135 plugin_unregister_init ("perl");
2136 plugin_unregister_read ("perl");
2137 plugin_unregister_write ("perl");
2138 plugin_unregister_flush ("perl");
2140 ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
2142 pthread_mutex_lock (&perl_threads->mutex);
2143 t = perl_threads->tail;
2146 struct timespec ts_wait;
2147 c_ithread_t *thr = t;
2149 /* the pointer has to be advanced before destroying
2150 * the thread as this will free the memory */
2155 /* Give some time to thread to exit from Perl interpreter */
2156 WARNING ("perl shutdown: Thread is running inside Perl. Waiting.");
2158 ts_wait.tv_nsec = 500000;
2159 nanosleep (&ts_wait, NULL);
2162 pthread_kill (thr->pthread, SIGTERM);
2163 ERROR ("perl shutdown: Thread hangs inside Perl. Thread killed.");
2165 c_ithread_destroy (thr);
2168 pthread_mutex_unlock (&perl_threads->mutex);
2169 pthread_mutex_destroy (&perl_threads->mutex);
2170 pthread_mutexattr_destroy (&perl_threads->mutexattr);
2172 sfree (perl_threads);
2174 pthread_key_delete (perl_thr_key);
2178 plugin_unregister_shutdown ("perl");
2180 } /* static void perl_shutdown (void) */
2183 * Access functions for global variables.
2185 * These functions implement the "magic" used to access
2186 * the global variables from Perl.
2189 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
2191 char *pv = mg->mg_ptr;
2194 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2196 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
2198 char *pv = mg->mg_ptr;
2199 sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
2201 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2203 static int g_interval_get (pTHX_ SV *var, MAGIC *mg)
2205 log_warn ("Accessing $interval_g is deprecated (and might not "
2206 "give the desired results) - plugin_get_interval() should "
2207 "be used instead.");
2208 sv_setnv (var, CDTIME_T_TO_DOUBLE (interval_g));
2210 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2212 static int g_interval_set (pTHX_ SV *var, MAGIC *mg)
2214 double nv = (double)SvNV (var);
2215 log_warn ("Accessing $interval_g is deprecated (and might not "
2216 "give the desired results) - plugin_get_interval() should "
2217 "be used instead.");
2218 interval_g = DOUBLE_TO_CDTIME_T (nv);
2220 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2222 static MGVTBL g_pv_vtbl = {
2223 g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2224 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2228 static MGVTBL g_interval_vtbl = {
2229 g_interval_get, g_interval_set, NULL, NULL, NULL, NULL, NULL
2230 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2235 /* bootstrap the Collectd module */
2236 static void xs_init (pTHX)
2240 char *file = __FILE__;
2246 /* enable usage of Perl modules using shared libraries */
2247 newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2250 for (i = 0; NULL != api[i].f; ++i)
2251 newXS (api[i].name, api[i].f, file);
2253 stash = gv_stashpv ("Collectd", 1);
2255 /* export "constants" */
2256 for (i = 0; '\0' != constants[i].name[0]; ++i)
2257 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
2259 /* export global variables
2260 * by adding "magic" to the SV's representing the globale variables
2261 * perl is able to automagically call the get/set function when
2262 * accessing any such variable (this is basically the same as using
2264 /* global strings */
2265 for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
2266 tmp = get_sv (g_strings[i].name, 1);
2267 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
2268 g_strings[i].var, 0);
2271 tmp = get_sv ("Collectd::interval_g", /* create = */ 1);
2272 sv_magicext (tmp, NULL, /* how = */ PERL_MAGIC_ext,
2273 /* vtbl = */ &g_interval_vtbl,
2274 /* name = */ NULL, /* namelen = */ 0);
2277 } /* static void xs_init (pTHX) */
2279 /* Initialize the global Perl interpreter. */
2280 static int init_pi (int argc, char **argv)
2284 if (NULL != perl_threads)
2287 log_info ("Initializing Perl interpreter...");
2292 for (i = 0; i < argc; ++i)
2293 log_debug ("argv[%i] = \"%s\"", i, argv[i]);
2295 #endif /* COLLECT_DEBUG */
2297 if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
2298 log_err ("init_pi: pthread_key_create failed");
2300 /* this must not happen - cowardly giving up if it does */
2305 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2306 * triggers a "value computed is not used" warning by gcc. */
2309 PERL_SYS_INIT3 (&argc, &argv, &environ);
2311 perl_threads = smalloc (sizeof (*perl_threads));
2312 memset (perl_threads, 0, sizeof (c_ithread_list_t));
2314 pthread_mutexattr_init(&perl_threads->mutexattr);
2315 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2316 pthread_mutex_init (&perl_threads->mutex, &perl_threads->mutexattr);
2317 /* locking the mutex should not be necessary at this point
2318 * but let's just do it for the sake of completeness */
2319 pthread_mutex_lock (&perl_threads->mutex);
2321 perl_threads->head = c_ithread_create (NULL);
2322 perl_threads->tail = perl_threads->head;
2324 if (NULL == (perl_threads->head->interp = perl_alloc ())) {
2325 log_err ("init_pi: Not enough memory.");
2329 aTHX = perl_threads->head->interp;
2330 pthread_mutex_unlock (&perl_threads->mutex);
2332 perl_construct (aTHX);
2334 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2336 if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
2337 SV *err = get_sv ("@", 1);
2338 log_err ("init_pi: Unable to bootstrap Collectd: %s",
2341 perl_destruct (perl_threads->head->interp);
2342 perl_free (perl_threads->head->interp);
2343 sfree (perl_threads);
2345 pthread_key_delete (perl_thr_key);
2349 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2350 sv_setpv (get_sv ("0", 0), "collectd");
2354 plugin_register_log ("perl", perl_log, /* user_data = */ NULL);
2355 plugin_register_notification ("perl", perl_notify,
2356 /* user_data = */ NULL);
2357 plugin_register_init ("perl", perl_init);
2359 plugin_register_read ("perl", perl_read);
2361 plugin_register_write ("perl", perl_write, /* user_data = */ NULL);
2362 plugin_register_flush ("perl", perl_flush, /* user_data = */ NULL);
2363 plugin_register_shutdown ("perl", perl_shutdown);
2365 } /* static int init_pi (const char **, const int) */
2368 * LoadPlugin "<Plugin>"
2370 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
2372 char module_name[DATA_MAX_NAME_LEN];
2376 if ((0 != ci->children_num) || (1 != ci->values_num)
2377 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2378 log_err ("LoadPlugin expects a single string argument.");
2382 value = ci->values[0].value.string;
2384 if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
2385 log_err ("Invalid module name %s", value);
2389 if (0 != init_pi (perl_argc, perl_argv))
2392 assert (NULL != perl_threads);
2393 assert (NULL != perl_threads->head);
2395 aTHX = perl_threads->head->interp;
2397 log_debug ("perl_config: Loading Perl plugin \"%s\"", value);
2398 load_module (PERL_LOADMOD_NOIMPORT,
2399 newSVpv (module_name, strlen (module_name)), Nullsv);
2401 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2406 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
2410 if ((0 != ci->children_num) || (1 != ci->values_num)
2411 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2412 log_err ("BaseName expects a single string argument.");
2416 value = ci->values[0].value.string;
2418 log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
2419 sstrncpy (base_name, value, sizeof (base_name));
2421 } /* static int perl_config_basename (oconfig_item_it *) */
2424 * EnableDebugger "<Package>"|""
2426 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
2430 if ((0 != ci->children_num) || (1 != ci->values_num)
2431 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2432 log_err ("EnableDebugger expects a single string argument.");
2436 if (NULL != perl_threads) {
2437 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
2441 value = ci->values[0].value.string;
2443 perl_argv = realloc (perl_argv,
2444 (++perl_argc + 1) * sizeof (char *));
2446 if (NULL == perl_argv) {
2447 log_err ("perl_config: Not enough memory.");
2451 if ('\0' == value[0]) {
2452 perl_argv[perl_argc - 1] = "-d";
2455 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 4);
2456 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
2457 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
2460 perl_argv[perl_argc] = NULL;
2462 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2465 * IncludeDir "<Dir>"
2467 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
2471 if ((0 != ci->children_num) || (1 != ci->values_num)
2472 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2473 log_err ("IncludeDir expects a single string argument.");
2477 value = ci->values[0].value.string;
2480 perl_argv = realloc (perl_argv,
2481 (++perl_argc + 1) * sizeof (char *));
2483 if (NULL == perl_argv) {
2484 log_err ("perl_config: Not enough memory.");
2488 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 3);
2489 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2490 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
2492 perl_argv[perl_argc] = NULL;
2495 /* prepend the directory to @INC */
2496 av_unshift (GvAVn (PL_incgv), 1);
2497 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
2500 } /* static int perl_config_includedir (oconfig_item_it *) */
2505 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2515 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2516 log_err ("LoadPlugin expects a single string argument.");
2520 plugin = ci->values[0].value.string;
2523 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2527 log_err ("Unable to convert configuration to a Perl hash value.");
2528 config = (HV *)&PL_sv_undef;
2536 XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2537 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2541 retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2556 } /* static int perl_config_plugin (oconfig_item_it *) */
2558 static int perl_config (oconfig_item_t *ci)
2565 for (i = 0; i < ci->children_num; ++i) {
2566 oconfig_item_t *c = ci->children + i;
2567 int current_status = 0;
2569 if (NULL != perl_threads)
2571 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2575 if (0 == strcasecmp (c->key, "LoadPlugin"))
2576 current_status = perl_config_loadplugin (aTHX_ c);
2577 else if (0 == strcasecmp (c->key, "BaseName"))
2578 current_status = perl_config_basename (aTHX_ c);
2579 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2580 current_status = perl_config_enabledebugger (aTHX_ c);
2581 else if (0 == strcasecmp (c->key, "IncludeDir"))
2582 current_status = perl_config_includedir (aTHX_ c);
2583 else if (0 == strcasecmp (c->key, "Plugin"))
2584 current_status = perl_config_plugin (aTHX_ c);
2587 log_warn ("Ignoring unknown config key \"%s\".", c->key);
2591 /* fatal error - it's up to perl_config_* to clean up */
2592 if (0 > current_status) {
2593 log_err ("Configuration failed with a fatal error - "
2594 "plugin disabled!");
2595 return current_status;
2598 status += current_status;
2601 } /* static int perl_config (oconfig_item_t *) */
2603 void module_register (void)
2606 perl_argv = smalloc ((perl_argc + 1) * sizeof (*perl_argv));
2608 /* default options for the Perl interpreter */
2610 perl_argv[1] = "-MCollectd";
2611 perl_argv[2] = "-e";
2613 perl_argv[4] = NULL;
2615 plugin_register_complex_config ("perl", perl_config);
2617 } /* void module_register (void) */
2619 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */