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
47 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
49 #pragma GCC poison sprintf
54 /* Some versions of Perl define their own version of DEBUG... :-/ */
59 /* ... while we want the definition found in plugin.h. */
63 #include "filter_chain.h"
65 #if !defined(USE_ITHREADS)
66 #error "Perl does not support ithreads!"
67 #endif /* !defined(USE_ITHREADS) */
69 /* clear the Perl sub's stack frame
70 * (this should only be used inside an XSUB) */
71 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
75 #define PLUGIN_WRITE 2
76 #define PLUGIN_SHUTDOWN 3
78 #define PLUGIN_NOTIF 5
79 #define PLUGIN_FLUSH 6
81 #define PLUGIN_TYPES 7
83 #define PLUGIN_CONFIG 254
84 #define PLUGIN_DATASET 255
91 #define FC_CB_CREATE 0
92 #define FC_CB_DESTROY 1
97 #define log_debug(...) DEBUG("perl: " __VA_ARGS__)
98 #define log_info(...) INFO("perl: " __VA_ARGS__)
99 #define log_warn(...) WARNING("perl: " __VA_ARGS__)
100 #define log_err(...) ERROR("perl: " __VA_ARGS__)
102 /* this is defined in DynaLoader.a */
103 void boot_DynaLoader(PerlInterpreter *, CV *);
105 static XS(Collectd_plugin_register_ds);
106 static XS(Collectd_plugin_unregister_ds);
107 static XS(Collectd_plugin_dispatch_values);
108 static XS(Collectd_plugin_get_interval);
109 static XS(Collectd__plugin_write);
110 static XS(Collectd__plugin_flush);
111 static XS(Collectd_plugin_dispatch_notification);
112 static XS(Collectd_plugin_log);
113 static XS(Collectd__fc_register);
114 static XS(Collectd_call_by_name);
120 typedef struct c_ithread_s {
121 /* the thread's Perl interpreter */
122 PerlInterpreter *interp;
123 _Bool running; /* thread is inside Perl interpreter */
127 /* double linked list of threads */
128 struct c_ithread_s *prev;
129 struct c_ithread_s *next;
137 /* some usage stats */
138 int number_of_threads;
139 #endif /* COLLECT_DEBUG */
141 pthread_mutex_t mutex;
142 pthread_mutexattr_t mutexattr;
145 /* name / user_data for Perl matches / targets */
151 #define PFC_USER_DATA_FREE(data) \
153 sfree((data)->name); \
154 if (NULL != (data)->user_data) \
155 sv_free((data)->user_data); \
162 extern char **environ;
168 /* if perl_threads != NULL perl_threads->head must
169 * point to the "base" thread */
170 static c_ithread_list_t *perl_threads = NULL;
172 /* the key used to store each pthread's ithread */
173 static pthread_key_t perl_thr_key;
175 static int perl_argc = 0;
176 static char **perl_argv = NULL;
178 static char base_name[DATA_MAX_NAME_LEN] = "";
184 {"Collectd::plugin_register_data_set", Collectd_plugin_register_ds},
185 {"Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds},
186 {"Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values},
187 {"Collectd::plugin_get_interval", Collectd_plugin_get_interval},
188 {"Collectd::_plugin_write", Collectd__plugin_write},
189 {"Collectd::_plugin_flush", Collectd__plugin_flush},
190 {"Collectd::plugin_dispatch_notification",
191 Collectd_plugin_dispatch_notification},
192 {"Collectd::plugin_log", Collectd_plugin_log},
193 {"Collectd::_fc_register", Collectd__fc_register},
194 {"Collectd::call_by_name", Collectd_call_by_name},
200 } constants[] = {{"Collectd::TYPE_INIT", PLUGIN_INIT},
201 {"Collectd::TYPE_READ", PLUGIN_READ},
202 {"Collectd::TYPE_WRITE", PLUGIN_WRITE},
203 {"Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN},
204 {"Collectd::TYPE_LOG", PLUGIN_LOG},
205 {"Collectd::TYPE_NOTIF", PLUGIN_NOTIF},
206 {"Collectd::TYPE_FLUSH", PLUGIN_FLUSH},
207 {"Collectd::TYPE_CONFIG", PLUGIN_CONFIG},
208 {"Collectd::TYPE_DATASET", PLUGIN_DATASET},
209 {"Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER},
210 {"Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE},
211 {"Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE},
212 {"Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE},
213 {"Collectd::LOG_ERR", LOG_ERR},
214 {"Collectd::LOG_WARNING", LOG_WARNING},
215 {"Collectd::LOG_NOTICE", LOG_NOTICE},
216 {"Collectd::LOG_INFO", LOG_INFO},
217 {"Collectd::LOG_DEBUG", LOG_DEBUG},
218 {"Collectd::FC_MATCH", FC_MATCH},
219 {"Collectd::FC_TARGET", FC_TARGET},
220 {"Collectd::FC_CB_CREATE", FC_CB_CREATE},
221 {"Collectd::FC_CB_DESTROY", FC_CB_DESTROY},
222 {"Collectd::FC_CB_EXEC", FC_CB_EXEC},
223 {"Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH},
224 {"Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES},
225 {"Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE},
226 {"Collectd::FC_TARGET_STOP", FC_TARGET_STOP},
227 {"Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN},
228 {"Collectd::NOTIF_FAILURE", NOTIF_FAILURE},
229 {"Collectd::NOTIF_WARNING", NOTIF_WARNING},
230 {"Collectd::NOTIF_OKAY", NOTIF_OKAY},
236 } g_strings[] = {{"Collectd::hostname_g", hostname_g}, {"", NULL}};
239 * Helper functions for data type conversion.
254 static int hv2data_source(pTHX_ HV *hash, data_source_t *ds) {
257 if ((NULL == hash) || (NULL == ds))
260 if (NULL != (tmp = hv_fetch(hash, "name", 4, 0))) {
261 sstrncpy(ds->name, SvPV_nolen(*tmp), sizeof(ds->name));
263 log_err("hv2data_source: No DS name given.");
267 if (NULL != (tmp = hv_fetch(hash, "type", 4, 0))) {
268 ds->type = SvIV(*tmp);
270 if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type) &&
271 (DS_TYPE_DERIVE != ds->type) && (DS_TYPE_ABSOLUTE != ds->type)) {
272 log_err("hv2data_source: Invalid DS type.");
276 ds->type = DS_TYPE_COUNTER;
279 if (NULL != (tmp = hv_fetch(hash, "min", 3, 0)))
280 ds->min = SvNV(*tmp);
284 if (NULL != (tmp = hv_fetch(hash, "max", 3, 0)))
285 ds->max = SvNV(*tmp);
289 } /* static int hv2data_source (HV *, data_source_t *) */
291 /* av2value converts at most "len" elements from "array" to "value". Returns the
292 * number of elements converted or zero on error. */
293 static size_t av2value(pTHX_ char *name, AV *array, value_t *value,
295 const data_set_t *ds;
297 if ((NULL == name) || (NULL == array) || (NULL == value) || (array_len == 0))
300 ds = plugin_get_ds(name);
302 log_err("av2value: Unknown dataset \"%s\"", name);
306 if (array_len < ds->ds_num) {
307 log_warn("av2value: array does not contain enough elements for type "
308 "\"%s\": got %zu, want %zu",
309 name, array_len, ds->ds_num);
311 } else if (array_len > ds->ds_num) {
312 log_warn("av2value: array contains excess elements for type \"%s\": got "
314 name, array_len, ds->ds_num);
317 for (size_t i = 0; i < ds->ds_num; ++i) {
318 SV **tmp = av_fetch(array, i, 0);
321 if (DS_TYPE_COUNTER == ds->ds[i].type)
322 value[i].counter = SvIV(*tmp);
323 else if (DS_TYPE_GAUGE == ds->ds[i].type)
324 value[i].gauge = SvNV(*tmp);
325 else if (DS_TYPE_DERIVE == ds->ds[i].type)
326 value[i].derive = SvIV(*tmp);
327 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
328 value[i].absolute = SvIV(*tmp);
335 } /* static size_t av2value (char *, AV *, value_t *, size_t) */
340 * values => [ @values ],
344 * plugin_instance => $pinstance,
345 * type_instance => $tinstance,
348 static int hv2value_list(pTHX_ HV *hash, value_list_t *vl) {
351 if ((NULL == hash) || (NULL == vl))
354 if (NULL == (tmp = hv_fetch(hash, "type", 4, 0))) {
355 log_err("hv2value_list: No type given.");
359 sstrncpy(vl->type, SvPV_nolen(*tmp), sizeof(vl->type));
361 if ((NULL == (tmp = hv_fetch(hash, "values", 6, 0))) ||
362 (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp)))))) {
363 log_err("hv2value_list: No valid values given.");
368 AV *array = (AV *)SvRV(*tmp);
369 /* av_len returns the highest index, not the actual length. */
370 size_t array_len = (size_t)(av_len(array) + 1);
374 vl->values = calloc(array_len, sizeof(*vl->values));
376 av2value(aTHX_ vl->type, (AV *)SvRV(*tmp), vl->values, array_len);
377 if (vl->values_len == 0) {
383 if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
384 double t = SvNV(*tmp);
385 vl->time = DOUBLE_TO_CDTIME_T(t);
388 if (NULL != (tmp = hv_fetch(hash, "interval", 8, 0))) {
389 double t = SvNV(*tmp);
390 vl->interval = DOUBLE_TO_CDTIME_T(t);
393 if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
394 sstrncpy(vl->host, SvPV_nolen(*tmp), sizeof(vl->host));
396 sstrncpy(vl->host, hostname_g, sizeof(vl->host));
398 if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
399 sstrncpy(vl->plugin, SvPV_nolen(*tmp), sizeof(vl->plugin));
401 if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
402 sstrncpy(vl->plugin_instance, SvPV_nolen(*tmp),
403 sizeof(vl->plugin_instance));
405 if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
406 sstrncpy(vl->type_instance, SvPV_nolen(*tmp), sizeof(vl->type_instance));
408 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
410 static int av2data_set(pTHX_ AV *array, char *name, data_set_t *ds) {
413 if ((NULL == array) || (NULL == name) || (NULL == ds))
419 log_err("av2data_set: Invalid data set.");
423 ds->ds = smalloc((len + 1) * sizeof(*ds->ds));
424 ds->ds_num = len + 1;
426 for (int i = 0; i <= len; ++i) {
427 SV **elem = av_fetch(array, i, 0);
430 log_err("av2data_set: Failed to fetch data source %i.", i);
434 if (!(SvROK(*elem) && (SVt_PVHV == SvTYPE(SvRV(*elem))))) {
435 log_err("av2data_set: Invalid data source.");
439 if (-1 == hv2data_source(aTHX_(HV *) SvRV(*elem), &ds->ds[i]))
442 log_debug("av2data_set: "
443 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
444 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
447 sstrncpy(ds->type, name, sizeof(ds->type));
449 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
454 * severity => $severity,
460 * plugin_instance => $instance,
461 * type_instance => $type_instance,
462 * meta => [ { name => <name>, value => <value> }, ... ]
465 static int av2notification_meta(pTHX_ AV *array, notification_meta_t **meta) {
466 notification_meta_t **m = meta;
468 int len = av_len(array);
470 for (int i = 0; i <= len; ++i) {
471 SV **tmp = av_fetch(array, i, 0);
477 if (!(SvROK(*tmp) && (SVt_PVHV == SvTYPE(SvRV(*tmp))))) {
478 log_warn("av2notification_meta: Skipping invalid "
479 "meta information.");
483 hash = (HV *)SvRV(*tmp);
485 *m = smalloc(sizeof(**m));
487 if (NULL == (tmp = hv_fetch(hash, "name", 4, 0))) {
488 log_warn("av2notification_meta: Skipping invalid "
489 "meta information.");
493 sstrncpy((*m)->name, SvPV_nolen(*tmp), sizeof((*m)->name));
495 if (NULL == (tmp = hv_fetch(hash, "value", 5, 0))) {
496 log_warn("av2notification_meta: Skipping invalid "
497 "meta information.");
503 (*m)->nm_value.nm_double = SvNVX(*tmp);
504 (*m)->type = NM_TYPE_DOUBLE;
505 } else if (SvUOK(*tmp)) {
506 (*m)->nm_value.nm_unsigned_int = SvUVX(*tmp);
507 (*m)->type = NM_TYPE_UNSIGNED_INT;
508 } else if (SvIOK(*tmp)) {
509 (*m)->nm_value.nm_signed_int = SvIVX(*tmp);
510 (*m)->type = NM_TYPE_SIGNED_INT;
512 (*m)->nm_value.nm_string = sstrdup(SvPV_nolen(*tmp));
513 (*m)->type = NM_TYPE_STRING;
520 } /* static int av2notification_meta (AV *, notification_meta_t *) */
522 static int hv2notification(pTHX_ HV *hash, notification_t *n) {
525 if ((NULL == hash) || (NULL == n))
528 if (NULL != (tmp = hv_fetch(hash, "severity", 8, 0)))
529 n->severity = SvIV(*tmp);
531 n->severity = NOTIF_FAILURE;
533 if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
534 double t = SvNV(*tmp);
535 n->time = DOUBLE_TO_CDTIME_T(t);
539 if (NULL != (tmp = hv_fetch(hash, "message", 7, 0)))
540 sstrncpy(n->message, SvPV_nolen(*tmp), sizeof(n->message));
542 if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
543 sstrncpy(n->host, SvPV_nolen(*tmp), sizeof(n->host));
545 sstrncpy(n->host, hostname_g, sizeof(n->host));
547 if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
548 sstrncpy(n->plugin, SvPV_nolen(*tmp), sizeof(n->plugin));
550 if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
551 sstrncpy(n->plugin_instance, SvPV_nolen(*tmp), sizeof(n->plugin_instance));
553 if (NULL != (tmp = hv_fetch(hash, "type", 4, 0)))
554 sstrncpy(n->type, SvPV_nolen(*tmp), sizeof(n->type));
556 if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
557 sstrncpy(n->type_instance, SvPV_nolen(*tmp), sizeof(n->type_instance));
560 while (NULL != (tmp = hv_fetch(hash, "meta", 4, 0))) {
561 if (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp))))) {
562 log_warn("hv2notification: Ignoring invalid meta information.");
566 if (0 != av2notification_meta(aTHX_(AV *) SvRV(*tmp), &n->meta)) {
567 plugin_notification_meta_free(n->meta);
574 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
576 static int data_set2av(pTHX_ data_set_t *ds, AV *array) {
577 if ((NULL == ds) || (NULL == array))
580 av_extend(array, ds->ds_num);
582 for (size_t i = 0; i < ds->ds_num; ++i) {
583 HV *source = newHV();
585 if (NULL == hv_store(source, "name", 4, newSVpv(ds->ds[i].name, 0), 0))
588 if (NULL == hv_store(source, "type", 4, newSViv(ds->ds[i].type), 0))
591 if (!isnan(ds->ds[i].min))
592 if (NULL == hv_store(source, "min", 3, newSVnv(ds->ds[i].min), 0))
595 if (!isnan(ds->ds[i].max))
596 if (NULL == hv_store(source, "max", 3, newSVnv(ds->ds[i].max), 0))
599 if (NULL == av_store(array, i, newRV_noinc((SV *)source)))
603 } /* static int data_set2av (data_set_t *, AV *) */
605 static int value_list2hv(pTHX_ value_list_t *vl, data_set_t *ds, HV *hash) {
609 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
613 /* av_extend takes the last *index* to which the array should be extended. */
614 av_extend(values, vl->values_len - 1);
616 assert(ds->ds_num == vl->values_len);
617 for (i = 0; i < vl->values_len; ++i) {
620 if (DS_TYPE_COUNTER == ds->ds[i].type)
621 val = newSViv(vl->values[i].counter);
622 else if (DS_TYPE_GAUGE == ds->ds[i].type)
623 val = newSVnv(vl->values[i].gauge);
624 else if (DS_TYPE_DERIVE == ds->ds[i].type)
625 val = newSViv(vl->values[i].derive);
626 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
627 val = newSViv(vl->values[i].absolute);
629 if (NULL == av_store(values, i, val)) {
635 if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0))
639 double t = CDTIME_T_TO_DOUBLE(vl->time);
640 if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
645 double t = CDTIME_T_TO_DOUBLE(vl->interval);
646 if (NULL == hv_store(hash, "interval", 8, newSVnv(t), 0))
650 if ('\0' != vl->host[0])
651 if (NULL == hv_store(hash, "host", 4, newSVpv(vl->host, 0), 0))
654 if ('\0' != vl->plugin[0])
655 if (NULL == hv_store(hash, "plugin", 6, newSVpv(vl->plugin, 0), 0))
658 if ('\0' != vl->plugin_instance[0])
659 if (NULL == hv_store(hash, "plugin_instance", 15,
660 newSVpv(vl->plugin_instance, 0), 0))
663 if ('\0' != vl->type[0])
664 if (NULL == hv_store(hash, "type", 4, newSVpv(vl->type, 0), 0))
667 if ('\0' != vl->type_instance[0])
669 hv_store(hash, "type_instance", 13, newSVpv(vl->type_instance, 0), 0))
672 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
674 static int notification_meta2av(pTHX_ notification_meta_t *meta, AV *array) {
682 av_extend(array, meta_num);
684 for (int i = 0; NULL != meta; meta = meta->next, ++i) {
688 if (NULL == hv_store(m, "name", 4, newSVpv(meta->name, 0), 0))
691 if (NM_TYPE_STRING == meta->type)
692 value = newSVpv(meta->nm_value.nm_string, 0);
693 else if (NM_TYPE_SIGNED_INT == meta->type)
694 value = newSViv(meta->nm_value.nm_signed_int);
695 else if (NM_TYPE_UNSIGNED_INT == meta->type)
696 value = newSVuv(meta->nm_value.nm_unsigned_int);
697 else if (NM_TYPE_DOUBLE == meta->type)
698 value = newSVnv(meta->nm_value.nm_double);
699 else if (NM_TYPE_BOOLEAN == meta->type)
700 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
704 if (NULL == hv_store(m, "value", 5, value, 0)) {
709 if (NULL == av_store(array, i, newRV_noinc((SV *)m))) {
716 } /* static int notification_meta2av (notification_meta_t *, AV *) */
718 static int notification2hv(pTHX_ notification_t *n, HV *hash) {
719 if (NULL == hv_store(hash, "severity", 8, newSViv(n->severity), 0))
723 double t = CDTIME_T_TO_DOUBLE(n->time);
724 if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
728 if ('\0' != *n->message)
729 if (NULL == hv_store(hash, "message", 7, newSVpv(n->message, 0), 0))
732 if ('\0' != *n->host)
733 if (NULL == hv_store(hash, "host", 4, newSVpv(n->host, 0), 0))
736 if ('\0' != *n->plugin)
737 if (NULL == hv_store(hash, "plugin", 6, newSVpv(n->plugin, 0), 0))
740 if ('\0' != *n->plugin_instance)
741 if (NULL == hv_store(hash, "plugin_instance", 15,
742 newSVpv(n->plugin_instance, 0), 0))
745 if ('\0' != *n->type)
746 if (NULL == hv_store(hash, "type", 4, newSVpv(n->type, 0), 0))
749 if ('\0' != *n->type_instance)
751 hv_store(hash, "type_instance", 13, newSVpv(n->type_instance, 0), 0))
754 if (NULL != n->meta) {
756 if ((0 != notification_meta2av(aTHX_ n->meta, meta)) ||
757 (NULL == hv_store(hash, "meta", 4, newRV_noinc((SV *)meta), 0))) {
764 } /* static int notification2hv (notification_t *, HV *) */
766 static int oconfig_item2hv(pTHX_ oconfig_item_t *ci, HV *hash) {
770 if (NULL == hv_store(hash, "key", 3, newSVpv(ci->key, 0), 0))
774 if (0 < ci->values_num)
775 av_extend(values, ci->values_num);
777 if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0)) {
783 for (int i = 0; i < ci->values_num; ++i) {
786 switch (ci->values[i].type) {
787 case OCONFIG_TYPE_STRING:
788 value = newSVpv(ci->values[i].value.string, 0);
790 case OCONFIG_TYPE_NUMBER:
791 value = newSVnv((NV)ci->values[i].value.number);
793 case OCONFIG_TYPE_BOOLEAN:
794 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
797 log_err("oconfig_item2hv: Invalid value type %i.", ci->values[i].type);
798 value = &PL_sv_undef;
801 if (NULL == av_store(values, i, value)) {
807 /* ignoring 'parent' member which is uninteresting in this case */
810 if (0 < ci->children_num)
811 av_extend(children, ci->children_num);
813 if (NULL == hv_store(hash, "children", 8, newRV_noinc((SV *)children), 0)) {
819 for (int i = 0; i < ci->children_num; ++i) {
822 if (0 != oconfig_item2hv(aTHX_ ci->children + i, child)) {
828 if (NULL == av_store(children, i, newRV_noinc((SV *)child))) {
835 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
838 * Internal functions.
841 static char *get_module_name(char *buf, size_t buf_len, const char *module) {
843 if (base_name[0] == '\0')
844 status = ssnprintf(buf, buf_len, "%s", module);
846 status = ssnprintf(buf, buf_len, "%s::%s", base_name, module);
847 if ((status < 0) || ((unsigned int)status >= buf_len))
850 } /* char *get_module_name */
853 * Add a plugin's data set definition.
855 static int pplugin_register_data_set(pTHX_ char *name, AV *dataset) {
860 if ((NULL == name) || (NULL == dataset))
863 if (0 != av2data_set(aTHX_ dataset, name, &ds))
866 ret = plugin_register_data_set(&ds);
870 } /* static int pplugin_register_data_set (char *, SV *) */
873 * Remove a plugin's data set definition.
875 static int pplugin_unregister_data_set(char *name) {
878 return plugin_unregister_data_set(name);
879 } /* static int pplugin_unregister_data_set (char *) */
882 * Submit the values to the write functions.
884 static int pplugin_dispatch_values(pTHX_ HV *values) {
885 value_list_t vl = VALUE_LIST_INIT;
892 if (0 != hv2value_list(aTHX_ values, &vl))
895 ret = plugin_dispatch_values(&vl);
899 } /* static int pplugin_dispatch_values (char *, HV *) */
902 * Submit the values to a single write function.
904 static int pplugin_write(pTHX_ const char *plugin, AV *data_set, HV *values) {
906 value_list_t vl = VALUE_LIST_INIT;
913 if (0 != hv2value_list(aTHX_ values, &vl))
916 if ((NULL != data_set) && (0 != av2data_set(aTHX_ data_set, vl.type, &ds)))
919 ret = plugin_write(plugin, NULL == data_set ? NULL : &ds, &vl);
921 log_warn("Dispatching value to plugin \"%s\" failed with status %i.",
922 NULL == plugin ? "<any>" : plugin, ret);
924 if (NULL != data_set)
928 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
931 * Dispatch a notification.
933 static int pplugin_dispatch_notification(pTHX_ HV *notif) {
934 notification_t n = {0};
941 if (0 != hv2notification(aTHX_ notif, &n))
944 ret = plugin_dispatch_notification(&n);
945 plugin_notification_meta_free(n.meta);
947 } /* static int pplugin_dispatch_notification (HV *) */
950 * Call perl sub with thread locking flags handled.
952 static int call_pv_locked(pTHX_ const char *sub_name) {
956 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
957 if (t == NULL) /* thread destroyed */
960 old_running = t->running;
964 t->running = old_running;
968 ret = call_pv(sub_name, G_SCALAR);
970 t->running = old_running;
972 } /* static int call_pv_locked (pTHX, *sub_name) */
975 * Call all working functions of the given type.
977 static int pplugin_call_all(pTHX_ int type, ...) {
985 if ((type < 0) || (type >= PLUGIN_TYPES))
995 XPUSHs(sv_2mortal(newSViv((IV)type)));
997 if (PLUGIN_WRITE == type) {
999 * $_[0] = $plugin_type;
1014 * values => [ $v1, ... ],
1016 * host => $hostname,
1017 * plugin => $plugin,
1019 * plugin_instance => $instance,
1020 * type_instance => $type_instance
1029 ds = va_arg(ap, data_set_t *);
1030 vl = va_arg(ap, value_list_t *);
1032 if (-1 == data_set2av(aTHX_ ds, pds)) {
1035 pds = (AV *)&PL_sv_undef;
1039 if (-1 == value_list2hv(aTHX_ vl, ds, pvl)) {
1042 pvl = (HV *)&PL_sv_undef;
1046 XPUSHs(sv_2mortal(newSVpv(ds->type, 0)));
1047 XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1048 XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1049 } else if (PLUGIN_LOG == type) {
1055 XPUSHs(sv_2mortal(newSViv(va_arg(ap, int))));
1056 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1057 } else if (PLUGIN_NOTIF == type) {
1061 * severity => $severity,
1065 * plugin => $plugin,
1067 * plugin_instance => $instance,
1068 * type_instance => $type_instance
1072 HV *notif = newHV();
1074 n = va_arg(ap, notification_t *);
1076 if (-1 == notification2hv(aTHX_ n, notif)) {
1079 notif = (HV *)&PL_sv_undef;
1083 XPUSHs(sv_2mortal(newRV_noinc((SV *)notif)));
1084 } else if (PLUGIN_FLUSH == type) {
1089 * $_[1] = $identifier;
1091 timeout = va_arg(ap, cdtime_t);
1093 XPUSHs(sv_2mortal(newSVnv(CDTIME_T_TO_DOUBLE(timeout))));
1094 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1099 retvals = call_pv_locked(aTHX_ "Collectd::plugin_call_all");
1114 } /* static int pplugin_call_all (int, ...) */
1117 * collectd's Perl interpreter based thread implementation.
1119 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1122 /* must be called with perl_threads->mutex locked */
1123 static void c_ithread_destroy(c_ithread_t *ithread) {
1124 dTHXa(ithread->interp);
1126 assert(NULL != perl_threads);
1128 PERL_SET_CONTEXT(aTHX);
1129 log_debug("Shutting down Perl interpreter %p...", aTHX);
1134 --perl_threads->number_of_threads;
1135 #endif /* COLLECT_DEBUG */
1137 perl_destruct(aTHX);
1140 if (NULL == ithread->prev)
1141 perl_threads->head = ithread->next;
1143 ithread->prev->next = ithread->next;
1145 if (NULL == ithread->next)
1146 perl_threads->tail = ithread->prev;
1148 ithread->next->prev = ithread->prev;
1152 } /* static void c_ithread_destroy (c_ithread_t *) */
1154 static void c_ithread_destructor(void *arg) {
1155 c_ithread_t *ithread = (c_ithread_t *)arg;
1156 c_ithread_t *t = NULL;
1158 if (NULL == perl_threads)
1161 pthread_mutex_lock(&perl_threads->mutex);
1163 for (t = perl_threads->head; NULL != t; t = t->next)
1167 /* the ithread no longer exists */
1169 pthread_mutex_unlock(&perl_threads->mutex);
1173 c_ithread_destroy(ithread);
1175 pthread_mutex_unlock(&perl_threads->mutex);
1177 } /* static void c_ithread_destructor (void *) */
1179 /* must be called with perl_threads->mutex locked */
1180 static c_ithread_t *c_ithread_create(PerlInterpreter *base) {
1181 c_ithread_t *t = NULL;
1184 assert(NULL != perl_threads);
1186 t = smalloc(sizeof(*t));
1187 memset(t, 0, sizeof(c_ithread_t));
1189 t->interp = (NULL == base) ? NULL : perl_clone(base, CLONEf_KEEP_PTR_TABLE);
1193 if ((NULL != base) && (NULL != PL_endav)) {
1200 ++perl_threads->number_of_threads;
1201 #endif /* COLLECT_DEBUG */
1205 if (NULL == perl_threads->tail) {
1206 perl_threads->head = t;
1209 perl_threads->tail->next = t;
1210 t->prev = perl_threads->tail;
1213 t->pthread = pthread_self();
1216 perl_threads->tail = t;
1218 pthread_setspecific(perl_thr_key, (const void *)t);
1220 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1223 * Filter chains implementation.
1226 static int fc_call(pTHX_ int type, int cb_type, pfc_user_data_t *data, ...) {
1232 notification_meta_t **meta = NULL;
1237 if ((type < 0) || (type >= FC_TYPES))
1240 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1250 XPUSHs(sv_2mortal(newSViv((IV)type)));
1251 XPUSHs(sv_2mortal(newSVpv(data->name, 0)));
1252 XPUSHs(sv_2mortal(newSViv((IV)cb_type)));
1254 if (FC_CB_CREATE == cb_type) {
1257 * $_[1] = $user_data;
1260 HV *config = newHV();
1262 ci = va_arg(ap, oconfig_item_t *);
1264 if (0 != oconfig_item2hv(aTHX_ ci, config)) {
1267 config = (HV *)&PL_sv_undef;
1271 XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
1272 } else if (FC_CB_DESTROY == cb_type) {
1274 * $_[1] = $user_data;
1277 /* nothing to be done - the user data pointer
1278 * is pushed onto the stack later */
1279 } else if (FC_CB_EXEC == cb_type) {
1284 * $_[3] = $user_data;
1292 ds = va_arg(ap, data_set_t *);
1293 vl = va_arg(ap, value_list_t *);
1294 meta = va_arg(ap, notification_meta_t **);
1296 if (0 != data_set2av(aTHX_ ds, pds)) {
1299 pds = (AV *)&PL_sv_undef;
1303 if (0 != value_list2hv(aTHX_ vl, ds, pvl)) {
1306 pvl = (HV *)&PL_sv_undef;
1313 if (0 != notification_meta2av(aTHX_ * meta, pmeta)) {
1316 pmeta = (AV *)&PL_sv_undef;
1320 pmeta = (AV *)&PL_sv_undef;
1323 XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1324 XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1325 XPUSHs(sv_2mortal(newRV_noinc((SV *)pmeta)));
1328 XPUSHs(sv_2mortal(newRV_inc(data->user_data)));
1332 retvals = call_pv_locked(aTHX_ "Collectd::fc_call");
1334 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1335 assert(pmeta != NULL);
1337 plugin_notification_meta_free(*meta);
1338 av2notification_meta(aTHX_ pmeta, meta);
1345 /* the exec callbacks return a status, while
1346 * the others return a boolean value */
1347 if (FC_CB_EXEC == cb_type)
1349 else if (!SvTRUE(tmp))
1359 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1361 static int fc_create(int type, const oconfig_item_t *ci, void **user_data) {
1362 pfc_user_data_t *data;
1368 if (NULL == perl_threads)
1372 c_ithread_t *t = NULL;
1374 pthread_mutex_lock(&perl_threads->mutex);
1375 t = c_ithread_create(perl_threads->head->interp);
1376 pthread_mutex_unlock(&perl_threads->mutex);
1381 log_debug("fc_create: c_ithread: interp = %p (active threads: %i)", aTHX,
1382 perl_threads->number_of_threads);
1384 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1385 log_warn("A \"%s\" block expects a single string argument.",
1386 (FC_MATCH == type) ? "Match" : "Target");
1390 data = smalloc(sizeof(*data));
1391 data->name = sstrdup(ci->values[0].value.string);
1392 data->user_data = newSV(0);
1394 ret = fc_call(aTHX_ type, FC_CB_CREATE, data, ci);
1397 PFC_USER_DATA_FREE(data);
1401 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1403 static int fc_destroy(int type, void **user_data) {
1404 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1410 if ((NULL == perl_threads) || (NULL == data))
1414 c_ithread_t *t = NULL;
1416 pthread_mutex_lock(&perl_threads->mutex);
1417 t = c_ithread_create(perl_threads->head->interp);
1418 pthread_mutex_unlock(&perl_threads->mutex);
1423 log_debug("fc_destroy: c_ithread: interp = %p (active threads: %i)", aTHX,
1424 perl_threads->number_of_threads);
1426 ret = fc_call(aTHX_ type, FC_CB_DESTROY, data);
1428 PFC_USER_DATA_FREE(data);
1431 } /* static int fc_destroy (int, void **) */
1433 static int fc_exec(int type, const data_set_t *ds, const value_list_t *vl,
1434 notification_meta_t **meta, void **user_data) {
1435 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1439 if (NULL == perl_threads)
1442 assert(NULL != data);
1445 c_ithread_t *t = NULL;
1447 pthread_mutex_lock(&perl_threads->mutex);
1448 t = c_ithread_create(perl_threads->head->interp);
1449 pthread_mutex_unlock(&perl_threads->mutex);
1454 log_debug("fc_exec: c_ithread: interp = %p (active threads: %i)", aTHX,
1455 perl_threads->number_of_threads);
1457 return fc_call(aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1458 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1459 notification_meta_t **, void **) */
1461 static int pmatch_create(const oconfig_item_t *ci, void **user_data) {
1462 return fc_create(FC_MATCH, ci, user_data);
1463 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1465 static int pmatch_destroy(void **user_data) {
1466 return fc_destroy(FC_MATCH, user_data);
1467 } /* static int pmatch_destroy (void **) */
1469 static int pmatch_match(const data_set_t *ds, const value_list_t *vl,
1470 notification_meta_t **meta, void **user_data) {
1471 return fc_exec(FC_MATCH, ds, vl, meta, user_data);
1472 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1473 notification_meta_t **, void **) */
1475 static match_proc_t pmatch = {pmatch_create, pmatch_destroy, pmatch_match};
1477 static int ptarget_create(const oconfig_item_t *ci, void **user_data) {
1478 return fc_create(FC_TARGET, ci, user_data);
1479 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1481 static int ptarget_destroy(void **user_data) {
1482 return fc_destroy(FC_TARGET, user_data);
1483 } /* static int ptarget_destroy (void **) */
1485 static int ptarget_invoke(const data_set_t *ds, value_list_t *vl,
1486 notification_meta_t **meta, void **user_data) {
1487 return fc_exec(FC_TARGET, ds, vl, meta, user_data);
1488 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1489 notification_meta_t **, void **) */
1491 static target_proc_t ptarget = {ptarget_create, ptarget_destroy,
1495 * Exported Perl API.
1499 * Collectd::plugin_register_data_set (type, dataset).
1502 * type of the dataset
1505 * dataset to be registered
1507 static XS(Collectd_plugin_register_ds) {
1513 log_warn("Using plugin_register() to register new data-sets is "
1514 "deprecated - add new entries to a custom types.db instead.");
1517 log_err("Usage: Collectd::plugin_register_data_set(type, dataset)");
1521 log_debug("Collectd::plugin_register_data_set: "
1522 "type = \"%s\", dataset = \"%s\"",
1523 SvPV_nolen(ST(0)), SvPV_nolen(ST(1)));
1527 if (SvROK(data) && (SVt_PVAV == SvTYPE(SvRV(data)))) {
1528 ret = pplugin_register_data_set(aTHX_ SvPV_nolen(ST(0)), (AV *)SvRV(data));
1530 log_err("Collectd::plugin_register_data_set: Invalid data.");
1538 } /* static XS (Collectd_plugin_register_ds) */
1541 * Collectd::plugin_unregister_data_set (type).
1544 * type of the dataset
1546 static XS(Collectd_plugin_unregister_ds) {
1550 log_err("Usage: Collectd::plugin_unregister_data_set(type)");
1554 log_debug("Collectd::plugin_unregister_data_set: type = \"%s\"",
1557 if (0 == pplugin_unregister_data_set(SvPV_nolen(ST(0))))
1561 } /* static XS (Collectd_plugin_register_ds) */
1564 * Collectd::plugin_dispatch_values (name, values).
1567 * name of the plugin
1570 * value list to submit
1572 static XS(Collectd_plugin_dispatch_values) {
1580 log_err("Usage: Collectd::plugin_dispatch_values(values)");
1584 log_debug("Collectd::plugin_dispatch_values: values=\"%s\"",
1585 SvPV_nolen(ST(/* stack index = */ 0)));
1587 values = ST(/* stack index = */ 0);
1592 /* Make sure the argument is a hash reference. */
1593 if (!(SvROK(values) && (SVt_PVHV == SvTYPE(SvRV(values))))) {
1594 log_err("Collectd::plugin_dispatch_values: Invalid values.");
1598 ret = pplugin_dispatch_values(aTHX_(HV *) SvRV(values));
1604 } /* static XS (Collectd_plugin_dispatch_values) */
1607 * Collectd::plugin_get_interval ().
1609 static XS(Collectd_plugin_get_interval) {
1612 /* make sure we don't get any unused variable warnings for 'items';
1613 * don't abort, though */
1615 log_err("Usage: Collectd::plugin_get_interval()");
1617 XSRETURN_NV((NV)CDTIME_T_TO_DOUBLE(plugin_get_interval()));
1618 } /* static XS (Collectd_plugin_get_interval) */
1620 /* Collectd::plugin_write (plugin, ds, vl).
1623 * name of the plugin to call, may be 'undef'
1626 * data-set that describes the submitted values, may be 'undef'
1629 * value-list to be written
1631 static XS(Collectd__plugin_write) {
1641 log_err("Usage: Collectd::plugin_write(plugin, ds, vl)");
1645 log_debug("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1646 SvPV_nolen(ST(0)), SvOK(ST(1)) ? SvPV_nolen(ST(1)) : "",
1652 plugin = SvPV_nolen(ST(0));
1655 if (SvROK(ds) && (SVt_PVAV == SvTYPE(SvRV(ds))))
1656 ds_array = (AV *)SvRV(ds);
1660 log_err("Collectd::plugin_write: Invalid data-set.");
1665 if (!(SvROK(vl) && (SVt_PVHV == SvTYPE(SvRV(vl))))) {
1666 log_err("Collectd::plugin_write: Invalid value-list.");
1670 ret = pplugin_write(aTHX_ plugin, ds_array, (HV *)SvRV(vl));
1676 } /* static XS (Collectd__plugin_write) */
1679 * Collectd::_plugin_flush (plugin, timeout, identifier).
1682 * name of the plugin to flush
1685 * timeout to use when flushing the data
1688 * data-set identifier to flush
1690 static XS(Collectd__plugin_flush) {
1691 char *plugin = NULL;
1698 log_err("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1703 plugin = SvPV_nolen(ST(0));
1706 timeout = (int)SvIV(ST(1));
1709 id = SvPV_nolen(ST(2));
1711 log_debug("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1713 plugin, timeout, id);
1715 if (0 == plugin_flush(plugin, timeout, id))
1719 } /* static XS (Collectd__plugin_flush) */
1722 * Collectd::plugin_dispatch_notification (notif).
1725 * notification to dispatch
1727 static XS(Collectd_plugin_dispatch_notification) {
1735 log_err("Usage: Collectd::plugin_dispatch_notification(notif)");
1739 log_debug("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1744 if (!(SvROK(notif) && (SVt_PVHV == SvTYPE(SvRV(notif))))) {
1745 log_err("Collectd::plugin_dispatch_notification: Invalid notif.");
1749 ret = pplugin_dispatch_notification(aTHX_(HV *) SvRV(notif));
1755 } /* static XS (Collectd_plugin_dispatch_notification) */
1758 * Collectd::plugin_log (level, message).
1761 * log level (LOG_DEBUG, ... LOG_ERR)
1766 static XS(Collectd_plugin_log) {
1770 log_err("Usage: Collectd::plugin_log(level, message)");
1774 plugin_log(SvIV(ST(0)), "%s", SvPV_nolen(ST(1)));
1776 } /* static XS (Collectd_plugin_log) */
1779 * Collectd::_fc_register (type, name)
1787 static XS(Collectd__fc_register) {
1796 log_err("Usage: Collectd::_fc_register(type, name)");
1801 name = SvPV_nolen(ST(1));
1803 if (FC_MATCH == type)
1804 ret = fc_register_match(name, pmatch);
1805 else if (FC_TARGET == type)
1806 ret = fc_register_target(name, ptarget);
1812 } /* static XS (Collectd_fc_register) */
1815 * Collectd::call_by_name (...).
1817 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1819 static XS(Collectd_call_by_name) {
1823 if (NULL == (tmp = get_sv("Collectd::cb_name", 0))) {
1824 sv_setpv(get_sv("@", 1), "cb_name has not been set");
1829 name = SvPV_nolen(tmp);
1831 if (NULL == get_cv(name, 0)) {
1832 sv_setpvf(get_sv("@", 1), "unknown callback \"%s\"", name);
1837 /* simply pass on the subroutine call without touching the stack,
1838 * thus leaving any arguments and return values in place */
1840 } /* static XS (Collectd_call_by_name) */
1843 * Interface to collectd.
1846 static int perl_init(void) {
1850 if (NULL == perl_threads)
1854 c_ithread_t *t = NULL;
1856 pthread_mutex_lock(&perl_threads->mutex);
1857 t = c_ithread_create(perl_threads->head->interp);
1858 pthread_mutex_unlock(&perl_threads->mutex);
1863 log_debug("perl_init: c_ithread: interp = %p (active threads: %i)", aTHX,
1864 perl_threads->number_of_threads);
1866 /* Lock the base thread to avoid race conditions with c_ithread_create().
1867 * See https://github.com/collectd/collectd/issues/9 and
1868 * https://github.com/collectd/collectd/issues/1706 for details.
1870 assert(aTHX == perl_threads->head->interp);
1871 pthread_mutex_lock(&perl_threads->mutex);
1873 status = pplugin_call_all(aTHX_ PLUGIN_INIT);
1875 pthread_mutex_unlock(&perl_threads->mutex);
1878 } /* static int perl_init (void) */
1880 static int perl_read(void) {
1883 if (NULL == perl_threads)
1887 c_ithread_t *t = NULL;
1889 pthread_mutex_lock(&perl_threads->mutex);
1890 t = c_ithread_create(perl_threads->head->interp);
1891 pthread_mutex_unlock(&perl_threads->mutex);
1896 /* Assert that we're not running as the base thread. Otherwise, we might
1897 * run into concurrency issues with c_ithread_create(). See
1898 * https://github.com/collectd/collectd/issues/9 for details. */
1899 assert(aTHX != perl_threads->head->interp);
1901 log_debug("perl_read: c_ithread: interp = %p (active threads: %i)", aTHX,
1902 perl_threads->number_of_threads);
1903 return pplugin_call_all(aTHX_ PLUGIN_READ);
1904 } /* static int perl_read (void) */
1906 static int perl_write(const data_set_t *ds, const value_list_t *vl,
1907 user_data_t __attribute__((unused)) * user_data) {
1911 if (NULL == perl_threads)
1915 c_ithread_t *t = NULL;
1917 pthread_mutex_lock(&perl_threads->mutex);
1918 t = c_ithread_create(perl_threads->head->interp);
1919 pthread_mutex_unlock(&perl_threads->mutex);
1924 /* Lock the base thread if this is not called from one of the read threads
1925 * to avoid race conditions with c_ithread_create(). See
1926 * https://github.com/collectd/collectd/issues/9 for details. */
1927 if (aTHX == perl_threads->head->interp)
1928 pthread_mutex_lock(&perl_threads->mutex);
1930 log_debug("perl_write: c_ithread: interp = %p (active threads: %i)", aTHX,
1931 perl_threads->number_of_threads);
1932 status = pplugin_call_all(aTHX_ PLUGIN_WRITE, ds, vl);
1934 if (aTHX == perl_threads->head->interp)
1935 pthread_mutex_unlock(&perl_threads->mutex);
1938 } /* static int perl_write (const data_set_t *, const value_list_t *) */
1940 static void perl_log(int level, const char *msg,
1941 user_data_t __attribute__((unused)) * user_data) {
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 /* Lock the base thread if this is not called from one of the read threads
1958 * to avoid race conditions with c_ithread_create(). See
1959 * https://github.com/collectd/collectd/issues/9 for details.
1962 if (aTHX == perl_threads->head->interp)
1963 pthread_mutex_lock(&perl_threads->mutex);
1965 pplugin_call_all(aTHX_ PLUGIN_LOG, level, msg);
1967 if (aTHX == perl_threads->head->interp)
1968 pthread_mutex_unlock(&perl_threads->mutex);
1971 } /* static void perl_log (int, const char *) */
1973 static int perl_notify(const notification_t *notif,
1974 user_data_t __attribute__((unused)) * user_data) {
1977 if (NULL == perl_threads)
1981 c_ithread_t *t = NULL;
1983 pthread_mutex_lock(&perl_threads->mutex);
1984 t = c_ithread_create(perl_threads->head->interp);
1985 pthread_mutex_unlock(&perl_threads->mutex);
1989 return pplugin_call_all(aTHX_ PLUGIN_NOTIF, notif);
1990 } /* static int perl_notify (const notification_t *) */
1992 static int perl_flush(cdtime_t timeout, const char *identifier,
1993 user_data_t __attribute__((unused)) * user_data) {
1996 if (NULL == perl_threads)
2000 c_ithread_t *t = NULL;
2002 pthread_mutex_lock(&perl_threads->mutex);
2003 t = c_ithread_create(perl_threads->head->interp);
2004 pthread_mutex_unlock(&perl_threads->mutex);
2008 return pplugin_call_all(aTHX_ PLUGIN_FLUSH, timeout, identifier);
2009 } /* static int perl_flush (const int) */
2011 static int perl_shutdown(void) {
2017 plugin_unregister_complex_config("perl");
2019 if (NULL == perl_threads)
2023 pthread_mutex_lock(&perl_threads->mutex);
2024 t = c_ithread_create(perl_threads->head->interp);
2025 pthread_mutex_unlock(&perl_threads->mutex);
2030 log_debug("perl_shutdown: c_ithread: interp = %p (active threads: %i)", aTHX,
2031 perl_threads->number_of_threads);
2033 plugin_unregister_log("perl");
2034 plugin_unregister_notification("perl");
2035 plugin_unregister_init("perl");
2036 plugin_unregister_read("perl");
2037 plugin_unregister_write("perl");
2038 plugin_unregister_flush("perl");
2040 ret = pplugin_call_all(aTHX_ PLUGIN_SHUTDOWN);
2042 pthread_mutex_lock(&perl_threads->mutex);
2043 t = perl_threads->tail;
2046 struct timespec ts_wait;
2047 c_ithread_t *thr = t;
2049 /* the pointer has to be advanced before destroying
2050 * the thread as this will free the memory */
2055 /* Give some time to thread to exit from Perl interpreter */
2056 WARNING("perl shutdown: Thread is running inside Perl. Waiting.");
2058 ts_wait.tv_nsec = 500000;
2059 nanosleep(&ts_wait, NULL);
2062 pthread_kill(thr->pthread, SIGTERM);
2063 ERROR("perl shutdown: Thread hangs inside Perl. Thread killed.");
2065 c_ithread_destroy(thr);
2068 pthread_mutex_unlock(&perl_threads->mutex);
2069 pthread_mutex_destroy(&perl_threads->mutex);
2070 pthread_mutexattr_destroy(&perl_threads->mutexattr);
2072 sfree(perl_threads);
2074 pthread_key_delete(perl_thr_key);
2078 plugin_unregister_shutdown("perl");
2080 } /* static void perl_shutdown (void) */
2083 * Access functions for global variables.
2085 * These functions implement the "magic" used to access
2086 * the global variables from Perl.
2089 static int g_pv_get(pTHX_ SV *var, MAGIC *mg) {
2090 char *pv = mg->mg_ptr;
2093 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2095 static int g_pv_set(pTHX_ SV *var, MAGIC *mg) {
2096 char *pv = mg->mg_ptr;
2097 sstrncpy(pv, SvPV_nolen(var), DATA_MAX_NAME_LEN);
2099 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2101 static int g_interval_get(pTHX_ SV *var, MAGIC *mg) {
2102 log_warn("Accessing $interval_g is deprecated (and might not "
2103 "give the desired results) - plugin_get_interval() should "
2104 "be used instead.");
2105 sv_setnv(var, CDTIME_T_TO_DOUBLE(interval_g));
2107 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2109 static int g_interval_set(pTHX_ SV *var, MAGIC *mg) {
2110 double nv = (double)SvNV(var);
2111 log_warn("Accessing $interval_g is deprecated (and might not "
2112 "give the desired results) - plugin_get_interval() should "
2113 "be used instead.");
2114 interval_g = DOUBLE_TO_CDTIME_T(nv);
2116 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2118 static MGVTBL g_pv_vtbl = {g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2119 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2124 static MGVTBL g_interval_vtbl = {g_interval_get, g_interval_set, NULL, NULL,
2126 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2132 /* bootstrap the Collectd module */
2133 static void xs_init(pTHX) {
2136 char *file = __FILE__;
2140 /* enable usage of Perl modules using shared libraries */
2141 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2144 for (int i = 0; NULL != api[i].f; ++i)
2145 newXS(api[i].name, api[i].f, file);
2147 stash = gv_stashpv("Collectd", 1);
2149 /* export "constants" */
2150 for (int i = 0; '\0' != constants[i].name[0]; ++i)
2151 newCONSTSUB(stash, constants[i].name, newSViv(constants[i].value));
2153 /* export global variables
2154 * by adding "magic" to the SV's representing the globale variables
2155 * perl is able to automagically call the get/set function when
2156 * accessing any such variable (this is basically the same as using
2158 /* global strings */
2159 for (int i = 0; '\0' != g_strings[i].name[0]; ++i) {
2160 tmp = get_sv(g_strings[i].name, 1);
2161 sv_magicext(tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl, g_strings[i].var, 0);
2164 tmp = get_sv("Collectd::interval_g", /* create = */ 1);
2165 sv_magicext(tmp, NULL, /* how = */ PERL_MAGIC_ext,
2166 /* vtbl = */ &g_interval_vtbl,
2167 /* name = */ NULL, /* namelen = */ 0);
2170 } /* static void xs_init (pTHX) */
2172 /* Initialize the global Perl interpreter. */
2173 static int init_pi(int argc, char **argv) {
2176 if (NULL != perl_threads)
2179 log_info("Initializing Perl interpreter...");
2182 for (int i = 0; i < argc; ++i)
2183 log_debug("argv[%i] = \"%s\"", i, argv[i]);
2185 #endif /* COLLECT_DEBUG */
2187 if (0 != pthread_key_create(&perl_thr_key, c_ithread_destructor)) {
2188 log_err("init_pi: pthread_key_create failed");
2190 /* this must not happen - cowardly giving up if it does */
2195 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2196 * triggers a "value computed is not used" warning by gcc. */
2199 PERL_SYS_INIT3(&argc, &argv, &environ);
2201 perl_threads = smalloc(sizeof(*perl_threads));
2202 memset(perl_threads, 0, sizeof(c_ithread_list_t));
2204 pthread_mutexattr_init(&perl_threads->mutexattr);
2205 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2206 pthread_mutex_init(&perl_threads->mutex, &perl_threads->mutexattr);
2207 /* locking the mutex should not be necessary at this point
2208 * but let's just do it for the sake of completeness */
2209 pthread_mutex_lock(&perl_threads->mutex);
2211 perl_threads->head = c_ithread_create(NULL);
2212 perl_threads->tail = perl_threads->head;
2214 if (NULL == (perl_threads->head->interp = perl_alloc())) {
2215 log_err("init_pi: Not enough memory.");
2219 aTHX = perl_threads->head->interp;
2220 pthread_mutex_unlock(&perl_threads->mutex);
2222 perl_construct(aTHX);
2224 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2226 if (0 != perl_parse(aTHX_ xs_init, argc, argv, NULL)) {
2227 SV *err = get_sv("@", 1);
2228 log_err("init_pi: Unable to bootstrap Collectd: %s", SvPV_nolen(err));
2230 perl_destruct(perl_threads->head->interp);
2231 perl_free(perl_threads->head->interp);
2232 sfree(perl_threads);
2234 pthread_key_delete(perl_thr_key);
2238 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2239 sv_setpv(get_sv("0", 0), "collectd");
2243 plugin_register_log("perl", perl_log, /* user_data = */ NULL);
2244 plugin_register_notification("perl", perl_notify,
2245 /* user_data = */ NULL);
2246 plugin_register_init("perl", perl_init);
2248 plugin_register_read("perl", perl_read);
2250 plugin_register_write("perl", perl_write, /* user_data = */ NULL);
2251 plugin_register_flush("perl", perl_flush, /* user_data = */ NULL);
2252 plugin_register_shutdown("perl", perl_shutdown);
2254 } /* static int init_pi (const char **, const int) */
2257 * LoadPlugin "<Plugin>"
2259 static int perl_config_loadplugin(pTHX_ oconfig_item_t *ci) {
2260 char module_name[DATA_MAX_NAME_LEN];
2264 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2265 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2266 log_err("LoadPlugin expects a single string argument.");
2270 value = ci->values[0].value.string;
2272 if (NULL == get_module_name(module_name, sizeof(module_name), value)) {
2273 log_err("Invalid module name %s", value);
2277 if (0 != init_pi(perl_argc, perl_argv))
2280 assert(NULL != perl_threads);
2281 assert(NULL != perl_threads->head);
2283 aTHX = perl_threads->head->interp;
2285 log_debug("perl_config: Loading Perl plugin \"%s\"", value);
2286 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(module_name, strlen(module_name)),
2289 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2294 static int perl_config_basename(pTHX_ oconfig_item_t *ci) {
2297 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2298 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2299 log_err("BaseName expects a single string argument.");
2303 value = ci->values[0].value.string;
2305 log_debug("perl_config: Setting plugin basename to \"%s\"", value);
2306 sstrncpy(base_name, value, sizeof(base_name));
2308 } /* static int perl_config_basename (oconfig_item_it *) */
2311 * EnableDebugger "<Package>"|""
2313 static int perl_config_enabledebugger(pTHX_ oconfig_item_t *ci) {
2316 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2317 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2318 log_err("EnableDebugger expects a single string argument.");
2322 if (NULL != perl_threads) {
2323 log_warn("EnableDebugger has no effects if used after LoadPlugin.");
2327 value = ci->values[0].value.string;
2329 perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2331 if (NULL == perl_argv) {
2332 log_err("perl_config: Not enough memory.");
2336 if ('\0' == value[0]) {
2337 perl_argv[perl_argc - 1] = "-d";
2339 perl_argv[perl_argc - 1] = smalloc(strlen(value) + 4);
2340 sstrncpy(perl_argv[perl_argc - 1], "-d:", 4);
2341 sstrncpy(perl_argv[perl_argc - 1] + 3, value, strlen(value) + 1);
2344 perl_argv[perl_argc] = NULL;
2346 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2349 * IncludeDir "<Dir>"
2351 static int perl_config_includedir(pTHX_ oconfig_item_t *ci) {
2354 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2355 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2356 log_err("IncludeDir expects a single string argument.");
2360 value = ci->values[0].value.string;
2363 perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2365 if (NULL == perl_argv) {
2366 log_err("perl_config: Not enough memory.");
2370 perl_argv[perl_argc - 1] = smalloc(strlen(value) + 3);
2371 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2372 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen(value) + 1);
2374 perl_argv[perl_argc] = NULL;
2376 /* prepend the directory to @INC */
2377 av_unshift(GvAVn(PL_incgv), 1);
2378 av_store(GvAVn(PL_incgv), 0, newSVpv(value, strlen(value)));
2381 } /* static int perl_config_includedir (oconfig_item_it *) */
2386 static int perl_config_plugin(pTHX_ oconfig_item_t *ci) {
2395 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2396 log_err("LoadPlugin expects a single string argument.");
2400 plugin = ci->values[0].value.string;
2403 if (0 != oconfig_item2hv(aTHX_ ci, config)) {
2407 log_err("Unable to convert configuration to a Perl hash value.");
2408 config = (HV *)&PL_sv_undef;
2416 XPUSHs(sv_2mortal(newSVpv(plugin, 0)));
2417 XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
2421 retvals = call_pv("Collectd::_plugin_dispatch_config", G_SCALAR);
2435 } /* static int perl_config_plugin (oconfig_item_it *) */
2437 static int perl_config(oconfig_item_t *ci) {
2442 for (int i = 0; i < ci->children_num; ++i) {
2443 oconfig_item_t *c = ci->children + i;
2444 int current_status = 0;
2446 if (NULL != perl_threads) {
2447 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2451 if (0 == strcasecmp(c->key, "LoadPlugin"))
2452 current_status = perl_config_loadplugin(aTHX_ c);
2453 else if (0 == strcasecmp(c->key, "BaseName"))
2454 current_status = perl_config_basename(aTHX_ c);
2455 else if (0 == strcasecmp(c->key, "EnableDebugger"))
2456 current_status = perl_config_enabledebugger(aTHX_ c);
2457 else if (0 == strcasecmp(c->key, "IncludeDir"))
2458 current_status = perl_config_includedir(aTHX_ c);
2459 else if (0 == strcasecmp(c->key, "Plugin"))
2460 current_status = perl_config_plugin(aTHX_ c);
2462 log_warn("Ignoring unknown config key \"%s\".", c->key);
2466 /* fatal error - it's up to perl_config_* to clean up */
2467 if (0 > current_status) {
2468 log_err("Configuration failed with a fatal error - "
2469 "plugin disabled!");
2470 return current_status;
2473 status += current_status;
2476 } /* static int perl_config (oconfig_item_t *) */
2478 void module_register(void) {
2480 perl_argv = smalloc((perl_argc + 1) * sizeof(*perl_argv));
2482 /* default options for the Perl interpreter */
2484 perl_argv[1] = "-MCollectd";
2485 perl_argv[2] = "-e";
2487 perl_argv[4] = NULL;
2489 plugin_register_complex_config("perl", perl_config);
2491 } /* void module_register (void) */
2493 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */