String arguments = argsRegex.get(METRIC_PROPERTY_ARGUMENTS);
String regex = argsRegex.get(METRIC_PROPERTY_REGEX);
boolean valueIsExitCode = METRIC_PROPERTY_EXITCODE.equals(regex);
// if we already executed it with the same arguments, don't bother doing it again
ProcessExecutionResults exeResults = exeResultsCache.get((arguments == null) ? "" : arguments);
if (exeResults == null) {
boolean captureOutput = !valueIsExitCode; // don't need output if we need to just check exit code
exeResults = executeExecutable(arguments, DEFAULT_MAX_WAIT_TIME, captureOutput);
exeResultsCache.put((arguments == null) ? "" : arguments, exeResults);
}
// don't report a metric value if the CLI failed to execute
if (exeResults.getError() != null) {
LOG.error("Cannot collect CLI metric [" + metricPropertyName + "]. Cause: "
+ ThrowableUtil.getAllMessages(exeResults.getError()));
continue;
}
// set dataValue to the appropriate value based on how the metric property defined it
if (valueIsExitCode) {
dataValue = exeResults.getExitCode();
if (dataValue == null) {
LOG.error("Could not determine exit code for metric property [" + metricPropertyName
+ "] - metric will not be collected");
continue;
}
} else if (regex != null) {
String output = exeResults.getCapturedOutput();
if (output == null) {
LOG.error("Could not get output for metric property [" + metricPropertyName
+ "] -- metric will not be collected");
continue;
} else {
output = output.trim();
}
Pattern pattern = Pattern.compile(regex);
Matcher match = pattern.matcher(output);
if (match.find()) {
if (match.groupCount() > 0) {
dataValue = match.group(1);
} else {
dataValue = output;
}
} else {
LOG.error("Output did not match metric property [" + metricPropertyName
+ "] - metric will not be collected: " + truncateString(output));
continue;
}
} else {
dataValue = exeResults.getCapturedOutput();
if (dataValue == null) {
LOG.error("Could not get output for metric property [" + metricPropertyName
+ "] - metric will not be collected");
continue;
}