Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Beanshell support to extend value field functionality #619

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions collector/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,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 @@ -496,11 +498,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 @@ -580,6 +580,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