初始化系统融合软件代码仓库
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
package com.xtrh;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
/**
|
||||
* 同一份 Java 程序按配置运行总控、网关或节点,业务操作统一由 PXHJ 发起。
|
||||
* 启动入口保留在根包,使 Spring 能扫描各业务模块中的组件。
|
||||
*/
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("java.awt.headless", "true");
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.xtrh.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
|
||||
/**
|
||||
* 主节点同时管理集群与执行视频,心跳、调度和画面生成不能占用同一条定时线程。
|
||||
* 定时任务仍使用各自的固定延迟,业务状态同步由对应服务的锁保护。
|
||||
*/
|
||||
@Configuration
|
||||
public class SchedulerConfiguration {
|
||||
@Bean(name = "taskScheduler")
|
||||
public ThreadPoolTaskScheduler taskScheduler() {
|
||||
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||
scheduler.setPoolSize(4);
|
||||
scheduler.setThreadNamePrefix("xtrh-scheduled-");
|
||||
return scheduler;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.xtrh.common.config;
|
||||
|
||||
import com.xtrh.common.dao.NodeIdentityDao;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.boot.web.context.WebServerInitializedEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 将部署配置集中转换为服务启动参数,业务层不需要重复读取环境变量。
|
||||
* 配置不完整时直接拒绝启动,避免节点以错误集群身份接收任务。
|
||||
* 本类不依赖总控或发现服务,网关也能独立加载已保存的转发配置。
|
||||
*/
|
||||
@Component
|
||||
public class Settings {
|
||||
public final String role, cluster, token, id, bootId, name, coordinator, advertisedHost, bindHost;
|
||||
public final Path directory;
|
||||
public final int capacity, gatewayPort, targetPort;
|
||||
// HTTP 就绪事件发布实际端口,随机端口部署不能继续上报配置中的 0。
|
||||
public volatile int port;
|
||||
private volatile boolean serverReady;
|
||||
public final long leaseMs;
|
||||
public final boolean discoveryEnabled;
|
||||
public final boolean supportsWorker;
|
||||
public final String discoveryAddress;
|
||||
|
||||
public Settings(Environment env) throws Exception {
|
||||
// 三种角色共用一个 JAR;安装脚本分别指定角色、端口和独立数据目录。
|
||||
role = env.getProperty("fusion.role", "coordinator");
|
||||
if (!Set.of("coordinator", "worker", "gateway").contains(role)) {
|
||||
throw new IllegalArgumentException("Unknown service role");
|
||||
}
|
||||
// 主节点默认兼任执行节点;仅总控部署可关闭执行能力,子节点仍保持执行职责。
|
||||
supportsWorker = workerEnabled(env);
|
||||
|
||||
// 集群名称用于筛选发现线索,凭证则用于请求和响应签名,二者用途不同。
|
||||
// 凭证从私有部署配置读取,不能通过公共健康接口或节点状态返回。
|
||||
cluster = env.getProperty("fusion.cluster-id", "pxhj-fusion");
|
||||
token = env.getProperty("fusion.token", "");
|
||||
if (token.length() < 24) {
|
||||
throw new IllegalArgumentException("Configure a shared service credential with at least 24 characters");
|
||||
}
|
||||
|
||||
// 稳定身份由 DAO 保存;每次进程启动重新生成 bootId,以隔离旧进程回执。
|
||||
// 不在配置层执行文件读写细节,身份文件损坏或无法保存时让启动失败。
|
||||
directory = Path.of(env.getProperty("fusion.data-dir", "./data/" + role))
|
||||
.toAbsolutePath().normalize();
|
||||
id = NodeIdentityDao.loadOrCreate(directory);
|
||||
bootId = UUID.randomUUID().toString();
|
||||
|
||||
name = env.getProperty("fusion.node-name", InetAddress.getLocalHost().getHostName());
|
||||
// 同网段部署默认不填写总控 URL,保留为空以使用自动发现。
|
||||
coordinator = env.getProperty("fusion.coordinator-url", "").replaceAll("/+$", "");
|
||||
advertisedHost = env.getProperty("fusion.advertised-host", "");
|
||||
bindHost = env.getProperty("server.address", "0.0.0.0");
|
||||
|
||||
// 容量是管理员确认的最大并行路数,不代表程序已经测量过显卡能力。
|
||||
capacity = env.getProperty("fusion.capacity", Integer.class, 2);
|
||||
if (capacity < 0 || capacity > 64) {
|
||||
throw new IllegalArgumentException("Capacity must be between 0 and 64");
|
||||
}
|
||||
|
||||
// HTTP 管理、网关 UDP 接入和 PXHJ 接收端口各自配置,不能混为同一入口。
|
||||
port = env.getProperty("server.port", Integer.class, 18100);
|
||||
gatewayPort = env.getProperty("fusion.gateway-port", Integer.class, 19002);
|
||||
targetPort = env.getProperty("fusion.forward-target-port", Integer.class, 19001);
|
||||
|
||||
// 授权有效期交给业务服务用单调时钟计时;这里仅校验部署值范围。
|
||||
leaseMs = env.getProperty("fusion.lease-ms", Long.class, 8000L);
|
||||
if (leaseMs < 3000 || leaseMs > 120000) {
|
||||
throw new IllegalArgumentException("Invalid lease duration");
|
||||
}
|
||||
|
||||
// 多网卡环境可限定发现网卡;不指定时由发现服务尝试可用组播网卡。
|
||||
discoveryEnabled = env.getProperty("fusion.discovery-enabled", Boolean.class, true);
|
||||
discoveryAddress = env.getProperty("fusion.discovery-address", "");
|
||||
}
|
||||
|
||||
/** 能力判断由配置与条件组件共用,避免启动了媒体接口却没有执行服务。 */
|
||||
public static boolean workerEnabled(Environment env) {
|
||||
String role = env.getProperty("fusion.role", "coordinator");
|
||||
return role.equals("worker") || (role.equals("coordinator")
|
||||
&& env.getProperty("fusion.coordinator-worker-enabled", Boolean.class, true));
|
||||
}
|
||||
|
||||
/** 本机执行端等待总控 HTTP 已就绪,再按实际端口自注册。 */
|
||||
@EventListener public void serverStarted(WebServerInitializedEvent event) {
|
||||
port = event.getWebServer().getPort();
|
||||
serverReady = true;
|
||||
}
|
||||
|
||||
public boolean httpReady() { return serverReady; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.xtrh.common.controller;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 将已知业务异常转换为现有 HTTP 契约,业务判断仍由服务层完成。
|
||||
* 错误响应不能伪装成成功,调用方据状态码决定是否修正配置或重新注册。
|
||||
*/
|
||||
@RestControllerAdvice
|
||||
public class ApiErrors {
|
||||
// 参数、容量或地址不合法时返回 400,避免客户端反复重试同一错误输入。
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public ResponseEntity<?> invalid(IllegalArgumentException e) {
|
||||
return ResponseEntity.badRequest().body(Map.of("message", e.getMessage()));
|
||||
}
|
||||
|
||||
// 旧会话或当前状态冲突返回 409,节点需要重新核对总控状态。
|
||||
// 此处保留错误消息契约,不输出异常堆栈、凭证或请求头。
|
||||
@ExceptionHandler(IllegalStateException.class)
|
||||
public ResponseEntity<?> conflict(IllegalStateException e) {
|
||||
return ResponseEntity.status(409).body(Map.of("message", e.getMessage()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.xtrh.common.controller;
|
||||
|
||||
import com.xtrh.common.config.Settings;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 提供无凭证的进程身份查询,供安装脚本确认启动的是本部署实例。
|
||||
* 不返回集群凭证、设备密钥、试验配置或播放许可。
|
||||
* 健康响应只代表进程存在,任务就绪和总控存储状态需查询正式控制接口。
|
||||
*/
|
||||
@RestController
|
||||
public class HealthController {
|
||||
private final Settings settings;
|
||||
|
||||
public HealthController(Settings settings) {
|
||||
this.settings = settings;
|
||||
}
|
||||
|
||||
// 控制层只组装公开的身份信息,不触发注册、调度或数据库更新。
|
||||
@GetMapping("/health")
|
||||
public Object health() {
|
||||
return Map.of(
|
||||
"service", "xtrh-services",
|
||||
"role", settings.role,
|
||||
"workerEnabled", settings.supportsWorker,
|
||||
"clusterId", settings.cluster,
|
||||
"serviceId", settings.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.xtrh.common.dao;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 负责部署实例身份的文件持久化。
|
||||
* 每台电脑使用独立数据目录,重启复用原身份,重新安装也无需手动登记节点。
|
||||
*/
|
||||
public final class NodeIdentityDao {
|
||||
private NodeIdentityDao() {}
|
||||
|
||||
/** 首次安装生成身份;已有文件格式错误时停止启动,避免错误身份覆盖集群中的其他节点。 */
|
||||
public static String loadOrCreate(Path directory) throws Exception {
|
||||
Files.createDirectories(directory);
|
||||
Path identity = directory.resolve("identity.txt");
|
||||
// CREATE_NEW 避免并发启动时覆盖另一个进程刚生成的身份。
|
||||
if (!Files.exists(identity)) Files.writeString(identity, UUID.randomUUID().toString(), StandardOpenOption.CREATE_NEW);
|
||||
String value = Files.readString(identity).trim();
|
||||
if (!value.matches("[a-zA-Z0-9_-]{8,64}")) throw new IllegalArgumentException("Invalid persisted service identity");
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.xtrh.common.dao;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.xtrh.common.util.Jsons;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
|
||||
/**
|
||||
* 仅负责读取和保存完整状态快照,不在 DAO 中决定任务分配或轮次状态。
|
||||
* H2 文件锁阻止两个进程同时占用同一状态文件,避免并行写入产生双总控。
|
||||
*/
|
||||
public final class StateStore implements AutoCloseable {
|
||||
private final Connection connection;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
// 文件数据库的 JDBC 地址由 DAO 统一组装,业务服务只选择本角色的数据文件。
|
||||
// 使用绝对规范路径,避免工作目录变化后误建另一份总控或网关状态。
|
||||
public static StateStore open(Path databaseFile, ObjectMapper mapper) throws Exception {
|
||||
String databasePath = databaseFile.toAbsolutePath().normalize().toString().replace('\\', '/');
|
||||
return new StateStore("jdbc:h2:file:" + databasePath + ";DB_CLOSE_ON_EXIT=FALSE", mapper);
|
||||
}
|
||||
|
||||
public StateStore(String url, ObjectMapper mapper) throws Exception {
|
||||
this.mapper = mapper;
|
||||
connection = DriverManager.getConnection(url, "sa", "");
|
||||
|
||||
// 固定主键只保存一个当前快照;初始化失败向上传递,不降级到临时内存状态。
|
||||
try (var statement = connection.createStatement()) {
|
||||
statement.execute(
|
||||
"CREATE TABLE IF NOT EXISTS fusion_state (id INT PRIMARY KEY, payload CLOB NOT NULL)");
|
||||
}
|
||||
}
|
||||
|
||||
// 新数据库由业务服务补齐结构;已有内容读取失败不能当成首次部署。
|
||||
public ObjectNode load() throws Exception {
|
||||
try (var statement = connection.createStatement();
|
||||
var result = statement.executeQuery("SELECT payload FROM fusion_state WHERE id=1")) {
|
||||
return result.next()
|
||||
? (ObjectNode) mapper.readTree(result.getString(1))
|
||||
: Jsons.object();
|
||||
}
|
||||
}
|
||||
|
||||
// 一条 MERGE 原子替换快照,避免分别保存节点与任务造成不一致。
|
||||
// 写入失败交由总控服务标记存储异常并停止续发任务许可。
|
||||
public void save(ObjectNode value) {
|
||||
try (var statement = connection.prepareStatement(
|
||||
"MERGE INTO fusion_state (id,payload) KEY(id) VALUES(1,?)")) {
|
||||
// 使用参数绑定保存 JSON,配置内容不会被拼接成 SQL。
|
||||
statement.setString(1, mapper.writeValueAsString(value));
|
||||
statement.executeUpdate();
|
||||
} catch (Exception e) {
|
||||
// 保留底层原因供服务端排查,不能静默跳过持久化后继续宣称保存成功。
|
||||
throw new IllegalStateException("Cannot persist coordinator state", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
connection.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.xtrh.common.util;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 公共 JSON 构造及输入校验工具,不依赖数据库或 Spring 容器。
|
||||
* 统一保留字段和错误消息规则,控制层与后台通信共用相同校验口径。
|
||||
*/
|
||||
public final class Jsons {
|
||||
private Jsons() {}
|
||||
|
||||
public static ObjectNode object() {
|
||||
return JsonNodeFactory.instance.objectNode();
|
||||
}
|
||||
|
||||
public static ArrayNode array() {
|
||||
return JsonNodeFactory.instance.arrayNode();
|
||||
}
|
||||
|
||||
// 参数错误向上传递,交由统一 HTTP 异常处理器返回失败。
|
||||
public static void require(boolean valid, String message) {
|
||||
if (!valid) {
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 必填标识去除首尾空白并限制长度;不截断输入,避免两个标识意外变成同一值。
|
||||
* 字段是否允许空值仍由业务服务决定,不能在工具中猜测试验或设备关系。
|
||||
*/
|
||||
public static String required(JsonNode node, String key) {
|
||||
String value = node.path(key).asText("").trim();
|
||||
require(!value.isEmpty() && value.length() <= 200, "Invalid " + key);
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 来源服务地址必须是 HTTP/HTTPS 根地址,具体控制或媒体路径由程序追加。
|
||||
* 拒绝嵌入用户凭证、查询参数和片段,避免缓存地址夹带身份或改变请求签名路径。
|
||||
* 地址合法不等于可信,发现服务仍需验证远端响应签名、集群和总控身份。
|
||||
*/
|
||||
public static String baseUrl(String value) {
|
||||
URI uri = URI.create(value);
|
||||
require(
|
||||
Set.of("http", "https").contains(uri.getScheme())
|
||||
&& uri.getHost() != null
|
||||
&& uri.getUserInfo() == null
|
||||
&& uri.getRawQuery() == null
|
||||
&& uri.getFragment() == null
|
||||
&& (uri.getPath().isEmpty() || uri.getPath().equals("/")),
|
||||
"Invalid service address");
|
||||
return value.replaceAll("/+$", "");
|
||||
}
|
||||
|
||||
// 返回当前对象的引用,服务层须在自己的同步范围内修改,向外展示时另做快照复制。
|
||||
public static List<ObjectNode> rows(ObjectNode root, String key) {
|
||||
List<ObjectNode> result = new ArrayList<>();
|
||||
root.path(key).elements().forEachRemaining(n -> result.add((ObjectNode) n));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.xtrh.communication.client;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xtrh.common.config.Settings;
|
||||
import com.xtrh.common.util.Jsons;
|
||||
import com.xtrh.communication.security.Signatures;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 后台服务之间的签名 HTTP 客户端,供自动发现、注册与领取任务共用。
|
||||
* 发送方和接收方都证明持有集群凭证,网络请求不传输明文密钥。
|
||||
* 浏览器通过 PXHJ 会话操作,不能直接获得这个服务客户端的凭证。
|
||||
*/
|
||||
@Component
|
||||
public class PeerClient {
|
||||
private final Settings settings;
|
||||
private final ObjectMapper mapper;
|
||||
// 连接和请求都有时限,总控不可用时尽快进入重试,不占住心跳线程。
|
||||
private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
|
||||
|
||||
public PeerClient(Settings settings, ObjectMapper mapper) {
|
||||
this.settings = settings;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名必须使用实际发送的原始字节,不能签完以后再重新序列化 JSON。
|
||||
* nonce 将响应绑定到本次请求,旧响应不能冒充新的任务计划。
|
||||
*/
|
||||
public JsonNode request(String base, String path, String method, JsonNode body) throws Exception {
|
||||
byte[] bytes = body == null ? new byte[0] : mapper.writeValueAsBytes(body);
|
||||
String nonce = UUID.randomUUID().toString();
|
||||
String time = Long.toString(System.currentTimeMillis());
|
||||
// 根地址先校验;查询参数、HTTP 方法与完整正文随后一起进入签名。
|
||||
var builder = HttpRequest.newBuilder(URI.create(Jsons.baseUrl(base) + path))
|
||||
.timeout(Duration.ofSeconds(3))
|
||||
.header("X-Xtrh-Time", time)
|
||||
.header("X-Xtrh-Nonce", nonce)
|
||||
.header("X-Xtrh-Signature", Signatures.request(settings.token, method, path, time, nonce, bytes))
|
||||
.header("Content-Type", "application/json");
|
||||
builder.method(method, HttpRequest.BodyPublishers.ofByteArray(bytes));
|
||||
var response = client.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
// 先验证响应来源再读取业务内容,发现广播中的伪造服务无法下发有效任务。
|
||||
String expected = Signatures.response(settings.token, nonce, response.statusCode(), response.body());
|
||||
String actual = response.headers().firstValue("X-Xtrh-Response-Signature").orElse(null);
|
||||
if (!Signatures.equal(expected, actual)) throw new IllegalStateException("Peer response authentication failed");
|
||||
// 非成功状态不作为计划使用;由调用服务执行重注册或延后重试。
|
||||
if (response.statusCode() / 100 != 2) throw new IllegalStateException("Peer request failed: HTTP " + response.statusCode());
|
||||
return mapper.readTree(response.body());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.xtrh.communication.security;
|
||||
|
||||
import com.xtrh.common.config.Settings;
|
||||
import com.xtrh.console.security.ConsoleRequestPolicy;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ReadListener;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.ServletInputStream;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletRequestWrapper;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import org.springframework.web.util.ContentCachingResponseWrapper;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 为所有内部控制接口统一校验签名、防止重放并签署响应。
|
||||
* 这套凭证只用于后台服务互认;PXHJ 用户登录和权限仍由原平台负责。
|
||||
* 媒体流由节点服务单独检查任务版本及临时媒体许可。
|
||||
*/
|
||||
@Component
|
||||
public class ServiceSecurity extends OncePerRequestFilter {
|
||||
private final Settings settings;
|
||||
private final boolean consoleEnabled;
|
||||
// 验证成功的 nonce 才进入缓存,原子插入确保并发重放最多接受一次。
|
||||
private final ConcurrentHashMap<String, Long> nonces = new ConcurrentHashMap<>();
|
||||
|
||||
public ServiceSecurity(Settings settings) { this(settings, true); }
|
||||
|
||||
@Autowired
|
||||
public ServiceSecurity(Settings settings, Environment environment) {
|
||||
this(settings, environment.getProperty("fusion.console-enabled", Boolean.class, true));
|
||||
}
|
||||
|
||||
public ServiceSecurity(Settings settings, boolean consoleEnabled) {
|
||||
this.settings = settings;
|
||||
this.consoleEnabled = consoleEnabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
|
||||
String path = req.getRequestURI();
|
||||
if (consoleEnabled && settings.role.equals("coordinator")
|
||||
&& (path.equals("/console") || path.startsWith("/console/"))) {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
res.setHeader("X-Frame-Options", "DENY");
|
||||
boolean read = req.getMethod().equals("GET") || req.getMethod().equals("HEAD");
|
||||
boolean safePath = !path.contains("..") && !path.contains("\\") && !path.contains("%") && !path.contains(";");
|
||||
boolean api = path.equals("/console/api") || path.startsWith("/console/api/");
|
||||
if (!read || !safePath || (api && !ConsoleRequestPolicy.localRead(req))) {
|
||||
res.setStatus(403);
|
||||
res.setContentType("application/json");
|
||||
res.getWriter().write("{\"message\":\"Console read access denied\"}");
|
||||
return;
|
||||
}
|
||||
chain.doFilter(req, res);
|
||||
return;
|
||||
}
|
||||
// 健康入口只返回身份;媒体入口在业务层验证许可,错误分发不重复认证。
|
||||
if (path.equals("/health") || path.startsWith("/media/") || path.equals("/error")) {
|
||||
chain.doFilter(req, res);
|
||||
return;
|
||||
}
|
||||
String supplied = req.getHeader("X-Xtrh-Signature");
|
||||
String time = req.getHeader("X-Xtrh-Time");
|
||||
String nonce = req.getHeader("X-Xtrh-Nonce");
|
||||
long timestamp;
|
||||
try { timestamp = Long.parseLong(time); } catch (Exception e) { timestamp = 0; }
|
||||
// 先检查格式和一分钟时间窗,再读取正文,尽早拒绝不符合协议的控制请求。
|
||||
if (supplied == null || !supplied.matches("[0-9a-f]{64}") || nonce == null
|
||||
|| !nonce.matches("[a-zA-Z0-9-]{16,64}") || Math.abs(System.currentTimeMillis() - timestamp) > 60000) {
|
||||
reject(res, "Service authentication required");
|
||||
return;
|
||||
}
|
||||
// 有界读取保护内存;签名绑定方法、路径、查询参数和实际收到的全部正文。
|
||||
byte[] body = req.getInputStream().readNBytes(2 * 1024 * 1024 + 1);
|
||||
String requestPath = path + (req.getQueryString() == null ? "" : "?" + req.getQueryString());
|
||||
String expected = Signatures.request(settings.token, req.getMethod(), requestPath, time, nonce, body);
|
||||
if (body.length > 2 * 1024 * 1024 || !Signatures.equal(expected, supplied)
|
||||
|| nonces.putIfAbsent(nonce, timestamp) != null) {
|
||||
reject(res, "Invalid service signature");
|
||||
return;
|
||||
}
|
||||
// 超出认证时间窗的 nonce 已不能再次成功使用,可以移除以避免无限积累。
|
||||
long cutoff = System.currentTimeMillis() - 60000;
|
||||
nonces.entrySet().removeIf(entry -> entry.getValue() < cutoff);
|
||||
// 验签已经读过输入流;提供同一份字节给 Spring,避免控制层收到空正文。
|
||||
HttpServletRequest wrapped = replayable(req, body);
|
||||
ContentCachingResponseWrapper response = new ContentCachingResponseWrapper(res);
|
||||
chain.doFilter(wrapped, response);
|
||||
// 发现广播只提供地址线索;只有验证响应签名才能确认服务属于本集群。
|
||||
response.setHeader("X-Xtrh-Response-Signature", Signatures.response(settings.token, nonce, response.getStatus(), response.getContentAsByteArray()));
|
||||
response.copyBodyToResponse();
|
||||
}
|
||||
|
||||
/** 失败只返回固定原因,绝不把密钥或待签名的正文写入响应。 */
|
||||
private void reject(HttpServletResponse response, String message) throws IOException {
|
||||
response.setStatus(401);
|
||||
response.setContentType("application/json");
|
||||
response.getWriter().write("{\"message\":\"" + message + "\"}");
|
||||
}
|
||||
|
||||
/**
|
||||
* 每次获取输入流时复用已认证正文,业务层解析的数据与签名校验的数据一致。
|
||||
* 内部控制接口采用同步 JSON 读取,不支持非阻塞流监听。
|
||||
*/
|
||||
private HttpServletRequest replayable(HttpServletRequest request, byte[] body) {
|
||||
return new HttpServletRequestWrapper(request) {
|
||||
@Override public ServletInputStream getInputStream() {
|
||||
ByteArrayInputStream input = new ByteArrayInputStream(body);
|
||||
return new ServletInputStream() {
|
||||
public int read() { return input.read(); }
|
||||
public boolean isFinished() { return input.available() == 0; }
|
||||
public boolean isReady() { return true; }
|
||||
public void setReadListener(ReadListener listener) { throw new UnsupportedOperationException(); }
|
||||
};
|
||||
}
|
||||
@Override public BufferedReader getReader() {
|
||||
return new BufferedReader(new InputStreamReader(getInputStream(), StandardCharsets.UTF_8));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.xtrh.communication.security;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/**
|
||||
* 服务请求与响应的签名规则,必须与 PXHJ 后端保持一致。
|
||||
* 请求和响应使用不同前缀,避免把某一方向的签名直接复用到另一方向。
|
||||
* 正文只取字节摘要参与签名,不会改变被传输的数据。
|
||||
*/
|
||||
public final class Signatures {
|
||||
private Signatures() {}
|
||||
|
||||
/** 空正文也计算摘要,使 GET 与有正文的请求遵循同一套规则。 */
|
||||
public static String digest(byte[] bytes) {
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 每次创建独立 Mac,避免多个心跳线程并发使用非线程安全的算法实例。
|
||||
* 密钥只存在于进程私有配置中,HTTP 头仅发送计算结果。
|
||||
*/
|
||||
private static String hmac(String token, String canonical) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(token.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
return HexFormat.of().formatHex(mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** 字段之间以换行分隔,双方按照相同顺序生成待签名内容。 */
|
||||
public static String request(String token, String method, String path, String time, String nonce, byte[] body) {
|
||||
return hmac(token, "request\n" + method + "\n" + path + "\n" + time + "\n" + nonce + "\n" + digest(body));
|
||||
}
|
||||
|
||||
/** 响应绑定原请求的随机数、状态码和正文,错误响应不能冒充成功响应。 */
|
||||
public static String response(String token, String nonce, int status, byte[] body) {
|
||||
return hmac(token, "response\n" + nonce + "\n" + status + "\n" + digest(body));
|
||||
}
|
||||
|
||||
/** 使用固定时间比较原语,避免直接字符串比较泄露匹配前缀信息。 */
|
||||
public static boolean equal(String expected, String actual) {
|
||||
return actual != null && MessageDigest.isEqual(expected.getBytes(StandardCharsets.US_ASCII), actual.getBytes(StandardCharsets.US_ASCII));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.xtrh.console.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.xtrh.console.service.ConsoleCollectionStore;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/** 签名服务入口仅更新内存查看快照,与总控任务、路由和节点许可解耦。 */
|
||||
@RestController
|
||||
@ConditionalOnProperty(name = "fusion.role", havingValue = "coordinator", matchIfMissing = true)
|
||||
public class ConsoleCollectionController {
|
||||
private final ConsoleCollectionStore collection;
|
||||
|
||||
public ConsoleCollectionController(ConsoleCollectionStore collection) { this.collection = collection; }
|
||||
|
||||
@PostMapping("/control/collection/sync")
|
||||
public Object sync(@RequestBody JsonNode input) { return collection.sync(input); }
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.xtrh.console.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.xtrh.console.service.ConsoleCollectionStore;
|
||||
import com.xtrh.control.service.CoordinatorService;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import static com.xtrh.common.util.Jsons.object;
|
||||
|
||||
/** 原生控制台仅查看状态,不能创建任务、修改容量或操作采集设备。 */
|
||||
@Controller
|
||||
@ConditionalOnExpression("'${fusion.role:coordinator}' == 'coordinator' && ${fusion.console-enabled:true}")
|
||||
public class ConsoleController {
|
||||
private final ConsoleCollectionStore collection;
|
||||
private final CoordinatorService coordinator;
|
||||
|
||||
public ConsoleController(ConsoleCollectionStore collection, CoordinatorService coordinator) {
|
||||
this.collection = collection;
|
||||
this.coordinator = coordinator;
|
||||
}
|
||||
|
||||
@GetMapping("/console") public String redirect() { return "redirect:/console/"; }
|
||||
@GetMapping("/console/") public String index() { return "forward:/console/index.html"; }
|
||||
|
||||
@ResponseBody
|
||||
@GetMapping("/console/api/snapshot")
|
||||
public ObjectNode snapshot() {
|
||||
ObjectNode result = object().put("serverTime", System.currentTimeMillis());
|
||||
result.set("collection", collection.snapshot());
|
||||
ArrayNode nodes = result.putArray("nodes");
|
||||
for (JsonNode source : coordinator.snapshot().path("nodes")) {
|
||||
ObjectNode node = object();
|
||||
for (String field : new String[]{"nodeId", "name", "nodeRole", "online", "lastHeartbeat"})
|
||||
if (source.has(field)) node.set(field, source.path(field).deepCopy());
|
||||
// 旧节点尚未上报资源遥测;在线心跳不能推算 CPU、内存或网络利用率。
|
||||
node.putNull("cpu").putNull("memory").putNull("network");
|
||||
nodes.add(node);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.xtrh.console.security;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.net.URI;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** 本机只读查看入口不接受跨站请求或可用于 DNS 重绑定的任意 Host。 */
|
||||
public final class ConsoleRequestPolicy {
|
||||
private static final Pattern HOST = Pattern.compile("(?i)(localhost|127\\.0\\.0\\.1|\\[::1\\])(?::([0-9]{1,5}))?");
|
||||
private ConsoleRequestPolicy() {}
|
||||
|
||||
public static boolean localRead(HttpServletRequest request) {
|
||||
if (!Set.of("GET", "HEAD").contains(request.getMethod())) return false;
|
||||
if (!Set.of("127.0.0.1", "::1", "0:0:0:0:0:0:0:1").contains(request.getRemoteAddr())) return false;
|
||||
String host = request.getHeader("Host");
|
||||
if (host == null) return false;
|
||||
Matcher matcher = HOST.matcher(host);
|
||||
if (!matcher.matches()) return false;
|
||||
int port = matcher.group(2) == null ? (request.isSecure() ? 443 : 80) : Integer.parseInt(matcher.group(2));
|
||||
if (port < 1 || port > 65535 || port != request.getLocalPort()) return false;
|
||||
if ("cross-site".equals(request.getHeader("Sec-Fetch-Site"))) return false;
|
||||
String origin = request.getHeader("Origin");
|
||||
if (origin == null) return true;
|
||||
try {
|
||||
URI uri = URI.create(origin);
|
||||
return uri.getScheme().equals(request.getScheme()) && uri.getRawAuthority() != null
|
||||
&& uri.getRawAuthority().equalsIgnoreCase(host) && uri.getRawUserInfo() == null
|
||||
&& (uri.getRawPath() == null || uri.getRawPath().isEmpty())
|
||||
&& uri.getRawQuery() == null && uri.getRawFragment() == null;
|
||||
} catch (IllegalArgumentException | NullPointerException failure) { return false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.xtrh.console.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.function.LongSupplier;
|
||||
|
||||
import static com.xtrh.common.util.Jsons.*;
|
||||
|
||||
/**
|
||||
* 接收 PXHJ 已解析的只读采集快照,与任务调度、许可和 H2 状态完全分开。
|
||||
* 只保留白名单标量;模拟数据、凭证及媒体许可不会进入浏览器数据集合。
|
||||
*/
|
||||
@Service
|
||||
@ConditionalOnProperty(name = "fusion.role", havingValue = "coordinator", matchIfMissing = true)
|
||||
public class ConsoleCollectionStore {
|
||||
private static final int MAX_BYTES = 1_500_000;
|
||||
private static final long STALE_MS = 15_000;
|
||||
private static final Set<String> QUALITIES = Set.of("GOOD", "VALID", "STALE", "MISSING", "AMBIGUOUS",
|
||||
"INVALID_TIME", "INVALID_VALUE", "WAITING", "OFFLINE", "UNKNOWN", "ERROR", "UNAVAILABLE");
|
||||
private final ObjectMapper mapper;
|
||||
private final LongSupplier clock;
|
||||
private ArrayNode contexts = array();
|
||||
private long observedAt;
|
||||
private long lastSyncedAt;
|
||||
|
||||
@Autowired
|
||||
public ConsoleCollectionStore(ObjectMapper mapper) { this(mapper, System::currentTimeMillis); }
|
||||
|
||||
public ConsoleCollectionStore(ObjectMapper mapper, LongSupplier clock) {
|
||||
this.mapper = mapper;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/** 整体校验成功后原子替换;失败与迟到快照不会破坏上次有效数据。 */
|
||||
public synchronized ObjectNode sync(JsonNode input) {
|
||||
require(input != null && input.isObject(), "Invalid collection snapshot");
|
||||
require("PXHJ".equals(text(input, "source", 16, true)), "Invalid collection source");
|
||||
require(!simulated(input), "Simulated collection is not accepted");
|
||||
try { require(mapper.writeValueAsBytes(input).length <= MAX_BYTES, "Collection snapshot too large"); }
|
||||
catch (java.io.IOException failure) { throw new IllegalArgumentException("Invalid collection snapshot"); }
|
||||
long received = clock.getAsLong();
|
||||
long observed = timestamp(input, "observedAt", true);
|
||||
require(observed <= received + 60_000, "Collection time is in the future");
|
||||
require(observed >= observedAt, "Outdated collection snapshot");
|
||||
JsonNode sourceContexts = boundedArray(input, "contexts", 32);
|
||||
ArrayNode accepted = array();
|
||||
int equipmentCount = 0, itemCount = 0;
|
||||
Set<String> contextIds = new HashSet<>();
|
||||
for (JsonNode context : sourceContexts) {
|
||||
require(context.isObject(), "Invalid context");
|
||||
String contextId = text(context, "id", 200, true);
|
||||
require(contextIds.add(contextId), "Duplicate collection context");
|
||||
ObjectNode copy = object().put("id", contextId).put("name", text(context, "name", 200, false))
|
||||
.put("roundId", text(context, "roundId", 200, false));
|
||||
ArrayNode equipment = copy.putArray("equipment");
|
||||
Set<String> equipmentIds = new HashSet<>();
|
||||
for (JsonNode row : boundedArray(context, "equipment", 128)) {
|
||||
require(row.isObject() && ++equipmentCount <= 512, "Too many collection equipment");
|
||||
String id = text(row, "id", 200, true);
|
||||
require(equipmentIds.add(id), "Duplicate collection equipment");
|
||||
if (simulated(row)) continue;
|
||||
ObjectNode target = object().put("id", id)
|
||||
.put("participantCode", text(row, "participantCode", 200, false))
|
||||
.put("code", text(row, "code", 200, false)).put("name", text(row, "name", 200, false))
|
||||
.put("type", text(row, "type", 200, false)).put("state", text(row, "state", 64, false));
|
||||
nullableTime(target, row, "lastReceivedAt");
|
||||
ArrayNode items = target.putArray("items");
|
||||
Set<String> keys = new HashSet<>();
|
||||
for (JsonNode item : boundedArray(row, "items", 256)) {
|
||||
require(item.isObject() && ++itemCount <= 4096, "Too many collection items");
|
||||
String key = text(item, "key", 200, true);
|
||||
require(keys.add(key), "Duplicate collection item");
|
||||
if (simulated(item) || sensitive(key)) continue;
|
||||
ObjectNode value = object().put("key", key).put("label", text(item, "label", 200, false))
|
||||
.put("type", text(item, "type", 64, false)).put("unit", text(item, "unit", 32, false))
|
||||
.put("sourceName", text(item, "sourceName", 200, false))
|
||||
.put("sourceType", text(item, "sourceType", 64, false));
|
||||
String quality = text(item, "quality", 64, false).toUpperCase(Locale.ROOT);
|
||||
value.put("quality", QUALITIES.contains(quality) ? quality : "UNKNOWN");
|
||||
JsonNode sample = item.get("value");
|
||||
require(sample == null || sample.isNull() || sample.isNumber() || sample.isTextual() || sample.isBoolean(), "Collection values must be scalar");
|
||||
require(sample == null || !sample.isTextual() || sample.textValue().length() <= 4096, "Collection value too long");
|
||||
require(sample == null || !sample.isFloatingPointNumber() || Double.isFinite(sample.doubleValue()), "Invalid collection number");
|
||||
if (sample == null || sample.isNull()) value.putNull("value"); else value.set("value", sample.deepCopy());
|
||||
nullableTime(value, item, "receivedAt");
|
||||
nullableTime(value, item, "sampleTime");
|
||||
items.add(value);
|
||||
}
|
||||
equipment.add(target);
|
||||
}
|
||||
accepted.add(copy);
|
||||
}
|
||||
contexts = accepted;
|
||||
observedAt = observed;
|
||||
lastSyncedAt = received;
|
||||
return object().put("accepted", true).put("lastSyncedAt", lastSyncedAt).put("observedAt", observedAt);
|
||||
}
|
||||
|
||||
/** 失联后保留最后值并标记过期,不以空值或假在线状态覆盖真实采集记录。 */
|
||||
public synchronized ObjectNode snapshot() {
|
||||
long now = clock.getAsLong();
|
||||
String state = lastSyncedAt == 0 ? "WAITING"
|
||||
: now - lastSyncedAt > STALE_MS || now - observedAt > STALE_MS ? "STALE" : "CONNECTED";
|
||||
ObjectNode out = object().put("state", state);
|
||||
if (lastSyncedAt == 0) out.putNull("lastSyncedAt").putNull("observedAt");
|
||||
else out.put("lastSyncedAt", lastSyncedAt).put("observedAt", observedAt);
|
||||
out.set("contexts", contexts.deepCopy());
|
||||
return out;
|
||||
}
|
||||
|
||||
private static JsonNode boundedArray(JsonNode node, String key, int limit) {
|
||||
JsonNode value = node.path(key);
|
||||
require(value.isArray() && value.size() <= limit, "Invalid or excessive " + key);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String key, int limit, boolean required) {
|
||||
JsonNode value = node.get(key);
|
||||
require(value == null || value.isNull() || value.isTextual(), "Invalid " + key);
|
||||
String result = value == null || value.isNull() ? "" : value.textValue().trim();
|
||||
require(result.length() <= limit && (!required || !result.isEmpty()), "Invalid " + key);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static long timestamp(JsonNode node, String key, boolean required) {
|
||||
JsonNode value = node.get(key);
|
||||
if (value == null || value.isNull()) { require(!required, "Missing " + key); return 0; }
|
||||
require(value.isIntegralNumber() && value.canConvertToLong() && value.longValue() > 0, "Invalid " + key);
|
||||
return value.longValue();
|
||||
}
|
||||
|
||||
private static void nullableTime(ObjectNode target, JsonNode source, String key) {
|
||||
long value = timestamp(source, key, false);
|
||||
if (value == 0) target.putNull(key); else target.put(key, value);
|
||||
}
|
||||
|
||||
private static boolean simulated(JsonNode row) {
|
||||
if (row.path("simulated").asBoolean(false)) return true;
|
||||
for (String key : Set.of("quality", "sourceName", "sourceType", "state")) {
|
||||
String value = row.path(key).asText("").toUpperCase(Locale.ROOT);
|
||||
if (value.contains("SIMULAT") || value.contains("DEMO") || value.contains("模拟") || value.contains("演示")) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean sensitive(String key) {
|
||||
return key.toLowerCase(Locale.ROOT).matches(".*(password|passwd|secret|credential|token|mediakey|privatekey|sm4key|hmackey|sessionid|bootid).*");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.xtrh.control.controller;
|
||||
|
||||
import com.xtrh.control.service.CoordinatorService;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
/**
|
||||
* 总控 HTTP 入口:只接收参数和返回结果,调度与持久化由服务层处理。
|
||||
* 内部接口认证统一交给服务签名过滤器,避免各入口出现不同认证规则。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/control")
|
||||
@ConditionalOnProperty(name="fusion.role", havingValue="coordinator", matchIfMissing=true)
|
||||
public class CoordinatorController {
|
||||
private final CoordinatorService service;
|
||||
public CoordinatorController(CoordinatorService service){this.service=service;}
|
||||
@GetMapping("/info") public Object info(){return service.info();}
|
||||
@GetMapping("/snapshot") public Object snapshot(){return service.snapshot();}
|
||||
@PostMapping("/nodes/register") public Object register(@RequestBody JsonNode input){return service.register(input);}
|
||||
@PostMapping("/nodes/{id}/heartbeat") public Object heartbeat(@PathVariable String id,@RequestBody JsonNode input){return service.heartbeat(id,input);}
|
||||
@PatchMapping("/nodes/{id}/capacity") public Object capacity(@PathVariable String id,@RequestBody JsonNode input){return service.capacity(id,input);}
|
||||
// 试验和轮次状态以 PXHJ 保存的数据为准,浏览器不直接访问总控接口。
|
||||
@PostMapping("/contexts/sync") public Object context(@RequestBody JsonNode input){return service.context(input);}
|
||||
// 原图接入不依赖试验启动;密钥只经过内部签名接口进入短期内存许可。
|
||||
@PostMapping("/image-sources/register") public Object imageSource(@RequestBody JsonNode input){return service.imageSource(input);}
|
||||
@PostMapping("/image-sources/resolve") public Object imageRoutes(@RequestBody JsonNode input){return service.imageRoutes(input);}
|
||||
@PutMapping("/routes") public Object routes(@RequestBody JsonNode input){return service.routes(input);}
|
||||
@PostMapping("/gateways/heartbeat") public Object gateway(@RequestBody JsonNode input){return service.gateway(input);}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
package com.xtrh.control.service;
|
||||
|
||||
import com.xtrh.common.util.Jsons;
|
||||
import com.xtrh.common.config.Settings;
|
||||
import com.xtrh.common.dao.StateStore;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.*;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.function.LongSupplier;
|
||||
import static com.xtrh.common.util.Jsons.*;
|
||||
|
||||
/**
|
||||
* 总控业务服务:根据 PXHJ 的正式试验状态、节点许可和配置路数组织任务。
|
||||
* 所有状态操作在同一把锁内执行,保证两个并发心跳不会重复占用同一个空位。
|
||||
* controller 不决定分配结果;DAO 只负责完整状态的保存和读取。
|
||||
*/
|
||||
@Service
|
||||
@ConditionalOnProperty(name="fusion.role", havingValue="coordinator", matchIfMissing=true)
|
||||
public class CoordinatorService {
|
||||
private final StateStore store;
|
||||
private final ObjectNode state;
|
||||
// 展示时间与授权计时分开:墙上时钟用于日志,单调时钟用于判断节点是否失联。
|
||||
private final LongSupplier clock;
|
||||
private final LongSupplier leaseClock;
|
||||
private final Map<String,Long> leaseRefresh=new HashMap<>();
|
||||
private final long leaseMs;
|
||||
private final String cluster;
|
||||
// 来源许可与试验快照隔离,采集器密钥不会写入 StateStore 或公开节点列表。
|
||||
private final ImageSourceRegistry imageSources = new ImageSourceRegistry();
|
||||
// 保存失败后停止继续派发,避免内存中的新授权与磁盘中的旧状态发生分歧。
|
||||
private boolean storageHealthy = true;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
public CoordinatorService(Settings settings, ObjectMapper mapper) throws Exception {
|
||||
this(StateStore.open(settings.directory.resolve("coordinator"), mapper),
|
||||
System::currentTimeMillis, ()->System.nanoTime()/1_000_000, settings.leaseMs, settings.cluster);
|
||||
state.put("serviceId",settings.id);persist();
|
||||
}
|
||||
|
||||
/** 测试可以提供可控时钟;实际部署使用系统单调时钟,不依赖设备报来的时间。 */
|
||||
CoordinatorService(StateStore store, LongSupplier clock, long leaseMs, String cluster) throws Exception {
|
||||
this(store,clock,clock,leaseMs,cluster);
|
||||
}
|
||||
CoordinatorService(StateStore store,LongSupplier clock,LongSupplier leaseClock,long leaseMs,String cluster) throws Exception {
|
||||
this.store=store; this.clock=clock;this.leaseClock=leaseClock; this.leaseMs=leaseMs; this.cluster=cluster;
|
||||
state=store.load();
|
||||
// 五类业务状态共同保存为原子快照,恢复时先补齐首次部署缺失的集合。
|
||||
for(String key:List.of("nodes","contexts","tasks","gateways","routes")) if(!state.path(key).isObject()) state.putObject(key);
|
||||
// 重启后提升总控代次并撤销旧授权,等 PXHJ 重新确认正式试验后再派发,防止复活已结束任务。
|
||||
state.put("epoch", state.path("epoch").asLong()+1);
|
||||
if(!state.hasNonNull("serviceId"))state.put("serviceId",UUID.randomUUID().toString());
|
||||
if(!state.has("routesConfirmed"))state.put("routesConfirmed",state.has("routeVersion"));
|
||||
// 保留节点容量和身份,重新生成会话,让重启前迟到的准备回执无法重新获得授权。
|
||||
for(ObjectNode n:rows(state,"nodes")) n.put("lastHeartbeat",0).put("sessionId",UUID.randomUUID().toString());
|
||||
for(ObjectNode t:rows(state,"tasks")) {t.putNull("active");t.putNull("candidate");t.put("reason","RECONCILING");}
|
||||
// 原磁盘记录只说明曾经运行过;没有 PXHJ 的当前确认不能推断试验仍在进行。
|
||||
for(ObjectNode c:rows(state,"contexts")) c.put("confirmed",false);
|
||||
// 原图是短期接入任务;重启后等下一次认证协商重新创建,避免遗留接收槽位。
|
||||
for(ObjectNode t:rows(state,"tasks"))if(original(t))t.put("desired","STOPPED");
|
||||
for(ObjectNode c:rows(state,"contexts"))if(c.path("kind").asText().equals("ORIGINAL_IMAGE"))map("contexts").remove(c.path("trialId").asText());
|
||||
for(ObjectNode g:rows(state,"gateways")) g.put("lastHeartbeat",0);
|
||||
persist();
|
||||
}
|
||||
|
||||
private long now(){return clock.getAsLong();}
|
||||
private ObjectNode map(String key){return (ObjectNode)state.path(key);}
|
||||
private ObjectNode node(String id){var n=map("nodes").get(id);if(n==null)throw new IllegalArgumentException("Unknown node");return (ObjectNode)n;}
|
||||
// 授权按单调时钟到期;系统校时只影响展示时间,不延长失联节点的许可。
|
||||
private boolean live(ObjectNode n){Long last=leaseRefresh.get(n.path("nodeId").asText());long age=last==null?Long.MAX_VALUE:leaseClock.getAsLong()-last;return age>=0&&age<leaseMs;}
|
||||
/** 许可同时绑定节点身份和本次启动会话,节点重新启动后旧任务立即失效。 */
|
||||
private boolean valid(ObjectNode assignment){
|
||||
if(assignment==null)return false;
|
||||
var n=map("nodes").get(assignment.path("nodeId").asText());
|
||||
return n!=null&&live((ObjectNode)n)&&n.path("sessionId").asText().equals(assignment.path("sessionId").asText());
|
||||
}
|
||||
private ObjectNode assignment(ObjectNode task,String key){return task.path(key).isObject()?(ObjectNode)task.path(key):null;}
|
||||
private void persist(){
|
||||
if(!storageHealthy)throw new IllegalStateException("CoordinatorService persistence unavailable");
|
||||
// 修订号用于 PXHJ 拒绝迟到快照,同一总控代次中只能向更新的状态推进。
|
||||
state.put("revision",state.path("revision").asLong()+1);
|
||||
try{store.save(state);}catch(RuntimeException e){storageHealthy=false;throw e;}
|
||||
}
|
||||
|
||||
/** 发现阶段的身份凭据:客户端验证响应签名后,再比较集群与稳定服务身份。 */
|
||||
public synchronized ObjectNode info(){return object().put("role","coordinator").put("clusterId",cluster).put("serviceId",state.path("serviceId").asText()).put("epoch",state.path("epoch").asLong()).put("storageHealthy",storageHealthy);}
|
||||
|
||||
/**
|
||||
* 自动注册复用持久化节点身份;本次启动号变化时更新会话。
|
||||
* 已经由 PXHJ 调整过的容量优先,重新注册不能用安装默认值覆盖管理员配置。
|
||||
*/
|
||||
public synchronized ObjectNode register(JsonNode input){
|
||||
require(cluster.equals(required(input,"clusterId")),"Cluster mismatch");
|
||||
String id=required(input,"nodeId"),boot=required(input,"bootId"),url=baseUrl(required(input,"baseUrl"));
|
||||
require(id.matches("[a-zA-Z0-9_-]{8,64}"),"Invalid node identity");
|
||||
String nodeRole=input.path("nodeRole").asText("WORKER");
|
||||
require(Set.of("COORDINATOR","WORKER").contains(nodeRole),"Invalid execution node role");
|
||||
// 主执行行复用总控的稳定身份,普通子节点不能占用它或自称另一个主节点。
|
||||
require(nodeRole.equals("COORDINATOR")==id.equals(state.path("serviceId").asText()),"Coordinator worker identity mismatch");
|
||||
int suggested=input.path("capacity").asInt(2);
|
||||
require(suggested>=0&&suggested<=64,"Invalid capacity");
|
||||
ObjectNode n=map("nodes").has(id)?node(id):object().put("nodeId",id).put("capacity",suggested).put("enabled",true);
|
||||
// 注册可重复调用;同一启动号沿用会话,避免网络重试生成重复节点或打断在途任务。
|
||||
if(!boot.equals(n.path("bootId").asText())) n.put("sessionId",UUID.randomUUID().toString());
|
||||
n.put("bootId",boot).put("name",required(input,"name")).put("nodeRole",nodeRole).put("baseUrl",url).put("lastHeartbeat",now());
|
||||
// 旧版本节点仍可执行演示任务,只有明确上报有效图片入口的节点才能接原图。
|
||||
int imagePort=input.path("imageInputPort").asInt(0);
|
||||
String imageHost=input.path("imageHost").asText("");
|
||||
require(imagePort==0||(imagePort>0&&imagePort<=65535&&ImageSourceRegistry.ipv4(imageHost)),"Invalid node image input");
|
||||
n.put("imageInputPort",imagePort).put("imageHost",imageHost);
|
||||
map("nodes").set(id,n);leaseRefresh.put(id,leaseClock.getAsLong());schedule();persist();
|
||||
return object().put("nodeId",id).put("sessionId",n.path("sessionId").asText()).put("epoch",state.path("epoch").asLong()).put("leaseMs",leaseMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 心跳既续期节点许可,也提交候选任务的准备结果。
|
||||
* 回复仅包含当前节点、当前会话仍有效的任务,节点以此撤销不再属于自己的任务。
|
||||
*/
|
||||
public synchronized ObjectNode heartbeat(String id,JsonNode input){
|
||||
ObjectNode n=node(id);
|
||||
if(!required(input,"sessionId").equals(n.path("sessionId").asText())||!required(input,"bootId").equals(n.path("bootId").asText()))
|
||||
throw new IllegalStateException("Node session superseded; register again");
|
||||
n.put("lastHeartbeat",now());leaseRefresh.put(id,leaseClock.getAsLong());schedule();
|
||||
// 先移除失效分配,再检查回执;旧节点的迟到结果不能覆盖迁移后的新版本。
|
||||
for(JsonNode report:input.path("reports")){
|
||||
var entry=map("tasks").get(report.path("taskId").asText());if(entry==null)continue;
|
||||
ObjectNode t=(ObjectNode)entry,candidate=assignment(t,"candidate");
|
||||
// 原图首帧状态属于具体分配版本;旧节点的迟到图片不能宣布新版本就绪。
|
||||
if(original(t))for(String key:List.of("active","candidate")){
|
||||
ObjectNode a=assignment(t,key);
|
||||
if(a!=null&&valid(a)&&a.path("nodeId").asText().equals(id)&&a.path("version").asLong()==report.path("version").asLong()){
|
||||
a.put("imageReady",report.path("imageReady").asBoolean());
|
||||
a.put("lastFrameTime",report.path("lastFrameTime").asLong());
|
||||
}
|
||||
}
|
||||
if(t.path("desired").asText().equals("STOPPED")||candidate==null||!candidate.path("nodeId").asText().equals(id)
|
||||
||candidate.path("version").asLong()!=report.path("version").asLong()||!valid(candidate))continue;
|
||||
// 新节点已经生成可播放画面后才切换 active;准备期间旧节点继续承担播放。
|
||||
if(report.path("ready").asBoolean()){
|
||||
candidate.put("ready",true);
|
||||
// 首次接入先开放上传地址;迁移则继续双发,收到新节点首帧后才切换 PXHJ 取图。
|
||||
if(!original(t)||assignment(t,"active")==null||report.path("imageReady").asBoolean()){
|
||||
candidate.put("activatedAt",now());t.set("active",candidate.deepCopy());t.putNull("candidate");t.put("reason","");
|
||||
}
|
||||
}else if(report.hasNonNull("error")){
|
||||
// 准备失败只撤销候选;旧 active 保留,冷却后重试,防止失败任务占住预留容量。
|
||||
t.putNull("candidate");t.put("reason","MEDIA_PREPARE_FAILED").put("lastFailure",now());
|
||||
}
|
||||
}
|
||||
schedule();persist();
|
||||
var result=object().put("leaseMs",leaseMs).put("epoch",state.path("epoch").asLong());var plans=result.putArray("tasks");
|
||||
// 迁移期间两个节点分别拿到运行和预热计划,完成接管后旧节点不再收到该版本。
|
||||
for(ObjectNode t:rows(state,"tasks"))for(String key:List.of("active","candidate")){
|
||||
ObjectNode a=assignment(t,key);if(a==null||!a.path("nodeId").asText().equals(id)||!valid(a))continue;
|
||||
ObjectNode plan=t.deepCopy();plan.remove(List.of("active","candidate"));plan.set("assignment",a.deepCopy());plan.put("preparing",key.equals("candidate"));plans.add(plan);
|
||||
// 密钥仅发送给当前有效的执行节点,不进入任务快照、持久化或浏览器 API。
|
||||
if(original(t))plan.set("imageAccess",imageSources.access(t.path("sourceEndpointId").asText()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 路数是管理员配置的最大并发任务数;当前阶段不根据 CPU/GPU 自动推算。 */
|
||||
public synchronized ObjectNode capacity(String id,JsonNode input){
|
||||
require(input.path("capacity").isIntegralNumber(),"Capacity must be an integer");int value=input.path("capacity").asInt();
|
||||
require(value>=0&&value<=64,"Capacity must be between 0 and 64");
|
||||
var n=node(id);n.put("capacity",value);if(input.has("enabled"))n.put("enabled",input.path("enabled").asBoolean());
|
||||
schedule();persist();return snapshot();
|
||||
}
|
||||
|
||||
/** 只接收通过签名认证的 PXHJ 后台提供的已保存试验与正式轮次状态。 */
|
||||
public synchronized ObjectNode context(JsonNode input){
|
||||
String trialId=required(input,"trialId"),roundId=required(input,"roundId"),name=required(input,"name");
|
||||
String phase=required(input,"roundStatus");require(Set.of("PENDING","RUNNING","SAVED").contains(phase),"Invalid round state");
|
||||
require(input.path("channels").isArray()&&input.path("channels").size()<=128,"Invalid channels");
|
||||
// 通道身份必须唯一,同一装备可以对应多路,但重复通道不能形成重复调度任务。
|
||||
var seen=new HashSet<String>();
|
||||
for(JsonNode channel:input.path("channels")){require(seen.add(required(channel,"channelId")),"Duplicate channel");required(channel,"equipmentId");required(channel,"name");}
|
||||
String revision=input.path("configurationVersion").asText("0");
|
||||
var c=map("contexts").has(trialId)?(ObjectNode)map("contexts").get(trialId):object();
|
||||
boolean enabled=input.path("enabled").asBoolean(true);
|
||||
c.put("trialId",trialId).put("roundId",roundId).put("name",name).put("roundStatus",phase).put("configurationVersion",revision)
|
||||
.put("enabled",enabled).put("confirmed",true).put("confirmedAt",now());
|
||||
c.set("channels",input.path("channels").deepCopy());c.set("bindings",input.path("bindings").deepCopy());map("contexts").set(trialId,c);
|
||||
Set<String> wanted=new HashSet<>();
|
||||
// 稳定任务号绑定试验、轮次和通道;同步重试复用任务,新一轮生成独立任务。
|
||||
if(enabled&&!phase.equals("SAVED"))for(JsonNode channel:input.path("channels")){
|
||||
String id=UUID.nameUUIDFromBytes((trialId+"/"+roundId+"/"+channel.path("channelId").asText()).getBytes(StandardCharsets.UTF_8)).toString();wanted.add(id);
|
||||
var t=map("tasks").has(id)?(ObjectNode)map("tasks").get(id):object().put("taskId",id).put("versionCounter",0).put("createdAt",now());
|
||||
t.put("trialId",trialId).put("roundId",roundId).put("channelId",channel.path("channelId").asText()).put("equipmentId",channel.path("equipmentId").asText())
|
||||
.put("name",channel.path("name").asText()).put("trialName",name).put("desired",phase.equals("RUNNING")?"RUNNING":"READY").put("mediaKind","DEMO_VIDEO");
|
||||
map("tasks").set(id,t);
|
||||
}
|
||||
// 正式结束、关闭功能或删除通道都会撤销旧任务;此处不触碰独立的采集网关路由。
|
||||
for(ObjectNode t:rows(state,"tasks"))if(t.path("trialId").asText().equals(trialId)&&!wanted.contains(t.path("taskId").asText())){
|
||||
t.put("desired","STOPPED");t.putNull("active");t.putNull("candidate");t.put("reason","");
|
||||
}
|
||||
schedule();persist();return snapshot();
|
||||
}
|
||||
|
||||
// 运行任务和预热任务都占用路数,迁移时不能把新节点的容量重复分给其他任务。
|
||||
private int load(String id){int count=0;for(ObjectNode t:rows(state,"tasks"))for(String key:List.of("active","candidate")){
|
||||
ObjectNode a=assignment(t,key);if(a!=null&&a.path("nodeId").asText().equals(id))count++;
|
||||
}return count;}
|
||||
/** 空位按已占用比例选择,容量不同的电脑可承担不同路数;迁移排除原节点。 */
|
||||
private ObjectNode available(String exclude,ObjectNode task){
|
||||
return rows(state,"nodes").stream().filter(n->live(n)&&n.path("enabled").asBoolean()&&!n.path("nodeId").asText().equals(exclude)
|
||||
&&load(n.path("nodeId").asText())<n.path("capacity").asInt()
|
||||
&&(!original(task)||(n.path("imageInputPort").asInt()>0&&ImageSourceRegistry.ipv4(n.path("imageHost").asText()))))
|
||||
.min(Comparator.comparingDouble((ObjectNode n)->(double)load(n.path("nodeId").asText())/Math.max(1,n.path("capacity").asInt()))
|
||||
.thenComparing(n->n.path("nodeId").asText())).orElse(null);
|
||||
}
|
||||
/**
|
||||
* 每次分配提升任务版本并生成新的媒体许可。
|
||||
* 候选准备完成之前不替换 active,因此 PXHJ 可以继续播放已就绪的旧地址。
|
||||
*/
|
||||
private void assign(ObjectNode t,ObjectNode n){
|
||||
long version=t.path("versionCounter").asLong()+1;t.put("versionCounter",version);
|
||||
t.set("candidate",object().put("nodeId",n.path("nodeId").asText()).put("sessionId",n.path("sessionId").asText())
|
||||
.put("version",version).put("mediaKey",UUID.randomUUID().toString()).put("assignedAt",now()));
|
||||
t.put("reason",assignment(t,"active")==null?"PREPARING":"MIGRATING");
|
||||
}
|
||||
/**
|
||||
* 调度顺序:撤销失效许可、处理容量缩减,再为等待任务寻找空位。
|
||||
* 同一次调度把所有候选预热任务计入容量,避免并发抢占和超发。
|
||||
*/
|
||||
private void schedule(){
|
||||
expireImageSources();
|
||||
// 同等条件下先处理较早创建的任务,让容量不足时的等待顺序可预测。
|
||||
List<ObjectNode> tasks=rows(state,"tasks");tasks.sort(Comparator.comparingLong(t->t.path("createdAt").asLong()));
|
||||
for(ObjectNode t:tasks){
|
||||
var context=map("contexts").get(t.path("trialId").asText());
|
||||
if(t.path("desired").asText().equals("STOPPED")||context==null||!context.path("confirmed").asBoolean()){t.putNull("active");t.putNull("candidate");continue;}
|
||||
for(String key:List.of("active","candidate")){ObjectNode a=assignment(t,key);if(a!=null&&!valid(a)){t.putNull(key);t.put("reason","NODE_OFFLINE");}}
|
||||
ObjectNode candidate=assignment(t,"candidate");
|
||||
// 预热超时释放预留槽位,已有输出仍然保留;错误状态向 PXHJ 汇总展示。
|
||||
if(candidate!=null&&now()-candidate.path("assignedAt").asLong()>30000){t.putNull("candidate");t.put("reason","PREPARE_TIMEOUT").put("lastFailure",now());}
|
||||
}
|
||||
for(ObjectNode n:rows(state,"nodes")){
|
||||
String id=n.path("nodeId").asText();int effective=n.path("enabled").asBoolean()?n.path("capacity").asInt():0;
|
||||
int active=(int)tasks.stream().filter(t->t.path("active").path("nodeId").asText().equals(id)).count();
|
||||
var incoming=tasks.stream().filter(t->t.path("candidate").path("nodeId").asText().equals(id)).toList();
|
||||
// 管理员减少容量后先撤销多余的预热任务,再逐步迁出正在播放的任务。
|
||||
for(int i=Math.max(0,effective-active);i<incoming.size();i++){incoming.get(i).putNull("candidate");incoming.get(i).put("reason","CAPACITY_CHANGED");}
|
||||
var owned=tasks.stream().filter(t->t.path("active").path("nodeId").asText().equals(id)).toList();
|
||||
// 降低路数时先寻找接管节点;集群没有空位则标记调整中,保留现有视频直到能迁出。
|
||||
int surplus=Math.max(0,owned.size()-effective);
|
||||
for(int i=owned.size()-1;i>=0&&surplus>0;i--,surplus--){var t=owned.get(i);if(assignment(t,"candidate")!=null)continue;
|
||||
ObjectNode target=available(id,t);if(target==null)t.put("reason","CAPACITY_WAIT_KEEP_RUNNING");else assign(t,target);
|
||||
}
|
||||
}
|
||||
// 没有 active/candidate 的任务才参与新分配;容量不足保持排队,不强行一机一路。
|
||||
for(ObjectNode t:tasks)if(!t.path("desired").asText().equals("STOPPED")&&assignment(t,"active")==null&&assignment(t,"candidate")==null){
|
||||
var c=map("contexts").get(t.path("trialId").asText());if(c==null||!c.path("confirmed").asBoolean())continue;
|
||||
if(now()-t.path("lastFailure").asLong()>3000){ObjectNode target=available(null,t);if(target==null)t.put("reason","CAPACITY_WAIT");else assign(t,target);}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean original(JsonNode task){return task.path("mediaKind").asText().equals("ORIGINAL_IMAGE");}
|
||||
private static String imageTaskId(String endpoint){return UUID.nameUUIDFromBytes(("original-image/"+endpoint).getBytes(StandardCharsets.UTF_8)).toString();}
|
||||
|
||||
/** 采集器在线时原图随时可接入,不以正式轮次启动作为试验准备取图的前提。 */
|
||||
public synchronized ObjectNode imageSource(JsonNode input){
|
||||
expireImageSources();
|
||||
String endpoint=required(input,"endpointId"),name=required(input,"name");
|
||||
ObjectNode oldAccess=imageSources.access(endpoint);
|
||||
imageSources.register(input,leaseClock.getAsLong());
|
||||
ObjectNode access=imageSources.access(endpoint);
|
||||
String contextId="collector-image:"+endpoint,id=imageTaskId(endpoint);
|
||||
map("contexts").set(contextId,object().put("kind","ORIGINAL_IMAGE").put("trialId",contextId)
|
||||
.put("roundId","standby").put("name","采集器原图接入").put("roundStatus","PENDING").put("confirmed",true));
|
||||
ObjectNode t=map("tasks").has(id)?(ObjectNode)map("tasks").get(id):object().put("taskId",id).put("versionCounter",0).put("createdAt",now());
|
||||
// 原连接或密钥变化时撤销旧接收许可,再分配新版本,防止继续使用旧设备凭据。
|
||||
if(oldAccess!=null&&!oldAccess.equals(access)){t.putNull("active");t.putNull("candidate");}
|
||||
t.put("trialId",contextId).put("roundId","standby").put("channelId","original-image").put("equipmentId",endpoint)
|
||||
.put("name",name+"原图").put("trialName","试验准备原图").put("desired","READY").put("mediaKind","ORIGINAL_IMAGE")
|
||||
.put("sourceEndpointId",endpoint).put("sourceHost",access.path("sourceHost").asText()).put("collectorId",access.path("collectorId").asInt());
|
||||
map("tasks").set(id,t);schedule();persist();return imageRoute(t);
|
||||
}
|
||||
|
||||
/** PXHJ 在已有图片 API 后面查询有效接收节点,浏览器无需知道集群内部地址。 */
|
||||
public synchronized ObjectNode imageRoutes(JsonNode input){
|
||||
require(input.path("endpointIds").isArray()&&input.path("endpointIds").size()<=64,"Invalid image endpoints");
|
||||
schedule();ObjectNode result=object();ArrayNode routes=result.putArray("routes");
|
||||
Set<String> seen=new HashSet<>();
|
||||
for(JsonNode value:input.path("endpointIds")){
|
||||
String endpoint=value.asText();require(endpoint.matches("[0-9a-fA-F-]{36}"),"Invalid image endpoint");
|
||||
if(!seen.add(endpoint))continue;JsonNode entry=map("tasks").get(imageTaskId(endpoint));if(entry==null)continue;
|
||||
ObjectNode a=assignment((ObjectNode)entry,"active");if(!valid(a))continue;
|
||||
routes.add(object().put("endpointId",endpoint).put("taskId",entry.path("taskId").asText())
|
||||
.put("version",a.path("version").asLong()).put("nodeBaseUrl",node(a.path("nodeId").asText()).path("baseUrl").asText()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// 迁移期间最多发布两个地址;bulk 图片不经过网关,网关只运送短小的协商报文。
|
||||
private ObjectNode imageRoute(ObjectNode t){
|
||||
ObjectNode result=object().put("status","WAITING").put("coordinatorId",state.path("serviceId").asText())
|
||||
.put("epoch",state.path("epoch").asLong()).put("version",t.path("versionCounter").asLong()).put("leaseMs",8000);
|
||||
ArrayNode targets=result.putArray("targets");
|
||||
for(String key:List.of("active","candidate")){
|
||||
ObjectNode a=assignment(t,key);if(!valid(a)||!a.path("ready").asBoolean())continue;
|
||||
ObjectNode n=node(a.path("nodeId").asText());
|
||||
if(n.path("imageInputPort").asInt()>0&&ImageSourceRegistry.ipv4(n.path("imageHost").asText()))
|
||||
targets.add(object().put("host",n.path("imageHost").asText()).put("port",n.path("imageInputPort").asInt()));
|
||||
}
|
||||
if(!targets.isEmpty())result.put("status","READY");return result;
|
||||
}
|
||||
|
||||
/** 连续三十秒没有经过认证的协商就释放原图任务,独立试验和 UDP 路由保持原状。 */
|
||||
private void expireImageSources(){
|
||||
for(String endpoint:imageSources.expire(leaseClock.getAsLong())){
|
||||
// 保留不含密钥的版本计数,采集器恢复后不可能回到同一总控代次中的旧许可。
|
||||
JsonNode entry=map("tasks").get(imageTaskId(endpoint));
|
||||
if(entry instanceof ObjectNode task){task.put("desired","STOPPED");task.putNull("active");task.putNull("candidate");}
|
||||
map("contexts").remove("collector-image:"+endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 登记的是原始报文的来源与转发地址,总控不解析采集模块专有协议。
|
||||
* 稳定的中转源端口供 PXHJ 关联原连接,保留原采集器登记和原密钥。
|
||||
*/
|
||||
public synchronized ObjectNode routes(JsonNode input){
|
||||
require(input.path("routes").isArray()&&input.path("routes").size()<=255,"Invalid routes");
|
||||
var updated=object();Set<Integer> ports=new HashSet<>();Set<String> ids=new HashSet<>();List<JsonNode> approved=new ArrayList<>();
|
||||
for(JsonNode route:input.path("routes")){
|
||||
String id=required(route,"endpointId");required(route,"sourceHost");required(route,"targetHost");
|
||||
require(ids.add(id),"Duplicate endpoint identity");
|
||||
int source=route.path("sourcePort").asInt(),relay=route.path("relayPort").asInt(),target=route.path("targetPort").asInt();
|
||||
require(source>=0&&source<=65535&&relay>1024&&relay<=65535&&target>0&&target<=65535&&ports.add(relay),"Invalid or duplicate route ports");
|
||||
require(relay!=19002,"Relay port conflicts with the default gateway input");
|
||||
// 不允许把仍在使用的源端口换给另一采集器,否则旧回执可能发到错误设备。
|
||||
for(ObjectNode old:rows(state,"routes"))require(old.path("relayPort").asInt()!=relay||old.path("endpointId").asText().equals(id),"Relay port belongs to another endpoint; allocate a different port");
|
||||
// 来源端口为 0 表示该地址的任意端口,不能与同地址的另一登记同时匹配。
|
||||
for(JsonNode previous:approved)require(!previous.path("sourceHost").asText().equals(route.path("sourceHost").asText())
|
||||
||(source!=0&&previous.path("sourcePort").asInt()!=0&&source!=previous.path("sourcePort").asInt()),"Overlapping source mappings");
|
||||
approved.add(route);
|
||||
updated.set(id,route.deepCopy());
|
||||
}
|
||||
state.set("routes",updated);state.put("routeVersion",state.path("routeVersion").asLong()+1).put("routesConfirmed",true);persist();return snapshot();
|
||||
}
|
||||
|
||||
/** 网关上报实际 UDP 出口和统计;总控仅返回已由 PXHJ 确认的路由版本。 */
|
||||
public synchronized ObjectNode gateway(JsonNode input){
|
||||
require(cluster.equals(required(input,"clusterId")),"Cluster mismatch");String id=required(input,"gatewayId");
|
||||
var report=(ObjectNode)input.deepCopy();report.remove("clusterId");report.put("lastHeartbeat",now());map("gateways").set(id,report);
|
||||
var result=object().put("routeVersion",state.path("routeVersion").asLong()).put("routesConfirmed",state.path("routesConfirmed").asBoolean());result.set("routes",array().addAll(rows(state,"routes")));persist();return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* PXHJ 使用的业务快照,隐藏内部节点会话,提供当前任务状态及可用播放地址。
|
||||
* 地址由已注册节点和有效任务构造,不能直接相信节点自行提交的任意播放 URL。
|
||||
*/
|
||||
public synchronized ObjectNode snapshot(){
|
||||
ObjectNode result=object().put("clusterId",cluster).put("serverTime",now()).put("serviceId",state.path("serviceId").asText()).put("epoch",state.path("epoch").asLong()).put("revision",state.path("revision").asLong()).put("storageHealthy",storageHealthy);
|
||||
ArrayNode nodes=result.putArray("nodes"),tasks=result.putArray("tasks"),gateways=result.putArray("gateways");
|
||||
int capacity=0,active=0,queued=0;
|
||||
for(ObjectNode n:rows(state,"nodes")){
|
||||
ObjectNode copy=n.deepCopy();copy.remove(List.of("sessionId","bootId"));copy.put("online",live(n));
|
||||
// 兼容升级前的子节点记录;角色由稳定身份确认,前端无需猜测名称或端口。
|
||||
copy.put("nodeRole",n.path("nodeId").asText().equals(state.path("serviceId").asText())?"COORDINATOR":"WORKER");
|
||||
int used=0,reserved=0;for(ObjectNode t:rows(state,"tasks")){if(t.path("active").path("nodeId").asText().equals(n.path("nodeId").asText()))used++;if(t.path("candidate").path("nodeId").asText().equals(n.path("nodeId").asText()))reserved++;}
|
||||
copy.put("running",used).put("reserved",reserved).put("adjusting",used+reserved>(n.path("enabled").asBoolean()?n.path("capacity").asInt():0));nodes.add(copy);
|
||||
if(live(n)&&n.path("enabled").asBoolean())capacity+=n.path("capacity").asInt();
|
||||
}
|
||||
for(ObjectNode t:rows(state,"tasks")){
|
||||
if(original(t)&&t.path("desired").asText().equals("STOPPED"))continue;
|
||||
ObjectNode copy=t.deepCopy(),a=assignment(t,"active");copy.remove(List.of("active","candidate"));
|
||||
String status=t.path("desired").asText().equals("STOPPED")?"ENDED":assignment(t,"candidate")!=null?(a==null?"PREPARING":"MIGRATING")
|
||||
:a!=null?(t.path("desired").asText().equals("RUNNING")?"RUNNING":"READY"):"QUEUED";
|
||||
copy.put("status",status);
|
||||
// MIGRATING 状态也保留旧 active 的地址,只有接管成功才对外切换版本。
|
||||
if(a!=null&&valid(a)){
|
||||
String url=node(a.path("nodeId").asText()).path("baseUrl").asText()+"/media/"+t.path("taskId").asText()+"/"+a.path("version").asLong()+"/stream?key="+a.path("mediaKey").asText();
|
||||
copy.put("nodeId",a.path("nodeId").asText()).put("version",a.path("version").asLong())
|
||||
.put("playProtocol",original(t)?"MJPEG_ORIGINAL":"MJPEG_DEMO").put("playUrl",url);active++;
|
||||
if(original(t))copy.put("imageReady",a.path("imageReady").asBoolean()).put("lastFrameTime",a.path("lastFrameTime").asLong());
|
||||
}
|
||||
if(status.equals("QUEUED"))queued++;tasks.add(copy);
|
||||
}
|
||||
for(ObjectNode g:rows(state,"gateways")){var copy=g.deepCopy();copy.put("online",now()-g.path("lastHeartbeat").asLong()<leaseMs);gateways.add(copy);}
|
||||
result.set("routes",array().addAll(rows(state,"routes")));result.set("contexts",array().addAll(rows(state,"contexts")));
|
||||
result.set("summary",object().put("capacity",capacity).put("active",active).put("queued",queued));return result;
|
||||
}
|
||||
|
||||
/** 没有新心跳时也定期撤销到期许可,避免失联任务一直显示在线。 */
|
||||
@Scheduled(fixedDelay=1000) public synchronized void tick(){if(!storageHealthy)return;schedule();persist();}
|
||||
@PreDestroy public void close() throws Exception{store.close();}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.xtrh.control.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import java.util.*;
|
||||
import static com.xtrh.common.util.Jsons.*;
|
||||
|
||||
/**
|
||||
* 原图来源的短期许可:密钥只停留在内存中,不属于可持久化的试验状态。
|
||||
* 总控重启后必须由经过 PXHJ 认证的采集器重新协商,不能恢复旧上传授权。
|
||||
*/
|
||||
final class ImageSourceRegistry {
|
||||
// 由 CoordinatorService 的同步边界调用,注册、续期与回收不会与调度交叉修改。
|
||||
static final long SOURCE_LEASE_MS = 30_000;
|
||||
private final Map<String, Entry> entries = new HashMap<>();
|
||||
private record Entry(ObjectNode access, long refreshed) {}
|
||||
|
||||
/** 来源 IP 与采集器编号取自 PXHJ 保存的连接,浏览器不能自行指定密钥。 */
|
||||
String register(JsonNode input, long monotonic) {
|
||||
String endpoint = required(input,"endpointId");
|
||||
require(endpoint.matches("[0-9a-fA-F-]{36}") && UUID.fromString(endpoint).toString().equalsIgnoreCase(endpoint), "Invalid endpoint identity");
|
||||
String host = required(input,"sourceHost");
|
||||
require(ipv4(host), "An IPv4 image source is required");
|
||||
require(input.path("collectorId").isIntegralNumber()&&input.path("collectorId").canConvertToInt(), "Invalid collector identity");
|
||||
int collector = input.path("collectorId").asInt();
|
||||
require(collector > 0 && collector <= 255, "Invalid collector identity");
|
||||
String sm4 = required(input,"sm4Key"), hmac = required(input,"hmacKey");
|
||||
// 校验长度后重新编码,拒绝不完整密钥;异常消息始终不包含提交的密钥内容。
|
||||
try {
|
||||
byte[] a=Base64.getDecoder().decode(sm4), b=Base64.getDecoder().decode(hmac);
|
||||
require(a.length == 16 && b.length >= 32 && b.length <= 64, "Invalid collector key lengths");
|
||||
sm4=Base64.getEncoder().encodeToString(a);hmac=Base64.getEncoder().encodeToString(b);
|
||||
} catch (IllegalArgumentException ex) { throw new IllegalArgumentException("Invalid collector keys"); }
|
||||
// FND 的采集器编号只有一个字节,同时限制来源缓存数量,避免无限注册占用内存。
|
||||
require(entries.containsKey(endpoint) || entries.size() < 255, "Image source capacity exceeded");
|
||||
// Base64 仅用于 JSON 携带二进制密钥,传输身份校验仍由内部签名接口负责。
|
||||
ObjectNode access=object().put("endpointId",endpoint).put("sourceHost",host).put("collectorId",collector)
|
||||
.put("sm4Key",sm4).put("hmacKey",hmac);
|
||||
entries.put(endpoint,new Entry(access,monotonic));
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
/** 仅返回副本,避免生成节点计划时意外修改后续协商使用的凭据。 */
|
||||
ObjectNode access(String endpoint) {
|
||||
Entry e=entries.get(endpoint);return e==null?null:e.access.deepCopy();
|
||||
}
|
||||
|
||||
// 使用单调时钟回收失联来源,停止长期占用可配置的节点路数。
|
||||
Set<String> expire(long monotonic) {
|
||||
Set<String> expired=new HashSet<>();
|
||||
// 非法时钟倒退同样撤销许可,不能靠回退计时给旧上传目标延长寿命。
|
||||
entries.entrySet().removeIf(e->{long age=monotonic-e.getValue().refreshed;
|
||||
boolean old=age<0||age>=SOURCE_LEASE_MS;if(old)expired.add(e.getKey());return old;});
|
||||
return expired;
|
||||
}
|
||||
|
||||
/** 协商协议只发布数值 IPv4,避免把未验证域名变成采集器新的外联地址。 */
|
||||
static boolean ipv4(String value) {
|
||||
if(value==null)return false;String[] parts=value.split("\\.",-1);if(parts.length!=4)return false;
|
||||
for(String part:parts){if(!part.matches("0|[1-9][0-9]{0,2}"))return false;
|
||||
int n=Integer.parseInt(part);if(n>255)return false;}
|
||||
int first=Integer.parseInt(parts[0]);
|
||||
return first>0&&first<224&&!value.equals("255.255.255.255");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package com.xtrh.discovery.service;
|
||||
|
||||
import com.xtrh.common.config.Settings;
|
||||
import com.xtrh.common.util.Jsons;
|
||||
import com.xtrh.communication.client.PeerClient;
|
||||
import com.xtrh.discovery.util.NodeAddress;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 将配置、历史地址和 mDNS 线索转换为已认证的总控连接。
|
||||
* 与发现服务分开,避免未经认证的广播记录直接改变当前任务归属。
|
||||
* 重连间隔由调用方负责,本类只判断一次查找是否成功或存在冲突。
|
||||
* 磁盘缓存只保存地址,远端公开的逻辑身份用于当次验证和去重。
|
||||
*/
|
||||
@Component
|
||||
public class CoordinatorLocator {
|
||||
private final Settings settings;
|
||||
private final Discovery discovery;
|
||||
private final PeerClient peer;
|
||||
private volatile String connected = "";
|
||||
private volatile String status = "WAITING";
|
||||
|
||||
public CoordinatorLocator(Settings settings, Discovery discovery, PeerClient peer) {
|
||||
this.settings = settings;
|
||||
this.discovery = discovery;
|
||||
this.peer = peer;
|
||||
}
|
||||
|
||||
public synchronized String locate() throws Exception {
|
||||
// 主执行端只向自家总控注册;使用本机控制入口,不依赖总控监听自己的发现广播。
|
||||
if (settings.role.equals("coordinator")) {
|
||||
if (!connected.isEmpty()) return connected;
|
||||
String local = NodeAddress.controlUrl(settings);
|
||||
var info = peer.request(local, "/control/info", "GET", null);
|
||||
if (!settings.cluster.equals(info.path("clusterId").asText())
|
||||
|| !settings.id.equals(info.path("serviceId").asText())
|
||||
|| !info.path("role").asText().equals("coordinator")
|
||||
|| !info.path("storageHealthy").asBoolean()) {
|
||||
throw new IllegalStateException("Local coordinator identity mismatch");
|
||||
}
|
||||
connected = local;
|
||||
status = "CONNECTED";
|
||||
return connected;
|
||||
}
|
||||
// 复用地址不跳过后续心跳的响应签名校验,也不自动延长任务执行许可。
|
||||
if (!connected.isEmpty()) {
|
||||
return connected;
|
||||
}
|
||||
|
||||
// 显式部署入口和上次成功地址优先,但缓存不免除每次重连时的签名验证。
|
||||
// 顺序集合避免重复请求同一地址,也保持固定入口的优先级。
|
||||
Set<String> candidates = new LinkedHashSet<>();
|
||||
if (!settings.coordinator.isBlank()) {
|
||||
candidates.add(settings.coordinator);
|
||||
}
|
||||
Path cache = settings.directory.resolve("coordinator-url.txt");
|
||||
if (Files.exists(cache)) {
|
||||
// 历史地址可能随 IP 调整失效,读取它不会直接把状态改为已连接。
|
||||
candidates.add(Files.readString(cache).trim());
|
||||
}
|
||||
|
||||
for (String url : candidates) {
|
||||
try {
|
||||
// 固定入口或缓存成功时优先恢复,不再根据未认证广播随机选择其他地址。
|
||||
// PeerClient 校验响应签名后才返回内容,私有凭证不会发送给候选服务器。
|
||||
var info = peer.request(url, "/control/info", "GET", null);
|
||||
if (!settings.cluster.equals(info.path("clusterId").asText())
|
||||
|| info.path("serviceId").asText().isBlank()
|
||||
|| !info.path("storageHealthy").asBoolean()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 只缓存合法根地址;总控存储失败时不接受新连接,避免继续领取无持久化保障的许可。
|
||||
connected = Jsons.baseUrl(url);
|
||||
Files.writeString(cache, connected);
|
||||
status = "CONNECTED";
|
||||
return connected;
|
||||
} catch (Exception ignored) {
|
||||
// 固定或缓存地址暂时不可用时继续自动发现,不把连接失败当成已注册。
|
||||
}
|
||||
}
|
||||
|
||||
// 发现线索全部验证后再按认证得到的 serviceId 去重。
|
||||
// 同一总控多网卡的多个 IP 可以合并;两个不同有效总控不能随机选择。
|
||||
Map<String, String> verified = new LinkedHashMap<>();
|
||||
// 同一名称的公告也可能来自不同服务,冲突判断使用签名响应中的逻辑 ID。
|
||||
// 无有效签名的伪造公告不能挤占正常总控,也不能触发误报双总控。
|
||||
for (String url : discovery.candidates()) {
|
||||
try {
|
||||
var info = peer.request(url, "/control/info", "GET", null);
|
||||
if (settings.cluster.equals(info.path("clusterId").asText())
|
||||
&& !info.path("serviceId").asText().isBlank()
|
||||
&& info.path("storageHealthy").asBoolean()) {
|
||||
verified.putIfAbsent(info.path("serviceId").asText(), Jsons.baseUrl(url));
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 未认证或不可达的公告不进入冲突集合,避免陌生广播阻止正常注册。
|
||||
}
|
||||
}
|
||||
|
||||
if (verified.size() > 1) {
|
||||
// 尚未绑定时发现两个已认证总控,保持冲突状态,不保存任意一个候选。
|
||||
status = "CONFLICT";
|
||||
throw new IllegalStateException("Multiple authenticated coordinators discovered");
|
||||
}
|
||||
if (verified.size() == 1) {
|
||||
// 唯一有效身份可以对应多个 IP,只缓存本次验证成功的服务根地址。
|
||||
connected = verified.values().iterator().next();
|
||||
Files.writeString(cache, connected);
|
||||
status = "CONNECTED";
|
||||
return connected;
|
||||
}
|
||||
|
||||
// 找不到总控时不自建试验上下文,网关可独立沿用已确认路由继续转发。
|
||||
status = "WAITING";
|
||||
// 失败返回异常,由网关或节点按各自重试周期再次调用。
|
||||
throw new IllegalStateException("Waiting for authenticated coordinator discovery");
|
||||
}
|
||||
|
||||
public synchronized void disconnect() {
|
||||
// 调用方发现请求失败后清掉连接,下次重新验证固定地址、缓存和发现线索。
|
||||
// 保留历史地址文件,短暂网络故障恢复后仍可先验证原入口。
|
||||
connected = "";
|
||||
status = "WAITING";
|
||||
}
|
||||
|
||||
public String status() {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.xtrh.discovery.service;
|
||||
|
||||
import com.xtrh.common.config.Settings;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import org.springframework.boot.web.context.WebServerInitializedEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.jmdns.JmDNS;
|
||||
import javax.jmdns.ServiceEvent;
|
||||
import javax.jmdns.ServiceInfo;
|
||||
import javax.jmdns.ServiceListener;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/**
|
||||
* 通过局域网广播获取总控候选地址,不在发现层建立信任或下发任务。
|
||||
* mDNS 的集群名称和 serviceId 均可能被伪造,最终由 Locator 验证签名响应。
|
||||
* 多块网卡发现同一总控时按逻辑身份收集地址,不把不同 IP 当成不同总控。
|
||||
* 服务类型与协议版本只用于缩小候选范围,不构成服务认证。
|
||||
* 候选缓存不承载试验、节点容量或执行许可,业务状态仍以总控为准。
|
||||
*/
|
||||
@Component
|
||||
public class Discovery {
|
||||
public static final String TYPE = "_xtrh-control._tcp.local.";
|
||||
|
||||
private final Settings settings;
|
||||
// 回调与关闭操作可能同时访问引擎列表,使用可安全遍历的并发容器。
|
||||
private final List<JmDNS> engines = new CopyOnWriteArrayList<>();
|
||||
// 地址按公告身份汇集;真正的逻辑身份仍需从已签名的控制响应中确认。
|
||||
private final Map<String, Set<String>> discovered = new ConcurrentHashMap<>();
|
||||
private volatile String status = "STARTING";
|
||||
private volatile boolean closed;
|
||||
|
||||
public Discovery(Settings settings) {
|
||||
this.settings = settings;
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void started(WebServerInitializedEvent event) {
|
||||
// 禁用发现只关闭组播路径,Locator 仍可尝试统一配置的入口和历史地址。
|
||||
if (!settings.discoveryEnabled) {
|
||||
status = "DISABLED";
|
||||
return;
|
||||
}
|
||||
|
||||
// 等 HTTP 服务确定真实端口再发布;发现初始化不阻塞服务启动或 UDP 转发。
|
||||
// 后台线程不领取任务,注册必须等候选地址通过正式 HTTP 身份校验。
|
||||
// 安装时 HTTP 端口可以改动,公告使用事件中的实际监听端口。
|
||||
Thread thread = new Thread(
|
||||
() -> start(event.getWebServer().getPort()), "xtrh-discovery");
|
||||
thread.setDaemon(true);
|
||||
thread.start();
|
||||
}
|
||||
|
||||
private void start(int port) {
|
||||
try {
|
||||
// 发现只覆盖组播能够到达的网段;跨 VLAN 部署由统一入口配置兜底。
|
||||
// 不同网卡可以进入不同网络,因此不能只尝试主机名解析出的一个地址。
|
||||
List<InetAddress> addresses = new ArrayList<>();
|
||||
if (!settings.discoveryAddress.isBlank()) {
|
||||
// 多网卡部署可以指定一块网卡,避免发现报文发送到不相关网络。
|
||||
// 显式地址仍由 JmDNS 检查可用性,失败保持未发现状态。
|
||||
addresses.add(InetAddress.getByName(settings.discoveryAddress));
|
||||
} else {
|
||||
// 自动选择已启用、非回环且支持组播的 IPv4 地址,不假定第一块网卡可用。
|
||||
// 当前协议公告使用 IPv4,链路本地地址不作为跨电脑服务入口。
|
||||
for (NetworkInterface card : Collections.list(NetworkInterface.getNetworkInterfaces())) {
|
||||
if (!card.isUp() || card.isLoopback() || !card.supportsMulticast()) {
|
||||
continue;
|
||||
}
|
||||
for (InetAddress address : Collections.list(card.getInetAddresses())) {
|
||||
if (address instanceof Inet4Address && !address.isLinkLocalAddress()) {
|
||||
addresses.add(address);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 无合适组播网卡时保留主机地址尝试;网络隔离部署仍可使用固定总控入口。
|
||||
if (addresses.isEmpty()) {
|
||||
addresses.add(InetAddress.getLocalHost());
|
||||
}
|
||||
|
||||
for (InetAddress address : addresses) {
|
||||
// 服务关闭后不再为尚未处理的网卡建立发现套接字。
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// 每个地址建立发现引擎;并发回调使用线程安全集合收集候选信息。
|
||||
// 引擎名称由部署实例身份派生,重启后仍能对应同一台节点。
|
||||
JmDNS dns = JmDNS.create(address, "xtrh-" + settings.id.substring(0, 8));
|
||||
engines.add(dns);
|
||||
if (settings.role.equals("coordinator")) {
|
||||
// 广播只有公开线索,不包含私有凭证、试验配置或播放许可。
|
||||
// 身份字段只便于关联公告,不能用它替代签名响应认证。
|
||||
dns.registerService(ServiceInfo.create(
|
||||
TYPE, "PXHJ-" + settings.id, port, 0, 0,
|
||||
Map.of(
|
||||
"clusterId", settings.cluster,
|
||||
"serviceId", settings.id,
|
||||
"protocol", "1")));
|
||||
} else {
|
||||
dns.addServiceListener(TYPE, new ServiceListener() {
|
||||
public void serviceAdded(ServiceEvent event) {
|
||||
// 新服务先解析完整记录,不能直接使用仅包含名称的公告。
|
||||
dns.requestServiceInfo(event.getType(), event.getName());
|
||||
}
|
||||
|
||||
public void serviceRemoved(ServiceEvent event) {
|
||||
// 注销公告只清除发现线索;当前控制连接是否失效由心跳确认。
|
||||
// 缓存入口仍可在重连时尝试,避免单次组播事件终止正式业务。
|
||||
String id = event.getInfo().getPropertyString("serviceId");
|
||||
if (id != null) {
|
||||
discovered.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
public void serviceResolved(ServiceEvent event) {
|
||||
ServiceInfo info = event.getInfo();
|
||||
// 先筛除其他集群和接口版本;通过此筛选仍然不代表已经认证。
|
||||
// 接收公告不执行配置、不修改任务归属,也不发送服务凭证。
|
||||
if (!settings.cluster.equals(info.getPropertyString("clusterId"))
|
||||
|| !"1".equals(info.getPropertyString("protocol"))) {
|
||||
return;
|
||||
}
|
||||
|
||||
Set<String> urls = ConcurrentHashMap.newKeySet();
|
||||
// 一个公告可能含多个可达 IP,留给 Locator 逐个验证。
|
||||
for (Inet4Address host : info.getInet4Addresses()) {
|
||||
urls.add("http://" + host.getHostAddress() + ":" + info.getPort());
|
||||
}
|
||||
String id = info.getPropertyString("serviceId");
|
||||
if (id != null && !urls.isEmpty()) {
|
||||
// 多网卡回调合并地址,避免相同总控因重复公告被请求多次。
|
||||
// 公告中的身份只作为缓存键,认证去重在 Locator 完成。
|
||||
discovered.computeIfAbsent(id, key -> ConcurrentHashMap.newKeySet())
|
||||
.addAll(urls);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 某块网卡失败时继续尝试其他网卡,不停止已经建立的发现引擎。
|
||||
}
|
||||
}
|
||||
// ACTIVE 只表示发现引擎存在,并不宣称节点已注册或总控已经可信。
|
||||
status = engines.isEmpty() ? "UNAVAILABLE" : "ACTIVE";
|
||||
} catch (Exception e) {
|
||||
status = "UNAVAILABLE";
|
||||
}
|
||||
}
|
||||
|
||||
// 未认证广播只能给线索;多个有效总控的判断必须放在响应签名验证之后。
|
||||
// 返回去重后的稳定顺序,避免同一轮查找重复试探相同服务地址。
|
||||
public List<String> candidates() {
|
||||
return discovered.values().stream()
|
||||
.flatMap(Set::stream)
|
||||
.distinct()
|
||||
.sorted()
|
||||
.toList();
|
||||
}
|
||||
|
||||
public String status() {
|
||||
return status;
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void close() {
|
||||
// 发现引擎只负责组播套接字,任务与数据库生命周期由各业务服务管理。
|
||||
closed = true;
|
||||
for (JmDNS dns : engines) {
|
||||
try {
|
||||
dns.close();
|
||||
} catch (Exception ignored) {
|
||||
// 逐个关闭网卡引擎,单个关闭错误不能阻止其他组播套接字释放。
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.xtrh.discovery.util;
|
||||
|
||||
import com.xtrh.common.config.Settings;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.InetAddress;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
import java.util.Collections;
|
||||
|
||||
/**
|
||||
* 选择节点对外登记的地址,不把本机回环地址默认当成跨电脑播放地址。
|
||||
* 多网卡时根据到已认证总控的实际网络路由选择本机地址,而非主机名的首个解析结果。
|
||||
*/
|
||||
public final class NodeAddress {
|
||||
private NodeAddress() {}
|
||||
|
||||
public static String host(Settings settings, String coordinator) throws Exception {
|
||||
if (!settings.advertisedHost.isBlank()) {
|
||||
// 特殊网络或播放域名由部署配置覆盖,最终注册仍执行服务根地址校验。
|
||||
return settings.advertisedHost;
|
||||
}
|
||||
|
||||
// 主执行端通过本机入口领取任务,对外登记地址必须另外选择,供其他电脑播放。
|
||||
if (settings.role.equals("coordinator")) return localHost(settings);
|
||||
URI uri = URI.create(coordinator);
|
||||
try (Socket route = new Socket()) {
|
||||
// 连接只用于查询操作系统选出的本机接口,关闭后不会持续占用控制连接。
|
||||
// HTTPS 未显式写端口时按 443 查询路由,HTTP 按 80。
|
||||
route.connect(new InetSocketAddress(
|
||||
uri.getHost(),
|
||||
uri.getPort() > 0 ? uri.getPort() : (uri.getScheme().equals("https") ? 443 : 80)),
|
||||
1000);
|
||||
InetAddress local = route.getLocalAddress();
|
||||
// 同电脑的独立子节点可能连接 localhost,同样不能把回环默认发布给远端观看者。
|
||||
return local.isLoopbackAddress() ? localHost(settings) : local.getHostAddress();
|
||||
}
|
||||
}
|
||||
|
||||
/** 自注册只访问本实例已绑定的控制入口,网络发送仍走正常签名认证。 */
|
||||
public static String controlUrl(Settings settings) {
|
||||
if (!settings.httpReady()) throw new IllegalStateException("Waiting for local HTTP server");
|
||||
String host = wildcard(settings.bindHost) ? "127.0.0.1" : settings.bindHost;
|
||||
return httpUrl(host, settings.port);
|
||||
}
|
||||
|
||||
// 发布实际 HTTP 端口;主节点的控制和媒体入口共用同一端口,不增开第二个执行进程。
|
||||
public static String url(Settings settings, String coordinator) throws Exception {
|
||||
return httpUrl(host(settings, coordinator), settings.port);
|
||||
}
|
||||
|
||||
/** 对外地址优先尊重显式绑定与发现网卡,多网卡部署仍可用 advertised-host 指定。 */
|
||||
private static String localHost(Settings settings) throws Exception {
|
||||
if (!wildcard(settings.bindHost)) return settings.bindHost;
|
||||
if (!settings.discoveryAddress.isBlank()) {
|
||||
InetAddress configured = InetAddress.getByName(settings.discoveryAddress);
|
||||
if (!configured.isLoopbackAddress() && !configured.isAnyLocalAddress()) return configured.getHostAddress();
|
||||
}
|
||||
// 只考虑启用的真实 IPv4 网卡,避免默认发布回环、链路本地或虚拟接口的地址。
|
||||
var interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
|
||||
InetAddress preferred = null;
|
||||
try { preferred = InetAddress.getLocalHost(); } catch (Exception ignored) { }
|
||||
String first = null;
|
||||
for (NetworkInterface card : interfaces) {
|
||||
if (!card.isUp() || card.isLoopback() || card.isVirtual()) continue;
|
||||
for (InetAddress address : Collections.list(card.getInetAddresses())) {
|
||||
if (!(address instanceof Inet4Address) || address.isLoopbackAddress() || address.isLinkLocalAddress()) continue;
|
||||
if (address.equals(preferred)) return address.getHostAddress();
|
||||
if (first == null) first = address.getHostAddress();
|
||||
}
|
||||
}
|
||||
// 无局域网网卡的纯本机环境仍可运行;跨电脑使用须发布观看端可访问的地址。
|
||||
return first == null ? "127.0.0.1" : first;
|
||||
}
|
||||
|
||||
private static boolean wildcard(String host) {
|
||||
return host.isBlank() || host.equals("0.0.0.0") || host.equals("::") || host.equals("[::]");
|
||||
}
|
||||
|
||||
// IPv6 字面量需要方括号,确保绑定特定网卡时仍生成合法 URL。
|
||||
private static String httpUrl(String host, int port) {
|
||||
String authority = host.contains(":") && !host.startsWith("[") ? "[" + host + "]" : host;
|
||||
return "http://" + authority + ":" + port;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.xtrh.gateway.controller;
|
||||
|
||||
import com.xtrh.gateway.service.GatewayService;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 网关 HTTP 入口仅返回转发状态与统计信息。
|
||||
* 路由由经过认证的总控计划同步,不能从此入口任意修改。
|
||||
* UDP socket、队列与双向转发均封装在业务服务中。
|
||||
*/
|
||||
@RestController
|
||||
@ConditionalOnProperty(name = "fusion.role", havingValue = "gateway")
|
||||
public class GatewayController {
|
||||
private final GatewayService gateway;
|
||||
|
||||
public GatewayController(GatewayService gateway) {
|
||||
this.gateway = gateway;
|
||||
}
|
||||
|
||||
// 状态快照不含采集报文与共享凭证,供总控和运行检查读取。
|
||||
@GetMapping("/gateway/status")
|
||||
public Object status() {
|
||||
return gateway.status();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
package com.xtrh.gateway.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.xtrh.common.config.Settings;
|
||||
import com.xtrh.common.dao.StateStore;
|
||||
import com.xtrh.communication.client.PeerClient;
|
||||
import com.xtrh.discovery.service.CoordinatorLocator;
|
||||
import com.xtrh.discovery.util.NodeAddress;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static com.xtrh.common.util.Jsons.array;
|
||||
import static com.xtrh.common.util.Jsons.object;
|
||||
import static com.xtrh.common.util.Jsons.require;
|
||||
import static com.xtrh.common.util.Jsons.required;
|
||||
|
||||
/**
|
||||
* 独立采集接入服务:接收原始 UDP 报文、识别来源并双向转送。
|
||||
* 总控只负责同步路由,视频轮次结束或总控失联不停止已确认的转发。
|
||||
* 不解密或重组采集协议,正式协议认证及业务解析仍由 PXHJ 完成。
|
||||
*/
|
||||
@Service
|
||||
@ConditionalOnProperty(name = "fusion.role", havingValue = "gateway")
|
||||
public class GatewayService {
|
||||
// 采用 IPv4 UDP 的最大有效负载上限,不截取其中的采集协议字段。
|
||||
private static final int MAX_DATAGRAM_BYTES = 65507;
|
||||
// 字节限额与报文数限额配合,大报文不能绕过队列长度限制。
|
||||
private static final long MAX_BUFFERED_BYTES = 16L * 1024 * 1024;
|
||||
|
||||
// 收包时保留来源及匹配的路由,发送线程无需重复猜测采集器身份。
|
||||
// 字节数组专属这一报文,与接收循环复用的缓冲区不共享。
|
||||
private record Packet(byte[] bytes, InetSocketAddress source, Relay relay) {}
|
||||
|
||||
private final Settings settings;
|
||||
private final CoordinatorLocator locator;
|
||||
private final PeerClient peer;
|
||||
// 路由持久化经 DAO 完成;业务服务不包含表结构或 SQL 语句。
|
||||
private final StateStore store;
|
||||
private final DatagramSocket ingress;
|
||||
// 上行接收与发送解耦,避免目标发送迟缓阻塞所有采集器的接收。
|
||||
private final ArrayBlockingQueue<Packet> queue = new ArrayBlockingQueue<>(2048);
|
||||
// 计数描述本次进程运行,重启恢复的是路由,而不是历史报文统计。
|
||||
// 原子计数可同时由上行线程和各采集器回传线程更新。
|
||||
// 未登记、队列丢弃和发送错误分别计数,PXHJ 可区分数据缺失原因。
|
||||
private final AtomicLong received = new AtomicLong(), forwarded = new AtomicLong();
|
||||
private final AtomicLong unknown = new AtomicLong(), overflow = new AtomicLong();
|
||||
private final AtomicLong errors = new AtomicLong(), buffered = new AtomicLong();
|
||||
// 发布只读列表快照,收包线程遍历期间不受路由增删影响。
|
||||
private volatile List<Relay> relays = List.of();
|
||||
private volatile boolean closed;
|
||||
private volatile long routeVersion = -1;
|
||||
private volatile JsonNode appliedRoutes = array();
|
||||
// connection 描述总控连接;routeState 描述转发配置,二者不互相替代。
|
||||
// WAITING 不代表数据线程停止,已经确认的转发可以继续运行。
|
||||
private volatile String connection = "WAITING", routeState = "WAITING";
|
||||
private long retryAfter;
|
||||
|
||||
/**
|
||||
* 固定采集入口与各采集器的独立转发端口分别绑定。
|
||||
* 启动先恢复最后确认路由,再开启收发线程,支持断网重启后的转发。
|
||||
* 路由文件锁由 DAO 管理,防止两个网关误用同一个数据目录。
|
||||
*/
|
||||
public GatewayService(Settings settings, CoordinatorLocator locator,
|
||||
PeerClient peer, ObjectMapper mapper) throws Exception {
|
||||
this.settings = settings;
|
||||
this.locator = locator;
|
||||
this.peer = peer;
|
||||
store = StateStore.open(settings.directory.resolve("gateway"), mapper);
|
||||
ingress = new DatagramSocket(null);
|
||||
// 增大内核收包缓冲区以应对短时突发,实际可用大小仍由操作系统决定。
|
||||
// 内核缓冲区和业务队列是两层容量,业务队列满时会显式累计丢弃数。
|
||||
ingress.setReceiveBufferSize(4 * 1024 * 1024);
|
||||
ingress.bind(new InetSocketAddress(settings.gatewayPort));
|
||||
ObjectNode saved = store.load();
|
||||
if (saved.path("routes").isArray()) {
|
||||
apply(saved.path("routes"), saved.path("routeVersion").asLong(), false);
|
||||
}
|
||||
daemon("xtrh-udp-receive", this::receive);
|
||||
daemon("xtrh-udp-forward", this::forward);
|
||||
}
|
||||
|
||||
// UDP 循环独立于总控心跳,关闭服务时由 closed 标记和 socket 关闭退出。
|
||||
private static void daemon(String name, Runnable runnable) {
|
||||
Thread thread = new Thread(runnable, name);
|
||||
thread.setDaemon(true);
|
||||
thread.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* 协商分类只识别完整 FND 外层,普通二进制报文碰巧含类型字节仍透明转发。
|
||||
* 帧边界校验用于避免误分类,不能代替 PXHJ 的 CRC、HMAC 和密钥校验。
|
||||
* 使用报文实际长度校验帧尾,接收循环的复用缓冲区尾部不属于本次报文。
|
||||
*/
|
||||
private static boolean frameType(byte[] bytes, int length, int type) {
|
||||
if (length < 109 || length > 1133 || Byte.toUnsignedInt(bytes[8]) != type) {
|
||||
return false;
|
||||
}
|
||||
ByteBuffer header = ByteBuffer.wrap(bytes, 0, length);
|
||||
return header.getInt(0) == 0x5AA5FAFB && header.getInt(4) == length
|
||||
&& header.getInt(length - 4) == 0xA55AFCFD;
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅接收唯一匹配的登记来源;未登记和歧义来源统一丢弃并计数。
|
||||
* 接收缓冲区循环复用,入队前复制有效字节,防止下一报文覆盖旧内容。
|
||||
* 队列同时限制报文数和累计字节数,避免高频或大报文耗尽内存。
|
||||
*/
|
||||
private void receive() {
|
||||
byte[] buffer = new byte[MAX_DATAGRAM_BYTES];
|
||||
while (!closed) {
|
||||
try {
|
||||
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
|
||||
ingress.receive(packet);
|
||||
received.incrementAndGet();
|
||||
InetSocketAddress source = (InetSocketAddress) packet.getSocketAddress();
|
||||
Relay match = matchSource(source);
|
||||
if (match == null) {
|
||||
unknown.incrementAndGet();
|
||||
continue;
|
||||
}
|
||||
// 不改原始密文、报文长度和采样时间,PXHJ 继续按既有协议解析。
|
||||
byte[] bytes = Arrays.copyOf(buffer, packet.getLength());
|
||||
long reserved = buffered.addAndGet(bytes.length);
|
||||
if (reserved > MAX_BUFFERED_BYTES || !queue.offer(new Packet(bytes, source, match))) {
|
||||
buffered.addAndGet(-bytes.length);
|
||||
overflow.incrementAndGet();
|
||||
}
|
||||
} catch (Exception failure) {
|
||||
if (!closed) {
|
||||
errors.incrementAndGet();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 同一来源若匹配多条路由就拒绝转发,防止把数据归入错误采集器。
|
||||
private Relay matchSource(InetSocketAddress source) {
|
||||
// 匹配依据来源 IP 与登记端口,内容中的模块编号仍交给 PXHJ 校验。
|
||||
// 动态源端口由各 Relay 的 sourcePort=0 明确允许,不放宽来源 IP。
|
||||
Relay match = null;
|
||||
for (Relay relay : relays) {
|
||||
if (relay.matches(source)) {
|
||||
if (match != null) {
|
||||
return null;
|
||||
}
|
||||
match = relay;
|
||||
}
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
/**
|
||||
* 每个采集器通过自己的稳定源端口转发,PXHJ 可保持独立身份映射。
|
||||
* 单个报文发送失败只增加错误计数,后续报文及其他路由继续执行。
|
||||
* 出队报文无论成功与否都释放字节额度,避免错误路径泄漏缓存容量。
|
||||
*/
|
||||
private void forward() {
|
||||
// 上行保持单个发送循环的出队顺序,不为每个报文创建临时线程。
|
||||
// 空队列等待有时间上限,便于在关闭标记变化后退出循环。
|
||||
while (!closed) {
|
||||
try {
|
||||
Packet packet = queue.poll(1, TimeUnit.SECONDS);
|
||||
if (packet == null) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
packet.relay.send(packet.bytes, packet.source);
|
||||
forwarded.incrementAndGet();
|
||||
} catch (Exception failure) {
|
||||
errors.incrementAndGet();
|
||||
} finally {
|
||||
buffered.addAndGet(-packet.bytes.length);
|
||||
}
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 路由变更先校验地址并准备新 socket,再发布新的列表快照。
|
||||
* 相同采集器及相同转发端口复用 socket,保留回传线程与端口身份。
|
||||
* 准备失败时关闭本次新开的端口,不关闭仍在服务的旧路由。
|
||||
*/
|
||||
private synchronized void apply(JsonNode routes, long version, boolean save) throws Exception {
|
||||
Map<String, Relay> existing = new HashMap<>();
|
||||
for (Relay relay : relays) {
|
||||
existing.put(relay.id, relay);
|
||||
}
|
||||
List<Relay> next = new ArrayList<>(), opened = new ArrayList<>();
|
||||
Map<Relay, ObjectNode> updates = new HashMap<>();
|
||||
try {
|
||||
for (JsonNode route : routes) {
|
||||
// 转发端口不能占用采集入口,否则会破坏收包与回传的端口分工。
|
||||
require(route.path("relayPort").asInt() != ingress.getLocalPort(),
|
||||
"Relay port conflicts with gateway input");
|
||||
String id = required(route, "endpointId");
|
||||
ObjectNode config = (ObjectNode) route.deepCopy();
|
||||
InetAddress.getByName(required(route, "sourceHost"));
|
||||
InetAddress.getByName(required(route, "targetHost"));
|
||||
Relay old = existing.get(id);
|
||||
if (old != null && old.route.path("relayPort").asInt() == route.path("relayPort").asInt()) {
|
||||
next.add(old);
|
||||
updates.put(old, config);
|
||||
} else {
|
||||
Relay fresh = new Relay(config);
|
||||
opened.add(fresh);
|
||||
next.add(fresh);
|
||||
}
|
||||
}
|
||||
// 保存确认内容与版本,重启恢复时无需依赖总控马上在线。
|
||||
ObjectNode snapshot = object().put("routeVersion", version);
|
||||
snapshot.set("routes", routes.deepCopy());
|
||||
if (save) {
|
||||
store.save(snapshot);
|
||||
}
|
||||
for (Map.Entry<Relay, ObjectNode> entry : updates.entrySet()) {
|
||||
entry.getKey().update(entry.getValue());
|
||||
}
|
||||
List<Relay> previous = relays;
|
||||
// 旧列表不再修改;新列表发布后才关闭已撤销的旧 socket。
|
||||
relays = List.copyOf(next);
|
||||
routeVersion = version;
|
||||
appliedRoutes = routes.deepCopy();
|
||||
routeState = "APPLIED";
|
||||
for (Relay old : previous) {
|
||||
if (!next.contains(old)) {
|
||||
old.close();
|
||||
}
|
||||
}
|
||||
} catch (Exception failure) {
|
||||
for (Relay relay : opened) {
|
||||
relay.close();
|
||||
}
|
||||
routeState = "APPLY_FAILED";
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动发现总控后以稳定网关标识和本次启动标识报告状态。
|
||||
* 只有 PXHJ 已确认的计划才替换本地路由,未确认的空计划不是撤销。
|
||||
* 版本及内容同时比较,避免总控存储重建后复用版本号导致漏更新。
|
||||
*/
|
||||
@Scheduled(fixedDelay = 1000)
|
||||
public void heartbeat() {
|
||||
// 重试退避约束发现与 HTTP 通信频率,不占用 UDP 收发线程。
|
||||
if (System.currentTimeMillis() < retryAfter) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String coordinator = locator.locate();
|
||||
ObjectNode input = status().put("clusterId", settings.cluster)
|
||||
.put("gatewayId", settings.id).put("bootId", settings.bootId)
|
||||
.put("name", settings.name).put("baseUrl", NodeAddress.url(settings, coordinator));
|
||||
JsonNode plan = peer.request(coordinator, "/control/gateways/heartbeat", "POST", input);
|
||||
// 认证及响应验签由通信客户端统一完成,业务层只处理可信计划。
|
||||
long version = plan.path("routeVersion").asLong();
|
||||
if (plan.path("routesConfirmed").asBoolean()
|
||||
&& (version != routeVersion || !appliedRoutes.equals(plan.path("routes")))) {
|
||||
apply(plan.path("routes"), version, true);
|
||||
}
|
||||
connection = "CONNECTED";
|
||||
} catch (Exception failure) {
|
||||
// 控制连接故障仅触发重新发现,已经确认的 UDP 线程继续服务。
|
||||
locator.disconnect();
|
||||
connection = "WAITING";
|
||||
retryAfter = System.currentTimeMillis() + 1500;
|
||||
}
|
||||
}
|
||||
|
||||
// 控制层读取统计快照,不接触 socket、队列或可变路由对象。
|
||||
public ObjectNode status() {
|
||||
ObjectNode result = object().put("connection", connection).put("routeState", routeState)
|
||||
.put("routeVersion", routeVersion).put("inputPort", ingress.getLocalPort())
|
||||
.put("received", received.get()).put("forwarded", forwarded.get())
|
||||
.put("unknownSource", unknown.get()).put("queueDropped", overflow.get())
|
||||
.put("errors", errors.get()).put("bufferedBytes", buffered.get());
|
||||
ArrayNode entries = result.putArray("routeStatus");
|
||||
for (Relay relay : relays) {
|
||||
entries.add(relay.status());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// 先关闭 socket 唤醒阻塞接收,再关闭持久化连接。
|
||||
@PreDestroy
|
||||
public void close() throws Exception {
|
||||
closed = true;
|
||||
ingress.close();
|
||||
for (Relay relay : relays) {
|
||||
relay.close();
|
||||
}
|
||||
store.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* 单个采集器的转发会话,负责稳定端口、目标连接和独立回传线程。
|
||||
* 上行经统一队列,下行从该 socket 直接回到原采集器入口。
|
||||
* 私有会话仅供服务使用,HTTP 控制器无法访问其可变状态。
|
||||
*/
|
||||
private final class Relay {
|
||||
private final String id;
|
||||
private final DatagramSocket socket;
|
||||
private volatile ObjectNode route;
|
||||
private volatile InetAddress sourceAddress;
|
||||
private volatile InetSocketAddress lastSource;
|
||||
// 图片地址协商使用稳定 socket;采集数据和心跳可能来自另一个临时端口。
|
||||
// 只按外层类型区分回程,不在网关解密;身份认证仍由 PXHJ 完成。
|
||||
private volatile InetSocketAddress lastNegotiationSource;
|
||||
private final AtomicLong sent = new AtomicLong(), replies = new AtomicLong();
|
||||
|
||||
Relay(ObjectNode config) throws Exception {
|
||||
id = config.path("endpointId").asText();
|
||||
socket = new DatagramSocket(null);
|
||||
try {
|
||||
// 专属转发端口是 PXHJ 识别原采集器的映射,不随视频任务迁移。
|
||||
socket.bind(new InetSocketAddress(config.path("relayPort").asInt()));
|
||||
socket.setSoTimeout(1000);
|
||||
update(config);
|
||||
daemon("xtrh-relay-" + id, this::reply);
|
||||
} catch (Exception failure) {
|
||||
socket.close();
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* UDP connect 限定回传来源为配置的 PXHJ 地址及端口。
|
||||
* 来源配置变化时清空最近设备地址,避免回执发到旧采集器。
|
||||
* 更新和发送共用对象锁,避免发送期间切换目标 socket 连接。
|
||||
*/
|
||||
synchronized void update(ObjectNode config) throws Exception {
|
||||
sourceAddress = InetAddress.getByName(config.path("sourceHost").asText());
|
||||
if (route == null || !route.path("sourceHost").equals(config.path("sourceHost"))
|
||||
|| !route.path("sourcePort").equals(config.path("sourcePort"))) {
|
||||
lastSource = null;
|
||||
lastNegotiationSource = null;
|
||||
}
|
||||
socket.disconnect();
|
||||
socket.connect(new InetSocketAddress(config.path("targetHost").asText(),
|
||||
config.path("targetPort").asInt()));
|
||||
route = config;
|
||||
}
|
||||
|
||||
// sourcePort 为零允许采集器临时源端口,来源 IP 仍必须匹配。
|
||||
boolean matches(InetSocketAddress source) {
|
||||
return source.getAddress().equals(sourceAddress)
|
||||
&& (route.path("sourcePort").asInt() == 0
|
||||
|| route.path("sourcePort").asInt() == source.getPort());
|
||||
}
|
||||
|
||||
// 记住最近真实来源,动态源端口的配置及回执才能准确返回。
|
||||
synchronized void send(byte[] bytes, InetSocketAddress source) throws Exception {
|
||||
// 类型字节只用于选择回程 socket,不能据此新增路由或认定报文可信。
|
||||
// 协商请求不能覆盖既有配置回执的设备端口,普通上行也不能覆盖协商端口。
|
||||
if (frameType(bytes, bytes.length, 0x14)) {
|
||||
lastNegotiationSource = source;
|
||||
} else {
|
||||
lastSource = source;
|
||||
}
|
||||
socket.send(new DatagramPacket(bytes, bytes.length));
|
||||
sent.incrementAndGet();
|
||||
}
|
||||
|
||||
/**
|
||||
* 回传保持原字节,覆盖采集器配置下发及接收回执等双向报文。
|
||||
* 优先使用最近来源,没有来源记录时仅使用明确登记的设备端口。
|
||||
* 各采集器独立等待回复,单路异常不会阻塞其他采集器的回传。
|
||||
*/
|
||||
void reply() {
|
||||
byte[] buffer = new byte[MAX_DATAGRAM_BYTES];
|
||||
while (!closed && !socket.isClosed()) {
|
||||
try {
|
||||
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
|
||||
socket.receive(packet);
|
||||
// 协商回复只能回最近一次协商请求来源,不能误发给心跳临时端口。
|
||||
// 尚未收到协商请求时丢弃该类回传;设备端仍需校验密文、请求ID和租约。
|
||||
boolean negotiation = frameType(buffer, packet.getLength(), 0x15);
|
||||
InetSocketAddress destination = negotiation ? lastNegotiationSource : lastSource;
|
||||
if (!negotiation && destination == null && route.path("sourcePort").asInt() > 0) {
|
||||
destination = new InetSocketAddress(sourceAddress, route.path("sourcePort").asInt());
|
||||
}
|
||||
if (destination != null) {
|
||||
// 配置请求和回执与数据报文同样透明转送,不重新编码协议。
|
||||
// 经固定入口回传,采集器看到的回复端口与其上传目标一致。
|
||||
ingress.send(new DatagramPacket(buffer, packet.getLength(), destination));
|
||||
replies.incrementAndGet();
|
||||
}
|
||||
} catch (SocketTimeoutException ignored) {
|
||||
// 周期醒来检查关闭标记,空闲等待不属于转发错误。
|
||||
} catch (Exception failure) {
|
||||
if (!socket.isClosed()) {
|
||||
errors.incrementAndGet();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 每路分别统计上行与回传,便于定位异常而不暴露报文内容。
|
||||
ObjectNode status() {
|
||||
return object().put("endpointId", id).put("relayPort", socket.getLocalPort())
|
||||
.put("relaySourceHost", socket.getLocalAddress().getHostAddress())
|
||||
.put("forwarded", sent.get()).put("replies", replies.get());
|
||||
}
|
||||
|
||||
void close() {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.xtrh.node.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* 为视频长连接配置独立的异步输出线程池。
|
||||
* 流输出不占用普通 HTTP 请求线程,状态与管理接口仍可响应。
|
||||
* 播放连接数与任务路数分别管理,一路视频可能有多个观看者。
|
||||
*/
|
||||
@Configuration
|
||||
@Conditional(WorkerCapabilityCondition.class)
|
||||
public class AsyncMediaConfiguration implements WebMvcConfigurer {
|
||||
// 不设置等待队列,观看线程达到上限时避免长连接无限积压。
|
||||
@Bean
|
||||
public ThreadPoolTaskExecutor mediaExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(2);
|
||||
executor.setMaxPoolSize(64);
|
||||
executor.setQueueCapacity(0);
|
||||
executor.setThreadNamePrefix("xtrh-media-");
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
|
||||
// 连接寿命由任务许可与客户端控制,禁用 MVC 默认请求超时。
|
||||
// 实际授权仍在服务层逐帧校验,关闭超时不会延长任务许可。
|
||||
@Override
|
||||
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
|
||||
configurer.setTaskExecutor(mediaExecutor()).setDefaultTimeout(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.xtrh.node.config;
|
||||
|
||||
import com.xtrh.common.config.Settings;
|
||||
import org.springframework.context.annotation.Condition;
|
||||
import org.springframework.context.annotation.ConditionContext;
|
||||
import org.springframework.core.type.AnnotatedTypeMetadata;
|
||||
|
||||
/**
|
||||
* 执行能力可同时存在于主节点和子节点,UDP 网关保持独立转发职责。
|
||||
* 服务与控制器共用条件,主节点关闭执行能力时不会留下无服务支持的媒体入口。
|
||||
*/
|
||||
public final class WorkerCapabilityCondition implements Condition {
|
||||
@Override
|
||||
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
|
||||
return Settings.workerEnabled(context.getEnvironment());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.xtrh.node.controller;
|
||||
|
||||
import com.xtrh.node.config.WorkerCapabilityCondition;
|
||||
import com.xtrh.node.service.ImageIngressService;
|
||||
import com.xtrh.node.service.WorkerService;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import static com.xtrh.common.util.Jsons.object;
|
||||
|
||||
/**
|
||||
* 节点原图私有查询入口,供 PXHJ 后台取图,不向浏览器分发集群凭证。
|
||||
* ServiceSecurity 对请求和包括 JPEG 在内的原始响应字节执行 HMAC 校验。
|
||||
* 没有原图、分配过期、版本迁移或帧已淘汰统一返回签名 JSON 404。
|
||||
*/
|
||||
@RestController
|
||||
@Conditional(WorkerCapabilityCondition.class)
|
||||
public class NodeImageController {
|
||||
private final WorkerService worker;
|
||||
|
||||
public NodeImageController(WorkerService worker) { this.worker = worker; }
|
||||
|
||||
// 控制器不保存图片状态,任务租约、帧缓存和撤销均交由服务层统一判断。
|
||||
|
||||
// 元数据只包含业务来源和图片尺寸;设备密钥、服务凭证和许可均不返回。
|
||||
@GetMapping("/node/images/{taskId}/{version}/latest")
|
||||
public ResponseEntity<?> latest(@PathVariable String taskId, @PathVariable long version) {
|
||||
ImageIngressService.Frame frame = worker.originalFrame(taskId, version, null);
|
||||
return frame == null ? missing() : ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(frame.metadata());
|
||||
}
|
||||
|
||||
// 帧号锁定最近缓存中的一张图,HTTP 输出不重编码,保留设备 JPEG 原字节。
|
||||
@GetMapping("/node/images/{taskId}/{version}/frames/{frameId}")
|
||||
public ResponseEntity<?> frame(@PathVariable String taskId, @PathVariable long version, @PathVariable String frameId) {
|
||||
ImageIngressService.Frame frame = worker.originalFrame(taskId, version, frameId);
|
||||
return frame == null ? missing() : ResponseEntity.ok().cacheControl(CacheControl.noStore())
|
||||
.contentType(MediaType.IMAGE_JPEG).body(frame.jpeg());
|
||||
}
|
||||
|
||||
// 固定错误不暴露任务密钥,也不允许浏览器缓存暂时无图的结果。
|
||||
private ResponseEntity<?> missing() {
|
||||
return ResponseEntity.status(404).cacheControl(CacheControl.noStore())
|
||||
.body(object().put("message", "Original image is not available"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.xtrh.node.controller;
|
||||
|
||||
import com.xtrh.node.service.WorkerService;
|
||||
import com.xtrh.node.config.WorkerCapabilityCondition;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 节点 HTTP 入口只负责查询与流输出,业务许可由服务层校验。
|
||||
* 播放地址包含任务号和版本,迁移时由总控向 PXHJ 回传新地址。
|
||||
* 主节点兼任执行端时在同一端口提供媒体入口,UDP 网关不承担视频任务。
|
||||
*/
|
||||
@RestController
|
||||
@Conditional(WorkerCapabilityCondition.class)
|
||||
public class WorkerController {
|
||||
private final WorkerService worker;
|
||||
|
||||
public WorkerController(WorkerService worker) {
|
||||
this.worker = worker;
|
||||
}
|
||||
|
||||
// 状态快照由服务生成,控制层不读取或修改内部任务集合。
|
||||
@GetMapping("/worker/status")
|
||||
public Object status() {
|
||||
return worker.status();
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出浏览器可直接读取的 MJPEG 流,每个分段是一张完整 JPEG。
|
||||
* 先检查授权再返回成功响应,避免无效地址建立空的长连接。
|
||||
* 不缓存实时画面,防止浏览器复用结束或迁移前的内容。
|
||||
*/
|
||||
@GetMapping("/media/{taskId}/{version}/stream")
|
||||
public ResponseEntity<StreamingResponseBody> stream(
|
||||
@PathVariable String taskId, @PathVariable long version, @RequestParam String key) {
|
||||
worker.frame(taskId, version, key);
|
||||
StreamingResponseBody body = output -> {
|
||||
try {
|
||||
while (true) {
|
||||
// 每帧重新取得当前状态,准备转运行后不再引用旧任务对象。
|
||||
byte[] frame = worker.frame(taskId, version, key);
|
||||
if (frame != null) {
|
||||
String header = "--frame\r\nContent-Type: image/jpeg\r\nContent-Length: "
|
||||
+ frame.length + "\r\n\r\n";
|
||||
output.write(header.getBytes(StandardCharsets.US_ASCII));
|
||||
output.write(frame);
|
||||
output.write("\r\n".getBytes(StandardCharsets.US_ASCII));
|
||||
output.flush();
|
||||
}
|
||||
Thread.sleep(250);
|
||||
}
|
||||
} catch (InterruptedException interrupted) {
|
||||
// 容器关闭线程时保留中断标记,流循环随之结束。
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (IllegalArgumentException inactiveTask) {
|
||||
// 迁移、结束或许可到期后停止旧流,不能继续发送缓存画面。
|
||||
}
|
||||
};
|
||||
return ResponseEntity.ok().cacheControl(CacheControl.noStore())
|
||||
.header("Content-Type", "multipart/x-mixed-replace; boundary=frame").body(body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.xtrh.node.protocol;
|
||||
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.Security;
|
||||
import java.util.Arrays;
|
||||
import java.util.zip.CRC32;
|
||||
|
||||
/**
|
||||
* 按既有 PXHJ-FND/1 图片协议解码,仅允许消息类型 0x12。
|
||||
* 先校验边界、时间、CRC 和 HMAC,再解密 JPG1 分片;协议不是自定义演示格式。
|
||||
* 设备密钥由有效私有任务许可提供,本类不读取配置文件或记录明文密钥。
|
||||
*/
|
||||
public final class ImageWireDecoder {
|
||||
static {
|
||||
if (Security.getProvider("BC") == null) Security.addProvider(new BouncyCastleProvider());
|
||||
}
|
||||
|
||||
private ImageWireDecoder() {}
|
||||
|
||||
// 头部 collectorId 是未认证线索,只可用于缩小候选许可,不能据此接受报文。
|
||||
public static int collectorId(byte[] frame) {
|
||||
return frame.length > 9 ? Byte.toUnsignedInt(frame[9]) : -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 固定头长、密文偏移与 MAC 范围和 PXHJ WireCodec 保持一致。
|
||||
* 不扩展原协议的 1024 字节明文限制,超长 UDP 即使被截断也会拒绝。
|
||||
*/
|
||||
public static byte[] decode(byte[] frame, byte[] sm4, byte[] hmac, int collectorId, long now) throws Exception {
|
||||
require(frame.length >= 109 && frame.length <= 1133);
|
||||
ByteBuffer input = ByteBuffer.wrap(frame).order(ByteOrder.BIG_ENDIAN);
|
||||
require(input.getInt() == 0x5AA5FAFB && input.getInt() == frame.length);
|
||||
require(Byte.toUnsignedInt(input.get()) == 0x12);
|
||||
require(Byte.toUnsignedInt(input.get()) == collectorId);
|
||||
input.get();
|
||||
long time = input.getLong();
|
||||
input.getLong();
|
||||
// 使用上下界而不是 abs 差值,异常 Long 值不能通过溢出绕过时间窗口。
|
||||
require(time >= now - 60_000 && time <= now + 60_000);
|
||||
require(input.get() == 1 && input.get() == 1 && input.getInt() == 1);
|
||||
byte[] iv = new byte[16];
|
||||
input.get(iv);
|
||||
int length = input.getInt();
|
||||
require(length > 0 && length % 16 == 0 && length + 93 == frame.length);
|
||||
int macStart = 53 + length;
|
||||
// CRC 覆盖 MAC 但不含 CRC 自身和帧尾,保持现有设备发送端的精确字节范围。
|
||||
CRC32 crc = new CRC32();
|
||||
crc.update(frame, 0, macStart + 32);
|
||||
require((int) crc.getValue() == ByteBuffer.wrap(frame, macStart + 32, 4).getInt());
|
||||
require(ByteBuffer.wrap(frame, frame.length - 4, 4).getInt() == 0xA55AFCFD);
|
||||
|
||||
// 认证覆盖长度后的协议头、IV 和密文;CRC 只检错,不能替代身份认证。
|
||||
Mac authentication = Mac.getInstance("HMACSM3", "BC");
|
||||
authentication.init(new SecretKeySpec(hmac, "HMACSM3"));
|
||||
authentication.update(frame, 4, macStart - 4);
|
||||
require(MessageDigest.isEqual(authentication.doFinal(), Arrays.copyOfRange(frame, macStart, macStart + 32)));
|
||||
Cipher cipher = Cipher.getInstance("SM4/CBC/PKCS7Padding", "BC");
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(sm4, "SM4"), new IvParameterSpec(iv));
|
||||
byte[] plain = cipher.doFinal(Arrays.copyOfRange(frame, 53, macStart));
|
||||
require(plain.length <= 1024);
|
||||
return plain;
|
||||
}
|
||||
|
||||
// 固定错误消息不含输入报文、密钥或失败的认证摘要。
|
||||
private static void require(boolean valid) {
|
||||
if (!valid) throw new IllegalArgumentException("Invalid authenticated image packet");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
package com.xtrh.node.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.xtrh.common.config.Settings;
|
||||
import com.xtrh.node.config.WorkerCapabilityCondition;
|
||||
import com.xtrh.node.protocol.ImageWireDecoder;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.BitSet;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.LongSupplier;
|
||||
import java.util.zip.CRC32;
|
||||
|
||||
import static com.xtrh.common.util.Jsons.object;
|
||||
|
||||
/**
|
||||
* 节点直接接收设备原图,总控和网关只负责控制,不中转图片字节。
|
||||
* 私有许可只在内存中保存,按任务版本和单调时钟到期,不写入 H2 或公共快照。
|
||||
* 接收队列、分片重组和近期帧都有独立上限;无首帧时不生成替代演示图。
|
||||
*/
|
||||
@Service
|
||||
@Conditional(WorkerCapabilityCondition.class)
|
||||
public class ImageIngressService implements AutoCloseable {
|
||||
// 一个 FND 帧最多承载 1024 字节明文,其中 36 字节属于 JPG1 分片头。
|
||||
// 重组最多 32 帧、64MiB;完整帧缓存另有 64MiB 预算,不随设备持续上传而增长。
|
||||
// 图片解码串行执行,实际尺寸也受限制,压缩 JPEG 不能扩大到任意像素数。
|
||||
public static final int CHUNK_SIZE = 988, MAX_IMAGE_BYTES = 2 * 1024 * 1024;
|
||||
private static final long ASSEMBLY_TTL = TimeUnit.SECONDS.toNanos(5);
|
||||
private static final long MAX_BUFFER_BYTES = 64L * 1024 * 1024;
|
||||
private final Settings settings;
|
||||
private final Integer configuredPort;
|
||||
private final LongSupplier clock, nanos;
|
||||
// 接收线程只投递受限报文,耗时认证、重组和 ImageIO 解码在单个处理线程执行。
|
||||
// 队列最多约 2.2MiB 密文;过载时计数丢弃,让设备后续完整帧恢复画面。
|
||||
private final ArrayBlockingQueue<Packet> queue = new ArrayBlockingQueue<>(2048);
|
||||
private final Map<String, Permit> permits = new HashMap<>();
|
||||
private final Map<String, String> accessErrors = new HashMap<>();
|
||||
private final Map<String, Assembly> pending = new HashMap<>();
|
||||
// 最近帧按任务版本隔离;同来源的多项任务可以引用同一份不可变 JPEG 字节。
|
||||
// 元数据查询后还有两帧容错空间,防止下一次上传立刻淘汰正在取图的帧号。
|
||||
private final Map<String, List<Frame>> recent = new HashMap<>();
|
||||
private final LinkedHashMap<String, Long> completed = new LinkedHashMap<>();
|
||||
private final AtomicLong accepted = new AtomicLong(), rejected = new AtomicLong(), dropped = new AtomicLong();
|
||||
private volatile DatagramSocket socket;
|
||||
private volatile boolean closed;
|
||||
private volatile String error = "";
|
||||
private long retryAfter, pendingBytes;
|
||||
|
||||
// 来源地址由 UDP socket 提供,不能从设备载荷中的自报字段推导。
|
||||
// Permit 包含集群私有计划给出的设备密钥,不能直接序列化为对外状态。
|
||||
// Assembly 的 group 含来源与密钥摘要,避免密钥轮换后拼接旧许可的在途分片。
|
||||
private record Packet(byte[] bytes, InetSocketAddress source) {}
|
||||
private record Permit(String task, String endpoint, InetAddress source, int collector,
|
||||
byte[] sm4, byte[] hmac, String group, long deadline) {}
|
||||
private record Assembly(String group, long frame, long time, int size, int count, int crc,
|
||||
int width, int height, long created, byte[] data, BitSet seen) {}
|
||||
|
||||
/** 原图不可变视图;公开元数据不包含设备认证材料或网络路由许可。 */
|
||||
public record Frame(String frameId, String endpointId, long sourceTime, long receivedTime,
|
||||
int width, int height, byte[] jpeg, long receivedNanos) {
|
||||
public ObjectNode metadata() {
|
||||
return object().put("frameId", frameId).put("endpointId", endpointId)
|
||||
.put("sourceTime", sourceTime).put("receivedTime", receivedTime)
|
||||
.put("width", width).put("height", height).put("bytes", jpeg.length);
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public ImageIngressService(Settings settings, Environment environment) {
|
||||
this(settings, environment.getProperty("fusion.image-port", Integer.class), System::currentTimeMillis, System::nanoTime);
|
||||
}
|
||||
|
||||
public ImageIngressService(Settings settings, int imagePort) {
|
||||
this(settings, imagePort, System::currentTimeMillis, System::nanoTime);
|
||||
}
|
||||
|
||||
ImageIngressService(Settings settings, Integer port, LongSupplier clock, LongSupplier nanos) {
|
||||
// 注入两种时钟只为确定性测试;生产授权始终以单调时钟判断到期。
|
||||
// 墙上时间负责设备拍摄时间窗,不能用于延长任务或在途分片的寿命。
|
||||
this.settings = settings;
|
||||
this.configuredPort = port;
|
||||
this.clock = clock;
|
||||
this.nanos = nanos;
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认使用真实 HTTP 端口+1000;等待 HTTP 就绪,不能把配置中的随机端口 0 当实际端口。
|
||||
* 显式图片端口 0 由操作系统分配,便于隔离测试,也会登记实际绑定结果。
|
||||
*/
|
||||
public synchronized boolean ensureStarted() {
|
||||
if (closed || socket != null) return socket != null && !socket.isClosed();
|
||||
if (configuredPort == null && !settings.httpReady()) return false;
|
||||
if (clock.getAsLong() < retryAfter) return false;
|
||||
int port = configuredPort == null ? settings.port + 1000 : configuredPort;
|
||||
DatagramSocket opened = null;
|
||||
try {
|
||||
if (port < 0 || port > 65535) throw new IllegalArgumentException();
|
||||
// 不启用复用地址,部署端口冲突应明确失败,不能让多个节点抢收同一批分片。
|
||||
// 绑定地址遵守该角色原有配置,登记时另行选择设备可达的 IPv4 网卡地址。
|
||||
opened = new DatagramSocket(null);
|
||||
opened.setReceiveBufferSize(4 * 1024 * 1024);
|
||||
opened.bind(new InetSocketAddress(settings.bindHost, port));
|
||||
socket = opened;
|
||||
daemon("xtrh-original-receive", this::receive);
|
||||
daemon("xtrh-original-assemble", this::process);
|
||||
error = "";
|
||||
return true;
|
||||
} catch (Exception failure) {
|
||||
// 失败保持未就绪并有限重试;错误信息不带异常报文、设备密钥或明文图片。
|
||||
// 未成功绑定的 socket 及时释放,启动失败不会泄漏后续可重试的系统资源。
|
||||
if (opened != null) opened.close();
|
||||
error = "原图监听未就绪,请检查图片端口和绑定地址";
|
||||
retryAfter = clock.getAsLong() + 1500;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收与组装只在成功绑定后启动,重试监听不会重复建立工作线程。
|
||||
* 使用守护线程并配合 closed/socket.close,让服务退出不等待设备关闭连接。
|
||||
*/
|
||||
private static void daemon(String name, Runnable body) {
|
||||
Thread thread = new Thread(body, name);
|
||||
thread.setDaemon(true);
|
||||
thread.start();
|
||||
}
|
||||
|
||||
public int inputPort() {
|
||||
// 登记的是操作系统实际分配端口,显式配置 0 也不能上报为未知目的端口。
|
||||
// 服务关闭后返回 0,后续心跳不能继续向总控承诺已失效的接入能力。
|
||||
DatagramSocket current = socket;
|
||||
return current == null || current.isClosed() ? 0 : current.getLocalPort();
|
||||
}
|
||||
|
||||
// 多余一字节用于拒绝超长包;队列满时计数丢弃,不能无限缓存密文。
|
||||
private void receive() {
|
||||
while (!closed) {
|
||||
try {
|
||||
DatagramPacket packet = new DatagramPacket(new byte[1134], 1134);
|
||||
socket.receive(packet);
|
||||
// 复制准确报文长度,不能把复用缓冲区剩余字节带入 CRC 和 HMAC 校验。
|
||||
Packet work = new Packet(Arrays.copyOf(packet.getData(), packet.getLength()),
|
||||
(InetSocketAddress) packet.getSocketAddress());
|
||||
if (!queue.offer(work)) dropped.incrementAndGet();
|
||||
} catch (Exception failure) {
|
||||
if (!closed) rejected.incrementAndGet();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 单个组装线程使图片解码并发和临时内存有界;失败不终止其他通道接收。
|
||||
private void process() {
|
||||
// 接收线程不等待 JPEG 解码;独立队列隔离慢图片,避免 UDP socket 长时间无人读取。
|
||||
// 停机关闭 socket 后接收线程退出;处理线程最多等待一次受限 poll 即结束。
|
||||
while (!closed) {
|
||||
try {
|
||||
Packet packet = queue.poll(1, TimeUnit.SECONDS);
|
||||
if (packet != null) accept(packet);
|
||||
} catch (InterruptedException stopped) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 完整计划替换许可;未再列出的版本立即删除帧和在途分片。
|
||||
* 同版本状态由准备变为运行时保留原图,避免元数据查询后 JPEG 被状态切换清除。
|
||||
*/
|
||||
public synchronized void applyPlans(JsonNode entries, long deadline) {
|
||||
// 总控发送完整而非增量计划;任何未列出的许可都应撤销,不能靠旧缓存继续授权。
|
||||
// 新表构建完成后一次替换,状态查询、组装和许可回收共享此同步边界。
|
||||
Map<String, Permit> next = new HashMap<>();
|
||||
accessErrors.clear();
|
||||
for (JsonNode entry : entries) {
|
||||
if (!entry.path("mediaKind").asText().equals("ORIGINAL_IMAGE")) continue;
|
||||
String task = taskKey(entry.path("taskId").asText(), entry.path("assignment").path("version").asLong());
|
||||
try {
|
||||
if (next.size() >= 128) throw new IllegalArgumentException();
|
||||
JsonNode access = entry.path("imageAccess");
|
||||
String endpoint = access.path("endpointId").asText();
|
||||
if (endpoint.isBlank() || endpoint.length() > 200) throw new IllegalArgumentException();
|
||||
if (entry.path("taskId").asText().isBlank() || !entry.path("assignment").path("version").isIntegralNumber()
|
||||
|| !entry.path("assignment").path("version").canConvertToLong() || entry.path("assignment").path("version").asLong() < 1) throw new IllegalArgumentException();
|
||||
InetAddress source = numericIpv4(access.path("sourceHost").asText());
|
||||
// 编号严格要求整数和单字节范围,禁止大整数截断后命中另一个采集器。
|
||||
// 同一条私有许可还需与公共来源字段一致,防止内部上下文混配到其他装备。
|
||||
JsonNode collectorValue = access.path("collectorId");
|
||||
if (!collectorValue.isIntegralNumber() || !collectorValue.canConvertToInt()) throw new IllegalArgumentException();
|
||||
int collector = collectorValue.asInt();
|
||||
byte[] sm4 = Base64.getDecoder().decode(access.path("sm4Key").asText());
|
||||
byte[] hmac = Base64.getDecoder().decode(access.path("hmacKey").asText());
|
||||
// HMAC 密钥长度与既有采集端兼容为 32..64 字节,SM4 固定 128 位。
|
||||
// Base64 只是私有 JSON 传输编码,不能被当作脱敏或公开发布依据。
|
||||
if (sm4.length != 16 || hmac.length < 32 || hmac.length > 64 || collector < 1 || collector > 255) throw new IllegalArgumentException();
|
||||
if (entry.hasNonNull("sourceEndpointId") && !endpoint.equals(entry.path("sourceEndpointId").asText())) throw new IllegalArgumentException();
|
||||
if (entry.has("collectorId") && (!entry.path("collectorId").isIntegralNumber()
|
||||
|| !entry.path("collectorId").canConvertToInt() || collector != entry.path("collectorId").asInt())) throw new IllegalArgumentException();
|
||||
if (entry.hasNonNull("sourceHost") && !source.equals(numericIpv4(entry.path("sourceHost").asText()))) throw new IllegalArgumentException();
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
// 分组摘要只作内部缓存键,不作为网络认证或向外返回的设备身份。
|
||||
// 同 endpoint/IP/collector/密钥的多个任务共享重组,仍分别检查自己的租约。
|
||||
digest.update(sm4);
|
||||
String group = endpoint + "/" + source.getHostAddress() + "/" + collector + "/"
|
||||
+ HexFormat.of().formatHex(digest.digest(hmac));
|
||||
Permit permit = new Permit(task, endpoint, source, collector, sm4, hmac, group, deadline);
|
||||
// 同版本的授权来源变化也清除旧帧,不能把前一台设备的缓存交给新的连接。
|
||||
Permit old = permits.get(task);
|
||||
if (old != null && !old.group.equals(group)) recent.remove(task);
|
||||
next.put(task, permit);
|
||||
} catch (Exception invalid) {
|
||||
// 只暴露固定原因,Base64 解码器或异常对象中的密钥不进入日志、状态或快照。
|
||||
accessErrors.put(task, "原图接入许可无效");
|
||||
}
|
||||
}
|
||||
permits.clear();
|
||||
permits.putAll(next);
|
||||
cleanup();
|
||||
}
|
||||
|
||||
public static String taskKey(String id, long version) { return id + "/" + version; }
|
||||
|
||||
// 接入许可只接受字面 IPv4,空字符串和域名不能借 DNS 解析改变授权来源。
|
||||
private static InetAddress numericIpv4(String host) throws Exception {
|
||||
// 手工核对四个十进制段,拒绝 DNS、缩写地址、八进制和超出单字节范围的值。
|
||||
// 回环地址可用于隔离测试;泛地址、组播和广播不属于可授权的设备来源。
|
||||
String[] parts = host.split("\\.", -1);
|
||||
require(parts.length == 4);
|
||||
byte[] address = new byte[4];
|
||||
for (int index = 0; index < 4; index++) {
|
||||
require(parts[index].matches("0|[1-9][0-9]{0,2}"));
|
||||
int value = Integer.parseInt(parts[index]);
|
||||
require(value <= 255);
|
||||
address[index] = (byte) value;
|
||||
}
|
||||
InetAddress parsed = InetAddress.getByAddress(address);
|
||||
require(!parsed.isAnyLocalAddress() && !parsed.isMulticastAddress() && !host.equals("255.255.255.255"));
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** 端口与许可先就绪,不等首帧,以免设备等待地址、节点等待首帧形成协商循环。 */
|
||||
public synchronized boolean ready(String task) {
|
||||
cleanup();
|
||||
return inputPort() > 0 && permits.containsKey(task);
|
||||
}
|
||||
|
||||
public synchronized String accessError(String task) { return accessErrors.getOrDefault(task, ""); }
|
||||
|
||||
/** 新鲜度同时检查拍摄时间和单调接收时间,延迟或重放旧图不能完成迁移接管。 */
|
||||
public synchronized boolean imageReady(String task) {
|
||||
// 新图只在来源时间和接收时间都新鲜时可完成迁移,旧图不能靠再次查询恢复活性。
|
||||
// 最近帧缓存并不等同于视频在线,业务界面应使用 lastFrameTime 判断拍摄时刻。
|
||||
Frame frame = latest(task);
|
||||
return frame != null && clock.getAsLong() - frame.sourceTime <= 5000
|
||||
&& clock.getAsLong() >= frame.sourceTime - 5000
|
||||
&& nanos.getAsLong() - frame.receivedNanos <= ASSEMBLY_TTL;
|
||||
}
|
||||
|
||||
public synchronized Frame latest(String task) {
|
||||
// 最新元数据与具体帧内容分开取,但始终在每次读取之前回收失效许可。
|
||||
// 许可有效时保留近期原图;imageReady 另行表达是否五秒内有新鲜画面。
|
||||
cleanup();
|
||||
List<Frame> frames = recent.get(task);
|
||||
return frames == null || frames.isEmpty() ? null : frames.get(0);
|
||||
}
|
||||
|
||||
public synchronized Frame frame(String task, String id) {
|
||||
// 帧号只在所属任务的近期缓存中查找,不能跨任务或分配版本借用其他装备原图。
|
||||
cleanup();
|
||||
return recent.getOrDefault(task, List.of()).stream().filter(frame -> frame.frameId.equals(id)).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
// 许可到期和分片超时用单调时钟;校时不延长执行或组装寿命。
|
||||
private void cleanup() {
|
||||
long now = nanos.getAsLong();
|
||||
permits.values().removeIf(permit -> now >= permit.deadline);
|
||||
recent.keySet().removeIf(task -> !permits.containsKey(task));
|
||||
Set<String> groups = new HashSet<>();
|
||||
// 仅当同来源分组仍有有效任务时保留在途分片,撤销一路不会误停共享的其他任务。
|
||||
// 任务全部撤销或超时后立即归还预算,不需要等待设备再发包才释放内存。
|
||||
permits.values().forEach(permit -> groups.add(permit.group));
|
||||
var iterator = pending.values().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Assembly assembly = iterator.next();
|
||||
if (!groups.contains(assembly.group) || now - assembly.created > ASSEMBLY_TTL) {
|
||||
pendingBytes -= assembly.size;
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
completed.entrySet().removeIf(entry -> now - entry.getValue() > ASSEMBLY_TTL);
|
||||
}
|
||||
|
||||
private void accept(Packet packet) {
|
||||
try {
|
||||
// 来源 IP 与 collectorId 先匹配许可,再执行密钥认证,未授权来源不尝试解密。
|
||||
List<Permit> matches;
|
||||
synchronized (this) {
|
||||
cleanup();
|
||||
matches = permits.values().stream().filter(permit -> permit.source.equals(packet.source.getAddress())
|
||||
&& permit.collector == ImageWireDecoder.collectorId(packet.bytes)).toList();
|
||||
}
|
||||
Map<String, Permit> groups = new LinkedHashMap<>();
|
||||
// 密钥轮换期间允许尝试多个明确授权的候选;同一分组只认证一次。
|
||||
// 只有唯一来源成功认证才组装,不能用未知来源的 packet header 直接发布图片。
|
||||
matches.forEach(permit -> groups.putIfAbsent(permit.group, permit));
|
||||
Permit authenticated = null;
|
||||
byte[] plain = null;
|
||||
for (Permit permit : groups.values()) {
|
||||
// 逐个候选先验 MAC 再解密;报文 CRC 正确也不足以证明持有设备密钥。
|
||||
try {
|
||||
byte[] candidate = ImageWireDecoder.decode(packet.bytes, permit.sm4, permit.hmac, permit.collector, clock.getAsLong());
|
||||
if (authenticated != null) throw new IllegalStateException("Ambiguous image source");
|
||||
authenticated = permit;
|
||||
plain = candidate;
|
||||
} catch (IllegalStateException ambiguity) { throw ambiguity; }
|
||||
catch (Exception wrongCredential) { /* 同来源密钥轮换时可尝试另一个已授权候选。 */ }
|
||||
}
|
||||
if (authenticated == null) throw new IllegalArgumentException();
|
||||
assemble(authenticated, plain);
|
||||
accepted.incrementAndGet();
|
||||
} catch (Exception invalid) {
|
||||
rejected.incrementAndGet();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JPG1 头为36字节,988字节分片;严格核对同帧参数和重复片内容。
|
||||
* 完整 CRC、JPEG 标记、实际解码尺寸均通过后才发布,缺片永远不会成为可见图片。
|
||||
*/
|
||||
private synchronized void assemble(Permit authenticated, byte[] plain) throws Exception {
|
||||
cleanup();
|
||||
// 包从队列取出到完成认证之间可能已撤销任务,组装前再次确认来源许可仍存在。
|
||||
if (permits.values().stream().noneMatch(permit -> permit.group.equals(authenticated.group))) throw new IllegalArgumentException();
|
||||
require(plain.length > 36 && plain.length <= 1024);
|
||||
ByteBuffer input = ByteBuffer.wrap(plain).order(ByteOrder.BIG_ENDIAN);
|
||||
require(input.getInt() == 0x4A504731);
|
||||
long wireFrame = input.getLong(), time = input.getLong();
|
||||
int size = input.getInt(), index = Short.toUnsignedInt(input.getShort()), count = Short.toUnsignedInt(input.getShort());
|
||||
int crc = input.getInt(), width = Short.toUnsignedInt(input.getShort()), height = Short.toUnsignedInt(input.getShort());
|
||||
long now = clock.getAsLong();
|
||||
require(time >= now - 60_000 && time <= now + 60_000);
|
||||
require(size > 3 && size <= MAX_IMAGE_BYTES && count == (size + CHUNK_SIZE - 1) / CHUNK_SIZE && index < count);
|
||||
require(width > 0 && width <= 4096 && height > 0 && height <= 4096);
|
||||
// 每片实际长度必须与图片大小推导结果一致;缺片、尾片越界和额外字节均拒绝。
|
||||
// 不通过扩容补齐异常分片,固定一次分配的 buffer 使每帧预算可准确核算。
|
||||
int offset = index * CHUNK_SIZE, bytes = Math.min(CHUNK_SIZE, size - offset);
|
||||
require(input.remaining() == bytes);
|
||||
String key = authenticated.group + "/" + Long.toUnsignedString(wireFrame) + "/" + time;
|
||||
if (completed.containsKey(key)) return;
|
||||
// 已发布帧的短期重复上传只作幂等确认,不生成新帧号或刷新图片新鲜度。
|
||||
Assembly assembly = pending.get(key);
|
||||
if (assembly == null) {
|
||||
require(pending.size() < 32 && pendingBytes + size <= MAX_BUFFER_BYTES);
|
||||
assembly = new Assembly(authenticated.group, wireFrame, time, size, count, crc, width, height,
|
||||
nanos.getAsLong(), new byte[size], new BitSet(count));
|
||||
pending.put(key, assembly);
|
||||
pendingBytes += size;
|
||||
}
|
||||
require(assembly.time == time && assembly.size == size && assembly.count == count
|
||||
&& assembly.crc == crc && assembly.width == width && assembly.height == height);
|
||||
if (assembly.seen.get(index)) {
|
||||
// 正常 UDP 重复包允许;同索引携带不同内容属于冲突,不能覆盖已接收的部分图。
|
||||
for (int i = 0; i < bytes; i++) require(assembly.data[offset + i] == plain[36 + i]);
|
||||
return;
|
||||
}
|
||||
input.get(assembly.data, offset, bytes);
|
||||
assembly.seen.set(index);
|
||||
if (assembly.seen.cardinality() != count) return;
|
||||
pending.remove(key);
|
||||
pendingBytes -= size;
|
||||
// 接收所有片只是必要条件,完整 JPEG 的 CRC 与图片格式仍需独立验证。
|
||||
// 丢弃完整但损坏的图片之后释放其重组预算,后续帧继续正常接入。
|
||||
CRC32 checksum = new CRC32();
|
||||
checksum.update(assembly.data);
|
||||
require((int) checksum.getValue() == crc);
|
||||
require(Byte.toUnsignedInt(assembly.data[0]) == 255 && Byte.toUnsignedInt(assembly.data[1]) == 216
|
||||
&& Byte.toUnsignedInt(assembly.data[size - 2]) == 255 && Byte.toUnsignedInt(assembly.data[size - 1]) == 217);
|
||||
validateJpeg(assembly.data, width, height);
|
||||
|
||||
// 同来源多任务共享只读帧对象;任务版本仍各有许可,撤销其中一路不影响其他有效任务。
|
||||
Frame frame = new Frame(java.util.UUID.randomUUID().toString(), authenticated.endpoint, time, now,
|
||||
width, height, assembly.data, nanos.getAsLong());
|
||||
for (Permit permit : permits.values()) {
|
||||
if (!permit.group.equals(authenticated.group)) continue;
|
||||
List<Frame> frames = new ArrayList<>(recent.getOrDefault(permit.task, List.of()));
|
||||
frames.add(frame);
|
||||
frames.sort(Comparator.comparingLong(Frame::sourceTime).thenComparingLong(Frame::receivedTime).reversed());
|
||||
if (frames.size() > 3) frames = new ArrayList<>(frames.subList(0, 3));
|
||||
recent.put(permit.task, frames);
|
||||
}
|
||||
completed.put(key, nanos.getAsLong());
|
||||
// 去重索引本身也受数量限制,长期上传不会累积无限历史帧号。
|
||||
while (completed.size() > 1024) completed.remove(completed.keySet().iterator().next());
|
||||
trimFrames();
|
||||
}
|
||||
|
||||
// 先读取实际尺寸再解码,不能相信分片头伪造的小尺寸放任解压大图。
|
||||
private static void validateJpeg(byte[] data, int width, int height) throws Exception {
|
||||
try (var input = ImageIO.createImageInputStream(new ByteArrayInputStream(data))) {
|
||||
// ImageReader 先读取 JPEG 内真实尺寸,再作完整解码,头部谎报小图不能绕过像素限制。
|
||||
// 正确标记和 CRC 不能证明压缩数据可解码,因此仍需要解码确认图片结构完整。
|
||||
var readers = ImageIO.getImageReaders(input);
|
||||
require(readers.hasNext());
|
||||
var reader = readers.next();
|
||||
try {
|
||||
reader.setInput(input);
|
||||
require(reader.getFormatName().equalsIgnoreCase("JPEG") && reader.getWidth(0) == width && reader.getHeight(0) == height);
|
||||
require(reader.read(0) != null);
|
||||
} finally { reader.dispose(); }
|
||||
}
|
||||
}
|
||||
|
||||
// 每任务保留最近3帧供元数据/取图竞争;总缓存预算不足时淘汰最旧引用并返回明确404。
|
||||
private void trimFrames() {
|
||||
// 预算按缓存引用计数,共享 JPEG 也保守计入;实际保留内存不会大于计算结果。
|
||||
// 容量不足允许提前淘汰旧图,HTTP 接口用 404 明确表达帧已不在缓存。
|
||||
long bytes = recent.values().stream().flatMap(List::stream).mapToLong(frame -> frame.jpeg.length).sum();
|
||||
while (bytes > MAX_BUFFER_BYTES) {
|
||||
// 淘汰按单调接收顺序选择,系统校时不会颠倒缓存内存的释放顺序。
|
||||
String owner = null;
|
||||
Frame oldest = null;
|
||||
for (var entry : recent.entrySet()) for (Frame frame : entry.getValue()) {
|
||||
if (oldest == null || frame.receivedNanos < oldest.receivedNanos) { owner = entry.getKey(); oldest = frame; }
|
||||
}
|
||||
if (oldest == null) return;
|
||||
recent.get(owner).remove(oldest);
|
||||
bytes -= oldest.jpeg.length;
|
||||
}
|
||||
}
|
||||
|
||||
private static void require(boolean valid) { if (!valid) throw new IllegalArgumentException("Invalid original image fragment"); }
|
||||
|
||||
@Scheduled(fixedDelay = 250)
|
||||
// 独立定时清理保证设备静默时也释放到期任务,不依赖下一次 UDP 包触发回收。
|
||||
public synchronized void tick() { ensureStarted(); cleanup(); }
|
||||
|
||||
public synchronized ObjectNode status() {
|
||||
// 仅输出计数和接入能力,permit、source keys 和私有计划不进入工作节点状态。
|
||||
cleanup();
|
||||
return object().put("imageInputPort", inputPort()).put("running", inputPort() > 0).put("error", error)
|
||||
.put("accepted", accepted.get()).put("rejected", rejected.get()).put("queueDrops", dropped.get())
|
||||
.put("pending", pending.size()).put("bufferedBytes", pendingBytes).put("authorizedTasks", permits.size());
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
@Override
|
||||
public synchronized void close() {
|
||||
// 停机立即撤销所有接入授权与缓存,不持久化恢复设备密钥或已结束任务的原图。
|
||||
// close 可重复调用,测试和 Spring 容器都可以可靠释放动态 UDP 端口。
|
||||
closed = true;
|
||||
if (socket != null) socket.close();
|
||||
queue.clear();
|
||||
permits.clear();
|
||||
accessErrors.clear();
|
||||
pending.clear();
|
||||
recent.clear();
|
||||
completed.clear();
|
||||
pendingBytes = 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
package com.xtrh.node.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.xtrh.common.config.Settings;
|
||||
import com.xtrh.communication.client.PeerClient;
|
||||
import com.xtrh.discovery.service.CoordinatorLocator;
|
||||
import com.xtrh.discovery.util.NodeAddress;
|
||||
import com.xtrh.node.config.WorkerCapabilityCondition;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
import java.awt.GradientPaint;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.net.InetAddress;
|
||||
import java.net.Inet4Address;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.xtrh.common.util.Jsons.object;
|
||||
|
||||
/**
|
||||
* 融合节点的业务服务:自动注册、领取许可、准备画面并报告就绪。
|
||||
* 节点只执行总控分配的任务,不自行决定试验轮次或占用路数。
|
||||
* 演示任务生成验证画面;原图任务只提供设备上传的真实 JPEG。
|
||||
*/
|
||||
@Service
|
||||
@Conditional(WorkerCapabilityCondition.class)
|
||||
public class WorkerService {
|
||||
/**
|
||||
* 一个分配版本的本地运行状态,集中保存在服务内部。
|
||||
* 同一任务迁移后使用新版本,旧播放地址不能访问新任务。
|
||||
* 画面与许可由定时处理更新,volatile 保证播放线程及时可见。
|
||||
*/
|
||||
public static final class MediaTask {
|
||||
final String taskId, key, name, trialName, desired, mediaKind;
|
||||
final long version;
|
||||
volatile byte[] jpeg;
|
||||
volatile long deadlineNanos;
|
||||
|
||||
MediaTask(JsonNode plan) {
|
||||
taskId = plan.path("taskId").asText();
|
||||
version = plan.path("assignment").path("version").asLong();
|
||||
key = plan.path("assignment").path("mediaKey").asText();
|
||||
name = plan.path("name").asText();
|
||||
trialName = plan.path("trialName").asText();
|
||||
desired = plan.path("desired").asText();
|
||||
mediaKind = plan.path("mediaKind").asText("DEMO_VIDEO");
|
||||
}
|
||||
|
||||
// 使用单调时钟,电脑调整系统时间不会延长任务执行许可。
|
||||
boolean valid() {
|
||||
return System.nanoTime() < deadlineNanos;
|
||||
}
|
||||
}
|
||||
|
||||
private final Settings settings;
|
||||
private final CoordinatorLocator locator;
|
||||
private final PeerClient peer;
|
||||
private final ImageIngressService images;
|
||||
// 心跳、画面生成和 HTTP 播放会同时访问任务,键包含任务号及分配版本。
|
||||
private final ConcurrentMap<String, MediaTask> tasks = new ConcurrentHashMap<>();
|
||||
private volatile String session = "", connection = "WAITING";
|
||||
// 发现失败后的重试间隔只影响联网操作,不改变已经领取的许可期限。
|
||||
private long retryAfter;
|
||||
private int registeredImagePort = -1;
|
||||
|
||||
public WorkerService(Settings settings, CoordinatorLocator locator, PeerClient peer) {
|
||||
this(settings, locator, peer, null);
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public WorkerService(Settings settings, CoordinatorLocator locator, PeerClient peer, ImageIngressService images) {
|
||||
// 正式服务注入原图接入端;兼容构造保留现有演示测试,避免额外启动 UDP。
|
||||
// 演示和原图分别有画面来源,不能因为接入失败向 PXHJ 返回伪造的替代图片。
|
||||
this.settings = settings;
|
||||
this.locator = locator;
|
||||
this.peer = peer;
|
||||
this.images = images;
|
||||
}
|
||||
|
||||
/**
|
||||
* 先移除过期任务,再发现总控、注册并领取最新分配。
|
||||
* 原图先报告接入就绪供设备协商地址,再单独报告新鲜首帧决定迁移接管。
|
||||
* 心跳异常时保留尚未到期的任务,超过许可期限后自动停止播放。
|
||||
*/
|
||||
@Scheduled(fixedDelay = 700)
|
||||
public void heartbeat() {
|
||||
tasks.entrySet().removeIf(entry -> !entry.getValue().valid());
|
||||
if (System.currentTimeMillis() < retryAfter) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (images != null) images.ensureStarted();
|
||||
String coordinator = locator.locate();
|
||||
registerIfNeeded(coordinator);
|
||||
ObjectNode input = readinessReport();
|
||||
// 从发出请求的时刻计算许可,不能把网络等待时间额外算作授权。
|
||||
long requestedAt = System.nanoTime();
|
||||
JsonNode plan = peer.request(coordinator,
|
||||
"/control/nodes/" + settings.id + "/heartbeat", "POST", input);
|
||||
long deadline = requestedAt + TimeUnit.MILLISECONDS.toNanos(plan.path("leaseMs").asLong());
|
||||
if (System.nanoTime() >= deadline) {
|
||||
throw new IllegalStateException("Expired task plan");
|
||||
}
|
||||
applyPlan(plan, deadline);
|
||||
connection = "CONNECTED";
|
||||
} catch (Exception failure) {
|
||||
// 下次重新发现与注册;旧会话不会跨总控重启或连接故障继续复用。
|
||||
session = "";
|
||||
locator.disconnect();
|
||||
connection = "WAITING";
|
||||
retryAfter = System.currentTimeMillis() + 1500;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 持久节点标识区分电脑,本次 bootId 区分同一电脑的不同启动。
|
||||
* 会话由总控返回,后续心跳继续证明当前启动的身份。
|
||||
* 对外地址按与总控通信的网卡确定,避免上报不可达的回环地址。
|
||||
*/
|
||||
private void registerIfNeeded(String coordinator) throws Exception {
|
||||
int imagePort = images == null ? 0 : images.inputPort();
|
||||
if (!session.isEmpty() && registeredImagePort == imagePort) {
|
||||
return;
|
||||
}
|
||||
ObjectNode registration = object().put("clusterId", settings.cluster)
|
||||
.put("nodeId", settings.id).put("bootId", settings.bootId)
|
||||
// 主执行端复用总控身份和同一 HTTP 端口,加入同一调度池而不额外复制节点。
|
||||
.put("nodeRole", settings.role.equals("coordinator") ? "COORDINATOR" : "WORKER")
|
||||
.put("name", settings.name).put("capacity", settings.capacity)
|
||||
.put("baseUrl", NodeAddress.url(settings, coordinator));
|
||||
// 图片直达节点 UDP 端口;控制与浏览器媒体接口仍复用现有 HTTP 端口。
|
||||
// 广播和注册中只有地址与能力,设备 SM4/HMAC 密钥只存在私有任务计划。
|
||||
if (images != null && imagePort > 0) {
|
||||
String host = NodeAddress.host(settings, coordinator);
|
||||
String ipv4 = java.util.Arrays.stream(InetAddress.getAllByName(host))
|
||||
.filter(address -> address instanceof Inet4Address).map(InetAddress::getHostAddress)
|
||||
.findFirst().orElseThrow(() -> new IllegalStateException("Image input requires IPv4"));
|
||||
registration.put("imageHost", ipv4).put("imageInputPort", imagePort);
|
||||
}
|
||||
JsonNode result = peer.request(coordinator, "/control/nodes/register", "POST", registration);
|
||||
session = result.path("sessionId").asText();
|
||||
registeredImagePort = imagePort;
|
||||
}
|
||||
|
||||
// 没有生成首帧或许可已经过期时,不向总控承诺该任务可播放。
|
||||
// 就绪报告带分配版本,旧节点的迟到报告不能确认新版本的迁移。
|
||||
private ObjectNode readinessReport() {
|
||||
// 每个仍有效分配都报告接入和画面状态,包括迁移中的 active 与 candidate。
|
||||
ObjectNode input = object().put("sessionId", session).put("bootId", settings.bootId);
|
||||
ArrayNode reports = input.putArray("reports");
|
||||
for (MediaTask task : tasks.values()) {
|
||||
if (!task.valid()) continue;
|
||||
ObjectNode report = object().put("taskId", task.taskId).put("version", task.version);
|
||||
if (task.mediaKind.equals("ORIGINAL_IMAGE")) {
|
||||
String id = ImageIngressService.taskKey(task.taskId, task.version);
|
||||
report.put("ready", images != null && images.ready(id))
|
||||
.put("imageReady", images != null && images.imageReady(id));
|
||||
if (images != null) {
|
||||
ImageIngressService.Frame frame = images.latest(id);
|
||||
if (frame != null) report.put("lastFrameId", frame.frameId()).put("lastFrameTime", frame.sourceTime());
|
||||
if (!images.accessError(id).isEmpty()) report.put("error", images.accessError(id));
|
||||
}
|
||||
reports.add(report);
|
||||
} else if (task.jpeg != null) reports.add(report.put("ready", true));
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
/**
|
||||
* 完整计划决定本机应保留哪些分配,未列出的任务及时释放。
|
||||
* 首次领取或准备转运行时,先生成首帧再发布新的任务对象。
|
||||
* 同版本播放连接按键读取当前对象,状态切换不会绑死在旧对象上。
|
||||
*/
|
||||
private void applyPlan(JsonNode plan, long deadline) throws Exception {
|
||||
// 完整计划先替换接入许可,撤销任务时连同在途分片和旧图一并释放。
|
||||
// 原图接入不等待上传,否则设备将拿不到目标地址而无法发送首帧。
|
||||
if (images != null) images.applyPlans(plan.path("tasks"), deadline);
|
||||
Set<String> present = new HashSet<>();
|
||||
for (JsonNode entry : plan.path("tasks")) {
|
||||
String id = entry.path("taskId").asText() + "/"
|
||||
+ entry.path("assignment").path("version").asLong();
|
||||
present.add(id);
|
||||
MediaTask old = tasks.get(id);
|
||||
if (old == null || !old.desired.equals(entry.path("desired").asText())
|
||||
|| !old.mediaKind.equals(entry.path("mediaKind").asText("DEMO_VIDEO"))) {
|
||||
MediaTask fresh = new MediaTask(entry);
|
||||
fresh.deadlineNanos = deadline;
|
||||
if (!fresh.mediaKind.equals("ORIGINAL_IMAGE")) fresh.jpeg = render(fresh);
|
||||
tasks.put(id, fresh);
|
||||
} else {
|
||||
old.deadlineNanos = deadline;
|
||||
}
|
||||
}
|
||||
tasks.keySet().removeIf(id -> !present.contains(id));
|
||||
}
|
||||
|
||||
// 一路画面生成失败保留其上次成功帧,其他通道仍继续刷新。
|
||||
// 许可检查独立于画面生成;缓存帧不能让已过期任务继续提供视频。
|
||||
@Scheduled(fixedDelay = 250)
|
||||
public void frames() {
|
||||
for (MediaTask task : tasks.values()) {
|
||||
if (task.valid() && !task.mediaKind.equals("ORIGINAL_IMAGE")) {
|
||||
try {
|
||||
task.jpeg = render(task);
|
||||
} catch (Exception ignored) {
|
||||
// 保持最后一帧,等待下一次定时生成重试。
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 播放必须同时满足任务号、分配版本、访问密钥及有效许可。
|
||||
* 密钥采用固定时间比较,避免直接字符串比较泄露匹配前缀。
|
||||
* 该校验每帧执行,任务撤销或许可失效可终止已经打开的连接。
|
||||
*/
|
||||
public MediaTask playable(String taskId, long version, String key) {
|
||||
MediaTask task = tasks.get(taskId + "/" + version);
|
||||
if (task == null || !task.valid() || key == null
|
||||
|| !MessageDigest.isEqual(task.key.getBytes(StandardCharsets.UTF_8),
|
||||
key.getBytes(StandardCharsets.UTF_8))) {
|
||||
throw new IllegalArgumentException("Video task is not active");
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
// 控制层只取得当前授权帧,任务对象与其可变状态由服务层管理。
|
||||
public byte[] frame(String taskId, long version, String key) {
|
||||
MediaTask task = playable(taskId, version, key);
|
||||
if (!task.mediaKind.equals("ORIGINAL_IMAGE")) return task.jpeg;
|
||||
ImageIngressService.Frame frame = originalFrame(taskId, version, null);
|
||||
return frame == null ? null : frame.jpeg();
|
||||
}
|
||||
|
||||
/**
|
||||
* 私有原图接口由服务 HMAC 鉴权,另逐次检查分配版本和租约。
|
||||
* 元数据和 JPEG 之间允许短暂并发,用不透明帧号锁定近期真实帧。
|
||||
* 无图返回 null,不能回退到演示画面或其他装备的图片。
|
||||
*/
|
||||
public ImageIngressService.Frame originalFrame(String taskId, long version, String frameId) {
|
||||
// 服务认证只证明调用者身份,不能代替本次任务的版本与执行许可检查。
|
||||
MediaTask task = tasks.get(ImageIngressService.taskKey(taskId, version));
|
||||
if (task == null || !task.valid() || !task.mediaKind.equals("ORIGINAL_IMAGE") || images == null) return null;
|
||||
String id = ImageIngressService.taskKey(taskId, version);
|
||||
return frameId == null ? images.latest(id) : images.frame(id, frameId);
|
||||
}
|
||||
|
||||
// 对外状态不包含会话、播放密钥或采集业务数据。
|
||||
public ObjectNode status() {
|
||||
ObjectNode result = object().put("nodeId", settings.id).put("connection", connection).put("tasks", tasks.size());
|
||||
if (images != null) result.set("imageInput", images.status());
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 合成带通道名、试验名、节点名及版本号的演示帧。
|
||||
* 移动图形用于观察画面是否持续刷新,不代表真实装备运动。
|
||||
* 不读取或伪造采集数据,未来可在此服务接入真正的融合算法。
|
||||
*/
|
||||
private byte[] render(MediaTask task) throws Exception {
|
||||
int width = 640, height = 360;
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D graphics = image.createGraphics();
|
||||
try {
|
||||
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
drawScene(graphics, width, height);
|
||||
drawLabels(graphics, task);
|
||||
} finally {
|
||||
// 每次生成均释放图形上下文,避免长期运行积累本地图形资源。
|
||||
graphics.dispose();
|
||||
}
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
ImageIO.write(image, "jpg", buffer);
|
||||
return buffer.toByteArray();
|
||||
}
|
||||
|
||||
// 场景只负责可见运动与背景绘制,业务身份文字单独输出。
|
||||
private void drawScene(Graphics2D graphics, int width, int height) {
|
||||
graphics.setPaint(new GradientPaint(0, 0, new Color(35, 64, 89),
|
||||
0, height, new Color(9, 22, 38)));
|
||||
graphics.fillRect(0, 0, width, height);
|
||||
graphics.setColor(new Color(74, 102, 121));
|
||||
for (int x = 0; x < width; x += 40) {
|
||||
graphics.drawLine(x, 95, x, height);
|
||||
}
|
||||
for (int y = 95; y < height; y += 35) {
|
||||
graphics.drawLine(0, y, width, y);
|
||||
}
|
||||
graphics.setColor(new Color(79, 112, 129));
|
||||
graphics.fillRect(0, 220, width, 65);
|
||||
graphics.setColor(new Color(170, 185, 190));
|
||||
for (int x = 0; x < width; x += 65) {
|
||||
graphics.fillRect(x, 250, 35, 3);
|
||||
}
|
||||
int x = (int) ((System.currentTimeMillis() / 30) % 730) - 65;
|
||||
graphics.setColor(new Color(38, 161, 217));
|
||||
graphics.fillRoundRect(x, 221, 72, 33, 7, 7);
|
||||
graphics.setColor(new Color(163, 216, 238));
|
||||
graphics.fillRect(x + 18, 226, 25, 11);
|
||||
graphics.setColor(new Color(5, 14, 23));
|
||||
graphics.fillOval(x + 10, 247, 15, 15);
|
||||
graphics.fillOval(x + 49, 247, 15, 15);
|
||||
}
|
||||
|
||||
// 持续标出演示性质,避免界面把节点演示误当成真实视频融合结果。
|
||||
private void drawLabels(Graphics2D graphics, MediaTask task) {
|
||||
graphics.setColor(Color.WHITE);
|
||||
graphics.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
|
||||
graphics.drawString(task.name, 22, 33);
|
||||
graphics.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
|
||||
graphics.drawString(task.trialName, 22, 58);
|
||||
graphics.setColor(new Color(255, 206, 108));
|
||||
graphics.drawString("演示视频 · 尚未接入真实视频融合", 22, 83);
|
||||
graphics.setColor(new Color(214, 229, 240));
|
||||
graphics.drawString(settings.name + " / "
|
||||
+ (task.desired.equals("RUNNING") ? "本轮运行中" : "准备预览"), 22, 326);
|
||||
graphics.drawString("任务版本 " + task.version, 510, 326);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
server.address=0.0.0.0
|
||||
server.port=18100
|
||||
spring.config.import=optional:file:./config/cluster.local.properties
|
||||
spring.jackson.default-property-inclusion=non_null
|
||||
spring.mvc.async.request-timeout=0
|
||||
fusion.role=coordinator
|
||||
fusion.coordinator-worker-enabled=true
|
||||
fusion.cluster-id=pxhj-fusion
|
||||
fusion.token=${XTRH_CLUSTER_TOKEN:}
|
||||
fusion.capacity=2
|
||||
fusion.lease-ms=8000
|
||||
fusion.discovery-enabled=true
|
||||
fusion.gateway-port=19002
|
||||
fusion.forward-target-port=19001
|
||||
logging.level.javax.jmdns=WARN
|
||||
server.error.include-message=never
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 28 28" fill="none" focusable="false">
|
||||
<circle cx="14" cy="14" r="10" stroke="#ffffff" stroke-width="1.5" opacity=".35"/>
|
||||
<path d="M4 14h5l2.5-6 5 12 2.5-6h5" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<circle cx="21.5" cy="6.5" r="2" fill="#ffffff"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 372 B |
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="referrer" content="same-origin" />
|
||||
<link rel="icon" type="image/svg+xml" href="/console/assets/brand.svg" />
|
||||
<title>系统融合软件</title>
|
||||
<script type="module" crossorigin src="/console/assets/index-DHXeX6-t.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/console/assets/index-CGh3g9P7.css">
|
||||
</head>
|
||||
<body><div id="root"></div></body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user