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 #if HAVE_STDBOOL_H
42 #include <stdbool.h>
43 #endif
45 #include <EXTERN.h>
46 #include <perl.h>
48 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
49 #undef sprintf
50 #pragma GCC poison sprintf
51 #endif
53 #include <XSUB.h>
55 /* Some versions of Perl define their own version of DEBUG... :-/ */
56 #ifdef DEBUG
57 #undef DEBUG
58 #endif /* DEBUG */
60 /* ... while we want the definition found in plugin.h. */
61 #include "common.h"
62 #include "plugin.h"
64 #include "filter_chain.h"
66 #if !defined(USE_ITHREADS)
67 #error "Perl does not support ithreads!"
68 #endif /* !defined(USE_ITHREADS) */
70 /* clear the Perl sub's stack frame
71 * (this should only be used inside an XSUB) */
72 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
74 #define PLUGIN_INIT 0
75 #define PLUGIN_READ 1
76 #define PLUGIN_WRITE 2
77 #define PLUGIN_SHUTDOWN 3
78 #define PLUGIN_LOG 4
79 #define PLUGIN_NOTIF 5
80 #define PLUGIN_FLUSH 6
81 #define PLUGIN_FLUSH_ALL 7 /* For collectd-5.6 only */
83 #define PLUGIN_TYPES 8
85 #define PLUGIN_CONFIG 254
86 #define PLUGIN_DATASET 255
88 #define FC_MATCH 0
89 #define FC_TARGET 1
91 #define FC_TYPES 2
93 #define FC_CB_CREATE 0
94 #define FC_CB_DESTROY 1
95 #define FC_CB_EXEC 2
97 #define FC_CB_TYPES 3
99 #define log_debug(...) DEBUG("perl: " __VA_ARGS__)
100 #define log_info(...) INFO("perl: " __VA_ARGS__)
101 #define log_warn(...) WARNING("perl: " __VA_ARGS__)
102 #define log_err(...) ERROR("perl: " __VA_ARGS__)
104 /* this is defined in DynaLoader.a */
105 void boot_DynaLoader(PerlInterpreter *, CV *);
107 static XS(Collectd_plugin_register_read);
108 static XS(Collectd_plugin_register_write);
109 static XS(Collectd_plugin_register_log);
110 static XS(Collectd_plugin_register_notification);
111 static XS(Collectd_plugin_register_flush);
112 static XS(Collectd_plugin_unregister_read);
113 static XS(Collectd_plugin_unregister_write);
114 static XS(Collectd_plugin_unregister_log);
115 static XS(Collectd_plugin_unregister_notification);
116 static XS(Collectd_plugin_unregister_flush);
117 static XS(Collectd_plugin_register_ds);
118 static XS(Collectd_plugin_unregister_ds);
119 static XS(Collectd_plugin_dispatch_values);
120 static XS(Collectd_plugin_get_interval);
121 static XS(Collectd__plugin_write);
122 static XS(Collectd__plugin_flush);
123 static XS(Collectd_plugin_dispatch_notification);
124 static XS(Collectd_plugin_log);
125 static XS(Collectd__fc_register);
126 static XS(Collectd_call_by_name);
128 static int perl_read(user_data_t *ud);
129 static int perl_write(const data_set_t *ds, const value_list_t *vl,
130 user_data_t *user_data);
131 static void perl_log(int level, const char *msg, user_data_t *user_data);
132 static int perl_notify(const notification_t *notif, user_data_t *user_data);
133 static int perl_flush(cdtime_t timeout, const char *identifier,
134 user_data_t *user_data);
136 /*
137 * private data types
138 */
140 typedef struct c_ithread_s {
141 /* the thread's Perl interpreter */
142 PerlInterpreter *interp;
143 _Bool running; /* thread is inside Perl interpreter */
144 _Bool shutdown;
145 pthread_t pthread;
147 /* double linked list of threads */
148 struct c_ithread_s *prev;
149 struct c_ithread_s *next;
150 } c_ithread_t;
152 typedef struct {
153 c_ithread_t *head;
154 c_ithread_t *tail;
156 #if COLLECT_DEBUG
157 /* some usage stats */
158 int number_of_threads;
159 #endif /* COLLECT_DEBUG */
161 pthread_mutex_t mutex;
162 pthread_mutexattr_t mutexattr;
163 } c_ithread_list_t;
165 /* name / user_data for Perl matches / targets */
166 typedef struct {
167 char *name;
168 SV *user_data;
169 } pfc_user_data_t;
171 #define PFC_USER_DATA_FREE(data) \
172 do { \
173 sfree((data)->name); \
174 if (NULL != (data)->user_data) \
175 sv_free((data)->user_data); \
176 sfree(data); \
177 } while (0)
179 /*
180 * Public variable
181 */
182 extern char **environ;
184 /*
185 * private variables
186 */
188 static _Bool register_legacy_flush = 1;
190 /* if perl_threads != NULL perl_threads->head must
191 * point to the "base" thread */
192 static c_ithread_list_t *perl_threads = NULL;
194 /* the key used to store each pthread's ithread */
195 static pthread_key_t perl_thr_key;
197 static int perl_argc = 0;
198 static char **perl_argv = NULL;
200 static char base_name[DATA_MAX_NAME_LEN] = "";
202 static struct {
203 char name[64];
204 XS((*f));
205 } api[] = {
206 {"Collectd::plugin_register_read", Collectd_plugin_register_read},
207 {"Collectd::plugin_register_write", Collectd_plugin_register_write},
208 {"Collectd::plugin_register_log", Collectd_plugin_register_log},
209 {"Collectd::plugin_register_notification",
210 Collectd_plugin_register_notification},
211 {"Collectd::plugin_register_flush", Collectd_plugin_register_flush},
212 {"Collectd::plugin_unregister_read", Collectd_plugin_unregister_read},
213 {"Collectd::plugin_unregister_write", Collectd_plugin_unregister_write},
214 {"Collectd::plugin_unregister_log", Collectd_plugin_unregister_log},
215 {"Collectd::plugin_unregister_notification",
216 Collectd_plugin_unregister_notification},
217 {"Collectd::plugin_unregister_flush", Collectd_plugin_unregister_flush},
218 {"Collectd::plugin_register_data_set", Collectd_plugin_register_ds},
219 {"Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds},
220 {"Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values},
221 {"Collectd::plugin_get_interval", Collectd_plugin_get_interval},
222 {"Collectd::_plugin_write", Collectd__plugin_write},
223 {"Collectd::_plugin_flush", Collectd__plugin_flush},
224 {"Collectd::plugin_dispatch_notification",
225 Collectd_plugin_dispatch_notification},
226 {"Collectd::plugin_log", Collectd_plugin_log},
227 {"Collectd::_fc_register", Collectd__fc_register},
228 {"Collectd::call_by_name", Collectd_call_by_name},
229 {"", NULL}};
231 struct {
232 char name[64];
233 int value;
234 } constants[] = {{"Collectd::TYPE_INIT", PLUGIN_INIT},
235 {"Collectd::TYPE_READ", PLUGIN_READ},
236 {"Collectd::TYPE_WRITE", PLUGIN_WRITE},
237 {"Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN},
238 {"Collectd::TYPE_LOG", PLUGIN_LOG},
239 {"Collectd::TYPE_NOTIF", PLUGIN_NOTIF},
240 {"Collectd::TYPE_FLUSH", PLUGIN_FLUSH},
241 {"Collectd::TYPE_CONFIG", PLUGIN_CONFIG},
242 {"Collectd::TYPE_DATASET", PLUGIN_DATASET},
243 {"Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER},
244 {"Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE},
245 {"Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE},
246 {"Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE},
247 {"Collectd::LOG_ERR", LOG_ERR},
248 {"Collectd::LOG_WARNING", LOG_WARNING},
249 {"Collectd::LOG_NOTICE", LOG_NOTICE},
250 {"Collectd::LOG_INFO", LOG_INFO},
251 {"Collectd::LOG_DEBUG", LOG_DEBUG},
252 {"Collectd::FC_MATCH", FC_MATCH},
253 {"Collectd::FC_TARGET", FC_TARGET},
254 {"Collectd::FC_CB_CREATE", FC_CB_CREATE},
255 {"Collectd::FC_CB_DESTROY", FC_CB_DESTROY},
256 {"Collectd::FC_CB_EXEC", FC_CB_EXEC},
257 {"Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH},
258 {"Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES},
259 {"Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE},
260 {"Collectd::FC_TARGET_STOP", FC_TARGET_STOP},
261 {"Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN},
262 {"Collectd::NOTIF_FAILURE", NOTIF_FAILURE},
263 {"Collectd::NOTIF_WARNING", NOTIF_WARNING},
264 {"Collectd::NOTIF_OKAY", NOTIF_OKAY},
265 {"", 0}};
267 struct {
268 char name[64];
269 char *var;
270 } g_strings[] = {{"Collectd::hostname_g", hostname_g}, {"", NULL}};
272 /*
273 * Helper functions for data type conversion.
274 */
276 /*
277 * data source:
278 * [
279 * {
280 * name => $ds_name,
281 * type => $ds_type,
282 * min => $ds_min,
283 * max => $ds_max
284 * },
285 * ...
286 * ]
287 */
288 static int hv2data_source(pTHX_ HV *hash, data_source_t *ds) {
289 SV **tmp = NULL;
291 if ((NULL == hash) || (NULL == ds))
292 return -1;
294 if (NULL != (tmp = hv_fetch(hash, "name", 4, 0))) {
295 sstrncpy(ds->name, SvPV_nolen(*tmp), sizeof(ds->name));
296 } else {
297 log_err("hv2data_source: No DS name given.");
298 return -1;
299 }
301 if (NULL != (tmp = hv_fetch(hash, "type", 4, 0))) {
302 ds->type = SvIV(*tmp);
304 if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type) &&
305 (DS_TYPE_DERIVE != ds->type) && (DS_TYPE_ABSOLUTE != ds->type)) {
306 log_err("hv2data_source: Invalid DS type.");
307 return -1;
308 }
309 } else {
310 ds->type = DS_TYPE_COUNTER;
311 }
313 if (NULL != (tmp = hv_fetch(hash, "min", 3, 0)))
314 ds->min = SvNV(*tmp);
315 else
316 ds->min = NAN;
318 if (NULL != (tmp = hv_fetch(hash, "max", 3, 0)))
319 ds->max = SvNV(*tmp);
320 else
321 ds->max = NAN;
322 return 0;
323 } /* static int hv2data_source (HV *, data_source_t *) */
325 /* av2value converts at most "len" elements from "array" to "value". Returns the
326 * number of elements converted or zero on error. */
327 static size_t av2value(pTHX_ char *name, AV *array, value_t *value,
328 size_t array_len) {
329 const data_set_t *ds;
331 if ((NULL == name) || (NULL == array) || (NULL == value) || (array_len == 0))
332 return 0;
334 ds = plugin_get_ds(name);
335 if (NULL == ds) {
336 log_err("av2value: Unknown dataset \"%s\"", name);
337 return 0;
338 }
340 if (array_len < ds->ds_num) {
341 log_warn("av2value: array does not contain enough elements for type "
342 "\"%s\": got %zu, want %zu",
343 name, array_len, ds->ds_num);
344 return 0;
345 } else if (array_len > ds->ds_num) {
346 log_warn("av2value: array contains excess elements for type \"%s\": got "
347 "%zu, want %zu",
348 name, array_len, ds->ds_num);
349 }
351 for (size_t i = 0; i < ds->ds_num; ++i) {
352 SV **tmp = av_fetch(array, i, 0);
354 if (NULL != tmp) {
355 if (DS_TYPE_COUNTER == ds->ds[i].type)
356 value[i].counter = SvIV(*tmp);
357 else if (DS_TYPE_GAUGE == ds->ds[i].type)
358 value[i].gauge = SvNV(*tmp);
359 else if (DS_TYPE_DERIVE == ds->ds[i].type)
360 value[i].derive = SvIV(*tmp);
361 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
362 value[i].absolute = SvIV(*tmp);
363 } else {
364 return 0;
365 }
366 }
368 return ds->ds_num;
369 } /* static size_t av2value (char *, AV *, value_t *, size_t) */
371 /*
372 * value list:
373 * {
374 * values => [ @values ],
375 * time => $time,
376 * host => $host,
377 * plugin => $plugin,
378 * plugin_instance => $pinstance,
379 * type_instance => $tinstance,
380 * }
381 */
382 static int hv2value_list(pTHX_ HV *hash, value_list_t *vl) {
383 SV **tmp;
385 if ((NULL == hash) || (NULL == vl))
386 return -1;
388 if (NULL == (tmp = hv_fetch(hash, "type", 4, 0))) {
389 log_err("hv2value_list: No type given.");
390 return -1;
391 }
393 sstrncpy(vl->type, SvPV_nolen(*tmp), sizeof(vl->type));
395 if ((NULL == (tmp = hv_fetch(hash, "values", 6, 0))) ||
396 (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp)))))) {
397 log_err("hv2value_list: No valid values given.");
398 return -1;
399 }
401 {
402 AV *array = (AV *)SvRV(*tmp);
403 /* av_len returns the highest index, not the actual length. */
404 size_t array_len = (size_t)(av_len(array) + 1);
405 if (array_len == 0)
406 return -1;
408 vl->values = calloc(array_len, sizeof(*vl->values));
409 vl->values_len =
410 av2value(aTHX_ vl->type, (AV *)SvRV(*tmp), vl->values, array_len);
411 if (vl->values_len == 0) {
412 sfree(vl->values);
413 return -1;
414 }
415 }
417 if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
418 double t = SvNV(*tmp);
419 vl->time = DOUBLE_TO_CDTIME_T(t);
420 }
422 if (NULL != (tmp = hv_fetch(hash, "interval", 8, 0))) {
423 double t = SvNV(*tmp);
424 vl->interval = DOUBLE_TO_CDTIME_T(t);
425 }
427 if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
428 sstrncpy(vl->host, SvPV_nolen(*tmp), sizeof(vl->host));
429 else
430 sstrncpy(vl->host, hostname_g, sizeof(vl->host));
432 if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
433 sstrncpy(vl->plugin, SvPV_nolen(*tmp), sizeof(vl->plugin));
435 if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
436 sstrncpy(vl->plugin_instance, SvPV_nolen(*tmp),
437 sizeof(vl->plugin_instance));
439 if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
440 sstrncpy(vl->type_instance, SvPV_nolen(*tmp), sizeof(vl->type_instance));
441 return 0;
442 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
444 static int av2data_set(pTHX_ AV *array, char *name, data_set_t *ds) {
445 int len;
447 if ((NULL == array) || (NULL == name) || (NULL == ds))
448 return -1;
450 len = av_len(array);
452 if (-1 == len) {
453 log_err("av2data_set: Invalid data set.");
454 return -1;
455 }
457 ds->ds = smalloc((len + 1) * sizeof(*ds->ds));
458 ds->ds_num = len + 1;
460 for (int i = 0; i <= len; ++i) {
461 SV **elem = av_fetch(array, i, 0);
463 if (NULL == elem) {
464 log_err("av2data_set: Failed to fetch data source %i.", i);
465 return -1;
466 }
468 if (!(SvROK(*elem) && (SVt_PVHV == SvTYPE(SvRV(*elem))))) {
469 log_err("av2data_set: Invalid data source.");
470 return -1;
471 }
473 if (-1 == hv2data_source(aTHX_(HV *) SvRV(*elem), &ds->ds[i]))
474 return -1;
476 log_debug("av2data_set: "
477 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
478 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
479 }
481 sstrncpy(ds->type, name, sizeof(ds->type));
482 return 0;
483 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
485 /*
486 * notification:
487 * {
488 * severity => $severity,
489 * time => $time,
490 * message => $msg,
491 * host => $host,
492 * plugin => $plugin,
493 * type => $type,
494 * plugin_instance => $instance,
495 * type_instance => $type_instance,
496 * meta => [ { name => <name>, value => <value> }, ... ]
497 * }
498 */
499 static int av2notification_meta(pTHX_ AV *array, notification_meta_t **ret_meta) {
500 notification_meta_t *tail = NULL;
502 int len = av_len(array);
504 for (int i = 0; i <= len; ++i) {
505 SV **tmp = av_fetch(array, i, 0);
507 if (tmp == NULL)
508 return -1;
510 if (!(SvROK(*tmp) && (SVt_PVHV == SvTYPE(SvRV(*tmp))))) {
511 log_warn("av2notification_meta: Skipping invalid "
512 "meta information.");
513 continue;
514 }
516 HV *hash = (HV *)SvRV(*tmp);
518 notification_meta_t *m = calloc(1, sizeof(*m));
519 if (m == NULL)
520 return ENOMEM;
522 SV **name = hv_fetch(hash, "name", strlen("name"), 0);
523 if (name == NULL) {
524 log_warn("av2notification_meta: Skipping invalid "
525 "meta information.");
526 sfree(m);
527 continue;
528 }
529 sstrncpy(m->name, SvPV_nolen(*name), sizeof(m->name));
531 SV **value = hv_fetch(hash, "value", strlen("value"), 0);
532 if (value == NULL) {
533 log_warn("av2notification_meta: Skipping invalid "
534 "meta information.");
535 sfree(m);
536 continue;
537 }
539 if (SvNOK(*value)) {
540 m->nm_value.nm_double = SvNVX(*value);
541 m->type = NM_TYPE_DOUBLE;
542 } else if (SvUOK(*value)) {
543 m->nm_value.nm_unsigned_int = SvUVX(*value);
544 m->type = NM_TYPE_UNSIGNED_INT;
545 } else if (SvIOK(*value)) {
546 m->nm_value.nm_signed_int = SvIVX(*value);
547 m->type = NM_TYPE_SIGNED_INT;
548 } else {
549 m->nm_value.nm_string = sstrdup(SvPV_nolen(*value));
550 m->type = NM_TYPE_STRING;
551 }
553 m->next = NULL;
554 if (tail == NULL)
555 *ret_meta = m;
556 else
557 tail->next = m;
558 tail = m;
559 }
561 return 0;
562 } /* static int av2notification_meta (AV *, notification_meta_t *) */
564 static int hv2notification(pTHX_ HV *hash, notification_t *n) {
565 SV **tmp = NULL;
567 if ((NULL == hash) || (NULL == n))
568 return -1;
570 if (NULL != (tmp = hv_fetch(hash, "severity", 8, 0)))
571 n->severity = SvIV(*tmp);
572 else
573 n->severity = NOTIF_FAILURE;
575 if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
576 double t = SvNV(*tmp);
577 n->time = DOUBLE_TO_CDTIME_T(t);
578 } else
579 n->time = cdtime();
581 if (NULL != (tmp = hv_fetch(hash, "message", 7, 0)))
582 sstrncpy(n->message, SvPV_nolen(*tmp), sizeof(n->message));
584 if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
585 sstrncpy(n->host, SvPV_nolen(*tmp), sizeof(n->host));
586 else
587 sstrncpy(n->host, hostname_g, sizeof(n->host));
589 if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
590 sstrncpy(n->plugin, SvPV_nolen(*tmp), sizeof(n->plugin));
592 if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
593 sstrncpy(n->plugin_instance, SvPV_nolen(*tmp), sizeof(n->plugin_instance));
595 if (NULL != (tmp = hv_fetch(hash, "type", 4, 0)))
596 sstrncpy(n->type, SvPV_nolen(*tmp), sizeof(n->type));
598 if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
599 sstrncpy(n->type_instance, SvPV_nolen(*tmp), sizeof(n->type_instance));
601 n->meta = NULL;
602 while (NULL != (tmp = hv_fetch(hash, "meta", 4, 0))) {
603 if (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp))))) {
604 log_warn("hv2notification: Ignoring invalid meta information.");
605 break;
606 }
608 if (0 != av2notification_meta(aTHX_(AV *) SvRV(*tmp), &n->meta)) {
609 plugin_notification_meta_free(n->meta);
610 n->meta = NULL;
611 return -1;
612 }
613 break;
614 }
615 return 0;
616 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
618 static int data_set2av(pTHX_ data_set_t *ds, AV *array) {
619 if ((NULL == ds) || (NULL == array))
620 return -1;
622 av_extend(array, ds->ds_num);
624 for (size_t i = 0; i < ds->ds_num; ++i) {
625 HV *source = newHV();
627 if (NULL == hv_store(source, "name", 4, newSVpv(ds->ds[i].name, 0), 0))
628 return -1;
630 if (NULL == hv_store(source, "type", 4, newSViv(ds->ds[i].type), 0))
631 return -1;
633 if (!isnan(ds->ds[i].min))
634 if (NULL == hv_store(source, "min", 3, newSVnv(ds->ds[i].min), 0))
635 return -1;
637 if (!isnan(ds->ds[i].max))
638 if (NULL == hv_store(source, "max", 3, newSVnv(ds->ds[i].max), 0))
639 return -1;
641 if (NULL == av_store(array, i, newRV_noinc((SV *)source)))
642 return -1;
643 }
644 return 0;
645 } /* static int data_set2av (data_set_t *, AV *) */
647 static int value_list2hv(pTHX_ value_list_t *vl, data_set_t *ds, HV *hash) {
648 AV *values = NULL;
649 size_t i;
651 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
652 return -1;
654 values = newAV();
655 /* av_extend takes the last *index* to which the array should be extended. */
656 av_extend(values, vl->values_len - 1);
658 assert(ds->ds_num == vl->values_len);
659 for (i = 0; i < vl->values_len; ++i) {
660 SV *val = NULL;
662 if (DS_TYPE_COUNTER == ds->ds[i].type)
663 val = newSViv(vl->values[i].counter);
664 else if (DS_TYPE_GAUGE == ds->ds[i].type)
665 val = newSVnv(vl->values[i].gauge);
666 else if (DS_TYPE_DERIVE == ds->ds[i].type)
667 val = newSViv(vl->values[i].derive);
668 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
669 val = newSViv(vl->values[i].absolute);
671 if (NULL == av_store(values, i, val)) {
672 av_undef(values);
673 return -1;
674 }
675 }
677 if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0))
678 return -1;
680 if (0 != vl->time) {
681 double t = CDTIME_T_TO_DOUBLE(vl->time);
682 if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
683 return -1;
684 }
686 {
687 double t = CDTIME_T_TO_DOUBLE(vl->interval);
688 if (NULL == hv_store(hash, "interval", 8, newSVnv(t), 0))
689 return -1;
690 }
692 if ('\0' != vl->host[0])
693 if (NULL == hv_store(hash, "host", 4, newSVpv(vl->host, 0), 0))
694 return -1;
696 if ('\0' != vl->plugin[0])
697 if (NULL == hv_store(hash, "plugin", 6, newSVpv(vl->plugin, 0), 0))
698 return -1;
700 if ('\0' != vl->plugin_instance[0])
701 if (NULL == hv_store(hash, "plugin_instance", 15,
702 newSVpv(vl->plugin_instance, 0), 0))
703 return -1;
705 if ('\0' != vl->type[0])
706 if (NULL == hv_store(hash, "type", 4, newSVpv(vl->type, 0), 0))
707 return -1;
709 if ('\0' != vl->type_instance[0])
710 if (NULL ==
711 hv_store(hash, "type_instance", 13, newSVpv(vl->type_instance, 0), 0))
712 return -1;
713 return 0;
714 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
716 static int notification_meta2av(pTHX_ notification_meta_t *meta, AV *array) {
717 int meta_num = 0;
719 while (meta) {
720 ++meta_num;
721 meta = meta->next;
722 }
724 av_extend(array, meta_num);
726 for (int i = 0; NULL != meta; meta = meta->next, ++i) {
727 HV *m = newHV();
728 SV *value;
730 if (NULL == hv_store(m, "name", 4, newSVpv(meta->name, 0), 0))
731 return -1;
733 if (NM_TYPE_STRING == meta->type)
734 value = newSVpv(meta->nm_value.nm_string, 0);
735 else if (NM_TYPE_SIGNED_INT == meta->type)
736 value = newSViv(meta->nm_value.nm_signed_int);
737 else if (NM_TYPE_UNSIGNED_INT == meta->type)
738 value = newSVuv(meta->nm_value.nm_unsigned_int);
739 else if (NM_TYPE_DOUBLE == meta->type)
740 value = newSVnv(meta->nm_value.nm_double);
741 else if (NM_TYPE_BOOLEAN == meta->type)
742 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
743 else
744 return -1;
746 if (NULL == hv_store(m, "value", 5, value, 0)) {
747 sv_free(value);
748 return -1;
749 }
751 if (NULL == av_store(array, i, newRV_noinc((SV *)m))) {
752 hv_clear(m);
753 hv_undef(m);
754 return -1;
755 }
756 }
757 return 0;
758 } /* static int notification_meta2av (notification_meta_t *, AV *) */
760 static int notification2hv(pTHX_ notification_t *n, HV *hash) {
761 if (NULL == hv_store(hash, "severity", 8, newSViv(n->severity), 0))
762 return -1;
764 if (0 != n->time) {
765 double t = CDTIME_T_TO_DOUBLE(n->time);
766 if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
767 return -1;
768 }
770 if ('\0' != *n->message)
771 if (NULL == hv_store(hash, "message", 7, newSVpv(n->message, 0), 0))
772 return -1;
774 if ('\0' != *n->host)
775 if (NULL == hv_store(hash, "host", 4, newSVpv(n->host, 0), 0))
776 return -1;
778 if ('\0' != *n->plugin)
779 if (NULL == hv_store(hash, "plugin", 6, newSVpv(n->plugin, 0), 0))
780 return -1;
782 if ('\0' != *n->plugin_instance)
783 if (NULL == hv_store(hash, "plugin_instance", 15,
784 newSVpv(n->plugin_instance, 0), 0))
785 return -1;
787 if ('\0' != *n->type)
788 if (NULL == hv_store(hash, "type", 4, newSVpv(n->type, 0), 0))
789 return -1;
791 if ('\0' != *n->type_instance)
792 if (NULL ==
793 hv_store(hash, "type_instance", 13, newSVpv(n->type_instance, 0), 0))
794 return -1;
796 if (NULL != n->meta) {
797 AV *meta = newAV();
798 if ((0 != notification_meta2av(aTHX_ n->meta, meta)) ||
799 (NULL == hv_store(hash, "meta", 4, newRV_noinc((SV *)meta), 0))) {
800 av_clear(meta);
801 av_undef(meta);
802 return -1;
803 }
804 }
805 return 0;
806 } /* static int notification2hv (notification_t *, HV *) */
808 static int oconfig_item2hv(pTHX_ oconfig_item_t *ci, HV *hash) {
809 AV *values;
810 AV *children;
812 if (NULL == hv_store(hash, "key", 3, newSVpv(ci->key, 0), 0))
813 return -1;
815 values = newAV();
816 if (0 < ci->values_num)
817 av_extend(values, ci->values_num);
819 if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0)) {
820 av_clear(values);
821 av_undef(values);
822 return -1;
823 }
825 for (int i = 0; i < ci->values_num; ++i) {
826 SV *value;
828 switch (ci->values[i].type) {
829 case OCONFIG_TYPE_STRING:
830 value = newSVpv(ci->values[i].value.string, 0);
831 break;
832 case OCONFIG_TYPE_NUMBER:
833 value = newSVnv((NV)ci->values[i].value.number);
834 break;
835 case OCONFIG_TYPE_BOOLEAN:
836 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
837 break;
838 default:
839 log_err("oconfig_item2hv: Invalid value type %i.", ci->values[i].type);
840 value = &PL_sv_undef;
841 }
843 if (NULL == av_store(values, i, value)) {
844 sv_free(value);
845 return -1;
846 }
847 }
849 /* ignoring 'parent' member which is uninteresting in this case */
851 children = newAV();
852 if (0 < ci->children_num)
853 av_extend(children, ci->children_num);
855 if (NULL == hv_store(hash, "children", 8, newRV_noinc((SV *)children), 0)) {
856 av_clear(children);
857 av_undef(children);
858 return -1;
859 }
861 for (int i = 0; i < ci->children_num; ++i) {
862 HV *child = newHV();
864 if (0 != oconfig_item2hv(aTHX_ ci->children + i, child)) {
865 hv_clear(child);
866 hv_undef(child);
867 return -1;
868 }
870 if (NULL == av_store(children, i, newRV_noinc((SV *)child))) {
871 hv_clear(child);
872 hv_undef(child);
873 return -1;
874 }
875 }
876 return 0;
877 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
879 /*
880 * Internal functions.
881 */
883 static char *get_module_name(char *buf, size_t buf_len, const char *module) {
884 int status = 0;
885 if (base_name[0] == '\0')
886 status = ssnprintf(buf, buf_len, "%s", module);
887 else
888 status = ssnprintf(buf, buf_len, "%s::%s", base_name, module);
889 if ((status < 0) || ((unsigned int)status >= buf_len))
890 return (NULL);
891 return (buf);
892 } /* char *get_module_name */
894 /*
895 * Add a plugin's data set definition.
896 */
897 static int pplugin_register_data_set(pTHX_ char *name, AV *dataset) {
898 int ret = 0;
900 data_set_t ds;
902 if ((NULL == name) || (NULL == dataset))
903 return -1;
905 if (0 != av2data_set(aTHX_ dataset, name, &ds))
906 return -1;
908 ret = plugin_register_data_set(&ds);
910 free(ds.ds);
911 return ret;
912 } /* static int pplugin_register_data_set (char *, SV *) */
914 /*
915 * Remove a plugin's data set definition.
916 */
917 static int pplugin_unregister_data_set(char *name) {
918 if (NULL == name)
919 return 0;
920 return plugin_unregister_data_set(name);
921 } /* static int pplugin_unregister_data_set (char *) */
923 /*
924 * Submit the values to the write functions.
925 */
926 static int pplugin_dispatch_values(pTHX_ HV *values) {
927 value_list_t vl = VALUE_LIST_INIT;
929 int ret = 0;
931 if (NULL == values)
932 return -1;
934 if (0 != hv2value_list(aTHX_ values, &vl))
935 return -1;
937 ret = plugin_dispatch_values(&vl);
939 sfree(vl.values);
940 return ret;
941 } /* static int pplugin_dispatch_values (char *, HV *) */
943 /*
944 * Submit the values to a single write function.
945 */
946 static int pplugin_write(pTHX_ const char *plugin, AV *data_set, HV *values) {
947 data_set_t ds;
948 value_list_t vl = VALUE_LIST_INIT;
950 int ret;
952 if (NULL == values)
953 return -1;
955 if (0 != hv2value_list(aTHX_ values, &vl))
956 return -1;
958 if ((NULL != data_set) && (0 != av2data_set(aTHX_ data_set, vl.type, &ds)))
959 return -1;
961 ret = plugin_write(plugin, NULL == data_set ? NULL : &ds, &vl);
962 if (0 != ret)
963 log_warn("Dispatching value to plugin \"%s\" failed with status %i.",
964 NULL == plugin ? "<any>" : plugin, ret);
966 if (NULL != data_set)
967 sfree(ds.ds);
968 sfree(vl.values);
969 return ret;
970 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
972 /*
973 * Dispatch a notification.
974 */
975 static int pplugin_dispatch_notification(pTHX_ HV *notif) {
976 notification_t n = {0};
978 int ret;
980 if (NULL == notif)
981 return -1;
983 if (0 != hv2notification(aTHX_ notif, &n))
984 return -1;
986 ret = plugin_dispatch_notification(&n);
987 plugin_notification_meta_free(n.meta);
988 return ret;
989 } /* static int pplugin_dispatch_notification (HV *) */
991 /*
992 * Call perl sub with thread locking flags handled.
993 */
994 static int call_pv_locked(pTHX_ const char *sub_name) {
995 _Bool old_running;
996 int ret;
998 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
999 if (t == NULL) /* thread destroyed */
1000 return 0;
1002 old_running = t->running;
1003 t->running = 1;
1005 if (t->shutdown) {
1006 t->running = old_running;
1007 return 0;
1008 }
1010 ret = call_pv(sub_name, G_SCALAR | G_EVAL);
1012 t->running = old_running;
1013 return ret;
1014 } /* static int call_pv_locked (pTHX, *sub_name) */
1016 /*
1017 * Call all working functions of the given type.
1018 */
1019 static int pplugin_call(pTHX_ int type, ...) {
1020 int retvals = 0;
1022 va_list ap;
1023 int ret = 0;
1024 char *subname;
1026 dSP;
1028 if ((type < 0) || (type >= PLUGIN_TYPES))
1029 return -1;
1031 va_start(ap, type);
1033 ENTER;
1034 SAVETMPS;
1036 PUSHMARK(SP);
1038 if (PLUGIN_READ == type) {
1039 subname = va_arg(ap, char *);
1040 } else if (PLUGIN_WRITE == type) {
1041 data_set_t *ds;
1042 value_list_t *vl;
1044 AV *pds = newAV();
1045 HV *pvl = newHV();
1047 subname = va_arg(ap, char *);
1048 /*
1049 * $_[0] = $plugin_type;
1050 *
1051 * $_[1] =
1052 * [
1053 * {
1054 * name => $ds_name,
1055 * type => $ds_type,
1056 * min => $ds_min,
1057 * max => $ds_max
1058 * },
1059 * ...
1060 * ];
1061 *
1062 * $_[2] =
1063 * {
1064 * values => [ $v1, ... ],
1065 * time => $time,
1066 * host => $hostname,
1067 * plugin => $plugin,
1068 * type => $type,
1069 * plugin_instance => $instance,
1070 * type_instance => $type_instance
1071 * };
1072 */
1073 ds = va_arg(ap, data_set_t *);
1074 vl = va_arg(ap, value_list_t *);
1076 if (-1 == data_set2av(aTHX_ ds, pds)) {
1077 av_clear(pds);
1078 av_undef(pds);
1079 pds = (AV *)&PL_sv_undef;
1080 ret = -1;
1081 }
1083 if (-1 == value_list2hv(aTHX_ vl, ds, pvl)) {
1084 hv_clear(pvl);
1085 hv_undef(pvl);
1086 pvl = (HV *)&PL_sv_undef;
1087 ret = -1;
1088 }
1090 XPUSHs(sv_2mortal(newSVpv(ds->type, 0)));
1091 XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1092 XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1093 } else if (PLUGIN_LOG == type) {
1094 subname = va_arg(ap, char *);
1095 /*
1096 * $_[0] = $level;
1097 *
1098 * $_[1] = $message;
1099 */
1100 XPUSHs(sv_2mortal(newSViv(va_arg(ap, int))));
1101 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1102 } else if (PLUGIN_NOTIF == type) {
1103 notification_t *n;
1104 HV *notif = newHV();
1106 subname = va_arg(ap, char *);
1107 /*
1108 * $_[0] =
1109 * {
1110 * severity => $severity,
1111 * time => $time,
1112 * message => $msg,
1113 * host => $host,
1114 * plugin => $plugin,
1115 * type => $type,
1116 * plugin_instance => $instance,
1117 * type_instance => $type_instance
1118 * };
1119 */
1120 n = va_arg(ap, notification_t *);
1122 if (-1 == notification2hv(aTHX_ n, notif)) {
1123 hv_clear(notif);
1124 hv_undef(notif);
1125 notif = (HV *)&PL_sv_undef;
1126 ret = -1;
1127 }
1129 XPUSHs(sv_2mortal(newRV_noinc((SV *)notif)));
1130 } else if (PLUGIN_FLUSH == type) {
1131 cdtime_t timeout;
1132 subname = va_arg(ap, char *);
1133 /*
1134 * $_[0] = $timeout;
1135 * $_[1] = $identifier;
1136 */
1137 timeout = va_arg(ap, cdtime_t);
1139 XPUSHs(sv_2mortal(newSVnv(CDTIME_T_TO_DOUBLE(timeout))));
1140 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1141 } else if (PLUGIN_FLUSH_ALL == type) {
1142 cdtime_t timeout;
1143 subname = "Collectd::plugin_call_all";
1144 /*
1145 * $_[0] = $timeout;
1146 * $_[1] = $identifier;
1147 */
1148 timeout = va_arg(ap, cdtime_t);
1150 XPUSHs(sv_2mortal(newSViv((IV)PLUGIN_FLUSH)));
1151 XPUSHs(sv_2mortal(newSVnv(CDTIME_T_TO_DOUBLE(timeout))));
1152 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1153 } else if (PLUGIN_INIT == type) {
1154 subname = "Collectd::plugin_call_all";
1155 XPUSHs(sv_2mortal(newSViv((IV)type)));
1156 } else if (PLUGIN_SHUTDOWN == type) {
1157 subname = "Collectd::plugin_call_all";
1158 XPUSHs(sv_2mortal(newSViv((IV)type)));
1159 } else { /* Unknown type. Run 'plugin_call_all' and make compiler happy */
1160 subname = "Collectd::plugin_call_all";
1161 XPUSHs(sv_2mortal(newSViv((IV)type)));
1162 }
1164 PUTBACK;
1166 retvals = call_pv_locked(aTHX_ subname);
1168 SPAGAIN;
1169 if (SvTRUE(ERRSV)) {
1170 if (PLUGIN_LOG != type)
1171 ERROR("perl: %s error: %s", subname, SvPV_nolen(ERRSV));
1172 ret = -1;
1173 } else if (0 < retvals) {
1174 SV *tmp = POPs;
1175 if (!SvTRUE(tmp))
1176 ret = -1;
1177 }
1179 PUTBACK;
1180 FREETMPS;
1181 LEAVE;
1183 va_end(ap);
1184 return ret;
1185 } /* static int pplugin_call (int, ...) */
1187 /*
1188 * collectd's Perl interpreter based thread implementation.
1189 *
1190 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1191 */
1193 /* must be called with perl_threads->mutex locked */
1194 static void c_ithread_destroy(c_ithread_t *ithread) {
1195 dTHXa(ithread->interp);
1197 assert(NULL != perl_threads);
1199 PERL_SET_CONTEXT(aTHX);
1200 /* Mark as running to avoid deadlock:
1201 c_ithread_destroy -> log_debug -> perl_log()
1202 */
1203 ithread->running = 1;
1204 log_debug("Shutting down Perl interpreter %p...", aTHX);
1206 #if COLLECT_DEBUG
1207 sv_report_used();
1209 --perl_threads->number_of_threads;
1210 #endif /* COLLECT_DEBUG */
1212 perl_destruct(aTHX);
1213 perl_free(aTHX);
1215 if (NULL == ithread->prev)
1216 perl_threads->head = ithread->next;
1217 else
1218 ithread->prev->next = ithread->next;
1220 if (NULL == ithread->next)
1221 perl_threads->tail = ithread->prev;
1222 else
1223 ithread->next->prev = ithread->prev;
1225 sfree(ithread);
1226 return;
1227 } /* static void c_ithread_destroy (c_ithread_t *) */
1229 static void c_ithread_destructor(void *arg) {
1230 c_ithread_t *ithread = (c_ithread_t *)arg;
1231 c_ithread_t *t = NULL;
1233 if (NULL == perl_threads)
1234 return;
1236 pthread_mutex_lock(&perl_threads->mutex);
1238 for (t = perl_threads->head; NULL != t; t = t->next)
1239 if (t == ithread)
1240 break;
1242 /* the ithread no longer exists */
1243 if (NULL == t) {
1244 pthread_mutex_unlock(&perl_threads->mutex);
1245 return;
1246 }
1248 c_ithread_destroy(ithread);
1250 pthread_mutex_unlock(&perl_threads->mutex);
1251 return;
1252 } /* static void c_ithread_destructor (void *) */
1254 /* must be called with perl_threads->mutex locked */
1255 static c_ithread_t *c_ithread_create(PerlInterpreter *base) {
1256 c_ithread_t *t = NULL;
1257 dTHXa(NULL);
1259 assert(NULL != perl_threads);
1261 t = smalloc(sizeof(*t));
1262 memset(t, 0, sizeof(c_ithread_t));
1264 t->interp = (NULL == base) ? NULL : perl_clone(base, CLONEf_KEEP_PTR_TABLE);
1266 aTHX = t->interp;
1268 if ((NULL != base) && (NULL != PL_endav)) {
1269 av_clear(PL_endav);
1270 av_undef(PL_endav);
1271 PL_endav = Nullav;
1272 }
1274 #if COLLECT_DEBUG
1275 ++perl_threads->number_of_threads;
1276 #endif /* COLLECT_DEBUG */
1278 t->next = NULL;
1280 if (NULL == perl_threads->tail) {
1281 perl_threads->head = t;
1282 t->prev = NULL;
1283 } else {
1284 perl_threads->tail->next = t;
1285 t->prev = perl_threads->tail;
1286 }
1288 t->pthread = pthread_self();
1289 t->running = 0;
1290 t->shutdown = 0;
1291 perl_threads->tail = t;
1293 pthread_setspecific(perl_thr_key, (const void *)t);
1294 return t;
1295 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1297 /*
1298 * Filter chains implementation.
1299 */
1301 static int fc_call(pTHX_ int type, int cb_type, pfc_user_data_t *data, ...) {
1302 int retvals = 0;
1304 va_list ap;
1305 int ret = 0;
1307 notification_meta_t **meta = NULL;
1308 AV *pmeta = NULL;
1310 dSP;
1312 if ((type < 0) || (type >= FC_TYPES))
1313 return -1;
1315 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1316 return -1;
1318 va_start(ap, data);
1320 ENTER;
1321 SAVETMPS;
1323 PUSHMARK(SP);
1325 XPUSHs(sv_2mortal(newSViv((IV)type)));
1326 XPUSHs(sv_2mortal(newSVpv(data->name, 0)));
1327 XPUSHs(sv_2mortal(newSViv((IV)cb_type)));
1329 if (FC_CB_CREATE == cb_type) {
1330 /*
1331 * $_[0] = $ci;
1332 * $_[1] = $user_data;
1333 */
1334 oconfig_item_t *ci;
1335 HV *config = newHV();
1337 ci = va_arg(ap, oconfig_item_t *);
1339 if (0 != oconfig_item2hv(aTHX_ ci, config)) {
1340 hv_clear(config);
1341 hv_undef(config);
1342 config = (HV *)&PL_sv_undef;
1343 ret = -1;
1344 }
1346 XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
1347 } else if (FC_CB_DESTROY == cb_type) {
1348 /*
1349 * $_[1] = $user_data;
1350 */
1352 /* nothing to be done - the user data pointer
1353 * is pushed onto the stack later */
1354 } else if (FC_CB_EXEC == cb_type) {
1355 /*
1356 * $_[0] = $ds;
1357 * $_[1] = $vl;
1358 * $_[2] = $meta;
1359 * $_[3] = $user_data;
1360 */
1361 data_set_t *ds;
1362 value_list_t *vl;
1364 AV *pds = newAV();
1365 HV *pvl = newHV();
1367 ds = va_arg(ap, data_set_t *);
1368 vl = va_arg(ap, value_list_t *);
1369 meta = va_arg(ap, notification_meta_t **);
1371 if (0 != data_set2av(aTHX_ ds, pds)) {
1372 av_clear(pds);
1373 av_undef(pds);
1374 pds = (AV *)&PL_sv_undef;
1375 ret = -1;
1376 }
1378 if (0 != value_list2hv(aTHX_ vl, ds, pvl)) {
1379 hv_clear(pvl);
1380 hv_undef(pvl);
1381 pvl = (HV *)&PL_sv_undef;
1382 ret = -1;
1383 }
1385 if (NULL != meta) {
1386 pmeta = newAV();
1388 if (0 != notification_meta2av(aTHX_ * meta, pmeta)) {
1389 av_clear(pmeta);
1390 av_undef(pmeta);
1391 pmeta = (AV *)&PL_sv_undef;
1392 ret = -1;
1393 }
1394 } else {
1395 pmeta = (AV *)&PL_sv_undef;
1396 }
1398 XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1399 XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1400 XPUSHs(sv_2mortal(newRV_noinc((SV *)pmeta)));
1401 }
1403 XPUSHs(sv_2mortal(newRV_inc(data->user_data)));
1405 PUTBACK;
1407 retvals = call_pv_locked(aTHX_ "Collectd::fc_call");
1409 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1410 assert(pmeta != NULL);
1412 plugin_notification_meta_free(*meta);
1413 av2notification_meta(aTHX_ pmeta, meta);
1414 }
1416 SPAGAIN;
1417 if (SvTRUE(ERRSV)) {
1418 ERROR("perl: Collectd::fc_call error: %s", SvPV_nolen(ERRSV));
1419 ret = -1;
1420 } else if (0 < retvals) {
1421 SV *tmp = POPs;
1423 /* the exec callbacks return a status, while
1424 * the others return a boolean value */
1425 if (FC_CB_EXEC == cb_type)
1426 ret = SvIV(tmp);
1427 else if (!SvTRUE(tmp))
1428 ret = -1;
1429 }
1431 PUTBACK;
1432 FREETMPS;
1433 LEAVE;
1435 va_end(ap);
1436 return ret;
1437 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1439 static int fc_create(int type, const oconfig_item_t *ci, void **user_data) {
1440 pfc_user_data_t *data;
1442 int ret = 0;
1444 dTHX;
1446 if (NULL == perl_threads)
1447 return 0;
1449 if (NULL == aTHX) {
1450 c_ithread_t *t = NULL;
1452 pthread_mutex_lock(&perl_threads->mutex);
1453 t = c_ithread_create(perl_threads->head->interp);
1454 pthread_mutex_unlock(&perl_threads->mutex);
1456 aTHX = t->interp;
1457 }
1459 log_debug("fc_create: c_ithread: interp = %p (active threads: %i)", aTHX,
1460 perl_threads->number_of_threads);
1462 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1463 log_warn("A \"%s\" block expects a single string argument.",
1464 (FC_MATCH == type) ? "Match" : "Target");
1465 return -1;
1466 }
1468 data = smalloc(sizeof(*data));
1469 data->name = sstrdup(ci->values[0].value.string);
1470 data->user_data = newSV(0);
1472 ret = fc_call(aTHX_ type, FC_CB_CREATE, data, ci);
1474 if (0 != ret)
1475 PFC_USER_DATA_FREE(data);
1476 else
1477 *user_data = data;
1478 return ret;
1479 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1481 static int fc_destroy(int type, void **user_data) {
1482 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1484 int ret = 0;
1486 dTHX;
1488 if ((NULL == perl_threads) || (NULL == data))
1489 return 0;
1491 if (NULL == aTHX) {
1492 c_ithread_t *t = NULL;
1494 pthread_mutex_lock(&perl_threads->mutex);
1495 t = c_ithread_create(perl_threads->head->interp);
1496 pthread_mutex_unlock(&perl_threads->mutex);
1498 aTHX = t->interp;
1499 }
1501 log_debug("fc_destroy: c_ithread: interp = %p (active threads: %i)", aTHX,
1502 perl_threads->number_of_threads);
1504 ret = fc_call(aTHX_ type, FC_CB_DESTROY, data);
1506 PFC_USER_DATA_FREE(data);
1507 *user_data = NULL;
1508 return ret;
1509 } /* static int fc_destroy (int, void **) */
1511 static int fc_exec(int type, const data_set_t *ds, const value_list_t *vl,
1512 notification_meta_t **meta, void **user_data) {
1513 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1515 dTHX;
1517 if (NULL == perl_threads)
1518 return 0;
1520 assert(NULL != data);
1522 if (NULL == aTHX) {
1523 c_ithread_t *t = NULL;
1525 pthread_mutex_lock(&perl_threads->mutex);
1526 t = c_ithread_create(perl_threads->head->interp);
1527 pthread_mutex_unlock(&perl_threads->mutex);
1529 aTHX = t->interp;
1530 }
1532 log_debug("fc_exec: c_ithread: interp = %p (active threads: %i)", aTHX,
1533 perl_threads->number_of_threads);
1535 return fc_call(aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1536 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1537 notification_meta_t **, void **) */
1539 static int pmatch_create(const oconfig_item_t *ci, void **user_data) {
1540 return fc_create(FC_MATCH, ci, user_data);
1541 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1543 static int pmatch_destroy(void **user_data) {
1544 return fc_destroy(FC_MATCH, user_data);
1545 } /* static int pmatch_destroy (void **) */
1547 static int pmatch_match(const data_set_t *ds, const value_list_t *vl,
1548 notification_meta_t **meta, void **user_data) {
1549 return fc_exec(FC_MATCH, ds, vl, meta, user_data);
1550 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1551 notification_meta_t **, void **) */
1553 static match_proc_t pmatch = {pmatch_create, pmatch_destroy, pmatch_match};
1555 static int ptarget_create(const oconfig_item_t *ci, void **user_data) {
1556 return fc_create(FC_TARGET, ci, user_data);
1557 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1559 static int ptarget_destroy(void **user_data) {
1560 return fc_destroy(FC_TARGET, user_data);
1561 } /* static int ptarget_destroy (void **) */
1563 static int ptarget_invoke(const data_set_t *ds, value_list_t *vl,
1564 notification_meta_t **meta, void **user_data) {
1565 return fc_exec(FC_TARGET, ds, vl, meta, user_data);
1566 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1567 notification_meta_t **, void **) */
1569 static target_proc_t ptarget = {ptarget_create, ptarget_destroy,
1570 ptarget_invoke};
1572 /*
1573 * Exported Perl API.
1574 */
1576 static void _plugin_register_generic_userdata(pTHX, int type,
1577 const char *desc) {
1578 int ret = 0;
1579 user_data_t userdata;
1580 char *pluginname;
1582 dXSARGS;
1584 if (2 != items) {
1585 log_err("Usage: Collectd::plugin_register_%s(pluginname, subname)", desc);
1586 XSRETURN_EMPTY;
1587 }
1589 if (!SvOK(ST(0))) {
1590 log_err("Collectd::plugin_register_%s(pluginname, subname): "
1591 "Invalid pluginname",
1592 desc);
1593 XSRETURN_EMPTY;
1594 }
1595 if (!SvOK(ST(1))) {
1596 log_err("Collectd::plugin_register_%s(pluginname, subname): "
1597 "Invalid subname",
1598 desc);
1599 XSRETURN_EMPTY;
1600 }
1602 /* Use pluginname as-is to allow flush a single perl plugin */
1603 pluginname = SvPV_nolen(ST(0));
1605 log_debug("Collectd::plugin_register_%s: "
1606 "plugin = \"%s\", sub = \"%s\"",
1607 desc, pluginname, SvPV_nolen(ST(1)));
1609 memset(&userdata, 0, sizeof(userdata));
1610 userdata.data = strdup(SvPV_nolen(ST(1)));
1611 userdata.free_func = free;
1613 if (PLUGIN_READ == type) {
1614 ret = plugin_register_complex_read(
1615 "perl", /* group */
1616 pluginname, perl_read, plugin_get_interval(), /* Default interval */
1617 &userdata);
1618 } else if (PLUGIN_WRITE == type) {
1619 ret = plugin_register_write(pluginname, perl_write, &userdata);
1620 } else if (PLUGIN_LOG == type) {
1621 ret = plugin_register_log(pluginname, perl_log, &userdata);
1622 } else if (PLUGIN_NOTIF == type) {
1623 ret = plugin_register_notification(pluginname, perl_notify, &userdata);
1624 } else if (PLUGIN_FLUSH == type) {
1625 if (1 == register_legacy_flush) { /* For collectd-5.7 only, #1731 */
1626 register_legacy_flush = 0;
1627 ret = plugin_register_flush("perl", perl_flush, /* user_data = */ NULL);
1628 }
1630 if (0 == ret)
1631 ret = plugin_register_flush(pluginname, perl_flush, &userdata);
1632 } else {
1633 ret = -1;
1634 }
1636 if (0 == ret)
1637 XSRETURN_YES;
1638 else {
1639 free(userdata.data);
1640 XSRETURN_EMPTY;
1641 }
1642 } /* static void _plugin_register_generic_userdata ( ... ) */
1644 /*
1645 * Collectd::plugin_register_TYPE (pluginname, subname).
1646 *
1647 * pluginname:
1648 * name of the perl plugin
1649 *
1650 * subname:
1651 * name of the plugin's subroutine that does the work
1652 */
1654 static XS(Collectd_plugin_register_read) {
1655 return _plugin_register_generic_userdata(aTHX, PLUGIN_READ, "read");
1656 }
1658 static XS(Collectd_plugin_register_write) {
1659 return _plugin_register_generic_userdata(aTHX, PLUGIN_WRITE, "write");
1660 }
1662 static XS(Collectd_plugin_register_log) {
1663 return _plugin_register_generic_userdata(aTHX, PLUGIN_LOG, "log");
1664 }
1666 static XS(Collectd_plugin_register_notification) {
1667 return _plugin_register_generic_userdata(aTHX, PLUGIN_NOTIF, "notification");
1668 }
1670 static XS(Collectd_plugin_register_flush) {
1671 return _plugin_register_generic_userdata(aTHX, PLUGIN_FLUSH, "flush");
1672 }
1674 typedef int perl_unregister_function_t(const char *name);
1676 static void _plugin_unregister_generic(pTHX, perl_unregister_function_t *unreg,
1677 const char *desc) {
1678 dXSARGS;
1680 if (1 != items) {
1681 log_err("Usage: Collectd::plugin_unregister_%s(pluginname)", desc);
1682 XSRETURN_EMPTY;
1683 }
1685 if (!SvOK(ST(0))) {
1686 log_err("Collectd::plugin_unregister_%s(pluginname): "
1687 "Invalid pluginname",
1688 desc);
1689 XSRETURN_EMPTY;
1690 }
1692 log_debug("Collectd::plugin_unregister_%s: plugin = \"%s\"", desc,
1693 SvPV_nolen(ST(0)));
1695 unreg(SvPV_nolen(ST(0)));
1697 XSRETURN_EMPTY;
1699 return;
1700 } /* static void _plugin_unregister_generic ( ... ) */
1702 /*
1703 * Collectd::plugin_unregister_TYPE (pluginname).
1704 *
1705 * TYPE:
1706 * type of callback to be unregistered: read, write, log, notification, flush
1707 *
1708 * pluginname:
1709 * name of the perl plugin
1710 */
1712 static XS(Collectd_plugin_unregister_read) {
1713 return _plugin_unregister_generic(aTHX, plugin_unregister_read, "read");
1714 }
1716 static XS(Collectd_plugin_unregister_write) {
1717 return _plugin_unregister_generic(aTHX, plugin_unregister_write, "write");
1718 }
1720 static XS(Collectd_plugin_unregister_log) {
1721 return _plugin_unregister_generic(aTHX, plugin_unregister_log, "log");
1722 }
1724 static XS(Collectd_plugin_unregister_notification) {
1725 return _plugin_unregister_generic(aTHX, plugin_unregister_notification,
1726 "notification");
1727 }
1729 static XS(Collectd_plugin_unregister_flush) {
1730 return _plugin_unregister_generic(aTHX, plugin_unregister_flush, "flush");
1731 }
1733 /*
1734 * Collectd::plugin_register_data_set (type, dataset).
1735 *
1736 * type:
1737 * type of the dataset
1738 *
1739 * dataset:
1740 * dataset to be registered
1741 */
1742 static XS(Collectd_plugin_register_ds) {
1743 SV *data = NULL;
1744 int ret = 0;
1746 dXSARGS;
1748 log_warn("Using plugin_register() to register new data-sets is "
1749 "deprecated - add new entries to a custom types.db instead.");
1751 if (2 != items) {
1752 log_err("Usage: Collectd::plugin_register_data_set(type, dataset)");
1753 XSRETURN_EMPTY;
1754 }
1756 log_debug("Collectd::plugin_register_data_set: "
1757 "type = \"%s\", dataset = \"%s\"",
1758 SvPV_nolen(ST(0)), SvPV_nolen(ST(1)));
1760 data = ST(1);
1762 if (SvROK(data) && (SVt_PVAV == SvTYPE(SvRV(data)))) {
1763 ret = pplugin_register_data_set(aTHX_ SvPV_nolen(ST(0)), (AV *)SvRV(data));
1764 } else {
1765 log_err("Collectd::plugin_register_data_set: Invalid data.");
1766 XSRETURN_EMPTY;
1767 }
1769 if (0 == ret)
1770 XSRETURN_YES;
1771 else
1772 XSRETURN_EMPTY;
1773 } /* static XS (Collectd_plugin_register_ds) */
1775 /*
1776 * Collectd::plugin_unregister_data_set (type).
1777 *
1778 * type:
1779 * type of the dataset
1780 */
1781 static XS(Collectd_plugin_unregister_ds) {
1782 dXSARGS;
1784 if (1 != items) {
1785 log_err("Usage: Collectd::plugin_unregister_data_set(type)");
1786 XSRETURN_EMPTY;
1787 }
1789 log_debug("Collectd::plugin_unregister_data_set: type = \"%s\"",
1790 SvPV_nolen(ST(0)));
1792 if (0 == pplugin_unregister_data_set(SvPV_nolen(ST(0))))
1793 XSRETURN_YES;
1794 else
1795 XSRETURN_EMPTY;
1796 } /* static XS (Collectd_plugin_register_ds) */
1798 /*
1799 * Collectd::plugin_dispatch_values (name, values).
1800 *
1801 * name:
1802 * name of the plugin
1803 *
1804 * values:
1805 * value list to submit
1806 */
1807 static XS(Collectd_plugin_dispatch_values) {
1808 SV *values = NULL;
1810 int ret = 0;
1812 dXSARGS;
1814 if (1 != items) {
1815 log_err("Usage: Collectd::plugin_dispatch_values(values)");
1816 XSRETURN_EMPTY;
1817 }
1819 log_debug("Collectd::plugin_dispatch_values: values=\"%s\"",
1820 SvPV_nolen(ST(/* stack index = */ 0)));
1822 values = ST(/* stack index = */ 0);
1824 if (NULL == values)
1825 XSRETURN_EMPTY;
1827 /* Make sure the argument is a hash reference. */
1828 if (!(SvROK(values) && (SVt_PVHV == SvTYPE(SvRV(values))))) {
1829 log_err("Collectd::plugin_dispatch_values: Invalid values.");
1830 XSRETURN_EMPTY;
1831 }
1833 ret = pplugin_dispatch_values(aTHX_(HV *) SvRV(values));
1835 if (0 == ret)
1836 XSRETURN_YES;
1837 else
1838 XSRETURN_EMPTY;
1839 } /* static XS (Collectd_plugin_dispatch_values) */
1841 /*
1842 * Collectd::plugin_get_interval ().
1843 */
1844 static XS(Collectd_plugin_get_interval) {
1845 dXSARGS;
1847 /* make sure we don't get any unused variable warnings for 'items';
1848 * don't abort, though */
1849 if (items)
1850 log_err("Usage: Collectd::plugin_get_interval()");
1852 XSRETURN_NV((NV)CDTIME_T_TO_DOUBLE(plugin_get_interval()));
1853 } /* static XS (Collectd_plugin_get_interval) */
1855 /* Collectd::plugin_write (plugin, ds, vl).
1856 *
1857 * plugin:
1858 * name of the plugin to call, may be 'undef'
1859 *
1860 * ds:
1861 * data-set that describes the submitted values, may be 'undef'
1862 *
1863 * vl:
1864 * value-list to be written
1865 */
1866 static XS(Collectd__plugin_write) {
1867 char *plugin;
1868 SV *ds, *vl;
1869 AV *ds_array;
1871 int ret;
1873 dXSARGS;
1875 if (3 != items) {
1876 log_err("Usage: Collectd::plugin_write(plugin, ds, vl)");
1877 XSRETURN_EMPTY;
1878 }
1880 log_debug("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1881 SvPV_nolen(ST(0)), SvOK(ST(1)) ? SvPV_nolen(ST(1)) : "",
1882 SvPV_nolen(ST(2)));
1884 if (!SvOK(ST(0)))
1885 plugin = NULL;
1886 else
1887 plugin = SvPV_nolen(ST(0));
1889 ds = ST(1);
1890 if (SvROK(ds) && (SVt_PVAV == SvTYPE(SvRV(ds))))
1891 ds_array = (AV *)SvRV(ds);
1892 else if (!SvOK(ds))
1893 ds_array = NULL;
1894 else {
1895 log_err("Collectd::plugin_write: Invalid data-set.");
1896 XSRETURN_EMPTY;
1897 }
1899 vl = ST(2);
1900 if (!(SvROK(vl) && (SVt_PVHV == SvTYPE(SvRV(vl))))) {
1901 log_err("Collectd::plugin_write: Invalid value-list.");
1902 XSRETURN_EMPTY;
1903 }
1905 ret = pplugin_write(aTHX_ plugin, ds_array, (HV *)SvRV(vl));
1907 if (0 == ret)
1908 XSRETURN_YES;
1909 else
1910 XSRETURN_EMPTY;
1911 } /* static XS (Collectd__plugin_write) */
1913 /*
1914 * Collectd::_plugin_flush (plugin, timeout, identifier).
1915 *
1916 * plugin:
1917 * name of the plugin to flush
1918 *
1919 * timeout:
1920 * timeout to use when flushing the data
1921 *
1922 * identifier:
1923 * data-set identifier to flush
1924 */
1925 static XS(Collectd__plugin_flush) {
1926 char *plugin = NULL;
1927 int timeout = -1;
1928 char *id = NULL;
1930 dXSARGS;
1932 if (3 != items) {
1933 log_err("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1934 XSRETURN_EMPTY;
1935 }
1937 if (SvOK(ST(0)))
1938 plugin = SvPV_nolen(ST(0));
1940 if (SvOK(ST(1)))
1941 timeout = (int)SvIV(ST(1));
1943 if (SvOK(ST(2)))
1944 id = SvPV_nolen(ST(2));
1946 log_debug("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1947 "id = \"%s\"",
1948 plugin, timeout, id);
1950 if (0 == plugin_flush(plugin, timeout, id))
1951 XSRETURN_YES;
1952 else
1953 XSRETURN_EMPTY;
1954 } /* static XS (Collectd__plugin_flush) */
1956 /*
1957 * Collectd::plugin_dispatch_notification (notif).
1958 *
1959 * notif:
1960 * notification to dispatch
1961 */
1962 static XS(Collectd_plugin_dispatch_notification) {
1963 SV *notif = NULL;
1965 int ret = 0;
1967 dXSARGS;
1969 if (1 != items) {
1970 log_err("Usage: Collectd::plugin_dispatch_notification(notif)");
1971 XSRETURN_EMPTY;
1972 }
1974 log_debug("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1975 SvPV_nolen(ST(0)));
1977 notif = ST(0);
1979 if (!(SvROK(notif) && (SVt_PVHV == SvTYPE(SvRV(notif))))) {
1980 log_err("Collectd::plugin_dispatch_notification: Invalid notif.");
1981 XSRETURN_EMPTY;
1982 }
1984 ret = pplugin_dispatch_notification(aTHX_(HV *) SvRV(notif));
1986 if (0 == ret)
1987 XSRETURN_YES;
1988 else
1989 XSRETURN_EMPTY;
1990 } /* static XS (Collectd_plugin_dispatch_notification) */
1992 /*
1993 * Collectd::plugin_log (level, message).
1994 *
1995 * level:
1996 * log level (LOG_DEBUG, ... LOG_ERR)
1997 *
1998 * message:
1999 * log message
2000 */
2001 static XS(Collectd_plugin_log) {
2002 dXSARGS;
2004 if (2 != items) {
2005 log_err("Usage: Collectd::plugin_log(level, message)");
2006 XSRETURN_EMPTY;
2007 }
2009 plugin_log(SvIV(ST(0)), "%s", SvPV_nolen(ST(1)));
2010 XSRETURN_YES;
2011 } /* static XS (Collectd_plugin_log) */
2013 /*
2014 * Collectd::_fc_register (type, name)
2015 *
2016 * type:
2017 * match | target
2018 *
2019 * name:
2020 * name of the match
2021 */
2022 static XS(Collectd__fc_register) {
2023 int type;
2024 char *name;
2026 int ret = 0;
2028 dXSARGS;
2030 if (2 != items) {
2031 log_err("Usage: Collectd::_fc_register(type, name)");
2032 XSRETURN_EMPTY;
2033 }
2035 type = SvIV(ST(0));
2036 name = SvPV_nolen(ST(1));
2038 if (FC_MATCH == type)
2039 ret = fc_register_match(name, pmatch);
2040 else if (FC_TARGET == type)
2041 ret = fc_register_target(name, ptarget);
2043 if (0 == ret)
2044 XSRETURN_YES;
2045 else
2046 XSRETURN_EMPTY;
2047 } /* static XS (Collectd_fc_register) */
2049 /*
2050 * Collectd::call_by_name (...).
2051 *
2052 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
2053 */
2054 static XS(Collectd_call_by_name) {
2055 SV *tmp = NULL;
2056 char *name = NULL;
2058 if (NULL == (tmp = get_sv("Collectd::cb_name", 0))) {
2059 sv_setpv(get_sv("@", 1), "cb_name has not been set");
2060 CLEAR_STACK_FRAME;
2061 return;
2062 }
2064 name = SvPV_nolen(tmp);
2066 if (NULL == get_cv(name, 0)) {
2067 sv_setpvf(get_sv("@", 1), "unknown callback \"%s\"", name);
2068 CLEAR_STACK_FRAME;
2069 return;
2070 }
2072 /* simply pass on the subroutine call without touching the stack,
2073 * thus leaving any arguments and return values in place */
2074 call_pv(name, 0);
2075 } /* static XS (Collectd_call_by_name) */
2077 /*
2078 * Interface to collectd.
2079 */
2081 static int perl_init(void) {
2082 int status;
2083 dTHX;
2085 if (NULL == perl_threads)
2086 return 0;
2088 if (NULL == aTHX) {
2089 c_ithread_t *t = NULL;
2091 pthread_mutex_lock(&perl_threads->mutex);
2092 t = c_ithread_create(perl_threads->head->interp);
2093 pthread_mutex_unlock(&perl_threads->mutex);
2095 aTHX = t->interp;
2096 }
2098 log_debug("perl_init: c_ithread: interp = %p (active threads: %i)", aTHX,
2099 perl_threads->number_of_threads);
2101 /* Lock the base thread to avoid race conditions with c_ithread_create().
2102 * See https://github.com/collectd/collectd/issues/9 and
2103 * https://github.com/collectd/collectd/issues/1706 for details.
2104 */
2105 assert(aTHX == perl_threads->head->interp);
2106 pthread_mutex_lock(&perl_threads->mutex);
2108 status = pplugin_call(aTHX_ PLUGIN_INIT);
2110 pthread_mutex_unlock(&perl_threads->mutex);
2112 return status;
2113 } /* static int perl_init (void) */
2115 static int perl_read(user_data_t *user_data) {
2116 dTHX;
2118 if (NULL == perl_threads)
2119 return 0;
2121 if (NULL == aTHX) {
2122 c_ithread_t *t = NULL;
2124 pthread_mutex_lock(&perl_threads->mutex);
2125 t = c_ithread_create(perl_threads->head->interp);
2126 pthread_mutex_unlock(&perl_threads->mutex);
2128 aTHX = t->interp;
2129 }
2131 /* Assert that we're not running as the base thread. Otherwise, we might
2132 * run into concurrency issues with c_ithread_create(). See
2133 * https://github.com/collectd/collectd/issues/9 for details. */
2134 assert(aTHX != perl_threads->head->interp);
2136 log_debug("perl_read: c_ithread: interp = %p (active threads: %i)", aTHX,
2137 perl_threads->number_of_threads);
2139 return pplugin_call(aTHX_ PLUGIN_READ, user_data->data);
2140 } /* static int perl_read (user_data_t *user_data) */
2142 static int perl_write(const data_set_t *ds, const value_list_t *vl,
2143 user_data_t *user_data) {
2144 int status;
2145 dTHX;
2147 if (NULL == perl_threads)
2148 return 0;
2150 if (NULL == aTHX) {
2151 c_ithread_t *t = NULL;
2153 pthread_mutex_lock(&perl_threads->mutex);
2154 t = c_ithread_create(perl_threads->head->interp);
2155 pthread_mutex_unlock(&perl_threads->mutex);
2157 aTHX = t->interp;
2158 }
2160 /* Lock the base thread if this is not called from one of the read threads
2161 * to avoid race conditions with c_ithread_create(). See
2162 * https://github.com/collectd/collectd/issues/9 for details. */
2163 if (aTHX == perl_threads->head->interp)
2164 pthread_mutex_lock(&perl_threads->mutex);
2166 log_debug("perl_write: c_ithread: interp = %p (active threads: %i)", aTHX,
2167 perl_threads->number_of_threads);
2168 status = pplugin_call(aTHX_ PLUGIN_WRITE, user_data->data, ds, vl);
2170 if (aTHX == perl_threads->head->interp)
2171 pthread_mutex_unlock(&perl_threads->mutex);
2173 return status;
2174 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2176 static void perl_log(int level, const char *msg, user_data_t *user_data) {
2177 dTHX;
2179 if (NULL == perl_threads)
2180 return;
2182 if (NULL == aTHX) {
2183 c_ithread_t *t = NULL;
2185 pthread_mutex_lock(&perl_threads->mutex);
2186 t = c_ithread_create(perl_threads->head->interp);
2187 pthread_mutex_unlock(&perl_threads->mutex);
2189 aTHX = t->interp;
2190 }
2192 /* Lock the base thread if this is not called from one of the read threads
2193 * to avoid race conditions with c_ithread_create(). See
2194 * https://github.com/collectd/collectd/issues/9 for details.
2195 */
2197 if (aTHX == perl_threads->head->interp)
2198 pthread_mutex_lock(&perl_threads->mutex);
2200 pplugin_call(aTHX_ PLUGIN_LOG, user_data->data, level, msg);
2202 if (aTHX == perl_threads->head->interp)
2203 pthread_mutex_unlock(&perl_threads->mutex);
2205 return;
2206 } /* static void perl_log (int, const char *) */
2208 static int perl_notify(const notification_t *notif, user_data_t *user_data) {
2209 dTHX;
2211 if (NULL == perl_threads)
2212 return 0;
2214 if (NULL == aTHX) {
2215 c_ithread_t *t = NULL;
2217 pthread_mutex_lock(&perl_threads->mutex);
2218 t = c_ithread_create(perl_threads->head->interp);
2219 pthread_mutex_unlock(&perl_threads->mutex);
2221 aTHX = t->interp;
2222 }
2223 return pplugin_call(aTHX_ PLUGIN_NOTIF, user_data->data, notif);
2224 } /* static int perl_notify (const notification_t *) */
2226 static int perl_flush(cdtime_t timeout, const char *identifier,
2227 user_data_t *user_data) {
2228 dTHX;
2230 if (NULL == perl_threads)
2231 return 0;
2233 if (NULL == aTHX) {
2234 c_ithread_t *t = NULL;
2236 pthread_mutex_lock(&perl_threads->mutex);
2237 t = c_ithread_create(perl_threads->head->interp);
2238 pthread_mutex_unlock(&perl_threads->mutex);
2240 aTHX = t->interp;
2241 }
2243 /* For collectd-5.6 only, #1731 */
2244 if (user_data == NULL || user_data->data == NULL)
2245 return pplugin_call(aTHX_ PLUGIN_FLUSH_ALL, timeout, identifier);
2247 return pplugin_call(aTHX_ PLUGIN_FLUSH, user_data->data, timeout, identifier);
2248 } /* static int perl_flush (const int) */
2250 static int perl_shutdown(void) {
2251 c_ithread_t *t;
2252 int ret;
2254 dTHX;
2256 plugin_unregister_complex_config("perl");
2257 plugin_unregister_read_group("perl");
2259 if (NULL == perl_threads)
2260 return 0;
2262 if (NULL == aTHX) {
2263 pthread_mutex_lock(&perl_threads->mutex);
2264 t = c_ithread_create(perl_threads->head->interp);
2265 pthread_mutex_unlock(&perl_threads->mutex);
2267 aTHX = t->interp;
2268 }
2270 log_debug("perl_shutdown: c_ithread: interp = %p (active threads: %i)", aTHX,
2271 perl_threads->number_of_threads);
2273 plugin_unregister_init("perl");
2274 plugin_unregister_flush("perl"); /* For collectd-5.6 only, #1731 */
2276 ret = pplugin_call(aTHX_ PLUGIN_SHUTDOWN);
2278 pthread_mutex_lock(&perl_threads->mutex);
2279 t = perl_threads->tail;
2281 while (NULL != t) {
2282 struct timespec ts_wait;
2283 c_ithread_t *thr = t;
2285 /* the pointer has to be advanced before destroying
2286 * the thread as this will free the memory */
2287 t = t->prev;
2289 thr->shutdown = 1;
2290 if (thr->running) {
2291 /* Give some time to thread to exit from Perl interpreter */
2292 WARNING("perl shutdown: Thread is running inside Perl. Waiting.");
2293 ts_wait.tv_sec = 0;
2294 ts_wait.tv_nsec = 500000;
2295 nanosleep(&ts_wait, NULL);
2296 }
2297 if (thr->running) {
2298 pthread_kill(thr->pthread, SIGTERM);
2299 ERROR("perl shutdown: Thread hangs inside Perl. Thread killed.");
2300 }
2301 c_ithread_destroy(thr);
2302 }
2304 pthread_mutex_unlock(&perl_threads->mutex);
2305 pthread_mutex_destroy(&perl_threads->mutex);
2306 pthread_mutexattr_destroy(&perl_threads->mutexattr);
2308 sfree(perl_threads);
2310 pthread_key_delete(perl_thr_key);
2312 PERL_SYS_TERM();
2314 plugin_unregister_shutdown("perl");
2315 return ret;
2316 } /* static void perl_shutdown (void) */
2318 /*
2319 * Access functions for global variables.
2320 *
2321 * These functions implement the "magic" used to access
2322 * the global variables from Perl.
2323 */
2325 static int g_pv_get(pTHX_ SV *var, MAGIC *mg) {
2326 char *pv = mg->mg_ptr;
2327 sv_setpv(var, pv);
2328 return 0;
2329 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2331 static int g_pv_set(pTHX_ SV *var, MAGIC *mg) {
2332 char *pv = mg->mg_ptr;
2333 sstrncpy(pv, SvPV_nolen(var), DATA_MAX_NAME_LEN);
2334 return 0;
2335 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2337 static int g_interval_get(pTHX_ SV *var, MAGIC *mg) {
2338 log_warn("Accessing $interval_g is deprecated (and might not "
2339 "give the desired results) - plugin_get_interval() should "
2340 "be used instead.");
2341 sv_setnv(var, CDTIME_T_TO_DOUBLE(interval_g));
2342 return 0;
2343 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2345 static int g_interval_set(pTHX_ SV *var, MAGIC *mg) {
2346 double nv = (double)SvNV(var);
2347 log_warn("Accessing $interval_g is deprecated (and might not "
2348 "give the desired results) - plugin_get_interval() should "
2349 "be used instead.");
2350 interval_g = DOUBLE_TO_CDTIME_T(nv);
2351 return 0;
2352 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2354 static MGVTBL g_pv_vtbl = {g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2355 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2356 ,
2357 NULL
2358 #endif
2359 };
2360 static MGVTBL g_interval_vtbl = {g_interval_get, g_interval_set, NULL, NULL,
2361 NULL, NULL, NULL
2362 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2363 ,
2364 NULL
2365 #endif
2366 };
2368 /* bootstrap the Collectd module */
2369 static void xs_init(pTHX) {
2370 HV *stash = NULL;
2371 SV *tmp = NULL;
2372 char *file = __FILE__;
2374 dXSUB_SYS;
2376 /* enable usage of Perl modules using shared libraries */
2377 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2379 /* register API */
2380 for (int i = 0; NULL != api[i].f; ++i)
2381 newXS(api[i].name, api[i].f, file);
2383 stash = gv_stashpv("Collectd", 1);
2385 /* export "constants" */
2386 for (int i = 0; '\0' != constants[i].name[0]; ++i)
2387 newCONSTSUB(stash, constants[i].name, newSViv(constants[i].value));
2389 /* export global variables
2390 * by adding "magic" to the SV's representing the globale variables
2391 * perl is able to automagically call the get/set function when
2392 * accessing any such variable (this is basically the same as using
2393 * tie() in Perl) */
2394 /* global strings */
2395 for (int i = 0; '\0' != g_strings[i].name[0]; ++i) {
2396 tmp = get_sv(g_strings[i].name, 1);
2397 sv_magicext(tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl, g_strings[i].var, 0);
2398 }
2400 tmp = get_sv("Collectd::interval_g", /* create = */ 1);
2401 sv_magicext(tmp, NULL, /* how = */ PERL_MAGIC_ext,
2402 /* vtbl = */ &g_interval_vtbl,
2403 /* name = */ NULL, /* namelen = */ 0);
2405 return;
2406 } /* static void xs_init (pTHX) */
2408 /* Initialize the global Perl interpreter. */
2409 static int init_pi(int argc, char **argv) {
2410 dTHXa(NULL);
2412 if (NULL != perl_threads)
2413 return 0;
2415 log_info("Initializing Perl interpreter...");
2416 #if COLLECT_DEBUG
2417 {
2418 for (int i = 0; i < argc; ++i)
2419 log_debug("argv[%i] = \"%s\"", i, argv[i]);
2420 }
2421 #endif /* COLLECT_DEBUG */
2423 if (0 != pthread_key_create(&perl_thr_key, c_ithread_destructor)) {
2424 log_err("init_pi: pthread_key_create failed");
2426 /* this must not happen - cowardly giving up if it does */
2427 return -1;
2428 }
2430 #ifdef __FreeBSD__
2431 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2432 * triggers a "value computed is not used" warning by gcc. */
2433 (void)
2434 #endif
2435 PERL_SYS_INIT3(&argc, &argv, &environ);
2437 perl_threads = smalloc(sizeof(*perl_threads));
2438 memset(perl_threads, 0, sizeof(c_ithread_list_t));
2440 pthread_mutexattr_init(&perl_threads->mutexattr);
2441 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2442 pthread_mutex_init(&perl_threads->mutex, &perl_threads->mutexattr);
2443 /* locking the mutex should not be necessary at this point
2444 * but let's just do it for the sake of completeness */
2445 pthread_mutex_lock(&perl_threads->mutex);
2447 perl_threads->head = c_ithread_create(NULL);
2448 perl_threads->tail = perl_threads->head;
2450 if (NULL == (perl_threads->head->interp = perl_alloc())) {
2451 log_err("init_pi: Not enough memory.");
2452 exit(3);
2453 }
2455 aTHX = perl_threads->head->interp;
2456 pthread_mutex_unlock(&perl_threads->mutex);
2458 perl_construct(aTHX);
2460 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2462 if (0 != perl_parse(aTHX_ xs_init, argc, argv, NULL)) {
2463 SV *err = get_sv("@", 1);
2464 log_err("init_pi: Unable to bootstrap Collectd: %s", SvPV_nolen(err));
2466 perl_destruct(perl_threads->head->interp);
2467 perl_free(perl_threads->head->interp);
2468 sfree(perl_threads);
2470 pthread_key_delete(perl_thr_key);
2471 return -1;
2472 }
2474 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2475 sv_setpv(get_sv("0", 0), "collectd");
2477 perl_run(aTHX);
2479 plugin_register_init("perl", perl_init);
2480 plugin_register_shutdown("perl", perl_shutdown);
2481 return 0;
2482 } /* static int init_pi (const char **, const int) */
2484 /*
2485 * LoadPlugin "<Plugin>"
2486 */
2487 static int perl_config_loadplugin(pTHX_ oconfig_item_t *ci) {
2488 char module_name[DATA_MAX_NAME_LEN];
2490 char *value = NULL;
2492 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2493 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2494 log_err("LoadPlugin expects a single string argument.");
2495 return 1;
2496 }
2498 value = ci->values[0].value.string;
2500 if (NULL == get_module_name(module_name, sizeof(module_name), value)) {
2501 log_err("Invalid module name %s", value);
2502 return (1);
2503 }
2505 if (0 != init_pi(perl_argc, perl_argv))
2506 return -1;
2508 assert(NULL != perl_threads);
2509 assert(NULL != perl_threads->head);
2511 aTHX = perl_threads->head->interp;
2513 log_debug("perl_config: Loading Perl plugin \"%s\"", value);
2514 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(module_name, strlen(module_name)),
2515 Nullsv);
2516 return 0;
2517 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2519 /*
2520 * BaseName "<Name>"
2521 */
2522 static int perl_config_basename(pTHX_ oconfig_item_t *ci) {
2523 char *value = NULL;
2525 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2526 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2527 log_err("BaseName expects a single string argument.");
2528 return 1;
2529 }
2531 value = ci->values[0].value.string;
2533 log_debug("perl_config: Setting plugin basename to \"%s\"", value);
2534 sstrncpy(base_name, value, sizeof(base_name));
2535 return 0;
2536 } /* static int perl_config_basename (oconfig_item_it *) */
2538 /*
2539 * EnableDebugger "<Package>"|""
2540 */
2541 static int perl_config_enabledebugger(pTHX_ oconfig_item_t *ci) {
2542 char *value = NULL;
2544 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2545 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2546 log_err("EnableDebugger expects a single string argument.");
2547 return 1;
2548 }
2550 if (NULL != perl_threads) {
2551 log_warn("EnableDebugger has no effects if used after LoadPlugin.");
2552 return 1;
2553 }
2555 value = ci->values[0].value.string;
2557 perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2559 if (NULL == perl_argv) {
2560 log_err("perl_config: Not enough memory.");
2561 exit(3);
2562 }
2564 if ('\0' == value[0]) {
2565 perl_argv[perl_argc - 1] = "-d";
2566 } else {
2567 perl_argv[perl_argc - 1] = smalloc(strlen(value) + 4);
2568 sstrncpy(perl_argv[perl_argc - 1], "-d:", 4);
2569 sstrncpy(perl_argv[perl_argc - 1] + 3, value, strlen(value) + 1);
2570 }
2572 perl_argv[perl_argc] = NULL;
2573 return 0;
2574 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2576 /*
2577 * IncludeDir "<Dir>"
2578 */
2579 static int perl_config_includedir(pTHX_ oconfig_item_t *ci) {
2580 char *value = NULL;
2582 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2583 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2584 log_err("IncludeDir expects a single string argument.");
2585 return 1;
2586 }
2588 value = ci->values[0].value.string;
2590 if (NULL == aTHX) {
2591 perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2593 if (NULL == perl_argv) {
2594 log_err("perl_config: Not enough memory.");
2595 exit(3);
2596 }
2598 perl_argv[perl_argc - 1] = smalloc(strlen(value) + 3);
2599 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2600 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen(value) + 1);
2602 perl_argv[perl_argc] = NULL;
2603 } else {
2604 /* prepend the directory to @INC */
2605 av_unshift(GvAVn(PL_incgv), 1);
2606 av_store(GvAVn(PL_incgv), 0, newSVpv(value, strlen(value)));
2607 }
2608 return 0;
2609 } /* static int perl_config_includedir (oconfig_item_it *) */
2611 /*
2612 * <Plugin> block
2613 */
2614 static int perl_config_plugin(pTHX_ oconfig_item_t *ci) {
2615 int retvals = 0;
2616 int ret = 0;
2618 char *plugin;
2619 HV *config;
2621 if (NULL == perl_threads) {
2622 log_err("A `Plugin' block was encountered but no plugin was loaded yet. "
2623 "Put the appropriate `LoadPlugin' option in front of it.");
2624 return -1;
2625 }
2627 dSP;
2629 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2630 log_err("LoadPlugin expects a single string argument.");
2631 return 1;
2632 }
2634 plugin = ci->values[0].value.string;
2635 config = newHV();
2637 if (0 != oconfig_item2hv(aTHX_ ci, config)) {
2638 hv_clear(config);
2639 hv_undef(config);
2641 log_err("Unable to convert configuration to a Perl hash value.");
2642 config = (HV *)&PL_sv_undef;
2643 }
2645 ENTER;
2646 SAVETMPS;
2648 PUSHMARK(SP);
2650 XPUSHs(sv_2mortal(newSVpv(plugin, 0)));
2651 XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
2653 PUTBACK;
2655 retvals = call_pv("Collectd::_plugin_dispatch_config", G_SCALAR);
2657 SPAGAIN;
2658 if (0 < retvals) {
2659 SV *tmp = POPs;
2660 if (!SvTRUE(tmp))
2661 ret = 1;
2662 } else
2663 ret = 1;
2665 PUTBACK;
2666 FREETMPS;
2667 LEAVE;
2668 return ret;
2669 } /* static int perl_config_plugin (oconfig_item_it *) */
2671 static int perl_config(oconfig_item_t *ci) {
2672 int status = 0;
2674 dTHXa(NULL);
2676 for (int i = 0; i < ci->children_num; ++i) {
2677 oconfig_item_t *c = ci->children + i;
2678 int current_status = 0;
2680 if (NULL != perl_threads) {
2681 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2682 return -1;
2683 }
2685 if (0 == strcasecmp(c->key, "LoadPlugin"))
2686 current_status = perl_config_loadplugin(aTHX_ c);
2687 else if (0 == strcasecmp(c->key, "BaseName"))
2688 current_status = perl_config_basename(aTHX_ c);
2689 else if (0 == strcasecmp(c->key, "EnableDebugger"))
2690 current_status = perl_config_enabledebugger(aTHX_ c);
2691 else if (0 == strcasecmp(c->key, "IncludeDir"))
2692 current_status = perl_config_includedir(aTHX_ c);
2693 else if (0 == strcasecmp(c->key, "Plugin"))
2694 current_status = perl_config_plugin(aTHX_ c);
2695 else if (0 == strcasecmp(c->key, "RegisterLegacyFlush"))
2696 cf_util_get_boolean(c, ®ister_legacy_flush);
2697 else {
2698 log_warn("Ignoring unknown config key \"%s\".", c->key);
2699 current_status = 0;
2700 }
2702 /* fatal error - it's up to perl_config_* to clean up */
2703 if (0 > current_status) {
2704 log_err("Configuration failed with a fatal error - "
2705 "plugin disabled!");
2706 return current_status;
2707 }
2709 status += current_status;
2710 }
2711 return status;
2712 } /* static int perl_config (oconfig_item_t *) */
2714 void module_register(void) {
2715 perl_argc = 4;
2716 perl_argv = smalloc((perl_argc + 1) * sizeof(*perl_argv));
2718 /* default options for the Perl interpreter */
2719 perl_argv[0] = "";
2720 perl_argv[1] = "-MCollectd";
2721 perl_argv[2] = "-e";
2722 perl_argv[3] = "1";
2723 perl_argv[4] = NULL;
2725 plugin_register_complex_config("perl", perl_config);
2726 return;
2727 } /* void module_register (void) */
2729 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */