package org.apache.catalina.valves;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.util.LifecycleBase;
import org.apache.tomcat.util.buf.MessageBytes;
public class HealthCheckValve extends ValveBase {
private static final String UP =
"{\n" +
" \"status\": \"UP\",\n" +
" \"checks\": []\n" +
"}";
private static final String DOWN =
"{\n" +
" \"status\": \"DOWN\",\n" +
" \"checks\": []\n" +
"}";
private String path = "/health";
protected boolean context = false;
protected boolean checkContainersAvailable = true;
public HealthCheckValve() {
super(true);
}
public final String getPath() {
return path;
}
public final void setPath(String path) {
this.path = path;
}
public boolean getCheckContainersAvailable() {
return this.checkContainersAvailable;
}
public void setCheckContainersAvailable(boolean checkContainersAvailable) {
this.checkContainersAvailable = checkContainersAvailable;
}
@Override
protected synchronized void startInternal() throws LifecycleException {
super.startInternal();
context = (getContainer() instanceof Context);
}
@Override
public void invoke(Request request, Response response)
throws IOException, ServletException {
MessageBytes urlMB =
context ? request.getRequestPathMB() : request.getDecodedRequestURIMB();
if (urlMB.equals(path)) {
response.setContentType("application/json");
if (!checkContainersAvailable || isAvailable(getContainer())) {
response.getOutputStream().print(UP);
} else {
response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
response.getOutputStream().print(DOWN);
}
} else {
getNext().invoke(request, response);
}
}
protected boolean isAvailable(Container container) {
for (Container child : container.findChildren()) {
if (!isAvailable(child)) {
return false;
}
}
if (container instanceof LifecycleBase) {
return ((LifecycleBase) container).getState().isAvailable();
} else {
return true;
}
}
}