usdt-ui在全局配置那边显示执行器的可用状态显示,需要定期去检查,如果不在线,则只能通过输入配置密码,如果下线了又重新上线需要重新启用执行器功能。

This commit is contained in:
lu7213 committed 2026-11-06 23:07:07 -05:00
1 parent 637be83684
commit f3f4a306e5
6 files changed
+202 -7

No files matched your search

@@ -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<Void>(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<String, Object> availability() {
Map<String, Object> 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<Void>(headers()), String.class).getBody();
String ready = http.exchange(url + "/internal/v1/readiness", HttpMethod.GET,
new HttpEntity<Void>(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();
@@ -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<String> 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);
}
}
}
@@ -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<String, Object> result = new LinkedHashMap<>();
result.put("enabled", client.isEnabled());
result.put("ready", client.ready());
Map<String, Object> 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());
}
}
@@ -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());
}
}