Skip to content

Instantly share code, notes, and snippets.

@gjesse
Created May 19, 2016 00:01
Show Gist options
  • Save gjesse/f31be0217b4366d7cb1c01d2fb281c19 to your computer and use it in GitHub Desktop.
Save gjesse/f31be0217b4366d7cb1c01d2fb281c19 to your computer and use it in GitHub Desktop.
/**
* Gauge-based health check that will return unhealthy if the
* gauge value falls below the threshold
*/
public class RatioGaugeHealthCheck extends HealthCheck {
private final RatioGauge gauge;
private final double threshold;
private final String name;
public RatioGaugeHealthCheck(String name, RatioGauge gauge, double threshold) {
this.name = requireNonNull(name);
this.gauge = requireNonNull(gauge);
this.threshold = threshold;
checkArgument(!name.isEmpty(), "name must be specified");
checkArgument(threshold >= 0 && threshold <= 1, String.format("threshold out of range: [%.02f]", threshold));
}
public String getName() {
return name;
}
@Override
protected Result check() throws Exception {
final Double value = gauge.getValue();
if (Double.isNaN(value)) {
return Result.healthy("Unable to determine health. Gauge value is Double.NaN. The gauge may have no data or there may be a problem.");
} else if ( value >= threshold ) {
return Result.healthy();
} else {
return Result.unhealthy("Healthcheck [%s] value of %.02f is below threshold %.02f", name, value, threshold);
}
}
}
// mark these meters on success/failure
private static final Meter PUBLISH_STATE_OK = new Meter();
private static final Meter PUBLISH_STATE_NOT_OK = new Meter();
private static final RatioGauge PUBLISH_STATE_GAUGE = new RatioGauge() {
@Override
protected Ratio getRatio() {
final double numerator = PUBLISH_STATE_OK.getOneMinuteRate();
final double denominator = numerator + PUBLISH_STATE_NOT_OK.getOneMinuteRate();
return Ratio.of(numerator, denominator);
}
};
// register a health check
final RatioGaugeHealthCheck check =
new RatioGaugeHealthCheck("publish-success", PUBLISH_STATE_GAUGE, configuration.getPublishHealthThreshold());
environment.healthChecks().register(check.getName(), check);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment