From 0cca83da7b992f44fe1f98ec35667f528d7dbaf2 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Tue, 17 Feb 2026 13:01:16 +0530 Subject: [PATCH 1/9] feat(health,version): add health and version endpoints --- pom.xml | 26 ++ .../controller/health/HealthController.java | 118 +++++++ .../controller/version/VersionController.java | 79 +++++ .../fhir/service/health/HealthService.java | 310 ++++++++++++++++++ .../fhir/utils/JwtUserIdValidationFilter.java | 4 +- 5 files changed, 536 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/wipro/fhir/controller/health/HealthController.java create mode 100644 src/main/java/com/wipro/fhir/controller/version/VersionController.java create mode 100644 src/main/java/com/wipro/fhir/service/health/HealthService.java diff --git a/pom.xml b/pom.xml index 0479b05..2c7ac4a 100644 --- a/pom.xml +++ b/pom.xml @@ -456,6 +456,32 @@ + + io.github.git-commit-id + git-commit-id-maven-plugin + 7.0.0 + + + get-the-git-infos + + revision + + initialize + + + + true + ${project.build.outputDirectory}/git.properties + + ^git.branch$ + ^git.commit.id.abbrev$ + ^git.build.version$ + ^git.build.time$ + + false + false + + org.springframework.boot spring-boot-maven-plugin diff --git a/src/main/java/com/wipro/fhir/controller/health/HealthController.java b/src/main/java/com/wipro/fhir/controller/health/HealthController.java new file mode 100644 index 0000000..a39067e --- /dev/null +++ b/src/main/java/com/wipro/fhir/controller/health/HealthController.java @@ -0,0 +1,118 @@ +package com.wipro.fhir.controller.health; + +import java.time.Instant; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import com.wipro.fhir.service.health.HealthService; +import com.wipro.fhir.utils.JwtAuthenticationUtil; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + + +@RestController +@RequestMapping("/health") +@Tag(name = "Health Check", description = "APIs for checking infrastructure health status") +public class HealthController { + + private static final Logger logger = LoggerFactory.getLogger(HealthController.class); + + private final HealthService healthService; + private final JwtAuthenticationUtil jwtAuthenticationUtil; + + public HealthController(HealthService healthService, JwtAuthenticationUtil jwtAuthenticationUtil) { + this.healthService = healthService; + this.jwtAuthenticationUtil = jwtAuthenticationUtil; + } + @GetMapping + @Operation(summary = "Check infrastructure health", + description = "Returns the health status of MySQL, Redis, and other configured services") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "All checked components are UP"), + @ApiResponse(responseCode = "503", description = "One or more critical services are DOWN") + }) + public ResponseEntity> checkHealth(HttpServletRequest request) { + logger.info("Health check endpoint called"); + + try { + // Check if user is authenticated by verifying Authorization header + boolean isAuthenticated = isUserAuthenticated(request); + Map healthStatus = healthService.checkHealth(isAuthenticated); + String overallStatus = (String) healthStatus.get("status"); + + // Return 200 if overall status is UP, 503 if DOWN + HttpStatus httpStatus = "UP".equals(overallStatus) ? HttpStatus.OK : HttpStatus.SERVICE_UNAVAILABLE; + + logger.debug("Health check completed with status: {}", overallStatus); + return new ResponseEntity<>(healthStatus, httpStatus); + + } catch (Exception e) { + logger.error("Unexpected error during health check", e); + + // Return sanitized error response + Map errorResponse = Map.of( + "status", "DOWN", + "error", "Health check service unavailable", + "timestamp", Instant.now().toString() + ); + + return new ResponseEntity<>(errorResponse, HttpStatus.SERVICE_UNAVAILABLE); + } + } + + private boolean isUserAuthenticated(HttpServletRequest request) { + String token = null; + + // First, try to get token from JwtToken header + token = request.getHeader("JwtToken"); + + // If not found, try Authorization header + if (token == null || token.trim().isEmpty()) { + String authHeader = request.getHeader("Authorization"); + if (authHeader != null && !authHeader.trim().isEmpty()) { + // Extract token from "Bearer " format + token = authHeader.startsWith("Bearer ") + ? authHeader.substring(7) + : authHeader; + } + } + + // If still not found, try to get from cookies + if (token == null || token.trim().isEmpty()) { + token = getJwtTokenFromCookies(request); + } + + // Validate the token if found + if (token != null && !token.trim().isEmpty()) { + try { + return jwtAuthenticationUtil.validateUserIdAndJwtToken(token); + } catch (Exception e) { + logger.debug("JWT token validation failed: {}", e.getMessage()); + return false; + } + } + + return false; + } + + private String getJwtTokenFromCookies(HttpServletRequest request) { + Cookie[] cookies = request.getCookies(); + if (cookies != null) { + for (Cookie cookie : cookies) { + if (cookie.getName().equalsIgnoreCase("Jwttoken")) { + return cookie.getValue(); + } + } + } + return null; + } +} diff --git a/src/main/java/com/wipro/fhir/controller/version/VersionController.java b/src/main/java/com/wipro/fhir/controller/version/VersionController.java new file mode 100644 index 0000000..7a5af18 --- /dev/null +++ b/src/main/java/com/wipro/fhir/controller/version/VersionController.java @@ -0,0 +1,79 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ +package com.wipro.fhir.controller.version; + +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Operation; + +@RestController +public class VersionController { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); + + private static final String UNKNOWN_VALUE = "unknown"; + + @Operation(summary = "Get version information") + @GetMapping(value = "/version", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> versionInformation() { + Map response = new LinkedHashMap<>(); + try { + logger.info("version Controller Start"); + Properties gitProperties = loadGitProperties(); + response.put("buildTimestamp", gitProperties.getProperty("git.build.time", UNKNOWN_VALUE)); + response.put("version", gitProperties.getProperty("git.build.version", UNKNOWN_VALUE)); + response.put("branch", gitProperties.getProperty("git.branch", UNKNOWN_VALUE)); + response.put("commitHash", gitProperties.getProperty("git.commit.id.abbrev", UNKNOWN_VALUE)); + } catch (Exception e) { + logger.error("Failed to load version information", e); + response.put("buildTimestamp", UNKNOWN_VALUE); + response.put("version", UNKNOWN_VALUE); + response.put("branch", UNKNOWN_VALUE); + response.put("commitHash", UNKNOWN_VALUE); + } + logger.info("version Controller End"); + return ResponseEntity.ok(response); + } + + private Properties loadGitProperties() throws IOException { + Properties properties = new Properties(); + try (InputStream input = getClass().getClassLoader() + .getResourceAsStream("git.properties")) { + if (input != null) { + properties.load(input); + } + } + return properties; + } +} diff --git a/src/main/java/com/wipro/fhir/service/health/HealthService.java b/src/main/java/com/wipro/fhir/service/health/HealthService.java new file mode 100644 index 0000000..9bbe052 --- /dev/null +++ b/src/main/java/com/wipro/fhir/service/health/HealthService.java @@ -0,0 +1,310 @@ +package com.wipro.fhir.service.health; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Supplier; +import javax.sql.DataSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +@Service +public class HealthService { + + private static final Logger logger = LoggerFactory.getLogger(HealthService.class); + private static final String STATUS_KEY = "status"; + private static final String DB_HEALTH_CHECK_QUERY = "SELECT 1 as health_check"; + private static final String DB_VERSION_QUERY = "SELECT VERSION()"; + private static final String STATUS_UP = "UP"; + private static final String STATUS_DOWN = "DOWN"; + private static final String UNKNOWN_VALUE = "unknown"; + private static final int REDIS_TIMEOUT_SECONDS = 3; + private static final ExecutorService executorService = Executors.newFixedThreadPool(4); + + private final DataSource dataSource; + private final RedisTemplate redisTemplate; + private final String dbUrl; + private final String redisHost; + private final int redisPort; + + public HealthService(DataSource dataSource, + @Autowired(required = false) RedisTemplate redisTemplate, + @Value("${spring.datasource.url:unknown}") String dbUrl, + @Value("${spring.data.redis.host:localhost}") String redisHost, + @Value("${spring.data.redis.port:6379}") int redisPort) { + this.dataSource = dataSource; + this.redisTemplate = redisTemplate; + this.dbUrl = dbUrl; + this.redisHost = redisHost; + this.redisPort = redisPort; + } + + public Map checkHealth(boolean includeDetails) { + Map healthStatus = new LinkedHashMap<>(); + Map components = new LinkedHashMap<>(); + boolean overallHealth = true; + + Map mysqlStatus = checkMySQLHealth(includeDetails); + components.put("mysql", mysqlStatus); + if (!isHealthy(mysqlStatus)) { + overallHealth = false; + } + + if (redisTemplate != null) { + Map redisStatus = checkRedisHealth(includeDetails); + components.put("redis", redisStatus); + if (!isHealthy(redisStatus)) { + overallHealth = false; + } + } + + healthStatus.put(STATUS_KEY, overallHealth ? STATUS_UP : STATUS_DOWN); + healthStatus.put("timestamp", Instant.now().toString()); + healthStatus.put("components", components); + logger.info("Health check completed - Overall status: {}", overallHealth ? STATUS_UP : STATUS_DOWN); + + return healthStatus; + } + + public Map checkHealth() { + return checkHealth(true); + } + + private Map checkMySQLHealth(boolean includeDetails) { + Map details = new LinkedHashMap<>(); + details.put("type", "MySQL"); + + if (includeDetails) { + details.put("host", extractHost(dbUrl)); + details.put("port", extractPort(dbUrl)); + details.put("database", extractDatabaseName(dbUrl)); + } + + return performHealthCheck("MySQL", details, () -> { + try { + try (Connection connection = dataSource.getConnection()) { + if (connection.isValid(2)) { + try (PreparedStatement stmt = connection.prepareStatement(DB_HEALTH_CHECK_QUERY)) { + stmt.setQueryTimeout(3); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next() && rs.getInt(1) == 1) { + String version = includeDetails ? getMySQLVersion(connection) : null; + return new HealthCheckResult(true, version, null); + } + } + } + } + return new HealthCheckResult(false, null, "Connection validation failed"); + } + } catch (Exception e) { + throw new IllegalStateException("Failed to perform MySQL health check", e); + } + }); + } + + private Map checkRedisHealth(boolean includeDetails) { + Map details = new LinkedHashMap<>(); + details.put("type", "Redis"); + + if (includeDetails) { + details.put("host", redisHost); + details.put("port", redisPort); + } + + return performHealthCheck("Redis", details, () -> { + try { + // Wrap PING in CompletableFuture with timeout + String pong = CompletableFuture.supplyAsync(() -> + redisTemplate.execute((RedisCallback) connection -> connection.ping()), + executorService + ).get(REDIS_TIMEOUT_SECONDS, TimeUnit.SECONDS); + + if ("PONG".equals(pong)) { + String version = includeDetails ? getRedisVersionWithTimeout() : null; + return new HealthCheckResult(true, version, null); + } + return new HealthCheckResult(false, null, "Ping returned unexpected response"); + } catch (TimeoutException e) { + return new HealthCheckResult(false, null, "Redis ping timed out after " + REDIS_TIMEOUT_SECONDS + " seconds"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return new HealthCheckResult(false, null, "Redis health check was interrupted"); + } catch (Exception e) { + throw new IllegalStateException("Redis health check failed", e); + } + }); + } + + private Map performHealthCheck(String componentName, + Map details, + Supplier checker) { + Map status = new LinkedHashMap<>(); + long startTime = System.currentTimeMillis(); + + try { + HealthCheckResult result = checker.get(); + long responseTime = System.currentTimeMillis() - startTime; + + details.put("responseTimeMs", responseTime); + + if (result.isHealthy) { + logger.debug("{} health check: UP ({}ms)", componentName, responseTime); + status.put(STATUS_KEY, STATUS_UP); + if (result.version != null) { + details.put("version", result.version); + } + } else { + String safeError = result.error != null ? result.error : "Health check failed"; + logger.warn("{} health check failed: {}", componentName, safeError); + status.put(STATUS_KEY, STATUS_DOWN); + details.put("error", safeError); + details.put("errorType", "CheckFailed"); + } + + status.put("details", details); + return status; + + } catch (Exception e) { + long responseTime = System.currentTimeMillis() - startTime; + + logger.error("{} health check failed", componentName, e); + + status.put(STATUS_KEY, STATUS_DOWN); + details.put("responseTimeMs", responseTime); + details.put("error", "Health check failed"); + details.put("errorType", "InternalError"); + status.put("details", details); + + return status; + } + } + + private boolean isHealthy(Map componentStatus) { + return STATUS_UP.equals(componentStatus.get(STATUS_KEY)); + } + + private String getMySQLVersion(Connection connection) { + try (PreparedStatement stmt = connection.prepareStatement(DB_VERSION_QUERY); + ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + return rs.getString(1); + } + } catch (Exception e) { + logger.debug("Could not retrieve MySQL version", e); + } + return null; + } + + private String getRedisVersion() { + try { + Properties info = redisTemplate.execute((RedisCallback) connection -> + connection.serverCommands().info("server") + ); + if (info != null && info.containsKey("redis_version")) { + return info.getProperty("redis_version"); + } + } catch (Exception e) { + logger.debug("Could not retrieve Redis version", e); + } + return null; + } + + private String getRedisVersionWithTimeout() { + try { + return CompletableFuture.supplyAsync(this::getRedisVersion, executorService) + .get(REDIS_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (TimeoutException e) { + logger.debug("Redis version retrieval timed out"); + return null; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.debug("Redis version retrieval was interrupted"); + return null; + } catch (Exception e) { + logger.debug("Could not retrieve Redis version with timeout", e); + return null; + } + } + + private String extractHost(String jdbcUrl) { + if (jdbcUrl == null || UNKNOWN_VALUE.equals(jdbcUrl)) { + return UNKNOWN_VALUE; + } + try { + String withoutPrefix = jdbcUrl.replaceFirst("jdbc:mysql://", ""); + int slashIndex = withoutPrefix.indexOf('/'); + String hostPort = slashIndex > 0 + ? withoutPrefix.substring(0, slashIndex) + : withoutPrefix; + int colonIndex = hostPort.indexOf(':'); + return colonIndex > 0 ? hostPort.substring(0, colonIndex) : hostPort; + } catch (Exception e) { + logger.debug("Could not extract host from URL", e); + } + return UNKNOWN_VALUE; + } + + private String extractPort(String jdbcUrl) { + if (jdbcUrl == null || UNKNOWN_VALUE.equals(jdbcUrl)) { + return UNKNOWN_VALUE; + } + try { + String withoutPrefix = jdbcUrl.replaceFirst("jdbc:mysql://", ""); + int slashIndex = withoutPrefix.indexOf('/'); + String hostPort = slashIndex > 0 + ? withoutPrefix.substring(0, slashIndex) + : withoutPrefix; + int colonIndex = hostPort.indexOf(':'); + return colonIndex > 0 ? hostPort.substring(colonIndex + 1) : "3306"; + } catch (Exception e) { + logger.debug("Could not extract port from URL", e); + } + return "3306"; + } + + private String extractDatabaseName(String jdbcUrl) { + if (jdbcUrl == null || UNKNOWN_VALUE.equals(jdbcUrl)) { + return UNKNOWN_VALUE; + } + try { + int lastSlash = jdbcUrl.lastIndexOf('/'); + if (lastSlash >= 0 && lastSlash < jdbcUrl.length() - 1) { + String afterSlash = jdbcUrl.substring(lastSlash + 1); + int queryStart = afterSlash.indexOf('?'); + if (queryStart > 0) { + return afterSlash.substring(0, queryStart); + } + return afterSlash; + } + } catch (Exception e) { + logger.debug("Could not extract database name from URL", e); + } + return UNKNOWN_VALUE; + } + + private static class HealthCheckResult { + final boolean isHealthy; + final String version; + final String error; + + HealthCheckResult(boolean isHealthy, String version, String error) { + this.isHealthy = isHealthy; + this.version = version; + this.error = error; + } + } +} diff --git a/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java b/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java index b415fc3..0a2052b 100644 --- a/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java @@ -160,7 +160,9 @@ private boolean shouldSkipPath(String path, String contextPath) { || path.equalsIgnoreCase(contextPath + "/user/logOutUserFromConcurrentSession") || path.startsWith(contextPath + "/swagger-ui") || path.startsWith(contextPath + "/v3/api-docs") - || path.startsWith(contextPath + "/public"); + || path.startsWith(contextPath + "/public") + || path.startsWith(contextPath + "/version") + || path.startsWith(contextPath + "/health"); } private String getJwtTokenFromCookies(HttpServletRequest request) { From 70537216585ef2e59b287fd3046caf33576160f5 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Tue, 17 Feb 2026 13:30:28 +0530 Subject: [PATCH 2/9] fix(jwt): fix the jwtvalidation issues --- .../java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java b/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java index 0a2052b..631f206 100644 --- a/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java @@ -161,8 +161,8 @@ private boolean shouldSkipPath(String path, String contextPath) { || path.startsWith(contextPath + "/swagger-ui") || path.startsWith(contextPath + "/v3/api-docs") || path.startsWith(contextPath + "/public") - || path.startsWith(contextPath + "/version") - || path.startsWith(contextPath + "/health"); + || path.equals(contextPath +"/version") + || path.equals(contextPath +"/health"); } private String getJwtTokenFromCookies(HttpServletRequest request) { From 2e7a63d3f060d5362d1e7c2d8966f32119d44a1d Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Thu, 19 Feb 2026 12:17:33 +0530 Subject: [PATCH 3/9] refactor(health): simplify MySQL health check and remove sensitive details --- .../controller/health/HealthController.java | 65 +---- .../fhir/service/health/HealthService.java | 247 ++++-------------- 2 files changed, 54 insertions(+), 258 deletions(-) diff --git a/src/main/java/com/wipro/fhir/controller/health/HealthController.java b/src/main/java/com/wipro/fhir/controller/health/HealthController.java index a39067e..7037856 100644 --- a/src/main/java/com/wipro/fhir/controller/health/HealthController.java +++ b/src/main/java/com/wipro/fhir/controller/health/HealthController.java @@ -9,16 +9,12 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; import com.wipro.fhir.service.health.HealthService; -import com.wipro.fhir.utils.JwtAuthenticationUtil; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; - @RestController @RequestMapping("/health") @Tag(name = "Health Check", description = "APIs for checking infrastructure health status") @@ -27,12 +23,11 @@ public class HealthController { private static final Logger logger = LoggerFactory.getLogger(HealthController.class); private final HealthService healthService; - private final JwtAuthenticationUtil jwtAuthenticationUtil; - public HealthController(HealthService healthService, JwtAuthenticationUtil jwtAuthenticationUtil) { + public HealthController(HealthService healthService) { this.healthService = healthService; - this.jwtAuthenticationUtil = jwtAuthenticationUtil; } + @GetMapping @Operation(summary = "Check infrastructure health", description = "Returns the health status of MySQL, Redis, and other configured services") @@ -40,16 +35,13 @@ public HealthController(HealthService healthService, JwtAuthenticationUtil jwtAu @ApiResponse(responseCode = "200", description = "All checked components are UP"), @ApiResponse(responseCode = "503", description = "One or more critical services are DOWN") }) - public ResponseEntity> checkHealth(HttpServletRequest request) { + public ResponseEntity> checkHealth() { logger.info("Health check endpoint called"); try { - // Check if user is authenticated by verifying Authorization header - boolean isAuthenticated = isUserAuthenticated(request); - Map healthStatus = healthService.checkHealth(isAuthenticated); + Map healthStatus = healthService.checkHealth(); String overallStatus = (String) healthStatus.get("status"); - // Return 200 if overall status is UP, 503 if DOWN HttpStatus httpStatus = "UP".equals(overallStatus) ? HttpStatus.OK : HttpStatus.SERVICE_UNAVAILABLE; logger.debug("Health check completed with status: {}", overallStatus); @@ -58,61 +50,12 @@ public ResponseEntity> checkHealth(HttpServletRequest reques } catch (Exception e) { logger.error("Unexpected error during health check", e); - // Return sanitized error response Map errorResponse = Map.of( "status", "DOWN", - "error", "Health check service unavailable", "timestamp", Instant.now().toString() ); return new ResponseEntity<>(errorResponse, HttpStatus.SERVICE_UNAVAILABLE); } } - - private boolean isUserAuthenticated(HttpServletRequest request) { - String token = null; - - // First, try to get token from JwtToken header - token = request.getHeader("JwtToken"); - - // If not found, try Authorization header - if (token == null || token.trim().isEmpty()) { - String authHeader = request.getHeader("Authorization"); - if (authHeader != null && !authHeader.trim().isEmpty()) { - // Extract token from "Bearer " format - token = authHeader.startsWith("Bearer ") - ? authHeader.substring(7) - : authHeader; - } - } - - // If still not found, try to get from cookies - if (token == null || token.trim().isEmpty()) { - token = getJwtTokenFromCookies(request); - } - - // Validate the token if found - if (token != null && !token.trim().isEmpty()) { - try { - return jwtAuthenticationUtil.validateUserIdAndJwtToken(token); - } catch (Exception e) { - logger.debug("JWT token validation failed: {}", e.getMessage()); - return false; - } - } - - return false; - } - - private String getJwtTokenFromCookies(HttpServletRequest request) { - Cookie[] cookies = request.getCookies(); - if (cookies != null) { - for (Cookie cookie : cookies) { - if (cookie.getName().equalsIgnoreCase("Jwttoken")) { - return cookie.getValue(); - } - } - } - return null; - } } diff --git a/src/main/java/com/wipro/fhir/service/health/HealthService.java b/src/main/java/com/wipro/fhir/service/health/HealthService.java index 9bbe052..b2f446f 100644 --- a/src/main/java/com/wipro/fhir/service/health/HealthService.java +++ b/src/main/java/com/wipro/fhir/service/health/HealthService.java @@ -6,7 +6,6 @@ import java.time.Instant; import java.util.LinkedHashMap; import java.util.Map; -import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -17,7 +16,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @@ -28,121 +26,88 @@ public class HealthService { private static final Logger logger = LoggerFactory.getLogger(HealthService.class); private static final String STATUS_KEY = "status"; private static final String DB_HEALTH_CHECK_QUERY = "SELECT 1 as health_check"; - private static final String DB_VERSION_QUERY = "SELECT VERSION()"; private static final String STATUS_UP = "UP"; private static final String STATUS_DOWN = "DOWN"; - private static final String UNKNOWN_VALUE = "unknown"; private static final int REDIS_TIMEOUT_SECONDS = 3; - private static final ExecutorService executorService = Executors.newFixedThreadPool(4); private final DataSource dataSource; + private final ExecutorService executorService = Executors.newFixedThreadPool(2); private final RedisTemplate redisTemplate; - private final String dbUrl; - private final String redisHost; - private final int redisPort; public HealthService(DataSource dataSource, - @Autowired(required = false) RedisTemplate redisTemplate, - @Value("${spring.datasource.url:unknown}") String dbUrl, - @Value("${spring.data.redis.host:localhost}") String redisHost, - @Value("${spring.data.redis.port:6379}") int redisPort) { + @Autowired(required = false) RedisTemplate redisTemplate) { this.dataSource = dataSource; this.redisTemplate = redisTemplate; - this.dbUrl = dbUrl; - this.redisHost = redisHost; - this.redisPort = redisPort; } - public Map checkHealth(boolean includeDetails) { - Map healthStatus = new LinkedHashMap<>(); + public Map checkHealth() { + Map response = new LinkedHashMap<>(); + response.put("timestamp", Instant.now().toString()); + Map components = new LinkedHashMap<>(); - boolean overallHealth = true; - - Map mysqlStatus = checkMySQLHealth(includeDetails); - components.put("mysql", mysqlStatus); - if (!isHealthy(mysqlStatus)) { - overallHealth = false; - } - + + // Check MySQL + components.put("mysql", checkMySQLHealth()); + + // Check Redis if available if (redisTemplate != null) { - Map redisStatus = checkRedisHealth(includeDetails); - components.put("redis", redisStatus); - if (!isHealthy(redisStatus)) { - overallHealth = false; - } + components.put("redis", checkRedisHealth()); } - - healthStatus.put(STATUS_KEY, overallHealth ? STATUS_UP : STATUS_DOWN); - healthStatus.put("timestamp", Instant.now().toString()); - healthStatus.put("components", components); - logger.info("Health check completed - Overall status: {}", overallHealth ? STATUS_UP : STATUS_DOWN); - - return healthStatus; - } - - public Map checkHealth() { - return checkHealth(true); + + response.put("components", components); + + // Overall status: UP only if all components are UP + boolean allUp = components.values().stream() + .allMatch(value -> isHealthy((Map) value)); + response.put(STATUS_KEY, allUp ? STATUS_UP : STATUS_DOWN); + + logger.info("Health check completed - Overall status: {}", allUp ? STATUS_UP : STATUS_DOWN); + + return response; } - private Map checkMySQLHealth(boolean includeDetails) { - Map details = new LinkedHashMap<>(); - details.put("type", "MySQL"); + private Map checkMySQLHealth() { + Map status = new LinkedHashMap<>(); - if (includeDetails) { - details.put("host", extractHost(dbUrl)); - details.put("port", extractPort(dbUrl)); - details.put("database", extractDatabaseName(dbUrl)); - } - - return performHealthCheck("MySQL", details, () -> { + return performHealthCheck("MySQL", status, () -> { try { try (Connection connection = dataSource.getConnection()) { - if (connection.isValid(2)) { - try (PreparedStatement stmt = connection.prepareStatement(DB_HEALTH_CHECK_QUERY)) { - stmt.setQueryTimeout(3); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next() && rs.getInt(1) == 1) { - String version = includeDetails ? getMySQLVersion(connection) : null; - return new HealthCheckResult(true, version, null); - } + try (PreparedStatement stmt = connection.prepareStatement(DB_HEALTH_CHECK_QUERY)) { + stmt.setQueryTimeout(3); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next() && rs.getInt(1) == 1) { + return new HealthCheckResult(true, null); } } } - return new HealthCheckResult(false, null, "Connection validation failed"); + return new HealthCheckResult(false, "Query validation failed"); } } catch (Exception e) { - throw new IllegalStateException("Failed to perform MySQL health check", e); + throw new IllegalStateException("MySQL health check failed: " + e.getMessage(), e); } }); } - private Map checkRedisHealth(boolean includeDetails) { - Map details = new LinkedHashMap<>(); - details.put("type", "Redis"); - - if (includeDetails) { - details.put("host", redisHost); - details.put("port", redisPort); - } + private Map checkRedisHealth() { + Map status = new LinkedHashMap<>(); - return performHealthCheck("Redis", details, () -> { + return performHealthCheck("Redis", status, () -> { + CompletableFuture future = CompletableFuture.supplyAsync( + () -> redisTemplate.execute((RedisCallback) connection -> connection.ping()), + executorService); try { - // Wrap PING in CompletableFuture with timeout - String pong = CompletableFuture.supplyAsync(() -> - redisTemplate.execute((RedisCallback) connection -> connection.ping()), - executorService - ).get(REDIS_TIMEOUT_SECONDS, TimeUnit.SECONDS); + String pong = future.get(REDIS_TIMEOUT_SECONDS, TimeUnit.SECONDS); if ("PONG".equals(pong)) { - String version = includeDetails ? getRedisVersionWithTimeout() : null; - return new HealthCheckResult(true, version, null); + return new HealthCheckResult(true, null); } - return new HealthCheckResult(false, null, "Ping returned unexpected response"); + return new HealthCheckResult(false, "Ping returned unexpected response"); } catch (TimeoutException e) { - return new HealthCheckResult(false, null, "Redis ping timed out after " + REDIS_TIMEOUT_SECONDS + " seconds"); + future.cancel(true); + return new HealthCheckResult(false, "Redis ping timed out after " + REDIS_TIMEOUT_SECONDS + " seconds"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - return new HealthCheckResult(false, null, "Redis health check was interrupted"); + return new HealthCheckResult(false, "Redis health check was interrupted"); } catch (Exception e) { throw new IllegalStateException("Redis health check failed", e); } @@ -150,44 +115,33 @@ private Map checkRedisHealth(boolean includeDetails) { } private Map performHealthCheck(String componentName, - Map details, + Map status, Supplier checker) { - Map status = new LinkedHashMap<>(); long startTime = System.currentTimeMillis(); try { HealthCheckResult result = checker.get(); long responseTime = System.currentTimeMillis() - startTime; - details.put("responseTimeMs", responseTime); + status.put("responseTimeMs", responseTime); if (result.isHealthy) { logger.debug("{} health check: UP ({}ms)", componentName, responseTime); status.put(STATUS_KEY, STATUS_UP); - if (result.version != null) { - details.put("version", result.version); - } } else { String safeError = result.error != null ? result.error : "Health check failed"; logger.warn("{} health check failed: {}", componentName, safeError); status.put(STATUS_KEY, STATUS_DOWN); - details.put("error", safeError); - details.put("errorType", "CheckFailed"); } - status.put("details", details); return status; } catch (Exception e) { long responseTime = System.currentTimeMillis() - startTime; - - logger.error("{} health check failed", componentName, e); + logger.error("{} health check failed with exception: {}", componentName, e.getMessage(), e); status.put(STATUS_KEY, STATUS_DOWN); - details.put("responseTimeMs", responseTime); - details.put("error", "Health check failed"); - details.put("errorType", "InternalError"); - status.put("details", details); + status.put("responseTimeMs", responseTime); return status; } @@ -197,113 +151,12 @@ private boolean isHealthy(Map componentStatus) { return STATUS_UP.equals(componentStatus.get(STATUS_KEY)); } - private String getMySQLVersion(Connection connection) { - try (PreparedStatement stmt = connection.prepareStatement(DB_VERSION_QUERY); - ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - return rs.getString(1); - } - } catch (Exception e) { - logger.debug("Could not retrieve MySQL version", e); - } - return null; - } - - private String getRedisVersion() { - try { - Properties info = redisTemplate.execute((RedisCallback) connection -> - connection.serverCommands().info("server") - ); - if (info != null && info.containsKey("redis_version")) { - return info.getProperty("redis_version"); - } - } catch (Exception e) { - logger.debug("Could not retrieve Redis version", e); - } - return null; - } - - private String getRedisVersionWithTimeout() { - try { - return CompletableFuture.supplyAsync(this::getRedisVersion, executorService) - .get(REDIS_TIMEOUT_SECONDS, TimeUnit.SECONDS); - } catch (TimeoutException e) { - logger.debug("Redis version retrieval timed out"); - return null; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - logger.debug("Redis version retrieval was interrupted"); - return null; - } catch (Exception e) { - logger.debug("Could not retrieve Redis version with timeout", e); - return null; - } - } - - private String extractHost(String jdbcUrl) { - if (jdbcUrl == null || UNKNOWN_VALUE.equals(jdbcUrl)) { - return UNKNOWN_VALUE; - } - try { - String withoutPrefix = jdbcUrl.replaceFirst("jdbc:mysql://", ""); - int slashIndex = withoutPrefix.indexOf('/'); - String hostPort = slashIndex > 0 - ? withoutPrefix.substring(0, slashIndex) - : withoutPrefix; - int colonIndex = hostPort.indexOf(':'); - return colonIndex > 0 ? hostPort.substring(0, colonIndex) : hostPort; - } catch (Exception e) { - logger.debug("Could not extract host from URL", e); - } - return UNKNOWN_VALUE; - } - - private String extractPort(String jdbcUrl) { - if (jdbcUrl == null || UNKNOWN_VALUE.equals(jdbcUrl)) { - return UNKNOWN_VALUE; - } - try { - String withoutPrefix = jdbcUrl.replaceFirst("jdbc:mysql://", ""); - int slashIndex = withoutPrefix.indexOf('/'); - String hostPort = slashIndex > 0 - ? withoutPrefix.substring(0, slashIndex) - : withoutPrefix; - int colonIndex = hostPort.indexOf(':'); - return colonIndex > 0 ? hostPort.substring(colonIndex + 1) : "3306"; - } catch (Exception e) { - logger.debug("Could not extract port from URL", e); - } - return "3306"; - } - - private String extractDatabaseName(String jdbcUrl) { - if (jdbcUrl == null || UNKNOWN_VALUE.equals(jdbcUrl)) { - return UNKNOWN_VALUE; - } - try { - int lastSlash = jdbcUrl.lastIndexOf('/'); - if (lastSlash >= 0 && lastSlash < jdbcUrl.length() - 1) { - String afterSlash = jdbcUrl.substring(lastSlash + 1); - int queryStart = afterSlash.indexOf('?'); - if (queryStart > 0) { - return afterSlash.substring(0, queryStart); - } - return afterSlash; - } - } catch (Exception e) { - logger.debug("Could not extract database name from URL", e); - } - return UNKNOWN_VALUE; - } - private static class HealthCheckResult { final boolean isHealthy; - final String version; final String error; - HealthCheckResult(boolean isHealthy, String version, String error) { + HealthCheckResult(boolean isHealthy, String error) { this.isHealthy = isHealthy; - this.version = version; this.error = error; } } From d1ad22e732a5f0fd7ac208e876301d9dd60923b3 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Fri, 20 Feb 2026 22:10:19 +0530 Subject: [PATCH 4/9] fix(health): harden advanced MySQL checks and throttle execution --- .../controller/health/HealthController.java | 5 +- .../fhir/service/health/HealthService.java | 520 +++++++++++++++--- 2 files changed, 454 insertions(+), 71 deletions(-) diff --git a/src/main/java/com/wipro/fhir/controller/health/HealthController.java b/src/main/java/com/wipro/fhir/controller/health/HealthController.java index 7037856..b0aaf77 100644 --- a/src/main/java/com/wipro/fhir/controller/health/HealthController.java +++ b/src/main/java/com/wipro/fhir/controller/health/HealthController.java @@ -32,7 +32,7 @@ public HealthController(HealthService healthService) { @Operation(summary = "Check infrastructure health", description = "Returns the health status of MySQL, Redis, and other configured services") @ApiResponses({ - @ApiResponse(responseCode = "200", description = "All checked components are UP"), + @ApiResponse(responseCode = "200", description = "Services are UP or DEGRADED (operational with warnings)"), @ApiResponse(responseCode = "503", description = "One or more critical services are DOWN") }) public ResponseEntity> checkHealth() { @@ -42,7 +42,8 @@ public ResponseEntity> checkHealth() { Map healthStatus = healthService.checkHealth(); String overallStatus = (String) healthStatus.get("status"); - HttpStatus httpStatus = "UP".equals(overallStatus) ? HttpStatus.OK : HttpStatus.SERVICE_UNAVAILABLE; + // Return 503 only if DOWN; 200 for both UP and DEGRADED (DEGRADED = operational with warnings) + HttpStatus httpStatus = "DOWN".equals(overallStatus) ? HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.OK; logger.debug("Health check completed with status: {}", overallStatus); return new ResponseEntity<>(healthStatus, httpStatus); diff --git a/src/main/java/com/wipro/fhir/service/health/HealthService.java b/src/main/java/com/wipro/fhir/service/health/HealthService.java index b2f446f..6aa320c 100644 --- a/src/main/java/com/wipro/fhir/service/health/HealthService.java +++ b/src/main/java/com/wipro/fhir/service/health/HealthService.java @@ -1,3 +1,25 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + package com.wipro.fhir.service.health; import java.sql.Connection; @@ -12,11 +34,18 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Supplier; +import jakarta.annotation.PreDestroy; import javax.sql.DataSource; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import java.lang.management.ManagementFactory; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import java.util.concurrent.locks.ReentrantReadWriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.RedisCallback; +import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @@ -24,94 +53,177 @@ public class HealthService { private static final Logger logger = LoggerFactory.getLogger(HealthService.class); + + // Status constants private static final String STATUS_KEY = "status"; - private static final String DB_HEALTH_CHECK_QUERY = "SELECT 1 as health_check"; private static final String STATUS_UP = "UP"; private static final String STATUS_DOWN = "DOWN"; - private static final int REDIS_TIMEOUT_SECONDS = 3; + private static final String STATUS_DEGRADED = "DEGRADED"; + + // Severity levels and keys + private static final String SEVERITY_KEY = "severity"; + private static final String SEVERITY_OK = "OK"; + private static final String SEVERITY_WARNING = "WARNING"; + private static final String SEVERITY_CRITICAL = "CRITICAL"; + + // Response keys + private static final String ERROR_KEY = "error"; + private static final String MESSAGE_KEY = "message"; + private static final String RESPONSE_TIME_KEY = "responseTimeMs"; + + // Timeouts (in seconds) + private static final long MYSQL_TIMEOUT_SECONDS = 3; + private static final long REDIS_TIMEOUT_SECONDS = 3; + + // Advanced checks configuration + private static final long ADVANCED_CHECKS_TIMEOUT_MS = 500; // Strict timeout for advanced checks + private static final long ADVANCED_CHECKS_THROTTLE_SECONDS = 30; // Run at most once per 30 seconds + + // Performance threshold (milliseconds) - response time > 2000ms = DEGRADED + private static final long RESPONSE_TIME_THRESHOLD_MS = 2000; + + // Diagnostic event codes for concise logging + private static final String DIAGNOSTIC_LOCK_WAIT = "MYSQL_LOCK_WAIT"; + private static final String DIAGNOSTIC_DEADLOCK = "MYSQL_DEADLOCK"; + private static final String DIAGNOSTIC_SLOW_QUERIES = "MYSQL_SLOW_QUERIES"; + private static final String DIAGNOSTIC_POOL_EXHAUSTED = "MYSQL_POOL_EXHAUSTED"; + private static final String DIAGNOSTIC_LOG_TEMPLATE = "Diagnostic: {}"; private final DataSource dataSource; - private final ExecutorService executorService = Executors.newFixedThreadPool(2); private final RedisTemplate redisTemplate; + private final ExecutorService executorService; + + // Advanced checks throttling (thread-safe) + private volatile long lastAdvancedCheckTime = 0; + private volatile AdvancedCheckResult cachedAdvancedCheckResult = null; + private final ReentrantReadWriteLock advancedCheckLock = new ReentrantReadWriteLock(); + + // Deadlock check resilience - disable after first permission error + private volatile boolean deadlockCheckDisabled = false; + + @Value("${health.advanced.enabled:true}") + private boolean advancedHealthChecksEnabled; public HealthService(DataSource dataSource, @Autowired(required = false) RedisTemplate redisTemplate) { this.dataSource = dataSource; this.redisTemplate = redisTemplate; + this.executorService = Executors.newFixedThreadPool(2); + } + + @PreDestroy + public void shutdown() { + if (executorService != null && !executorService.isShutdown()) { + try { + executorService.shutdown(); + if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + logger.warn("ExecutorService did not terminate gracefully"); + } + } catch (InterruptedException e) { + executorService.shutdownNow(); + Thread.currentThread().interrupt(); + logger.warn("ExecutorService shutdown interrupted", e); + } + } } public Map checkHealth() { Map response = new LinkedHashMap<>(); response.put("timestamp", Instant.now().toString()); - Map components = new LinkedHashMap<>(); + Map mysqlStatus = new LinkedHashMap<>(); + Map redisStatus = new LinkedHashMap<>(); - // Check MySQL - components.put("mysql", checkMySQLHealth()); + // Submit both checks concurrently + CompletableFuture mysqlFuture = CompletableFuture.runAsync( + () -> performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealthSync), executorService); + CompletableFuture redisFuture = CompletableFuture.runAsync( + () -> performHealthCheck("Redis", redisStatus, this::checkRedisHealthSync), executorService); - // Check Redis if available - if (redisTemplate != null) { - components.put("redis", checkRedisHealth()); + // Wait for both checks to complete with combined timeout + long maxTimeout = Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; + try { + CompletableFuture.allOf(mysqlFuture, redisFuture) + .get(maxTimeout, TimeUnit.SECONDS); + } catch (TimeoutException e) { + logger.warn("Health check aggregate timeout after {} seconds", maxTimeout); + mysqlFuture.cancel(true); + redisFuture.cancel(true); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.warn("Health check was interrupted"); + mysqlFuture.cancel(true); + redisFuture.cancel(true); + } catch (Exception e) { + logger.warn("Health check execution error: {}", e.getMessage()); } - response.put("components", components); + // Ensure timed-out or unfinished components are marked DOWN + ensurePopulated(mysqlStatus, "MySQL"); + ensurePopulated(redisStatus, "Redis"); - // Overall status: UP only if all components are UP - boolean allUp = components.values().stream() - .allMatch(value -> isHealthy((Map) value)); - response.put(STATUS_KEY, allUp ? STATUS_UP : STATUS_DOWN); + Map> components = new LinkedHashMap<>(); + components.put("mysql", mysqlStatus); + components.put("redis", redisStatus); + + response.put("components", components); - logger.info("Health check completed - Overall status: {}", allUp ? STATUS_UP : STATUS_DOWN); + // Compute overall status + String overallStatus = computeOverallStatus(components); + response.put(STATUS_KEY, overallStatus); return response; } - private Map checkMySQLHealth() { - Map status = new LinkedHashMap<>(); - - return performHealthCheck("MySQL", status, () -> { - try { - try (Connection connection = dataSource.getConnection()) { - try (PreparedStatement stmt = connection.prepareStatement(DB_HEALTH_CHECK_QUERY)) { - stmt.setQueryTimeout(3); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next() && rs.getInt(1) == 1) { - return new HealthCheckResult(true, null); - } - } - } - return new HealthCheckResult(false, "Query validation failed"); + private void ensurePopulated(Map status, String componentName) { + if (!status.containsKey(STATUS_KEY)) { + status.put(STATUS_KEY, STATUS_DOWN); + status.put(SEVERITY_KEY, SEVERITY_CRITICAL); + status.put(ERROR_KEY, componentName + " health check did not complete in time"); + } + } + + private HealthCheckResult checkMySQLHealthSync() { + try (Connection connection = dataSource.getConnection(); + PreparedStatement stmt = connection.prepareStatement("SELECT 1 as health_check")) { + + stmt.setQueryTimeout((int) MYSQL_TIMEOUT_SECONDS); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + // Basic health check passed, now run advanced checks with throttling + boolean isDegraded = performAdvancedMySQLChecksWithThrottle(connection); + return new HealthCheckResult(true, null, isDegraded); } - } catch (Exception e) { - throw new IllegalStateException("MySQL health check failed: " + e.getMessage(), e); } - }); + + return new HealthCheckResult(false, "No result from health check query", false); + + } catch (Exception e) { + logger.warn("MySQL health check failed: {}", e.getMessage(), e); + return new HealthCheckResult(false, "MySQL connection failed", false); + } } - private Map checkRedisHealth() { - Map status = new LinkedHashMap<>(); - - return performHealthCheck("Redis", status, () -> { - CompletableFuture future = CompletableFuture.supplyAsync( - () -> redisTemplate.execute((RedisCallback) connection -> connection.ping()), - executorService); - try { - String pong = future.get(REDIS_TIMEOUT_SECONDS, TimeUnit.SECONDS); - - if ("PONG".equals(pong)) { - return new HealthCheckResult(true, null); - } - return new HealthCheckResult(false, "Ping returned unexpected response"); - } catch (TimeoutException e) { - future.cancel(true); - return new HealthCheckResult(false, "Redis ping timed out after " + REDIS_TIMEOUT_SECONDS + " seconds"); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return new HealthCheckResult(false, "Redis health check was interrupted"); - } catch (Exception e) { - throw new IllegalStateException("Redis health check failed", e); + private HealthCheckResult checkRedisHealthSync() { + if (redisTemplate == null) { + return new HealthCheckResult(true, "Redis not configured — skipped", false); + } + + try { + String pong = redisTemplate.execute((org.springframework.data.redis.core.RedisCallback) (connection) -> connection.ping()); + + if ("PONG".equals(pong)) { + return new HealthCheckResult(true, null, false); } - }); + + return new HealthCheckResult(false, "Redis PING failed", false); + + } catch (Exception e) { + logger.warn("Redis health check failed: {}", e.getMessage(), e); + return new HealthCheckResult(false, "Redis connection failed", false); + } } private Map performHealthCheck(String componentName, @@ -123,15 +235,30 @@ private Map performHealthCheck(String componentName, HealthCheckResult result = checker.get(); long responseTime = System.currentTimeMillis() - startTime; - status.put("responseTimeMs", responseTime); - - if (result.isHealthy) { - logger.debug("{} health check: UP ({}ms)", componentName, responseTime); - status.put(STATUS_KEY, STATUS_UP); + // Determine status: DOWN (unhealthy), DEGRADED (healthy but with issues), or UP + String componentStatus; + if (!result.isHealthy) { + componentStatus = STATUS_DOWN; + } else if (result.isDegraded) { + componentStatus = STATUS_DEGRADED; } else { - String safeError = result.error != null ? result.error : "Health check failed"; - logger.warn("{} health check failed: {}", componentName, safeError); - status.put(STATUS_KEY, STATUS_DOWN); + componentStatus = STATUS_UP; + } + status.put(STATUS_KEY, componentStatus); + + // Set response time + status.put(RESPONSE_TIME_KEY, responseTime); + + // Determine severity based on health, response time, and degradation flags + String severity = determineSeverity(result.isHealthy, responseTime, result.isDegraded); + status.put(SEVERITY_KEY, severity); + + // Include message or error based on health status + if (result.error != null) { + // Use MESSAGE_KEY for informational messages when healthy + // Use ERROR_KEY for actual error messages when unhealthy + String fieldKey = result.isHealthy ? MESSAGE_KEY : ERROR_KEY; + status.put(fieldKey, result.error); } return status; @@ -141,23 +268,278 @@ private Map performHealthCheck(String componentName, logger.error("{} health check failed with exception: {}", componentName, e.getMessage(), e); status.put(STATUS_KEY, STATUS_DOWN); - status.put("responseTimeMs", responseTime); + status.put(RESPONSE_TIME_KEY, responseTime); + status.put(SEVERITY_KEY, SEVERITY_CRITICAL); + status.put(ERROR_KEY, "Health check failed with an unexpected error"); return status; } } - private boolean isHealthy(Map componentStatus) { - return STATUS_UP.equals(componentStatus.get(STATUS_KEY)); + private String determineSeverity(boolean isHealthy, long responseTimeMs, boolean isDegraded) { + if (!isHealthy) { + return SEVERITY_CRITICAL; + } + + if (isDegraded) { + return SEVERITY_WARNING; + } + + if (responseTimeMs > RESPONSE_TIME_THRESHOLD_MS) { + return SEVERITY_WARNING; + } + + return SEVERITY_OK; + } + + private String computeOverallStatus(Map> components) { + boolean hasCritical = false; + boolean hasDegraded = false; + + for (Map componentStatus : components.values()) { + String status = (String) componentStatus.get(STATUS_KEY); + String severity = (String) componentStatus.get(SEVERITY_KEY); + + if (STATUS_DOWN.equals(status) || SEVERITY_CRITICAL.equals(severity)) { + hasCritical = true; + } + + if (STATUS_DEGRADED.equals(status)) { + hasDegraded = true; + } + + if (SEVERITY_WARNING.equals(severity)) { + hasDegraded = true; + } + } + + if (hasCritical) { + return STATUS_DOWN; + } + + if (hasDegraded) { + return STATUS_DEGRADED; + } + + return STATUS_UP; + } + + // Internal advanced health checks for MySQL - do not expose details in responses + private boolean performAdvancedMySQLChecksWithThrottle(Connection connection) { + if (!advancedHealthChecksEnabled) { + return false; // Advanced checks disabled + } + + long currentTime = System.currentTimeMillis(); + + // Check throttle window - use read lock first for fast path + advancedCheckLock.readLock().lock(); + try { + if (cachedAdvancedCheckResult != null && + (currentTime - lastAdvancedCheckTime) < ADVANCED_CHECKS_THROTTLE_SECONDS * 1000) { + // Return cached result - within throttle window + return cachedAdvancedCheckResult.isDegraded; + } + } finally { + advancedCheckLock.readLock().unlock(); + } + + // Outside throttle window - acquire write lock and run checks + advancedCheckLock.writeLock().lock(); + try { + // Double-check after acquiring write lock + if (cachedAdvancedCheckResult != null && + (currentTime - lastAdvancedCheckTime) < ADVANCED_CHECKS_THROTTLE_SECONDS * 1000) { + return cachedAdvancedCheckResult.isDegraded; + } + + AdvancedCheckResult result = performAdvancedMySQLChecks(connection); + + // Cache the result + lastAdvancedCheckTime = currentTime; + cachedAdvancedCheckResult = result; + + return result.isDegraded; + } finally { + advancedCheckLock.writeLock().unlock(); + } + } + + private AdvancedCheckResult performAdvancedMySQLChecks(Connection connection) { + try { + boolean hasIssues = false; + + if (hasLockWaits(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_LOCK_WAIT); + hasIssues = true; + } + + if (hasDeadlocks(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_DEADLOCK); + hasIssues = true; + } + + if (hasSlowQueries(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_SLOW_QUERIES); + hasIssues = true; + } + + if (hasConnectionPoolExhaustion()) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_POOL_EXHAUSTED); + hasIssues = true; + } + + return new AdvancedCheckResult(hasIssues); + } catch (Exception e) { + logger.debug("Advanced MySQL checks encountered exception, marking degraded"); + return new AdvancedCheckResult(true); + } + } + + private boolean hasLockWaits(Connection connection) { + try (PreparedStatement stmt = connection.prepareStatement( + "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + + "WHERE (state = 'Waiting for table metadata lock' " + + " OR state = 'Waiting for row lock' " + + " OR state = 'Waiting for lock') " + + "AND user NOT IN ('event_scheduler', 'system user', 'root')")) { + stmt.setQueryTimeout(2); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int lockCount = rs.getInt(1); + return lockCount > 0; + } + } + } catch (Exception e) { + logger.debug("Could not check for lock waits"); + } + return false; + } + + private boolean hasDeadlocks(Connection connection) { + // Skip deadlock check if already disabled due to permissions + if (deadlockCheckDisabled) { + return false; + } + + try (PreparedStatement stmt = connection.prepareStatement("SHOW ENGINE INNODB STATUS")) { + stmt.setQueryTimeout(2); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + String innodbStatus = rs.getString(3); + return innodbStatus != null && innodbStatus.contains("LATEST DETECTED DEADLOCK"); + } + } + } catch (java.sql.SQLException e) { + // Check if this is a permission error + if (e.getMessage() != null && + (e.getMessage().contains("Access denied") || + e.getMessage().contains("permission"))) { + // Disable this check permanently after first permission error + deadlockCheckDisabled = true; + logger.warn("Deadlock check disabled: Insufficient privileges"); + } else { + logger.debug("Could not check for deadlocks"); + } + } catch (Exception e) { + logger.debug("Could not check for deadlocks"); + } + return false; + } + + private boolean hasSlowQueries(Connection connection) { + try (PreparedStatement stmt = connection.prepareStatement( + "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + + "WHERE command != 'Sleep' AND time > ? AND user NOT IN ('event_scheduler', 'system user')")) { + stmt.setQueryTimeout(2); + stmt.setInt(1, 10); // Queries running longer than 10 seconds + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int slowQueryCount = rs.getInt(1); + return slowQueryCount > 3; // Alert if more than 3 slow queries + } + } + } catch (Exception e) { + logger.debug("Could not check for slow queries"); + } + return false; + } + + private boolean hasConnectionPoolExhaustion() { + // Use HikariCP metrics if available + if (dataSource instanceof HikariDataSource hikariDataSource) { + try { + HikariPoolMXBean poolMXBean = hikariDataSource.getHikariPoolMXBean(); + + if (poolMXBean != null) { + int activeConnections = poolMXBean.getActiveConnections(); + int maxPoolSize = hikariDataSource.getMaximumPoolSize(); + + // Alert if > 80% of pool is exhausted + int threshold = (int) (maxPoolSize * 0.8); + return activeConnections > threshold; + } + } catch (Exception e) { + logger.debug("Could not retrieve HikariCP pool metrics"); + } + } + + // Fallback: try to get pool metrics via JMX if HikariCP is not directly available + return checkPoolMetricsViaJMX(); + } + + private boolean checkPoolMetricsViaJMX() { + try { + MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); + ObjectName objectName = new ObjectName("com.zaxxer.hikari:type=Pool (*)"); + var mBeans = mBeanServer.queryMBeans(objectName, null); + + for (var mBean : mBeans) { + if (evaluatePoolMetrics(mBeanServer, mBean.getObjectName())) { + return true; + } + } + } catch (Exception e) { + logger.debug("Could not access HikariCP pool metrics via JMX"); + } + + // No pool metrics available - disable this check + logger.debug("Pool exhaustion check disabled: HikariCP metrics unavailable"); + return false; + } + + private boolean evaluatePoolMetrics(MBeanServer mBeanServer, ObjectName objectName) { + try { + Integer activeConnections = (Integer) mBeanServer.getAttribute(objectName, "ActiveConnections"); + Integer maximumPoolSize = (Integer) mBeanServer.getAttribute(objectName, "MaximumPoolSize"); + + if (activeConnections != null && maximumPoolSize != null) { + int threshold = (int) (maximumPoolSize * 0.8); + return activeConnections > threshold; + } + } catch (Exception e) { + // Continue to next MBean + } + return false; + } + + private static class AdvancedCheckResult { + final boolean isDegraded; + + AdvancedCheckResult(boolean isDegraded) { + this.isDegraded = isDegraded; + } } private static class HealthCheckResult { final boolean isHealthy; final String error; + final boolean isDegraded; - HealthCheckResult(boolean isHealthy, String error) { + HealthCheckResult(boolean isHealthy, String error, boolean isDegraded) { this.isHealthy = isHealthy; this.error = error; + this.isDegraded = isDegraded; } } } From d25a108a60bd0566416187eab4a2ce27f288f5fd Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Sat, 21 Feb 2026 12:03:30 +0530 Subject: [PATCH 5/9] fix(health): scope PROCESSLIST lock-wait check to application DB user --- .../fhir/service/health/HealthService.java | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/health/HealthService.java b/src/main/java/com/wipro/fhir/service/health/HealthService.java index 6aa320c..4d2d456 100644 --- a/src/main/java/com/wipro/fhir/service/health/HealthService.java +++ b/src/main/java/com/wipro/fhir/service/health/HealthService.java @@ -28,9 +28,10 @@ import java.time.Instant; import java.util.LinkedHashMap; import java.util.Map; -import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Supplier; @@ -74,12 +75,7 @@ public class HealthService { // Timeouts (in seconds) private static final long MYSQL_TIMEOUT_SECONDS = 3; private static final long REDIS_TIMEOUT_SECONDS = 3; - - // Advanced checks configuration - private static final long ADVANCED_CHECKS_TIMEOUT_MS = 500; // Strict timeout for advanced checks - private static final long ADVANCED_CHECKS_THROTTLE_SECONDS = 30; // Run at most once per 30 seconds - - // Performance threshold (milliseconds) - response time > 2000ms = DEGRADED + private static final long ADVANCED_CHECKS_THROTTLE_SECONDS = 30; private static final long RESPONSE_TIME_THRESHOLD_MS = 2000; // Diagnostic event codes for concise logging @@ -92,8 +88,6 @@ public class HealthService { private final DataSource dataSource; private final RedisTemplate redisTemplate; private final ExecutorService executorService; - - // Advanced checks throttling (thread-safe) private volatile long lastAdvancedCheckTime = 0; private volatile AdvancedCheckResult cachedAdvancedCheckResult = null; private final ReentrantReadWriteLock advancedCheckLock = new ReentrantReadWriteLock(); @@ -132,20 +126,26 @@ public Map checkHealth() { Map response = new LinkedHashMap<>(); response.put("timestamp", Instant.now().toString()); - Map mysqlStatus = new LinkedHashMap<>(); - Map redisStatus = new LinkedHashMap<>(); + Map mysqlStatus = new ConcurrentHashMap<>(); + Map redisStatus = new ConcurrentHashMap<>(); - // Submit both checks concurrently - CompletableFuture mysqlFuture = CompletableFuture.runAsync( - () -> performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealthSync), executorService); - CompletableFuture redisFuture = CompletableFuture.runAsync( - () -> performHealthCheck("Redis", redisStatus, this::checkRedisHealthSync), executorService); + // Submit both checks concurrently using executorService for proper cancellation support + Future mysqlFuture = executorService.submit( + () -> performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealthSync)); + Future redisFuture = executorService.submit( + () -> performHealthCheck("Redis", redisStatus, this::checkRedisHealthSync)); - // Wait for both checks to complete with combined timeout + // Wait for both checks to complete with combined timeout (shared deadline) long maxTimeout = Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; + long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); try { - CompletableFuture.allOf(mysqlFuture, redisFuture) - .get(maxTimeout, TimeUnit.SECONDS); + mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); + long remainingNs = deadlineNs - System.nanoTime(); + if (remainingNs > 0) { + redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); + } else { + redisFuture.cancel(true); + } } catch (TimeoutException e) { logger.warn("Health check aggregate timeout after {} seconds", maxTimeout); mysqlFuture.cancel(true); @@ -402,7 +402,7 @@ private boolean hasLockWaits(Connection connection) { "WHERE (state = 'Waiting for table metadata lock' " + " OR state = 'Waiting for row lock' " + " OR state = 'Waiting for lock') " + - "AND user NOT IN ('event_scheduler', 'system user', 'root')")) { + "AND user = USER()")) { stmt.setQueryTimeout(2); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { From 8daf3b155d3b02a2a2d6cd25616505a0a5fa909c Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Sun, 22 Feb 2026 09:37:25 +0530 Subject: [PATCH 6/9] fix(health): cancel timed-out advanced MySQL checks to avoid orphaned tasks --- .../fhir/service/health/HealthService.java | 149 ++++++++++-------- 1 file changed, 83 insertions(+), 66 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/health/HealthService.java b/src/main/java/com/wipro/fhir/service/health/HealthService.java index 4d2d456..3a93c0c 100644 --- a/src/main/java/com/wipro/fhir/service/health/HealthService.java +++ b/src/main/java/com/wipro/fhir/service/health/HealthService.java @@ -72,15 +72,19 @@ public class HealthService { private static final String MESSAGE_KEY = "message"; private static final String RESPONSE_TIME_KEY = "responseTimeMs"; + // Component names + private static final String MYSQL_COMPONENT = "MySQL"; + private static final String REDIS_COMPONENT = "Redis"; + // Timeouts (in seconds) private static final long MYSQL_TIMEOUT_SECONDS = 3; private static final long REDIS_TIMEOUT_SECONDS = 3; + private static final long ADVANCED_CHECKS_TIMEOUT_MS = 500L; private static final long ADVANCED_CHECKS_THROTTLE_SECONDS = 30; private static final long RESPONSE_TIME_THRESHOLD_MS = 2000; // Diagnostic event codes for concise logging private static final String DIAGNOSTIC_LOCK_WAIT = "MYSQL_LOCK_WAIT"; - private static final String DIAGNOSTIC_DEADLOCK = "MYSQL_DEADLOCK"; private static final String DIAGNOSTIC_SLOW_QUERIES = "MYSQL_SLOW_QUERIES"; private static final String DIAGNOSTIC_POOL_EXHAUSTED = "MYSQL_POOL_EXHAUSTED"; private static final String DIAGNOSTIC_LOG_TEMPLATE = "Diagnostic: {}"; @@ -88,6 +92,7 @@ public class HealthService { private final DataSource dataSource; private final RedisTemplate redisTemplate; private final ExecutorService executorService; + private final ExecutorService advancedCheckExecutor; private volatile long lastAdvancedCheckTime = 0; private volatile AdvancedCheckResult cachedAdvancedCheckResult = null; private final ReentrantReadWriteLock advancedCheckLock = new ReentrantReadWriteLock(); @@ -103,6 +108,11 @@ public HealthService(DataSource dataSource, this.dataSource = dataSource; this.redisTemplate = redisTemplate; this.executorService = Executors.newFixedThreadPool(2); + this.advancedCheckExecutor = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "health-advanced-check"); + t.setDaemon(true); + return t; + }); } @PreDestroy @@ -120,6 +130,9 @@ public void shutdown() { logger.warn("ExecutorService shutdown interrupted", e); } } + if (advancedCheckExecutor != null && !advancedCheckExecutor.isShutdown()) { + advancedCheckExecutor.shutdownNow(); + } } public Map checkHealth() { @@ -129,39 +142,49 @@ public Map checkHealth() { Map mysqlStatus = new ConcurrentHashMap<>(); Map redisStatus = new ConcurrentHashMap<>(); - // Submit both checks concurrently using executorService for proper cancellation support - Future mysqlFuture = executorService.submit( - () -> performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealthSync)); - Future redisFuture = executorService.submit( - () -> performHealthCheck("Redis", redisStatus, this::checkRedisHealthSync)); - - // Wait for both checks to complete with combined timeout (shared deadline) - long maxTimeout = Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; - long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); - try { - mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); - long remainingNs = deadlineNs - System.nanoTime(); - if (remainingNs > 0) { - redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); - } else { + // Check if executor service is shutdown (during graceful shutdown) + if (executorService.isShutdown()) { + ensurePopulated(mysqlStatus, MYSQL_COMPONENT); + ensurePopulated(redisStatus, REDIS_COMPONENT); + // Fall through to build response with DOWN status + } else { + // Submit both checks concurrently using executorService for proper cancellation support + Future mysqlFuture = executorService.submit( + () -> performHealthCheck(MYSQL_COMPONENT, mysqlStatus, this::checkMySQLHealthSync)); + Future redisFuture = executorService.submit( + () -> performHealthCheck(REDIS_COMPONENT, redisStatus, this::checkRedisHealthSync)); + + // Wait for both checks to complete with combined timeout (shared deadline) + long maxTimeout = Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; + long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); + try { + mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); + long remainingNs = deadlineNs - System.nanoTime(); + if (remainingNs > 0) { + redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); + } else { + redisFuture.cancel(true); + } + } catch (TimeoutException e) { + logger.warn("Health check aggregate timeout after {} seconds", maxTimeout); + mysqlFuture.cancel(true); + redisFuture.cancel(true); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.warn("Health check was interrupted"); + mysqlFuture.cancel(true); + redisFuture.cancel(true); + // Mark components as DOWN before returning + } catch (Exception e) { + logger.warn("Health check execution error: {}", e.getMessage()); + mysqlFuture.cancel(true); redisFuture.cancel(true); } - } catch (TimeoutException e) { - logger.warn("Health check aggregate timeout after {} seconds", maxTimeout); - mysqlFuture.cancel(true); - redisFuture.cancel(true); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - logger.warn("Health check was interrupted"); - mysqlFuture.cancel(true); - redisFuture.cancel(true); - } catch (Exception e) { - logger.warn("Health check execution error: {}", e.getMessage()); } // Ensure timed-out or unfinished components are marked DOWN - ensurePopulated(mysqlStatus, "MySQL"); - ensurePopulated(redisStatus, "Redis"); + ensurePopulated(mysqlStatus, MYSQL_COMPONENT); + ensurePopulated(redisStatus, REDIS_COMPONENT); Map> components = new LinkedHashMap<>(); components.put("mysql", mysqlStatus); @@ -353,7 +376,36 @@ private boolean performAdvancedMySQLChecksWithThrottle(Connection connection) { return cachedAdvancedCheckResult.isDegraded; } - AdvancedCheckResult result = performAdvancedMySQLChecks(connection); + AdvancedCheckResult result; + java.util.concurrent.CompletableFuture future = + java.util.concurrent.CompletableFuture + .supplyAsync(() -> performAdvancedMySQLChecks(connection), advancedCheckExecutor); + try { + result = future.get(ADVANCED_CHECKS_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (java.util.concurrent.TimeoutException ex) { + logger.debug("Advanced MySQL checks timed out after {}ms", ADVANCED_CHECKS_TIMEOUT_MS); + future.cancel(true); + result = new AdvancedCheckResult(true); // treat timeout as degraded + } catch (java.util.concurrent.ExecutionException ex) { + future.cancel(true); + // Check if the cause is an InterruptedException + if (ex.getCause() instanceof InterruptedException) { + Thread.currentThread().interrupt(); + logger.debug("Advanced MySQL checks were interrupted"); + } else { + logger.debug("Advanced MySQL checks failed: {}", ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage()); + } + result = new AdvancedCheckResult(true); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + logger.debug("Advanced MySQL checks interrupted"); + future.cancel(true); + result = new AdvancedCheckResult(true); + } catch (Exception ex) { + logger.debug("Advanced MySQL checks failed: {}", ex.getMessage()); + future.cancel(true); + result = new AdvancedCheckResult(true); + } // Cache the result lastAdvancedCheckTime = currentTime; @@ -374,11 +426,6 @@ private AdvancedCheckResult performAdvancedMySQLChecks(Connection connection) { hasIssues = true; } - if (hasDeadlocks(connection)) { - logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_DEADLOCK); - hasIssues = true; - } - if (hasSlowQueries(connection)) { logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_SLOW_QUERIES); hasIssues = true; @@ -402,7 +449,7 @@ private boolean hasLockWaits(Connection connection) { "WHERE (state = 'Waiting for table metadata lock' " + " OR state = 'Waiting for row lock' " + " OR state = 'Waiting for lock') " + - "AND user = USER()")) { + "AND user = SUBSTRING_INDEX(USER(), '@', 1)")) { stmt.setQueryTimeout(2); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { @@ -416,36 +463,6 @@ private boolean hasLockWaits(Connection connection) { return false; } - private boolean hasDeadlocks(Connection connection) { - // Skip deadlock check if already disabled due to permissions - if (deadlockCheckDisabled) { - return false; - } - - try (PreparedStatement stmt = connection.prepareStatement("SHOW ENGINE INNODB STATUS")) { - stmt.setQueryTimeout(2); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - String innodbStatus = rs.getString(3); - return innodbStatus != null && innodbStatus.contains("LATEST DETECTED DEADLOCK"); - } - } - } catch (java.sql.SQLException e) { - // Check if this is a permission error - if (e.getMessage() != null && - (e.getMessage().contains("Access denied") || - e.getMessage().contains("permission"))) { - // Disable this check permanently after first permission error - deadlockCheckDisabled = true; - logger.warn("Deadlock check disabled: Insufficient privileges"); - } else { - logger.debug("Could not check for deadlocks"); - } - } catch (Exception e) { - logger.debug("Could not check for deadlocks"); - } - return false; - } private boolean hasSlowQueries(Connection connection) { try (PreparedStatement stmt = connection.prepareStatement( From 51147acfc50c849775f25fbd7f17b89629318852 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Sun, 22 Feb 2026 09:49:04 +0530 Subject: [PATCH 7/9] fix(health): avoid sharing JDBC connections across threads in advanced MySQL checks --- .../fhir/service/health/HealthService.java | 51 ++++++++++--------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/health/HealthService.java b/src/main/java/com/wipro/fhir/service/health/HealthService.java index 3a93c0c..dfba24a 100644 --- a/src/main/java/com/wipro/fhir/service/health/HealthService.java +++ b/src/main/java/com/wipro/fhir/service/health/HealthService.java @@ -216,7 +216,7 @@ private HealthCheckResult checkMySQLHealthSync() { try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { // Basic health check passed, now run advanced checks with throttling - boolean isDegraded = performAdvancedMySQLChecksWithThrottle(connection); + boolean isDegraded = performAdvancedMySQLChecksWithThrottle(); return new HealthCheckResult(true, null, isDegraded); } } @@ -348,7 +348,7 @@ private String computeOverallStatus(Map> components) } // Internal advanced health checks for MySQL - do not expose details in responses - private boolean performAdvancedMySQLChecksWithThrottle(Connection connection) { + private boolean performAdvancedMySQLChecksWithThrottle() { if (!advancedHealthChecksEnabled) { return false; // Advanced checks disabled } @@ -379,7 +379,7 @@ private boolean performAdvancedMySQLChecksWithThrottle(Connection connection) { AdvancedCheckResult result; java.util.concurrent.CompletableFuture future = java.util.concurrent.CompletableFuture - .supplyAsync(() -> performAdvancedMySQLChecks(connection), advancedCheckExecutor); + .supplyAsync(this::performAdvancedMySQLChecks, advancedCheckExecutor); try { result = future.get(ADVANCED_CHECKS_TIMEOUT_MS, TimeUnit.MILLISECONDS); } catch (java.util.concurrent.TimeoutException ex) { @@ -417,28 +417,33 @@ private boolean performAdvancedMySQLChecksWithThrottle(Connection connection) { } } - private AdvancedCheckResult performAdvancedMySQLChecks(Connection connection) { - try { - boolean hasIssues = false; - - if (hasLockWaits(connection)) { - logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_LOCK_WAIT); - hasIssues = true; - } - - if (hasSlowQueries(connection)) { - logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_SLOW_QUERIES); - hasIssues = true; - } - - if (hasConnectionPoolExhaustion()) { - logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_POOL_EXHAUSTED); - hasIssues = true; + private AdvancedCheckResult performAdvancedMySQLChecks() { + try (Connection connection = dataSource.getConnection()) { + try { + boolean hasIssues = false; + + if (hasLockWaits(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_LOCK_WAIT); + hasIssues = true; + } + + if (hasSlowQueries(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_SLOW_QUERIES); + hasIssues = true; + } + + if (hasConnectionPoolExhaustion()) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_POOL_EXHAUSTED); + hasIssues = true; + } + + return new AdvancedCheckResult(hasIssues); + } catch (Exception e) { + logger.debug("Advanced MySQL checks encountered exception, marking degraded"); + return new AdvancedCheckResult(true); } - - return new AdvancedCheckResult(hasIssues); } catch (Exception e) { - logger.debug("Advanced MySQL checks encountered exception, marking degraded"); + logger.debug("Advanced MySQL checks could not obtain connection: {}", e.getMessage()); return new AdvancedCheckResult(true); } } From 936684677ac0614b25e8978d53ef2234972139be Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Sun, 22 Feb 2026 09:53:24 +0530 Subject: [PATCH 8/9] refactor(health): extract MySQL basic health query into helper method --- .../fhir/service/health/HealthService.java | 50 ++++++++++--------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/health/HealthService.java b/src/main/java/com/wipro/fhir/service/health/HealthService.java index dfba24a..811c948 100644 --- a/src/main/java/com/wipro/fhir/service/health/HealthService.java +++ b/src/main/java/com/wipro/fhir/service/health/HealthService.java @@ -419,35 +419,39 @@ private boolean performAdvancedMySQLChecksWithThrottle() { private AdvancedCheckResult performAdvancedMySQLChecks() { try (Connection connection = dataSource.getConnection()) { - try { - boolean hasIssues = false; - - if (hasLockWaits(connection)) { - logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_LOCK_WAIT); - hasIssues = true; - } - - if (hasSlowQueries(connection)) { - logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_SLOW_QUERIES); - hasIssues = true; - } - - if (hasConnectionPoolExhaustion()) { - logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_POOL_EXHAUSTED); - hasIssues = true; - } - - return new AdvancedCheckResult(hasIssues); - } catch (Exception e) { - logger.debug("Advanced MySQL checks encountered exception, marking degraded"); - return new AdvancedCheckResult(true); - } + return performAdvancedCheckLogic(connection); } catch (Exception e) { logger.debug("Advanced MySQL checks could not obtain connection: {}", e.getMessage()); return new AdvancedCheckResult(true); } } + private AdvancedCheckResult performAdvancedCheckLogic(Connection connection) { + try { + boolean hasIssues = false; + + if (hasLockWaits(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_LOCK_WAIT); + hasIssues = true; + } + + if (hasSlowQueries(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_SLOW_QUERIES); + hasIssues = true; + } + + if (hasConnectionPoolExhaustion()) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_POOL_EXHAUSTED); + hasIssues = true; + } + + return new AdvancedCheckResult(hasIssues); + } catch (Exception e) { + logger.debug("Advanced MySQL checks encountered exception, marking degraded"); + return new AdvancedCheckResult(true); + } + } + private boolean hasLockWaits(Connection connection) { try (PreparedStatement stmt = connection.prepareStatement( "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + From c41ec7b5193c1c0d0a80896993c980777bc66aee Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Sun, 22 Feb 2026 20:47:43 +0530 Subject: [PATCH 9/9] fix(health): avoid blocking DB I/O under write lock and restore interrupt flag --- .../fhir/service/health/HealthService.java | 110 +++++++++--------- 1 file changed, 56 insertions(+), 54 deletions(-) diff --git a/src/main/java/com/wipro/fhir/service/health/HealthService.java b/src/main/java/com/wipro/fhir/service/health/HealthService.java index 811c948..4072bb5 100644 --- a/src/main/java/com/wipro/fhir/service/health/HealthService.java +++ b/src/main/java/com/wipro/fhir/service/health/HealthService.java @@ -34,6 +34,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.concurrent.ExecutionException; import java.util.function.Supplier; import jakarta.annotation.PreDestroy; import javax.sql.DataSource; @@ -46,7 +47,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @@ -100,14 +100,14 @@ public class HealthService { // Deadlock check resilience - disable after first permission error private volatile boolean deadlockCheckDisabled = false; - @Value("${health.advanced.enabled:true}") - private boolean advancedHealthChecksEnabled; + // Advanced checks always enabled + private static final boolean ADVANCED_HEALTH_CHECKS_ENABLED = true; public HealthService(DataSource dataSource, @Autowired(required = false) RedisTemplate redisTemplate) { this.dataSource = dataSource; this.redisTemplate = redisTemplate; - this.executorService = Executors.newFixedThreadPool(2); + this.executorService = Executors.newFixedThreadPool(6); this.advancedCheckExecutor = Executors.newSingleThreadExecutor(r -> { Thread t = new Thread(r, "health-advanced-check"); t.setDaemon(true); @@ -142,47 +142,10 @@ public Map checkHealth() { Map mysqlStatus = new ConcurrentHashMap<>(); Map redisStatus = new ConcurrentHashMap<>(); - // Check if executor service is shutdown (during graceful shutdown) - if (executorService.isShutdown()) { - ensurePopulated(mysqlStatus, MYSQL_COMPONENT); - ensurePopulated(redisStatus, REDIS_COMPONENT); - // Fall through to build response with DOWN status - } else { - // Submit both checks concurrently using executorService for proper cancellation support - Future mysqlFuture = executorService.submit( - () -> performHealthCheck(MYSQL_COMPONENT, mysqlStatus, this::checkMySQLHealthSync)); - Future redisFuture = executorService.submit( - () -> performHealthCheck(REDIS_COMPONENT, redisStatus, this::checkRedisHealthSync)); - - // Wait for both checks to complete with combined timeout (shared deadline) - long maxTimeout = Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; - long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); - try { - mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); - long remainingNs = deadlineNs - System.nanoTime(); - if (remainingNs > 0) { - redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); - } else { - redisFuture.cancel(true); - } - } catch (TimeoutException e) { - logger.warn("Health check aggregate timeout after {} seconds", maxTimeout); - mysqlFuture.cancel(true); - redisFuture.cancel(true); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - logger.warn("Health check was interrupted"); - mysqlFuture.cancel(true); - redisFuture.cancel(true); - // Mark components as DOWN before returning - } catch (Exception e) { - logger.warn("Health check execution error: {}", e.getMessage()); - mysqlFuture.cancel(true); - redisFuture.cancel(true); - } + if (!executorService.isShutdown()) { + performHealthChecks(mysqlStatus, redisStatus); } - // Ensure timed-out or unfinished components are marked DOWN ensurePopulated(mysqlStatus, MYSQL_COMPONENT); ensurePopulated(redisStatus, REDIS_COMPONENT); @@ -191,14 +154,54 @@ public Map checkHealth() { components.put("redis", redisStatus); response.put("components", components); - - // Compute overall status - String overallStatus = computeOverallStatus(components); - response.put(STATUS_KEY, overallStatus); + response.put(STATUS_KEY, computeOverallStatus(components)); return response; } + private void performHealthChecks(Map mysqlStatus, Map redisStatus) { + Future mysqlFuture = executorService.submit( + () -> performHealthCheck(MYSQL_COMPONENT, mysqlStatus, this::checkMySQLHealthSync)); + Future redisFuture = executorService.submit( + () -> performHealthCheck(REDIS_COMPONENT, redisStatus, this::checkRedisHealthSync)); + + try { + awaitHealthChecks(mysqlFuture, redisFuture); + } catch (TimeoutException e) { + logger.warn("Health check aggregate timeout after {} seconds", getMaxTimeout()); + mysqlFuture.cancel(true); + redisFuture.cancel(true); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.warn("Health check was interrupted"); + mysqlFuture.cancel(true); + redisFuture.cancel(true); + } catch (Exception e) { + logger.warn("Health check execution error: {}", e.getMessage()); + mysqlFuture.cancel(true); + redisFuture.cancel(true); + } + } + + private void awaitHealthChecks(Future mysqlFuture, Future redisFuture) throws TimeoutException, InterruptedException, ExecutionException { + long maxTimeout = getMaxTimeout(); + long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); + + mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); + long remainingNs = deadlineNs - System.nanoTime(); + + if (remainingNs > 0) { + redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); + } else { + redisFuture.cancel(true); + } + } + + private long getMaxTimeout() { + return Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; + } + + private void ensurePopulated(Map status, String componentName) { if (!status.containsKey(STATUS_KEY)) { status.put(STATUS_KEY, STATUS_DOWN); @@ -349,7 +352,7 @@ private String computeOverallStatus(Map> components) // Internal advanced health checks for MySQL - do not expose details in responses private boolean performAdvancedMySQLChecksWithThrottle() { - if (!advancedHealthChecksEnabled) { + if (!ADVANCED_HEALTH_CHECKS_ENABLED) { return false; // Advanced checks disabled } @@ -377,16 +380,15 @@ private boolean performAdvancedMySQLChecksWithThrottle() { } AdvancedCheckResult result; - java.util.concurrent.CompletableFuture future = - java.util.concurrent.CompletableFuture - .supplyAsync(this::performAdvancedMySQLChecks, advancedCheckExecutor); + Future future = + advancedCheckExecutor.submit(this::performAdvancedMySQLChecks); try { result = future.get(ADVANCED_CHECKS_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } catch (java.util.concurrent.TimeoutException ex) { + } catch (TimeoutException ex) { logger.debug("Advanced MySQL checks timed out after {}ms", ADVANCED_CHECKS_TIMEOUT_MS); future.cancel(true); result = new AdvancedCheckResult(true); // treat timeout as degraded - } catch (java.util.concurrent.ExecutionException ex) { + } catch (ExecutionException ex) { future.cancel(true); // Check if the cause is an InterruptedException if (ex.getCause() instanceof InterruptedException) { @@ -476,7 +478,7 @@ private boolean hasLockWaits(Connection connection) { private boolean hasSlowQueries(Connection connection) { try (PreparedStatement stmt = connection.prepareStatement( "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + - "WHERE command != 'Sleep' AND time > ? AND user NOT IN ('event_scheduler', 'system user')")) { + "WHERE command != 'Sleep' AND time > ? AND user = SUBSTRING_INDEX(USER(), '@', 1)")) { stmt.setQueryTimeout(2); stmt.setInt(1, 10); // Queries running longer than 10 seconds try (ResultSet rs = stmt.executeQuery()) {