|
| 1 | +package de.tum.in.www1.hephaestus.observability; |
| 2 | + |
| 3 | +import jakarta.annotation.PostConstruct; |
| 4 | +import jakarta.servlet.FilterChain; |
| 5 | +import jakarta.servlet.ServletException; |
| 6 | +import jakarta.servlet.http.HttpServletRequest; |
| 7 | +import jakarta.servlet.http.HttpServletResponse; |
| 8 | +import java.io.IOException; |
| 9 | +import java.net.InetAddress; |
| 10 | +import java.net.UnknownHostException; |
| 11 | +import org.slf4j.Logger; |
| 12 | +import org.slf4j.LoggerFactory; |
| 13 | +import org.springframework.core.Ordered; |
| 14 | +import org.springframework.core.annotation.Order; |
| 15 | +import org.springframework.stereotype.Component; |
| 16 | +import org.springframework.web.filter.OncePerRequestFilter; |
| 17 | + |
| 18 | +/** Stamps every response with the serving replica id — see docs/contributor/unified-pi-runtime.mdx. */ |
| 19 | +@Component |
| 20 | +@Order(Ordered.HIGHEST_PRECEDENCE) |
| 21 | +public class ReplicaIdentityFilter extends OncePerRequestFilter { |
| 22 | + |
| 23 | + public static final String HEADER_NAME = "X-Hephaestus-Replica"; |
| 24 | + |
| 25 | + private static final Logger log = LoggerFactory.getLogger(ReplicaIdentityFilter.class); |
| 26 | + private static final String REPLICA_ID = resolveReplicaId(); |
| 27 | + |
| 28 | + @Override |
| 29 | + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) |
| 30 | + throws ServletException, IOException { |
| 31 | + response.setHeader(HEADER_NAME, REPLICA_ID); |
| 32 | + chain.doFilter(request, response); |
| 33 | + } |
| 34 | + |
| 35 | + @PostConstruct |
| 36 | + void announceReplica() { |
| 37 | + log.info("Replica id: {}", REPLICA_ID); |
| 38 | + } |
| 39 | + |
| 40 | + // HOSTNAME is the container id under Docker; InetAddress fallback is dev-only. |
| 41 | + private static String resolveReplicaId() { |
| 42 | + String env = System.getenv("HOSTNAME"); |
| 43 | + if (env != null && !env.isBlank()) return env; |
| 44 | + try { |
| 45 | + return InetAddress.getLocalHost().getHostName(); |
| 46 | + } catch (UnknownHostException e) { |
| 47 | + return "unknown"; |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments