From 17ec981881a6dde56588516a5bce5c9c61dfa806 Mon Sep 17 00:00:00 2001 From: Csaba Karsai Date: Thu, 8 Jul 2021 10:17:41 +0200 Subject: [PATCH] added beanshell support for value field Signed-off-by: Csaba Karsai --- collector/pom.xml | 5 ++++ .../java/io/prometheus/jmx/JmxCollector.java | 23 +++++++++++++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/collector/pom.xml b/collector/pom.xml index af16826c..012213ab 100644 --- a/collector/pom.xml +++ b/collector/pom.xml @@ -19,6 +19,11 @@ io.prometheus simpleclient + + org.beanshell + bsh-core + 2.0b4 + junit junit diff --git a/collector/src/main/java/io/prometheus/jmx/JmxCollector.java b/collector/src/main/java/io/prometheus/jmx/JmxCollector.java index 7758bd5f..78dd17b3 100644 --- a/collector/src/main/java/io/prometheus/jmx/JmxCollector.java +++ b/collector/src/main/java/io/prometheus/jmx/JmxCollector.java @@ -1,5 +1,7 @@ package io.prometheus.jmx; +import bsh.EvalError; +import bsh.Interpreter; import io.prometheus.client.Collector; import io.prometheus.client.Counter; import org.yaml.snakeyaml.Yaml; @@ -444,11 +446,9 @@ public void recordBean( Double value = null; if (rule.value != null && !rule.value.isEmpty()) { - String val = matcher.replaceAll(rule.value); try { - value = Double.valueOf(val); - } catch (NumberFormatException e) { - LOGGER.fine("Unable to parse configured value '" + val + "' to number for bean: " + beanName + attrName + ": " + beanValue); + value = evaluateValueExpression(matcher, rule.value); + } catch (RuntimeException e) { return; } } @@ -528,6 +528,21 @@ public void recordBean( } + private Double evaluateValueExpression(Matcher matcher, String value) { + try { + Interpreter interpreter = new Interpreter(); + List groups = new ArrayList(matcher.groupCount()); + for(int i=0; i<=matcher.groupCount(); i++) { + groups.add(matcher.group(i)); + } + interpreter.set("matches", groups); + return Double.valueOf(interpreter.eval(matcher.replaceAll(value)).toString()); + } catch (EvalError e) { + LOGGER.fine(e.toString()); + throw new RuntimeException(e); + } + } + public List collect() { // Take a reference to the current config and collect with this one // (to avoid race conditions in case another thread reloads the config in the meantime)