Use ServletHolder lifecycle more carefully

Fixes metrics with Jetty > 9.4.20
This commit is contained in:
Simon Detheridge 2021-06-22 15:38:43 +01:00
parent 70f4e5801d
commit 63ca055637
2 changed files with 32 additions and 10 deletions

View file

@ -127,7 +127,7 @@ public class GitBridgeServer {
handlers.addHandler(new StatusHandler(bridge)); handlers.addHandler(new StatusHandler(bridge));
handlers.addHandler(new HealthCheckHandler(bridge)); handlers.addHandler(new HealthCheckHandler(bridge));
handlers.addHandler(new GitLfsHandler(bridge)); handlers.addHandler(new GitLfsHandler(bridge));
handlers.addHandler(new PrometheusHandler(bridge)); handlers.addHandler(new PrometheusHandler());
base.setHandler(handlers); base.setHandler(handlers);
return base; return base;
} }

View file

@ -18,17 +18,30 @@ import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
/**
* Wrapper for the MetricsServlet from the Prometheus client.
*
* We wrap this in a handler here, as we use a wildcard servlet context on /*, and adding
* an additional servlet context collides with it. Adding a servlet context on /metrics
* causes a redirect to /metrics/ which breaks things when jetty doesn't know the full
* public URL.
*
* There may still be a better way to do this, but it works.
**/
public class PrometheusHandler extends AbstractHandler { public class PrometheusHandler extends AbstractHandler {
private final Bridge bridge;
private final MetricsServlet metricsServlet;
private final ServletHolder holder; private final ServletHolder holder;
public PrometheusHandler(Bridge bridge) { public PrometheusHandler() {
this.bridge = bridge;
this.metricsServlet = new MetricsServlet();
this.holder = new ServletHolder(metricsServlet);
DefaultExports.initialize(); DefaultExports.initialize();
this.holder = new ServletHolder(new MetricsServlet());
try {
this.holder.initialize();
} catch (Exception e) {
Log.error("Unable to initialise metrics servlet: " + e.getMessage());
}
} }
@Override @Override
@ -45,11 +58,20 @@ public class PrometheusHandler extends AbstractHandler {
&& target.matches("^/metrics/?$") && target.matches("^/metrics/?$")
) { ) {
Log.info(method + " <- /metrics"); Log.info(method + " <- /metrics");
response.setContentType("application/vnd.git-lfs+json");
response.setStatus(200); if (!this.holder.isAvailable()) {
try {
this.holder.start();
} catch (Exception e) {
Log.error("Unable to start metrics servlet: " + e.getMessage());
response.setStatus(500);
baseRequest.setHandled(true);
return;
}
}
this.holder.handle(baseRequest, request, response); this.holder.handle(baseRequest, request, response);
baseRequest.setHandled(true); baseRequest.setHandled(true);
} }
} }
} }