From f3f4a306e598de995627970c2912e542bf9c3c7f Mon Sep 17 00:00:00 2001 From: luqingjie <544309509@qq.com> Date: Fri, 6 Nov 2026 23:07:07 -0500 Subject: [PATCH] =?UTF-8?q?usdt-ui=E5=9C=A8=E5=85=A8=E5=B1=80=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E9=82=A3=E8=BE=B9=E6=98=BE=E7=A4=BA=E6=89=A7=E8=A1=8C?= =?UTF-8?q?=E5=99=A8=E7=9A=84=E5=8F=AF=E7=94=A8=E7=8A=B6=E6=80=81=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=EF=BC=8C=E9=9C=80=E8=A6=81=E5=AE=9A=E6=9C=9F=E5=8E=BB?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=EF=BC=8C=E5=A6=82=E6=9E=9C=E4=B8=8D=E5=9C=A8?= =?UTF-8?q?=E7=BA=BF=EF=BC=8C=E5=88=99=E5=8F=AA=E8=83=BD=E9=80=9A=E8=BF=87?= =?UTF-8?q?=E8=BE=93=E5=85=A5=E9=85=8D=E7=BD=AE=E5=AF=86=E7=A0=81=EF=BC=8C?= =?UTF-8?q?=E5=A6=82=E6=9E=9C=E4=B8=8B=E7=BA=BF=E4=BA=86=E5=8F=88=E9=87=8D?= =?UTF-8?q?=E6=96=B0=E4=B8=8A=E7=BA=BF=E9=9C=80=E8=A6=81=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E5=90=AF=E7=94=A8=E6=89=A7=E8=A1=8C=E5=99=A8=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/chain-executor.md | 6 ++ .../src/main/resources/application.yml | 5 +- .../system/chain/ChainExecutorClient.java | 97 ++++++++++++++++++- .../chain/ChainExecutorRuntimeState.java | 52 ++++++++++ .../controller/ChainExecutorController.java | 13 ++- .../chain/ChainExecutorRuntimeStateTest.java | 36 +++++++ 6 files changed, 202 insertions(+), 7 deletions(-) create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorRuntimeState.java create mode 100644 ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainExecutorRuntimeStateTest.java diff --git a/docs/chain-executor.md b/docs/chain-executor.md index 73d8a89..4a99ef8 100644 --- a/docs/chain-executor.md +++ b/docs/chain-executor.md @@ -52,6 +52,8 @@ | `CHAIN_EXECUTOR_BASE_URL` | 无尾斜杠/路径的 HTTP 或 HTTPS 根地址,例如 `http://192.168.10.20:9088` 或 `https://192.168.10.20:9088` | | `CHAIN_EXECUTOR_TOKEN` | 独立服务凭据,与执行器一致 | | `CHAIN_EXECUTOR_TLS_CERTIFICATE` | HTTPS时可配置 `file:/.../rent-cert.pem` 或 `classpath:` 证书/CA;HTTP忽略 | +| `CHAIN_EXECUTOR_HEALTH_CHECK_INTERVAL_MS` | 后端健康检查周期,默认 `10000` 毫秒 | +| `CHAIN_EXECUTOR_HEALTH_FAILURE_THRESHOLD` | 连续失败自动停用阈值,默认 `3` 次 | 执行器自身只提供 HTTP。支付后端可使用 HTTP 直连,或使用 HTTPS 调用同机 Nginx,由 Nginx 转发到回环 HTTP。 生产跨机器调用推荐 HTTPS;证书 SAN 必须包含配置的内网 IP,支付后端 JVM 需信任签发 CA,禁止关闭证书校验。 @@ -60,6 +62,10 @@ HTTPS使用自签或内部CA时,建议设置 `CHAIN_EXECUTOR_TLS_CERTIFICATE=f 只支持 IPv4 字面地址,不接受域名,避免 DNS 重绑定和意外公网解析。Nginx 示例见 `usdt-chain-executor/nginx/usdt-chain-executor.conf`。 +后端定期检查执行器联通和业务就绪状态。管理员运行开关保存在 `sys_config` 的 +`chain.executor.runtime.enabled`:连续失败达到阈值后自动写为 `false`,新链上操作只能使用配置密码。 +服务恢复后只更新可达状态,不会自动打开运行开关;管理员需在全局配置页确认并重新启用。 + ### HTTPS + Nginx 推荐配置 执行器配置为 `CHAIN_EXECUTOR_BIND_ADDRESS=127.0.0.1`、`CHAIN_EXECUTOR_PORT=9089`、 diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index bf3dd5b..26083c2 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -5,7 +5,10 @@ chain: url: ${CHAIN_EXECUTOR_BASE_URL:https://192.168.3.103:9088} token: ${CHAIN_EXECUTOR_TOKEN:6hsYMjzuXPXYFd8SYRa45YnA7LyctJYD} # HTTPS模式下追加信任的执行器证书或CA证书,仅允许file:/或classpath:资源。 - tls-certificate-location: ${CHAIN_EXECUTOR_TLS_CERTIFICATE:file:/etc/nginx/certs/rent-cert.pem}} + tls-certificate-location: ${CHAIN_EXECUTOR_TLS_CERTIFICATE:file:/etc/nginx/certs/rent-cert.pem} + # 连续失败达到阈值后自动停用;服务恢复后必须由管理员在全局配置页重新启用。 + health-check-interval-ms: ${CHAIN_EXECUTOR_HEALTH_CHECK_INTERVAL_MS:10000} + health-failure-threshold: ${CHAIN_EXECUTOR_HEALTH_FAILURE_THRESHOLD:3} # 项目相关配置 ruoyi: diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorClient.java b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorClient.java index be72823..7d38386 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorClient.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorClient.java @@ -9,12 +9,18 @@ import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestClientResponseException; import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import javax.net.ssl.HttpsURLConnection; import java.net.URI; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; /** 内网调用客户端。仅允许内网字面 IP;禁用 HTTP 重定向,避免凭据被转发到其他主机。 */ @Component @@ -28,7 +34,17 @@ public class ChainExecutorClient { private String token; @Value("${chain.executor.tls-certificate-location:}") private String tlsCertificateLocation; + @Value("${chain.executor.health-failure-threshold:3}") + private int healthFailureThreshold; + @Autowired(required = false) + private ChainExecutorRuntimeState runtimeState; private RestTemplate http; + private final AtomicBoolean checking = new AtomicBoolean(); + private volatile boolean reachable; + private volatile boolean checked; + private volatile int consecutiveFailures; + private volatile long checkedAt; + private volatile String lastDiagnostic = "NOT_CHECKED"; public ChainExecutorClient() { http = createHttp(null); @@ -80,8 +96,10 @@ public class ChainExecutorClient { try { requireResponse("/internal/v1/connectivity", "CONNECTED", "联通测试"); requireResponse("/internal/v1/readiness", "READY", "业务就绪检查"); + recordSuccess(); log.info("内网链上执行器服务验证通过,联通状态=CONNECTED,业务状态=READY"); } catch (IllegalStateException unavailable) { + recordFailure(unavailable.getMessage()); // 执行器可能与支付系统存在短暂启动顺序差异。保留支付管理能力,实际远程执行仍由ready()拒绝。 log.error("内网链上执行器启动验证未通过,支付系统继续启动,远程链上操作暂不可用,诊断={}", unavailable.getMessage()); @@ -90,17 +108,55 @@ public class ChainExecutorClient { public boolean isEnabled() { return enabled; } + public boolean isRuntimeEnabled() { return enabled && (runtimeState == null || runtimeState.enabled()); } + public boolean ready() { - if (!enabled) return false; + if (!isRuntimeEnabled()) return false; try { - return "READY".equals(http.exchange(url + "/internal/v1/readiness", HttpMethod.GET, + boolean current = "READY".equals(http.exchange(url + "/internal/v1/readiness", HttpMethod.GET, new HttpEntity(headers()), String.class).getBody()); + if (current) recordSuccess(); else recordFailure("INVALID_READY_RESPONSE"); + return current; } catch (Exception failure) { - log.warn("内网链上执行器业务就绪检查失败,诊断={}", diagnostic(failure)); + String diagnostic = diagnostic(failure); + recordFailure(diagnostic); + log.warn("内网链上执行器业务就绪检查失败,诊断={}", diagnostic); return false; } } + /** 后台持续探测,即使已自动停用也继续更新“已恢复、待管理员启用”状态。 */ + @Scheduled(fixedDelayString = "${chain.executor.health-check-interval-ms:10000}", initialDelayString = "${chain.executor.health-check-initial-delay-ms:10000}") + public void monitor() { + if (!enabled || !checking.compareAndSet(false, true)) return; + try { + probeNow(); + } finally { + checking.set(false); + } + } + + /** 只有实时探测可用时才允许管理员重新打开,避免误启用后立即接受远程任务。 */ + public void enableRuntime(String operator) { + if (!probeNow()) throw new com.ruoyi.common.exception.CustomException("执行器尚未恢复,无法启用"); + if (runtimeState != null) runtimeState.enableByAdministrator(operator); + } + + public Map availability() { + Map result = new LinkedHashMap<>(); + boolean runtimeEnabled = isRuntimeEnabled(); + result.put("enabled", enabled); + result.put("runtimeEnabled", runtimeEnabled); + result.put("reachable", reachable); + result.put("ready", enabled && runtimeEnabled && reachable); + result.put("requiresManualEnable", enabled && reachable && !runtimeEnabled); + result.put("checked", checked); + result.put("checkedAt", checkedAt == 0 ? null : Instant.ofEpochMilli(checkedAt).toString()); + result.put("consecutiveFailures", consecutiveFailures); + result.put("diagnostic", lastDiagnostic); + return result; + } + public void notifyExecutor() { try { http.exchange(url + "/internal/v1/executions", HttpMethod.POST, @@ -136,6 +192,41 @@ public class ChainExecutorClient { return cause.getClass().getSimpleName(); } + private synchronized void recordSuccess() { + boolean recovered = checked && !reachable; + reachable = true; + checked = true; + consecutiveFailures = 0; + checkedAt = System.currentTimeMillis(); + lastDiagnostic = "READY"; + if (recovered) log.info("内网链上执行器探测已恢复,等待管理员确认运行开关状态"); + } + + private synchronized void recordFailure(String diagnostic) { + reachable = false; + checked = true; + consecutiveFailures++; + checkedAt = System.currentTimeMillis(); + lastDiagnostic = diagnostic == null ? "UNAVAILABLE" : diagnostic; + int threshold = Math.max(1, healthFailureThreshold); + if (consecutiveFailures >= threshold && runtimeState != null) runtimeState.disableAfterOutage(); + } + + private boolean probeNow() { + try { + String connected = http.exchange(url + "/internal/v1/connectivity", HttpMethod.GET, + new HttpEntity(headers()), String.class).getBody(); + String ready = http.exchange(url + "/internal/v1/readiness", HttpMethod.GET, + new HttpEntity(headers()), String.class).getBody(); + boolean available = "CONNECTED".equals(connected) && "READY".equals(ready); + if (available) recordSuccess(); else recordFailure("INVALID_HEALTH_RESPONSE"); + return available; + } catch (Exception failure) { + recordFailure(diagnostic(failure)); + return false; + } + } + private static String rootType(Throwable failure) { Throwable cause = failure; while (cause.getCause() != null && cause.getCause() != cause) cause = cause.getCause(); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorRuntimeState.java b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorRuntimeState.java new file mode 100644 index 0000000..bc9b3b4 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorRuntimeState.java @@ -0,0 +1,52 @@ +package com.ruoyi.system.chain; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import java.util.List; + +/** + * 持久化远程执行器的管理员启用闩锁。 + * 部署开关表示具备远程能力;本状态表示管理员是否允许使用。自动检测只能关闭,不能自动重新打开。 + */ +@Component +public class ChainExecutorRuntimeState { + static final String CONFIG_KEY = "chain.executor.runtime.enabled"; + private static final Logger log = LoggerFactory.getLogger(ChainExecutorRuntimeState.class); + private final JdbcTemplate jdbc; + + public ChainExecutorRuntimeState(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + /** 未写入状态表示沿用部署开关启用,兼容升级前的现有行为。 */ + public boolean enabled() { + List values = jdbc.queryForList("select config_value from sys_config where config_key=? " + + "order by config_id desc limit 1", String.class, CONFIG_KEY); + return values.isEmpty() || "true".equalsIgnoreCase(values.get(0)); + } + + public synchronized void disableAfterOutage() { + if (!enabled()) return; + save(false, "executor-monitor", "执行器连续探测失败,已自动停用;恢复后需管理员重新启用"); + log.warn("内网链上执行器已因连续探测失败自动停用"); + } + + public synchronized void enableByAdministrator(String operator) { + save(true, operator, "管理员确认执行器已恢复并重新启用"); + log.info("内网链上执行器已由管理员重新启用,operator={}", operator); + } + + private void save(boolean enabled, String operator, String remark) { + int updated = jdbc.update("update sys_config set config_value=?,config_type='Y',update_by=?," + + "update_time=CURRENT_TIMESTAMP,remark=? where config_key=?", + String.valueOf(enabled), operator, remark, CONFIG_KEY); + if (updated == 0) { + jdbc.update("insert into sys_config(config_name,config_key,config_value,config_type,create_by,create_time,remark) " + + "values('链上执行器运行开关',?,?,'Y',?,CURRENT_TIMESTAMP,?)", + CONFIG_KEY, String.valueOf(enabled), operator, remark); + } + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/ChainExecutorController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/ChainExecutorController.java index 7f8ed52..b73dd8e 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/controller/ChainExecutorController.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/ChainExecutorController.java @@ -8,6 +8,7 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.PostMapping; import java.util.LinkedHashMap; import java.util.Map; @@ -31,9 +32,7 @@ public class ChainExecutorController { + "or @ss.hasPermi('system:usdtTaskItem:edit') or @ss.hasPermi('system:usdtPayoutOrder:execute')") @GetMapping("/status") public AjaxResult status() { - Map result = new LinkedHashMap<>(); - result.put("enabled", client.isEnabled()); - result.put("ready", client.ready()); + Map result = new LinkedHashMap<>(client.availability()); // 明确列出公开字段,禁止 SELECT * 结果进入 HTTP 响应。 boolean rentalEnabled = rentalProperties != null && rentalProperties.isEnabled(); result.put("executions", client.isEnabled() ? store.jdbc().queryForList(rentalEnabled @@ -45,4 +44,12 @@ public class ChainExecutorController { : java.util.Collections.emptyList()); return AjaxResult.success(result); } + + /** 服务恢复后必须由全局配置管理员显式重新启用,状态探测本身绝不自动开启。 */ + @PreAuthorize("@ss.hasPermi('system:usdtConfig:edit')") + @PostMapping("/enable") + public AjaxResult enable() { + client.enableRuntime(SecurityUtils.getUsername()); + return AjaxResult.success("链上执行器已重新启用", client.availability()); + } } diff --git a/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainExecutorRuntimeStateTest.java b/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainExecutorRuntimeStateTest.java new file mode 100644 index 0000000..0fe26cb --- /dev/null +++ b/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainExecutorRuntimeStateTest.java @@ -0,0 +1,36 @@ +package com.ruoyi.system.chain; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** 运行闩锁持久化测试:故障只能关闭,恢复必须显式由管理员重新开启。 */ +public class ChainExecutorRuntimeStateTest { + private ChainExecutorRuntimeState state; + + @Before + public void setup() { + JdbcTemplate jdbc = new JdbcTemplate(new DriverManagerDataSource( + "jdbc:h2:mem:executor-state" + System.nanoTime() + + ";MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1", "sa", "")); + jdbc.execute("create table sys_config(config_id bigint auto_increment primary key,config_name varchar(100)," + + "config_key varchar(100),config_value varchar(500),config_type char(1),create_by varchar(64)," + + "create_time timestamp,update_by varchar(64),update_time timestamp,remark varchar(500))"); + state = new ChainExecutorRuntimeState(jdbc); + } + + @Test + public void defaultsEnabledThenRequiresExplicitAdministratorEnableAfterOutage() { + assertTrue(state.enabled()); + state.disableAfterOutage(); + assertFalse(state.enabled()); + state.disableAfterOutage(); + assertFalse(state.enabled()); + state.enableByAdministrator("admin"); + assertTrue(state.enabled()); + } +}