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 "plugin.h"
62 #include "common.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 {
207 { "Collectd::plugin_register_read", Collectd_plugin_register_read },
208 { "Collectd::plugin_register_write", Collectd_plugin_register_write },
209 { "Collectd::plugin_register_log", Collectd_plugin_register_log },
210 { "Collectd::plugin_register_notification",
211 Collectd_plugin_register_notification },
212 { "Collectd::plugin_register_flush", Collectd_plugin_register_flush },
213 { "Collectd::plugin_unregister_read", Collectd_plugin_unregister_read },
214 { "Collectd::plugin_unregister_write", Collectd_plugin_unregister_write },
215 { "Collectd::plugin_unregister_log", Collectd_plugin_unregister_log },
216 { "Collectd::plugin_unregister_notification",
217 Collectd_plugin_unregister_notification },
218 { "Collectd::plugin_unregister_flush", Collectd_plugin_unregister_flush },
219 { "Collectd::plugin_register_data_set", Collectd_plugin_register_ds },
220 { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
221 { "Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values },
222 { "Collectd::plugin_get_interval", Collectd_plugin_get_interval },
223 { "Collectd::_plugin_write", Collectd__plugin_write },
224 { "Collectd::_plugin_flush", Collectd__plugin_flush },
225 { "Collectd::plugin_dispatch_notification",
226 Collectd_plugin_dispatch_notification },
227 { "Collectd::plugin_log", Collectd_plugin_log },
228 { "Collectd::_fc_register", Collectd__fc_register },
229 { "Collectd::call_by_name", Collectd_call_by_name },
230 { "", NULL }
231 };
233 struct {
234 char name[64];
235 int value;
236 } constants[] =
237 {
238 { "Collectd::TYPE_INIT", PLUGIN_INIT },
239 { "Collectd::TYPE_READ", PLUGIN_READ },
240 { "Collectd::TYPE_WRITE", PLUGIN_WRITE },
241 { "Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN },
242 { "Collectd::TYPE_LOG", PLUGIN_LOG },
243 { "Collectd::TYPE_NOTIF", PLUGIN_NOTIF },
244 { "Collectd::TYPE_FLUSH", PLUGIN_FLUSH },
245 { "Collectd::TYPE_CONFIG", PLUGIN_CONFIG },
246 { "Collectd::TYPE_DATASET", PLUGIN_DATASET },
247 { "Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER },
248 { "Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE },
249 { "Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE },
250 { "Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE },
251 { "Collectd::LOG_ERR", LOG_ERR },
252 { "Collectd::LOG_WARNING", LOG_WARNING },
253 { "Collectd::LOG_NOTICE", LOG_NOTICE },
254 { "Collectd::LOG_INFO", LOG_INFO },
255 { "Collectd::LOG_DEBUG", LOG_DEBUG },
256 { "Collectd::FC_MATCH", FC_MATCH },
257 { "Collectd::FC_TARGET", FC_TARGET },
258 { "Collectd::FC_CB_CREATE", FC_CB_CREATE },
259 { "Collectd::FC_CB_DESTROY", FC_CB_DESTROY },
260 { "Collectd::FC_CB_EXEC", FC_CB_EXEC },
261 { "Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH },
262 { "Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES },
263 { "Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE },
264 { "Collectd::FC_TARGET_STOP", FC_TARGET_STOP },
265 { "Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN },
266 { "Collectd::NOTIF_FAILURE", NOTIF_FAILURE },
267 { "Collectd::NOTIF_WARNING", NOTIF_WARNING },
268 { "Collectd::NOTIF_OKAY", NOTIF_OKAY },
269 { "", 0 }
270 };
272 struct {
273 char name[64];
274 char *var;
275 } g_strings[] =
276 {
277 { "Collectd::hostname_g", hostname_g },
278 { "", NULL }
279 };
281 /*
282 * Helper functions for data type conversion.
283 */
285 /*
286 * data source:
287 * [
288 * {
289 * name => $ds_name,
290 * type => $ds_type,
291 * min => $ds_min,
292 * max => $ds_max
293 * },
294 * ...
295 * ]
296 */
297 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
298 {
299 SV **tmp = NULL;
301 if ((NULL == hash) || (NULL == ds))
302 return -1;
304 if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
305 sstrncpy (ds->name, SvPV_nolen (*tmp), sizeof (ds->name));
306 }
307 else {
308 log_err ("hv2data_source: No DS name given.");
309 return -1;
310 }
312 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
313 ds->type = SvIV (*tmp);
315 if ((DS_TYPE_COUNTER != ds->type)
316 && (DS_TYPE_GAUGE != ds->type)
317 && (DS_TYPE_DERIVE != ds->type)
318 && (DS_TYPE_ABSOLUTE != ds->type)) {
319 log_err ("hv2data_source: Invalid DS type.");
320 return -1;
321 }
322 }
323 else {
324 ds->type = DS_TYPE_COUNTER;
325 }
327 if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
328 ds->min = SvNV (*tmp);
329 else
330 ds->min = NAN;
332 if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
333 ds->max = SvNV (*tmp);
334 else
335 ds->max = NAN;
336 return 0;
337 } /* static int hv2data_source (HV *, data_source_t *) */
339 /* av2value converts at most "len" elements from "array" to "value". Returns the
340 * number of elements converted or zero on error. */
341 static size_t av2value (pTHX_ char *name, AV *array, value_t *value, size_t array_len)
342 {
343 const data_set_t *ds;
345 if ((NULL == name) || (NULL == array) || (NULL == value) || (array_len == 0))
346 return 0;
348 ds = plugin_get_ds (name);
349 if (NULL == ds) {
350 log_err ("av2value: Unknown dataset \"%s\"", name);
351 return 0;
352 }
354 if (array_len < ds->ds_num) {
355 log_warn ("av2value: array does not contain enough elements for type \"%s\": got %zu, want %zu",
356 name, array_len, ds->ds_num);
357 return 0;
358 } else if (array_len > ds->ds_num) {
359 log_warn ("av2value: array contains excess elements for type \"%s\": got %zu, want %zu",
360 name, array_len, ds->ds_num);
361 }
363 for (size_t i = 0; i < ds->ds_num; ++i) {
364 SV **tmp = av_fetch (array, i, 0);
366 if (NULL != tmp) {
367 if (DS_TYPE_COUNTER == ds->ds[i].type)
368 value[i].counter = SvIV (*tmp);
369 else if (DS_TYPE_GAUGE == ds->ds[i].type)
370 value[i].gauge = SvNV (*tmp);
371 else if (DS_TYPE_DERIVE == ds->ds[i].type)
372 value[i].derive = SvIV (*tmp);
373 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
374 value[i].absolute = SvIV (*tmp);
375 }
376 else {
377 return 0;
378 }
379 }
381 return ds->ds_num;
382 } /* static size_t av2value (char *, AV *, value_t *, size_t) */
384 /*
385 * value list:
386 * {
387 * values => [ @values ],
388 * time => $time,
389 * host => $host,
390 * plugin => $plugin,
391 * plugin_instance => $pinstance,
392 * type_instance => $tinstance,
393 * }
394 */
395 static int hv2value_list (pTHX_ HV *hash, value_list_t *vl)
396 {
397 SV **tmp;
399 if ((NULL == hash) || (NULL == vl))
400 return -1;
402 if (NULL == (tmp = hv_fetch (hash, "type", 4, 0))) {
403 log_err ("hv2value_list: No type given.");
404 return -1;
405 }
407 sstrncpy (vl->type, SvPV_nolen (*tmp), sizeof (vl->type));
409 if ((NULL == (tmp = hv_fetch (hash, "values", 6, 0)))
410 || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
411 log_err ("hv2value_list: No valid values given.");
412 return -1;
413 }
415 {
416 AV *array = (AV *)SvRV (*tmp);
417 /* av_len returns the highest index, not the actual length. */
418 size_t array_len = (size_t) (av_len (array) + 1);
419 if (array_len == 0)
420 return -1;
422 vl->values = calloc (array_len, sizeof (*vl->values));
423 vl->values_len = av2value (aTHX_ vl->type, (AV *)SvRV (*tmp), vl->values, array_len);
424 if (vl->values_len == 0) {
425 sfree (vl->values);
426 return -1;
427 }
428 }
430 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
431 {
432 double t = SvNV (*tmp);
433 vl->time = DOUBLE_TO_CDTIME_T (t);
434 }
436 if (NULL != (tmp = hv_fetch (hash, "interval", 8, 0)))
437 {
438 double t = SvNV (*tmp);
439 vl->interval = DOUBLE_TO_CDTIME_T (t);
440 }
442 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
443 sstrncpy (vl->host, SvPV_nolen (*tmp), sizeof (vl->host));
444 else
445 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
447 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
448 sstrncpy (vl->plugin, SvPV_nolen (*tmp), sizeof (vl->plugin));
450 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
451 sstrncpy (vl->plugin_instance, SvPV_nolen (*tmp),
452 sizeof (vl->plugin_instance));
454 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
455 sstrncpy (vl->type_instance, SvPV_nolen (*tmp),
456 sizeof (vl->type_instance));
457 return 0;
458 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
460 static int av2data_set (pTHX_ AV *array, char *name, data_set_t *ds)
461 {
462 int len;
464 if ((NULL == array) || (NULL == name) || (NULL == ds))
465 return -1;
467 len = av_len (array);
469 if (-1 == len) {
470 log_err ("av2data_set: Invalid data set.");
471 return -1;
472 }
474 ds->ds = smalloc ((len + 1) * sizeof (*ds->ds));
475 ds->ds_num = len + 1;
477 for (int i = 0; i <= len; ++i) {
478 SV **elem = av_fetch (array, i, 0);
480 if (NULL == elem) {
481 log_err ("av2data_set: Failed to fetch data source %i.", i);
482 return -1;
483 }
485 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
486 log_err ("av2data_set: Invalid data source.");
487 return -1;
488 }
490 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds->ds[i]))
491 return -1;
493 log_debug ("av2data_set: "
494 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
495 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
496 }
498 sstrncpy (ds->type, name, sizeof (ds->type));
499 return 0;
500 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
502 /*
503 * notification:
504 * {
505 * severity => $severity,
506 * time => $time,
507 * message => $msg,
508 * host => $host,
509 * plugin => $plugin,
510 * type => $type,
511 * plugin_instance => $instance,
512 * type_instance => $type_instance,
513 * meta => [ { name => <name>, value => <value> }, ... ]
514 * }
515 */
516 static int av2notification_meta (pTHX_ AV *array, notification_meta_t **meta)
517 {
518 notification_meta_t **m = meta;
520 int len = av_len (array);
522 for (int i = 0; i <= len; ++i) {
523 SV **tmp = av_fetch (array, i, 0);
524 HV *hash;
526 if (NULL == tmp)
527 return -1;
529 if (! (SvROK (*tmp) && (SVt_PVHV == SvTYPE (SvRV (*tmp))))) {
530 log_warn ("av2notification_meta: Skipping invalid "
531 "meta information.");
532 continue;
533 }
535 hash = (HV *)SvRV (*tmp);
537 *m = smalloc (sizeof (**m));
539 if (NULL == (tmp = hv_fetch (hash, "name", 4, 0))) {
540 log_warn ("av2notification_meta: Skipping invalid "
541 "meta information.");
542 free (*m);
543 continue;
544 }
545 sstrncpy ((*m)->name, SvPV_nolen (*tmp), sizeof ((*m)->name));
547 if (NULL == (tmp = hv_fetch (hash, "value", 5, 0))) {
548 log_warn ("av2notification_meta: Skipping invalid "
549 "meta information.");
550 free (*m);
551 continue;
552 }
554 if (SvNOK (*tmp)) {
555 (*m)->nm_value.nm_double = SvNVX (*tmp);
556 (*m)->type = NM_TYPE_DOUBLE;
557 }
558 else if (SvUOK (*tmp)) {
559 (*m)->nm_value.nm_unsigned_int = SvUVX (*tmp);
560 (*m)->type = NM_TYPE_UNSIGNED_INT;
561 }
562 else if (SvIOK (*tmp)) {
563 (*m)->nm_value.nm_signed_int = SvIVX (*tmp);
564 (*m)->type = NM_TYPE_SIGNED_INT;
565 }
566 else {
567 (*m)->nm_value.nm_string = sstrdup (SvPV_nolen (*tmp));
568 (*m)->type = NM_TYPE_STRING;
569 }
571 (*m)->next = NULL;
572 m = &((*m)->next);
573 }
574 return 0;
575 } /* static int av2notification_meta (AV *, notification_meta_t *) */
577 static int hv2notification (pTHX_ HV *hash, notification_t *n)
578 {
579 SV **tmp = NULL;
581 if ((NULL == hash) || (NULL == n))
582 return -1;
584 if (NULL != (tmp = hv_fetch (hash, "severity", 8, 0)))
585 n->severity = SvIV (*tmp);
586 else
587 n->severity = NOTIF_FAILURE;
589 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
590 {
591 double t = SvNV (*tmp);
592 n->time = DOUBLE_TO_CDTIME_T (t);
593 }
594 else
595 n->time = cdtime ();
597 if (NULL != (tmp = hv_fetch (hash, "message", 7, 0)))
598 sstrncpy (n->message, SvPV_nolen (*tmp), sizeof (n->message));
600 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
601 sstrncpy (n->host, SvPV_nolen (*tmp), sizeof (n->host));
602 else
603 sstrncpy (n->host, hostname_g, sizeof (n->host));
605 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
606 sstrncpy (n->plugin, SvPV_nolen (*tmp), sizeof (n->plugin));
608 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
609 sstrncpy (n->plugin_instance, SvPV_nolen (*tmp),
610 sizeof (n->plugin_instance));
612 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0)))
613 sstrncpy (n->type, SvPV_nolen (*tmp), sizeof (n->type));
615 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
616 sstrncpy (n->type_instance, SvPV_nolen (*tmp),
617 sizeof (n->type_instance));
619 n->meta = NULL;
620 while (NULL != (tmp = hv_fetch (hash, "meta", 4, 0))) {
621 if (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp))))) {
622 log_warn ("hv2notification: Ignoring invalid meta information.");
623 break;
624 }
626 if (0 != av2notification_meta (aTHX_ (AV *)SvRV (*tmp), &n->meta)) {
627 plugin_notification_meta_free (n->meta);
628 n->meta = NULL;
629 return -1;
630 }
631 break;
632 }
633 return 0;
634 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
636 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
637 {
638 if ((NULL == ds) || (NULL == array))
639 return -1;
641 av_extend (array, ds->ds_num);
643 for (size_t i = 0; i < ds->ds_num; ++i) {
644 HV *source = newHV ();
646 if (NULL == hv_store (source, "name", 4,
647 newSVpv (ds->ds[i].name, 0), 0))
648 return -1;
650 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
651 return -1;
653 if (! isnan (ds->ds[i].min))
654 if (NULL == hv_store (source, "min", 3,
655 newSVnv (ds->ds[i].min), 0))
656 return -1;
658 if (! isnan (ds->ds[i].max))
659 if (NULL == hv_store (source, "max", 3,
660 newSVnv (ds->ds[i].max), 0))
661 return -1;
663 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
664 return -1;
665 }
666 return 0;
667 } /* static int data_set2av (data_set_t *, AV *) */
669 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
670 {
671 AV *values = NULL;
672 size_t i;
674 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
675 return -1;
677 values = newAV ();
678 /* av_extend takes the last *index* to which the array should be extended. */
679 av_extend (values, vl->values_len - 1);
681 assert (ds->ds_num == vl->values_len);
682 for (i = 0; i < vl->values_len; ++i) {
683 SV *val = NULL;
685 if (DS_TYPE_COUNTER == ds->ds[i].type)
686 val = newSViv (vl->values[i].counter);
687 else if (DS_TYPE_GAUGE == ds->ds[i].type)
688 val = newSVnv (vl->values[i].gauge);
689 else if (DS_TYPE_DERIVE == ds->ds[i].type)
690 val = newSViv (vl->values[i].derive);
691 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
692 val = newSViv (vl->values[i].absolute);
694 if (NULL == av_store (values, i, val)) {
695 av_undef (values);
696 return -1;
697 }
698 }
700 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
701 return -1;
703 if (0 != vl->time)
704 {
705 double t = CDTIME_T_TO_DOUBLE (vl->time);
706 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
707 return -1;
708 }
710 {
711 double t = CDTIME_T_TO_DOUBLE (vl->interval);
712 if (NULL == hv_store (hash, "interval", 8, newSVnv (t), 0))
713 return -1;
714 }
716 if ('\0' != vl->host[0])
717 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
718 return -1;
720 if ('\0' != vl->plugin[0])
721 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
722 return -1;
724 if ('\0' != vl->plugin_instance[0])
725 if (NULL == hv_store (hash, "plugin_instance", 15,
726 newSVpv (vl->plugin_instance, 0), 0))
727 return -1;
729 if ('\0' != vl->type[0])
730 if (NULL == hv_store (hash, "type", 4, newSVpv (vl->type, 0), 0))
731 return -1;
733 if ('\0' != vl->type_instance[0])
734 if (NULL == hv_store (hash, "type_instance", 13,
735 newSVpv (vl->type_instance, 0), 0))
736 return -1;
737 return 0;
738 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
740 static int notification_meta2av (pTHX_ notification_meta_t *meta, AV *array)
741 {
742 int meta_num = 0;
744 while (meta) {
745 ++meta_num;
746 meta = meta->next;
747 }
749 av_extend (array, meta_num);
751 for (int i = 0; NULL != meta; meta = meta->next, ++i) {
752 HV *m = newHV ();
753 SV *value;
755 if (NULL == hv_store (m, "name", 4, newSVpv (meta->name, 0), 0))
756 return -1;
758 if (NM_TYPE_STRING == meta->type)
759 value = newSVpv (meta->nm_value.nm_string, 0);
760 else if (NM_TYPE_SIGNED_INT == meta->type)
761 value = newSViv (meta->nm_value.nm_signed_int);
762 else if (NM_TYPE_UNSIGNED_INT == meta->type)
763 value = newSVuv (meta->nm_value.nm_unsigned_int);
764 else if (NM_TYPE_DOUBLE == meta->type)
765 value = newSVnv (meta->nm_value.nm_double);
766 else if (NM_TYPE_BOOLEAN == meta->type)
767 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
768 else
769 return -1;
771 if (NULL == hv_store (m, "value", 5, value, 0)) {
772 sv_free (value);
773 return -1;
774 }
776 if (NULL == av_store (array, i, newRV_noinc ((SV *)m))) {
777 hv_clear (m);
778 hv_undef (m);
779 return -1;
780 }
781 }
782 return 0;
783 } /* static int notification_meta2av (notification_meta_t *, AV *) */
785 static int notification2hv (pTHX_ notification_t *n, HV *hash)
786 {
787 if (NULL == hv_store (hash, "severity", 8, newSViv (n->severity), 0))
788 return -1;
790 if (0 != n->time)
791 {
792 double t = CDTIME_T_TO_DOUBLE (n->time);
793 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
794 return -1;
795 }
797 if ('\0' != *n->message)
798 if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
799 return -1;
801 if ('\0' != *n->host)
802 if (NULL == hv_store (hash, "host", 4, newSVpv (n->host, 0), 0))
803 return -1;
805 if ('\0' != *n->plugin)
806 if (NULL == hv_store (hash, "plugin", 6, newSVpv (n->plugin, 0), 0))
807 return -1;
809 if ('\0' != *n->plugin_instance)
810 if (NULL == hv_store (hash, "plugin_instance", 15,
811 newSVpv (n->plugin_instance, 0), 0))
812 return -1;
814 if ('\0' != *n->type)
815 if (NULL == hv_store (hash, "type", 4, newSVpv (n->type, 0), 0))
816 return -1;
818 if ('\0' != *n->type_instance)
819 if (NULL == hv_store (hash, "type_instance", 13,
820 newSVpv (n->type_instance, 0), 0))
821 return -1;
823 if (NULL != n->meta) {
824 AV *meta = newAV ();
825 if ((0 != notification_meta2av (aTHX_ n->meta, meta))
826 || (NULL == hv_store (hash, "meta", 4,
827 newRV_noinc ((SV *)meta), 0))) {
828 av_clear (meta);
829 av_undef (meta);
830 return -1;
831 }
832 }
833 return 0;
834 } /* static int notification2hv (notification_t *, HV *) */
836 static int oconfig_item2hv (pTHX_ oconfig_item_t *ci, HV *hash)
837 {
838 AV *values;
839 AV *children;
841 if (NULL == hv_store (hash, "key", 3, newSVpv (ci->key, 0), 0))
842 return -1;
844 values = newAV ();
845 if (0 < ci->values_num)
846 av_extend (values, ci->values_num);
848 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0)) {
849 av_clear (values);
850 av_undef (values);
851 return -1;
852 }
854 for (int i = 0; i < ci->values_num; ++i) {
855 SV *value;
857 switch (ci->values[i].type) {
858 case OCONFIG_TYPE_STRING:
859 value = newSVpv (ci->values[i].value.string, 0);
860 break;
861 case OCONFIG_TYPE_NUMBER:
862 value = newSVnv ((NV)ci->values[i].value.number);
863 break;
864 case OCONFIG_TYPE_BOOLEAN:
865 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
866 break;
867 default:
868 log_err ("oconfig_item2hv: Invalid value type %i.",
869 ci->values[i].type);
870 value = &PL_sv_undef;
871 }
873 if (NULL == av_store (values, i, value)) {
874 sv_free (value);
875 return -1;
876 }
877 }
879 /* ignoring 'parent' member which is uninteresting in this case */
881 children = newAV ();
882 if (0 < ci->children_num)
883 av_extend (children, ci->children_num);
885 if (NULL == hv_store (hash, "children", 8, newRV_noinc ((SV *)children), 0)) {
886 av_clear (children);
887 av_undef (children);
888 return -1;
889 }
891 for (int i = 0; i < ci->children_num; ++i) {
892 HV *child = newHV ();
894 if (0 != oconfig_item2hv (aTHX_ ci->children + i, child)) {
895 hv_clear (child);
896 hv_undef (child);
897 return -1;
898 }
900 if (NULL == av_store (children, i, newRV_noinc ((SV *)child))) {
901 hv_clear (child);
902 hv_undef (child);
903 return -1;
904 }
905 }
906 return 0;
907 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
909 /*
910 * Internal functions.
911 */
913 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
914 int status = 0;
915 if (base_name[0] == '\0')
916 status = ssnprintf (buf, buf_len, "%s", module);
917 else
918 status = ssnprintf (buf, buf_len, "%s::%s", base_name, module);
919 if ((status < 0) || ((unsigned int)status >= buf_len))
920 return (NULL);
921 return (buf);
922 } /* char *get_module_name */
924 /*
925 * Add a plugin's data set definition.
926 */
927 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
928 {
929 int ret = 0;
931 data_set_t ds;
933 if ((NULL == name) || (NULL == dataset))
934 return -1;
936 if (0 != av2data_set (aTHX_ dataset, name, &ds))
937 return -1;
939 ret = plugin_register_data_set (&ds);
941 free (ds.ds);
942 return ret;
943 } /* static int pplugin_register_data_set (char *, SV *) */
945 /*
946 * Remove a plugin's data set definition.
947 */
948 static int pplugin_unregister_data_set (char *name)
949 {
950 if (NULL == name)
951 return 0;
952 return plugin_unregister_data_set (name);
953 } /* static int pplugin_unregister_data_set (char *) */
955 /*
956 * Submit the values to the write functions.
957 */
958 static int pplugin_dispatch_values (pTHX_ HV *values)
959 {
960 value_list_t vl = VALUE_LIST_INIT;
962 int ret = 0;
964 if (NULL == values)
965 return -1;
967 if (0 != hv2value_list (aTHX_ values, &vl))
968 return -1;
970 ret = plugin_dispatch_values (&vl);
972 sfree (vl.values);
973 return ret;
974 } /* static int pplugin_dispatch_values (char *, HV *) */
976 /*
977 * Submit the values to a single write function.
978 */
979 static int pplugin_write (pTHX_ const char *plugin, AV *data_set, HV *values)
980 {
981 data_set_t ds;
982 value_list_t vl = VALUE_LIST_INIT;
984 int ret;
986 if (NULL == values)
987 return -1;
989 if (0 != hv2value_list (aTHX_ values, &vl))
990 return -1;
992 if ((NULL != data_set)
993 && (0 != av2data_set (aTHX_ data_set, vl.type, &ds)))
994 return -1;
996 ret = plugin_write (plugin, NULL == data_set ? NULL : &ds, &vl);
997 if (0 != ret)
998 log_warn ("Dispatching value to plugin \"%s\" failed with status %i.",
999 NULL == plugin ? "<any>" : plugin, ret);
1001 if (NULL != data_set)
1002 sfree (ds.ds);
1003 sfree (vl.values);
1004 return ret;
1005 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
1007 /*
1008 * Dispatch a notification.
1009 */
1010 static int pplugin_dispatch_notification (pTHX_ HV *notif)
1011 {
1012 notification_t n = { 0 };
1014 int ret;
1016 if (NULL == notif)
1017 return -1;
1019 if (0 != hv2notification (aTHX_ notif, &n))
1020 return -1;
1022 ret = plugin_dispatch_notification (&n);
1023 plugin_notification_meta_free (n.meta);
1024 return ret;
1025 } /* static int pplugin_dispatch_notification (HV *) */
1027 /*
1028 * Call perl sub with thread locking flags handled.
1029 */
1030 static int call_pv_locked (pTHX_ const char* sub_name)
1031 {
1032 _Bool old_running;
1033 int ret;
1035 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
1036 if (t == NULL) /* thread destroyed */
1037 return 0;
1039 old_running = t->running;
1040 t->running = 1;
1042 if (t->shutdown) {
1043 t->running = old_running;
1044 return 0;
1045 }
1047 ret = call_pv (sub_name, G_SCALAR|G_EVAL);
1049 t->running = old_running;
1050 return ret;
1051 } /* static int call_pv_locked (pTHX, *sub_name) */
1053 /*
1054 * Call all working functions of the given type.
1055 */
1056 static int pplugin_call (pTHX_ int type, ...)
1057 {
1058 int retvals = 0;
1060 va_list ap;
1061 int ret = 0;
1062 char *subname;
1064 dSP;
1066 if ((type < 0) || (type >= PLUGIN_TYPES))
1067 return -1;
1069 va_start (ap, type);
1071 ENTER;
1072 SAVETMPS;
1074 PUSHMARK (SP);
1076 if (PLUGIN_READ == type) {
1077 subname = va_arg(ap, char *);
1078 }
1079 else if (PLUGIN_WRITE == type) {
1080 data_set_t *ds;
1081 value_list_t *vl;
1083 AV *pds = newAV ();
1084 HV *pvl = newHV ();
1086 subname = va_arg(ap, char *);
1087 /*
1088 * $_[0] = $plugin_type;
1089 *
1090 * $_[1] =
1091 * [
1092 * {
1093 * name => $ds_name,
1094 * type => $ds_type,
1095 * min => $ds_min,
1096 * max => $ds_max
1097 * },
1098 * ...
1099 * ];
1100 *
1101 * $_[2] =
1102 * {
1103 * values => [ $v1, ... ],
1104 * time => $time,
1105 * host => $hostname,
1106 * plugin => $plugin,
1107 * type => $type,
1108 * plugin_instance => $instance,
1109 * type_instance => $type_instance
1110 * };
1111 */
1112 ds = va_arg (ap, data_set_t *);
1113 vl = va_arg (ap, value_list_t *);
1115 if (-1 == data_set2av (aTHX_ ds, pds)) {
1116 av_clear (pds);
1117 av_undef (pds);
1118 pds = (AV *)&PL_sv_undef;
1119 ret = -1;
1120 }
1122 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
1123 hv_clear (pvl);
1124 hv_undef (pvl);
1125 pvl = (HV *)&PL_sv_undef;
1126 ret = -1;
1127 }
1129 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
1130 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1131 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1132 }
1133 else if (PLUGIN_LOG == type) {
1134 subname = va_arg(ap, char *);
1135 /*
1136 * $_[0] = $level;
1137 *
1138 * $_[1] = $message;
1139 */
1140 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1141 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1142 }
1143 else if (PLUGIN_NOTIF == type) {
1144 notification_t *n;
1145 HV *notif = newHV ();
1147 subname = va_arg(ap, char *);
1148 /*
1149 * $_[0] =
1150 * {
1151 * severity => $severity,
1152 * time => $time,
1153 * message => $msg,
1154 * host => $host,
1155 * plugin => $plugin,
1156 * type => $type,
1157 * plugin_instance => $instance,
1158 * type_instance => $type_instance
1159 * };
1160 */
1161 n = va_arg (ap, notification_t *);
1163 if (-1 == notification2hv (aTHX_ n, notif)) {
1164 hv_clear (notif);
1165 hv_undef (notif);
1166 notif = (HV *)&PL_sv_undef;
1167 ret = -1;
1168 }
1170 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
1171 }
1172 else if (PLUGIN_FLUSH == type) {
1173 cdtime_t timeout;
1174 subname = va_arg(ap, char *);
1175 /*
1176 * $_[0] = $timeout;
1177 * $_[1] = $identifier;
1178 */
1179 timeout = va_arg (ap, cdtime_t);
1181 XPUSHs (sv_2mortal (newSVnv (CDTIME_T_TO_DOUBLE (timeout))));
1182 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1183 }
1184 else if (PLUGIN_FLUSH_ALL == type) {
1185 cdtime_t timeout;
1186 subname = "Collectd::plugin_call_all";
1187 /*
1188 * $_[0] = $timeout;
1189 * $_[1] = $identifier;
1190 */
1191 timeout = va_arg (ap, cdtime_t);
1193 XPUSHs (sv_2mortal (newSViv ((IV)PLUGIN_FLUSH)));
1194 XPUSHs (sv_2mortal (newSVnv (CDTIME_T_TO_DOUBLE (timeout))));
1195 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1196 }
1197 else if (PLUGIN_INIT == type) {
1198 subname = "Collectd::plugin_call_all";
1199 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1200 }
1201 else if (PLUGIN_SHUTDOWN == type) {
1202 subname = "Collectd::plugin_call_all";
1203 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1204 }
1205 else { /* Unknown type. Run 'plugin_call_all' and make compiler happy */
1206 subname = "Collectd::plugin_call_all";
1207 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1208 }
1210 PUTBACK;
1212 retvals = call_pv_locked (aTHX_ subname);
1214 SPAGAIN;
1215 if (SvTRUE(ERRSV)) {
1216 if (PLUGIN_LOG != type)
1217 ERROR ("perl: %s error: %s", subname, SvPV_nolen(ERRSV));
1218 ret = -1;
1219 }
1220 else if (0 < retvals) {
1221 SV *tmp = POPs;
1222 if (! SvTRUE (tmp))
1223 ret = -1;
1224 }
1226 PUTBACK;
1227 FREETMPS;
1228 LEAVE;
1230 va_end (ap);
1231 return ret;
1232 } /* static int pplugin_call (int, ...) */
1234 /*
1235 * collectd's Perl interpreter based thread implementation.
1236 *
1237 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1238 */
1240 /* must be called with perl_threads->mutex locked */
1241 static void c_ithread_destroy (c_ithread_t *ithread)
1242 {
1243 dTHXa (ithread->interp);
1245 assert (NULL != perl_threads);
1247 PERL_SET_CONTEXT (aTHX);
1248 /* Mark as running to avoid deadlock:
1249 c_ithread_destroy -> log_debug -> perl_log()
1250 */
1251 ithread->running = 1;
1252 log_debug ("Shutting down Perl interpreter %p...", aTHX);
1254 #if COLLECT_DEBUG
1255 sv_report_used ();
1257 --perl_threads->number_of_threads;
1258 #endif /* COLLECT_DEBUG */
1260 perl_destruct (aTHX);
1261 perl_free (aTHX);
1263 if (NULL == ithread->prev)
1264 perl_threads->head = ithread->next;
1265 else
1266 ithread->prev->next = ithread->next;
1268 if (NULL == ithread->next)
1269 perl_threads->tail = ithread->prev;
1270 else
1271 ithread->next->prev = ithread->prev;
1273 sfree (ithread);
1274 return;
1275 } /* static void c_ithread_destroy (c_ithread_t *) */
1277 static void c_ithread_destructor (void *arg)
1278 {
1279 c_ithread_t *ithread = (c_ithread_t *)arg;
1280 c_ithread_t *t = NULL;
1282 if (NULL == perl_threads)
1283 return;
1285 pthread_mutex_lock (&perl_threads->mutex);
1287 for (t = perl_threads->head; NULL != t; t = t->next)
1288 if (t == ithread)
1289 break;
1291 /* the ithread no longer exists */
1292 if (NULL == t)
1293 {
1294 pthread_mutex_unlock (&perl_threads->mutex);
1295 return;
1296 }
1298 c_ithread_destroy (ithread);
1300 pthread_mutex_unlock (&perl_threads->mutex);
1301 return;
1302 } /* static void c_ithread_destructor (void *) */
1304 /* must be called with perl_threads->mutex locked */
1305 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1306 {
1307 c_ithread_t *t = NULL;
1308 dTHXa (NULL);
1310 assert (NULL != perl_threads);
1312 t = smalloc (sizeof (*t));
1313 memset (t, 0, sizeof (c_ithread_t));
1315 t->interp = (NULL == base)
1316 ? NULL
1317 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1319 aTHX = t->interp;
1321 if ((NULL != base) && (NULL != PL_endav)) {
1322 av_clear (PL_endav);
1323 av_undef (PL_endav);
1324 PL_endav = Nullav;
1325 }
1327 #if COLLECT_DEBUG
1328 ++perl_threads->number_of_threads;
1329 #endif /* COLLECT_DEBUG */
1331 t->next = NULL;
1333 if (NULL == perl_threads->tail) {
1334 perl_threads->head = t;
1335 t->prev = NULL;
1336 }
1337 else {
1338 perl_threads->tail->next = t;
1339 t->prev = perl_threads->tail;
1340 }
1342 t->pthread = pthread_self();
1343 t->running = 0;
1344 t->shutdown = 0;
1345 perl_threads->tail = t;
1347 pthread_setspecific (perl_thr_key, (const void *)t);
1348 return t;
1349 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1351 /*
1352 * Filter chains implementation.
1353 */
1355 static int fc_call (pTHX_ int type, int cb_type, pfc_user_data_t *data, ...)
1356 {
1357 int retvals = 0;
1359 va_list ap;
1360 int ret = 0;
1362 notification_meta_t **meta = NULL;
1363 AV *pmeta = NULL;
1365 dSP;
1367 if ((type < 0) || (type >= FC_TYPES))
1368 return -1;
1370 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1371 return -1;
1373 va_start (ap, data);
1375 ENTER;
1376 SAVETMPS;
1378 PUSHMARK (SP);
1380 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1381 XPUSHs (sv_2mortal (newSVpv (data->name, 0)));
1382 XPUSHs (sv_2mortal (newSViv ((IV)cb_type)));
1384 if (FC_CB_CREATE == cb_type) {
1385 /*
1386 * $_[0] = $ci;
1387 * $_[1] = $user_data;
1388 */
1389 oconfig_item_t *ci;
1390 HV *config = newHV ();
1392 ci = va_arg (ap, oconfig_item_t *);
1394 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
1395 hv_clear (config);
1396 hv_undef (config);
1397 config = (HV *)&PL_sv_undef;
1398 ret = -1;
1399 }
1401 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
1402 }
1403 else if (FC_CB_DESTROY == cb_type) {
1404 /*
1405 * $_[1] = $user_data;
1406 */
1408 /* nothing to be done - the user data pointer
1409 * is pushed onto the stack later */
1410 }
1411 else if (FC_CB_EXEC == cb_type) {
1412 /*
1413 * $_[0] = $ds;
1414 * $_[1] = $vl;
1415 * $_[2] = $meta;
1416 * $_[3] = $user_data;
1417 */
1418 data_set_t *ds;
1419 value_list_t *vl;
1421 AV *pds = newAV ();
1422 HV *pvl = newHV ();
1424 ds = va_arg (ap, data_set_t *);
1425 vl = va_arg (ap, value_list_t *);
1426 meta = va_arg (ap, notification_meta_t **);
1428 if (0 != data_set2av (aTHX_ ds, pds)) {
1429 av_clear (pds);
1430 av_undef (pds);
1431 pds = (AV *)&PL_sv_undef;
1432 ret = -1;
1433 }
1435 if (0 != value_list2hv (aTHX_ vl, ds, pvl)) {
1436 hv_clear (pvl);
1437 hv_undef (pvl);
1438 pvl = (HV *)&PL_sv_undef;
1439 ret = -1;
1440 }
1442 if (NULL != meta) {
1443 pmeta = newAV ();
1445 if (0 != notification_meta2av (aTHX_ *meta, pmeta)) {
1446 av_clear (pmeta);
1447 av_undef (pmeta);
1448 pmeta = (AV *)&PL_sv_undef;
1449 ret = -1;
1450 }
1451 }
1452 else {
1453 pmeta = (AV *)&PL_sv_undef;
1454 }
1456 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1457 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1458 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pmeta)));
1459 }
1461 XPUSHs (sv_2mortal (newRV_inc (data->user_data)));
1463 PUTBACK;
1465 retvals = call_pv_locked (aTHX_ "Collectd::fc_call");
1467 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1468 assert (pmeta != NULL);
1470 plugin_notification_meta_free (*meta);
1471 av2notification_meta (aTHX_ pmeta, meta);
1472 }
1474 SPAGAIN;
1475 if (SvTRUE(ERRSV)) {
1476 ERROR ("perl: Collectd::fc_call error: %s", SvPV_nolen(ERRSV));
1477 ret = -1;
1478 }
1479 else if (0 < retvals) {
1480 SV *tmp = POPs;
1482 /* the exec callbacks return a status, while
1483 * the others return a boolean value */
1484 if (FC_CB_EXEC == cb_type)
1485 ret = SvIV (tmp);
1486 else if (! SvTRUE (tmp))
1487 ret = -1;
1488 }
1490 PUTBACK;
1491 FREETMPS;
1492 LEAVE;
1494 va_end (ap);
1495 return ret;
1496 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1498 static int fc_create (int type, const oconfig_item_t *ci, void **user_data)
1499 {
1500 pfc_user_data_t *data;
1502 int ret = 0;
1504 dTHX;
1506 if (NULL == perl_threads)
1507 return 0;
1509 if (NULL == aTHX) {
1510 c_ithread_t *t = NULL;
1512 pthread_mutex_lock (&perl_threads->mutex);
1513 t = c_ithread_create (perl_threads->head->interp);
1514 pthread_mutex_unlock (&perl_threads->mutex);
1516 aTHX = t->interp;
1517 }
1519 log_debug ("fc_create: c_ithread: interp = %p (active threads: %i)",
1520 aTHX, perl_threads->number_of_threads);
1522 if ((1 != ci->values_num)
1523 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1524 log_warn ("A \"%s\" block expects a single string argument.",
1525 (FC_MATCH == type) ? "Match" : "Target");
1526 return -1;
1527 }
1529 data = smalloc (sizeof (*data));
1530 data->name = sstrdup (ci->values[0].value.string);
1531 data->user_data = newSV (0);
1533 ret = fc_call (aTHX_ type, FC_CB_CREATE, data, ci);
1535 if (0 != ret)
1536 PFC_USER_DATA_FREE (data);
1537 else
1538 *user_data = data;
1539 return ret;
1540 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1542 static int fc_destroy (int type, void **user_data)
1543 {
1544 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1546 int ret = 0;
1548 dTHX;
1550 if ((NULL == perl_threads) || (NULL == data))
1551 return 0;
1553 if (NULL == aTHX) {
1554 c_ithread_t *t = NULL;
1556 pthread_mutex_lock (&perl_threads->mutex);
1557 t = c_ithread_create (perl_threads->head->interp);
1558 pthread_mutex_unlock (&perl_threads->mutex);
1560 aTHX = t->interp;
1561 }
1563 log_debug ("fc_destroy: c_ithread: interp = %p (active threads: %i)",
1564 aTHX, perl_threads->number_of_threads);
1566 ret = fc_call (aTHX_ type, FC_CB_DESTROY, data);
1568 PFC_USER_DATA_FREE (data);
1569 *user_data = NULL;
1570 return ret;
1571 } /* static int fc_destroy (int, void **) */
1573 static int fc_exec (int type, const data_set_t *ds, const value_list_t *vl,
1574 notification_meta_t **meta, void **user_data)
1575 {
1576 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1578 dTHX;
1580 if (NULL == perl_threads)
1581 return 0;
1583 assert (NULL != data);
1585 if (NULL == aTHX) {
1586 c_ithread_t *t = NULL;
1588 pthread_mutex_lock (&perl_threads->mutex);
1589 t = c_ithread_create (perl_threads->head->interp);
1590 pthread_mutex_unlock (&perl_threads->mutex);
1592 aTHX = t->interp;
1593 }
1595 log_debug ("fc_exec: c_ithread: interp = %p (active threads: %i)",
1596 aTHX, perl_threads->number_of_threads);
1598 return fc_call (aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1599 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1600 notification_meta_t **, void **) */
1602 static int pmatch_create (const oconfig_item_t *ci, void **user_data)
1603 {
1604 return fc_create (FC_MATCH, ci, user_data);
1605 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1607 static int pmatch_destroy (void **user_data)
1608 {
1609 return fc_destroy (FC_MATCH, user_data);
1610 } /* static int pmatch_destroy (void **) */
1612 static int pmatch_match (const data_set_t *ds, const value_list_t *vl,
1613 notification_meta_t **meta, void **user_data)
1614 {
1615 return fc_exec (FC_MATCH, ds, vl, meta, user_data);
1616 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1617 notification_meta_t **, void **) */
1619 static match_proc_t pmatch = {
1620 pmatch_create, pmatch_destroy, pmatch_match
1621 };
1623 static int ptarget_create (const oconfig_item_t *ci, void **user_data)
1624 {
1625 return fc_create (FC_TARGET, ci, user_data);
1626 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1628 static int ptarget_destroy (void **user_data)
1629 {
1630 return fc_destroy (FC_TARGET, user_data);
1631 } /* static int ptarget_destroy (void **) */
1633 static int ptarget_invoke (const data_set_t *ds, value_list_t *vl,
1634 notification_meta_t **meta, void **user_data)
1635 {
1636 return fc_exec (FC_TARGET, ds, vl, meta, user_data);
1637 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1638 notification_meta_t **, void **) */
1640 static target_proc_t ptarget = {
1641 ptarget_create, ptarget_destroy, ptarget_invoke
1642 };
1644 /*
1645 * Exported Perl API.
1646 */
1648 static void _plugin_register_generic_userdata (pTHX, int type, const char *desc)
1649 {
1650 int ret = 0;
1651 user_data_t userdata;
1652 char *pluginname;
1654 dXSARGS;
1656 if (2 != items) {
1657 log_err ("Usage: Collectd::plugin_register_%s(pluginname, subname)",
1658 desc);
1659 XSRETURN_EMPTY;
1660 }
1662 if (! SvOK (ST (0))) {
1663 log_err ("Collectd::plugin_register_%s(pluginname, subname): "
1664 "Invalid pluginname", desc);
1665 XSRETURN_EMPTY;
1666 }
1667 if (! SvOK (ST (1))) {
1668 log_err ("Collectd::plugin_register_%s(pluginname, subname): "
1669 "Invalid subname", desc);
1670 XSRETURN_EMPTY;
1671 }
1673 /* Use pluginname as-is to allow flush a single perl plugin */
1674 pluginname = SvPV_nolen (ST (0));
1676 log_debug ("Collectd::plugin_register_%s: "
1677 "plugin = \"%s\", sub = \"%s\"",
1678 desc, pluginname, SvPV_nolen (ST (1)));
1680 memset(&userdata, 0, sizeof(userdata));
1681 userdata.data = strdup(SvPV_nolen (ST (1)));
1682 userdata.free_func = free;
1684 if (PLUGIN_READ == type) {
1685 ret = plugin_register_complex_read(
1686 "perl", /* group */
1687 pluginname,
1688 perl_read,
1689 plugin_get_interval(), /* Default interval */
1690 &userdata);
1691 }
1692 else if (PLUGIN_WRITE == type) {
1693 ret = plugin_register_write(pluginname, perl_write, &userdata);
1694 }
1695 else if (PLUGIN_LOG == type) {
1696 ret = plugin_register_log(pluginname, perl_log, &userdata);
1697 }
1698 else if (PLUGIN_NOTIF == type) {
1699 ret = plugin_register_notification(pluginname, perl_notify, &userdata);
1700 }
1701 else if (PLUGIN_FLUSH == type) {
1702 if (1 == register_legacy_flush) { /* For collectd-5.7 only, #1731 */
1703 register_legacy_flush = 0;
1704 ret = plugin_register_flush("perl", perl_flush, /* user_data = */ NULL);
1705 }
1707 if (0 == ret)
1708 ret = plugin_register_flush(pluginname, perl_flush, &userdata);
1709 }
1710 else {
1711 ret = -1;
1712 }
1714 if (0 == ret)
1715 XSRETURN_YES;
1716 else {
1717 free (userdata.data);
1718 XSRETURN_EMPTY;
1719 }
1720 } /* static void _plugin_register_generic_userdata ( ... ) */
1722 /*
1723 * Collectd::plugin_register_TYPE (pluginname, subname).
1724 *
1725 * pluginname:
1726 * name of the perl plugin
1727 *
1728 * subname:
1729 * name of the plugin's subroutine that does the work
1730 */
1732 static XS (Collectd_plugin_register_read) {
1733 return _plugin_register_generic_userdata(aTHX, PLUGIN_READ, "read");
1734 }
1736 static XS (Collectd_plugin_register_write) {
1737 return _plugin_register_generic_userdata(aTHX, PLUGIN_WRITE, "write");
1738 }
1740 static XS (Collectd_plugin_register_log) {
1741 return _plugin_register_generic_userdata(aTHX, PLUGIN_LOG, "log");
1742 }
1744 static XS (Collectd_plugin_register_notification) {
1745 return _plugin_register_generic_userdata(aTHX, PLUGIN_NOTIF, "notification");
1746 }
1748 static XS (Collectd_plugin_register_flush) {
1749 return _plugin_register_generic_userdata(aTHX, PLUGIN_FLUSH, "flush");
1750 }
1752 typedef int perl_unregister_function_t(const char *name);
1754 static void _plugin_unregister_generic (pTHX,
1755 perl_unregister_function_t *unreg, const char *desc)
1756 {
1757 dXSARGS;
1759 if (1 != items) {
1760 log_err ("Usage: Collectd::plugin_unregister_%s(pluginname)", desc);
1761 XSRETURN_EMPTY;
1762 }
1764 if (! SvOK (ST (0))) {
1765 log_err ("Collectd::plugin_unregister_%s(pluginname): "
1766 "Invalid pluginname", desc);
1767 XSRETURN_EMPTY;
1768 }
1770 log_debug ("Collectd::plugin_unregister_%s: plugin = \"%s\"",
1771 desc, SvPV_nolen (ST (0)));
1773 unreg(SvPV_nolen (ST (0)));
1775 XSRETURN_EMPTY;
1777 return;
1778 } /* static void _plugin_unregister_generic ( ... ) */
1780 /*
1781 * Collectd::plugin_unregister_TYPE (pluginname).
1782 *
1783 * TYPE:
1784 * type of callback to be unregistered: read, write, log, notification, flush
1785 *
1786 * pluginname:
1787 * name of the perl plugin
1788 */
1790 static XS (Collectd_plugin_unregister_read) {
1791 return _plugin_unregister_generic(aTHX,
1792 plugin_unregister_read, "read");
1793 }
1795 static XS (Collectd_plugin_unregister_write) {
1796 return _plugin_unregister_generic(aTHX,
1797 plugin_unregister_write, "write");
1798 }
1800 static XS (Collectd_plugin_unregister_log) {
1801 return _plugin_unregister_generic(aTHX,
1802 plugin_unregister_log, "log");
1803 }
1805 static XS (Collectd_plugin_unregister_notification) {
1806 return _plugin_unregister_generic(aTHX,
1807 plugin_unregister_notification, "notification");
1808 }
1810 static XS (Collectd_plugin_unregister_flush) {
1811 return _plugin_unregister_generic(aTHX,
1812 plugin_unregister_flush, "flush");
1813 }
1815 /*
1816 * Collectd::plugin_register_data_set (type, dataset).
1817 *
1818 * type:
1819 * type of the dataset
1820 *
1821 * dataset:
1822 * dataset to be registered
1823 */
1824 static XS (Collectd_plugin_register_ds)
1825 {
1826 SV *data = NULL;
1827 int ret = 0;
1829 dXSARGS;
1831 log_warn ("Using plugin_register() to register new data-sets is "
1832 "deprecated - add new entries to a custom types.db instead.");
1834 if (2 != items) {
1835 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1836 XSRETURN_EMPTY;
1837 }
1839 log_debug ("Collectd::plugin_register_data_set: "
1840 "type = \"%s\", dataset = \"%s\"",
1841 SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1843 data = ST (1);
1845 if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1846 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1847 (AV *)SvRV (data));
1848 }
1849 else {
1850 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1851 XSRETURN_EMPTY;
1852 }
1854 if (0 == ret)
1855 XSRETURN_YES;
1856 else
1857 XSRETURN_EMPTY;
1858 } /* static XS (Collectd_plugin_register_ds) */
1860 /*
1861 * Collectd::plugin_unregister_data_set (type).
1862 *
1863 * type:
1864 * type of the dataset
1865 */
1866 static XS (Collectd_plugin_unregister_ds)
1867 {
1868 dXSARGS;
1870 if (1 != items) {
1871 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1872 XSRETURN_EMPTY;
1873 }
1875 log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1876 SvPV_nolen (ST (0)));
1878 if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1879 XSRETURN_YES;
1880 else
1881 XSRETURN_EMPTY;
1882 } /* static XS (Collectd_plugin_register_ds) */
1884 /*
1885 * Collectd::plugin_dispatch_values (name, values).
1886 *
1887 * name:
1888 * name of the plugin
1889 *
1890 * values:
1891 * value list to submit
1892 */
1893 static XS (Collectd_plugin_dispatch_values)
1894 {
1895 SV *values = NULL;
1897 int ret = 0;
1899 dXSARGS;
1901 if (1 != items) {
1902 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1903 XSRETURN_EMPTY;
1904 }
1906 log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1907 SvPV_nolen (ST (/* stack index = */ 0)));
1909 values = ST (/* stack index = */ 0);
1911 if (NULL == values)
1912 XSRETURN_EMPTY;
1914 /* Make sure the argument is a hash reference. */
1915 if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1916 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1917 XSRETURN_EMPTY;
1918 }
1920 ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1922 if (0 == ret)
1923 XSRETURN_YES;
1924 else
1925 XSRETURN_EMPTY;
1926 } /* static XS (Collectd_plugin_dispatch_values) */
1928 /*
1929 * Collectd::plugin_get_interval ().
1930 */
1931 static XS (Collectd_plugin_get_interval)
1932 {
1933 dXSARGS;
1935 /* make sure we don't get any unused variable warnings for 'items';
1936 * don't abort, though */
1937 if (items)
1938 log_err ("Usage: Collectd::plugin_get_interval()");
1940 XSRETURN_NV ((NV) CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
1941 } /* static XS (Collectd_plugin_get_interval) */
1943 /* Collectd::plugin_write (plugin, ds, vl).
1944 *
1945 * plugin:
1946 * name of the plugin to call, may be 'undef'
1947 *
1948 * ds:
1949 * data-set that describes the submitted values, may be 'undef'
1950 *
1951 * vl:
1952 * value-list to be written
1953 */
1954 static XS (Collectd__plugin_write)
1955 {
1956 char *plugin;
1957 SV *ds, *vl;
1958 AV *ds_array;
1960 int ret;
1962 dXSARGS;
1964 if (3 != items) {
1965 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1966 XSRETURN_EMPTY;
1967 }
1969 log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1970 SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1971 SvPV_nolen (ST (2)));
1973 if (! SvOK (ST (0)))
1974 plugin = NULL;
1975 else
1976 plugin = SvPV_nolen (ST (0));
1978 ds = ST (1);
1979 if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1980 ds_array = (AV *)SvRV (ds);
1981 else if (! SvOK (ds))
1982 ds_array = NULL;
1983 else {
1984 log_err ("Collectd::plugin_write: Invalid data-set.");
1985 XSRETURN_EMPTY;
1986 }
1988 vl = ST (2);
1989 if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1990 log_err ("Collectd::plugin_write: Invalid value-list.");
1991 XSRETURN_EMPTY;
1992 }
1994 ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1996 if (0 == ret)
1997 XSRETURN_YES;
1998 else
1999 XSRETURN_EMPTY;
2000 } /* static XS (Collectd__plugin_write) */
2002 /*
2003 * Collectd::_plugin_flush (plugin, timeout, identifier).
2004 *
2005 * plugin:
2006 * name of the plugin to flush
2007 *
2008 * timeout:
2009 * timeout to use when flushing the data
2010 *
2011 * identifier:
2012 * data-set identifier to flush
2013 */
2014 static XS (Collectd__plugin_flush)
2015 {
2016 char *plugin = NULL;
2017 int timeout = -1;
2018 char *id = NULL;
2020 dXSARGS;
2022 if (3 != items) {
2023 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
2024 XSRETURN_EMPTY;
2025 }
2027 if (SvOK (ST (0)))
2028 plugin = SvPV_nolen (ST (0));
2030 if (SvOK (ST (1)))
2031 timeout = (int)SvIV (ST (1));
2033 if (SvOK (ST (2)))
2034 id = SvPV_nolen (ST (2));
2036 log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
2037 "id = \"%s\"", plugin, timeout, id);
2039 if (0 == plugin_flush (plugin, timeout, id))
2040 XSRETURN_YES;
2041 else
2042 XSRETURN_EMPTY;
2043 } /* static XS (Collectd__plugin_flush) */
2045 /*
2046 * Collectd::plugin_dispatch_notification (notif).
2047 *
2048 * notif:
2049 * notification to dispatch
2050 */
2051 static XS (Collectd_plugin_dispatch_notification)
2052 {
2053 SV *notif = NULL;
2055 int ret = 0;
2057 dXSARGS;
2059 if (1 != items) {
2060 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
2061 XSRETURN_EMPTY;
2062 }
2064 log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
2065 SvPV_nolen (ST (0)));
2067 notif = ST (0);
2069 if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
2070 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
2071 XSRETURN_EMPTY;
2072 }
2074 ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
2076 if (0 == ret)
2077 XSRETURN_YES;
2078 else
2079 XSRETURN_EMPTY;
2080 } /* static XS (Collectd_plugin_dispatch_notification) */
2082 /*
2083 * Collectd::plugin_log (level, message).
2084 *
2085 * level:
2086 * log level (LOG_DEBUG, ... LOG_ERR)
2087 *
2088 * message:
2089 * log message
2090 */
2091 static XS (Collectd_plugin_log)
2092 {
2093 dXSARGS;
2095 if (2 != items) {
2096 log_err ("Usage: Collectd::plugin_log(level, message)");
2097 XSRETURN_EMPTY;
2098 }
2100 plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
2101 XSRETURN_YES;
2102 } /* static XS (Collectd_plugin_log) */
2104 /*
2105 * Collectd::_fc_register (type, name)
2106 *
2107 * type:
2108 * match | target
2109 *
2110 * name:
2111 * name of the match
2112 */
2113 static XS (Collectd__fc_register)
2114 {
2115 int type;
2116 char *name;
2118 int ret = 0;
2120 dXSARGS;
2122 if (2 != items) {
2123 log_err ("Usage: Collectd::_fc_register(type, name)");
2124 XSRETURN_EMPTY;
2125 }
2127 type = SvIV (ST (0));
2128 name = SvPV_nolen (ST (1));
2130 if (FC_MATCH == type)
2131 ret = fc_register_match (name, pmatch);
2132 else if (FC_TARGET == type)
2133 ret = fc_register_target (name, ptarget);
2135 if (0 == ret)
2136 XSRETURN_YES;
2137 else
2138 XSRETURN_EMPTY;
2139 } /* static XS (Collectd_fc_register) */
2141 /*
2142 * Collectd::call_by_name (...).
2143 *
2144 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
2145 */
2146 static XS (Collectd_call_by_name)
2147 {
2148 SV *tmp = NULL;
2149 char *name = NULL;
2151 if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
2152 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
2153 CLEAR_STACK_FRAME;
2154 return;
2155 }
2157 name = SvPV_nolen (tmp);
2159 if (NULL == get_cv (name, 0)) {
2160 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
2161 CLEAR_STACK_FRAME;
2162 return;
2163 }
2165 /* simply pass on the subroutine call without touching the stack,
2166 * thus leaving any arguments and return values in place */
2167 call_pv (name, 0);
2168 } /* static XS (Collectd_call_by_name) */
2170 /*
2171 * Interface to collectd.
2172 */
2174 static int perl_init (void)
2175 {
2176 int status;
2177 dTHX;
2179 if (NULL == perl_threads)
2180 return 0;
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 log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
2193 aTHX, perl_threads->number_of_threads);
2195 /* Lock the base thread to avoid race conditions with c_ithread_create().
2196 * See https://github.com/collectd/collectd/issues/9 and
2197 * https://github.com/collectd/collectd/issues/1706 for details.
2198 */
2199 assert (aTHX == perl_threads->head->interp);
2200 pthread_mutex_lock (&perl_threads->mutex);
2202 status = pplugin_call (aTHX_ PLUGIN_INIT);
2204 pthread_mutex_unlock (&perl_threads->mutex);
2206 return status;
2207 } /* static int perl_init (void) */
2209 static int perl_read (user_data_t *user_data)
2210 {
2211 dTHX;
2213 if (NULL == perl_threads)
2214 return 0;
2216 if (NULL == aTHX) {
2217 c_ithread_t *t = NULL;
2219 pthread_mutex_lock (&perl_threads->mutex);
2220 t = c_ithread_create (perl_threads->head->interp);
2221 pthread_mutex_unlock (&perl_threads->mutex);
2223 aTHX = t->interp;
2224 }
2226 /* Assert that we're not running as the base thread. Otherwise, we might
2227 * run into concurrency issues with c_ithread_create(). See
2228 * https://github.com/collectd/collectd/issues/9 for details. */
2229 assert (aTHX != perl_threads->head->interp);
2231 log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
2232 aTHX, perl_threads->number_of_threads);
2234 return pplugin_call (aTHX_ PLUGIN_READ, user_data->data);
2235 } /* static int perl_read (user_data_t *user_data) */
2237 static int perl_write (const data_set_t *ds, const value_list_t *vl,
2238 user_data_t *user_data)
2239 {
2240 int status;
2241 dTHX;
2243 if (NULL == perl_threads)
2244 return 0;
2246 if (NULL == aTHX) {
2247 c_ithread_t *t = NULL;
2249 pthread_mutex_lock (&perl_threads->mutex);
2250 t = c_ithread_create (perl_threads->head->interp);
2251 pthread_mutex_unlock (&perl_threads->mutex);
2253 aTHX = t->interp;
2254 }
2256 /* Lock the base thread if this is not called from one of the read threads
2257 * to avoid race conditions with c_ithread_create(). See
2258 * https://github.com/collectd/collectd/issues/9 for details. */
2259 if (aTHX == perl_threads->head->interp)
2260 pthread_mutex_lock (&perl_threads->mutex);
2262 log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
2263 aTHX, perl_threads->number_of_threads);
2264 status = pplugin_call (aTHX_ PLUGIN_WRITE, user_data->data, ds, vl);
2266 if (aTHX == perl_threads->head->interp)
2267 pthread_mutex_unlock (&perl_threads->mutex);
2269 return status;
2270 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2272 static void perl_log (int level, const char *msg,
2273 user_data_t *user_data)
2274 {
2275 dTHX;
2277 if (NULL == perl_threads)
2278 return;
2280 if (NULL == aTHX) {
2281 c_ithread_t *t = NULL;
2283 pthread_mutex_lock (&perl_threads->mutex);
2284 t = c_ithread_create (perl_threads->head->interp);
2285 pthread_mutex_unlock (&perl_threads->mutex);
2287 aTHX = t->interp;
2288 }
2290 /* Lock the base thread if this is not called from one of the read threads
2291 * to avoid race conditions with c_ithread_create(). See
2292 * https://github.com/collectd/collectd/issues/9 for details.
2293 */
2295 if (aTHX == perl_threads->head->interp)
2296 pthread_mutex_lock (&perl_threads->mutex);
2298 pplugin_call (aTHX_ PLUGIN_LOG, user_data->data, level, msg);
2300 if (aTHX == perl_threads->head->interp)
2301 pthread_mutex_unlock (&perl_threads->mutex);
2303 return;
2304 } /* static void perl_log (int, const char *) */
2306 static int perl_notify (const notification_t *notif, user_data_t *user_data)
2307 {
2308 dTHX;
2310 if (NULL == perl_threads)
2311 return 0;
2313 if (NULL == aTHX) {
2314 c_ithread_t *t = NULL;
2316 pthread_mutex_lock (&perl_threads->mutex);
2317 t = c_ithread_create (perl_threads->head->interp);
2318 pthread_mutex_unlock (&perl_threads->mutex);
2320 aTHX = t->interp;
2321 }
2322 return pplugin_call (aTHX_ PLUGIN_NOTIF, user_data->data, notif);
2323 } /* static int perl_notify (const notification_t *) */
2325 static int perl_flush (cdtime_t timeout, const char *identifier,
2326 user_data_t *user_data)
2327 {
2328 dTHX;
2330 if (NULL == perl_threads)
2331 return 0;
2333 if (NULL == aTHX) {
2334 c_ithread_t *t = NULL;
2336 pthread_mutex_lock (&perl_threads->mutex);
2337 t = c_ithread_create (perl_threads->head->interp);
2338 pthread_mutex_unlock (&perl_threads->mutex);
2340 aTHX = t->interp;
2341 }
2343 /* For collectd-5.6 only, #1731 */
2344 if (user_data == NULL || user_data->data == NULL)
2345 return pplugin_call (aTHX_ PLUGIN_FLUSH_ALL, timeout, identifier);
2347 return pplugin_call (aTHX_ PLUGIN_FLUSH, user_data->data, timeout, identifier);
2348 } /* static int perl_flush (const int) */
2350 static int perl_shutdown (void)
2351 {
2352 c_ithread_t *t;
2353 int ret;
2355 dTHX;
2357 plugin_unregister_complex_config ("perl");
2358 plugin_unregister_read_group ("perl");
2360 if (NULL == perl_threads)
2361 return 0;
2363 if (NULL == aTHX) {
2364 pthread_mutex_lock (&perl_threads->mutex);
2365 t = c_ithread_create (perl_threads->head->interp);
2366 pthread_mutex_unlock (&perl_threads->mutex);
2368 aTHX = t->interp;
2369 }
2371 log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2372 aTHX, perl_threads->number_of_threads);
2374 plugin_unregister_init ("perl");
2375 plugin_unregister_flush ("perl"); /* For collectd-5.6 only, #1731 */
2377 ret = pplugin_call (aTHX_ PLUGIN_SHUTDOWN);
2379 pthread_mutex_lock (&perl_threads->mutex);
2380 t = perl_threads->tail;
2382 while (NULL != t) {
2383 struct timespec ts_wait;
2384 c_ithread_t *thr = t;
2386 /* the pointer has to be advanced before destroying
2387 * the thread as this will free the memory */
2388 t = t->prev;
2390 thr->shutdown = 1;
2391 if (thr->running) {
2392 /* Give some time to thread to exit from Perl interpreter */
2393 WARNING ("perl shutdown: Thread is running inside Perl. Waiting.");
2394 ts_wait.tv_sec = 0;
2395 ts_wait.tv_nsec = 500000;
2396 nanosleep (&ts_wait, NULL);
2397 }
2398 if (thr->running) {
2399 pthread_kill (thr->pthread, SIGTERM);
2400 ERROR ("perl shutdown: Thread hangs inside Perl. Thread killed.");
2401 }
2402 c_ithread_destroy (thr);
2403 }
2405 pthread_mutex_unlock (&perl_threads->mutex);
2406 pthread_mutex_destroy (&perl_threads->mutex);
2407 pthread_mutexattr_destroy (&perl_threads->mutexattr);
2409 sfree (perl_threads);
2411 pthread_key_delete (perl_thr_key);
2413 PERL_SYS_TERM ();
2415 plugin_unregister_shutdown ("perl");
2416 return ret;
2417 } /* static void perl_shutdown (void) */
2419 /*
2420 * Access functions for global variables.
2421 *
2422 * These functions implement the "magic" used to access
2423 * the global variables from Perl.
2424 */
2426 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
2427 {
2428 char *pv = mg->mg_ptr;
2429 sv_setpv (var, pv);
2430 return 0;
2431 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2433 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
2434 {
2435 char *pv = mg->mg_ptr;
2436 sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
2437 return 0;
2438 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2440 static int g_interval_get (pTHX_ SV *var, MAGIC *mg)
2441 {
2442 log_warn ("Accessing $interval_g is deprecated (and might not "
2443 "give the desired results) - plugin_get_interval() should "
2444 "be used instead.");
2445 sv_setnv (var, CDTIME_T_TO_DOUBLE (interval_g));
2446 return 0;
2447 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2449 static int g_interval_set (pTHX_ SV *var, MAGIC *mg)
2450 {
2451 double nv = (double)SvNV (var);
2452 log_warn ("Accessing $interval_g is deprecated (and might not "
2453 "give the desired results) - plugin_get_interval() should "
2454 "be used instead.");
2455 interval_g = DOUBLE_TO_CDTIME_T (nv);
2456 return 0;
2457 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2459 static MGVTBL g_pv_vtbl = {
2460 g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2461 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2462 , NULL
2463 #endif
2464 };
2465 static MGVTBL g_interval_vtbl = {
2466 g_interval_get, g_interval_set, NULL, NULL, NULL, NULL, NULL
2467 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2468 , NULL
2469 #endif
2470 };
2472 /* bootstrap the Collectd module */
2473 static void xs_init (pTHX)
2474 {
2475 HV *stash = NULL;
2476 SV *tmp = NULL;
2477 char *file = __FILE__;
2479 dXSUB_SYS;
2481 /* enable usage of Perl modules using shared libraries */
2482 newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2484 /* register API */
2485 for (int i = 0; NULL != api[i].f; ++i)
2486 newXS (api[i].name, api[i].f, file);
2488 stash = gv_stashpv ("Collectd", 1);
2490 /* export "constants" */
2491 for (int i = 0; '\0' != constants[i].name[0]; ++i)
2492 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
2494 /* export global variables
2495 * by adding "magic" to the SV's representing the globale variables
2496 * perl is able to automagically call the get/set function when
2497 * accessing any such variable (this is basically the same as using
2498 * tie() in Perl) */
2499 /* global strings */
2500 for (int i = 0; '\0' != g_strings[i].name[0]; ++i) {
2501 tmp = get_sv (g_strings[i].name, 1);
2502 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
2503 g_strings[i].var, 0);
2504 }
2506 tmp = get_sv ("Collectd::interval_g", /* create = */ 1);
2507 sv_magicext (tmp, NULL, /* how = */ PERL_MAGIC_ext,
2508 /* vtbl = */ &g_interval_vtbl,
2509 /* name = */ NULL, /* namelen = */ 0);
2511 return;
2512 } /* static void xs_init (pTHX) */
2514 /* Initialize the global Perl interpreter. */
2515 static int init_pi (int argc, char **argv)
2516 {
2517 dTHXa (NULL);
2519 if (NULL != perl_threads)
2520 return 0;
2522 log_info ("Initializing Perl interpreter...");
2523 #if COLLECT_DEBUG
2524 {
2525 for (int i = 0; i < argc; ++i)
2526 log_debug ("argv[%i] = \"%s\"", i, argv[i]);
2527 }
2528 #endif /* COLLECT_DEBUG */
2530 if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
2531 log_err ("init_pi: pthread_key_create failed");
2533 /* this must not happen - cowardly giving up if it does */
2534 return -1;
2535 }
2537 #ifdef __FreeBSD__
2538 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2539 * triggers a "value computed is not used" warning by gcc. */
2540 (void)
2541 #endif
2542 PERL_SYS_INIT3 (&argc, &argv, &environ);
2544 perl_threads = smalloc (sizeof (*perl_threads));
2545 memset (perl_threads, 0, sizeof (c_ithread_list_t));
2547 pthread_mutexattr_init(&perl_threads->mutexattr);
2548 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2549 pthread_mutex_init (&perl_threads->mutex, &perl_threads->mutexattr);
2550 /* locking the mutex should not be necessary at this point
2551 * but let's just do it for the sake of completeness */
2552 pthread_mutex_lock (&perl_threads->mutex);
2554 perl_threads->head = c_ithread_create (NULL);
2555 perl_threads->tail = perl_threads->head;
2557 if (NULL == (perl_threads->head->interp = perl_alloc ())) {
2558 log_err ("init_pi: Not enough memory.");
2559 exit (3);
2560 }
2562 aTHX = perl_threads->head->interp;
2563 pthread_mutex_unlock (&perl_threads->mutex);
2565 perl_construct (aTHX);
2567 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2569 if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
2570 SV *err = get_sv ("@", 1);
2571 log_err ("init_pi: Unable to bootstrap Collectd: %s",
2572 SvPV_nolen (err));
2574 perl_destruct (perl_threads->head->interp);
2575 perl_free (perl_threads->head->interp);
2576 sfree (perl_threads);
2578 pthread_key_delete (perl_thr_key);
2579 return -1;
2580 }
2582 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2583 sv_setpv (get_sv ("0", 0), "collectd");
2585 perl_run (aTHX);
2587 plugin_register_init ("perl", perl_init);
2588 plugin_register_shutdown ("perl", perl_shutdown);
2589 return 0;
2590 } /* static int init_pi (const char **, const int) */
2592 /*
2593 * LoadPlugin "<Plugin>"
2594 */
2595 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
2596 {
2597 char module_name[DATA_MAX_NAME_LEN];
2599 char *value = NULL;
2601 if ((0 != ci->children_num) || (1 != ci->values_num)
2602 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2603 log_err ("LoadPlugin expects a single string argument.");
2604 return 1;
2605 }
2607 value = ci->values[0].value.string;
2609 if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
2610 log_err ("Invalid module name %s", value);
2611 return (1);
2612 }
2614 if (0 != init_pi (perl_argc, perl_argv))
2615 return -1;
2617 assert (NULL != perl_threads);
2618 assert (NULL != perl_threads->head);
2620 aTHX = perl_threads->head->interp;
2622 log_debug ("perl_config: Loading Perl plugin \"%s\"", value);
2623 load_module (PERL_LOADMOD_NOIMPORT,
2624 newSVpv (module_name, strlen (module_name)), Nullsv);
2625 return 0;
2626 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2628 /*
2629 * BaseName "<Name>"
2630 */
2631 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
2632 {
2633 char *value = NULL;
2635 if ((0 != ci->children_num) || (1 != ci->values_num)
2636 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2637 log_err ("BaseName expects a single string argument.");
2638 return 1;
2639 }
2641 value = ci->values[0].value.string;
2643 log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
2644 sstrncpy (base_name, value, sizeof (base_name));
2645 return 0;
2646 } /* static int perl_config_basename (oconfig_item_it *) */
2648 /*
2649 * EnableDebugger "<Package>"|""
2650 */
2651 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
2652 {
2653 char *value = NULL;
2655 if ((0 != ci->children_num) || (1 != ci->values_num)
2656 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2657 log_err ("EnableDebugger expects a single string argument.");
2658 return 1;
2659 }
2661 if (NULL != perl_threads) {
2662 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
2663 return 1;
2664 }
2666 value = ci->values[0].value.string;
2668 perl_argv = realloc (perl_argv,
2669 (++perl_argc + 1) * sizeof (char *));
2671 if (NULL == perl_argv) {
2672 log_err ("perl_config: Not enough memory.");
2673 exit (3);
2674 }
2676 if ('\0' == value[0]) {
2677 perl_argv[perl_argc - 1] = "-d";
2678 }
2679 else {
2680 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 4);
2681 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
2682 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
2683 }
2685 perl_argv[perl_argc] = NULL;
2686 return 0;
2687 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2689 /*
2690 * IncludeDir "<Dir>"
2691 */
2692 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
2693 {
2694 char *value = NULL;
2696 if ((0 != ci->children_num) || (1 != ci->values_num)
2697 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2698 log_err ("IncludeDir expects a single string argument.");
2699 return 1;
2700 }
2702 value = ci->values[0].value.string;
2704 if (NULL == aTHX) {
2705 perl_argv = realloc (perl_argv,
2706 (++perl_argc + 1) * sizeof (char *));
2708 if (NULL == perl_argv) {
2709 log_err ("perl_config: Not enough memory.");
2710 exit (3);
2711 }
2713 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 3);
2714 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2715 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
2717 perl_argv[perl_argc] = NULL;
2718 }
2719 else {
2720 /* prepend the directory to @INC */
2721 av_unshift (GvAVn (PL_incgv), 1);
2722 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
2723 }
2724 return 0;
2725 } /* static int perl_config_includedir (oconfig_item_it *) */
2727 /*
2728 * <Plugin> block
2729 */
2730 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2731 {
2732 int retvals = 0;
2733 int ret = 0;
2735 char *plugin;
2736 HV *config;
2738 dSP;
2740 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2741 log_err ("LoadPlugin expects a single string argument.");
2742 return 1;
2743 }
2745 plugin = ci->values[0].value.string;
2746 config = newHV ();
2748 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2749 hv_clear (config);
2750 hv_undef (config);
2752 log_err ("Unable to convert configuration to a Perl hash value.");
2753 config = (HV *)&PL_sv_undef;
2754 }
2756 ENTER;
2757 SAVETMPS;
2759 PUSHMARK (SP);
2761 XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2762 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2764 PUTBACK;
2766 retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2768 SPAGAIN;
2769 if (0 < retvals) {
2770 SV *tmp = POPs;
2771 if (! SvTRUE (tmp))
2772 ret = 1;
2773 }
2774 else
2775 ret = 1;
2777 PUTBACK;
2778 FREETMPS;
2779 LEAVE;
2780 return ret;
2781 } /* static int perl_config_plugin (oconfig_item_it *) */
2783 static int perl_config (oconfig_item_t *ci)
2784 {
2785 int status = 0;
2787 dTHXa (NULL);
2789 for (int i = 0; i < ci->children_num; ++i) {
2790 oconfig_item_t *c = ci->children + i;
2791 int current_status = 0;
2793 if (NULL != perl_threads)
2794 {
2795 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2796 return -1;
2797 }
2799 if (0 == strcasecmp (c->key, "LoadPlugin"))
2800 current_status = perl_config_loadplugin (aTHX_ c);
2801 else if (0 == strcasecmp (c->key, "BaseName"))
2802 current_status = perl_config_basename (aTHX_ c);
2803 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2804 current_status = perl_config_enabledebugger (aTHX_ c);
2805 else if (0 == strcasecmp (c->key, "IncludeDir"))
2806 current_status = perl_config_includedir (aTHX_ c);
2807 else if (0 == strcasecmp (c->key, "Plugin"))
2808 current_status = perl_config_plugin (aTHX_ c);
2809 else if (0 == strcasecmp (c->key, "RegisterLegacyFlush"))
2810 cf_util_get_boolean (c, ®ister_legacy_flush);
2811 else
2812 {
2813 log_warn ("Ignoring unknown config key \"%s\".", c->key);
2814 current_status = 0;
2815 }
2817 /* fatal error - it's up to perl_config_* to clean up */
2818 if (0 > current_status) {
2819 log_err ("Configuration failed with a fatal error - "
2820 "plugin disabled!");
2821 return current_status;
2822 }
2824 status += current_status;
2825 }
2826 return status;
2827 } /* static int perl_config (oconfig_item_t *) */
2829 void module_register (void)
2830 {
2831 perl_argc = 4;
2832 perl_argv = smalloc ((perl_argc + 1) * sizeof (*perl_argv));
2834 /* default options for the Perl interpreter */
2835 perl_argv[0] = "";
2836 perl_argv[1] = "-MCollectd";
2837 perl_argv[2] = "-e";
2838 perl_argv[3] = "1";
2839 perl_argv[4] = NULL;
2841 plugin_register_complex_config ("perl", perl_config);
2842 return;
2843 } /* void module_register (void) */
2845 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */