1 /**
2 * collectd - src/perl.c
3 * Copyright (C) 2007-2009 Sebastian Harl
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
22 *
23 * Authors:
24 * Sebastian Harl <sh at tokkee.org>
25 * Pavel Rochnyak <pavel2000 ngs.ru>
26 **/
28 /*
29 * This plugin embeds a Perl interpreter into collectd and provides an
30 * interface for collectd plugins written in perl.
31 */
33 /* do not automatically get the thread specific Perl interpreter */
34 #define PERL_NO_GET_CONTEXT
36 #define DONT_POISON_SPRINTF_YET 1
37 #include "collectd.h"
39 #undef DONT_POISON_SPRINTF_YET
41 #include <stdbool.h>
43 #include <EXTERN.h>
44 #include <perl.h>
46 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
47 #undef sprintf
48 #pragma GCC poison sprintf
49 #endif
51 #include <XSUB.h>
53 /* Some versions of Perl define their own version of DEBUG... :-/ */
54 #ifdef DEBUG
55 #undef DEBUG
56 #endif /* DEBUG */
58 /* ... while we want the definition found in plugin.h. */
59 #include "common.h"
60 #include "plugin.h"
62 #include "filter_chain.h"
64 #if !defined(USE_ITHREADS)
65 #error "Perl does not support ithreads!"
66 #endif /* !defined(USE_ITHREADS) */
68 /* clear the Perl sub's stack frame
69 * (this should only be used inside an XSUB) */
70 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
72 #define PLUGIN_INIT 0
73 #define PLUGIN_READ 1
74 #define PLUGIN_WRITE 2
75 #define PLUGIN_SHUTDOWN 3
76 #define PLUGIN_LOG 4
77 #define PLUGIN_NOTIF 5
78 #define PLUGIN_FLUSH 6
79 #define PLUGIN_FLUSH_ALL 7 /* For collectd-5.6 only */
81 #define PLUGIN_TYPES 8
83 #define PLUGIN_CONFIG 254
84 #define PLUGIN_DATASET 255
86 #define FC_MATCH 0
87 #define FC_TARGET 1
89 #define FC_TYPES 2
91 #define FC_CB_CREATE 0
92 #define FC_CB_DESTROY 1
93 #define FC_CB_EXEC 2
95 #define FC_CB_TYPES 3
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_read);
106 static XS(Collectd_plugin_register_write);
107 static XS(Collectd_plugin_register_log);
108 static XS(Collectd_plugin_register_notification);
109 static XS(Collectd_plugin_register_flush);
110 static XS(Collectd_plugin_unregister_read);
111 static XS(Collectd_plugin_unregister_write);
112 static XS(Collectd_plugin_unregister_log);
113 static XS(Collectd_plugin_unregister_notification);
114 static XS(Collectd_plugin_unregister_flush);
115 static XS(Collectd_plugin_register_ds);
116 static XS(Collectd_plugin_unregister_ds);
117 static XS(Collectd_plugin_dispatch_values);
118 static XS(Collectd_plugin_get_interval);
119 static XS(Collectd__plugin_write);
120 static XS(Collectd__plugin_flush);
121 static XS(Collectd_plugin_dispatch_notification);
122 static XS(Collectd_plugin_log);
123 static XS(Collectd__fc_register);
124 static XS(Collectd_call_by_name);
126 static int perl_read(user_data_t *ud);
127 static int perl_write(const data_set_t *ds, const value_list_t *vl,
128 user_data_t *user_data);
129 static void perl_log(int level, const char *msg, user_data_t *user_data);
130 static int perl_notify(const notification_t *notif, user_data_t *user_data);
131 static int perl_flush(cdtime_t timeout, const char *identifier,
132 user_data_t *user_data);
134 /*
135 * private data types
136 */
138 typedef struct c_ithread_s {
139 /* the thread's Perl interpreter */
140 PerlInterpreter *interp;
141 _Bool running; /* thread is inside Perl interpreter */
142 _Bool shutdown;
143 pthread_t pthread;
145 /* double linked list of threads */
146 struct c_ithread_s *prev;
147 struct c_ithread_s *next;
148 } c_ithread_t;
150 typedef struct {
151 c_ithread_t *head;
152 c_ithread_t *tail;
154 #if COLLECT_DEBUG
155 /* some usage stats */
156 int number_of_threads;
157 #endif /* COLLECT_DEBUG */
159 pthread_mutex_t mutex;
160 pthread_mutexattr_t mutexattr;
161 } c_ithread_list_t;
163 /* name / user_data for Perl matches / targets */
164 typedef struct {
165 char *name;
166 SV *user_data;
167 } pfc_user_data_t;
169 #define PFC_USER_DATA_FREE(data) \
170 do { \
171 sfree((data)->name); \
172 if (NULL != (data)->user_data) \
173 sv_free((data)->user_data); \
174 sfree(data); \
175 } while (0)
177 /*
178 * Public variable
179 */
180 extern char **environ;
182 /*
183 * private variables
184 */
186 static _Bool register_legacy_flush = 1;
188 /* if perl_threads != NULL perl_threads->head must
189 * point to the "base" thread */
190 static c_ithread_list_t *perl_threads = NULL;
192 /* the key used to store each pthread's ithread */
193 static pthread_key_t perl_thr_key;
195 static int perl_argc = 0;
196 static char **perl_argv = NULL;
198 static char base_name[DATA_MAX_NAME_LEN] = "";
200 static struct {
201 char name[64];
202 XS((*f));
203 } api[] = {
204 {"Collectd::plugin_register_read", Collectd_plugin_register_read},
205 {"Collectd::plugin_register_write", Collectd_plugin_register_write},
206 {"Collectd::plugin_register_log", Collectd_plugin_register_log},
207 {"Collectd::plugin_register_notification",
208 Collectd_plugin_register_notification},
209 {"Collectd::plugin_register_flush", Collectd_plugin_register_flush},
210 {"Collectd::plugin_unregister_read", Collectd_plugin_unregister_read},
211 {"Collectd::plugin_unregister_write", Collectd_plugin_unregister_write},
212 {"Collectd::plugin_unregister_log", Collectd_plugin_unregister_log},
213 {"Collectd::plugin_unregister_notification",
214 Collectd_plugin_unregister_notification},
215 {"Collectd::plugin_unregister_flush", Collectd_plugin_unregister_flush},
216 {"Collectd::plugin_register_data_set", Collectd_plugin_register_ds},
217 {"Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds},
218 {"Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values},
219 {"Collectd::plugin_get_interval", Collectd_plugin_get_interval},
220 {"Collectd::_plugin_write", Collectd__plugin_write},
221 {"Collectd::_plugin_flush", Collectd__plugin_flush},
222 {"Collectd::plugin_dispatch_notification",
223 Collectd_plugin_dispatch_notification},
224 {"Collectd::plugin_log", Collectd_plugin_log},
225 {"Collectd::_fc_register", Collectd__fc_register},
226 {"Collectd::call_by_name", Collectd_call_by_name},
227 {"", NULL}};
229 struct {
230 char name[64];
231 int value;
232 } constants[] = {{"Collectd::TYPE_INIT", PLUGIN_INIT},
233 {"Collectd::TYPE_READ", PLUGIN_READ},
234 {"Collectd::TYPE_WRITE", PLUGIN_WRITE},
235 {"Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN},
236 {"Collectd::TYPE_LOG", PLUGIN_LOG},
237 {"Collectd::TYPE_NOTIF", PLUGIN_NOTIF},
238 {"Collectd::TYPE_FLUSH", PLUGIN_FLUSH},
239 {"Collectd::TYPE_CONFIG", PLUGIN_CONFIG},
240 {"Collectd::TYPE_DATASET", PLUGIN_DATASET},
241 {"Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER},
242 {"Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE},
243 {"Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE},
244 {"Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE},
245 {"Collectd::LOG_ERR", LOG_ERR},
246 {"Collectd::LOG_WARNING", LOG_WARNING},
247 {"Collectd::LOG_NOTICE", LOG_NOTICE},
248 {"Collectd::LOG_INFO", LOG_INFO},
249 {"Collectd::LOG_DEBUG", LOG_DEBUG},
250 {"Collectd::FC_MATCH", FC_MATCH},
251 {"Collectd::FC_TARGET", FC_TARGET},
252 {"Collectd::FC_CB_CREATE", FC_CB_CREATE},
253 {"Collectd::FC_CB_DESTROY", FC_CB_DESTROY},
254 {"Collectd::FC_CB_EXEC", FC_CB_EXEC},
255 {"Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH},
256 {"Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES},
257 {"Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE},
258 {"Collectd::FC_TARGET_STOP", FC_TARGET_STOP},
259 {"Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN},
260 {"Collectd::NOTIF_FAILURE", NOTIF_FAILURE},
261 {"Collectd::NOTIF_WARNING", NOTIF_WARNING},
262 {"Collectd::NOTIF_OKAY", NOTIF_OKAY},
263 {"", 0}};
265 struct {
266 char name[64];
267 char *var;
268 } g_strings[] = {{"Collectd::hostname_g", hostname_g}, {"", NULL}};
270 /*
271 * Helper functions for data type conversion.
272 */
274 /*
275 * data source:
276 * [
277 * {
278 * name => $ds_name,
279 * type => $ds_type,
280 * min => $ds_min,
281 * max => $ds_max
282 * },
283 * ...
284 * ]
285 */
286 static int hv2data_source(pTHX_ HV *hash, data_source_t *ds) {
287 SV **tmp = NULL;
289 if ((NULL == hash) || (NULL == ds))
290 return -1;
292 if (NULL != (tmp = hv_fetch(hash, "name", 4, 0))) {
293 sstrncpy(ds->name, SvPV_nolen(*tmp), sizeof(ds->name));
294 } else {
295 log_err("hv2data_source: No DS name given.");
296 return -1;
297 }
299 if (NULL != (tmp = hv_fetch(hash, "type", 4, 0))) {
300 ds->type = SvIV(*tmp);
302 if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type) &&
303 (DS_TYPE_DERIVE != ds->type) && (DS_TYPE_ABSOLUTE != ds->type)) {
304 log_err("hv2data_source: Invalid DS type.");
305 return -1;
306 }
307 } else {
308 ds->type = DS_TYPE_COUNTER;
309 }
311 if (NULL != (tmp = hv_fetch(hash, "min", 3, 0)))
312 ds->min = SvNV(*tmp);
313 else
314 ds->min = NAN;
316 if (NULL != (tmp = hv_fetch(hash, "max", 3, 0)))
317 ds->max = SvNV(*tmp);
318 else
319 ds->max = NAN;
320 return 0;
321 } /* static int hv2data_source (HV *, data_source_t *) */
323 /* av2value converts at most "len" elements from "array" to "value". Returns the
324 * number of elements converted or zero on error. */
325 static size_t av2value(pTHX_ char *name, AV *array, value_t *value,
326 size_t array_len) {
327 const data_set_t *ds;
329 if ((NULL == name) || (NULL == array) || (NULL == value) || (array_len == 0))
330 return 0;
332 ds = plugin_get_ds(name);
333 if (NULL == ds) {
334 log_err("av2value: Unknown dataset \"%s\"", name);
335 return 0;
336 }
338 if (array_len < ds->ds_num) {
339 log_warn("av2value: array does not contain enough elements for type "
340 "\"%s\": got %zu, want %zu",
341 name, array_len, ds->ds_num);
342 return 0;
343 } else if (array_len > ds->ds_num) {
344 log_warn("av2value: array contains excess elements for type \"%s\": got "
345 "%zu, want %zu",
346 name, array_len, ds->ds_num);
347 }
349 for (size_t i = 0; i < ds->ds_num; ++i) {
350 SV **tmp = av_fetch(array, i, 0);
352 if (NULL != tmp) {
353 if (DS_TYPE_COUNTER == ds->ds[i].type)
354 value[i].counter = SvIV(*tmp);
355 else if (DS_TYPE_GAUGE == ds->ds[i].type)
356 value[i].gauge = SvNV(*tmp);
357 else if (DS_TYPE_DERIVE == ds->ds[i].type)
358 value[i].derive = SvIV(*tmp);
359 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
360 value[i].absolute = SvIV(*tmp);
361 } else {
362 return 0;
363 }
364 }
366 return ds->ds_num;
367 } /* static size_t av2value (char *, AV *, value_t *, size_t) */
369 /*
370 * value list:
371 * {
372 * values => [ @values ],
373 * time => $time,
374 * host => $host,
375 * plugin => $plugin,
376 * plugin_instance => $pinstance,
377 * type_instance => $tinstance,
378 * }
379 */
380 static int hv2value_list(pTHX_ HV *hash, value_list_t *vl) {
381 SV **tmp;
383 if ((NULL == hash) || (NULL == vl))
384 return -1;
386 if (NULL == (tmp = hv_fetch(hash, "type", 4, 0))) {
387 log_err("hv2value_list: No type given.");
388 return -1;
389 }
391 sstrncpy(vl->type, SvPV_nolen(*tmp), sizeof(vl->type));
393 if ((NULL == (tmp = hv_fetch(hash, "values", 6, 0))) ||
394 (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp)))))) {
395 log_err("hv2value_list: No valid values given.");
396 return -1;
397 }
399 {
400 AV *array = (AV *)SvRV(*tmp);
401 /* av_len returns the highest index, not the actual length. */
402 size_t array_len = (size_t)(av_len(array) + 1);
403 if (array_len == 0)
404 return -1;
406 vl->values = calloc(array_len, sizeof(*vl->values));
407 vl->values_len =
408 av2value(aTHX_ vl->type, (AV *)SvRV(*tmp), vl->values, array_len);
409 if (vl->values_len == 0) {
410 sfree(vl->values);
411 return -1;
412 }
413 }
415 if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
416 double t = SvNV(*tmp);
417 vl->time = DOUBLE_TO_CDTIME_T(t);
418 }
420 if (NULL != (tmp = hv_fetch(hash, "interval", 8, 0))) {
421 double t = SvNV(*tmp);
422 vl->interval = DOUBLE_TO_CDTIME_T(t);
423 }
425 if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
426 sstrncpy(vl->host, SvPV_nolen(*tmp), sizeof(vl->host));
428 if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
429 sstrncpy(vl->plugin, SvPV_nolen(*tmp), sizeof(vl->plugin));
431 if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
432 sstrncpy(vl->plugin_instance, SvPV_nolen(*tmp),
433 sizeof(vl->plugin_instance));
435 if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
436 sstrncpy(vl->type_instance, SvPV_nolen(*tmp), sizeof(vl->type_instance));
437 return 0;
438 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
440 static int av2data_set(pTHX_ AV *array, char *name, data_set_t *ds) {
441 int len;
443 if ((NULL == array) || (NULL == name) || (NULL == ds))
444 return -1;
446 len = av_len(array);
448 if (-1 == len) {
449 log_err("av2data_set: Invalid data set.");
450 return -1;
451 }
453 ds->ds = smalloc((len + 1) * sizeof(*ds->ds));
454 ds->ds_num = len + 1;
456 for (int i = 0; i <= len; ++i) {
457 SV **elem = av_fetch(array, i, 0);
459 if (NULL == elem) {
460 log_err("av2data_set: Failed to fetch data source %i.", i);
461 return -1;
462 }
464 if (!(SvROK(*elem) && (SVt_PVHV == SvTYPE(SvRV(*elem))))) {
465 log_err("av2data_set: Invalid data source.");
466 return -1;
467 }
469 if (-1 == hv2data_source(aTHX_(HV *) SvRV(*elem), &ds->ds[i]))
470 return -1;
472 log_debug("av2data_set: "
473 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
474 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
475 }
477 sstrncpy(ds->type, name, sizeof(ds->type));
478 return 0;
479 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
481 /*
482 * notification:
483 * {
484 * severity => $severity,
485 * time => $time,
486 * message => $msg,
487 * host => $host,
488 * plugin => $plugin,
489 * type => $type,
490 * plugin_instance => $instance,
491 * type_instance => $type_instance,
492 * meta => [ { name => <name>, value => <value> }, ... ]
493 * }
494 */
495 static int av2notification_meta(pTHX_ AV *array,
496 notification_meta_t **ret_meta) {
497 notification_meta_t *tail = NULL;
499 int len = av_len(array);
501 for (int i = 0; i <= len; ++i) {
502 SV **tmp = av_fetch(array, i, 0);
504 if (tmp == NULL)
505 return -1;
507 if (!(SvROK(*tmp) && (SVt_PVHV == SvTYPE(SvRV(*tmp))))) {
508 log_warn("av2notification_meta: Skipping invalid "
509 "meta information.");
510 continue;
511 }
513 HV *hash = (HV *)SvRV(*tmp);
515 notification_meta_t *m = calloc(1, sizeof(*m));
516 if (m == NULL)
517 return ENOMEM;
519 SV **name = hv_fetch(hash, "name", strlen("name"), 0);
520 if (name == NULL) {
521 log_warn("av2notification_meta: Skipping invalid "
522 "meta information.");
523 sfree(m);
524 continue;
525 }
526 sstrncpy(m->name, SvPV_nolen(*name), sizeof(m->name));
528 SV **value = hv_fetch(hash, "value", strlen("value"), 0);
529 if (value == NULL) {
530 log_warn("av2notification_meta: Skipping invalid "
531 "meta information.");
532 sfree(m);
533 continue;
534 }
536 if (SvNOK(*value)) {
537 m->nm_value.nm_double = SvNVX(*value);
538 m->type = NM_TYPE_DOUBLE;
539 } else if (SvUOK(*value)) {
540 m->nm_value.nm_unsigned_int = SvUVX(*value);
541 m->type = NM_TYPE_UNSIGNED_INT;
542 } else if (SvIOK(*value)) {
543 m->nm_value.nm_signed_int = SvIVX(*value);
544 m->type = NM_TYPE_SIGNED_INT;
545 } else {
546 m->nm_value.nm_string = sstrdup(SvPV_nolen(*value));
547 m->type = NM_TYPE_STRING;
548 }
550 m->next = NULL;
551 if (tail == NULL)
552 *ret_meta = m;
553 else
554 tail->next = m;
555 tail = m;
556 }
558 return 0;
559 } /* static int av2notification_meta (AV *, notification_meta_t *) */
561 static int hv2notification(pTHX_ HV *hash, notification_t *n) {
562 SV **tmp = NULL;
564 if ((NULL == hash) || (NULL == n))
565 return -1;
567 if (NULL != (tmp = hv_fetch(hash, "severity", 8, 0)))
568 n->severity = SvIV(*tmp);
569 else
570 n->severity = NOTIF_FAILURE;
572 if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
573 double t = SvNV(*tmp);
574 n->time = DOUBLE_TO_CDTIME_T(t);
575 } else
576 n->time = cdtime();
578 if (NULL != (tmp = hv_fetch(hash, "message", 7, 0)))
579 sstrncpy(n->message, SvPV_nolen(*tmp), sizeof(n->message));
581 if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
582 sstrncpy(n->host, SvPV_nolen(*tmp), sizeof(n->host));
583 else
584 sstrncpy(n->host, hostname_g, sizeof(n->host));
586 if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
587 sstrncpy(n->plugin, SvPV_nolen(*tmp), sizeof(n->plugin));
589 if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
590 sstrncpy(n->plugin_instance, SvPV_nolen(*tmp), sizeof(n->plugin_instance));
592 if (NULL != (tmp = hv_fetch(hash, "type", 4, 0)))
593 sstrncpy(n->type, SvPV_nolen(*tmp), sizeof(n->type));
595 if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
596 sstrncpy(n->type_instance, SvPV_nolen(*tmp), sizeof(n->type_instance));
598 n->meta = NULL;
599 while (NULL != (tmp = hv_fetch(hash, "meta", 4, 0))) {
600 if (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp))))) {
601 log_warn("hv2notification: Ignoring invalid meta information.");
602 break;
603 }
605 if (0 != av2notification_meta(aTHX_(AV *) SvRV(*tmp), &n->meta)) {
606 plugin_notification_meta_free(n->meta);
607 n->meta = NULL;
608 return -1;
609 }
610 break;
611 }
612 return 0;
613 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
615 static int data_set2av(pTHX_ data_set_t *ds, AV *array) {
616 if ((NULL == ds) || (NULL == array))
617 return -1;
619 av_extend(array, ds->ds_num);
621 for (size_t i = 0; i < ds->ds_num; ++i) {
622 HV *source = newHV();
624 if (NULL == hv_store(source, "name", 4, newSVpv(ds->ds[i].name, 0), 0))
625 return -1;
627 if (NULL == hv_store(source, "type", 4, newSViv(ds->ds[i].type), 0))
628 return -1;
630 if (!isnan(ds->ds[i].min))
631 if (NULL == hv_store(source, "min", 3, newSVnv(ds->ds[i].min), 0))
632 return -1;
634 if (!isnan(ds->ds[i].max))
635 if (NULL == hv_store(source, "max", 3, newSVnv(ds->ds[i].max), 0))
636 return -1;
638 if (NULL == av_store(array, i, newRV_noinc((SV *)source)))
639 return -1;
640 }
641 return 0;
642 } /* static int data_set2av (data_set_t *, AV *) */
644 static int value_list2hv(pTHX_ value_list_t *vl, data_set_t *ds, HV *hash) {
645 AV *values = NULL;
646 size_t i;
648 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
649 return -1;
651 values = newAV();
652 /* av_extend takes the last *index* to which the array should be extended. */
653 av_extend(values, vl->values_len - 1);
655 assert(ds->ds_num == vl->values_len);
656 for (i = 0; i < vl->values_len; ++i) {
657 SV *val = NULL;
659 if (DS_TYPE_COUNTER == ds->ds[i].type)
660 val = newSViv(vl->values[i].counter);
661 else if (DS_TYPE_GAUGE == ds->ds[i].type)
662 val = newSVnv(vl->values[i].gauge);
663 else if (DS_TYPE_DERIVE == ds->ds[i].type)
664 val = newSViv(vl->values[i].derive);
665 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
666 val = newSViv(vl->values[i].absolute);
668 if (NULL == av_store(values, i, val)) {
669 av_undef(values);
670 return -1;
671 }
672 }
674 if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0))
675 return -1;
677 if (0 != vl->time) {
678 double t = CDTIME_T_TO_DOUBLE(vl->time);
679 if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
680 return -1;
681 }
683 {
684 double t = CDTIME_T_TO_DOUBLE(vl->interval);
685 if (NULL == hv_store(hash, "interval", 8, newSVnv(t), 0))
686 return -1;
687 }
689 if ('\0' != vl->host[0])
690 if (NULL == hv_store(hash, "host", 4, newSVpv(vl->host, 0), 0))
691 return -1;
693 if ('\0' != vl->plugin[0])
694 if (NULL == hv_store(hash, "plugin", 6, newSVpv(vl->plugin, 0), 0))
695 return -1;
697 if ('\0' != vl->plugin_instance[0])
698 if (NULL == hv_store(hash, "plugin_instance", 15,
699 newSVpv(vl->plugin_instance, 0), 0))
700 return -1;
702 if ('\0' != vl->type[0])
703 if (NULL == hv_store(hash, "type", 4, newSVpv(vl->type, 0), 0))
704 return -1;
706 if ('\0' != vl->type_instance[0])
707 if (NULL ==
708 hv_store(hash, "type_instance", 13, newSVpv(vl->type_instance, 0), 0))
709 return -1;
710 return 0;
711 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
713 static int notification_meta2av(pTHX_ notification_meta_t *meta, AV *array) {
714 int meta_num = 0;
716 while (meta) {
717 ++meta_num;
718 meta = meta->next;
719 }
721 av_extend(array, meta_num);
723 for (int i = 0; NULL != meta; meta = meta->next, ++i) {
724 HV *m = newHV();
725 SV *value;
727 if (NULL == hv_store(m, "name", 4, newSVpv(meta->name, 0), 0))
728 return -1;
730 if (NM_TYPE_STRING == meta->type)
731 value = newSVpv(meta->nm_value.nm_string, 0);
732 else if (NM_TYPE_SIGNED_INT == meta->type)
733 value = newSViv(meta->nm_value.nm_signed_int);
734 else if (NM_TYPE_UNSIGNED_INT == meta->type)
735 value = newSVuv(meta->nm_value.nm_unsigned_int);
736 else if (NM_TYPE_DOUBLE == meta->type)
737 value = newSVnv(meta->nm_value.nm_double);
738 else if (NM_TYPE_BOOLEAN == meta->type)
739 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
740 else
741 return -1;
743 if (NULL == hv_store(m, "value", 5, value, 0)) {
744 sv_free(value);
745 return -1;
746 }
748 if (NULL == av_store(array, i, newRV_noinc((SV *)m))) {
749 hv_clear(m);
750 hv_undef(m);
751 return -1;
752 }
753 }
754 return 0;
755 } /* static int notification_meta2av (notification_meta_t *, AV *) */
757 static int notification2hv(pTHX_ notification_t *n, HV *hash) {
758 if (NULL == hv_store(hash, "severity", 8, newSViv(n->severity), 0))
759 return -1;
761 if (0 != n->time) {
762 double t = CDTIME_T_TO_DOUBLE(n->time);
763 if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
764 return -1;
765 }
767 if ('\0' != *n->message)
768 if (NULL == hv_store(hash, "message", 7, newSVpv(n->message, 0), 0))
769 return -1;
771 if ('\0' != *n->host)
772 if (NULL == hv_store(hash, "host", 4, newSVpv(n->host, 0), 0))
773 return -1;
775 if ('\0' != *n->plugin)
776 if (NULL == hv_store(hash, "plugin", 6, newSVpv(n->plugin, 0), 0))
777 return -1;
779 if ('\0' != *n->plugin_instance)
780 if (NULL == hv_store(hash, "plugin_instance", 15,
781 newSVpv(n->plugin_instance, 0), 0))
782 return -1;
784 if ('\0' != *n->type)
785 if (NULL == hv_store(hash, "type", 4, newSVpv(n->type, 0), 0))
786 return -1;
788 if ('\0' != *n->type_instance)
789 if (NULL ==
790 hv_store(hash, "type_instance", 13, newSVpv(n->type_instance, 0), 0))
791 return -1;
793 if (NULL != n->meta) {
794 AV *meta = newAV();
795 if ((0 != notification_meta2av(aTHX_ n->meta, meta)) ||
796 (NULL == hv_store(hash, "meta", 4, newRV_noinc((SV *)meta), 0))) {
797 av_clear(meta);
798 av_undef(meta);
799 return -1;
800 }
801 }
802 return 0;
803 } /* static int notification2hv (notification_t *, HV *) */
805 static int oconfig_item2hv(pTHX_ oconfig_item_t *ci, HV *hash) {
806 AV *values;
807 AV *children;
809 if (NULL == hv_store(hash, "key", 3, newSVpv(ci->key, 0), 0))
810 return -1;
812 values = newAV();
813 if (0 < ci->values_num)
814 av_extend(values, ci->values_num);
816 if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0)) {
817 av_clear(values);
818 av_undef(values);
819 return -1;
820 }
822 for (int i = 0; i < ci->values_num; ++i) {
823 SV *value;
825 switch (ci->values[i].type) {
826 case OCONFIG_TYPE_STRING:
827 value = newSVpv(ci->values[i].value.string, 0);
828 break;
829 case OCONFIG_TYPE_NUMBER:
830 value = newSVnv((NV)ci->values[i].value.number);
831 break;
832 case OCONFIG_TYPE_BOOLEAN:
833 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
834 break;
835 default:
836 log_err("oconfig_item2hv: Invalid value type %i.", ci->values[i].type);
837 value = &PL_sv_undef;
838 }
840 if (NULL == av_store(values, i, value)) {
841 sv_free(value);
842 return -1;
843 }
844 }
846 /* ignoring 'parent' member which is uninteresting in this case */
848 children = newAV();
849 if (0 < ci->children_num)
850 av_extend(children, ci->children_num);
852 if (NULL == hv_store(hash, "children", 8, newRV_noinc((SV *)children), 0)) {
853 av_clear(children);
854 av_undef(children);
855 return -1;
856 }
858 for (int i = 0; i < ci->children_num; ++i) {
859 HV *child = newHV();
861 if (0 != oconfig_item2hv(aTHX_ ci->children + i, child)) {
862 hv_clear(child);
863 hv_undef(child);
864 return -1;
865 }
867 if (NULL == av_store(children, i, newRV_noinc((SV *)child))) {
868 hv_clear(child);
869 hv_undef(child);
870 return -1;
871 }
872 }
873 return 0;
874 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
876 /*
877 * Internal functions.
878 */
880 static char *get_module_name(char *buf, size_t buf_len, const char *module) {
881 int status = 0;
882 if (base_name[0] == '\0')
883 status = snprintf(buf, buf_len, "%s", module);
884 else
885 status = snprintf(buf, buf_len, "%s::%s", base_name, module);
886 if ((status < 0) || ((unsigned int)status >= buf_len))
887 return NULL;
888 return buf;
889 } /* char *get_module_name */
891 /*
892 * Add a plugin's data set definition.
893 */
894 static int pplugin_register_data_set(pTHX_ char *name, AV *dataset) {
895 int ret = 0;
897 data_set_t ds;
899 if ((NULL == name) || (NULL == dataset))
900 return -1;
902 if (0 != av2data_set(aTHX_ dataset, name, &ds))
903 return -1;
905 ret = plugin_register_data_set(&ds);
907 free(ds.ds);
908 return ret;
909 } /* static int pplugin_register_data_set (char *, SV *) */
911 /*
912 * Remove a plugin's data set definition.
913 */
914 static int pplugin_unregister_data_set(char *name) {
915 if (NULL == name)
916 return 0;
917 return plugin_unregister_data_set(name);
918 } /* static int pplugin_unregister_data_set (char *) */
920 /*
921 * Submit the values to the write functions.
922 */
923 static int pplugin_dispatch_values(pTHX_ HV *values) {
924 value_list_t vl = VALUE_LIST_INIT;
926 int ret = 0;
928 if (NULL == values)
929 return -1;
931 if (0 != hv2value_list(aTHX_ values, &vl))
932 return -1;
934 ret = plugin_dispatch_values(&vl);
936 sfree(vl.values);
937 return ret;
938 } /* static int pplugin_dispatch_values (char *, HV *) */
940 /*
941 * Submit the values to a single write function.
942 */
943 static int pplugin_write(pTHX_ const char *plugin, AV *data_set, HV *values) {
944 data_set_t ds;
945 value_list_t vl = VALUE_LIST_INIT;
947 int ret;
949 if (NULL == values)
950 return -1;
952 if (0 != hv2value_list(aTHX_ values, &vl))
953 return -1;
955 if ((NULL != data_set) && (0 != av2data_set(aTHX_ data_set, vl.type, &ds)))
956 return -1;
958 ret = plugin_write(plugin, NULL == data_set ? NULL : &ds, &vl);
959 if (0 != ret)
960 log_warn("Dispatching value to plugin \"%s\" failed with status %i.",
961 NULL == plugin ? "<any>" : plugin, ret);
963 if (NULL != data_set)
964 sfree(ds.ds);
965 sfree(vl.values);
966 return ret;
967 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
969 /*
970 * Dispatch a notification.
971 */
972 static int pplugin_dispatch_notification(pTHX_ HV *notif) {
973 notification_t n = {0};
975 int ret;
977 if (NULL == notif)
978 return -1;
980 if (0 != hv2notification(aTHX_ notif, &n))
981 return -1;
983 ret = plugin_dispatch_notification(&n);
984 plugin_notification_meta_free(n.meta);
985 return ret;
986 } /* static int pplugin_dispatch_notification (HV *) */
988 /*
989 * Call perl sub with thread locking flags handled.
990 */
991 static int call_pv_locked(pTHX_ const char *sub_name) {
992 _Bool old_running;
993 int ret;
995 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
996 if (t == NULL) /* thread destroyed */
997 return 0;
999 old_running = t->running;
1000 t->running = 1;
1002 if (t->shutdown) {
1003 t->running = old_running;
1004 return 0;
1005 }
1007 ret = call_pv(sub_name, G_SCALAR | G_EVAL);
1009 t->running = old_running;
1010 return ret;
1011 } /* static int call_pv_locked (pTHX, *sub_name) */
1013 /*
1014 * Call all working functions of the given type.
1015 */
1016 static int pplugin_call(pTHX_ int type, ...) {
1017 int retvals = 0;
1019 va_list ap;
1020 int ret = 0;
1021 char *subname;
1023 dSP;
1025 if ((type < 0) || (type >= PLUGIN_TYPES))
1026 return -1;
1028 va_start(ap, type);
1030 ENTER;
1031 SAVETMPS;
1033 PUSHMARK(SP);
1035 if (PLUGIN_READ == type) {
1036 subname = va_arg(ap, char *);
1037 } else if (PLUGIN_WRITE == type) {
1038 data_set_t *ds;
1039 value_list_t *vl;
1041 AV *pds = newAV();
1042 HV *pvl = newHV();
1044 subname = va_arg(ap, char *);
1045 /*
1046 * $_[0] = $plugin_type;
1047 *
1048 * $_[1] =
1049 * [
1050 * {
1051 * name => $ds_name,
1052 * type => $ds_type,
1053 * min => $ds_min,
1054 * max => $ds_max
1055 * },
1056 * ...
1057 * ];
1058 *
1059 * $_[2] =
1060 * {
1061 * values => [ $v1, ... ],
1062 * time => $time,
1063 * host => $hostname,
1064 * plugin => $plugin,
1065 * type => $type,
1066 * plugin_instance => $instance,
1067 * type_instance => $type_instance
1068 * };
1069 */
1070 ds = va_arg(ap, data_set_t *);
1071 vl = va_arg(ap, value_list_t *);
1073 if (-1 == data_set2av(aTHX_ ds, pds)) {
1074 av_clear(pds);
1075 av_undef(pds);
1076 pds = (AV *)&PL_sv_undef;
1077 ret = -1;
1078 }
1080 if (-1 == value_list2hv(aTHX_ vl, ds, pvl)) {
1081 hv_clear(pvl);
1082 hv_undef(pvl);
1083 pvl = (HV *)&PL_sv_undef;
1084 ret = -1;
1085 }
1087 XPUSHs(sv_2mortal(newSVpv(ds->type, 0)));
1088 XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1089 XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1090 } else if (PLUGIN_LOG == type) {
1091 subname = va_arg(ap, char *);
1092 /*
1093 * $_[0] = $level;
1094 *
1095 * $_[1] = $message;
1096 */
1097 XPUSHs(sv_2mortal(newSViv(va_arg(ap, int))));
1098 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1099 } else if (PLUGIN_NOTIF == type) {
1100 notification_t *n;
1101 HV *notif = newHV();
1103 subname = va_arg(ap, char *);
1104 /*
1105 * $_[0] =
1106 * {
1107 * severity => $severity,
1108 * time => $time,
1109 * message => $msg,
1110 * host => $host,
1111 * plugin => $plugin,
1112 * type => $type,
1113 * plugin_instance => $instance,
1114 * type_instance => $type_instance
1115 * };
1116 */
1117 n = va_arg(ap, notification_t *);
1119 if (-1 == notification2hv(aTHX_ n, notif)) {
1120 hv_clear(notif);
1121 hv_undef(notif);
1122 notif = (HV *)&PL_sv_undef;
1123 ret = -1;
1124 }
1126 XPUSHs(sv_2mortal(newRV_noinc((SV *)notif)));
1127 } else if (PLUGIN_FLUSH == type) {
1128 cdtime_t timeout;
1129 subname = va_arg(ap, char *);
1130 /*
1131 * $_[0] = $timeout;
1132 * $_[1] = $identifier;
1133 */
1134 timeout = va_arg(ap, cdtime_t);
1136 XPUSHs(sv_2mortal(newSVnv(CDTIME_T_TO_DOUBLE(timeout))));
1137 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1138 } else if (PLUGIN_FLUSH_ALL == type) {
1139 cdtime_t timeout;
1140 subname = "Collectd::plugin_call_all";
1141 /*
1142 * $_[0] = $timeout;
1143 * $_[1] = $identifier;
1144 */
1145 timeout = va_arg(ap, cdtime_t);
1147 XPUSHs(sv_2mortal(newSViv((IV)PLUGIN_FLUSH)));
1148 XPUSHs(sv_2mortal(newSVnv(CDTIME_T_TO_DOUBLE(timeout))));
1149 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1150 } else if (PLUGIN_INIT == type) {
1151 subname = "Collectd::plugin_call_all";
1152 XPUSHs(sv_2mortal(newSViv((IV)type)));
1153 } else if (PLUGIN_SHUTDOWN == type) {
1154 subname = "Collectd::plugin_call_all";
1155 XPUSHs(sv_2mortal(newSViv((IV)type)));
1156 } else { /* Unknown type. Run 'plugin_call_all' and make compiler happy */
1157 subname = "Collectd::plugin_call_all";
1158 XPUSHs(sv_2mortal(newSViv((IV)type)));
1159 }
1161 PUTBACK;
1163 retvals = call_pv_locked(aTHX_ subname);
1165 SPAGAIN;
1166 if (SvTRUE(ERRSV)) {
1167 if (PLUGIN_LOG != type)
1168 ERROR("perl: %s error: %s", subname, SvPV_nolen(ERRSV));
1169 ret = -1;
1170 } else if (0 < retvals) {
1171 SV *tmp = POPs;
1172 if (!SvTRUE(tmp))
1173 ret = -1;
1174 }
1176 PUTBACK;
1177 FREETMPS;
1178 LEAVE;
1180 va_end(ap);
1181 return ret;
1182 } /* static int pplugin_call (int, ...) */
1184 /*
1185 * collectd's Perl interpreter based thread implementation.
1186 *
1187 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1188 */
1190 /* must be called with perl_threads->mutex locked */
1191 static void c_ithread_destroy(c_ithread_t *ithread) {
1192 dTHXa(ithread->interp);
1194 assert(NULL != perl_threads);
1196 PERL_SET_CONTEXT(aTHX);
1197 /* Mark as running to avoid deadlock:
1198 c_ithread_destroy -> log_debug -> perl_log()
1199 */
1200 ithread->running = 1;
1201 log_debug("Shutting down Perl interpreter %p...", aTHX);
1203 #if COLLECT_DEBUG
1204 sv_report_used();
1206 --perl_threads->number_of_threads;
1207 #endif /* COLLECT_DEBUG */
1209 perl_destruct(aTHX);
1210 perl_free(aTHX);
1212 if (NULL == ithread->prev)
1213 perl_threads->head = ithread->next;
1214 else
1215 ithread->prev->next = ithread->next;
1217 if (NULL == ithread->next)
1218 perl_threads->tail = ithread->prev;
1219 else
1220 ithread->next->prev = ithread->prev;
1222 sfree(ithread);
1223 return;
1224 } /* static void c_ithread_destroy (c_ithread_t *) */
1226 static void c_ithread_destructor(void *arg) {
1227 c_ithread_t *ithread = (c_ithread_t *)arg;
1228 c_ithread_t *t = NULL;
1230 if (NULL == perl_threads)
1231 return;
1233 pthread_mutex_lock(&perl_threads->mutex);
1235 for (t = perl_threads->head; NULL != t; t = t->next)
1236 if (t == ithread)
1237 break;
1239 /* the ithread no longer exists */
1240 if (NULL == t) {
1241 pthread_mutex_unlock(&perl_threads->mutex);
1242 return;
1243 }
1245 c_ithread_destroy(ithread);
1247 pthread_mutex_unlock(&perl_threads->mutex);
1248 return;
1249 } /* static void c_ithread_destructor (void *) */
1251 /* must be called with perl_threads->mutex locked */
1252 static c_ithread_t *c_ithread_create(PerlInterpreter *base) {
1253 c_ithread_t *t = NULL;
1254 dTHXa(NULL);
1256 assert(NULL != perl_threads);
1258 t = smalloc(sizeof(*t));
1259 memset(t, 0, sizeof(c_ithread_t));
1261 t->interp = (NULL == base) ? NULL : perl_clone(base, CLONEf_KEEP_PTR_TABLE);
1263 aTHX = t->interp;
1265 if ((NULL != base) && (NULL != PL_endav)) {
1266 av_clear(PL_endav);
1267 av_undef(PL_endav);
1268 PL_endav = Nullav;
1269 }
1271 #if COLLECT_DEBUG
1272 ++perl_threads->number_of_threads;
1273 #endif /* COLLECT_DEBUG */
1275 t->next = NULL;
1277 if (NULL == perl_threads->tail) {
1278 perl_threads->head = t;
1279 t->prev = NULL;
1280 } else {
1281 perl_threads->tail->next = t;
1282 t->prev = perl_threads->tail;
1283 }
1285 t->pthread = pthread_self();
1286 t->running = 0;
1287 t->shutdown = 0;
1288 perl_threads->tail = t;
1290 pthread_setspecific(perl_thr_key, (const void *)t);
1291 return t;
1292 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1294 /*
1295 * Filter chains implementation.
1296 */
1298 static int fc_call(pTHX_ int type, int cb_type, pfc_user_data_t *data, ...) {
1299 int retvals = 0;
1301 va_list ap;
1302 int ret = 0;
1304 notification_meta_t **meta = NULL;
1305 AV *pmeta = NULL;
1307 dSP;
1309 if ((type < 0) || (type >= FC_TYPES))
1310 return -1;
1312 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1313 return -1;
1315 va_start(ap, data);
1317 ENTER;
1318 SAVETMPS;
1320 PUSHMARK(SP);
1322 XPUSHs(sv_2mortal(newSViv((IV)type)));
1323 XPUSHs(sv_2mortal(newSVpv(data->name, 0)));
1324 XPUSHs(sv_2mortal(newSViv((IV)cb_type)));
1326 if (FC_CB_CREATE == cb_type) {
1327 /*
1328 * $_[0] = $ci;
1329 * $_[1] = $user_data;
1330 */
1331 oconfig_item_t *ci;
1332 HV *config = newHV();
1334 ci = va_arg(ap, oconfig_item_t *);
1336 if (0 != oconfig_item2hv(aTHX_ ci, config)) {
1337 hv_clear(config);
1338 hv_undef(config);
1339 config = (HV *)&PL_sv_undef;
1340 ret = -1;
1341 }
1343 XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
1344 } else if (FC_CB_DESTROY == cb_type) {
1345 /*
1346 * $_[1] = $user_data;
1347 */
1349 /* nothing to be done - the user data pointer
1350 * is pushed onto the stack later */
1351 } else if (FC_CB_EXEC == cb_type) {
1352 /*
1353 * $_[0] = $ds;
1354 * $_[1] = $vl;
1355 * $_[2] = $meta;
1356 * $_[3] = $user_data;
1357 */
1358 data_set_t *ds;
1359 value_list_t *vl;
1361 AV *pds = newAV();
1362 HV *pvl = newHV();
1364 ds = va_arg(ap, data_set_t *);
1365 vl = va_arg(ap, value_list_t *);
1366 meta = va_arg(ap, notification_meta_t **);
1368 if (0 != data_set2av(aTHX_ ds, pds)) {
1369 av_clear(pds);
1370 av_undef(pds);
1371 pds = (AV *)&PL_sv_undef;
1372 ret = -1;
1373 }
1375 if (0 != value_list2hv(aTHX_ vl, ds, pvl)) {
1376 hv_clear(pvl);
1377 hv_undef(pvl);
1378 pvl = (HV *)&PL_sv_undef;
1379 ret = -1;
1380 }
1382 if (NULL != meta) {
1383 pmeta = newAV();
1385 if (0 != notification_meta2av(aTHX_ * meta, pmeta)) {
1386 av_clear(pmeta);
1387 av_undef(pmeta);
1388 pmeta = (AV *)&PL_sv_undef;
1389 ret = -1;
1390 }
1391 } else {
1392 pmeta = (AV *)&PL_sv_undef;
1393 }
1395 XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1396 XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1397 XPUSHs(sv_2mortal(newRV_noinc((SV *)pmeta)));
1398 }
1400 XPUSHs(sv_2mortal(newRV_inc(data->user_data)));
1402 PUTBACK;
1404 retvals = call_pv_locked(aTHX_ "Collectd::fc_call");
1406 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1407 assert(pmeta != NULL);
1409 plugin_notification_meta_free(*meta);
1410 av2notification_meta(aTHX_ pmeta, meta);
1411 }
1413 SPAGAIN;
1414 if (SvTRUE(ERRSV)) {
1415 ERROR("perl: Collectd::fc_call error: %s", SvPV_nolen(ERRSV));
1416 ret = -1;
1417 } else if (0 < retvals) {
1418 SV *tmp = POPs;
1420 /* the exec callbacks return a status, while
1421 * the others return a boolean value */
1422 if (FC_CB_EXEC == cb_type)
1423 ret = SvIV(tmp);
1424 else if (!SvTRUE(tmp))
1425 ret = -1;
1426 }
1428 PUTBACK;
1429 FREETMPS;
1430 LEAVE;
1432 va_end(ap);
1433 return ret;
1434 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1436 static int fc_create(int type, const oconfig_item_t *ci, void **user_data) {
1437 pfc_user_data_t *data;
1439 int ret = 0;
1441 dTHX;
1443 if (NULL == perl_threads)
1444 return 0;
1446 if (NULL == aTHX) {
1447 c_ithread_t *t = NULL;
1449 pthread_mutex_lock(&perl_threads->mutex);
1450 t = c_ithread_create(perl_threads->head->interp);
1451 pthread_mutex_unlock(&perl_threads->mutex);
1453 aTHX = t->interp;
1454 }
1456 log_debug("fc_create: c_ithread: interp = %p (active threads: %i)", aTHX,
1457 perl_threads->number_of_threads);
1459 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1460 log_warn("A \"%s\" block expects a single string argument.",
1461 (FC_MATCH == type) ? "Match" : "Target");
1462 return -1;
1463 }
1465 data = smalloc(sizeof(*data));
1466 data->name = sstrdup(ci->values[0].value.string);
1467 data->user_data = newSV(0);
1469 ret = fc_call(aTHX_ type, FC_CB_CREATE, data, ci);
1471 if (0 != ret)
1472 PFC_USER_DATA_FREE(data);
1473 else
1474 *user_data = data;
1475 return ret;
1476 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1478 static int fc_destroy(int type, void **user_data) {
1479 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1481 int ret = 0;
1483 dTHX;
1485 if ((NULL == perl_threads) || (NULL == data))
1486 return 0;
1488 if (NULL == aTHX) {
1489 c_ithread_t *t = NULL;
1491 pthread_mutex_lock(&perl_threads->mutex);
1492 t = c_ithread_create(perl_threads->head->interp);
1493 pthread_mutex_unlock(&perl_threads->mutex);
1495 aTHX = t->interp;
1496 }
1498 log_debug("fc_destroy: c_ithread: interp = %p (active threads: %i)", aTHX,
1499 perl_threads->number_of_threads);
1501 ret = fc_call(aTHX_ type, FC_CB_DESTROY, data);
1503 PFC_USER_DATA_FREE(data);
1504 *user_data = NULL;
1505 return ret;
1506 } /* static int fc_destroy (int, void **) */
1508 static int fc_exec(int type, const data_set_t *ds, const value_list_t *vl,
1509 notification_meta_t **meta, void **user_data) {
1510 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1512 dTHX;
1514 if (NULL == perl_threads)
1515 return 0;
1517 assert(NULL != data);
1519 if (NULL == aTHX) {
1520 c_ithread_t *t = NULL;
1522 pthread_mutex_lock(&perl_threads->mutex);
1523 t = c_ithread_create(perl_threads->head->interp);
1524 pthread_mutex_unlock(&perl_threads->mutex);
1526 aTHX = t->interp;
1527 }
1529 log_debug("fc_exec: c_ithread: interp = %p (active threads: %i)", aTHX,
1530 perl_threads->number_of_threads);
1532 return fc_call(aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1533 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1534 notification_meta_t **, void **) */
1536 static int pmatch_create(const oconfig_item_t *ci, void **user_data) {
1537 return fc_create(FC_MATCH, ci, user_data);
1538 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1540 static int pmatch_destroy(void **user_data) {
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) {
1546 return fc_exec(FC_MATCH, ds, vl, meta, user_data);
1547 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1548 notification_meta_t **, void **) */
1550 static match_proc_t pmatch = {pmatch_create, pmatch_destroy, pmatch_match};
1552 static int ptarget_create(const oconfig_item_t *ci, void **user_data) {
1553 return fc_create(FC_TARGET, ci, user_data);
1554 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1556 static int ptarget_destroy(void **user_data) {
1557 return fc_destroy(FC_TARGET, user_data);
1558 } /* static int ptarget_destroy (void **) */
1560 static int ptarget_invoke(const data_set_t *ds, value_list_t *vl,
1561 notification_meta_t **meta, void **user_data) {
1562 return fc_exec(FC_TARGET, ds, vl, meta, user_data);
1563 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1564 notification_meta_t **, void **) */
1566 static target_proc_t ptarget = {ptarget_create, ptarget_destroy,
1567 ptarget_invoke};
1569 /*
1570 * Exported Perl API.
1571 */
1573 static void _plugin_register_generic_userdata(pTHX, int type,
1574 const char *desc) {
1575 int ret = 0;
1576 user_data_t userdata;
1577 char *pluginname;
1579 dXSARGS;
1581 if (2 != items) {
1582 log_err("Usage: Collectd::plugin_register_%s(pluginname, subname)", desc);
1583 XSRETURN_EMPTY;
1584 }
1586 if (!SvOK(ST(0))) {
1587 log_err("Collectd::plugin_register_%s(pluginname, subname): "
1588 "Invalid pluginname",
1589 desc);
1590 XSRETURN_EMPTY;
1591 }
1592 if (!SvOK(ST(1))) {
1593 log_err("Collectd::plugin_register_%s(pluginname, subname): "
1594 "Invalid subname",
1595 desc);
1596 XSRETURN_EMPTY;
1597 }
1599 /* Use pluginname as-is to allow flush a single perl plugin */
1600 pluginname = SvPV_nolen(ST(0));
1602 log_debug("Collectd::plugin_register_%s: "
1603 "plugin = \"%s\", sub = \"%s\"",
1604 desc, pluginname, SvPV_nolen(ST(1)));
1606 memset(&userdata, 0, sizeof(userdata));
1607 userdata.data = strdup(SvPV_nolen(ST(1)));
1608 userdata.free_func = free;
1610 if (PLUGIN_READ == type) {
1611 ret = plugin_register_complex_read(
1612 "perl", /* group */
1613 pluginname, perl_read, plugin_get_interval(), /* Default interval */
1614 &userdata);
1615 } else if (PLUGIN_WRITE == type) {
1616 ret = plugin_register_write(pluginname, perl_write, &userdata);
1617 } else if (PLUGIN_LOG == type) {
1618 ret = plugin_register_log(pluginname, perl_log, &userdata);
1619 } else if (PLUGIN_NOTIF == type) {
1620 ret = plugin_register_notification(pluginname, perl_notify, &userdata);
1621 } else if (PLUGIN_FLUSH == type) {
1622 if (1 == register_legacy_flush) { /* For collectd-5.7 only, #1731 */
1623 register_legacy_flush = 0;
1624 ret = plugin_register_flush("perl", perl_flush, /* user_data = */ NULL);
1625 }
1627 if (0 == ret) {
1628 ret = plugin_register_flush(pluginname, perl_flush, &userdata);
1629 } else {
1630 free(userdata.data);
1631 }
1632 } else {
1633 ret = -1;
1634 }
1636 if (0 == ret)
1637 XSRETURN_YES;
1638 else
1639 XSRETURN_EMPTY;
1640 } /* static void _plugin_register_generic_userdata ( ... ) */
1642 /*
1643 * Collectd::plugin_register_TYPE (pluginname, subname).
1644 *
1645 * pluginname:
1646 * name of the perl plugin
1647 *
1648 * subname:
1649 * name of the plugin's subroutine that does the work
1650 */
1652 static XS(Collectd_plugin_register_read) {
1653 return _plugin_register_generic_userdata(aTHX, PLUGIN_READ, "read");
1654 }
1656 static XS(Collectd_plugin_register_write) {
1657 return _plugin_register_generic_userdata(aTHX, PLUGIN_WRITE, "write");
1658 }
1660 static XS(Collectd_plugin_register_log) {
1661 return _plugin_register_generic_userdata(aTHX, PLUGIN_LOG, "log");
1662 }
1664 static XS(Collectd_plugin_register_notification) {
1665 return _plugin_register_generic_userdata(aTHX, PLUGIN_NOTIF, "notification");
1666 }
1668 static XS(Collectd_plugin_register_flush) {
1669 return _plugin_register_generic_userdata(aTHX, PLUGIN_FLUSH, "flush");
1670 }
1672 typedef int perl_unregister_function_t(const char *name);
1674 static void _plugin_unregister_generic(pTHX, perl_unregister_function_t *unreg,
1675 const char *desc) {
1676 dXSARGS;
1678 if (1 != items) {
1679 log_err("Usage: Collectd::plugin_unregister_%s(pluginname)", desc);
1680 XSRETURN_EMPTY;
1681 }
1683 if (!SvOK(ST(0))) {
1684 log_err("Collectd::plugin_unregister_%s(pluginname): "
1685 "Invalid pluginname",
1686 desc);
1687 XSRETURN_EMPTY;
1688 }
1690 log_debug("Collectd::plugin_unregister_%s: plugin = \"%s\"", desc,
1691 SvPV_nolen(ST(0)));
1693 unreg(SvPV_nolen(ST(0)));
1695 XSRETURN_EMPTY;
1697 return;
1698 } /* static void _plugin_unregister_generic ( ... ) */
1700 /*
1701 * Collectd::plugin_unregister_TYPE (pluginname).
1702 *
1703 * TYPE:
1704 * type of callback to be unregistered: read, write, log, notification, flush
1705 *
1706 * pluginname:
1707 * name of the perl plugin
1708 */
1710 static XS(Collectd_plugin_unregister_read) {
1711 return _plugin_unregister_generic(aTHX, plugin_unregister_read, "read");
1712 }
1714 static XS(Collectd_plugin_unregister_write) {
1715 return _plugin_unregister_generic(aTHX, plugin_unregister_write, "write");
1716 }
1718 static XS(Collectd_plugin_unregister_log) {
1719 return _plugin_unregister_generic(aTHX, plugin_unregister_log, "log");
1720 }
1722 static XS(Collectd_plugin_unregister_notification) {
1723 return _plugin_unregister_generic(aTHX, plugin_unregister_notification,
1724 "notification");
1725 }
1727 static XS(Collectd_plugin_unregister_flush) {
1728 return _plugin_unregister_generic(aTHX, plugin_unregister_flush, "flush");
1729 }
1731 /*
1732 * Collectd::plugin_register_data_set (type, dataset).
1733 *
1734 * type:
1735 * type of the dataset
1736 *
1737 * dataset:
1738 * dataset to be registered
1739 */
1740 static XS(Collectd_plugin_register_ds) {
1741 SV *data = NULL;
1742 int ret = 0;
1744 dXSARGS;
1746 log_warn("Using plugin_register() to register new data-sets is "
1747 "deprecated - add new entries to a custom types.db instead.");
1749 if (2 != items) {
1750 log_err("Usage: Collectd::plugin_register_data_set(type, dataset)");
1751 XSRETURN_EMPTY;
1752 }
1754 log_debug("Collectd::plugin_register_data_set: "
1755 "type = \"%s\", dataset = \"%s\"",
1756 SvPV_nolen(ST(0)), SvPV_nolen(ST(1)));
1758 data = ST(1);
1760 if (SvROK(data) && (SVt_PVAV == SvTYPE(SvRV(data)))) {
1761 ret = pplugin_register_data_set(aTHX_ SvPV_nolen(ST(0)), (AV *)SvRV(data));
1762 } else {
1763 log_err("Collectd::plugin_register_data_set: Invalid data.");
1764 XSRETURN_EMPTY;
1765 }
1767 if (0 == ret)
1768 XSRETURN_YES;
1769 else
1770 XSRETURN_EMPTY;
1771 } /* static XS (Collectd_plugin_register_ds) */
1773 /*
1774 * Collectd::plugin_unregister_data_set (type).
1775 *
1776 * type:
1777 * type of the dataset
1778 */
1779 static XS(Collectd_plugin_unregister_ds) {
1780 dXSARGS;
1782 if (1 != items) {
1783 log_err("Usage: Collectd::plugin_unregister_data_set(type)");
1784 XSRETURN_EMPTY;
1785 }
1787 log_debug("Collectd::plugin_unregister_data_set: type = \"%s\"",
1788 SvPV_nolen(ST(0)));
1790 if (0 == pplugin_unregister_data_set(SvPV_nolen(ST(0))))
1791 XSRETURN_YES;
1792 else
1793 XSRETURN_EMPTY;
1794 } /* static XS (Collectd_plugin_register_ds) */
1796 /*
1797 * Collectd::plugin_dispatch_values (name, values).
1798 *
1799 * name:
1800 * name of the plugin
1801 *
1802 * values:
1803 * value list to submit
1804 */
1805 static XS(Collectd_plugin_dispatch_values) {
1806 SV *values = NULL;
1808 int ret = 0;
1810 dXSARGS;
1812 if (1 != items) {
1813 log_err("Usage: Collectd::plugin_dispatch_values(values)");
1814 XSRETURN_EMPTY;
1815 }
1817 log_debug("Collectd::plugin_dispatch_values: values=\"%s\"",
1818 SvPV_nolen(ST(/* stack index = */ 0)));
1820 values = ST(/* stack index = */ 0);
1822 if (NULL == values)
1823 XSRETURN_EMPTY;
1825 /* Make sure the argument is a hash reference. */
1826 if (!(SvROK(values) && (SVt_PVHV == SvTYPE(SvRV(values))))) {
1827 log_err("Collectd::plugin_dispatch_values: Invalid values.");
1828 XSRETURN_EMPTY;
1829 }
1831 ret = pplugin_dispatch_values(aTHX_(HV *) SvRV(values));
1833 if (0 == ret)
1834 XSRETURN_YES;
1835 else
1836 XSRETURN_EMPTY;
1837 } /* static XS (Collectd_plugin_dispatch_values) */
1839 /*
1840 * Collectd::plugin_get_interval ().
1841 */
1842 static XS(Collectd_plugin_get_interval) {
1843 dXSARGS;
1845 /* make sure we don't get any unused variable warnings for 'items';
1846 * don't abort, though */
1847 if (items)
1848 log_err("Usage: Collectd::plugin_get_interval()");
1850 XSRETURN_NV((NV)CDTIME_T_TO_DOUBLE(plugin_get_interval()));
1851 } /* static XS (Collectd_plugin_get_interval) */
1853 /* Collectd::plugin_write (plugin, ds, vl).
1854 *
1855 * plugin:
1856 * name of the plugin to call, may be 'undef'
1857 *
1858 * ds:
1859 * data-set that describes the submitted values, may be 'undef'
1860 *
1861 * vl:
1862 * value-list to be written
1863 */
1864 static XS(Collectd__plugin_write) {
1865 char *plugin;
1866 SV *ds, *vl;
1867 AV *ds_array;
1869 int ret;
1871 dXSARGS;
1873 if (3 != items) {
1874 log_err("Usage: Collectd::plugin_write(plugin, ds, vl)");
1875 XSRETURN_EMPTY;
1876 }
1878 log_debug("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1879 SvPV_nolen(ST(0)), SvOK(ST(1)) ? SvPV_nolen(ST(1)) : "",
1880 SvPV_nolen(ST(2)));
1882 if (!SvOK(ST(0)))
1883 plugin = NULL;
1884 else
1885 plugin = SvPV_nolen(ST(0));
1887 ds = ST(1);
1888 if (SvROK(ds) && (SVt_PVAV == SvTYPE(SvRV(ds))))
1889 ds_array = (AV *)SvRV(ds);
1890 else if (!SvOK(ds))
1891 ds_array = NULL;
1892 else {
1893 log_err("Collectd::plugin_write: Invalid data-set.");
1894 XSRETURN_EMPTY;
1895 }
1897 vl = ST(2);
1898 if (!(SvROK(vl) && (SVt_PVHV == SvTYPE(SvRV(vl))))) {
1899 log_err("Collectd::plugin_write: Invalid value-list.");
1900 XSRETURN_EMPTY;
1901 }
1903 ret = pplugin_write(aTHX_ plugin, ds_array, (HV *)SvRV(vl));
1905 if (0 == ret)
1906 XSRETURN_YES;
1907 else
1908 XSRETURN_EMPTY;
1909 } /* static XS (Collectd__plugin_write) */
1911 /*
1912 * Collectd::_plugin_flush (plugin, timeout, identifier).
1913 *
1914 * plugin:
1915 * name of the plugin to flush
1916 *
1917 * timeout:
1918 * timeout to use when flushing the data
1919 *
1920 * identifier:
1921 * data-set identifier to flush
1922 */
1923 static XS(Collectd__plugin_flush) {
1924 char *plugin = NULL;
1925 int timeout = -1;
1926 char *id = NULL;
1928 dXSARGS;
1930 if (3 != items) {
1931 log_err("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1932 XSRETURN_EMPTY;
1933 }
1935 if (SvOK(ST(0)))
1936 plugin = SvPV_nolen(ST(0));
1938 if (SvOK(ST(1)))
1939 timeout = (int)SvIV(ST(1));
1941 if (SvOK(ST(2)))
1942 id = SvPV_nolen(ST(2));
1944 log_debug("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1945 "id = \"%s\"",
1946 plugin, timeout, id);
1948 if (0 == plugin_flush(plugin, timeout, id))
1949 XSRETURN_YES;
1950 else
1951 XSRETURN_EMPTY;
1952 } /* static XS (Collectd__plugin_flush) */
1954 /*
1955 * Collectd::plugin_dispatch_notification (notif).
1956 *
1957 * notif:
1958 * notification to dispatch
1959 */
1960 static XS(Collectd_plugin_dispatch_notification) {
1961 SV *notif = NULL;
1963 int ret = 0;
1965 dXSARGS;
1967 if (1 != items) {
1968 log_err("Usage: Collectd::plugin_dispatch_notification(notif)");
1969 XSRETURN_EMPTY;
1970 }
1972 log_debug("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1973 SvPV_nolen(ST(0)));
1975 notif = ST(0);
1977 if (!(SvROK(notif) && (SVt_PVHV == SvTYPE(SvRV(notif))))) {
1978 log_err("Collectd::plugin_dispatch_notification: Invalid notif.");
1979 XSRETURN_EMPTY;
1980 }
1982 ret = pplugin_dispatch_notification(aTHX_(HV *) SvRV(notif));
1984 if (0 == ret)
1985 XSRETURN_YES;
1986 else
1987 XSRETURN_EMPTY;
1988 } /* static XS (Collectd_plugin_dispatch_notification) */
1990 /*
1991 * Collectd::plugin_log (level, message).
1992 *
1993 * level:
1994 * log level (LOG_DEBUG, ... LOG_ERR)
1995 *
1996 * message:
1997 * log message
1998 */
1999 static XS(Collectd_plugin_log) {
2000 dXSARGS;
2002 if (2 != items) {
2003 log_err("Usage: Collectd::plugin_log(level, message)");
2004 XSRETURN_EMPTY;
2005 }
2007 plugin_log(SvIV(ST(0)), "%s", SvPV_nolen(ST(1)));
2008 XSRETURN_YES;
2009 } /* static XS (Collectd_plugin_log) */
2011 /*
2012 * Collectd::_fc_register (type, name)
2013 *
2014 * type:
2015 * match | target
2016 *
2017 * name:
2018 * name of the match
2019 */
2020 static XS(Collectd__fc_register) {
2021 int type;
2022 char *name;
2024 int ret = 0;
2026 dXSARGS;
2028 if (2 != items) {
2029 log_err("Usage: Collectd::_fc_register(type, name)");
2030 XSRETURN_EMPTY;
2031 }
2033 type = SvIV(ST(0));
2034 name = SvPV_nolen(ST(1));
2036 if (FC_MATCH == type)
2037 ret = fc_register_match(name, pmatch);
2038 else if (FC_TARGET == type)
2039 ret = fc_register_target(name, ptarget);
2041 if (0 == ret)
2042 XSRETURN_YES;
2043 else
2044 XSRETURN_EMPTY;
2045 } /* static XS (Collectd_fc_register) */
2047 /*
2048 * Collectd::call_by_name (...).
2049 *
2050 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
2051 */
2052 static XS(Collectd_call_by_name) {
2053 SV *tmp = NULL;
2054 char *name = NULL;
2056 if (NULL == (tmp = get_sv("Collectd::cb_name", 0))) {
2057 sv_setpv(get_sv("@", 1), "cb_name has not been set");
2058 CLEAR_STACK_FRAME;
2059 return;
2060 }
2062 name = SvPV_nolen(tmp);
2064 if (NULL == get_cv(name, 0)) {
2065 sv_setpvf(get_sv("@", 1), "unknown callback \"%s\"", name);
2066 CLEAR_STACK_FRAME;
2067 return;
2068 }
2070 /* simply pass on the subroutine call without touching the stack,
2071 * thus leaving any arguments and return values in place */
2072 call_pv(name, 0);
2073 } /* static XS (Collectd_call_by_name) */
2075 /*
2076 * Interface to collectd.
2077 */
2079 static int perl_init(void) {
2080 int status;
2081 dTHX;
2083 if (NULL == perl_threads)
2084 return 0;
2086 if (NULL == aTHX) {
2087 c_ithread_t *t = NULL;
2089 pthread_mutex_lock(&perl_threads->mutex);
2090 t = c_ithread_create(perl_threads->head->interp);
2091 pthread_mutex_unlock(&perl_threads->mutex);
2093 aTHX = t->interp;
2094 }
2096 log_debug("perl_init: c_ithread: interp = %p (active threads: %i)", aTHX,
2097 perl_threads->number_of_threads);
2099 /* Lock the base thread to avoid race conditions with c_ithread_create().
2100 * See https://github.com/collectd/collectd/issues/9 and
2101 * https://github.com/collectd/collectd/issues/1706 for details.
2102 */
2103 assert(aTHX == perl_threads->head->interp);
2104 pthread_mutex_lock(&perl_threads->mutex);
2106 status = pplugin_call(aTHX_ PLUGIN_INIT);
2108 pthread_mutex_unlock(&perl_threads->mutex);
2110 return status;
2111 } /* static int perl_init (void) */
2113 static int perl_read(user_data_t *user_data) {
2114 dTHX;
2116 if (NULL == perl_threads)
2117 return 0;
2119 if (NULL == aTHX) {
2120 c_ithread_t *t = NULL;
2122 pthread_mutex_lock(&perl_threads->mutex);
2123 t = c_ithread_create(perl_threads->head->interp);
2124 pthread_mutex_unlock(&perl_threads->mutex);
2126 aTHX = t->interp;
2127 }
2129 /* Assert that we're not running as the base thread. Otherwise, we might
2130 * run into concurrency issues with c_ithread_create(). See
2131 * https://github.com/collectd/collectd/issues/9 for details. */
2132 assert(aTHX != perl_threads->head->interp);
2134 log_debug("perl_read: c_ithread: interp = %p (active threads: %i)", aTHX,
2135 perl_threads->number_of_threads);
2137 return pplugin_call(aTHX_ PLUGIN_READ, user_data->data);
2138 } /* static int perl_read (user_data_t *user_data) */
2140 static int perl_write(const data_set_t *ds, const value_list_t *vl,
2141 user_data_t *user_data) {
2142 int status;
2143 dTHX;
2145 if (NULL == perl_threads)
2146 return 0;
2148 if (NULL == aTHX) {
2149 c_ithread_t *t = NULL;
2151 pthread_mutex_lock(&perl_threads->mutex);
2152 t = c_ithread_create(perl_threads->head->interp);
2153 pthread_mutex_unlock(&perl_threads->mutex);
2155 aTHX = t->interp;
2156 }
2158 /* Lock the base thread if this is not called from one of the read threads
2159 * to avoid race conditions with c_ithread_create(). See
2160 * https://github.com/collectd/collectd/issues/9 for details. */
2161 if (aTHX == perl_threads->head->interp)
2162 pthread_mutex_lock(&perl_threads->mutex);
2164 log_debug("perl_write: c_ithread: interp = %p (active threads: %i)", aTHX,
2165 perl_threads->number_of_threads);
2166 status = pplugin_call(aTHX_ PLUGIN_WRITE, user_data->data, ds, vl);
2168 if (aTHX == perl_threads->head->interp)
2169 pthread_mutex_unlock(&perl_threads->mutex);
2171 return status;
2172 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2174 static void perl_log(int level, const char *msg, user_data_t *user_data) {
2175 dTHX;
2177 if (NULL == perl_threads)
2178 return;
2180 if (NULL == aTHX) {
2181 c_ithread_t *t = NULL;
2183 pthread_mutex_lock(&perl_threads->mutex);
2184 t = c_ithread_create(perl_threads->head->interp);
2185 pthread_mutex_unlock(&perl_threads->mutex);
2187 aTHX = t->interp;
2188 }
2190 /* Lock the base thread if this is not called from one of the read threads
2191 * to avoid race conditions with c_ithread_create(). See
2192 * https://github.com/collectd/collectd/issues/9 for details.
2193 */
2195 if (aTHX == perl_threads->head->interp)
2196 pthread_mutex_lock(&perl_threads->mutex);
2198 pplugin_call(aTHX_ PLUGIN_LOG, user_data->data, level, msg);
2200 if (aTHX == perl_threads->head->interp)
2201 pthread_mutex_unlock(&perl_threads->mutex);
2203 return;
2204 } /* static void perl_log (int, const char *) */
2206 static int perl_notify(const notification_t *notif, user_data_t *user_data) {
2207 dTHX;
2209 if (NULL == perl_threads)
2210 return 0;
2212 if (NULL == aTHX) {
2213 c_ithread_t *t = NULL;
2215 pthread_mutex_lock(&perl_threads->mutex);
2216 t = c_ithread_create(perl_threads->head->interp);
2217 pthread_mutex_unlock(&perl_threads->mutex);
2219 aTHX = t->interp;
2220 }
2221 return pplugin_call(aTHX_ PLUGIN_NOTIF, user_data->data, notif);
2222 } /* static int perl_notify (const notification_t *) */
2224 static int perl_flush(cdtime_t timeout, const char *identifier,
2225 user_data_t *user_data) {
2226 dTHX;
2228 if (NULL == perl_threads)
2229 return 0;
2231 if (NULL == aTHX) {
2232 c_ithread_t *t = NULL;
2234 pthread_mutex_lock(&perl_threads->mutex);
2235 t = c_ithread_create(perl_threads->head->interp);
2236 pthread_mutex_unlock(&perl_threads->mutex);
2238 aTHX = t->interp;
2239 }
2241 /* For collectd-5.6 only, #1731 */
2242 if (user_data == NULL || user_data->data == NULL)
2243 return pplugin_call(aTHX_ PLUGIN_FLUSH_ALL, timeout, identifier);
2245 return pplugin_call(aTHX_ PLUGIN_FLUSH, user_data->data, timeout, identifier);
2246 } /* static int perl_flush (const int) */
2248 static int perl_shutdown(void) {
2249 c_ithread_t *t;
2250 int ret;
2252 dTHX;
2254 plugin_unregister_complex_config("perl");
2255 plugin_unregister_read_group("perl");
2257 if (NULL == perl_threads)
2258 return 0;
2260 if (NULL == aTHX) {
2261 pthread_mutex_lock(&perl_threads->mutex);
2262 t = c_ithread_create(perl_threads->head->interp);
2263 pthread_mutex_unlock(&perl_threads->mutex);
2265 aTHX = t->interp;
2266 }
2268 log_debug("perl_shutdown: c_ithread: interp = %p (active threads: %i)", aTHX,
2269 perl_threads->number_of_threads);
2271 plugin_unregister_init("perl");
2272 plugin_unregister_flush("perl"); /* For collectd-5.6 only, #1731 */
2274 ret = pplugin_call(aTHX_ PLUGIN_SHUTDOWN);
2276 pthread_mutex_lock(&perl_threads->mutex);
2277 t = perl_threads->tail;
2279 while (NULL != t) {
2280 struct timespec ts_wait;
2281 c_ithread_t *thr = t;
2283 /* the pointer has to be advanced before destroying
2284 * the thread as this will free the memory */
2285 t = t->prev;
2287 thr->shutdown = 1;
2288 if (thr->running) {
2289 /* Give some time to thread to exit from Perl interpreter */
2290 WARNING("perl shutdown: Thread is running inside Perl. Waiting.");
2291 ts_wait.tv_sec = 0;
2292 ts_wait.tv_nsec = 500000;
2293 nanosleep(&ts_wait, NULL);
2294 }
2295 if (thr->running) {
2296 pthread_kill(thr->pthread, SIGTERM);
2297 ERROR("perl shutdown: Thread hangs inside Perl. Thread killed.");
2298 }
2299 c_ithread_destroy(thr);
2300 }
2302 pthread_mutex_unlock(&perl_threads->mutex);
2303 pthread_mutex_destroy(&perl_threads->mutex);
2304 pthread_mutexattr_destroy(&perl_threads->mutexattr);
2306 sfree(perl_threads);
2308 pthread_key_delete(perl_thr_key);
2310 PERL_SYS_TERM();
2312 plugin_unregister_shutdown("perl");
2313 return ret;
2314 } /* static void perl_shutdown (void) */
2316 /*
2317 * Access functions for global variables.
2318 *
2319 * These functions implement the "magic" used to access
2320 * the global variables from Perl.
2321 */
2323 static int g_pv_get(pTHX_ SV *var, MAGIC *mg) {
2324 char *pv = mg->mg_ptr;
2325 sv_setpv(var, pv);
2326 return 0;
2327 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2329 static int g_pv_set(pTHX_ SV *var, MAGIC *mg) {
2330 char *pv = mg->mg_ptr;
2331 sstrncpy(pv, SvPV_nolen(var), DATA_MAX_NAME_LEN);
2332 return 0;
2333 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2335 static int g_interval_get(pTHX_ SV *var, MAGIC *mg) {
2336 log_warn("Accessing $interval_g is deprecated (and might not "
2337 "give the desired results) - plugin_get_interval() should "
2338 "be used instead.");
2339 sv_setnv(var, CDTIME_T_TO_DOUBLE(interval_g));
2340 return 0;
2341 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2343 static int g_interval_set(pTHX_ SV *var, MAGIC *mg) {
2344 double nv = (double)SvNV(var);
2345 log_warn("Accessing $interval_g is deprecated (and might not "
2346 "give the desired results) - plugin_get_interval() should "
2347 "be used instead.");
2348 interval_g = DOUBLE_TO_CDTIME_T(nv);
2349 return 0;
2350 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2352 static MGVTBL g_pv_vtbl = {g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2353 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2354 ,
2355 NULL
2356 #endif
2357 };
2358 static MGVTBL g_interval_vtbl = {g_interval_get, g_interval_set, NULL, NULL,
2359 NULL, NULL, NULL
2360 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2361 ,
2362 NULL
2363 #endif
2364 };
2366 /* bootstrap the Collectd module */
2367 static void xs_init(pTHX) {
2368 HV *stash = NULL;
2369 SV *tmp = NULL;
2370 char *file = __FILE__;
2372 dXSUB_SYS;
2374 /* enable usage of Perl modules using shared libraries */
2375 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2377 /* register API */
2378 for (int i = 0; NULL != api[i].f; ++i)
2379 newXS(api[i].name, api[i].f, file);
2381 stash = gv_stashpv("Collectd", 1);
2383 /* export "constants" */
2384 for (int i = 0; '\0' != constants[i].name[0]; ++i)
2385 newCONSTSUB(stash, constants[i].name, newSViv(constants[i].value));
2387 /* export global variables
2388 * by adding "magic" to the SV's representing the globale variables
2389 * perl is able to automagically call the get/set function when
2390 * accessing any such variable (this is basically the same as using
2391 * tie() in Perl) */
2392 /* global strings */
2393 for (int i = 0; '\0' != g_strings[i].name[0]; ++i) {
2394 tmp = get_sv(g_strings[i].name, 1);
2395 sv_magicext(tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl, g_strings[i].var, 0);
2396 }
2398 tmp = get_sv("Collectd::interval_g", /* create = */ 1);
2399 sv_magicext(tmp, NULL, /* how = */ PERL_MAGIC_ext,
2400 /* vtbl = */ &g_interval_vtbl,
2401 /* name = */ NULL, /* namelen = */ 0);
2403 return;
2404 } /* static void xs_init (pTHX) */
2406 /* Initialize the global Perl interpreter. */
2407 static int init_pi(int argc, char **argv) {
2408 dTHXa(NULL);
2410 if (NULL != perl_threads)
2411 return 0;
2413 log_info("Initializing Perl interpreter...");
2414 #if COLLECT_DEBUG
2415 {
2416 for (int i = 0; i < argc; ++i)
2417 log_debug("argv[%i] = \"%s\"", i, argv[i]);
2418 }
2419 #endif /* COLLECT_DEBUG */
2421 if (0 != pthread_key_create(&perl_thr_key, c_ithread_destructor)) {
2422 log_err("init_pi: pthread_key_create failed");
2424 /* this must not happen - cowardly giving up if it does */
2425 return -1;
2426 }
2428 #ifdef __FreeBSD__
2429 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2430 * triggers a "value computed is not used" warning by gcc. */
2431 (void)
2432 #endif
2433 PERL_SYS_INIT3(&argc, &argv, &environ);
2435 perl_threads = smalloc(sizeof(*perl_threads));
2436 memset(perl_threads, 0, sizeof(c_ithread_list_t));
2438 pthread_mutexattr_init(&perl_threads->mutexattr);
2439 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2440 pthread_mutex_init(&perl_threads->mutex, &perl_threads->mutexattr);
2441 /* locking the mutex should not be necessary at this point
2442 * but let's just do it for the sake of completeness */
2443 pthread_mutex_lock(&perl_threads->mutex);
2445 perl_threads->head = c_ithread_create(NULL);
2446 perl_threads->tail = perl_threads->head;
2448 if (NULL == (perl_threads->head->interp = perl_alloc())) {
2449 log_err("init_pi: Not enough memory.");
2450 exit(3);
2451 }
2453 aTHX = perl_threads->head->interp;
2454 pthread_mutex_unlock(&perl_threads->mutex);
2456 perl_construct(aTHX);
2458 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2460 if (0 != perl_parse(aTHX_ xs_init, argc, argv, NULL)) {
2461 SV *err = get_sv("@", 1);
2462 log_err("init_pi: Unable to bootstrap Collectd: %s", SvPV_nolen(err));
2464 perl_destruct(perl_threads->head->interp);
2465 perl_free(perl_threads->head->interp);
2466 sfree(perl_threads);
2468 pthread_key_delete(perl_thr_key);
2469 return -1;
2470 }
2472 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2473 sv_setpv(get_sv("0", 0), "collectd");
2475 perl_run(aTHX);
2477 plugin_register_init("perl", perl_init);
2478 plugin_register_shutdown("perl", perl_shutdown);
2479 return 0;
2480 } /* static int init_pi (const char **, const int) */
2482 /*
2483 * LoadPlugin "<Plugin>"
2484 */
2485 static int perl_config_loadplugin(pTHX_ oconfig_item_t *ci) {
2486 char module_name[DATA_MAX_NAME_LEN];
2488 char *value = NULL;
2490 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2491 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2492 log_err("LoadPlugin expects a single string argument.");
2493 return 1;
2494 }
2496 value = ci->values[0].value.string;
2498 if (NULL == get_module_name(module_name, sizeof(module_name), value)) {
2499 log_err("Invalid module name %s", value);
2500 return 1;
2501 }
2503 if (0 != init_pi(perl_argc, perl_argv))
2504 return -1;
2506 assert(NULL != perl_threads);
2507 assert(NULL != perl_threads->head);
2509 aTHX = perl_threads->head->interp;
2511 log_debug("perl_config: Loading Perl plugin \"%s\"", value);
2512 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(module_name, strlen(module_name)),
2513 Nullsv);
2514 return 0;
2515 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2517 /*
2518 * BaseName "<Name>"
2519 */
2520 static int perl_config_basename(pTHX_ oconfig_item_t *ci) {
2521 char *value = NULL;
2523 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2524 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2525 log_err("BaseName expects a single string argument.");
2526 return 1;
2527 }
2529 value = ci->values[0].value.string;
2531 log_debug("perl_config: Setting plugin basename to \"%s\"", value);
2532 sstrncpy(base_name, value, sizeof(base_name));
2533 return 0;
2534 } /* static int perl_config_basename (oconfig_item_it *) */
2536 /*
2537 * EnableDebugger "<Package>"|""
2538 */
2539 static int perl_config_enabledebugger(pTHX_ oconfig_item_t *ci) {
2540 char *value = NULL;
2542 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2543 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2544 log_err("EnableDebugger expects a single string argument.");
2545 return 1;
2546 }
2548 if (NULL != perl_threads) {
2549 log_warn("EnableDebugger has no effects if used after LoadPlugin.");
2550 return 1;
2551 }
2553 value = ci->values[0].value.string;
2555 perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2557 if (NULL == perl_argv) {
2558 log_err("perl_config: Not enough memory.");
2559 exit(3);
2560 }
2562 if ('\0' == value[0]) {
2563 perl_argv[perl_argc - 1] = "-d";
2564 } else {
2565 perl_argv[perl_argc - 1] = smalloc(strlen(value) + 4);
2566 sstrncpy(perl_argv[perl_argc - 1], "-d:", 4);
2567 sstrncpy(perl_argv[perl_argc - 1] + 3, value, strlen(value) + 1);
2568 }
2570 perl_argv[perl_argc] = NULL;
2571 return 0;
2572 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2574 /*
2575 * IncludeDir "<Dir>"
2576 */
2577 static int perl_config_includedir(pTHX_ oconfig_item_t *ci) {
2578 char *value = NULL;
2580 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2581 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2582 log_err("IncludeDir expects a single string argument.");
2583 return 1;
2584 }
2586 value = ci->values[0].value.string;
2588 if (NULL == aTHX) {
2589 perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2591 if (NULL == perl_argv) {
2592 log_err("perl_config: Not enough memory.");
2593 exit(3);
2594 }
2596 perl_argv[perl_argc - 1] = smalloc(strlen(value) + 3);
2597 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2598 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen(value) + 1);
2600 perl_argv[perl_argc] = NULL;
2601 } else {
2602 /* prepend the directory to @INC */
2603 av_unshift(GvAVn(PL_incgv), 1);
2604 av_store(GvAVn(PL_incgv), 0, newSVpv(value, strlen(value)));
2605 }
2606 return 0;
2607 } /* static int perl_config_includedir (oconfig_item_it *) */
2609 /*
2610 * <Plugin> block
2611 */
2612 static int perl_config_plugin(pTHX_ oconfig_item_t *ci) {
2613 int retvals = 0;
2614 int ret = 0;
2616 char *plugin;
2617 HV *config;
2619 dSP;
2621 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2622 log_err("LoadPlugin expects a single string argument.");
2623 return 1;
2624 }
2626 plugin = ci->values[0].value.string;
2627 config = newHV();
2629 if (0 != oconfig_item2hv(aTHX_ ci, config)) {
2630 hv_clear(config);
2631 hv_undef(config);
2633 log_err("Unable to convert configuration to a Perl hash value.");
2634 config = (HV *)&PL_sv_undef;
2635 }
2637 ENTER;
2638 SAVETMPS;
2640 PUSHMARK(SP);
2642 XPUSHs(sv_2mortal(newSVpv(plugin, 0)));
2643 XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
2645 PUTBACK;
2647 retvals = call_pv("Collectd::_plugin_dispatch_config", G_SCALAR);
2649 SPAGAIN;
2650 if (0 < retvals) {
2651 SV *tmp = POPs;
2652 if (!SvTRUE(tmp))
2653 ret = 1;
2654 } else
2655 ret = 1;
2657 PUTBACK;
2658 FREETMPS;
2659 LEAVE;
2660 return ret;
2661 } /* static int perl_config_plugin (oconfig_item_it *) */
2663 static int perl_config(oconfig_item_t *ci) {
2664 int status = 0;
2666 dTHXa(NULL);
2668 for (int i = 0; i < ci->children_num; ++i) {
2669 oconfig_item_t *c = ci->children + i;
2670 int current_status = 0;
2672 if (NULL != perl_threads) {
2673 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2674 return -1;
2675 }
2677 if (0 == strcasecmp(c->key, "LoadPlugin"))
2678 current_status = perl_config_loadplugin(aTHX_ c);
2679 else if (0 == strcasecmp(c->key, "BaseName"))
2680 current_status = perl_config_basename(aTHX_ c);
2681 else if (0 == strcasecmp(c->key, "EnableDebugger"))
2682 current_status = perl_config_enabledebugger(aTHX_ c);
2683 else if (0 == strcasecmp(c->key, "IncludeDir"))
2684 current_status = perl_config_includedir(aTHX_ c);
2685 else if (0 == strcasecmp(c->key, "Plugin"))
2686 current_status = perl_config_plugin(aTHX_ c);
2687 else if (0 == strcasecmp(c->key, "RegisterLegacyFlush"))
2688 cf_util_get_boolean(c, ®ister_legacy_flush);
2689 else {
2690 log_warn("Ignoring unknown config key \"%s\".", c->key);
2691 current_status = 0;
2692 }
2694 /* fatal error - it's up to perl_config_* to clean up */
2695 if (0 > current_status) {
2696 log_err("Configuration failed with a fatal error - "
2697 "plugin disabled!");
2698 return current_status;
2699 }
2701 status += current_status;
2702 }
2703 return status;
2704 } /* static int perl_config (oconfig_item_t *) */
2706 void module_register(void) {
2707 perl_argc = 4;
2708 perl_argv = smalloc((perl_argc + 1) * sizeof(*perl_argv));
2710 /* default options for the Perl interpreter */
2711 perl_argv[0] = "";
2712 perl_argv[1] = "-MCollectd";
2713 perl_argv[2] = "-e";
2714 perl_argv[3] = "1";
2715 perl_argv[4] = NULL;
2717 plugin_register_complex_config("perl", perl_config);
2718 return;
2719 } /* void module_register (void) */