0

I have a Spring Boot 2.3.1 application with actuator deployed on Kubernetes with the corresponding K8s probes mapped against the actuator endpoints:

livenessProbe:
  httpGet:
    path: /actuator/health/liveness
    ...

readinessProbe:
  httpGet:
    path: /actuator/health/readiness
    ...

I'd like to detect when K8s invokes each of the probes, get the execution result and some other pieces of info (pod name...) and send it to an http endpoint.

How could I detect those invocations and access its result? Is there some kind of Spring hook/listener that allows me to do it?

codependent
  • 23,193
  • 31
  • 166
  • 308

2 Answers2

0

This may not be the most elegant solution to your problem, but will do the trick.

Simply intercept the actuator call and do what you need to do after the response is sent.

@Component
public class ActuatorHandlerInterceptorAdapter extends HandlerInterceptorAdapter {

  private static final Logger logger = LoggerFactory
      .getLogger(ActuatorHandlerInterceptorAdapter.class);

  @Override
  public void afterCompletion(HttpServletRequest request,
      HttpServletResponse response, Object handler, Exception ex)
      throws Exception {
    if (request.getRequestURL().toString().contains("actuator/health/liveness")){
      System.out.println("Let's do something based on liveness response");
    }
    if (request.getRequestURL().toString().contains("actuator/health/readiness")){
      System.out.println("Let's do something based on readiness response");
    }
  }

}
FrancescoM
  • 1,400
  • 11
  • 16
0

The equivalent for Webflux applications would be:

@Component
public class ActuatorHealthWebFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerWebExchange exc = exchange;
        if(exchange.getRequest().getURI().toString().contains("/actuator/health")){
            exc = exchange.mutate().response(new ServerHttpResponseDecorator(exchange.getResponse()) {
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                    Mono<DataBuffer> buffer = Mono.from(body);
                    return super.writeWith(buffer.doOnNext(dataBuffer -> {
                        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
                            Channels.newChannel(byteArrayOutputStream).write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
                            String responseBody = byteArrayOutputStream.toString(UTF_8);
                            System.out.println(responseBody);
                            //TODO Do something with the response info
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }));
                }
            }).build();
        }
        return chain.filter(exc);
    }
}
codependent
  • 23,193
  • 31
  • 166
  • 308