Skip to content

Commit

Permalink
added beanshell support for value field
Browse files Browse the repository at this point in the history
Signed-off-by: Csaba Karsai <[email protected]>
  • Loading branch information
Csaba-emnify committed Jul 12, 2021
1 parent 1807e79 commit 17ec981
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
5 changes: 5 additions & 0 deletions collector/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@
<groupId>io.prometheus</groupId>
<artifactId>simpleclient</artifactId>
</dependency>
<dependency>
<groupId>org.beanshell</groupId>
<artifactId>bsh-core</artifactId>
<version>2.0b4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
Expand Down
23 changes: 19 additions & 4 deletions collector/src/main/java/io/prometheus/jmx/JmxCollector.java
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -528,6 +528,21 @@ public void recordBean(

}

private Double evaluateValueExpression(Matcher matcher, String value) {
try {
Interpreter interpreter = new Interpreter();
List<String> groups = new ArrayList<String>(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<MetricFamilySamples> 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)
Expand Down

0 comments on commit 17ec981

Please sign in to comment.