From ad10b01485327272e82c3ea065ec2f877820fc92 Mon Sep 17 00:00:00 2001 From: davidzollo Date: Sat, 1 Aug 2026 07:11:11 +0800 Subject: [PATCH 01/19] [Feature][Zeta] Add Web UI operation controls --- docs/en/engines/zeta/rest-api-v2.md | 57 +++- docs/en/engines/zeta/web-ui.md | 37 ++- docs/zh/engines/zeta/rest-api-v2.md | 57 +++- docs/zh/engines/zeta/web-ui.md | 37 ++- .../seatunnel/engine/server/JettyService.java | 6 + .../engine/server/rest/RestConstant.java | 1 + .../server/rest/service/BaseService.java | 16 +- .../rest/service/UpdateTagsService.java | 80 ++++- .../servlet/HttpServiceStatusServlet.java | 139 ++++++++ .../src/layouts/main/sidebar/index.tsx | 23 +- .../src/locales/en_US/detail.ts | 28 +- .../src/locales/en_US/index.ts | 4 +- .../src/locales/en_US/jobs.ts | 44 ++- .../src/locales/en_US/managers.ts | 18 +- .../src/locales/en_US/menu.ts | 1 + .../src/locales/en_US/operations.ts | 58 ++++ .../src/locales/zh_CN/detail.ts | 28 +- .../src/locales/zh_CN/index.ts | 4 +- .../src/locales/zh_CN/jobs.ts | 44 ++- .../src/locales/zh_CN/managers.ts | 18 +- .../src/locales/zh_CN/menu.ts | 3 +- .../src/locales/zh_CN/operations.ts | 58 ++++ .../seatunnel-engine-ui/src/router/routes.ts | 6 + .../src/service/job/index.ts | 72 +++- .../src/service/job/types.ts | 74 +++++ .../src/service/manager/index.ts | 9 +- .../src/service/manager/types.ts | 13 + .../src/service/operations/index.ts | 29 ++ .../src/service/operations/types.ts | 76 +++++ .../src/service/service.ts | 4 +- .../src/tests/checkpoints.spec.ts | 87 +++++ .../src/tests/detail.spec.ts | 10 +- .../src/tests/jobs.spec.ts | 105 +++++- .../src/tests/managers.spec.ts | 37 ++- .../src/tests/operations.spec.ts | 109 ++++++ .../src/views/jobs/checkpoints.tsx | 187 +++++++++++ .../src/views/jobs/detail.tsx | 4 + .../src/views/jobs/index.tsx | 6 +- .../src/views/jobs/job-operations.tsx | 286 ++++++++++++++++ .../src/views/jobs/running-jobs.tsx | 214 ++++++++++-- .../src/views/managers/index.tsx | 196 +++++++++-- .../src/views/operations/index.tsx | 313 ++++++++++++++++++ 42 files changed, 2485 insertions(+), 113 deletions(-) create mode 100644 seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServlet.java create mode 100644 seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/operations.ts create mode 100644 seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/operations.ts create mode 100644 seatunnel-engine/seatunnel-engine-ui/src/service/operations/index.ts create mode 100644 seatunnel-engine/seatunnel-engine-ui/src/service/operations/types.ts create mode 100644 seatunnel-engine/seatunnel-engine-ui/src/tests/checkpoints.spec.ts create mode 100644 seatunnel-engine/seatunnel-engine-ui/src/tests/operations.spec.ts create mode 100644 seatunnel-engine/seatunnel-engine-ui/src/views/jobs/checkpoints.tsx create mode 100644 seatunnel-engine/seatunnel-engine-ui/src/views/jobs/job-operations.tsx create mode 100644 seatunnel-engine/seatunnel-engine-ui/src/views/operations/index.tsx diff --git a/docs/en/engines/zeta/rest-api-v2.md b/docs/en/engines/zeta/rest-api-v2.md index 7afe0fc85391..59ef82e87aa9 100644 --- a/docs/en/engines/zeta/rest-api-v2.md +++ b/docs/en/engines/zeta/rest-api-v2.md @@ -1203,7 +1203,20 @@ For more information about customize encryption, please refer to the documentati #### update node tags ##### Body -If the request parameter is a `Map` object, it indicates that the tags of the current node need to be updated +Use the member `uuid` from `/system-monitoring-information` to make the target explicit. The request must be sent to the REST address of the target node; otherwise the server returns an error instead of updating a different node. + +```json +{ + "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", + "tags": { + "tag1": "dev_1", + "tag2": "dev_2" + } +} +``` + +For backward compatibility, a flat `Map` still updates the current REST node: + ```json { "tag1": "dev_1", @@ -1220,7 +1233,17 @@ If the request parameter is a `Map` object, it indicates that the tags of the cu ``` #### remove node tags ##### Body -If the parameter is an empty `Map` object, it means that the tags of the current node need to be cleared +Use an empty `tags` map to clear the target node tags: + +```json +{ + "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", + "tags": {} +} +``` + +For backward compatibility, an empty flat `Map` clears the current REST node: + ```json {} ``` @@ -1337,6 +1360,36 @@ More information about `Telemetry` can be found in the [Telemetry](telemetry.md) +### Get HTTP Service Status + +
+ GET /http-service/status (Return HTTP service runtime status.) + +#### Response + +Returns the HTTP service switches, configured ports, effective connector ports, context path, and authentication mode for the current node. +Sensitive values such as passwords and keystore or truststore paths are not returned. + +#### Response Example + +```json +{ + "httpEnabled": true, + "httpsEnabled": false, + "contextPath": "/", + "configuredHttpPort": 5801, + "configuredHttpsPort": 58443, + "httpPort": 5801, + "httpsPort": 58443, + "dynamicPortEnabled": false, + "portRange": 100, + "basicAuthEnabled": false, + "mutualTlsEnabled": false +} +``` + +
+ ### Get Job Checkpoint Overview
diff --git a/docs/en/engines/zeta/web-ui.md b/docs/en/engines/zeta/web-ui.md index 9ade5ea1f573..092cede79f8b 100644 --- a/docs/en/engines/zeta/web-ui.md +++ b/docs/en/engines/zeta/web-ui.md @@ -38,32 +38,40 @@ The Web UI of Apache SeaTunnel is a visual inspection console for SeaTunnel Engi ## Capability Summary -| UI area | Current capability | -|---------|--------------------| -| Overview | View cluster version, slot usage, worker count, and job counts | -| Jobs | View running and finished jobs, paginate job lists, and open job details | -| Job Detail | View DAG, job metrics, exception text, job configuration, logs, and realtime observability data | -| Workers | View worker-node system monitoring information | -| Master | View master-node system monitoring information | +| UI area | Current capability | +| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Overview | View cluster version, slot usage, worker count, and job counts | +| Jobs | Submit jobs from configuration text or uploaded files, restore jobs from savepoint state, view running and finished jobs, paginate job lists, and open job details | +| Job Detail | View DAG, job metrics, exception text, job configuration, checkpoint overview and history, logs, and realtime observability data | +| Operations | Browse connector OptionRule metadata and view safe HTTP, HTTPS, authentication, and mTLS status | +| Workers | View worker-node system monitoring information and update tags on the current node | +| Master | View master-node system monitoring information | ## Jobs +### Submit Jobs + +The Jobs page includes a "Submit Job" panel for submitting a new SeaTunnel job without leaving the Web UI. Users can paste JSON, HOCON, or SQL job configuration text, or upload a `.json`, `.conf`, `.config`, or `.sql` configuration file. + +The same panel can start a job from savepoint state by enabling restore mode and entering the existing job ID. This reuses the REST API contract `isStartWithSavePoint=true` and `jobId=`, so the submitted configuration still needs to match the job being restored. + ### Running Jobs The "Running Jobs" section lists SeaTunnel jobs that are currently in execution. Users can view job ID, job name, creation time, status, and open a detail page for a specific job. -The list refreshes periodically and supports pagination. +The list refreshes periodically and supports pagination. The Action column provides `View`, `Stop`, `Savepoint`, and `Cancel` controls. `Stop` sends a graceful stop request without savepoint, `Savepoint` stops the job through savepoint, and `Cancel` sends a forced stop request for exceptional situations. All state-changing actions require confirmation and show status feedback in the page. ![running.png](../../../images/ui/running.png) ![detail.png](../../../images/ui/detail.png) ### Job Detail -The Job Detail page contains four main tabs: +The Job Detail page contains five main tabs: - **Overview**: shows the job DAG, source and sink throughput metrics, flush-signal metrics, and realtime vertex or edge metrics when observability is enabled. - **Exception**: shows the job error message when the job has failed or reported an exception. - **Configuration**: shows the runtime job configuration exposed by the engine. +- **Checkpoints**: shows checkpoint counts, latest completed checkpoint, latest savepoint, and recent checkpoint history. The restore latest state action opens the submit panel with the source job ID prefilled for savepoint or latest checkpoint-state restore. - **Log**: shows job log files returned by the engine log API. #### Realtime Observability @@ -88,8 +96,19 @@ The "Finished Jobs" section displays jobs that have reached a terminal state, su The "Workers" section displays system monitoring information for worker nodes. Use it to inspect worker address, resource status, and runtime health signals exposed by the engine. +The Workers page can also update tags for the local worker served by the current Web UI request. Remote workers are shown for inspection, but their tag update button is disabled; use the Web UI address of the target node when changing that node's tags. + ![workers.png](../../../images/ui/workers.png) +## Operations + +The "Operations" page provides read-only and metadata-driven operational helpers: + +- Connector OptionRule metadata lookup for `source`, `sink`, and `transform` plugins, including required options, optional options, condition rules, and value constraints. +- Safe HTTP service status, including HTTP, HTTPS, context path, dynamic port, basic authentication, and mutual TLS flags. + +Sensitive values such as passwords, tokens, certificate paths, and key-store credentials are not displayed. + ## Master ### Master Information diff --git a/docs/zh/engines/zeta/rest-api-v2.md b/docs/zh/engines/zeta/rest-api-v2.md index 9b9676de35ce..682bb8d99a41 100644 --- a/docs/zh/engines/zeta/rest-api-v2.md +++ b/docs/zh/engines/zeta/rest-api-v2.md @@ -1188,7 +1188,20 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload' --form 'config_file=@" #### 更新节点tags ##### 请求体 -如果请求参数是`Map`对象,表示要更新当前节点的tags +推荐使用 `/system-monitoring-information` 返回的 member `uuid` 明确目标节点。请求必须发送到目标节点自己的 REST 地址;如果 `uuid` 与当前 REST 节点不一致,服务端会返回错误,避免误更新其他节点。 + +```json +{ + "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", + "tags": { + "tag1": "dev_1", + "tag2": "dev_2" + } +} +``` + +为了兼容旧客户端,扁平 `Map` 仍表示更新当前 REST 节点的 tags: + ```json { "tag1": "dev_1", @@ -1205,7 +1218,17 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload' --form 'config_file=@" ``` #### 移除节点tags ##### 请求体 -如果参数为空`Map`对象,表示要清除当前节点的tags +使用空的 `tags` map 清空目标节点 tags: + +```json +{ + "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", + "tags": {} +} +``` + +为了兼容旧客户端,空的扁平 `Map` 仍表示清空当前 REST 节点的 tags: + ```json {} ``` @@ -1324,6 +1347,36 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload' --form 'config_file=@"
+### 获取 HTTP 服务状态 + +
+ GET /http-service/status (返回当前节点 HTTP 服务运行状态。) + +#### 响应 + +返回当前节点 HTTP 服务开关、配置端口、实际监听端口、上下文路径和认证模式。 +接口不会返回密码、keystore 路径、truststore 路径等敏感值。 + +#### 响应示例 + +```json +{ + "httpEnabled": true, + "httpsEnabled": false, + "contextPath": "/", + "configuredHttpPort": 5801, + "configuredHttpsPort": 58443, + "httpPort": 5801, + "httpsPort": 58443, + "dynamicPortEnabled": false, + "portRange": 100, + "basicAuthEnabled": false, + "mutualTlsEnabled": false +} +``` + +
+ ### 获取作业 Checkpoint 概览
diff --git a/docs/zh/engines/zeta/web-ui.md b/docs/zh/engines/zeta/web-ui.md index 88c8bc58bb17..87a93723f277 100644 --- a/docs/zh/engines/zeta/web-ui.md +++ b/docs/zh/engines/zeta/web-ui.md @@ -38,32 +38,40 @@ Apache SeaTunnel 的 Web UI 是 SeaTunnel Engine 的可视化巡检控制台。 ## 能力总览 -| UI 区域 | 当前能力 | -|---------|----------| -| Overview | 查看集群版本、slot 使用、worker 数量和作业数量 | -| Jobs | 查看运行中和已完成作业、分页浏览作业列表、进入作业详情 | -| Job Detail | 查看 DAG、作业指标、异常文本、作业配置、日志,以及开启后的实时可观测指标 | -| Workers | 查看 worker 节点系统监控信息 | -| Master | 查看 master 节点系统监控信息 | +| UI 区域 | 当前能力 | +| ---------- | --------------------------------------------------------------------------------------------------------------------- | +| Overview | 查看集群版本、slot 使用、worker 数量和作业数量 | +| Jobs | 通过配置文本或上传文件提交作业、从 savepoint 状态恢复启动作业、查看运行中和已完成作业、分页浏览作业列表、进入作业详情 | +| Job Detail | 查看 DAG、作业指标、异常文本、作业配置、checkpoint 概览与历史、日志,以及开启后的实时可观测指标 | +| Operations | 浏览 Connector OptionRule 元数据,并查看安全过滤后的 HTTP、HTTPS、认证和 mTLS 状态 | +| Workers | 查看 worker 节点系统监控信息,并更新当前节点 tags | +| Master | 查看 master 节点系统监控信息 | ## 作业 +### 提交作业 + +Jobs 页面提供 “Submit Job” 面板,可以直接在 Web UI 中提交新的 SeaTunnel 作业。用户可以粘贴 JSON、HOCON 或 SQL 任务配置,也可以上传 `.json`、`.conf`、`.config` 或 `.sql` 配置文件。 + +同一个面板也支持从 savepoint 状态恢复启动作业:开启恢复模式并填写已有作业 ID 后,会复用 REST API 的 `isStartWithSavePoint=true` 和 `jobId=` 契约,因此提交的配置仍需与被恢复的作业匹配。 + ### 运行中的作业 “运行中的作业”模块列出当前正在执行的 SeaTunnel 作业。用户可以查看作业 ID、作业名称、创建时间、状态,并进入具体作业的详情页。 -列表会周期性刷新,并支持分页。 +列表会周期性刷新,并支持分页。Action 列提供 `View`、`Stop`、`Savepoint` 和 `Cancel` 控件。`Stop` 发送不带 savepoint 的平滑停止请求,`Savepoint` 通过 savepoint 停止作业,`Cancel` 面向异常场景发送强制停止请求。所有会改变状态的操作都需要确认,并会在页面展示状态反馈。 ![running.png](../../../images/ui/running.png) ![detail.png](../../../images/ui/detail.png) ### 作业详情 -作业详情页包含四个主要 tab: +作业详情页包含五个主要 tab: - **Overview**:展示作业 DAG、source 和 sink 吞吐指标、flush signal 指标,以及开启可观测性后的 vertex 或 edge 实时指标。 - **Exception**:当作业失败或上报异常时,展示异常文本。 - **Configuration**:展示引擎暴露的运行时作业配置。 +- **Checkpoints**:展示 checkpoint 计数、最近完成的 checkpoint、最近的 savepoint 和 checkpoint 历史记录。“恢复最新状态”操作会打开提交面板,并自动带入源作业 ID,用于从 savepoint 或最新 checkpoint 状态恢复提交。 - **Log**:展示引擎日志 API 返回的作业日志文件。 #### 实时可观测性(Realtime Observability) @@ -89,8 +97,19 @@ Apache SeaTunnel 的 Web UI 是 SeaTunnel Engine 的可视化巡检控制台。 “工作节点”模块展示 worker 节点的系统监控信息。可以用它查看 worker 地址、资源状态和引擎暴露的运行时健康信号。 +Workers 页面也可以更新当前 Web UI 请求所在本地 worker 的 tags。远端 worker 仅用于查看,其 tags 更新按钮会禁用;如果需要修改某个目标节点的 tags,需要访问该目标节点自己的 Web UI 地址。 + ![workers.png](../../../images/ui/workers.png) +## 运维 + +“Operations” 页面提供只读和元数据驱动的运维辅助能力: + +- 查询 `source`、`sink` 和 `transform` 插件的 Connector OptionRule 元数据,包括必填项、可选项、条件规则和值约束。 +- 查看安全过滤后的 HTTP 服务状态,包括 HTTP、HTTPS、context path、动态端口、basic authentication 和 mutual TLS 开关。 + +密码、token、证书路径、keystore 凭据等敏感信息不会在页面展示。 + ## 管理节点 ### 管理节点信息 diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/JettyService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/JettyService.java index 9686960fb5e4..a31f000bd02b 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/JettyService.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/JettyService.java @@ -36,6 +36,7 @@ import org.apache.seatunnel.engine.server.rest.servlet.CurrentNodeLogServlet; import org.apache.seatunnel.engine.server.rest.servlet.EncryptConfigServlet; import org.apache.seatunnel.engine.server.rest.servlet.FinishedJobsServlet; +import org.apache.seatunnel.engine.server.rest.servlet.HttpServiceStatusServlet; import org.apache.seatunnel.engine.server.rest.servlet.JobInfoServlet; import org.apache.seatunnel.engine.server.rest.servlet.MetricsServlet; import org.apache.seatunnel.engine.server.rest.servlet.OptionRulesServlet; @@ -71,6 +72,7 @@ import static org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_ENCRYPT_CONFIG; import static org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_FINISHED_JOBS; import static org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_GET_ALL_LOG_NAME; +import static org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_HTTP_SERVICE_STATUS; import static org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_JOB_INFO; import static org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_LOG; import static org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_LOGS; @@ -219,6 +221,8 @@ public void createJettyServer() { new ServletHolder(new CheckpointOverviewServlet(nodeEngine)); ServletHolder checkpointHistoryHolder = new ServletHolder(new CheckpointHistoryServlet(nodeEngine)); + ServletHolder httpServiceStatusHolder = + new ServletHolder(new HttpServiceStatusServlet(nodeEngine, seaTunnelConfig, server)); context.addServlet(overviewHolder, convertUrlToPath(REST_URL_OVERVIEW)); context.addServlet(runningJobsHolder, convertUrlToPath(REST_URL_RUNNING_JOBS)); @@ -253,6 +257,8 @@ public void createJettyServer() { context.addServlet( checkpointOverviewHolder, convertUrlToPath(REST_URL_CHECKPOINT_OVERVIEW)); context.addServlet(checkpointHistoryHolder, convertUrlToPath(REST_URL_CHECKPOINT_HISTORY)); + context.addServlet( + httpServiceStatusHolder, convertUrlToPath(REST_URL_HTTP_SERVICE_STATUS)); server.setHandler(context); diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/RestConstant.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/RestConstant.java index 61d488a1e240..1a1ff793143d 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/RestConstant.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/RestConstant.java @@ -111,6 +111,7 @@ public class RestConstant { public static final String REST_URL_CHECKPOINT_OVERVIEW = "/jobs/checkpoints"; public static final String REST_URL_CHECKPOINT_HISTORY = "/jobs/checkpoints/history"; public static final String REST_URL_REALTIME_METRICS = "/metrics/realtime"; + public static final String REST_URL_HTTP_SERVICE_STATUS = "/http-service/status"; // api path end } diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/BaseService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/BaseService.java index 9f8cd58bfcd9..0793fa14df1e 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/BaseService.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/BaseService.java @@ -1346,7 +1346,21 @@ protected JsonArray getSystemMonitoringInformationJsonValues() { log.error("Failed to get cluster health metrics", e); } - return parseSystemMonitoringMetrics(input, address); + JsonObject memberMetrics = + parseSystemMonitoringMetrics(input, address); + // Include identity so the UI can target the local REST node + // explicitly instead of updating the wrong worker. + memberMetrics.add("uuid", member.getUuid().toString()); + memberMetrics.add("localMember", member.localMember()); + JsonObject tags = new JsonObject(); + member.getAttributes() + .forEach( + (key, value) -> + tags.add( + key, + value == null ? "" : value)); + memberMetrics.add("tags", tags); + return memberMetrics; }) .collect(JsonArray::new, JsonArray::add, JsonArray::add); return jsonValues; diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java index 2b8fa692b76f..667c8d234233 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java @@ -24,31 +24,93 @@ import com.hazelcast.internal.json.JsonObject; import com.hazelcast.spi.impl.NodeEngineImpl; +import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; +/** + * Updates tags for the REST node that serves the request. + * + *

The optional member uuid prevents operators from accidentally updating the current node while + * intending to update a different worker. + */ public class UpdateTagsService extends BaseService { public UpdateTagsService(NodeEngineImpl nodeEngine) { super(nodeEngine); } + /** + * Updates the local member tags from the request body. + * + * @param requestBody JSON request body. It can be either a legacy flat tag map or a structured + * request with uuid and tags. + * @return operation status JSON. + */ public JsonObject updateTags(byte[] requestBody) { Map params = JsonUtils.toMap(requestHandle(requestBody)); SeaTunnelServer seaTunnelServer = getSeaTunnelServer(false); NodeEngineImpl nodeEngine = seaTunnelServer.getNodeEngine(); MemberImpl localMember = nodeEngine.getLocalMember(); + validateTargetMember(params, localMember); - Map tags = - params.entrySet().stream() - .collect( - Collectors.toMap( - Map.Entry::getKey, - value -> - value.getValue() != null - ? value.getValue().toString() - : "")); + Map tagParams = extractTagParams(params); + Map tags = toStringTags(tagParams); localMember.updateAttribute(tags); return new JsonObject().add("status", "success").add("message", "update node tags done."); } + + /** + * Validates that an explicit target uuid matches the local member. + * + * @param params parsed request parameters. + * @param localMember member served by the current REST endpoint. + */ + private void validateTargetMember(Map params, MemberImpl localMember) { + Object uuid = params.get("uuid"); + if (uuid != null && !localMember.getUuid().toString().equals(uuid.toString())) { + throw new IllegalArgumentException( + String.format( + "Target member uuid %s is not served by this REST node. " + + "Please send the request to the target node.", + uuid)); + } + } + + /** + * Extracts tag values from the structured or legacy request format. + * + * @param params parsed request parameters. + * @return tag map to apply to the local member. + */ + @SuppressWarnings("unchecked") + private Map extractTagParams(Map params) { + Object tags = params.get("tags"); + if (tags instanceof Map) { + return (Map) tags; + } + if (tags != null) { + throw new IllegalArgumentException("The tags field must be an object."); + } + Map legacyTags = new HashMap<>(params); + legacyTags.remove("uuid"); + return legacyTags; + } + + /** + * Converts JSON values to Hazelcast member attribute strings. + * + * @param tagParams raw tag values from the request. + * @return string tags accepted by Hazelcast member attributes. + */ + private Map toStringTags(Map tagParams) { + return tagParams.entrySet().stream() + .collect( + Collectors.toMap( + Map.Entry::getKey, + value -> + value.getValue() != null + ? value.getValue().toString() + : "")); + } } diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServlet.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServlet.java new file mode 100644 index 000000000000..8f24b216ab3e --- /dev/null +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServlet.java @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.seatunnel.engine.server.rest.servlet; + +import org.apache.seatunnel.engine.common.config.SeaTunnelConfig; +import org.apache.seatunnel.engine.common.config.server.HttpConfig; +import org.apache.seatunnel.shade.org.eclipse.jetty.server.Connector; +import org.apache.seatunnel.shade.org.eclipse.jetty.server.Server; +import org.apache.seatunnel.shade.org.eclipse.jetty.server.ServerConnector; +import org.apache.seatunnel.shade.org.eclipse.jetty.server.SslConnectionFactory; + +import com.hazelcast.internal.json.JsonObject; +import com.hazelcast.spi.impl.NodeEngineImpl; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.io.IOException; + +/** + * Returns safe, read-only HTTP service status without exposing credentials or certificate paths. + */ +public class HttpServiceStatusServlet extends BaseServlet { + + private final SeaTunnelConfig seaTunnelConfig; + private final Server server; + + /** + * Creates a status servlet bound to the current Jetty server instance. + * + * @param nodeEngine Hazelcast node engine used by REST servlet base class. + * @param seaTunnelConfig runtime configuration containing HTTP service options. + * @param server Jetty server whose connectors expose effective listener ports. + */ + public HttpServiceStatusServlet( + NodeEngineImpl nodeEngine, SeaTunnelConfig seaTunnelConfig, Server server) { + super(nodeEngine); + this.seaTunnelConfig = seaTunnelConfig; + this.server = server; + } + + /** + * Handles safe HTTP service status inspection for the current node. + * + *

The response intentionally reports only switches, ports, context path, and port range. It + * must not include passwords, usernames, keystore paths, or truststore paths. + */ + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + HttpConfig httpConfig = seaTunnelConfig.getEngineConfig().getHttpConfig(); + JsonObject status = + new JsonObject() + .add("httpEnabled", httpConfig.isEnabled()) + .add("httpsEnabled", httpConfig.isEnableHttps()) + .add("configuredHttpPort", httpConfig.getPort()) + .add("configuredHttpsPort", httpConfig.getHttpsPort()) + .add("httpPort", findConnectorPort(false, httpConfig.getPort())) + .add("httpsPort", findConnectorPort(true, httpConfig.getHttpsPort())) + .add("contextPath", defaultContextPath(httpConfig.getContextPath())) + .add("dynamicPortEnabled", httpConfig.isEnableDynamicPort()) + .add("portRange", httpConfig.getPortRange()) + .add("basicAuthEnabled", httpConfig.isEnableBasicAuth()) + .add( + "mutualTlsEnabled", + hasText(httpConfig.getTrustStorePath()) + && hasText(httpConfig.getTrustStorePassword())); + writeJson(resp, status); + } + + /** + * Returns the effective listener port for an HTTP or HTTPS connector. + * + * @param ssl whether to find an SSL connector. + * @param configuredPort fallback port from configuration. + * @return effective local port when available, otherwise the configured port. + */ + private int findConnectorPort(boolean ssl, int configuredPort) { + for (Connector connector : server.getConnectors()) { + if (!(connector instanceof ServerConnector)) { + continue; + } + ServerConnector serverConnector = (ServerConnector) connector; + if (hasSslConnectionFactory(serverConnector) == ssl) { + return serverConnector.getLocalPort() > 0 + ? serverConnector.getLocalPort() + : serverConnector.getPort(); + } + } + return configuredPort; + } + + /** + * Normalizes blank context paths for UI display. + * + * @param contextPath configured context path. + * @return configured path, or "/" when it is blank. + */ + private String defaultContextPath(String contextPath) { + return hasText(contextPath) ? contextPath : "/"; + } + + /** + * Checks whether a connector is backed by SSL. + * + * @param connector Jetty server connector to inspect. + * @return true when the connector has an SSL connection factory. + */ + private boolean hasSslConnectionFactory(ServerConnector connector) { + return connector.getConnectionFactories().stream() + .anyMatch(factory -> factory instanceof SslConnectionFactory); + } + + /** + * Returns whether a string contains non-whitespace text. + * + * @param value value to inspect. + * @return true if the value is non-null and non-blank. + */ + private boolean hasText(String value) { + return value != null && !value.trim().isEmpty(); + } +} diff --git a/seatunnel-engine/seatunnel-engine-ui/src/layouts/main/sidebar/index.tsx b/seatunnel-engine/seatunnel-engine-ui/src/layouts/main/sidebar/index.tsx index 0b3f5185f59c..2e7ee41984e9 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/layouts/main/sidebar/index.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/layouts/main/sidebar/index.tsx @@ -19,7 +19,13 @@ import { defineComponent, ref, type PropType, onMounted, h, type Component } fro import { NIcon, NLayoutSider, NMenu } from 'naive-ui' import { useRoute, RouterLink } from 'vue-router' import { useI18n } from 'vue-i18n' -import { DesktopOutline, ListOutline, PeopleOutline, PersonOutline } from '@vicons/ionicons5' +import { + DesktopOutline, + ListOutline, + PeopleOutline, + PersonOutline, + SettingsOutline +} from '@vicons/ionicons5' const Sidebar = defineComponent({ name: 'Sidebar', @@ -72,6 +78,21 @@ const Sidebar = defineComponent({ key: 'jobs', icon: renderIcon(ListOutline) }, + { + label: () => + h( + RouterLink, + { + to: { + path: '/operations' + }, + exact: false + }, + { default: () => t('menu.operations') } + ), + key: 'operations', + icon: renderIcon(SettingsOutline) + }, { label: () => h( diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts index 5bf47c677ec7..88efa4cbff3b 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts @@ -23,7 +23,8 @@ export default { overview: 'Overview', exception: 'Exception', configuration: 'Configuration', - log: 'Log', + checkpoints: 'Checkpoints', + log: 'Log' }, table: { name: 'Name', @@ -34,7 +35,7 @@ export default { receivedQps: 'Received QPS', writeQps: 'Write QPS', receivedBytesPerSecond: 'Received Bytes PerSecond', - writeBytesPerSecond: 'Write Bytes PerSecond', + writeBytesPerSecond: 'Write Bytes PerSecond' }, observability: { time: 'Time', @@ -51,6 +52,27 @@ export default { writeMsPerRecord: 'Write (ms/record)', // Edge bpRatio: 'Downstream Wait Ratio', - queueFillRatio: 'Queue Fill Ratio', + queueFillRatio: 'Queue Fill Ratio' }, + checkpoints: { + refresh: 'Refresh', + noSnapshot: 'No checkpoint snapshot', + updatedAt: 'Updated at {time}', + loadFailed: 'Failed to load checkpoint data.', + pipeline: 'Pipeline', + triggered: 'Triggered', + completed: 'Completed', + failed: 'Failed', + inProgress: 'In Progress', + restored: 'Restored', + latestCompleted: 'Latest Completed', + latestSavepoint: 'Latest Savepoint', + checkpoint: 'Checkpoint', + status: 'Status', + duration: 'Duration (ms)', + stateSize: 'State Size', + failureReason: 'Failure Reason', + action: 'Action', + restoreLatest: 'Restore Latest State' + } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/index.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/index.ts index 7eb5135dec6d..412019e814b6 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/index.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/index.ts @@ -20,11 +20,13 @@ import jobs from '@/locales/en_US/jobs' import detail from '@/locales/en_US/detail' import common from '@/locales/en_US/common' import managers from '@/locales/en_US/managers' +import operations from '@/locales/en_US/operations' export default { menu, jobs, detail, common, - managers + managers, + operations } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/jobs.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/jobs.ts index ed2f0e712aa3..56ca90ce34b9 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/jobs.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/jobs.ts @@ -16,6 +16,46 @@ */ export default { - runningJobs: 'Running Jobs', - finishedJobs: 'Finished Jobs' + runningJobs: 'Running Jobs', + finishedJobs: 'Finished Jobs', + operations: { + title: 'Submit Job', + textSubmit: 'Config Text', + fileSubmit: 'Config File', + jobName: 'Job Name', + jobNamePlaceholder: 'Optional job name', + configFormat: 'Format', + configContent: 'Config', + configPlaceholder: 'Paste JSON, HOCON, or SQL job config', + configFile: 'Config File', + startWithSavepoint: 'Restore', + restoreJobId: 'Restore Job ID', + restoreJobIdPlaceholder: 'Existing job ID with savepoint state', + chooseFile: 'Choose File', + reset: 'Reset', + submit: 'Submit', + configRequired: 'Job config is required.', + fileRequired: 'Please choose a config file.', + restoreJobIdRequired: 'Restore job ID is required when restore is enabled.', + submitSuccess: 'Submitted {job}.', + submitFailed: 'Failed to submit job.' + }, + actions: { + view: 'View', + stop: 'Stop', + savepoint: 'Savepoint', + cancel: 'Cancel', + confirm: 'Confirm', + cancelConfirm: 'Dismiss', + stopConfirmMessage: 'Stop {job} gracefully?', + savepointConfirmMessage: 'Stop {job} with savepoint?', + cancelConfirmMessage: 'Force cancel {job}?', + stopSuccess: 'Stop request sent for {job}.', + stopFailed: 'Failed to stop {job}.', + savepointSuccess: 'Savepoint stop request sent for {job}.', + savepointFailed: 'Failed to stop {job} with savepoint.', + cancelSuccess: 'Cancel request sent for {job}.', + cancelFailed: 'Failed to cancel {job}.', + refreshFailed: 'Failed to refresh running jobs.' + } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts index e2e4d7ccdfde..d9beb166eaa4 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts @@ -16,5 +16,21 @@ */ export default { - managers: 'Managers' + managers: 'Managers', + tags: { + title: 'Worker Tags', + content: 'Tags', + placeholder: 'One tag per line, for example: zone=prod', + update: 'Update Tags', + clear: 'Clear Tags', + success: 'Node tags updated.', + failed: 'Failed to update node tags.', + invalid: 'Each tag line must use key=value.', + select: 'Select', + local: 'Local', + remote: 'Remote', + remoteHint: 'Open the target node Web UI to update this worker.', + noWorkerSelected: 'No worker selected', + workerRequired: 'Please select a worker first.' + } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/menu.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/menu.ts index f01d702f81a7..2ff82c821607 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/menu.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/menu.ts @@ -18,6 +18,7 @@ export default { overview: 'Overview', jobs: 'Jobs', + operations: 'Operations', managers: { workers: 'Workers', master: 'Master' diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/operations.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/operations.ts new file mode 100644 index 000000000000..63a95e57759a --- /dev/null +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/operations.ts @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default { + optionRules: { + title: 'Connector Option Rules', + pluginType: 'Plugin Type', + pluginName: 'Plugin Name', + pluginNamePlaceholder: 'FakeSource, Console, Filter, ...', + load: 'Load', + pluginRequired: 'Plugin name is required.', + loadFailed: 'Failed to load connector option rules.', + required: 'Required', + optional: 'Optional', + conditionRules: 'Condition Rules', + valueConstraints: 'Value Constraints', + section: 'Section', + ruleType: 'Rule Type', + expression: 'Expression', + requiredCount: 'Required Options', + optionalCount: 'Optional Options', + conditionCount: 'Nested Conditions', + condition: 'Condition', + key: 'Key', + type: 'Type', + defaultValue: 'Default', + description: 'Description' + }, + httpStatus: { + title: 'HTTP Service Status', + refresh: 'Refresh', + loadFailed: 'Failed to load HTTP service status.', + enabled: 'Enabled', + disabled: 'Disabled', + http: 'HTTP', + https: 'HTTPS', + httpPort: 'HTTP Port', + httpsPort: 'HTTPS Port', + contextPath: 'Context Path', + dynamicPort: 'Dynamic Port', + basicAuth: 'Basic Auth', + mutualTls: 'Mutual TLS' + } +} diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts index a9050218994d..89e2d19d4e2b 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts @@ -23,7 +23,8 @@ export default { overview: '概览', exception: '异常', configuration: '配置', - log: '日志', + checkpoints: 'Checkpoint', + log: '日志' }, table: { name: '名称', @@ -34,7 +35,7 @@ export default { receivedQps: '读取 QPS', writeQps: '写入 QPS', receivedBytesPerSecond: '读取字节/秒', - writeBytesPerSecond: '写入字节/秒', + writeBytesPerSecond: '写入字节/秒' }, observability: { time: '时间', @@ -51,6 +52,27 @@ export default { writeMsPerRecord: '写入耗时(毫秒/条)', // Edge bpRatio: '下游等待占比', - queueFillRatio: '队列填充率', + queueFillRatio: '队列填充率' }, + checkpoints: { + refresh: '刷新', + noSnapshot: '暂无 Checkpoint 快照', + updatedAt: '更新时间 {time}', + loadFailed: '加载 Checkpoint 数据失败。', + pipeline: 'Pipeline', + triggered: '触发次数', + completed: '完成次数', + failed: '失败次数', + inProgress: '进行中', + restored: '恢复次数', + latestCompleted: '最近完成', + latestSavepoint: '最近保存点', + checkpoint: 'Checkpoint', + status: '状态', + duration: '耗时(毫秒)', + stateSize: '状态大小', + failureReason: '失败原因', + action: '操作', + restoreLatest: '恢复最新状态' + } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/index.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/index.ts index 134f4c742226..032e386f8057 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/index.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/index.ts @@ -20,11 +20,13 @@ import jobs from '@/locales/zh_CN/jobs' import detail from '@/locales/zh_CN/detail' import common from '@/locales/zh_CN/common' import managers from '@/locales/zh_CN/managers' +import operations from '@/locales/zh_CN/operations' export default { menu, jobs, detail, common, - managers + managers, + operations } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/jobs.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/jobs.ts index ae58343b9d7e..6385a1325457 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/jobs.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/jobs.ts @@ -16,6 +16,46 @@ */ export default { - runningJobs: '运行中', - finishedJobs: '已结束' + runningJobs: '运行中', + finishedJobs: '已结束', + operations: { + title: '提交任务', + textSubmit: '配置文本', + fileSubmit: '配置文件', + jobName: '任务名称', + jobNamePlaceholder: '可选任务名称', + configFormat: '格式', + configContent: '配置', + configPlaceholder: '粘贴 JSON、HOCON 或 SQL 任务配置', + configFile: '配置文件', + startWithSavepoint: '恢复启动', + restoreJobId: '恢复任务 ID', + restoreJobIdPlaceholder: '已有 savepoint 状态的任务 ID', + chooseFile: '选择文件', + reset: '重置', + submit: '提交', + configRequired: '任务配置不能为空。', + fileRequired: '请选择配置文件。', + restoreJobIdRequired: '开启恢复启动时必须填写任务 ID。', + submitSuccess: '已提交 {job}。', + submitFailed: '任务提交失败。' + }, + actions: { + view: '查看', + stop: '停止', + savepoint: '保存点停止', + cancel: '取消', + confirm: '确认', + cancelConfirm: '关闭', + stopConfirmMessage: '确认平滑停止 {job}?', + savepointConfirmMessage: '确认通过保存点停止 {job}?', + cancelConfirmMessage: '确认强制取消 {job}?', + stopSuccess: '已发送 {job} 的停止请求。', + stopFailed: '停止 {job} 失败。', + savepointSuccess: '已发送 {job} 的保存点停止请求。', + savepointFailed: '通过保存点停止 {job} 失败。', + cancelSuccess: '已发送 {job} 的取消请求。', + cancelFailed: '取消 {job} 失败。', + refreshFailed: '刷新运行中作业失败。' + } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts index cd924b0d0553..fa96715b673c 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts @@ -16,5 +16,21 @@ */ export default { - managers: '管理者' + managers: '管理者', + tags: { + title: 'Worker Tags', + content: 'Tags', + placeholder: '每行一个 tag,例如:zone=prod', + update: '更新 Tags', + clear: '清空 Tags', + success: '节点 Tags 已更新。', + failed: '更新节点 Tags 失败。', + invalid: '每行 tag 必须使用 key=value 格式。', + select: '选择', + local: '当前节点', + remote: '远端节点', + remoteHint: '请打开目标节点自己的 Web UI 更新该 Worker。', + noWorkerSelected: '未选择 Worker', + workerRequired: '请先选择一个 Worker。' + } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/menu.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/menu.ts index 911e7471e275..2cde63793ebc 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/menu.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/menu.ts @@ -18,9 +18,10 @@ export default { overview: '概览', jobs: '任务', + operations: '运维', managers: { workers: '工作节点', master: '主节点' }, - synchronization_instance: '同步任务实例', + synchronization_instance: '同步任务实例' } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/operations.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/operations.ts new file mode 100644 index 000000000000..6b98e1fff259 --- /dev/null +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/operations.ts @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default { + optionRules: { + title: 'Connector OptionRule', + pluginType: '插件类型', + pluginName: '插件名称', + pluginNamePlaceholder: 'FakeSource、Console、Filter 等', + load: '加载', + pluginRequired: '插件名称不能为空。', + loadFailed: '加载 Connector OptionRule 失败。', + required: '必填', + optional: '可选', + conditionRules: '条件规则', + valueConstraints: '取值约束', + section: '分组', + ruleType: '规则类型', + expression: '表达式', + requiredCount: '必填项数量', + optionalCount: '可选项数量', + conditionCount: '嵌套条件数量', + condition: '条件', + key: '配置项', + type: '类型', + defaultValue: '默认值', + description: '说明' + }, + httpStatus: { + title: 'HTTP 服务状态', + refresh: '刷新', + loadFailed: '加载 HTTP 服务状态失败。', + enabled: '已开启', + disabled: '未开启', + http: 'HTTP', + https: 'HTTPS', + httpPort: 'HTTP 端口', + httpsPort: 'HTTPS 端口', + contextPath: 'Context Path', + dynamicPort: '动态端口', + basicAuth: 'Basic Auth', + mutualTls: '双向 TLS' + } +} diff --git a/seatunnel-engine/seatunnel-engine-ui/src/router/routes.ts b/seatunnel-engine/seatunnel-engine-ui/src/router/routes.ts index 58296e674516..a7d8681537c8 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/router/routes.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/router/routes.ts @@ -42,6 +42,12 @@ const routes: RouteRecordRaw[] = [ meta: { title: 'detail', showSide: true, activeSide: 'jobs' }, component: () => import('@/views/jobs/detail') }, + { + path: 'operations', + name: 'operations', + meta: { title: 'operations', showSide: true, activeSide: 'operations' }, + component: () => import('@/views/operations') + }, { path: 'managers/workers', name: 'managers-workers', diff --git a/seatunnel-engine/seatunnel-engine-ui/src/service/job/index.ts b/seatunnel-engine/seatunnel-engine-ui/src/service/job/index.ts index ad07cc1971ad..5577de49c54d 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/service/job/index.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/service/job/index.ts @@ -15,18 +15,78 @@ * limitations under the License. */ -import { get } from '@/service/service' -import type { Job, JobPage } from './types' +import { get, post } from '@/service/service' +import type { + Job, + JobPage, + CheckpointHistoryRecord, + CheckpointOverview, + StopJobRequest, + StopJobResponse, + SubmitJobFileRequest, + SubmitJobRequest, + SubmitJobResponse +} from './types' export const getRunningJobs = (page: number, rows: number) => - get('/running-jobs/summary', {page: page, rows: rows}) -export const getFinishedJobs = (page: number, rows: number) => get(`/finished-jobs`, {page: page, rows: rows}) + get('/running-jobs/summary', { page: page, rows: rows }) +export const getFinishedJobs = (page: number, rows: number) => + get(`/finished-jobs`, { page: page, rows: rows }) export const getJobInfo = (jobId: string) => get(`/job-info/${jobId}`) export const getRunningJobInfo = (jobId: string) => get(`/running-job/${jobId}`) +const optionalParam = (value?: string) => { + const normalized = value?.trim() + return normalized ? normalized : undefined +} + +export const submitJob = (request: SubmitJobRequest) => + post('/submit-job', request.config, { + params: { + format: request.format, + jobName: optionalParam(request.jobName), + jobId: optionalParam(request.jobId), + isStartWithSavePoint: request.isStartWithSavePoint || undefined + }, + headers: { + 'Content-Type': 'text/plain;charset=UTF-8' + } + }) + +export const submitJobByUploadFile = (request: SubmitJobFileRequest) => { + const formData = new FormData() + formData.append('config_file', request.file) + return post('/submit-job/upload', formData, { + params: { + jobName: optionalParam(request.jobName), + jobId: optionalParam(request.jobId), + isStartWithSavePoint: request.isStartWithSavePoint || undefined + } + }) +} + +export const stopJob = (request: StopJobRequest) => + post('/stop-job', { + jobId: request.jobId, + isStopWithSavePoint: request.isStopWithSavePoint ?? false, + force: request.force ?? false + }) + +export const getCheckpointOverview = (jobId: string) => + get(`/jobs/checkpoints/${jobId}`) + +export const getCheckpointHistory = ( + jobId: string, + params?: { pipelineId?: number; limit?: number; status?: string } +) => get(`/jobs/checkpoints/history/${jobId}`, params) export const JobsService = { getRunningJobs, getFinishedJobs, getJobInfo, - getRunningJobInfo -} \ No newline at end of file + getRunningJobInfo, + submitJob, + submitJobByUploadFile, + stopJob, + getCheckpointOverview, + getCheckpointHistory +} diff --git a/seatunnel-engine/seatunnel-engine-ui/src/service/job/types.ts b/seatunnel-engine/seatunnel-engine-ui/src/service/job/types.ts index dd90c1066f43..b287495e2cd8 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/service/job/types.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/service/job/types.ts @@ -99,3 +99,77 @@ export interface JobPage { total: number data: Job[] } + +export type ConfigFormat = 'json' | 'hocon' | 'sql' + +export interface SubmitJobRequest { + config: string + format: ConfigFormat + jobName?: string + jobId?: string + isStartWithSavePoint?: boolean +} + +export interface SubmitJobFileRequest { + file: File + jobName?: string + jobId?: string + isStartWithSavePoint?: boolean +} + +export interface SubmitJobResponse { + jobId: string | number + jobName: string +} + +export interface StopJobRequest { + jobId: string | number + isStopWithSavePoint?: boolean + force?: boolean +} + +export interface StopJobResponse { + jobId: string | number +} + +export interface CheckpointCounts { + triggered: number + completed: number + failed: number + inProgress: number + restored: number +} + +export interface CheckpointInfo { + checkpointId: number + checkpointType: string + status?: string + triggerTimestamp?: number + completedTimestamp?: number + durationMillis?: number + stateSize?: number + failureReason?: string + acknowledged?: number + total?: number +} + +export interface CheckpointHistoryRecord { + pipelineId: number + checkpoint: CheckpointInfo +} + +export interface CheckpointPipeline { + pipelineId: number + counts: CheckpointCounts + latestCompleted?: CheckpointInfo | null + latestFailed?: CheckpointInfo | null + latestSavepoint?: CheckpointInfo | null + inProgress?: CheckpointInfo[] + history?: CheckpointHistoryRecord[] +} + +export interface CheckpointOverview { + jobId: string + updatedAt: number + pipelines: CheckpointPipeline[] +} diff --git a/seatunnel-engine/seatunnel-engine-ui/src/service/manager/index.ts b/seatunnel-engine/seatunnel-engine-ui/src/service/manager/index.ts index 777b853cf4a5..4ba2ec1aef64 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/service/manager/index.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/service/manager/index.ts @@ -15,10 +15,13 @@ * limitations under the License. */ -import { get } from '@/service/service' -import type { Monitor } from './types' +import { get, post } from '@/service/service' +import type { Monitor, UpdateTagsRequest, UpdateTagsResponse } from './types' export const getMonitors = () => get('/system-monitoring-information') +export const updateTags = (request: UpdateTagsRequest) => + post('/update-tags', request) export const managerService = { - getMonitors + getMonitors, + updateTags } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/service/manager/types.ts b/seatunnel-engine/seatunnel-engine-ui/src/service/manager/types.ts index 62bd70b91037..a073b718bb1b 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/service/manager/types.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/service/manager/types.ts @@ -16,6 +16,9 @@ */ export interface Monitor { + uuid?: string + localMember?: boolean + tags?: Record isMaster: 'true' | 'false' processors: string host: string @@ -65,3 +68,13 @@ export interface Monitor { 'client.connection.count': string 'connection.count': string } + +export interface UpdateTagsRequest { + uuid?: string + tags: Record +} + +export interface UpdateTagsResponse { + status: string + message: string +} diff --git a/seatunnel-engine/seatunnel-engine-ui/src/service/operations/index.ts b/seatunnel-engine/seatunnel-engine-ui/src/service/operations/index.ts new file mode 100644 index 000000000000..e7e3a77c073b --- /dev/null +++ b/seatunnel-engine/seatunnel-engine-ui/src/service/operations/index.ts @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { get } from '@/service/service' +import type { HttpServiceStatus, OptionRuleResponse, PluginType } from './types' + +export const getOptionRules = (type: PluginType, plugin: string) => + get('/option-rules', { type, plugin }) + +export const getHttpServiceStatus = () => get('/http-service/status') + +export const operationsService = { + getOptionRules, + getHttpServiceStatus +} diff --git a/seatunnel-engine/seatunnel-engine-ui/src/service/operations/types.ts b/seatunnel-engine/seatunnel-engine-ui/src/service/operations/types.ts new file mode 100644 index 000000000000..0a205ba06747 --- /dev/null +++ b/seatunnel-engine/seatunnel-engine-ui/src/service/operations/types.ts @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export type PluginType = 'source' | 'sink' | 'transform' + +export interface OptionMetadata { + key: string + type: string + defaultValue?: unknown + description?: string + fallbackKeys?: string[] + optionValues?: unknown[] | null +} + +export interface RequiredOptionRule { + ruleType: string + options: OptionMetadata[] + expression?: string + expressionTree?: unknown +} + +export interface ConditionRule { + expression?: string + expressionTree?: unknown + optionRule: { + optionalOptions?: OptionMetadata[] + requiredOptions?: RequiredOptionRule[] + conditionRules?: ConditionRule[] + valueConstraints?: ValueConstraint[] + } +} + +export interface ValueConstraint { + expression?: string + conditionTree?: unknown +} + +export interface OptionRuleResponse { + engineType: string + pluginType: PluginType + pluginName: string + optionRule: { + optionalOptions?: OptionMetadata[] + requiredOptions?: RequiredOptionRule[] + conditionRules?: ConditionRule[] + valueConstraints?: ValueConstraint[] + } +} + +export interface HttpServiceStatus { + httpEnabled: boolean + httpsEnabled: boolean + configuredHttpPort: number + configuredHttpsPort: number + httpPort: number + httpsPort: number + contextPath: string + dynamicPortEnabled: boolean + portRange: number + basicAuthEnabled: boolean + mutualTlsEnabled: boolean +} diff --git a/seatunnel-engine/seatunnel-engine-ui/src/service/service.ts b/seatunnel-engine/seatunnel-engine-ui/src/service/service.ts index b0b524d86cf7..454cf95ed72c 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/service/service.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/service/service.ts @@ -62,8 +62,8 @@ service.interceptors.response.use((res: AxiosResponse) => { export const get = (url: string, params?: Record) => { return >service.get(url, { params }) } -export const post = (url: string, data: Record) => { - return >service.post(url, data) +export const post = (url: string, data?: any, config?: AxiosRequestConfig) => { + return >service.post(url, data, config) } export { service as axios } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/checkpoints.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/checkpoints.spec.ts new file mode 100644 index 000000000000..7ec24f008554 --- /dev/null +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/checkpoints.spec.ts @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, test, expect, vi, afterEach } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import i18n from '@/locales' +import checkpoints from '@/views/jobs/checkpoints' +import { JobsService } from '@/service/job' + +const routerState = vi.hoisted(() => ({ + push: vi.fn() +})) + +vi.mock('vue-router', () => ({ + useRouter: () => ({ + push: routerState.push + }) +})) + +describe('checkpoints', () => { + afterEach(() => { + vi.restoreAllMocks() + routerState.push.mockReset() + }) + + test('restores from checkpoint view by preloading submit job restore id', async () => { + vi.spyOn(JobsService, 'getCheckpointOverview').mockResolvedValue({ + jobId: '123456789', + updatedAt: 1720000000123, + pipelines: [ + { + pipelineId: 1, + counts: { + triggered: 1, + completed: 1, + failed: 0, + inProgress: 0, + restored: 0 + }, + latestCompleted: { + checkpointId: 10, + checkpointType: 'CHECKPOINT_TYPE', + status: 'COMPLETED' + } + } + ] + }) + vi.spyOn(JobsService, 'getCheckpointHistory').mockResolvedValue([]) + + const wrapper = mount(checkpoints, { + props: { + jobId: '123456789' + }, + global: { + plugins: [i18n] + } + }) + + await flushPromises() + const restoreButton = wrapper + .findAll('button') + .find((button) => button.text() === 'Restore Latest State') + expect(restoreButton).toBeTruthy() + await restoreButton?.trigger('click') + expect(routerState.push).toHaveBeenCalledWith({ + name: 'jobs', + query: { + restoreJobId: '123456789' + } + }) + wrapper.unmount() + }) +}) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/detail.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/detail.spec.ts index 2b5be1596088..1db278b3bb37 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/detail.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/detail.spec.ts @@ -26,7 +26,15 @@ import type { Job } from '@/service/job/types' vi.mock('@/service/job', () => ({ getJobInfo: vi.fn(), - getRunningJobInfo: vi.fn() + getRunningJobInfo: vi.fn(), + JobsService: { + getCheckpointOverview: vi.fn().mockResolvedValue({ + jobId: '123456789', + updatedAt: 0, + pipelines: [] + }), + getCheckpointHistory: vi.fn().mockResolvedValue([]) + } })) vi.mock('vue-router', () => ({ diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts index 376667a27599..16ee4d3118a5 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts @@ -15,10 +15,12 @@ * limitations under the License. */ -import { describe, test, expect, vi, beforeEach } from 'vitest' +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest' import { flushPromises, mount } from '@vue/test-utils' // import { createTestingPinia } from '@pinia/testing' +import { NPopconfirm } from 'naive-ui' import runningJobs from '@/views/jobs/running-jobs' +import jobOperations from '@/views/jobs/job-operations' import { createApp } from 'vue' import { createPinia, setActivePinia } from 'pinia' import i18n from '@/locales' @@ -26,17 +28,51 @@ import finishedJobs from '@/views/jobs/finished-jobs' import { JobsService } from '@/service/job' import type { JobPage, Job } from '@/service/job/types' +const routeState = vi.hoisted(() => ({ + query: {} as Record, + push: vi.fn() +})) + +vi.mock('vue-router', () => ({ + useRoute: () => ({ + query: routeState.query + }), + useRouter: () => ({ + push: routeState.push + }) +})) + describe('jobs', () => { const app = createApp({}) beforeEach(() => { const pinia = createPinia() app.use(pinia) setActivePinia(createPinia()) + routeState.query = {} + routeState.push.mockReset() + }) + afterEach(() => { + vi.restoreAllMocks() }) test('Running Jobs component', async () => { - const mockData = {} as JobPage + const mockData = { + data: [ + { + jobId: '888413907541032961', + jobName: 'SeaTunnel_Job', + jobStatus: 'RUNNING', + errorMsg: '', + createTime: '2024-09-17 21:19:41', + finishTime: '' + } + ] as Job[], + total: 1 + } as JobPage vi.spyOn(JobsService, 'getRunningJobs').mockResolvedValue(mockData) + const stopJobSpy = vi.spyOn(JobsService, 'stopJob').mockResolvedValue({ + jobId: '888413907541032961' + }) const wrapper = mount(runningJobs, { global: { // plugins: [createTestingPinia({ createSpy: vi.fn() }), i18n] @@ -45,9 +81,34 @@ describe('jobs', () => { }) await flushPromises() expect(wrapper.text()).toContain('Running Jobs') + expect(wrapper.text()).toContain('Stop') + expect(wrapper.text()).toContain('Savepoint') + expect(wrapper.text()).toContain('Cancel') + const confirmations = wrapper.findAllComponents(NPopconfirm) + expect(confirmations).toHaveLength(3) + await confirmations[0].props('onPositiveClick')() + expect(stopJobSpy).toHaveBeenCalledWith({ + jobId: '888413907541032961', + isStopWithSavePoint: false, + force: false + }) + await confirmations[1].props('onPositiveClick')() + expect(stopJobSpy).toHaveBeenCalledWith({ + jobId: '888413907541032961', + isStopWithSavePoint: true, + force: false + }) + await confirmations[2].props('onPositiveClick')() + expect(stopJobSpy).toHaveBeenCalledWith({ + jobId: '888413907541032961', + isStopWithSavePoint: false, + force: true + }) + wrapper.unmount() }) test('Finished Jobs component', async () => { - const mockData = { data: [ + const mockData = { + data: [ { jobId: '888413907541032961', jobName: 'SeaTunnel_Job', @@ -56,7 +117,9 @@ describe('jobs', () => { createTime: '2024-09-17 21:19:41', finishTime: '2024-09-17 21:19:44' } - ] as Job[], total: 1} as JobPage + ] as Job[], + total: 1 + } as JobPage vi.spyOn(JobsService, 'getFinishedJobs').mockResolvedValue(mockData) @@ -70,5 +133,39 @@ describe('jobs', () => { expect(JobsService.getFinishedJobs).toHaveBeenCalledWith(1, 10) await flushPromises() expect(wrapper.text()).toContain('SeaTunnel_Job') + wrapper.unmount() + }) + test('Job Operations component', async () => { + routeState.query = { + restoreJobId: '888413907541032961' + } + const submitJobSpy = vi.spyOn(JobsService, 'submitJob').mockResolvedValue({ + jobId: '888413907541032961', + jobName: 'SeaTunnel_Job' + }) + const wrapper = mount(jobOperations, { + global: { + plugins: [i18n] + } + }) + + await flushPromises() + expect(wrapper.text()).toContain('Submit Job') + expect(wrapper.text()).toContain('Config Text') + expect(wrapper.text()).toContain('Config File') + expect(wrapper.text()).toContain('Restore Job ID') + await wrapper.find('textarea').setValue('env { job.mode = "BATCH" }') + const submitButton = wrapper.findAll('button').find((button) => button.text() === 'Submit') + expect(submitButton).toBeTruthy() + await submitButton?.trigger('click') + await flushPromises() + expect(submitJobSpy).toHaveBeenCalledWith({ + config: 'env { job.mode = "BATCH" }', + format: 'hocon', + jobName: '', + jobId: '888413907541032961', + isStartWithSavePoint: true + }) + wrapper.unmount() }) }) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts index 41bc9a222968..550d8e19c592 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts @@ -15,7 +15,7 @@ * limitations under the License. */ -import { describe, test, expect, vi, beforeEach } from 'vitest' +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest' import { flushPromises, mount } from '@vue/test-utils' // import { createTestingPinia } from '@pinia/testing' import { createApp } from 'vue' @@ -25,6 +25,12 @@ import type { Monitor } from '@/service/manager/types' import { managerService } from '@/service/manager' import managers from '@/views/managers' +vi.mock('vue-router', () => ({ + useRoute: () => ({ + path: '/managers/workers' + }) +})) + describe('managers', () => { const app = createApp({}) beforeEach(() => { @@ -32,9 +38,13 @@ describe('managers', () => { app.use(pinia) setActivePinia(createPinia()) }) + afterEach(() => { + vi.restoreAllMocks() + }) test('managers component', async () => { const mockData = [ { + uuid: 'master-1', isMaster: 'true', host: 'localhost', port: '5801', @@ -42,15 +52,24 @@ describe('managers', () => { 'heap.memory.used': '229.6M' }, { + uuid: 'worker-1', + localMember: true, isMaster: 'false', host: 'localhost', port: '5802', + tags: { + zone: 'old' + }, 'physical.memory.total': '3.6G', 'heap.memory.used': '1002.6M' } ] as Monitor[] vi.spyOn(managerService, 'getMonitors').mockResolvedValue(mockData) + const updateTagsSpy = vi.spyOn(managerService, 'updateTags').mockResolvedValue({ + status: 'success', + message: 'update node tags done.' + }) const wrapper = mount(managers, { global: { @@ -62,5 +81,21 @@ describe('managers', () => { expect(managerService.getMonitors).toHaveBeenCalledWith() await flushPromises() expect(wrapper.text()).toContain('localhost') + expect(wrapper.text()).toContain('zone=old') + const selectButton = wrapper.findAll('button').find((button) => button.text() === 'Select') + expect(selectButton).toBeTruthy() + await selectButton?.trigger('click') + await wrapper.find('textarea').setValue('zone=prod') + const updateButton = wrapper.findAll('button').find((button) => button.text() === 'Update Tags') + expect(updateButton).toBeTruthy() + await updateButton?.trigger('click') + await flushPromises() + expect(updateTagsSpy).toHaveBeenCalledWith({ + uuid: 'worker-1', + tags: { + zone: 'prod' + } + }) + wrapper.unmount() }) }) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/operations.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/operations.spec.ts new file mode 100644 index 000000000000..5119ab3a63fd --- /dev/null +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/operations.spec.ts @@ -0,0 +1,109 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, test, expect, vi, afterEach } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import i18n from '@/locales' +import operations from '@/views/operations' +import { operationsService } from '@/service/operations' + +describe('operations', () => { + afterEach(() => { + vi.restoreAllMocks() + }) + + test('Operations component', async () => { + vi.spyOn(operationsService, 'getOptionRules').mockResolvedValue({ + engineType: 'seatunnel', + pluginType: 'source', + pluginName: 'FakeSource', + optionRule: { + optionalOptions: [ + { + key: 'row.num', + type: 'java.lang.Integer', + defaultValue: 5, + description: 'row count' + } + ], + requiredOptions: [], + conditionRules: [ + { + expression: 'format = json', + optionRule: { + optionalOptions: [], + requiredOptions: [ + { + ruleType: 'ABSOLUTELY_REQUIRED', + options: [ + { + key: 'schema', + type: 'java.lang.String', + description: 'schema' + } + ] + } + ] + } + } + ], + valueConstraints: [ + { + expression: 'row.num > 0', + conditionTree: { + option: { + key: 'row.num', + type: 'java.lang.Integer' + }, + expectValue: 0, + compareOperator: '>' + } + } + ] + } + }) + vi.spyOn(operationsService, 'getHttpServiceStatus').mockResolvedValue({ + httpEnabled: true, + httpsEnabled: false, + configuredHttpPort: 5801, + configuredHttpsPort: 58443, + httpPort: 8080, + httpsPort: 8443, + contextPath: '', + dynamicPortEnabled: false, + portRange: 100, + basicAuthEnabled: false, + mutualTlsEnabled: false + }) + + const wrapper = mount(operations, { + global: { + plugins: [i18n] + } + }) + + await flushPromises() + expect(wrapper.text()).toContain('Connector Option Rules') + expect(wrapper.text()).toContain('HTTP Service Status') + expect(wrapper.text()).toContain('row.num') + expect(wrapper.text()).toContain('Condition Rules') + expect(wrapper.text()).toContain('format = json') + expect(wrapper.text()).toContain('Value Constraints') + expect(wrapper.text()).toContain('row.num > 0') + wrapper.unmount() + }) +}) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/checkpoints.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/checkpoints.tsx new file mode 100644 index 000000000000..a672da8d2179 --- /dev/null +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/checkpoints.tsx @@ -0,0 +1,187 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { defineComponent, onMounted, ref } from 'vue' +import { NAlert, NButton, NDataTable, NSpace, NTag, type DataTableColumns } from 'naive-ui' +import { useI18n } from 'vue-i18n' +import { useRouter } from 'vue-router' +import { JobsService } from '@/service/job' +import type { + CheckpointHistoryRecord, + CheckpointInfo, + CheckpointOverview, + CheckpointPipeline +} from '@/service/job/types' + +export default defineComponent({ + props: { + jobId: { + type: String, + required: true + } + }, + setup(props) { + const { t } = useI18n() + const router = useRouter() + const overview = ref(null) + const history = ref([]) + const loading = ref(false) + const error = ref('') + + const checkpointLabel = (checkpoint?: CheckpointInfo | null) => { + if (!checkpoint) { + return '-' + } + return `${checkpoint.checkpointType || '-'} #${checkpoint.checkpointId}` + } + + const refresh = async () => { + loading.value = true + error.value = '' + try { + const [overviewResponse, historyResponse] = await Promise.all([ + JobsService.getCheckpointOverview(props.jobId), + JobsService.getCheckpointHistory(props.jobId, { limit: 50 }) + ]) + overview.value = overviewResponse + history.value = historyResponse || [] + } catch (e) { + error.value = t('detail.checkpoints.loadFailed') + } finally { + loading.value = false + } + } + + onMounted(refresh) + + const restoreLatestState = () => { + router.push({ + name: 'jobs', + query: { + restoreJobId: props.jobId + } + }) + } + + const pipelineColumns: DataTableColumns = [ + { title: t('detail.checkpoints.pipeline'), key: 'pipelineId' }, + { + title: t('detail.checkpoints.triggered'), + key: 'triggered', + render: (row) => row.counts?.triggered ?? 0 + }, + { + title: t('detail.checkpoints.completed'), + key: 'completed', + render: (row) => row.counts?.completed ?? 0 + }, + { + title: t('detail.checkpoints.failed'), + key: 'failed', + render: (row) => row.counts?.failed ?? 0 + }, + { + title: t('detail.checkpoints.inProgress'), + key: 'inProgress', + render: (row) => row.counts?.inProgress ?? 0 + }, + { + title: t('detail.checkpoints.restored'), + key: 'restored', + render: (row) => row.counts?.restored ?? 0 + }, + { + title: t('detail.checkpoints.latestCompleted'), + key: 'latestCompleted', + render: (row) => checkpointLabel(row.latestCompleted) + }, + { + title: t('detail.checkpoints.latestSavepoint'), + key: 'latestSavepoint', + render: (row) => checkpointLabel(row.latestSavepoint) + }, + { + title: t('detail.checkpoints.action'), + key: 'actions', + render: () => ( + + {t('detail.checkpoints.restoreLatest')} + + ) + } + ] + + const historyColumns: DataTableColumns = [ + { title: t('detail.checkpoints.pipeline'), key: 'pipelineId' }, + { + title: t('detail.checkpoints.checkpoint'), + key: 'checkpoint', + render: (row) => checkpointLabel(row.checkpoint) + }, + { + title: t('detail.checkpoints.status'), + key: 'status', + render: (row) => {row.checkpoint?.status || '-'} + }, + { + title: t('detail.checkpoints.duration'), + key: 'durationMillis', + render: (row) => row.checkpoint?.durationMillis ?? '-' + }, + { + title: t('detail.checkpoints.stateSize'), + key: 'stateSize', + render: (row) => row.checkpoint?.stateSize ?? '-' + }, + { + title: t('detail.checkpoints.failureReason'), + key: 'failureReason', + render: (row) => row.checkpoint?.failureReason || '-' + } + ] + + return () => ( + + + + {overview.value?.updatedAt + ? t('detail.checkpoints.updatedAt', { time: overview.value.updatedAt }) + : t('detail.checkpoints.noSnapshot')} + + + {t('detail.checkpoints.refresh')} + + + {error.value && {error.value}} + + + + ) + } +}) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/detail.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/detail.tsx index cf15932833c5..d78c0ba2bbd3 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/detail.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/detail.tsx @@ -37,6 +37,7 @@ import { getColorFromStatus } from '@/utils/getTypeFromStatus' import './detail.scss' import Configuration from '@/components/configuration' import JobLog from '@/components/job-log' +import Checkpoints from '@/views/jobs/checkpoints' import { formatPercentFromRatio } from '@/utils/format' import { getRealtimeJobEdges, @@ -612,6 +613,9 @@ export default defineComponent({ + + + diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/index.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/index.tsx index 6f93c13b1974..295682cc6151 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/index.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/index.tsx @@ -15,8 +15,9 @@ * limitations under the License. */ -import { defineComponent, getCurrentInstance, h, ref } from 'vue' -import { NSpace, NLayout, NLayoutContent } from 'naive-ui' +import { defineComponent } from 'vue' +import { NLayout, NLayoutContent } from 'naive-ui' +import JobOperations from '@/views/jobs/job-operations' import RunningJobs from '@/views/jobs/running-jobs' import FinishedJobs from '@/views/jobs/finished-jobs' @@ -26,6 +27,7 @@ export default defineComponent({ return ( + diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/job-operations.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/job-operations.tsx new file mode 100644 index 000000000000..3f17ad5fd12a --- /dev/null +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/job-operations.tsx @@ -0,0 +1,286 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { defineComponent, ref } from 'vue' +import { + NAlert, + NButton, + NForm, + NFormItem, + NInput, + NSelect, + NSpace, + NSwitch, + NTabPane, + NTabs, + NUpload +} from 'naive-ui' +import type { SelectOption, UploadFileInfo } from 'naive-ui' +import { useI18n } from 'vue-i18n' +import { useRoute } from 'vue-router' +import { JobsService } from '@/service/job' +import type { ConfigFormat, SubmitJobResponse } from '@/service/job/types' + +type FeedbackType = 'success' | 'warning' | 'error' + +interface Feedback { + type: FeedbackType + message: string +} + +const configFormatOptions: SelectOption[] = [ + { label: 'HOCON', value: 'hocon' }, + { label: 'JSON', value: 'json' }, + { label: 'SQL', value: 'sql' } +] + +export default defineComponent({ + setup() { + const { t } = useI18n() + const route = useRoute() + const initialRestoreJobId = + typeof route.query.restoreJobId === 'string' ? route.query.restoreJobId : '' + const textJobName = ref('') + const fileJobName = ref('') + const textRestoreJobId = ref(initialRestoreJobId) + const fileRestoreJobId = ref(initialRestoreJobId) + const textStartWithSavepoint = ref(Boolean(initialRestoreJobId)) + const fileStartWithSavepoint = ref(Boolean(initialRestoreJobId)) + const configFormat = ref('hocon') + const configContent = ref('') + const fileList = ref([]) + const feedback = ref(null) + const submittingText = ref(false) + const submittingFile = ref(false) + + const setFeedback = (type: FeedbackType, message: string) => { + feedback.value = { type, message } + } + + const formatSubmitSuccess = (response: SubmitJobResponse) => { + const jobLabel = response.jobName + ? `${response.jobName} (${response.jobId})` + : `${response.jobId}` + return t('jobs.operations.submitSuccess', { job: jobLabel }) + } + + const submitText = async () => { + if (!configContent.value.trim()) { + setFeedback('warning', t('jobs.operations.configRequired')) + return + } + if (textStartWithSavepoint.value && !textRestoreJobId.value.trim()) { + setFeedback('warning', t('jobs.operations.restoreJobIdRequired')) + return + } + + submittingText.value = true + feedback.value = null + try { + const response = await JobsService.submitJob({ + config: configContent.value, + format: configFormat.value, + jobName: textJobName.value, + jobId: textRestoreJobId.value, + isStartWithSavePoint: textStartWithSavepoint.value + }) + setFeedback('success', formatSubmitSuccess(response)) + } catch (error) { + setFeedback('error', t('jobs.operations.submitFailed')) + } finally { + submittingText.value = false + } + } + + const submitFile = async () => { + const file = fileList.value[0]?.file + if (!file) { + setFeedback('warning', t('jobs.operations.fileRequired')) + return + } + if (fileStartWithSavepoint.value && !fileRestoreJobId.value.trim()) { + setFeedback('warning', t('jobs.operations.restoreJobIdRequired')) + return + } + + submittingFile.value = true + feedback.value = null + try { + const response = await JobsService.submitJobByUploadFile({ + file, + jobName: fileJobName.value, + jobId: fileRestoreJobId.value, + isStartWithSavePoint: fileStartWithSavepoint.value + }) + setFeedback('success', formatSubmitSuccess(response)) + } catch (error) { + setFeedback('error', t('jobs.operations.submitFailed')) + } finally { + submittingFile.value = false + } + } + + return () => ( +

+

{t('jobs.operations.title')}

+ {feedback.value && ( + { + feedback.value = null + }} + > + {feedback.value.message} + + )} + + + + + { + textJobName.value = value + }} + /> + + + { + configFormat.value = value as ConfigFormat + }} + /> + + + { + textStartWithSavepoint.value = value + }} + /> + + {textStartWithSavepoint.value && ( + + { + textRestoreJobId.value = value + }} + /> + + )} + + { + configContent.value = value + }} + /> + + + { + configContent.value = '' + textJobName.value = '' + textRestoreJobId.value = '' + textStartWithSavepoint.value = false + }} + > + {t('jobs.operations.reset')} + + + {t('jobs.operations.submit')} + + + + + + + + { + fileJobName.value = value + }} + /> + + + { + fileList.value = nextFileList + }} + > + {{ + default: () => {t('jobs.operations.chooseFile')} + }} + + + + { + fileStartWithSavepoint.value = value + }} + /> + + {fileStartWithSavepoint.value && ( + + { + fileRestoreJobId.value = value + }} + /> + + )} + + { + fileList.value = [] + fileJobName.value = '' + fileRestoreJobId.value = '' + fileStartWithSavepoint.value = false + }} + > + {t('jobs.operations.reset')} + + + {t('jobs.operations.submit')} + + + + + +
+ ) + } +}) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/running-jobs.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/running-jobs.tsx index f5daa5f84e27..e428a3119e58 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/running-jobs.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/running-jobs.tsx @@ -16,15 +16,21 @@ */ import { defineComponent, h, onUnmounted, ref } from 'vue' -import { NDataTable, NTag } from 'naive-ui' +import { NAlert, NButton, NDataTable, NPopconfirm, NSpace, NTag } from 'naive-ui' import { useI18n } from 'vue-i18n' import { JobsService } from '@/service/job' import type { DataTableColumns } from 'naive-ui' -import { NButton } from 'naive-ui' import type { Job } from '@/service/job/types' import { useRouter } from 'vue-router' import { getColorFromStatus } from '@/utils/getTypeFromStatus' +type FeedbackType = 'success' | 'error' + +interface Feedback { + type: FeedbackType + message: string +} + export default defineComponent({ setup() { const { t } = useI18n() @@ -33,15 +39,43 @@ export default defineComponent({ const page = ref(1) const pageSize = ref(10) const total = ref(0) + const actionLoading = ref('') + const feedback = ref(null) - let timer: NodeJS.Timeout + let timer: ReturnType | undefined + let fetchVersion = 0 const fetch = async () => { - const res = await JobsService.getRunningJobs(page.value, pageSize.value) - jobs.value = res.data - total.value = res.total - timer = setTimeout(fetch, 5000) + if (timer) { + clearTimeout(timer) + timer = undefined + } + const currentVersion = ++fetchVersion + try { + const res = await JobsService.getRunningJobs(page.value, pageSize.value) + if (currentVersion !== fetchVersion) { + return + } + jobs.value = res.data || [] + total.value = res.total || 0 + } catch (error) { + if (currentVersion === fetchVersion) { + feedback.value = { + type: 'error', + message: t('jobs.actions.refreshFailed') + } + } + } finally { + if (currentVersion === fetchVersion) { + timer = setTimeout(fetch, 5000) + } + } } - onUnmounted(() => clearTimeout(timer)) + onUnmounted(() => { + fetchVersion++ + if (timer) { + clearTimeout(timer) + } + }) fetch() @@ -51,6 +85,49 @@ export default defineComponent({ router.push({ name: 'detail', params: { jobId: job.jobId } }) } + const controlJob = async (job: Job, force: boolean, savepoint = false) => { + const action = savepoint ? 'savepoint' : force ? 'cancel' : 'stop' + actionLoading.value = `${job.jobId}-${action}` + feedback.value = null + try { + await JobsService.stopJob({ + jobId: job.jobId, + isStopWithSavePoint: savepoint, + force + }) + feedback.value = { + type: 'success', + message: t( + savepoint + ? 'jobs.actions.savepointSuccess' + : force + ? 'jobs.actions.cancelSuccess' + : 'jobs.actions.stopSuccess', + { + job: job.jobName || job.jobId + } + ) + } + await fetch() + } catch (error) { + feedback.value = { + type: 'error', + message: t( + savepoint + ? 'jobs.actions.savepointFailed' + : force + ? 'jobs.actions.cancelFailed' + : 'jobs.actions.stopFailed', + { + job: job.jobName || job.jobId + } + ) + } + } finally { + actionLoading.value = '' + } + } + return [ { title: 'No', @@ -77,9 +154,9 @@ export default defineComponent({ key: 'jobStatus', render(row) { return ( - - {row.jobStatus} - + + {row.jobStatus} + ) } }, @@ -87,15 +164,84 @@ export default defineComponent({ title: 'Action', key: 'actions', render(row) { - return h( - NButton, - { - strong: true, - tertiary: true, - size: 'small', - onClick: () => view(row) - }, - { default: () => 'View' } + return ( + + {h( + NButton, + { + strong: true, + tertiary: true, + size: 'small', + onClick: () => view(row) + }, + { default: () => t('jobs.actions.view') } + )} + controlJob(row, false)} + > + {{ + trigger: () => ( + + {t('jobs.actions.stop')} + + ), + default: () => + t('jobs.actions.stopConfirmMessage', { + job: row.jobName || row.jobId + }) + }} + + controlJob(row, false, true)} + > + {{ + trigger: () => ( + + {t('jobs.actions.savepoint')} + + ), + default: () => + t('jobs.actions.savepointConfirmMessage', { + job: row.jobName || row.jobId + }) + }} + + controlJob(row, true)} + > + {{ + trigger: () => ( + + {t('jobs.actions.cancel')} + + ), + default: () => + t('jobs.actions.cancelConfirmMessage', { + job: row.jobName || row.jobId + }) + }} + + ) } } @@ -104,9 +250,25 @@ export default defineComponent({ const columns = createColumns() return () => ( -
-

{t('jobs.runningJobs')}

- +

{t('jobs.runningJobs')}

+ {feedback.value && ( + { + feedback.value = null + }} + > + {feedback.value.message} + + )} + -
+ }} + bordered={false} + /> + ) } }) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx index 758a80343428..dc68b9aa6801 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx @@ -14,12 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { defineComponent, getCurrentInstance, h, ref } from 'vue' -import { useMessage, NDataTable } from 'naive-ui' +import { defineComponent, ref } from 'vue' +import { + NAlert, + NButton, + NDataTable, + NForm, + NFormItem, + NInput, + NLayout, + NLayoutContent, + NSpace, + NTag, + NTooltip +} from 'naive-ui' import { useI18n } from 'vue-i18n' import type { DataTableColumns } from 'naive-ui' -import { NButton } from 'naive-ui' -import { NSpace, NLayout, NLayoutContent } from 'naive-ui' import { managerService } from '@/service/manager' import type { Monitor } from '@/service/manager/types' import { useRoute } from 'vue-router' @@ -29,17 +39,82 @@ export default defineComponent({ const { t } = useI18n() const route = useRoute() const monitors = ref([] as Monitor[]) + const selectedMonitor = ref(null) + const tagContent = ref('') + const tagMessage = ref('') + const tagError = ref('') + const tagLoading = ref(false) const fetch = async () => { let res = await managerService.getMonitors() const isMaster = route?.path.endsWith('/master') || false res = res.filter((row) => row.isMaster === String(isMaster)) || [] monitors.value = res + if (selectedMonitor.value) { + selectedMonitor.value = + res.find((row) => row.uuid && row.uuid === selectedMonitor.value?.uuid) || null + } } fetch() + const parseTags = () => { + const tags: Record = {} + for (const rawLine of tagContent.value.split('\n')) { + const line = rawLine.trim() + if (!line) { + continue + } + const separatorIndex = line.indexOf('=') + if (separatorIndex <= 0) { + throw new Error(t('managers.tags.invalid')) + } + tags[line.substring(0, separatorIndex).trim()] = line.substring(separatorIndex + 1).trim() + } + return tags + } + + const updateTags = async (clear = false) => { + tagLoading.value = true + tagMessage.value = '' + tagError.value = '' + try { + if (!selectedMonitor.value) { + tagError.value = t('managers.tags.workerRequired') + return + } + await managerService.updateTags({ + uuid: selectedMonitor.value.uuid, + tags: clear ? {} : parseTags() + }) + if (clear) { + tagContent.value = '' + } + tagMessage.value = t('managers.tags.success') + } catch (error) { + tagError.value = error instanceof Error ? error.message : t('managers.tags.failed') + } finally { + tagLoading.value = false + } + } + + const selectMonitor = (row: Monitor) => { + selectedMonitor.value = row + tagContent.value = Object.entries(row.tags || {}) + .map(([key, value]) => `${key}=${value}`) + .join('\n') + tagMessage.value = '' + tagError.value = '' + } + + const formatTags = (tags?: Record) => { + const entries = Object.entries(tags || {}) + if (!entries.length) { + return '-' + } + return entries.map(([key, value]) => `${key}=${value}`).join(', ') + } + function createColumns(): DataTableColumns { - const view = (row: Monitor) => {} return [ { title: 'Host', @@ -56,22 +131,44 @@ export default defineComponent({ { title: 'Heap MEM Used', key: 'heap.memory.used' - // }, - // { - // title: 'Action', - // key: 'actions', - // render(row) { - // return h( - // NButton, - // { - // strong: true, - // tertiary: true, - // size: 'small', - // onClick: () => view(row) - // }, - // { default: () => 'View' } - // ) - // } + }, + { + title: 'Tags', + key: 'tags', + render: (row) => formatTags(row.tags) + }, + { + title: 'Action', + key: 'actions', + render(row) { + const selected = Boolean(row.uuid && selectedMonitor.value?.uuid === row.uuid) + return ( + + {row.localMember && ( + + {t('managers.tags.local')} + + )} + selectMonitor(row)} + > + {t('managers.tags.select')} + + {!row.localMember && ( + + {{ + trigger: () => {t('managers.tags.remote')}, + default: () => t('managers.tags.remoteHint') + }} + + )} + + ) + } } ] } @@ -80,6 +177,63 @@ export default defineComponent({ return () => ( + {!route?.path.endsWith('/master') && ( +
+ +

{t('managers.tags.title')}

+ + {selectedMonitor.value + ? `${selectedMonitor.value.host}:${selectedMonitor.value.port}` + : t('managers.tags.noWorkerSelected')} + +
+ {tagMessage.value && ( + (tagMessage.value = '')} + > + {tagMessage.value} + + )} + {tagError.value && ( + (tagError.value = '')}> + {tagError.value} + + )} + + + { + tagContent.value = value + }} + /> + + + updateTags(true)} + > + {t('managers.tags.clear')} + + updateTags()} + > + {t('managers.tags.update')} + + + +
+ )}

{t('managers.managers')}

('source') + const pluginName = ref('FakeSource') + const optionRules = ref(null) + const httpStatus = ref(null) + const optionLoading = ref(false) + const statusLoading = ref(false) + const optionError = ref('') + const statusError = ref('') + + const pluginTypeOptions = [ + { label: 'Source', value: 'source' }, + { label: 'Sink', value: 'sink' }, + { label: 'Transform', value: 'transform' } + ] + + const optionRows = () => { + const optional = + optionRules.value?.optionRule?.optionalOptions?.map((option) => ({ + ...option, + section: t('operations.optionRules.optional'), + ruleType: '-', + expression: '-' + })) || [] + const required = + optionRules.value?.optionRule?.requiredOptions?.flatMap((rule: RequiredOptionRule) => + (rule.options || []).map((option) => ({ + ...option, + section: t('operations.optionRules.required'), + ruleType: rule.ruleType, + expression: rule.expression || '-' + })) + ) || [] + return [...required, ...optional] + } + + const conditionRows = (): ConditionRuleRow[] => + (optionRules.value?.optionRule?.conditionRules || []).map((rule: ConditionRule) => ({ + expression: rule.expression || '-', + requiredCount: rule.optionRule?.requiredOptions?.length || 0, + optionalCount: rule.optionRule?.optionalOptions?.length || 0, + nestedConditionCount: rule.optionRule?.conditionRules?.length || 0 + })) + + const valueConstraintRows = (): ValueConstraintRow[] => + (optionRules.value?.optionRule?.valueConstraints || []).map((rule: ValueConstraint) => ({ + expression: rule.expression || '-', + condition: rule.conditionTree ? JSON.stringify(rule.conditionTree) : '-' + })) + + const fetchOptionRules = async () => { + if (!pluginName.value.trim()) { + optionError.value = t('operations.optionRules.pluginRequired') + return + } + + optionLoading.value = true + optionError.value = '' + try { + optionRules.value = await operationsService.getOptionRules( + pluginType.value, + pluginName.value.trim() + ) + } catch (e) { + optionRules.value = null + optionError.value = t('operations.optionRules.loadFailed') + } finally { + optionLoading.value = false + } + } + + const fetchHttpStatus = async () => { + statusLoading.value = true + statusError.value = '' + try { + httpStatus.value = await operationsService.getHttpServiceStatus() + } catch (e) { + httpStatus.value = null + statusError.value = t('operations.httpStatus.loadFailed') + } finally { + statusLoading.value = false + } + } + + onMounted(() => { + fetchOptionRules() + fetchHttpStatus() + }) + + const optionColumns: DataTableColumns = [ + { title: t('operations.optionRules.section'), key: 'section' }, + { title: t('operations.optionRules.ruleType'), key: 'ruleType' }, + { title: t('operations.optionRules.expression'), key: 'expression' }, + { title: t('operations.optionRules.key'), key: 'key' }, + { title: t('operations.optionRules.type'), key: 'type' }, + { + title: t('operations.optionRules.defaultValue'), + key: 'defaultValue', + render: (row) => + row.defaultValue === undefined || row.defaultValue === null + ? '-' + : String(row.defaultValue) + }, + { + title: t('operations.optionRules.description'), + key: 'description', + render: (row) => row.description || '-' + } + ] + + const conditionColumns: DataTableColumns = [ + { title: t('operations.optionRules.expression'), key: 'expression' }, + { + title: t('operations.optionRules.requiredCount'), + key: 'requiredCount' + }, + { + title: t('operations.optionRules.optionalCount'), + key: 'optionalCount' + }, + { + title: t('operations.optionRules.conditionCount'), + key: 'nestedConditionCount' + } + ] + + const valueConstraintColumns: DataTableColumns = [ + { title: t('operations.optionRules.expression'), key: 'expression' }, + { title: t('operations.optionRules.condition'), key: 'condition' } + ] + + const enabledTag = (enabled?: boolean) => ( + + {enabled ? t('operations.httpStatus.enabled') : t('operations.httpStatus.disabled')} + + ) + + return () => ( + + + +
+

{t('operations.optionRules.title')}

+ + + { + pluginType.value = value as PluginType + }} + /> + + + { + pluginName.value = value + }} + /> + + + + {t('operations.optionRules.load')} + + + + {optionError.value && ( + + {optionError.value} + + )} + +

+ {t('operations.optionRules.conditionRules')} +

+ +

+ {t('operations.optionRules.valueConstraints')} +

+ +
+
+ +

{t('operations.httpStatus.title')}

+ + {t('operations.httpStatus.refresh')} + +
+ {statusError.value && ( + + {statusError.value} + + )} + + + {enabledTag(httpStatus.value?.httpEnabled)} + + + {httpStatus.value?.httpPort ?? '-'} + + + {enabledTag(httpStatus.value?.httpsEnabled)} + + + {httpStatus.value?.httpsPort ?? '-'} + + + {httpStatus.value?.contextPath || '/'} + + + {enabledTag(httpStatus.value?.dynamicPortEnabled)} + + + {enabledTag(httpStatus.value?.basicAuthEnabled)} + + + {enabledTag(httpStatus.value?.mutualTlsEnabled)} + + +
+
+
+
+ ) + } +}) From c782fdd65a4c054bb655ec9e48a455f13e8bf0e9 Mon Sep 17 00:00:00 2001 From: DanielLeens Date: Tue, 18 Aug 2026 11:33:27 -0400 Subject: [PATCH 02/19] [Chore][Zeta] Apply spotless for web UI operation controls --- .../org/apache/seatunnel/engine/server/JettyService.java | 6 +++--- .../server/rest/servlet/HttpServiceStatusServlet.java | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/JettyService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/JettyService.java index a31f000bd02b..8fd4886d268e 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/JettyService.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/JettyService.java @@ -222,7 +222,8 @@ public void createJettyServer() { ServletHolder checkpointHistoryHolder = new ServletHolder(new CheckpointHistoryServlet(nodeEngine)); ServletHolder httpServiceStatusHolder = - new ServletHolder(new HttpServiceStatusServlet(nodeEngine, seaTunnelConfig, server)); + new ServletHolder( + new HttpServiceStatusServlet(nodeEngine, seaTunnelConfig, server)); context.addServlet(overviewHolder, convertUrlToPath(REST_URL_OVERVIEW)); context.addServlet(runningJobsHolder, convertUrlToPath(REST_URL_RUNNING_JOBS)); @@ -257,8 +258,7 @@ public void createJettyServer() { context.addServlet( checkpointOverviewHolder, convertUrlToPath(REST_URL_CHECKPOINT_OVERVIEW)); context.addServlet(checkpointHistoryHolder, convertUrlToPath(REST_URL_CHECKPOINT_HISTORY)); - context.addServlet( - httpServiceStatusHolder, convertUrlToPath(REST_URL_HTTP_SERVICE_STATUS)); + context.addServlet(httpServiceStatusHolder, convertUrlToPath(REST_URL_HTTP_SERVICE_STATUS)); server.setHandler(context); diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServlet.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServlet.java index 8f24b216ab3e..b44ecd1a7705 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServlet.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServlet.java @@ -17,13 +17,14 @@ package org.apache.seatunnel.engine.server.rest.servlet; -import org.apache.seatunnel.engine.common.config.SeaTunnelConfig; -import org.apache.seatunnel.engine.common.config.server.HttpConfig; import org.apache.seatunnel.shade.org.eclipse.jetty.server.Connector; import org.apache.seatunnel.shade.org.eclipse.jetty.server.Server; import org.apache.seatunnel.shade.org.eclipse.jetty.server.ServerConnector; import org.apache.seatunnel.shade.org.eclipse.jetty.server.SslConnectionFactory; +import org.apache.seatunnel.engine.common.config.SeaTunnelConfig; +import org.apache.seatunnel.engine.common.config.server.HttpConfig; + import com.hazelcast.internal.json.JsonObject; import com.hazelcast.spi.impl.NodeEngineImpl; From c68a711331886b7da22011276a466cf7c9f474a7 Mon Sep 17 00:00:00 2001 From: DanielLeens Date: Tue, 18 Aug 2026 21:31:27 -0400 Subject: [PATCH 03/19] [Chore][Zeta] Retry flaky CI From 37ca28b6e4139365ae7e9a45acbc6b10e3e446b8 Mon Sep 17 00:00:00 2001 From: DanielLeens Date: Wed, 19 Aug 2026 23:16:01 -0400 Subject: [PATCH 04/19] [Fix][Zeta] Fix Web UI job test type check --- .../seatunnel-engine-ui/src/tests/jobs.spec.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts index 16ee4d3118a5..1b9303f1d90e 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts @@ -86,19 +86,25 @@ describe('jobs', () => { expect(wrapper.text()).toContain('Cancel') const confirmations = wrapper.findAllComponents(NPopconfirm) expect(confirmations).toHaveLength(3) - await confirmations[0].props('onPositiveClick')() + const clickConfirmation = async (index: number) => { + const onPositiveClick = confirmations[index].props('onPositiveClick') as ( + event: MouseEvent + ) => Promise | void + await onPositiveClick(new MouseEvent('click')) + } + await clickConfirmation(0) expect(stopJobSpy).toHaveBeenCalledWith({ jobId: '888413907541032961', isStopWithSavePoint: false, force: false }) - await confirmations[1].props('onPositiveClick')() + await clickConfirmation(1) expect(stopJobSpy).toHaveBeenCalledWith({ jobId: '888413907541032961', isStopWithSavePoint: true, force: false }) - await confirmations[2].props('onPositiveClick')() + await clickConfirmation(2) expect(stopJobSpy).toHaveBeenCalledWith({ jobId: '888413907541032961', isStopWithSavePoint: false, From 1d815881620e07706da4c623f081432ea942fbd1 Mon Sep 17 00:00:00 2001 From: davidzollo Date: Thu, 3 Sep 2026 04:37:15 -0400 Subject: [PATCH 05/19] [Fix][Zeta] Declare servlet test exception --- .../rest/servlet/HttpServiceStatusServletTest.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServletTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServletTest.java index d551a0599b60..56b928c26a5a 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServletTest.java +++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServletTest.java @@ -24,6 +24,7 @@ import org.junit.jupiter.api.Test; +import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -35,10 +36,18 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +/** + * Verifies that HTTP status responses expose only derived operational values and never include + * sensitive configuration values, even when such values are configured. + */ class HttpServiceStatusServletTest { + /** + * Verifies that derived status can be returned without serializing secret configuration, which + * protects credentials and certificate paths from the operations UI. + */ @Test - void shouldNotExposeSensitiveHttpConfiguration() throws IOException { + void shouldNotExposeSensitiveHttpConfiguration() throws IOException, ServletException { SeaTunnelConfig seaTunnelConfig = new SeaTunnelConfig(); HttpConfig httpConfig = seaTunnelConfig.getEngineConfig().getHttpConfig(); httpConfig.setKeyStorePath("/secrets/key-store.p12"); From a947704bfe91c10f3495af99bb26bd62b482dc92 Mon Sep 17 00:00:00 2001 From: davidzollo Date: Tue, 15 Sep 2026 12:48:42 -0400 Subject: [PATCH 06/19] [Fix][Zeta] Harden Web UI operations --- .github/workflows/backend.yml | 9 +- docs/en/engines/zeta/rest-api-v2.md | 7 +- docs/en/engines/zeta/web-ui.md | 6 +- docs/zh/engines/zeta/rest-api-v2.md | 4 +- docs/zh/engines/zeta/web-ui.md | 6 +- .../server/rest/service/BaseService.java | 12 +- .../server/rest/service/JobInfoService.java | 24 ++- .../rest/service/UpdateTagsService.java | 19 +- .../servlet/HttpServiceStatusServlet.java | 30 ++- ...estApiSubmitJobStartWithSavePointTest.java | 28 +++ .../rest/service/UpdateTagsServiceTest.java | 15 ++ .../servlet/HttpServiceStatusServletTest.java | 25 ++- .../src/locales/en_US/detail.ts | 4 +- .../src/locales/en_US/jobs.ts | 16 +- .../src/locales/en_US/managers.ts | 10 +- .../src/locales/en_US/operations.ts | 5 + .../src/locales/zh_CN/detail.ts | 4 +- .../src/locales/zh_CN/jobs.ts | 16 +- .../src/locales/zh_CN/managers.ts | 10 +- .../src/locales/zh_CN/operations.ts | 5 + .../src/service/job/index.ts | 28 ++- .../src/service/job/types.ts | 5 + .../src/service/service.ts | 3 + .../src/tests/checkpoints.spec.ts | 88 +++++++- .../src/tests/jobs.spec.ts | 64 +++++- .../src/tests/managers.spec.ts | 8 + .../src/tests/operations.spec.ts | 11 +- .../src/views/jobs/checkpoints.tsx | 57 +++-- .../src/views/jobs/job-operations.tsx | 198 +++++++++++++----- .../src/views/jobs/running-jobs.tsx | 45 +++- .../src/views/managers/index.tsx | 112 +++++++--- .../src/views/operations/index.tsx | 62 ++++-- 32 files changed, 755 insertions(+), 181 deletions(-) diff --git a/.github/workflows/backend.yml b/.github/workflows/backend.yml index 814bb8f93e55..ef9fca3ebc55 100644 --- a/.github/workflows/backend.yml +++ b/.github/workflows/backend.yml @@ -155,6 +155,7 @@ jobs: outputs: api: ${{ steps.filter.outputs.api }} engine: ${{ steps.filter.outputs.engine }} + ui: ${{ steps.filter.outputs.ui }} engine-e2e: ${{ steps.filter.outputs.engine-e2e }} edge-agent: ${{ steps.filter.outputs.edge-agent }} edge-agent-e2e: ${{ steps.filter.outputs.edge-agent-e2e }} @@ -203,6 +204,12 @@ jobs: file_list=${engine_files#*$'\n'} echo "engine=$true_or_false" >> $GITHUB_OUTPUT echo "engine_files=$file_list" >> $GITHUB_OUTPUT + + ui_files=`python tools/update_modules_check/check_file_updates.py ua $workspace apache/dev origin/$current_branch "seatunnel-engine/seatunnel-engine-ui/**"` + true_or_false=${ui_files%%$'\n'*} + file_list=${ui_files#*$'\n'} + echo "ui=$true_or_false" >> $GITHUB_OUTPUT + echo "ui_files=$file_list" >> $GITHUB_OUTPUT deleted_poms_files=`python tools/update_modules_check/check_file_updates.py d $workspace apache/dev origin/$current_branch "**/pom.xml"` true_or_false=${deleted_poms_files%%$'\n'*} @@ -472,7 +479,7 @@ jobs: npm run build seatunnel-ui: - if: needs.changes.outputs.api == 'true' + if: needs.changes.outputs.api == 'true' || needs.changes.outputs.ui == 'true' needs: [ changes, sanity-check ] name: Build SeaTunnel UI runs-on: ubuntu-latest diff --git a/docs/en/engines/zeta/rest-api-v2.md b/docs/en/engines/zeta/rest-api-v2.md index f447408c9597..f17345b595a7 100644 --- a/docs/en/engines/zeta/rest-api-v2.md +++ b/docs/en/engines/zeta/rest-api-v2.md @@ -1969,8 +1969,9 @@ There is no dedicated `pause`, `resume` or `delete` endpoint. Use the existing j | Goal | How | |-----------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Pause a running job (stop now, resume later) | Call [`/stop-job`](#stop-a-job) with `isStopWithSavePoint: true`. The job stops and a savepoint of its current state is persisted. | -| Resume a paused job | Call [`/submit-job`](#submit-a-job) again with `isStartWithSavePoint: true`, the **same** `jobId` that was stopped, and the same job config. The job restores from its latest savepoint for that `jobId`. | +| Resume a paused job | Call [`/submit-job`](#submit-a-job) again with `restoreMode=SAVEPOINT`, `restoreSourceJobId=`, and the same job config. The job restores from its latest savepoint for that source job. The legacy `isStartWithSavePoint: true` with the same `jobId` remains supported. | | Delete a job | There is no delete endpoint. Stop the job with [`/stop-job`](#stop-a-job) if it is still running. Once a job reaches a finished state, its record is removed automatically after `history-job-expire-minutes` (default 1440 minutes) elapses -- see [History Job Expiry Configuration](separated-cluster-deployment.md#44-history-job-expiry-configuration). | -**Note:** `isStartWithSavePoint: true` requires `jobId` to be provided in the request; submitting -without a `jobId` in that case fails with `Please provide jobId when start with save point.` +**Note:** `restoreMode` requires `restoreSourceJobId`. `isStartWithSavePoint: true` remains a legacy +shortcut and requires `jobId` to be provided in the request; submitting without a `jobId` in that +case fails with `Please provide jobId when start with save point.` diff --git a/docs/en/engines/zeta/web-ui.md b/docs/en/engines/zeta/web-ui.md index 95e05c67251d..ad2aa6879f12 100644 --- a/docs/en/engines/zeta/web-ui.md +++ b/docs/en/engines/zeta/web-ui.md @@ -42,7 +42,7 @@ The Web UI combines visual inspection with common operational actions. It suppor | UI area | Current capability | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Overview | View cluster version, slot usage, worker count, and job counts | -| Jobs | Submit jobs from configuration text or uploaded files, restore jobs from savepoint state, view running and finished jobs, paginate job lists, and open job details | +| Jobs | Submit jobs from configuration text or uploaded files, restore jobs from checkpoint or savepoint state, view running and finished jobs, paginate job lists, and open job details | | Job Detail | View DAG, job metrics, exception text, job configuration, checkpoint overview and history, logs, and realtime observability data | | Operations | Browse connector OptionRule metadata and view safe HTTP, HTTPS, authentication, and mTLS status | | Workers | View worker-node system monitoring information and update tags on the current node | @@ -54,7 +54,7 @@ The Web UI combines visual inspection with common operational actions. It suppor The Jobs page includes a "Submit Job" panel for submitting a new SeaTunnel job without leaving the Web UI. Users can paste JSON, HOCON, or SQL job configuration text, or upload a `.json`, `.conf`, `.config`, or `.sql` configuration file. -The same panel can start a job from savepoint state by enabling restore mode and entering the existing job ID. This reuses the REST API contract `isStartWithSavePoint=true` and `jobId=`, so the submitted configuration still needs to match the job being restored. +The same panel can restore a job from checkpoint or savepoint state by selecting a restore mode and entering the source job ID. It sends the explicit REST parameters `restoreMode=CHECKPOINT|SAVEPOINT` and `restoreSourceJobId=`, so the submitted configuration still needs to match the job being restored. The Web UI does not send a destination job ID for checkpoint restore, so the engine creates a new job ID; savepoint restore retains the source job ID. ### Running Jobs @@ -72,7 +72,7 @@ The Job Detail page contains five main tabs: - **Overview**: shows the job DAG, source and sink throughput metrics, flush-signal metrics, and realtime vertex or edge metrics when observability is enabled. - **Exception**: shows the job error message when the job has failed or reported an exception. - **Configuration**: shows the runtime job configuration exposed by the engine. -- **Checkpoints**: shows checkpoint counts, latest completed checkpoint, latest savepoint, and recent checkpoint history. The restore latest state action opens the submit panel with the source job ID prefilled for savepoint or latest checkpoint-state restore. +- **Checkpoints**: shows checkpoint counts, latest completed checkpoint, latest savepoint, and recent checkpoint history. It offers separate checkpoint and savepoint restore actions only when every pipeline has a corresponding restorable state, then opens the submit panel with the source job ID and restore mode prefilled. - **Log**: shows job log files returned by the engine log API. #### Realtime Observability diff --git a/docs/zh/engines/zeta/rest-api-v2.md b/docs/zh/engines/zeta/rest-api-v2.md index 20a56594308a..644cf01fbc8a 100644 --- a/docs/zh/engines/zeta/rest-api-v2.md +++ b/docs/zh/engines/zeta/rest-api-v2.md @@ -1937,8 +1937,8 @@ Checkpoint 信息字段: | 目标 | 方法 | |---------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------| | 暂停一个正在运行的作业(先停止,之后再恢复) | 调用 [`/stop-job`](#停止作业),并设置 `isStopWithSavePoint: true`。作业会停止运行,同时会保存一个当前状态的 savepoint。 | -| 恢复一个已暂停的作业 | 再次调用 [`/submit-job`](#提交作业),设置 `isStartWithSavePoint: true`,并传入与之前停止时**相同**的 `jobId` 和相同的作业配置。作业会基于该 `jobId` 最近一次的 savepoint 恢复。 | +| 恢复一个已暂停的作业 | 再次调用 [`/submit-job`](#提交作业),设置 `restoreMode=SAVEPOINT`、`restoreSourceJobId=` 并传入相同的作业配置。作业会基于该来源作业最近一次的 savepoint 恢复。仍支持使用相同 `jobId` 加 `isStartWithSavePoint: true` 的旧契约。 | | 删除一个作业 | 没有专门的删除接口。如果作业仍在运行,先通过 [`/stop-job`](#停止作业) 停止它;作业进入结束状态后,其记录会在 `history-job-expire-minutes`(默认 1440 分钟)到期后自动清理,参见[历史作业过期配置](separated-cluster-deployment.md#44-历史作业过期配置)。 | -**注意:** 当 `isStartWithSavePoint: true` 时必须提供 `jobId`;不提供 `jobId` 会导致请求失败,报错信息为 +**注意:** 设置 `restoreMode` 时必须提供 `restoreSourceJobId`。`isStartWithSavePoint: true` 仍是旧的快捷方式,必须提供 `jobId`;不提供 `jobId` 会导致请求失败,报错信息为 `Please provide jobId when start with save point.` diff --git a/docs/zh/engines/zeta/web-ui.md b/docs/zh/engines/zeta/web-ui.md index a03028dcdbca..3593195012cd 100644 --- a/docs/zh/engines/zeta/web-ui.md +++ b/docs/zh/engines/zeta/web-ui.md @@ -42,7 +42,7 @@ Web UI 在可视化巡检之外,也提供常用运维操作:可以提交和 | UI 区域 | 当前能力 | | ---------- | --------------------------------------------------------------------------------------------------------------------- | | Overview | 查看集群版本、slot 使用、worker 数量和作业数量 | -| Jobs | 通过配置文本或上传文件提交作业、从 savepoint 状态恢复启动作业、查看运行中和已完成作业、分页浏览作业列表、进入作业详情 | +| Jobs | 通过配置文本或上传文件提交作业、从 checkpoint 或 savepoint 状态恢复启动作业、查看运行中和已完成作业、分页浏览作业列表、进入作业详情 | | Job Detail | 查看 DAG、作业指标、异常文本、作业配置、checkpoint 概览与历史、日志,以及开启后的实时可观测指标 | | Operations | 浏览 Connector OptionRule 元数据,并查看安全过滤后的 HTTP、HTTPS、认证和 mTLS 状态 | | Workers | 查看 worker 节点系统监控信息,并更新当前节点 tags | @@ -54,7 +54,7 @@ Web UI 在可视化巡检之外,也提供常用运维操作:可以提交和 Jobs 页面提供 “Submit Job” 面板,可以直接在 Web UI 中提交新的 SeaTunnel 作业。用户可以粘贴 JSON、HOCON 或 SQL 任务配置,也可以上传 `.json`、`.conf`、`.config` 或 `.sql` 配置文件。 -同一个面板也支持从 savepoint 状态恢复启动作业:开启恢复模式并填写已有作业 ID 后,会复用 REST API 的 `isStartWithSavePoint=true` 和 `jobId=` 契约,因此提交的配置仍需与被恢复的作业匹配。 +同一个面板也支持从 checkpoint 或 savepoint 状态恢复启动作业:选择恢复模式并填写来源作业 ID 后,会发送明确的 REST 参数 `restoreMode=CHECKPOINT|SAVEPOINT` 和 `restoreSourceJobId=`,因此提交的配置仍需与被恢复的作业匹配。Web UI 不会为 checkpoint 恢复传递目标作业 ID,因此引擎会创建新的作业 ID;savepoint 恢复会保留来源作业 ID。 ### 运行中的作业 @@ -72,7 +72,7 @@ Jobs 页面提供 “Submit Job” 面板,可以直接在 Web UI 中提交新 - **Overview**:展示作业 DAG、source 和 sink 吞吐指标、flush signal 指标,以及开启可观测性后的 vertex 或 edge 实时指标。 - **Exception**:当作业失败或上报异常时,展示异常文本。 - **Configuration**:展示引擎暴露的运行时作业配置。 -- **Checkpoints**:展示 checkpoint 计数、最近完成的 checkpoint、最近的 savepoint 和 checkpoint 历史记录。“恢复最新状态”操作会打开提交面板,并自动带入源作业 ID,用于从 savepoint 或最新 checkpoint 状态恢复提交。 +- **Checkpoints**:展示 checkpoint 计数、最近完成的 checkpoint、最近的 savepoint 和 checkpoint 历史记录。仅当所有 pipeline 都存在对应可恢复状态时,页面才会提供独立的 checkpoint 或 savepoint 恢复操作;操作会打开提交面板并自动带入来源作业 ID 和恢复模式。 - **Log**:展示引擎日志 API 返回的作业日志文件。 #### 实时可观测性(Realtime Observability) diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/BaseService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/BaseService.java index b6df3be39a54..a1e4c39e8d14 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/BaseService.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/BaseService.java @@ -83,6 +83,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -1372,10 +1373,19 @@ protected JsonObject submitJobInternal( .add(RestConstant.JOB_NAME, jobConfig.getName()); } + /** + * Resolves the explicit restore contract before the legacy savepoint flag. + * + *

The explicit mode is normalized because REST callers are not limited to the Web UI. The + * legacy flag remains the fallback for existing clients that do not send {@code restoreMode}. + * + * @param requestParams REST query parameters. + * @return the requested restore mode, or {@link RestoreMode#NONE} when no restore is requested. + */ private RestoreMode resolveRestoreMode(Map requestParams) { String restoreModeValue = requestParams.get(RestConstant.RESTORE_MODE); if (StringUtils.isNotBlank(restoreModeValue)) { - return RestoreMode.valueOf(restoreModeValue.toUpperCase()); + return RestoreMode.valueOf(restoreModeValue.trim().toUpperCase(Locale.ROOT)); } if (Boolean.parseBoolean(requestParams.get(RestConstant.IS_START_WITH_SAVE_POINT))) { return RestoreMode.SAVEPOINT; diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java index 5a9707e2f193..c9348b49d60f 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java @@ -19,6 +19,7 @@ import org.apache.seatunnel.shade.com.typesafe.config.Config; import org.apache.seatunnel.shade.com.typesafe.config.ConfigFactory; +import org.apache.seatunnel.shade.org.apache.commons.lang3.StringUtils; import org.apache.seatunnel.api.common.metrics.JobMetrics; import org.apache.seatunnel.common.utils.DateTimeUtils; @@ -53,6 +54,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -453,7 +455,7 @@ public JsonObject submitJob(Map requestParams, byte[] requestBod throw new IllegalArgumentException("Dry-run is only supported via CLI"); } if (Boolean.parseBoolean(requestParams.get(RestConstant.IS_START_WITH_SAVE_POINT)) - && requestParams.get(RestConstant.JOB_ID) == null) { + && StringUtils.isBlank(requestParams.get(RestConstant.JOB_ID))) { throw new IllegalArgumentException("Please provide jobId when start with save point."); } validateCheckpointRestoreRequest(requestParams); @@ -486,7 +488,7 @@ public JsonObject submitJob(Map requestParams, Config config) { throw new IllegalArgumentException("Dry-run is only supported via CLI"); } if (Boolean.parseBoolean(requestParams.get(RestConstant.IS_START_WITH_SAVE_POINT)) - && requestParams.get(RestConstant.JOB_ID) == null) { + && StringUtils.isBlank(requestParams.get(RestConstant.JOB_ID))) { throw new IllegalArgumentException("Please provide jobId when start with save point."); } validateCheckpointRestoreRequest(requestParams); @@ -521,12 +523,26 @@ public JsonArray submitJobs(byte[] requestBody) { .collect(JsonArray::new, JsonArray::add, JsonArray::add); } + /** + * Validates the explicit restore parameters before parsing the submitted job configuration. + * + *

A blank source ID is equivalent to an omitted source ID. Rejecting it here prevents the + * restore path from issuing a lookup for a null source after configuration parsing begins. + * + * @param requestParams REST query parameters. + */ private void validateCheckpointRestoreRequest(Map requestParams) { String restoreModeValue = requestParams.get(RestConstant.RESTORE_MODE); RestoreMode restoreMode = - restoreModeValue == null ? RestoreMode.NONE : RestoreMode.valueOf(restoreModeValue); + restoreModeValue == null || restoreModeValue.trim().isEmpty() + ? RestoreMode.NONE + : RestoreMode.valueOf(restoreModeValue.trim().toUpperCase(Locale.ROOT)); if (restoreMode.isRestore() - && requestParams.get(RestConstant.RESTORE_SOURCE_JOB_ID) == null) { + && (requestParams.get(RestConstant.RESTORE_SOURCE_JOB_ID) == null + || requestParams + .get(RestConstant.RESTORE_SOURCE_JOB_ID) + .trim() + .isEmpty())) { throw new IllegalArgumentException( "restoreSourceJobId is required when restoreMode=" + restoreMode); } diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java index 0618b4c8074c..88a5cf7b3ff9 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java @@ -72,10 +72,10 @@ private JsonObject updateTags(Map tagParams, MemberImpl localMem Map previousTags = new HashMap<>(localMember.getAttributes()); localMember.updateAttribute(tags); log.info( - "Node tags updated: node={}, {} -> {}", + "Node tags updated: node={}, previousTags={}, tags={}", localMember.getAddress(), - previousTags, - tags); + summarizeTagsForAudit(previousTags), + summarizeTagsForAudit(tags)); return new JsonObject().add("status", "success").add("message", "update node tags done."); } @@ -124,4 +124,17 @@ static Map toStringTags(Map tagParams) { ? value.getValue().toString() : "")); } + + /** + * Produces a content-free audit summary for a user-supplied tag map. + * + *

Tags are arbitrary user input, so neither their keys nor values are safe to write to the + * server log. + * + * @param tags updated tag map. + * @return the number of tags without any tag content. + */ + static String summarizeTagsForAudit(Map tags) { + return tags.size() + " tag(s)"; + } } diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServlet.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServlet.java index b44ecd1a7705..3518f2c4846d 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServlet.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServlet.java @@ -78,10 +78,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) .add("dynamicPortEnabled", httpConfig.isEnableDynamicPort()) .add("portRange", httpConfig.getPortRange()) .add("basicAuthEnabled", httpConfig.isEnableBasicAuth()) - .add( - "mutualTlsEnabled", - hasText(httpConfig.getTrustStorePath()) - && hasText(httpConfig.getTrustStorePassword())); + .add("mutualTlsEnabled", isMutualTlsEnabled()); writeJson(resp, status); } @@ -128,6 +125,31 @@ private boolean hasSslConnectionFactory(ServerConnector connector) { .anyMatch(factory -> factory instanceof SslConnectionFactory); } + /** + * Returns whether an active HTTPS connector requires client certificates. + * + *

The configured trust-store fields are insufficient for this status: mTLS is active only + * when Jetty's effective SSL context requires client authentication. + * + * @return true when an SSL connector is configured to require client authentication. + */ + private boolean isMutualTlsEnabled() { + for (Connector connector : server.getConnectors()) { + if (!(connector instanceof ServerConnector)) { + continue; + } + for (Object factory : ((ServerConnector) connector).getConnectionFactories()) { + if (factory instanceof SslConnectionFactory + && ((SslConnectionFactory) factory) + .getSslContextFactory() + .getNeedClientAuth()) { + return true; + } + } + } + return false; + } + /** * Returns whether a string contains non-whitespace text. * diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java index e6ce345c08f9..1d62cce17366 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java +++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java @@ -229,6 +229,20 @@ public void testSubmitCheckpointRestoreWithoutSourceJobIdReturns400() throws Exc Assertions.assertTrue(response.body.contains("restoreSourceJobId")); } + @Test + public void testSubmitCheckpointRestoreWithBlankSourceJobIdReturns400() throws Exception { + String requestUrl = + "http://localhost:" + + workerRestPort + + "/submit-job?format=json&restoreMode=checkpoint&restoreSourceJobId=%20%20&jobName=" + + TEST_JOB_NAME; + + HttpResponse response = postJson(requestUrl, getRequestBody()); + Assertions.assertEquals(400, response.code, () -> "responseBody=" + response.body); + Assertions.assertTrue(response.body.contains("\"status\":\"fail\"")); + Assertions.assertTrue(response.body.contains("restoreSourceJobId")); + } + @Test public void testSubmitSavepointRestoreWithoutSourceJobIdReturns400() throws Exception { String requestUrl = @@ -243,6 +257,20 @@ public void testSubmitSavepointRestoreWithoutSourceJobIdReturns400() throws Exce Assertions.assertTrue(response.body.contains("restoreSourceJobId")); } + @Test + public void testSubmitLegacySavepointRestoreWithBlankJobIdReturns400() throws Exception { + String requestUrl = + "http://localhost:" + + workerRestPort + + "/submit-job?format=json&isStartWithSavePoint=true&jobId=%20%20&jobName=" + + TEST_JOB_NAME; + + HttpResponse response = postJson(requestUrl, getRequestBody()); + Assertions.assertEquals(400, response.code, () -> "responseBody=" + response.body); + Assertions.assertTrue(response.body.contains("\"status\":\"fail\"")); + Assertions.assertTrue(response.body.contains("Please provide jobId")); + } + @Test public void testBuildJobStartWithCheckpointOnWorkerCreatesNewJobId() throws Exception { Assertions.assertNotNull(masterServer); diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsServiceTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsServiceTest.java index 025821879768..32ae81fed09c 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsServiceTest.java +++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsServiceTest.java @@ -23,6 +23,7 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -64,4 +65,18 @@ void shouldRejectStructuredRequestWithoutTagsObject() { () -> UpdateTagsService.extractStructuredTagParams(request)); assertTrue(error.getMessage().contains("tags field")); } + + @Test + void shouldExcludeTagContentFromAuditSummary() { + Map tags = new HashMap<>(); + tags.put("api-token", "sensitive-value"); + tags.put("zone", "production"); + + String summary = UpdateTagsService.summarizeTagsForAudit(tags); + + assertEquals("2 tag(s)", summary); + assertFalse(summary.contains("api-token")); + assertFalse(summary.contains("sensitive-value")); + assertFalse(summary.contains("production")); + } } diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServletTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServletTest.java index 56b928c26a5a..b02ed0c5baf2 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServletTest.java +++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/HttpServiceStatusServletTest.java @@ -18,6 +18,8 @@ package org.apache.seatunnel.engine.server.rest.servlet; import org.apache.seatunnel.shade.org.eclipse.jetty.server.Server; +import org.apache.seatunnel.shade.org.eclipse.jetty.server.ServerConnector; +import org.apache.seatunnel.shade.org.eclipse.jetty.util.ssl.SslContextFactory; import org.apache.seatunnel.engine.common.config.SeaTunnelConfig; import org.apache.seatunnel.engine.common.config.server.HttpConfig; @@ -65,7 +67,7 @@ void shouldNotExposeSensitiveHttpConfiguration() throws IOException, ServletExce new HttpServiceStatusServlet(null, seaTunnelConfig, new Server()).doGet(null, response); String status = body.toString(); - assertTrue(status.contains("\"mutualTlsEnabled\":true")); + assertFalse(status.contains("\"mutualTlsEnabled\":true")); assertFalse(status.contains("/secrets/key-store.p12")); assertFalse(status.contains("key-store-password")); assertFalse(status.contains("key-manager-password")); @@ -74,4 +76,25 @@ void shouldNotExposeSensitiveHttpConfiguration() throws IOException, ServletExce assertFalse(status.contains("operator")); assertFalse(status.contains("basic-auth-password")); } + + /** + * Verifies that mTLS status reflects the effective Jetty SSL connector, not secret presence. + */ + @Test + void shouldReportMutualTlsFromActiveSslConnector() throws IOException, ServletException { + SeaTunnelConfig seaTunnelConfig = new SeaTunnelConfig(); + seaTunnelConfig.getEngineConfig().getHttpConfig().setEnableHttps(true); + Server server = new Server(); + SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setNeedClientAuth(true); + server.addConnector(new ServerConnector(server, sslContextFactory)); + + HttpServletResponse response = mock(HttpServletResponse.class); + StringWriter body = new StringWriter(); + when(response.getWriter()).thenReturn(new PrintWriter(body)); + + new HttpServiceStatusServlet(null, seaTunnelConfig, server).doGet(null, response); + + assertTrue(body.toString().contains("\"mutualTlsEnabled\":true")); + } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts index 5daef4ae63a1..7acfeddb3c55 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts @@ -73,7 +73,9 @@ export default { stateSize: 'State Size', failureReason: 'Failure Reason', action: 'Action', - restoreLatest: 'Restore Latest State' + restoreLatest: 'Restore Latest State', + restoreFromCheckpoint: 'Restore From Checkpoint', + restoreFromSavepoint: 'Restore From Savepoint' }, liveMetrics: { pinnedTitle: 'Pinned live metrics', diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/jobs.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/jobs.ts index 56ca90ce34b9..ac83c47f41fc 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/jobs.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/jobs.ts @@ -28,17 +28,22 @@ export default { configContent: 'Config', configPlaceholder: 'Paste JSON, HOCON, or SQL job config', configFile: 'Config File', - startWithSavepoint: 'Restore', - restoreJobId: 'Restore Job ID', - restoreJobIdPlaceholder: 'Existing job ID with savepoint state', + restore: 'Restore', + restoreMode: 'Restore Mode', + restoreSourceJobId: 'Restore Source Job ID', + restoreSourceJobIdPlaceholder: 'Existing job ID containing the selected state', chooseFile: 'Choose File', reset: 'Reset', submit: 'Submit', configRequired: 'Job config is required.', fileRequired: 'Please choose a config file.', - restoreJobIdRequired: 'Restore job ID is required when restore is enabled.', + restoreSourceJobIdRequired: 'Restore source job ID is required when restore is enabled.', submitSuccess: 'Submitted {job}.', - submitFailed: 'Failed to submit job.' + submitFailed: 'Failed to submit job.', + submitOutcomeUnknown: 'The submit result is unknown. Refresh jobs before submitting again.', + confirm: 'Confirm', + cancelConfirm: 'Dismiss', + submitConfirmMessage: 'Submit this job?' }, actions: { view: 'View', @@ -56,6 +61,7 @@ export default { savepointFailed: 'Failed to stop {job} with savepoint.', cancelSuccess: 'Cancel request sent for {job}.', cancelFailed: 'Failed to cancel {job}.', + operationOutcomeUnknown: 'The operation result for {job} is unknown. Refresh before retrying.', refreshFailed: 'Failed to refresh running jobs.' } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts index d9beb166eaa4..2317f0181af4 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts @@ -25,12 +25,20 @@ export default { clear: 'Clear Tags', success: 'Node tags updated.', failed: 'Failed to update node tags.', + outcomeUnknown: 'The tag update result is unknown. Refresh before retrying.', + loadFailed: 'Failed to refresh node information.', invalid: 'Each tag line must use key=value.', + contentRequired: 'Enter at least one tag, or use Clear Tags.', + duplicate: 'Tag keys must be unique.', select: 'Select', local: 'Local', remote: 'Remote', remoteHint: 'Open the target node Web UI to update this worker.', noWorkerSelected: 'No worker selected', - workerRequired: 'Please select a worker first.' + workerRequired: 'Please select a worker first.', + confirm: 'Confirm', + cancelConfirm: 'Dismiss', + updateConfirmMessage: 'Update tags for the selected worker?', + clearConfirmMessage: 'Clear all tags for the selected worker?' } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/operations.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/operations.ts index 63a95e57759a..bfac1b0df5b3 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/operations.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/operations.ts @@ -26,11 +26,14 @@ export default { loadFailed: 'Failed to load connector option rules.', required: 'Required', optional: 'Optional', + root: 'Root', + conditional: 'Conditional', conditionRules: 'Condition Rules', valueConstraints: 'Value Constraints', section: 'Section', ruleType: 'Rule Type', expression: 'Expression', + expressionTree: 'Expression Tree', requiredCount: 'Required Options', optionalCount: 'Optional Options', conditionCount: 'Nested Conditions', @@ -38,6 +41,8 @@ export default { key: 'Key', type: 'Type', defaultValue: 'Default', + fallbackKeys: 'Fallback Keys', + optionValues: 'Allowed Values', description: 'Description' }, httpStatus: { diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts index b3ca520b982f..a6bddc4e2244 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts @@ -73,7 +73,9 @@ export default { stateSize: '状态大小', failureReason: '失败原因', action: '操作', - restoreLatest: '恢复最新状态' + restoreLatest: '恢复最新状态', + restoreFromCheckpoint: '从 Checkpoint 恢复', + restoreFromSavepoint: '从 Savepoint 恢复' }, liveMetrics: { pinnedTitle: '已固定实时指标', diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/jobs.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/jobs.ts index 6385a1325457..febfd5a00068 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/jobs.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/jobs.ts @@ -28,17 +28,22 @@ export default { configContent: '配置', configPlaceholder: '粘贴 JSON、HOCON 或 SQL 任务配置', configFile: '配置文件', - startWithSavepoint: '恢复启动', - restoreJobId: '恢复任务 ID', - restoreJobIdPlaceholder: '已有 savepoint 状态的任务 ID', + restore: '恢复启动', + restoreMode: '恢复模式', + restoreSourceJobId: '恢复来源任务 ID', + restoreSourceJobIdPlaceholder: '包含所选状态的已有任务 ID', chooseFile: '选择文件', reset: '重置', submit: '提交', configRequired: '任务配置不能为空。', fileRequired: '请选择配置文件。', - restoreJobIdRequired: '开启恢复启动时必须填写任务 ID。', + restoreSourceJobIdRequired: '开启恢复启动时必须填写恢复来源任务 ID。', submitSuccess: '已提交 {job}。', - submitFailed: '任务提交失败。' + submitFailed: '任务提交失败。', + submitOutcomeUnknown: '无法确认任务是否已提交,请刷新任务列表后再重试。', + confirm: '确认', + cancelConfirm: '关闭', + submitConfirmMessage: '确认提交此任务?' }, actions: { view: '查看', @@ -56,6 +61,7 @@ export default { savepointFailed: '通过保存点停止 {job} 失败。', cancelSuccess: '已发送 {job} 的取消请求。', cancelFailed: '取消 {job} 失败。', + operationOutcomeUnknown: '无法确认 {job} 的操作结果,请刷新后再重试。', refreshFailed: '刷新运行中作业失败。' } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts index fa96715b673c..201e2f110da7 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts @@ -25,12 +25,20 @@ export default { clear: '清空 Tags', success: '节点 Tags 已更新。', failed: '更新节点 Tags 失败。', + outcomeUnknown: '无法确认 Tags 是否已更新,请刷新后再重试。', + loadFailed: '刷新节点信息失败。', invalid: '每行 tag 必须使用 key=value 格式。', + contentRequired: '请至少填写一个 Tag,或使用清空 Tags。', + duplicate: 'Tag 键不能重复。', select: '选择', local: '当前节点', remote: '远端节点', remoteHint: '请打开目标节点自己的 Web UI 更新该 Worker。', noWorkerSelected: '未选择 Worker', - workerRequired: '请先选择一个 Worker。' + workerRequired: '请先选择一个 Worker。', + confirm: '确认', + cancelConfirm: '关闭', + updateConfirmMessage: '确认更新所选 Worker 的 Tags?', + clearConfirmMessage: '确认清空所选 Worker 的全部 Tags?' } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/operations.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/operations.ts index 6b98e1fff259..1aa6873337bf 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/operations.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/operations.ts @@ -26,11 +26,14 @@ export default { loadFailed: '加载 Connector OptionRule 失败。', required: '必填', optional: '可选', + root: '根规则', + conditional: '条件规则', conditionRules: '条件规则', valueConstraints: '取值约束', section: '分组', ruleType: '规则类型', expression: '表达式', + expressionTree: '表达式树', requiredCount: '必填项数量', optionalCount: '可选项数量', conditionCount: '嵌套条件数量', @@ -38,6 +41,8 @@ export default { key: '配置项', type: '类型', defaultValue: '默认值', + fallbackKeys: '回退键', + optionValues: '允许值', description: '说明' }, httpStatus: { diff --git a/seatunnel-engine/seatunnel-engine-ui/src/service/job/index.ts b/seatunnel-engine/seatunnel-engine-ui/src/service/job/index.ts index 5de57f4803b1..c1de0372191c 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/service/job/index.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/service/job/index.ts @@ -38,13 +38,20 @@ const optionalParam = (value?: string) => { return normalized ? normalized : undefined } +const operationRequestConfig = { + timeout: 0 +} + export const submitJob = (request: SubmitJobRequest) => post('/submit-job', request.config, { + ...operationRequestConfig, params: { format: request.format, jobName: optionalParam(request.jobName), jobId: optionalParam(request.jobId), - isStartWithSavePoint: request.isStartWithSavePoint || undefined + isStartWithSavePoint: request.isStartWithSavePoint || undefined, + restoreMode: request.restoreMode, + restoreSourceJobId: optionalParam(request.restoreSourceJobId) }, headers: { 'Content-Type': 'text/plain;charset=UTF-8' @@ -55,20 +62,27 @@ export const submitJobByUploadFile = (request: SubmitJobFileRequest) => { const formData = new FormData() formData.append('config_file', request.file) return post('/submit-job/upload', formData, { + ...operationRequestConfig, params: { jobName: optionalParam(request.jobName), jobId: optionalParam(request.jobId), - isStartWithSavePoint: request.isStartWithSavePoint || undefined + isStartWithSavePoint: request.isStartWithSavePoint || undefined, + restoreMode: request.restoreMode, + restoreSourceJobId: optionalParam(request.restoreSourceJobId) } }) } export const stopJob = (request: StopJobRequest) => - post('/stop-job', { - jobId: request.jobId, - isStopWithSavePoint: request.isStopWithSavePoint ?? false, - force: request.force ?? false - }) + post( + '/stop-job', + { + jobId: request.jobId, + isStopWithSavePoint: request.isStopWithSavePoint ?? false, + force: request.force ?? false + }, + operationRequestConfig + ) export const getCheckpointOverview = (jobId: string) => get(`/jobs/checkpoints/${jobId}`) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/service/job/types.ts b/seatunnel-engine/seatunnel-engine-ui/src/service/job/types.ts index b287495e2cd8..599a6fbd99e2 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/service/job/types.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/service/job/types.ts @@ -101,6 +101,7 @@ export interface JobPage { } export type ConfigFormat = 'json' | 'hocon' | 'sql' +export type RestoreMode = 'CHECKPOINT' | 'SAVEPOINT' export interface SubmitJobRequest { config: string @@ -108,6 +109,8 @@ export interface SubmitJobRequest { jobName?: string jobId?: string isStartWithSavePoint?: boolean + restoreMode?: RestoreMode + restoreSourceJobId?: string } export interface SubmitJobFileRequest { @@ -115,6 +118,8 @@ export interface SubmitJobFileRequest { jobName?: string jobId?: string isStartWithSavePoint?: boolean + restoreMode?: RestoreMode + restoreSourceJobId?: string } export interface SubmitJobResponse { diff --git a/seatunnel-engine/seatunnel-engine-ui/src/service/service.ts b/seatunnel-engine/seatunnel-engine-ui/src/service/service.ts index 454cf95ed72c..ca6b4d604706 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/service/service.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/service/service.ts @@ -66,4 +66,7 @@ export const post = (url: string, data?: any, config?: AxiosRequestConfig) => return >service.post(url, data, config) } +export const isRequestOutcomeUnknown = (error: unknown) => + axios.isAxiosError(error) && !error.response + export { service as axios } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/checkpoints.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/checkpoints.spec.ts index 7ec24f008554..ff3a4e11e19a 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/checkpoints.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/checkpoints.spec.ts @@ -37,7 +37,7 @@ describe('checkpoints', () => { routerState.push.mockReset() }) - test('restores from checkpoint view by preloading submit job restore id', async () => { + test('restores all checkpoint pipelines with an explicit source and mode', async () => { vi.spyOn(JobsService, 'getCheckpointOverview').mockResolvedValue({ jobId: '123456789', updatedAt: 1720000000123, @@ -53,7 +53,86 @@ describe('checkpoints', () => { }, latestCompleted: { checkpointId: 10, - checkpointType: 'CHECKPOINT_TYPE', + checkpointType: 'checkpoint', + status: 'COMPLETED' + } + }, + { + pipelineId: 2, + counts: { + triggered: 1, + completed: 1, + failed: 0, + inProgress: 0, + restored: 0 + }, + latestCompleted: { + checkpointId: 11, + checkpointType: 'checkpoint', + status: 'COMPLETED' + } + } + ] + }) + vi.spyOn(JobsService, 'getCheckpointHistory').mockResolvedValue([]) + + const wrapper = mount(checkpoints, { + props: { + jobId: '123456789' + }, + global: { + plugins: [i18n] + } + }) + + await flushPromises() + const restoreButton = wrapper + .findAll('button') + .find((button) => button.text() === 'Restore From Checkpoint') + expect(restoreButton).toBeTruthy() + await restoreButton?.trigger('click') + expect(routerState.push).toHaveBeenCalledWith({ + name: 'jobs', + query: { + restoreMode: 'CHECKPOINT', + restoreSourceJobId: '123456789' + } + }) + wrapper.unmount() + }) + + test('offers savepoint restore only when every pipeline has a savepoint', async () => { + vi.spyOn(JobsService, 'getCheckpointOverview').mockResolvedValue({ + jobId: '123456789', + updatedAt: 1720000000123, + pipelines: [ + { + pipelineId: 1, + counts: { + triggered: 1, + completed: 1, + failed: 0, + inProgress: 0, + restored: 0 + }, + latestSavepoint: { + checkpointId: 11, + checkpointType: 'savepoint', + status: 'COMPLETED' + } + }, + { + pipelineId: 2, + counts: { + triggered: 1, + completed: 1, + failed: 0, + inProgress: 0, + restored: 0 + }, + latestSavepoint: { + checkpointId: 12, + checkpointType: 'savepoint', status: 'COMPLETED' } } @@ -73,13 +152,14 @@ describe('checkpoints', () => { await flushPromises() const restoreButton = wrapper .findAll('button') - .find((button) => button.text() === 'Restore Latest State') + .find((button) => button.text() === 'Restore From Savepoint') expect(restoreButton).toBeTruthy() await restoreButton?.trigger('click') expect(routerState.push).toHaveBeenCalledWith({ name: 'jobs', query: { - restoreJobId: '123456789' + restoreMode: 'SAVEPOINT', + restoreSourceJobId: '123456789' } }) wrapper.unmount() diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts index fd45134356bf..770e4f7bac68 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts @@ -25,8 +25,8 @@ import { createApp } from 'vue' import { createPinia, setActivePinia } from 'pinia' import i18n from '@/locales' import finishedJobs from '@/views/jobs/finished-jobs' -import { getFinishedJobs, JobsService } from '@/service/job' -import { get } from '@/service/service' +import { getFinishedJobs, JobsService, stopJob, submitJob } from '@/service/job' +import { get, post } from '@/service/service' import type { JobPage, Job } from '@/service/job/types' const routeState = vi.hoisted(() => ({ @@ -43,7 +43,11 @@ vi.mock('vue-router', () => ({ }) })) -vi.mock('@/service/service', () => ({ get: vi.fn(), post: vi.fn() })) +vi.mock('@/service/service', () => ({ + get: vi.fn(), + post: vi.fn(), + isRequestOutcomeUnknown: () => false +})) describe('jobs', () => { const app = createApp({}) @@ -146,7 +150,8 @@ describe('jobs', () => { }) test('Job Operations component', async () => { routeState.query = { - restoreJobId: '888413907541032961' + restoreMode: 'CHECKPOINT', + restoreSourceJobId: '888413907541032961' } const submitJobSpy = vi.spyOn(JobsService, 'submitJob').mockResolvedValue({ jobId: '888413907541032961', @@ -162,18 +167,23 @@ describe('jobs', () => { expect(wrapper.text()).toContain('Submit Job') expect(wrapper.text()).toContain('Config Text') expect(wrapper.text()).toContain('Config File') - expect(wrapper.text()).toContain('Restore Job ID') + expect(wrapper.text()).toContain('Restore Source Job ID') await wrapper.find('textarea').setValue('env { job.mode = "BATCH" }') const submitButton = wrapper.findAll('button').find((button) => button.text() === 'Submit') expect(submitButton).toBeTruthy() await submitButton?.trigger('click') + const submitConfirmation = wrapper.findAllComponents(NPopconfirm)[0] + const onPositiveClick = submitConfirmation.props('onPositiveClick') as ( + event: MouseEvent + ) => Promise + await onPositiveClick(new MouseEvent('click')) await flushPromises() expect(submitJobSpy).toHaveBeenCalledWith({ config: 'env { job.mode = "BATCH" }', format: 'hocon', jobName: '', - jobId: '888413907541032961', - isStartWithSavePoint: true + restoreMode: 'CHECKPOINT', + restoreSourceJobId: '888413907541032961' }) wrapper.unmount() }) @@ -184,6 +194,44 @@ describe('jobs', () => { getFinishedJobs(1, 10) - expect(getMock).toHaveBeenCalledWith('/finished-jobs', {page: 1, rows: 10}) + expect(getMock).toHaveBeenCalledWith('/finished-jobs', { page: 1, rows: 10 }) + }) + + test('job operations preserve the selected restore source without a client timeout', () => { + const postMock = vi.mocked(post) + postMock.mockClear() + + submitJob({ + config: 'env { job.mode = "BATCH" }', + format: 'hocon', + restoreMode: 'CHECKPOINT', + restoreSourceJobId: '888413907541032961' + }) + stopJob({ + jobId: '888413907541032961', + isStopWithSavePoint: true + }) + + expect(postMock).toHaveBeenNthCalledWith( + 1, + '/submit-job', + 'env { job.mode = "BATCH" }', + expect.objectContaining({ + timeout: 0, + params: expect.objectContaining({ + restoreMode: 'CHECKPOINT', + restoreSourceJobId: '888413907541032961' + }) + }) + ) + expect(postMock).toHaveBeenNthCalledWith( + 2, + '/stop-job', + expect.objectContaining({ + jobId: '888413907541032961', + isStopWithSavePoint: true + }), + { timeout: 0 } + ) }) }) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts index 550d8e19c592..8757ef6f51d2 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts @@ -20,6 +20,7 @@ import { flushPromises, mount } from '@vue/test-utils' // import { createTestingPinia } from '@pinia/testing' import { createApp } from 'vue' import { createPinia, setActivePinia } from 'pinia' +import { NPopconfirm } from 'naive-ui' import i18n from '@/locales' import type { Monitor } from '@/service/manager/types' import { managerService } from '@/service/manager' @@ -89,6 +90,12 @@ describe('managers', () => { const updateButton = wrapper.findAll('button').find((button) => button.text() === 'Update Tags') expect(updateButton).toBeTruthy() await updateButton?.trigger('click') + const confirmations = wrapper.findAllComponents(NPopconfirm) + expect(confirmations).toHaveLength(2) + const onPositiveClick = confirmations[1].props('onPositiveClick') as ( + event: MouseEvent + ) => Promise + await onPositiveClick(new MouseEvent('click')) await flushPromises() expect(updateTagsSpy).toHaveBeenCalledWith({ uuid: 'worker-1', @@ -96,6 +103,7 @@ describe('managers', () => { zone: 'prod' } }) + expect(managerService.getMonitors).toHaveBeenCalledTimes(2) wrapper.unmount() }) }) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/operations.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/operations.spec.ts index 5119ab3a63fd..01614f613bda 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/operations.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/operations.spec.ts @@ -37,13 +37,18 @@ describe('operations', () => { key: 'row.num', type: 'java.lang.Integer', defaultValue: 5, - description: 'row count' + description: 'row count', + fallbackKeys: ['rows'], + optionValues: [1, 5, 10] } ], requiredOptions: [], conditionRules: [ { expression: 'format = json', + expressionTree: { + condition: 'format = json' + }, optionRule: { optionalOptions: [], requiredOptions: [ @@ -100,8 +105,12 @@ describe('operations', () => { expect(wrapper.text()).toContain('Connector Option Rules') expect(wrapper.text()).toContain('HTTP Service Status') expect(wrapper.text()).toContain('row.num') + expect(wrapper.text()).toContain('rows') + expect(wrapper.text()).toContain('1, 5, 10') expect(wrapper.text()).toContain('Condition Rules') expect(wrapper.text()).toContain('format = json') + expect(wrapper.text()).toContain('schema') + expect(wrapper.text()).toContain('Expression Tree') expect(wrapper.text()).toContain('Value Constraints') expect(wrapper.text()).toContain('row.num > 0') wrapper.unmount() diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/checkpoints.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/checkpoints.tsx index a672da8d2179..840dbbaec48b 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/checkpoints.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/checkpoints.tsx @@ -24,7 +24,8 @@ import type { CheckpointHistoryRecord, CheckpointInfo, CheckpointOverview, - CheckpointPipeline + CheckpointPipeline, + RestoreMode } from '@/service/job/types' export default defineComponent({ @@ -68,11 +69,28 @@ export default defineComponent({ onMounted(refresh) - const restoreLatestState = () => { + const isCheckpointRestorable = (checkpoint?: CheckpointInfo | null) => + checkpoint?.checkpointType === 'checkpoint' || + checkpoint?.checkpointType === 'completed-point' + + const canRestore = (mode: RestoreMode) => { + const pipelines = overview.value?.pipelines || [] + return ( + pipelines.length > 0 && + pipelines.every((pipeline) => + mode === 'CHECKPOINT' + ? isCheckpointRestorable(pipeline.latestCompleted) + : Boolean(pipeline.latestSavepoint) + ) + ) + } + + const restoreLatestState = (restoreMode: RestoreMode) => { router.push({ name: 'jobs', query: { - restoreJobId: props.jobId + restoreMode, + restoreSourceJobId: props.jobId } }) } @@ -113,15 +131,6 @@ export default defineComponent({ title: t('detail.checkpoints.latestSavepoint'), key: 'latestSavepoint', render: (row) => checkpointLabel(row.latestSavepoint) - }, - { - title: t('detail.checkpoints.action'), - key: 'actions', - render: () => ( - - {t('detail.checkpoints.restoreLatest')} - - ) } ] @@ -166,6 +175,30 @@ export default defineComponent({ {t('detail.checkpoints.refresh')} + {(canRestore('CHECKPOINT') || canRestore('SAVEPOINT')) && ( + + {canRestore('CHECKPOINT') && ( + restoreLatestState('CHECKPOINT')} + > + {t('detail.checkpoints.restoreFromCheckpoint')} + + )} + {canRestore('SAVEPOINT') && ( + restoreLatestState('SAVEPOINT')} + > + {t('detail.checkpoints.restoreFromSavepoint')} + + )} + + )} {error.value && {error.value}} + value === 'CHECKPOINT' || value === 'SAVEPOINT' + export default defineComponent({ setup() { const { t } = useI18n() const route = useRoute() - const initialRestoreJobId = - typeof route.query.restoreJobId === 'string' ? route.query.restoreJobId : '' + const initialRestoreSourceJobId = + typeof route.query.restoreSourceJobId === 'string' ? route.query.restoreSourceJobId : '' + const routeRestoreMode = route.query.restoreMode + const initialRestoreMode: RestoreMode = isRestoreMode(routeRestoreMode) + ? routeRestoreMode + : 'SAVEPOINT' const textJobName = ref('') const fileJobName = ref('') - const textRestoreJobId = ref(initialRestoreJobId) - const fileRestoreJobId = ref(initialRestoreJobId) - const textStartWithSavepoint = ref(Boolean(initialRestoreJobId)) - const fileStartWithSavepoint = ref(Boolean(initialRestoreJobId)) + const textRestoreSourceJobId = ref(initialRestoreSourceJobId) + const fileRestoreSourceJobId = ref(initialRestoreSourceJobId) + const textRestoreEnabled = ref(Boolean(initialRestoreSourceJobId)) + const fileRestoreEnabled = ref(Boolean(initialRestoreSourceJobId)) + const textRestoreMode = ref(initialRestoreMode) + const fileRestoreMode = ref(initialRestoreMode) const configFormat = ref('hocon') const configContent = ref('') const fileList = ref([]) @@ -79,12 +95,15 @@ export default defineComponent({ } const submitText = async () => { + if (submittingText.value) { + return + } if (!configContent.value.trim()) { setFeedback('warning', t('jobs.operations.configRequired')) return } - if (textStartWithSavepoint.value && !textRestoreJobId.value.trim()) { - setFeedback('warning', t('jobs.operations.restoreJobIdRequired')) + if (textRestoreEnabled.value && !textRestoreSourceJobId.value.trim()) { + setFeedback('warning', t('jobs.operations.restoreSourceJobIdRequired')) return } @@ -95,25 +114,33 @@ export default defineComponent({ config: configContent.value, format: configFormat.value, jobName: textJobName.value, - jobId: textRestoreJobId.value, - isStartWithSavePoint: textStartWithSavepoint.value + restoreMode: textRestoreEnabled.value ? textRestoreMode.value : undefined, + restoreSourceJobId: textRestoreEnabled.value ? textRestoreSourceJobId.value : undefined }) setFeedback('success', formatSubmitSuccess(response)) } catch (error) { - setFeedback('error', t('jobs.operations.submitFailed')) + setFeedback( + 'error', + isRequestOutcomeUnknown(error) + ? t('jobs.operations.submitOutcomeUnknown') + : t('jobs.operations.submitFailed') + ) } finally { submittingText.value = false } } const submitFile = async () => { + if (submittingFile.value) { + return + } const file = fileList.value[0]?.file if (!file) { setFeedback('warning', t('jobs.operations.fileRequired')) return } - if (fileStartWithSavepoint.value && !fileRestoreJobId.value.trim()) { - setFeedback('warning', t('jobs.operations.restoreJobIdRequired')) + if (fileRestoreEnabled.value && !fileRestoreSourceJobId.value.trim()) { + setFeedback('warning', t('jobs.operations.restoreSourceJobIdRequired')) return } @@ -123,12 +150,17 @@ export default defineComponent({ const response = await JobsService.submitJobByUploadFile({ file, jobName: fileJobName.value, - jobId: fileRestoreJobId.value, - isStartWithSavePoint: fileStartWithSavepoint.value + restoreMode: fileRestoreEnabled.value ? fileRestoreMode.value : undefined, + restoreSourceJobId: fileRestoreEnabled.value ? fileRestoreSourceJobId.value : undefined }) setFeedback('success', formatSubmitSuccess(response)) } catch (error) { - setFeedback('error', t('jobs.operations.submitFailed')) + setFeedback( + 'error', + isRequestOutcomeUnknown(error) + ? t('jobs.operations.submitOutcomeUnknown') + : t('jobs.operations.submitFailed') + ) } finally { submittingFile.value = false } @@ -170,24 +202,35 @@ export default defineComponent({ }} /> - + { - textStartWithSavepoint.value = value + textRestoreEnabled.value = value }} /> - {textStartWithSavepoint.value && ( - - { - textRestoreJobId.value = value - }} - /> - + {textRestoreEnabled.value && ( + <> + + { + textRestoreMode.value = value as RestoreMode + }} + /> + + + { + textRestoreSourceJobId.value = value + }} + /> + + )} { configContent.value = '' textJobName.value = '' - textRestoreJobId.value = '' - textStartWithSavepoint.value = false + textRestoreSourceJobId.value = '' + textRestoreEnabled.value = false + textRestoreMode.value = 'SAVEPOINT' }} > {t('jobs.operations.reset')} - - {t('jobs.operations.submit')} - + + {{ + trigger: () => ( + + {t('jobs.operations.submit')} + + ), + default: () => t('jobs.operations.submitConfirmMessage') + }} + @@ -243,39 +305,69 @@ export default defineComponent({ }} - + { - fileStartWithSavepoint.value = value + fileRestoreEnabled.value = value }} /> - {fileStartWithSavepoint.value && ( - - { - fileRestoreJobId.value = value - }} - /> - + {fileRestoreEnabled.value && ( + <> + + { + fileRestoreMode.value = value as RestoreMode + }} + /> + + + { + fileRestoreSourceJobId.value = value + }} + /> + + )} { fileList.value = [] fileJobName.value = '' - fileRestoreJobId.value = '' - fileStartWithSavepoint.value = false + fileRestoreSourceJobId.value = '' + fileRestoreEnabled.value = false + fileRestoreMode.value = 'SAVEPOINT' }} > {t('jobs.operations.reset')} - - {t('jobs.operations.submit')} - + + {{ + trigger: () => ( + + {t('jobs.operations.submit')} + + ), + default: () => t('jobs.operations.submitConfirmMessage') + }} + diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/running-jobs.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/running-jobs.tsx index e428a3119e58..14629d23b089 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/running-jobs.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/running-jobs.tsx @@ -23,6 +23,7 @@ import type { DataTableColumns } from 'naive-ui' import type { Job } from '@/service/job/types' import { useRouter } from 'vue-router' import { getColorFromStatus } from '@/utils/getTypeFromStatus' +import { isRequestOutcomeUnknown } from '@/service/service' type FeedbackType = 'success' | 'error' @@ -39,7 +40,7 @@ export default defineComponent({ const page = ref(1) const pageSize = ref(10) const total = ref(0) - const actionLoading = ref('') + const actionLoading = ref(new Set()) const feedback = ref(null) let timer: ReturnType | undefined @@ -80,6 +81,19 @@ export default defineComponent({ fetch() const router = useRouter() + const isActionLoading = (actionKey: string) => actionLoading.value.has(actionKey) + const hasJobActionLoading = (jobId: string) => + Array.from(actionLoading.value).some((actionKey) => actionKey.startsWith(`${jobId}-`)) + const setActionLoading = (actionKey: string, loading: boolean) => { + const next = new Set(actionLoading.value) + if (loading) { + next.add(actionKey) + } else { + next.delete(actionKey) + } + actionLoading.value = next + } + function createColumns(): DataTableColumns { const view = (job: Job) => { router.push({ name: 'detail', params: { jobId: job.jobId } }) @@ -87,7 +101,11 @@ export default defineComponent({ const controlJob = async (job: Job, force: boolean, savepoint = false) => { const action = savepoint ? 'savepoint' : force ? 'cancel' : 'stop' - actionLoading.value = `${job.jobId}-${action}` + const actionKey = `${job.jobId}-${action}` + if (hasJobActionLoading(job.jobId)) { + return + } + setActionLoading(actionKey, true) feedback.value = null try { await JobsService.stopJob({ @@ -113,18 +131,20 @@ export default defineComponent({ feedback.value = { type: 'error', message: t( - savepoint - ? 'jobs.actions.savepointFailed' - : force - ? 'jobs.actions.cancelFailed' - : 'jobs.actions.stopFailed', + isRequestOutcomeUnknown(error) + ? 'jobs.actions.operationOutcomeUnknown' + : savepoint + ? 'jobs.actions.savepointFailed' + : force + ? 'jobs.actions.cancelFailed' + : 'jobs.actions.stopFailed', { job: job.jobName || job.jobId } ) } } finally { - actionLoading.value = '' + setActionLoading(actionKey, false) } } @@ -186,7 +206,8 @@ export default defineComponent({ {t('jobs.actions.stop')} @@ -208,7 +229,8 @@ export default defineComponent({ size="small" tertiary type="warning" - loading={actionLoading.value === `${row.jobId}-savepoint`} + disabled={hasJobActionLoading(row.jobId)} + loading={isActionLoading(`${row.jobId}-savepoint`)} > {t('jobs.actions.savepoint')} @@ -230,7 +252,8 @@ export default defineComponent({ size="small" tertiary type="error" - loading={actionLoading.value === `${row.jobId}-cancel`} + disabled={hasJobActionLoading(row.jobId)} + loading={isActionLoading(`${row.jobId}-cancel`)} > {t('jobs.actions.cancel')} diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx index 7dae6ca2d404..f77504fda6ef 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx @@ -24,6 +24,7 @@ import { NInput, NLayout, NLayoutContent, + NPopconfirm, NSpace, NTag, NTooltip @@ -33,6 +34,7 @@ import type { DataTableColumns } from 'naive-ui' import { managerService } from '@/service/manager' import type { Monitor } from '@/service/manager/types' import { useRoute } from 'vue-router' +import { isRequestOutcomeUnknown } from '@/service/service' export default defineComponent({ setup() { @@ -46,52 +48,82 @@ export default defineComponent({ const tagLoading = ref(false) const fetch = async () => { - let res = await managerService.getMonitors() - const isMaster = route?.path.endsWith('/master') || false - res = res.filter((row) => row.isMaster === String(isMaster)) || [] - monitors.value = res - if (selectedMonitor.value) { - selectedMonitor.value = - res.find((row) => row.uuid && row.uuid === selectedMonitor.value?.uuid) || null + try { + let res = await managerService.getMonitors() + const isMaster = route?.path.endsWith('/master') || false + res = res.filter((row) => row.isMaster === String(isMaster)) || [] + monitors.value = res + if (selectedMonitor.value) { + selectedMonitor.value = + res.find((row) => row.uuid && row.uuid === selectedMonitor.value?.uuid) || null + } + return true + } catch { + tagError.value = t('managers.tags.loadFailed') + return false } } fetch() const parseTags = () => { const tags: Record = {} + const tagKeys = new Set() for (const rawLine of tagContent.value.split('\n')) { const line = rawLine.trim() if (!line) { continue } const separatorIndex = line.indexOf('=') - if (separatorIndex <= 0) { + const key = line.substring(0, separatorIndex).trim() + if (!key) { throw new Error(t('managers.tags.invalid')) } - tags[line.substring(0, separatorIndex).trim()] = line.substring(separatorIndex + 1).trim() + if (tagKeys.has(key)) { + throw new Error(t('managers.tags.duplicate')) + } + tagKeys.add(key) + tags[key] = line.substring(separatorIndex + 1).trim() } return tags } const updateTags = async (clear = false) => { - tagLoading.value = true + if (tagLoading.value) { + return + } tagMessage.value = '' tagError.value = '' + if (!selectedMonitor.value?.uuid) { + tagError.value = t('managers.tags.workerRequired') + return + } + if (!clear && !tagContent.value.trim()) { + tagError.value = t('managers.tags.contentRequired') + return + } + let tags: Record + try { + tags = clear ? {} : parseTags() + } catch (error) { + tagError.value = error instanceof Error ? error.message : t('managers.tags.invalid') + return + } + + tagLoading.value = true try { - if (!selectedMonitor.value?.uuid) { - tagError.value = t('managers.tags.workerRequired') - return - } await managerService.updateTags({ uuid: selectedMonitor.value.uuid, - tags: clear ? {} : parseTags() + tags }) if (clear) { tagContent.value = '' } tagMessage.value = t('managers.tags.success') + await fetch() } catch (error) { - tagError.value = error instanceof Error ? error.message : t('managers.tags.failed') + tagError.value = isRequestOutcomeUnknown(error) + ? t('managers.tags.outcomeUnknown') + : t('managers.tags.failed') } finally { tagLoading.value = false } @@ -215,21 +247,43 @@ export default defineComponent({ /> - updateTags(true)} + updateTags(true)} > - {t('managers.tags.clear')} - - updateTags()} + {{ + trigger: () => ( + + {t('managers.tags.clear')} + + ), + default: () => t('managers.tags.clearConfirmMessage') + }} + + updateTags()} > - {t('managers.tags.update')} - + {{ + trigger: () => ( + + {t('managers.tags.update')} + + ), + default: () => t('managers.tags.updateConfirmMessage') + }} +

diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/operations/index.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/operations/index.tsx index 2bfcbe9c64ad..37c5d7380e86 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/operations/index.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/operations/index.tsx @@ -52,6 +52,7 @@ type OptionRow = OptionMetadata & { interface ConditionRuleRow { expression: string + expressionTree: string requiredCount: number optionalCount: number nestedConditionCount: number @@ -80,29 +81,44 @@ export default defineComponent({ { label: 'Transform', value: 'transform' } ] - const optionRows = () => { - const optional = - optionRules.value?.optionRule?.optionalOptions?.map((option) => ({ + const collectOptionRows = ( + rule: OptionRuleResponse['optionRule'], + section: string, + expression = '-' + ): OptionRow[] => { + const required = (rule.requiredOptions || []).flatMap((requiredRule: RequiredOptionRule) => + (requiredRule.options || []).map((option) => ({ ...option, - section: t('operations.optionRules.optional'), - ruleType: '-', - expression: '-' - })) || [] - const required = - optionRules.value?.optionRule?.requiredOptions?.flatMap((rule: RequiredOptionRule) => - (rule.options || []).map((option) => ({ - ...option, - section: t('operations.optionRules.required'), - ruleType: rule.ruleType, - expression: rule.expression || '-' - })) - ) || [] - return [...required, ...optional] + section, + ruleType: requiredRule.ruleType, + expression: requiredRule.expression || expression + })) + ) + const optional = (rule.optionalOptions || []).map((option) => ({ + ...option, + section, + ruleType: '-', + expression + })) + const conditional = (rule.conditionRules || []).flatMap((conditionRule: ConditionRule) => + collectOptionRows( + conditionRule.optionRule, + t('operations.optionRules.conditional'), + conditionRule.expression || '-' + ) + ) + return [...required, ...optional, ...conditional] } + const optionRows = () => + optionRules.value + ? collectOptionRows(optionRules.value.optionRule, t('operations.optionRules.root')) + : [] + const conditionRows = (): ConditionRuleRow[] => (optionRules.value?.optionRule?.conditionRules || []).map((rule: ConditionRule) => ({ expression: rule.expression || '-', + expressionTree: rule.expressionTree ? JSON.stringify(rule.expressionTree) : '-', requiredCount: rule.optionRule?.requiredOptions?.length || 0, optionalCount: rule.optionRule?.optionalOptions?.length || 0, nestedConditionCount: rule.optionRule?.conditionRules?.length || 0 @@ -167,6 +183,17 @@ export default defineComponent({ ? '-' : String(row.defaultValue) }, + { + title: t('operations.optionRules.fallbackKeys'), + key: 'fallbackKeys', + render: (row) => (row.fallbackKeys?.length ? row.fallbackKeys.join(', ') : '-') + }, + { + title: t('operations.optionRules.optionValues'), + key: 'optionValues', + render: (row) => + row.optionValues?.length ? row.optionValues.map((value) => String(value)).join(', ') : '-' + }, { title: t('operations.optionRules.description'), key: 'description', @@ -176,6 +203,7 @@ export default defineComponent({ const conditionColumns: DataTableColumns = [ { title: t('operations.optionRules.expression'), key: 'expression' }, + { title: t('operations.optionRules.expressionTree'), key: 'expressionTree' }, { title: t('operations.optionRules.requiredCount'), key: 'requiredCount' From 5faae3e272bffe7173748512ee6bab4eed3899d8 Mon Sep 17 00:00:00 2001 From: davidzollo Date: Fri, 9 Oct 2026 04:20:29 -0400 Subject: [PATCH 07/19] [Fix][Zeta] Reject restore from active source jobs and document Web UI operation endpoints - Merge apache/dev and re-integrate the Workers tag editor with the new worker resource table; member identity (uuid, localMember, tags) is now stamped by the bounded health-metrics collector, including timed-out entries, so the local worker stays identifiable. - Reject restoreMode submissions while the source job has not reached an end state, and fail non-numeric restoreSourceJobId values with a clear 400; the Web UI submit panel now shows the engine failure message. - Document /update-local-member-tags, the /update-tags flat-map contract, the /http-service/status fields, the shared auth chain, the load-balancer limitation and the restore guard in English and Chinese. - Add RestApiIT coverage for /http-service/status and the target-validated tag endpoint on both the Jetty and Hazelcast REST ports. Co-Authored-By: Claude Fable 5.1 --- docs/en/engines/zeta/rest-api-v2.md | 129 ++++++++++++---- docs/en/engines/zeta/web-ui.md | 2 +- docs/zh/engines/zeta/rest-api-v2.md | 132 ++++++++++++----- docs/zh/engines/zeta/web-ui.md | 2 +- .../seatunnel/engine/e2e/RestApiIT.java | 139 ++++++++++++++++++ .../server/rest/service/JobInfoService.java | 71 ++++++++- ...estApiSubmitJobStartWithSavePointTest.java | 16 ++ .../JobInfoServiceRestoreGuardTest.java | 92 ++++++++++++ .../src/service/service.ts | 9 ++ .../src/tests/jobs.spec.ts | 38 +++++ .../src/views/jobs/job-operations.tsx | 26 ++-- 11 files changed, 569 insertions(+), 87 deletions(-) create mode 100644 seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/JobInfoServiceRestoreGuardTest.java diff --git a/docs/en/engines/zeta/rest-api-v2.md b/docs/en/engines/zeta/rest-api-v2.md index 975d2e8f06f1..caf9182fc3aa 100644 --- a/docs/en/engines/zeta/rest-api-v2.md +++ b/docs/en/engines/zeta/rest-api-v2.md @@ -1357,26 +1357,12 @@ For more information about customize encryption, please refer to the documentati #### update node tags ##### Body -`/update-tags` keeps the legacy flat `Map` contract without reserving tag names or values: +`/update-tags` keeps the legacy flat `Map` contract: every top-level key is a tag name and every value is that tag's value. No key is reserved, so a key literally named `uuid` or `tags` is stored as an ordinary tag instead of being read as a target member or a nested tag map. The request always applies to the REST node that serves it; to target a specific node, send the request to that node's own REST address. ```json { "tag1": "dev_1", - "tags": { - "nested": "legacy-value" - } -} -``` - -The Web UI uses `POST /update-local-member-tags` for the target-validated request format. It sends the request to its own REST origin, so open the UI from the target worker's REST address and use the member `uuid` from `/system-monitoring-information`; remote rows remain read-only and a mismatched UUID returns an error instead of updating a different node. - -```json -{ - "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", - "tags": { - "tag1": "dev_1", - "tag2": "dev_2" - } + "tag2": "dev_2" } ``` ##### Responses @@ -1389,16 +1375,7 @@ The Web UI uses `POST /update-local-member-tags` for the target-validated reques ``` #### remove node tags ##### Body -Use an empty `tags` map with `POST /update-local-member-tags` to clear target node tags: - -```json -{ - "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", - "tags": {} -} -``` - -An empty flat `Map` sent to `POST /update-tags` clears the current REST node: +An empty flat `Map` clears every tag of the current REST node: ```json {} @@ -1434,6 +1411,74 @@ An empty flat `Map` sent to `POST /update-tags` clears the current REST node: ```
+### Update Local Member Tags + +
POST/update-local-member-tagsUpdates the tags of the REST node serving the request after validating the target member UUID(If the update is successful, return a success message) + +This is the endpoint the Web UI Workers page uses. It is additive: `/update-tags` and its flat-map contract are unchanged. + +#### Authentication + +`/update-local-member-tags` is registered on the same servlet context as every other REST endpoint, so it is protected by the same basic authentication and mutual TLS configuration. No separate credentials or settings apply. + +#### Body + +| Field | Required | Type | Description | +|--------|----------|--------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `uuid` | yes | string | Member UUID of the node that must serve this request. Read it from `/system-monitoring-information`, whose entries carry `uuid` and `localMember` for every cluster member. | +| `tags` | yes | object | Tag name to tag value map that replaces the node's current tags. An empty object clears all tags. | + +```json +{ + "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", + "tags": { + "tag1": "dev_1", + "tag2": "dev_2" + } +} +``` + +Clear every tag of the node: + +```json +{ + "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", + "tags": {} +} +``` + +#### Responses + +```json +{ + "status": "success", + "message": "update node tags done." +} +``` + +#### Request parameter exception + +Each error is returned with HTTP status `400` and the following body. + +| Condition | `message` | +|--------------------------------------------------------------------|-----------------------------------------------------------------| +| The request body is empty | `Request body is empty.` | +| The request body is not a JSON object | `Invalid JSON format in request body.` | +| `uuid` is missing or does not match the node serving the request | `Target member uuid must match the REST node serving this request.` | +| `tags` is missing or is not a JSON object | `The tags field must be an object.` | + +```json +{ + "status": "fail", + "message": "Target member uuid must match the REST node serving this request." +} +``` + +#### Limitation + +The UUID check is local to the node serving the request. When the REST address is a load balancer or reverse proxy that fronts several masters, only the member that happens to serve the request can be updated, and requests for every other member are rejected with the UUID mismatch error. Send the request to the target member's own REST address instead. +
+ ------------------------------------------------------------------------------------------ ### Get Logs from All Nodes @@ -1723,7 +1768,22 @@ More information about `Telemetry` can be found in the [Telemetry](telemetry.md) #### Response Returns the HTTP service switches, configured ports, effective connector ports, context path, and authentication mode for the current node. -Sensitive values such as passwords and keystore or truststore paths are not returned. +Sensitive values such as passwords, user names, and keystore or truststore paths are never returned. +The endpoint is registered on the same servlet context as every other REST endpoint, so it is protected by the same basic authentication and mutual TLS configuration. + +| Field | Type | Description | +|-----------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `httpEnabled` | boolean | Whether the REST service is enabled on this node (`http.enable-http`). | +| `httpsEnabled` | boolean | Whether HTTPS is enabled on this node (`http.enable-https`). | +| `contextPath` | string | Context path the REST endpoints are served under; `/` when none is configured. | +| `configuredHttpPort` | number | HTTP port from the configuration (`http.port`, default `8080`). | +| `configuredHttpsPort` | number | HTTPS port from the configuration (`http.https-port`, default `8443`). | +| `httpPort` | number | Port the active HTTP connector is bound to. It differs from `configuredHttpPort` when dynamic ports are enabled; it equals the configured port when no HTTP connector is active. | +| `httpsPort` | number | Port the active HTTPS connector is bound to, with the same fallback rule as `httpPort`. | +| `dynamicPortEnabled` | boolean | Whether the node may pick the next free port when the configured one is taken (`http.enable-dynamic-port`). | +| `portRange` | number | Size of the port range searched when dynamic ports are enabled (`http.port-range`). | +| `basicAuthEnabled` | boolean | Whether HTTP basic authentication is enforced on this node. | +| `mutualTlsEnabled` | boolean | Whether the active HTTPS connector requires a client certificate. This reflects the effective TLS context, not merely whether a trust store is configured. | #### Response Example @@ -1732,10 +1792,10 @@ Sensitive values such as passwords and keystore or truststore paths are not retu "httpEnabled": true, "httpsEnabled": false, "contextPath": "/", - "configuredHttpPort": 5801, - "configuredHttpsPort": 58443, - "httpPort": 5801, - "httpsPort": 58443, + "configuredHttpPort": 8080, + "configuredHttpsPort": 8443, + "httpPort": 8080, + "httpsPort": 8443, "dynamicPortEnabled": false, "portRange": 100, "basicAuthEnabled": false, @@ -2012,3 +2072,10 @@ There is no dedicated `pause`, `resume` or `delete` endpoint. Use the existing j **Note:** `restoreMode` requires `restoreSourceJobId`. `isStartWithSavePoint: true` remains a legacy shortcut and requires `jobId` to be provided in the request; submitting without a `jobId` in that case fails with `Please provide jobId when start with save point.` + +**Restore guard:** a `restoreMode` submission is refused with HTTP `400` while the source job has +not reached an end state (`FINISHED`, `FAILED`, `CANCELED` or `SAVEPOINT_DONE`), for example +`restoreSourceJobId=42 is still RUNNING; stop or cancel the source job before restoring from its checkpoint state`. +Stop, savepoint or cancel the source job first. If the source job's checkpoint or savepoint state +has already been cleaned up, the submission fails with +`No checkpoint found for jobId=..., restoreMode=..., restoreSourceJobId=...`. diff --git a/docs/en/engines/zeta/web-ui.md b/docs/en/engines/zeta/web-ui.md index 087d67e8b6fa..3068a746daf8 100644 --- a/docs/en/engines/zeta/web-ui.md +++ b/docs/en/engines/zeta/web-ui.md @@ -72,7 +72,7 @@ The Job Detail page contains five main tabs: - **Overview**: shows the job DAG, source and sink throughput metrics, flush-signal metrics, and realtime vertex or edge metrics when observability is enabled. - **Exception**: shows the job error message when the job has failed or reported an exception. - **Configuration**: shows the runtime job configuration exposed by the engine. -- **Checkpoints**: shows checkpoint counts, latest completed checkpoint, latest savepoint, and recent checkpoint history. It offers separate checkpoint and savepoint restore actions only when every pipeline has a corresponding restorable state, then opens the submit panel with the source job ID and restore mode prefilled. +- **Checkpoints**: shows checkpoint counts, latest completed checkpoint, latest savepoint, and recent checkpoint history. It offers separate checkpoint and savepoint restore actions only when every pipeline has a corresponding restorable state, then opens the submit panel with the source job ID and restore mode prefilled. The tab does not check the job status: the engine refuses the restore while the source job is still active, and reports `No checkpoint found` when its state has already been cleaned up. Both messages are shown in the submit panel, so stop, savepoint or cancel the source job before restoring from it. - **Log**: shows job log files returned by the engine log API. #### Realtime Observability diff --git a/docs/zh/engines/zeta/rest-api-v2.md b/docs/zh/engines/zeta/rest-api-v2.md index c9941a26049e..4faefdf5d3dd 100644 --- a/docs/zh/engines/zeta/rest-api-v2.md +++ b/docs/zh/engines/zeta/rest-api-v2.md @@ -1327,32 +1327,17 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload?restoreMode=CHECKPOINT& ### 更新运行节点的tags -
-POST/update-tags使用旧版扁平 map 请求体更新当前 REST 节点的 tags(如果更新成功,则返回"success"信息) +
POST/update-tags使用旧版扁平 map 请求体更新当前 REST 节点的 tags(如果更新成功,则返回"success"信息) #### 更新节点tags ##### 请求体 -`/update-tags` 保留旧版扁平 `Map` 契约,不保留任何特殊 tag 名或 value: +`/update-tags` 保留旧版扁平 `Map` 契约:每个顶层 key 都是 tag 名,对应的 value 就是该 tag 的值。该接口不保留任何特殊 key,因此名为 `uuid` 或 `tags` 的 key 也只会作为普通 tag 存储,不会被解释为目标成员或嵌套的 tag map。请求始终作用于响应该请求的 REST 节点;如需更新指定节点,请把请求发送到该节点自己的 REST 地址。 ```json { "tag1": "dev_1", - "tags": { - "nested": "legacy-value" - } -} -``` - -Web UI 使用 `POST /update-local-member-tags` 发送带目标校验的请求。该请求会发送到 Web UI 自身的 REST 源地址,因此需要从目标 Worker 的 REST 地址打开 UI,并使用 `/system-monitoring-information` 返回的 member `uuid` 明确目标节点;远端节点保持只读,如果 `uuid` 与当前 REST 节点不一致,服务端会返回错误,避免误更新其他节点。 - -```json -{ - "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", - "tags": { - "tag1": "dev_1", - "tag2": "dev_2" - } + "tag2": "dev_2" } ``` ##### 响应 @@ -1365,22 +1350,13 @@ Web UI 使用 `POST /update-local-member-tags` 发送带目标校验的请求。 ``` #### 移除节点tags ##### 请求体 -使用空的 `tags` map,通过 `POST /update-local-member-tags` 清空目标节点 tags: - -```json -{ - "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", - "tags": {} -} -``` - -将空的扁平 `Map` 发送到 `POST /update-tags`,即可清空当前 REST 节点的 tags: +发送空的扁平 `Map` 即可清空当前 REST 节点的全部 tags: ```json {} ``` ##### 响应 -响应体将为: + ```json { "status": "success", @@ -1410,6 +1386,74 @@ Web UI 使用 `POST /update-local-member-tags` 发送带目标校验的请求。 ```
+### 更新本地成员 tags + +
POST/update-local-member-tags校验目标成员 UUID 后更新响应该请求的 REST 节点的 tags(如果更新成功,则返回"success"信息) + +这是 Web UI Workers 页面使用的接口。它是新增接口:`/update-tags` 及其扁平 map 契约保持不变。 + +#### 认证 + +`/update-local-member-tags` 与其他所有 REST 接口注册在同一个 servlet context 上,因此受相同的 basic 认证和双向 TLS 配置保护,不需要额外的凭据或配置。 + +#### 请求体 + +| 字段 | 必填 | 类型 | 说明 | +|--------|----|------|-------------------------------------------------------------------------------------------------------------| +| `uuid` | 是 | 字符串 | 必须响应本次请求的节点的成员 UUID。可从 `/system-monitoring-information` 获取,其返回的每个集群成员都带有 `uuid` 和 `localMember` 字段。 | +| `tags` | 是 | 对象 | tag 名到 tag 值的映射,会整体替换该节点当前的 tags。空对象表示清空全部 tags。 | + +```json +{ + "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", + "tags": { + "tag1": "dev_1", + "tag2": "dev_2" + } +} +``` + +清空该节点的全部 tags: + +```json +{ + "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", + "tags": {} +} +``` + +#### 响应 + +```json +{ + "status": "success", + "message": "update node tags done." +} +``` + +#### 请求参数异常 + +以下错误均以 HTTP `400` 返回,响应体格式如下。 + +| 场景 | `message` | +|-------------------------------------|---------------------------------------------------------------------| +| 请求体为空 | `Request body is empty.` | +| 请求体不是 JSON 对象 | `Invalid JSON format in request body.` | +| 缺少 `uuid`,或 `uuid` 与响应请求的节点不一致 | `Target member uuid must match the REST node serving this request.` | +| 缺少 `tags`,或 `tags` 不是 JSON 对象 | `The tags field must be an object.` | + +```json +{ + "status": "fail", + "message": "Target member uuid must match the REST node serving this request." +} +``` + +#### 限制 + +UUID 校验只针对响应请求的节点。如果 REST 地址是一个前置多个 master 的负载均衡或反向代理,那么只有恰好响应本次请求的成员可以被更新,针对其他成员的请求都会以 UUID 不匹配错误被拒绝。请改为直接向目标成员自己的 REST 地址发送请求。 +
+ ------------------------------------------------------------------------------------------ @@ -1687,7 +1731,22 @@ logger 会恢复到首次被覆盖之前的状态:配置文件中配置的级 #### 响应 返回当前节点 HTTP 服务开关、配置端口、实际监听端口、上下文路径和认证模式。 -接口不会返回密码、keystore 路径、truststore 路径等敏感值。 +接口不会返回密码、用户名、keystore 路径、truststore 路径等敏感值。 +该接口与其他所有 REST 接口注册在同一个 servlet context 上,因此受相同的 basic 认证和双向 TLS 配置保护。 + +| 字段 | 类型 | 说明 | +|-----------------------|-----|-------------------------------------------------------------------------------------------------| +| `httpEnabled` | 布尔 | 当前节点是否启用了 REST 服务(`http.enable-http`)。 | +| `httpsEnabled` | 布尔 | 当前节点是否启用了 HTTPS(`http.enable-https`)。 | +| `contextPath` | 字符串 | REST 接口所在的上下文路径;未配置时为 `/`。 | +| `configuredHttpPort` | 数字 | 配置中的 HTTP 端口(`http.port`,默认 `8080`)。 | +| `configuredHttpsPort` | 数字 | 配置中的 HTTPS 端口(`http.https-port`,默认 `8443`)。 | +| `httpPort` | 数字 | 当前 HTTP connector 实际绑定的端口。启用动态端口时可能与 `configuredHttpPort` 不同;没有活动的 HTTP connector 时等于配置端口。 | +| `httpsPort` | 数字 | 当前 HTTPS connector 实际绑定的端口,回退规则与 `httpPort` 相同。 | +| `dynamicPortEnabled` | 布尔 | 配置端口被占用时是否允许自动选择下一个可用端口(`http.enable-dynamic-port`)。 | +| `portRange` | 数字 | 启用动态端口时搜索的端口范围大小(`http.port-range`)。 | +| `basicAuthEnabled` | 布尔 | 当前节点是否强制 HTTP basic 认证。 | +| `mutualTlsEnabled` | 布尔 | 当前 HTTPS connector 是否要求客户端证书。该值反映实际生效的 TLS 上下文,而不只是是否配置了 truststore。 | #### 响应示例 @@ -1696,10 +1755,10 @@ logger 会恢复到首次被覆盖之前的状态:配置文件中配置的级 "httpEnabled": true, "httpsEnabled": false, "contextPath": "/", - "configuredHttpPort": 5801, - "configuredHttpsPort": 58443, - "httpPort": 5801, - "httpsPort": 58443, + "configuredHttpPort": 8080, + "configuredHttpsPort": 8443, + "httpPort": 8080, + "httpsPort": 8443, "dynamicPortEnabled": false, "portRange": 100, "basicAuthEnabled": false, @@ -1971,3 +2030,8 @@ Checkpoint 信息字段: **注意:** 设置 `restoreMode` 时必须提供 `restoreSourceJobId`。`isStartWithSavePoint: true` 仍是旧的快捷方式,必须提供 `jobId`;不提供 `jobId` 会导致请求失败,报错信息为 `Please provide jobId when start with save point.` + +**恢复保护:** 当来源作业尚未进入结束状态(`FINISHED`、`FAILED`、`CANCELED` 或 `SAVEPOINT_DONE`)时,带 `restoreMode` 的提交会以 HTTP `400` 被拒绝,例如 +`restoreSourceJobId=42 is still RUNNING; stop or cancel the source job before restoring from its checkpoint state`。 +请先停止、savepoint 或取消来源作业。如果来源作业的 checkpoint 或 savepoint 状态已经被清理,提交会失败并返回 +`No checkpoint found for jobId=..., restoreMode=..., restoreSourceJobId=...`。 diff --git a/docs/zh/engines/zeta/web-ui.md b/docs/zh/engines/zeta/web-ui.md index e2397153826b..6ca7bf471076 100644 --- a/docs/zh/engines/zeta/web-ui.md +++ b/docs/zh/engines/zeta/web-ui.md @@ -72,7 +72,7 @@ Jobs 页面提供 “Submit Job” 面板,可以直接在 Web UI 中提交新 - **Overview**:展示作业 DAG、source 和 sink 吞吐指标、flush signal 指标,以及开启可观测性后的 vertex 或 edge 实时指标。 - **Exception**:当作业失败或上报异常时,展示异常文本。 - **Configuration**:展示引擎暴露的运行时作业配置。 -- **Checkpoints**:展示 checkpoint 计数、最近完成的 checkpoint、最近的 savepoint 和 checkpoint 历史记录。仅当所有 pipeline 都存在对应可恢复状态时,页面才会提供独立的 checkpoint 或 savepoint 恢复操作;操作会打开提交面板并自动带入来源作业 ID 和恢复模式。 +- **Checkpoints**:展示 checkpoint 计数、最近完成的 checkpoint、最近的 savepoint 和 checkpoint 历史记录。仅当所有 pipeline 都存在对应可恢复状态时,页面才会提供独立的 checkpoint 或 savepoint 恢复操作;操作会打开提交面板并自动带入来源作业 ID 和恢复模式。该页签不会检查作业状态:来源作业仍在运行时引擎会拒绝恢复,其状态已被清理时会返回 `No checkpoint found`,两类错误信息都会显示在提交面板中,因此请先停止、savepoint 或取消来源作业再进行恢复。 - **Log**:展示引擎日志 API 返回的作业日志文件。 #### 实时可观测性(Realtime Observability) diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java index 381fe8cabf5b..ecf0c73f62d5 100644 --- a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java +++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java @@ -61,6 +61,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -1048,6 +1049,144 @@ public void testUpdateTagsSuccess() { .body("workers", equalTo("1")); } + /** + * The status endpoint must report the port Jetty actually bound (node2 is forced onto a dynamic + * port because both members share the configured one) and must never echo credentials or key + * material. + */ + @Test + public void testHttpServiceStatusReportsEffectivePortsWithoutSecrets() { + ports.forEach( + (hazelcastPort, jettyPort) -> { + String body = + given().get( + HOST + + jettyPort + + node1Config + .getEngineConfig() + .getHttpConfig() + .getContextPath() + + RestConstant.REST_URL_HTTP_SERVICE_STATUS) + .then() + .statusCode(200) + .body("httpEnabled", equalTo(true)) + .body("httpsEnabled", equalTo(false)) + .body("configuredHttpPort", equalTo(8080)) + .body("httpPort", equalTo(jettyPort)) + .body("dynamicPortEnabled", equalTo(true)) + .body("basicAuthEnabled", equalTo(false)) + .body("mutualTlsEnabled", equalTo(false)) + .extract() + .asString(); + String normalized = body.toLowerCase(Locale.ROOT); + for (String secret : + Arrays.asList("password", "username", "keystore", "truststore")) { + Assertions.assertFalse( + normalized.contains(secret), + () -> "status response leaks " + secret + ": " + body); + } + }); + } + + /** + * The target-validated tag endpoint only mutates the member serving the request: a foreign UUID + * is rejected without side effects, the serving member's UUID applies the tags on both the + * Jetty and the legacy Hazelcast REST port, and an empty map clears them. + */ + @Test + public void testUpdateLocalMemberTagsOnlyMutatesTheServingMember() { + int node1HazelcastPort = node1.getCluster().getLocalMember().getAddress().getPort(); + String jettyBase = + HOST + + ports.get(node1HazelcastPort) + + node1Config.getEngineConfig().getHttpConfig().getContextPath(); + String hazelcastBase = HOST + node1HazelcastPort + CONTEXT_PATH; + + List> members = + given().get(jettyBase + RestConstant.REST_URL_SYSTEM_MONITORING_INFORMATION) + .then() + .statusCode(200) + .extract() + .as(new TypeRef>>() {}); + Map localMember = + members.stream() + .filter(member -> Boolean.TRUE.equals(member.get("localMember"))) + .findFirst() + .orElseThrow( + () -> new AssertionError("no localMember entry in " + members)); + String localUuid = String.valueOf(localMember.get("uuid")); + Assertions.assertEquals( + node1.getCluster().getLocalMember().getUuid().toString(), localUuid); + Assertions.assertEquals("node1", ((Map) localMember.get("tags")).get("node")); + Assertions.assertEquals( + 1, members.stream().filter(m -> Boolean.TRUE.equals(m.get("localMember"))).count()); + String remoteUuid = node2.getCluster().getLocalMember().getUuid().toString(); + + given().body(tagRequest(remoteUuid, "{\"zone\": \"prod\"}")) + .post(jettyBase + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) + .then() + .statusCode(400) + .body("status", equalTo("fail")) + .body( + "message", + equalTo( + "Target member uuid must match the REST node serving this request.")); + given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?zone=prod") + .then() + .statusCode(200) + .body("workers", equalTo("0")); + given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?node=node1") + .then() + .statusCode(200) + .body("workers", equalTo("1")); + + given().body(tagRequest(localUuid, "{\"zone\": \"prod\"}")) + .post(jettyBase + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) + .then() + .statusCode(200) + .body("status", equalTo("success")) + .body("message", equalTo("update node tags done.")); + given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?zone=prod") + .then() + .statusCode(200) + .body("totalSlot", equalTo("20")) + .body("workers", equalTo("1")); + + given().body(tagRequest(localUuid, "{\"zone\": \"legacy-port\"}")) + .post(hazelcastBase + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) + .then() + .statusCode(200) + .body("message", equalTo("update node tags done.")); + given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?zone=legacy-port") + .then() + .statusCode(200) + .body("workers", equalTo("1")); + given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?zone=prod") + .then() + .statusCode(200) + .body("workers", equalTo("0")); + + given().body(tagRequest(localUuid, "{}")) + .post(jettyBase + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) + .then() + .statusCode(200) + .body("message", equalTo("update node tags done.")); + given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?zone=legacy-port") + .then() + .statusCode(200) + .body("workers", equalTo("0")); + + given().body(tagRequest(localUuid, "\"not-an-object\"")) + .post(jettyBase + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) + .then() + .statusCode(400) + .body("message", equalTo("The tags field must be an object.")); + } + + private static String tagRequest(String uuid, String tagsJson) { + return "{\"uuid\": \"" + uuid + "\", \"tags\": " + tagsJson + "}"; + } + @Test public void testUpdateTagsFail() { diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java index c9348b49d60f..b72f8cc74bd9 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java @@ -527,7 +527,9 @@ public JsonArray submitJobs(byte[] requestBody) { * Validates the explicit restore parameters before parsing the submitted job configuration. * *

A blank source ID is equivalent to an omitted source ID. Rejecting it here prevents the - * restore path from issuing a lookup for a null source after configuration parsing begins. + * restore path from issuing a lookup for a null source after configuration parsing begins. The + * source job must also have reached an end state: see {@link + * #rejectRestoreFromActiveSourceJob(RestoreMode, long, JobStatus)}. * * @param requestParams REST query parameters. */ @@ -537,14 +539,69 @@ private void validateCheckpointRestoreRequest(Map requestParams) restoreModeValue == null || restoreModeValue.trim().isEmpty() ? RestoreMode.NONE : RestoreMode.valueOf(restoreModeValue.trim().toUpperCase(Locale.ROOT)); - if (restoreMode.isRestore() - && (requestParams.get(RestConstant.RESTORE_SOURCE_JOB_ID) == null - || requestParams - .get(RestConstant.RESTORE_SOURCE_JOB_ID) - .trim() - .isEmpty())) { + if (!restoreMode.isRestore()) { + return; + } + String restoreSourceJobIdValue = requestParams.get(RestConstant.RESTORE_SOURCE_JOB_ID); + if (restoreSourceJobIdValue == null || restoreSourceJobIdValue.trim().isEmpty()) { throw new IllegalArgumentException( "restoreSourceJobId is required when restoreMode=" + restoreMode); } + long restoreSourceJobId; + try { + // No trimming: the submit path parses the raw value as well, so a padded ID must fail + // here with a clear message rather than later with a bare NumberFormatException. + restoreSourceJobId = Long.parseLong(restoreSourceJobIdValue); + } catch (NumberFormatException e) { + throw new IllegalArgumentException( + "restoreSourceJobId must be a numeric job id, got: " + restoreSourceJobIdValue, + e); + } + rejectRestoreFromActiveSourceJob( + restoreMode, restoreSourceJobId, getRestoreSourceJobStatus(restoreSourceJobId)); + } + + /** + * Rejects a restore whose source job has not reached an end state. + * + *

The Web UI exposes "Restore Latest State" on the Checkpoints tab of any job, including one + * that is still RUNNING. Restoring from a live job would start a second job from a checkpoint + * that the source keeps advancing past, so the operator must stop, savepoint or cancel the + * source first. A source job unknown to the cluster is reported as {@link JobStatus#UNKNOWABLE} + * and is deliberately not rejected here: the checkpoint lookup that follows returns the + * dedicated "No checkpoint found" error for it. + * + * @param restoreMode requested restore mode, used only for the error message. + * @param restoreSourceJobId source job whose state is restored. + * @param sourceJobStatus current status of the source job, or {@code null} when unknown. + */ + static void rejectRestoreFromActiveSourceJob( + RestoreMode restoreMode, long restoreSourceJobId, JobStatus sourceJobStatus) { + if (sourceJobStatus == null || sourceJobStatus.isEndState()) { + return; + } + throw new IllegalArgumentException( + String.format( + "restoreSourceJobId=%d is still %s; stop or cancel the source job before restoring from its %s state", + restoreSourceJobId, + sourceJobStatus, + restoreMode.name().toLowerCase(Locale.ROOT))); + } + + /** + * Resolves the source job status on the master, either locally or through {@link + * GetJobStatusOperation} when this REST node is not the master. + */ + private JobStatus getRestoreSourceJobStatus(long restoreSourceJobId) { + SeaTunnelServer seaTunnelServer = getSeaTunnelServer(true); + if (seaTunnelServer != null) { + return seaTunnelServer.getCoordinatorService().getJobStatus(restoreSourceJobId); + } + Integer statusOrdinal = + (Integer) + NodeEngineUtil.sendOperationToMasterNode( + nodeEngine, new GetJobStatusOperation(restoreSourceJobId)) + .join(); + return statusOrdinal == null ? null : JobStatus.values()[statusOrdinal]; } } diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java index 1d62cce17366..683eaab2a253 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java +++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java @@ -243,6 +243,22 @@ public void testSubmitCheckpointRestoreWithBlankSourceJobIdReturns400() throws E Assertions.assertTrue(response.body.contains("restoreSourceJobId")); } + @Test + public void testSubmitCheckpointRestoreWithNonNumericSourceJobIdReturns400() throws Exception { + String requestUrl = + "http://localhost:" + + workerRestPort + + "/submit-job?format=json&restoreMode=checkpoint&restoreSourceJobId=not-a-job&jobName=" + + TEST_JOB_NAME; + + HttpResponse response = postJson(requestUrl, getRequestBody()); + Assertions.assertEquals(400, response.code, () -> "responseBody=" + response.body); + Assertions.assertTrue(response.body.contains("\"status\":\"fail\"")); + Assertions.assertTrue( + response.body.contains("restoreSourceJobId must be a numeric job id"), + () -> "responseBody=" + response.body); + } + @Test public void testSubmitSavepointRestoreWithoutSourceJobIdReturns400() throws Exception { String requestUrl = diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/JobInfoServiceRestoreGuardTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/JobInfoServiceRestoreGuardTest.java new file mode 100644 index 000000000000..6bf486673a54 --- /dev/null +++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/JobInfoServiceRestoreGuardTest.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.seatunnel.engine.server.rest.service; + +import org.apache.seatunnel.engine.common.job.JobStatus; +import org.apache.seatunnel.engine.core.job.RestoreMode; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +/** + * Verifies the restore-source guard used by the REST submit path: a restore is refused while the + * source job is still active, and allowed once the source job has ended or is unknown, so the + * checkpoint lookup can report missing state with its own error. + */ +public class JobInfoServiceRestoreGuardTest { + + private static final long SOURCE_JOB_ID = 42L; + + @ParameterizedTest + @EnumSource( + value = JobStatus.class, + names = { + "INITIALIZING", + "CREATED", + "PENDING", + "SCHEDULED", + "RUNNING", + "FAILING", + "DOING_SAVEPOINT", + "CANCELING" + }) + public void testActiveSourceJobIsRejected(JobStatus status) { + IllegalArgumentException error = + Assertions.assertThrows( + IllegalArgumentException.class, + () -> + JobInfoService.rejectRestoreFromActiveSourceJob( + RestoreMode.CHECKPOINT, SOURCE_JOB_ID, status)); + Assertions.assertTrue( + error.getMessage().contains("restoreSourceJobId=42"), error.getMessage()); + Assertions.assertTrue(error.getMessage().contains(status.name()), error.getMessage()); + Assertions.assertTrue(error.getMessage().contains("checkpoint state"), error.getMessage()); + } + + @ParameterizedTest + @EnumSource( + value = JobStatus.class, + names = {"FAILED", "SAVEPOINT_DONE", "CANCELED", "FINISHED", "UNKNOWABLE"}) + public void testEndedOrUnknownSourceJobIsAccepted(JobStatus status) { + Assertions.assertDoesNotThrow( + () -> + JobInfoService.rejectRestoreFromActiveSourceJob( + RestoreMode.SAVEPOINT, SOURCE_JOB_ID, status)); + } + + @Test + public void testNullStatusIsAccepted() { + Assertions.assertDoesNotThrow( + () -> + JobInfoService.rejectRestoreFromActiveSourceJob( + RestoreMode.SAVEPOINT, SOURCE_JOB_ID, null)); + } + + @Test + public void testSavepointModeIsNamedInTheRejection() { + IllegalArgumentException error = + Assertions.assertThrows( + IllegalArgumentException.class, + () -> + JobInfoService.rejectRestoreFromActiveSourceJob( + RestoreMode.SAVEPOINT, SOURCE_JOB_ID, JobStatus.RUNNING)); + Assertions.assertTrue(error.getMessage().contains("savepoint state"), error.getMessage()); + } +} diff --git a/seatunnel-engine/seatunnel-engine-ui/src/service/service.ts b/seatunnel-engine/seatunnel-engine-ui/src/service/service.ts index ca6b4d604706..1af1154cc120 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/service/service.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/service/service.ts @@ -69,4 +69,13 @@ export const post = (url: string, data?: any, config?: AxiosRequestConfig) => export const isRequestOutcomeUnknown = (error: unknown) => axios.isAxiosError(error) && !error.response +// The engine answers rejected operations with { status: 'fail', message } and an HTTP error +// status; the message is the only operator-facing explanation (for example a restore refused +// because the source job is still running), so callers append it to their generic failure text. +export const requestFailureMessage = (error: unknown): string | undefined => { + if (!axios.isAxiosError(error)) return undefined + const message = (error.response?.data as { message?: unknown } | undefined)?.message + return typeof message === 'string' && message.trim() ? message.trim() : undefined +} + export { service as axios } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts index 770e4f7bac68..7e55f8556113 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts @@ -19,6 +19,7 @@ import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest' import { flushPromises, mount } from '@vue/test-utils' // import { createTestingPinia } from '@pinia/testing' import { NPopconfirm } from 'naive-ui' +import { AxiosError } from 'axios' import runningJobs from '@/views/jobs/running-jobs' import jobOperations from '@/views/jobs/job-operations' import { createApp } from 'vue' @@ -188,6 +189,43 @@ describe('jobs', () => { wrapper.unmount() }) + test('Job Operations shows the engine failure message when a restore is refused', async () => { + routeState.query = { + restoreMode: 'CHECKPOINT', + restoreSourceJobId: '42' + } + const refusal = new AxiosError('Request failed with status code 400', 'ERR_BAD_REQUEST') + refusal.response = { + status: 400, + statusText: 'Bad Request', + headers: {}, + config: {} as never, + data: { + status: 'fail', + message: + 'restoreSourceJobId=42 is still RUNNING; stop or cancel the source job before restoring from its checkpoint state' + } + } + vi.spyOn(JobsService, 'submitJob').mockRejectedValue(refusal) + const wrapper = mount(jobOperations, { + global: { + plugins: [i18n] + } + }) + await flushPromises() + await wrapper.find('textarea').setValue('env { job.mode = "STREAMING" }') + const submitButton = wrapper.findAll('button').find((button) => button.text() === 'Submit') + await submitButton?.trigger('click') + const onPositiveClick = wrapper.findAllComponents(NPopconfirm)[0].props('onPositiveClick') as ( + event: MouseEvent + ) => Promise + await onPositiveClick(new MouseEvent('click')) + await flushPromises() + expect(wrapper.text()).toContain('Failed to submit job.') + expect(wrapper.text()).toContain('restoreSourceJobId=42 is still RUNNING') + expect(wrapper.text()).not.toContain('The submit result is unknown') + wrapper.unmount() + }) test('Finished Jobs service requests all terminal jobs by default', () => { const getMock = vi.mocked(get) getMock.mockClear() diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/job-operations.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/job-operations.tsx index bfae82b902f7..f612c7f85cfc 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/job-operations.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/job-operations.tsx @@ -34,7 +34,7 @@ import type { SelectOption, UploadFileInfo } from 'naive-ui' import { useI18n } from 'vue-i18n' import { useRoute } from 'vue-router' import { JobsService } from '@/service/job' -import { isRequestOutcomeUnknown } from '@/service/service' +import { isRequestOutcomeUnknown, requestFailureMessage } from '@/service/service' import type { ConfigFormat, RestoreMode, SubmitJobResponse } from '@/service/job/types' type FeedbackType = 'success' | 'warning' | 'error' @@ -94,6 +94,16 @@ export default defineComponent({ return t('jobs.operations.submitSuccess', { job: jobLabel }) } + const submitFailureMessage = (error: unknown) => { + if (isRequestOutcomeUnknown(error)) { + return t('jobs.operations.submitOutcomeUnknown') + } + const serverMessage = requestFailureMessage(error) + return serverMessage + ? `${t('jobs.operations.submitFailed')} ${serverMessage}` + : t('jobs.operations.submitFailed') + } + const submitText = async () => { if (submittingText.value) { return @@ -119,12 +129,7 @@ export default defineComponent({ }) setFeedback('success', formatSubmitSuccess(response)) } catch (error) { - setFeedback( - 'error', - isRequestOutcomeUnknown(error) - ? t('jobs.operations.submitOutcomeUnknown') - : t('jobs.operations.submitFailed') - ) + setFeedback('error', submitFailureMessage(error)) } finally { submittingText.value = false } @@ -155,12 +160,7 @@ export default defineComponent({ }) setFeedback('success', formatSubmitSuccess(response)) } catch (error) { - setFeedback( - 'error', - isRequestOutcomeUnknown(error) - ? t('jobs.operations.submitOutcomeUnknown') - : t('jobs.operations.submitFailed') - ) + setFeedback('error', submitFailureMessage(error)) } finally { submittingFile.value = false } From 9272fba8fe05cc73410dd0d3ef6ad00f8608c3da Mon Sep 17 00:00:00 2001 From: davidzollo Date: Fri, 9 Oct 2026 13:05:01 -0400 Subject: [PATCH 08/19] [Chore][Zeta] Trigger CI for Web UI operation controls From fc1205384d3fea322866733c0865f693fc3008e5 Mon Sep 17 00:00:00 2001 From: davidzollo Date: Sat, 10 Oct 2026 03:56:45 -0400 Subject: [PATCH 09/19] [Chore][Zeta] Trigger CI after re-enabling fork workflows From a125187dc5a5498e7772e2a6dfffd947c894f8c8 Mon Sep 17 00:00:00 2001 From: davidzollo Date: Sat, 10 Oct 2026 06:31:30 -0400 Subject: [PATCH 10/19] [Test][Zeta] Cover Web UI operation endpoints in the basic-auth E2E - BasicAuthenticationIT asserts that /http-service/status, /update-local-member-tags and the legacy /update-tags reject unauthenticated requests and that authenticated requests reach the servlets behind the shared filter chain. - Document that /update-tags values must be strings. Co-Authored-By: Claude Fable 5.1 --- docs/en/engines/zeta/rest-api-v2.md | 2 +- docs/zh/engines/zeta/rest-api-v2.md | 2 +- .../engine/e2e/BasicAuthenticationIT.java | 56 +++++++++++++++++++ 3 files changed, 58 insertions(+), 2 deletions(-) diff --git a/docs/en/engines/zeta/rest-api-v2.md b/docs/en/engines/zeta/rest-api-v2.md index caf9182fc3aa..456f0047e867 100644 --- a/docs/en/engines/zeta/rest-api-v2.md +++ b/docs/en/engines/zeta/rest-api-v2.md @@ -1357,7 +1357,7 @@ For more information about customize encryption, please refer to the documentati #### update node tags ##### Body -`/update-tags` keeps the legacy flat `Map` contract: every top-level key is a tag name and every value is that tag's value. No key is reserved, so a key literally named `uuid` or `tags` is stored as an ordinary tag instead of being read as a target member or a nested tag map. The request always applies to the REST node that serves it; to target a specific node, send the request to that node's own REST address. +`/update-tags` keeps the legacy flat `Map` contract: every top-level key is a tag name and every value is that tag's value. Tag values must be strings; the server stores every value as a string, so nested objects are not a supported value type. No key is reserved, so a key literally named `uuid` or `tags` is stored as an ordinary tag instead of being read as a target member or a nested tag map. The request always applies to the REST node that serves it; to target a specific node, send the request to that node's own REST address. ```json { diff --git a/docs/zh/engines/zeta/rest-api-v2.md b/docs/zh/engines/zeta/rest-api-v2.md index 4faefdf5d3dd..f8d4c9fd5953 100644 --- a/docs/zh/engines/zeta/rest-api-v2.md +++ b/docs/zh/engines/zeta/rest-api-v2.md @@ -1332,7 +1332,7 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload?restoreMode=CHECKPOINT& #### 更新节点tags ##### 请求体 -`/update-tags` 保留旧版扁平 `Map` 契约:每个顶层 key 都是 tag 名,对应的 value 就是该 tag 的值。该接口不保留任何特殊 key,因此名为 `uuid` 或 `tags` 的 key 也只会作为普通 tag 存储,不会被解释为目标成员或嵌套的 tag map。请求始终作用于响应该请求的 REST 节点;如需更新指定节点,请把请求发送到该节点自己的 REST 地址。 +`/update-tags` 保留旧版扁平 `Map` 契约:每个顶层 key 都是 tag 名,对应的 value 就是该 tag 的值。tag 值必须是字符串;服务端会把每个值按字符串存储,不支持嵌套对象作为值。该接口不保留任何特殊 key,因此名为 `uuid` 或 `tags` 的 key 也只会作为普通 tag 存储,不会被解释为目标成员或嵌套的 tag map。请求始终作用于响应该请求的 REST 节点;如需更新指定节点,请把请求发送到该节点自己的 REST 地址。 ```json { diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/BasicAuthenticationIT.java b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/BasicAuthenticationIT.java index 4c0402f5cb87..b8dcdb0674e7 100644 --- a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/BasicAuthenticationIT.java +++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/BasicAuthenticationIT.java @@ -35,6 +35,7 @@ import static io.restassured.RestAssured.given; import static org.apache.seatunnel.e2e.common.util.ContainerUtil.PROJECT_ROOT_PATH; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; /** Integration test for basic authentication in SeaTunnel Engine. */ @@ -159,6 +160,61 @@ public void testRestApiAccessWithIncorrectCredentials() { .statusCode(401); } + /** + * The Web UI operation endpoints added for tag management and HTTP service status must sit + * behind the same basic-auth filter as every pre-existing servlet: one mutates member state and + * the other discloses the node's security posture. + */ + @Test + public void testOperationEndpointsRequireCredentials() { + String base = HTTP + server.getHost() + COLON + server.getMappedPort(8080); + + given().get(base + RestConstant.REST_URL_HTTP_SERVICE_STATUS).then().statusCode(401); + given().contentType(ContentType.JSON) + .body( + "{\"uuid\": \"00000000-0000-0000-0000-000000000000\", \"tags\": {\"zone\": \"x\"}}") + .post(base + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) + .then() + .statusCode(401); + given().contentType(ContentType.JSON) + .body("{\"zone\": \"x\"}") + .post(base + RestConstant.REST_URL_UPDATE_TAGS) + .then() + .statusCode(401); + } + + /** + * With valid credentials the status endpoint reports the enforced basic auth, and the tag + * endpoint reaches its own validation (a foreign UUID is rejected by the servlet, not by the + * filter), which proves the request passed the shared auth chain. + */ + @Test + public void testOperationEndpointsWithCorrectCredentials() { + String credentials = USERNAME + ":" + PASSWORD; + String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes()); + String base = HTTP + server.getHost() + COLON + server.getMappedPort(8080); + + given().header(BASIC_AUTH_HEADER, BASIC_AUTH_PREFIX + encodedCredentials) + .get(base + RestConstant.REST_URL_HTTP_SERVICE_STATUS) + .then() + .statusCode(200) + .body("httpEnabled", equalTo(true)) + .body("basicAuthEnabled", equalTo(true)) + .body("mutualTlsEnabled", equalTo(false)); + given().header(BASIC_AUTH_HEADER, BASIC_AUTH_PREFIX + encodedCredentials) + .contentType(ContentType.JSON) + .body( + "{\"uuid\": \"00000000-0000-0000-0000-000000000000\", \"tags\": {\"zone\": \"x\"}}") + .post(base + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) + .then() + .statusCode(400) + .body("status", equalTo("fail")) + .body( + "message", + equalTo( + "Target member uuid must match the REST node serving this request.")); + } + /** Test submitting a job via REST API with correct credentials. */ @Test public void testSubmitJobWithCorrectCredentials() { From 9dc0aede1848b7dcfde3e0457fde132f4b117afa Mon Sep 17 00:00:00 2001 From: davidzollo Date: Sat, 10 Oct 2026 10:31:26 -0400 Subject: [PATCH 11/19] [Test][Zeta] Prove the restore-source guard end to end and record it as a behavior change - RestApiSubmitJobStartWithSavePointTest submits an unbounded job, asserts a checkpoint restore from it is refused with 400 while it is RUNNING, and that the same request passes the guard once the job has been cancelled. - incompatible-changes.md (en, zh) records the narrowed restoreMode contract, its scope, the unchanged legacy path, and the migration step. Co-Authored-By: Claude Fable 5.1 --- .../concepts/incompatible-changes.md | 18 +++++ .../concepts/incompatible-changes.md | 15 ++++ ...estApiSubmitJobStartWithSavePointTest.java | 80 +++++++++++++++++++ 3 files changed, 113 insertions(+) diff --git a/docs/en/introduction/concepts/incompatible-changes.md b/docs/en/introduction/concepts/incompatible-changes.md index ac37c957a33e..133101c10ebf 100644 --- a/docs/en/introduction/concepts/incompatible-changes.md +++ b/docs/en/introduction/concepts/incompatible-changes.md @@ -439,6 +439,24 @@ The Zeta SQL ARRAY function now declares TINYINT elements as `ARRAY`, m ### Engine Behavior Changes +- **Behavior change: `restoreMode` submissions are refused while the source job is still active** + - **Affected component**: `seatunnel-engine-server`, REST v2 `POST /submit-job`, `POST /submit-job/upload` and + `POST /submit-jobs` when the request carries `restoreMode=CHECKPOINT|SAVEPOINT` with `restoreSourceJobId`. + - **Description**: The explicit restore contract used to accept any `restoreSourceJobId`, including a job that + was still `RUNNING`, `DOING_SAVEPOINT`, `CANCELING` or otherwise not finished, and the new job would restore + from a checkpoint that the source kept advancing past. The submit path now resolves the source job status on + the master and returns HTTP `400` with `restoreSourceJobId= is still ; stop or cancel the source + job before restoring from its checkpoint state` unless the source job has reached an end state (`FINISHED`, + `FAILED`, `CANCELED` or `SAVEPOINT_DONE`). A non-numeric `restoreSourceJobId` is now also a `400` with a clear + message. A job id unknown to the cluster is not rejected by the guard and still fails with the existing + `No checkpoint found ...` error. The legacy `isStartWithSavePoint=true` with `jobId` path is unchanged. + - **Impact**: Scripts or clients that submitted a restore against a job that was still running now receive + `400` instead of a new job. Restores from finished, failed, cancelled or savepoint-stopped jobs behave as + before. + - **Migration Guide**: Stop the source job first, for example `POST /stop-job` with + `isStopWithSavePoint: true` for a savepoint restore or a plain stop for a checkpoint restore, wait for its + status to reach an end state, and then submit the restore. (#11613) + - **Behavior change: the REST log-content endpoints return at most 64 MB by default** - **Affected component**: `seatunnel-engine-server`, REST v2 endpoints `GET /logs/:file` and `GET /log/:file` and their REST v1 equivalents `GET /hazelcast/rest/maps/logs/:file` and diff --git a/docs/zh/introduction/concepts/incompatible-changes.md b/docs/zh/introduction/concepts/incompatible-changes.md index cddfe214fe56..12666a8d1a04 100644 --- a/docs/zh/introduction/concepts/incompatible-changes.md +++ b/docs/zh/introduction/concepts/incompatible-changes.md @@ -361,6 +361,21 @@ Zeta SQL ARRAY 函数现在将 TINYINT 元素声明为 `ARRAY`,与实 ### 引擎行为变更 +- **行为变更:来源作业仍在运行时,带 `restoreMode` 的提交会被拒绝** + - **受影响组件**:`seatunnel-engine-server`,REST v2 `POST /submit-job`、`POST /submit-job/upload` 和 + `POST /submit-jobs`,当请求携带 `restoreMode=CHECKPOINT|SAVEPOINT` 与 `restoreSourceJobId` 时。 + - **说明**:显式恢复契约此前接受任意 `restoreSourceJobId`,包括仍处于 `RUNNING`、`DOING_SAVEPOINT`、 + `CANCELING` 等未结束状态的作业,新作业会基于一个来源作业仍在不断推进的 checkpoint 启动。现在提交路径会在 + master 上解析来源作业状态,只要来源作业尚未进入结束状态(`FINISHED`、`FAILED`、`CANCELED` 或 + `SAVEPOINT_DONE`),就返回 HTTP `400`,报错信息为 `restoreSourceJobId= is still ; stop or cancel + the source job before restoring from its checkpoint state`。非数字的 `restoreSourceJobId` 现在也会以清晰的 + `400` 信息被拒绝。集群未知的作业 ID 不会被该保护拒绝,仍然返回原有的 `No checkpoint found ...` 错误。旧的 + `isStartWithSavePoint=true` 加 `jobId` 路径保持不变。 + - **影响**:针对仍在运行的作业提交恢复请求的脚本或客户端,现在会收到 `400` 而不是一个新作业。从已完成、 + 失败、已取消或 savepoint 停止的作业恢复的行为与之前一致。 + - **迁移指南**:先停止来源作业,例如通过 `POST /stop-job`(savepoint 恢复使用 `isStopWithSavePoint: true`, + checkpoint 恢复使用普通停止),等待其状态进入结束状态后再提交恢复请求。(#11613) + - **行为变更:REST 日志内容接口默认最多返回 64 MB** - **受影响组件**:`seatunnel-engine-server`,REST v2 接口 `GET /logs/:file`、`GET /log/:file`, 以及对应的 REST v1 接口 `GET /hazelcast/rest/maps/logs/:file`、`GET /hazelcast/rest/maps/log/:file`。 diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java index 683eaab2a253..d022042a1bdd 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java +++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java @@ -28,6 +28,7 @@ import org.apache.seatunnel.engine.common.config.JobConfig; import org.apache.seatunnel.engine.common.config.SeaTunnelConfig; import org.apache.seatunnel.engine.common.config.server.HttpConfig; +import org.apache.seatunnel.engine.common.job.JobStatus; import org.apache.seatunnel.engine.common.runtime.ExecutionMode; import org.apache.seatunnel.engine.core.checkpoint.CheckpointType; import org.apache.seatunnel.engine.core.job.JobImmutableInformation; @@ -52,6 +53,7 @@ import com.hazelcast.config.Config; import com.hazelcast.instance.impl.HazelcastInstanceImpl; +import com.hazelcast.internal.json.Json; import java.io.BufferedReader; import java.io.IOException; @@ -259,6 +261,75 @@ public void testSubmitCheckpointRestoreWithNonNumericSourceJobIdReturns400() thr () -> "responseBody=" + response.body); } + /** + * Proves the restore guard is wired into the REST submit path and not only unit-tested as a + * predicate: a restore from a still RUNNING source job is refused with 400, and once that job + * has been cancelled the same request passes the guard (it may then fail only on checkpoint + * availability, which is a different error). + */ + @Test + public void testSubmitCheckpointRestoreFromActiveSourceJobReturns400() throws Exception { + String base = "http://localhost:" + workerRestPort; + HttpResponse submit = + postJson( + base + "/submit-job?format=json&jobName=restore_guard_source", + getStreamingRequestBody()); + Assertions.assertEquals(200, submit.code, () -> "responseBody=" + submit.body); + long sourceJobId = + Long.parseLong(Json.parse(submit.body).asObject().getString("jobId", "")); + String restoreUrl = + base + + "/submit-job?format=json&restoreMode=checkpoint&restoreSourceJobId=" + + sourceJobId + + "&jobName=" + + TEST_JOB_NAME; + try { + Awaitility.await() + .atMost(60, TimeUnit.SECONDS) + .pollInterval(500, TimeUnit.MILLISECONDS) + .until( + () -> + masterServer.getCoordinatorService().getJobStatus(sourceJobId) + == JobStatus.RUNNING); + + HttpResponse refused = postJson(restoreUrl, getRequestBody()); + Assertions.assertEquals(400, refused.code, () -> "responseBody=" + refused.body); + Assertions.assertTrue(refused.body.contains("\"status\":\"fail\"")); + Assertions.assertTrue( + refused.body.contains( + "restoreSourceJobId=" + sourceJobId + " is still RUNNING"), + () -> "responseBody=" + refused.body); + } finally { + postJson(base + "/stop-job", "{\"jobId\": " + sourceJobId + "}"); + } + + Awaitility.await() + .atMost(60, TimeUnit.SECONDS) + .pollInterval(500, TimeUnit.MILLISECONDS) + .until( + () -> + masterServer + .getCoordinatorService() + .getJobStatus(sourceJobId) + .isEndState()); + + HttpResponse afterCancel = postJson(restoreUrl, getRequestBody()); + Assertions.assertFalse( + afterCancel.body.contains("is still"), () -> "responseBody=" + afterCancel.body); + if (afterCancel.code == 200) { + // A checkpoint completed before the cancel, so the restore started a new job; stop it. + long restoredJobId = + Long.parseLong(Json.parse(afterCancel.body).asObject().getString("jobId", "")); + postJson(base + "/stop-job", "{\"jobId\": " + restoredJobId + "}"); + } else { + Assertions.assertEquals( + 400, afterCancel.code, () -> "responseBody=" + afterCancel.body); + Assertions.assertTrue( + afterCancel.body.contains("No checkpoint found"), + () -> "responseBody=" + afterCancel.body); + } + } + @Test public void testSubmitSavepointRestoreWithoutSourceJobIdReturns400() throws Exception { String requestUrl = @@ -441,6 +512,15 @@ private void storeFakeSourceCheckpoint( RestUtil.convertByteToJsonNode(getRequestBody().getBytes(StandardCharsets.UTF_8))); } + /** An unbounded FakeSource job that stays RUNNING until it is stopped. */ + private String getStreamingRequestBody() { + return getRequestBody() + .replace("\"job.mode\": \"BATCH\"", "\"job.mode\": \"STREAMING\"") + .replace( + "\"row.num\": 1,", + "\"row.num\": 10,\n \"split.read-interval\": 1000,"); + } + private String getRequestBody() { return "{\n" + " \"env\": {\n" From 4aba1e68924e5308c9d7dca3ec9087e46af8aba8 Mon Sep 17 00:00:00 2001 From: davidzollo Date: Thu, 22 Oct 2026 05:14:17 -0400 Subject: [PATCH 12/19] [Improve][Zeta] Gate checkpoint restore controls on terminal jobs --- docs/en/engines/zeta/web-ui.md | 5 +- docs/zh/engines/zeta/web-ui.md | 5 +- .../src/locales/en_US/detail.ts | 3 +- .../src/locales/zh_CN/detail.ts | 3 +- .../src/tests/checkpoints.spec.ts | 48 +++++++++++++++- .../src/views/jobs/checkpoints.tsx | 55 ++++++++++++------- .../src/views/jobs/detail.tsx | 2 +- 7 files changed, 88 insertions(+), 33 deletions(-) diff --git a/docs/en/engines/zeta/web-ui.md b/docs/en/engines/zeta/web-ui.md index e6919b6bac61..183ed5d83734 100644 --- a/docs/en/engines/zeta/web-ui.md +++ b/docs/en/engines/zeta/web-ui.md @@ -73,9 +73,6 @@ The "Running Jobs" section lists SeaTunnel jobs that are currently in execution. The list refreshes periodically and supports pagination. The Action column provides `View`, `Stop`, `Savepoint`, and `Cancel` controls. `Stop` sends a graceful stop request without savepoint, `Savepoint` stops the job through savepoint, and `Cancel` sends a forced stop request for exceptional situations. All state-changing actions require confirmation and show status feedback in the page. -![running.png](../../../images/ui/running.png) -![detail.png](../../../images/ui/detail.png) - ### Job Detail The Job Detail page contains five main tabs: @@ -83,7 +80,7 @@ The Job Detail page contains five main tabs: - **Overview**: shows the job DAG, source and sink throughput metrics, flush-signal metrics, and realtime vertex or edge metrics when observability is enabled. - **Exception**: shows the job error message when the job has failed or reported an exception. - **Configuration**: shows the runtime job configuration exposed by the engine. -- **Checkpoints**: shows checkpoint counts, latest completed checkpoint, latest savepoint, and recent checkpoint history. It offers separate checkpoint and savepoint restore actions only when every pipeline has a corresponding restorable state, then opens the submit panel with the source job ID and restore mode prefilled. The tab does not check the job status: the engine refuses the restore while the source job is still active, and reports `No checkpoint found` when its state has already been cleaned up. Both messages are shown in the submit panel, so stop, savepoint or cancel the source job before restoring from it. +- **Checkpoints**: shows checkpoint counts, latest completed checkpoint, latest savepoint, and recent checkpoint history. It offers separate checkpoint and savepoint restore actions only when every pipeline has a corresponding restorable state. These actions remain disabled until the source job reaches an end state (`FINISHED`, `FAILED`, `CANCELED`, or `SAVEPOINT_DONE`); the engine checks the status again when the restore is submitted. An enabled action opens the submit panel with the source job ID and restore mode prefilled. If checkpoint state has already been cleaned up, the engine returns `No checkpoint found` and the submit panel shows that error. - **Log**: shows job log files returned by the engine log API. #### Realtime Observability diff --git a/docs/zh/engines/zeta/web-ui.md b/docs/zh/engines/zeta/web-ui.md index dcc22f501d68..58671dc7e4b7 100644 --- a/docs/zh/engines/zeta/web-ui.md +++ b/docs/zh/engines/zeta/web-ui.md @@ -71,9 +71,6 @@ Jobs 页面提供 “Submit Job” 面板,可以直接在 Web UI 中提交新 列表会周期性刷新,并支持分页。Action 列提供 `View`、`Stop`、`Savepoint` 和 `Cancel` 控件。`Stop` 发送不带 savepoint 的平滑停止请求,`Savepoint` 通过 savepoint 停止作业,`Cancel` 面向异常场景发送强制停止请求。所有会改变状态的操作都需要确认,并会在页面展示状态反馈。 -![running.png](../../../images/ui/running.png) -![detail.png](../../../images/ui/detail.png) - ### 作业详情 作业详情页包含五个主要 tab: @@ -81,7 +78,7 @@ Jobs 页面提供 “Submit Job” 面板,可以直接在 Web UI 中提交新 - **Overview**:展示作业 DAG、source 和 sink 吞吐指标、flush signal 指标,以及开启可观测性后的 vertex 或 edge 实时指标。 - **Exception**:当作业失败或上报异常时,展示异常文本。 - **Configuration**:展示引擎暴露的运行时作业配置。 -- **Checkpoints**:展示 checkpoint 计数、最近完成的 checkpoint、最近的 savepoint 和 checkpoint 历史记录。仅当所有 pipeline 都存在对应可恢复状态时,页面才会提供独立的 checkpoint 或 savepoint 恢复操作;操作会打开提交面板并自动带入来源作业 ID 和恢复模式。该页签不会检查作业状态:来源作业仍在运行时引擎会拒绝恢复,其状态已被清理时会返回 `No checkpoint found`,两类错误信息都会显示在提交面板中,因此请先停止、savepoint 或取消来源作业再进行恢复。 +- **Checkpoints**:展示 checkpoint 计数、最近完成的 checkpoint、最近的 savepoint 和 checkpoint 历史记录。仅当所有 pipeline 都存在对应可恢复状态时,页面才会提供独立的 checkpoint 或 savepoint 恢复操作。来源作业达到结束状态(`FINISHED`、`FAILED`、`CANCELED` 或 `SAVEPOINT_DONE`)之前,这些操作保持禁用;提交恢复请求时引擎还会再次检查状态。启用后的操作会打开提交面板,并自动带入来源作业 ID 和恢复模式。若 checkpoint 状态已被清理,引擎会返回 `No checkpoint found`,提交面板会显示该错误。 - **Log**:展示引擎日志 API 返回的作业日志文件。 #### 实时可观测性(Realtime Observability) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts index 7acfeddb3c55..fb690d1fc611 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts @@ -75,7 +75,8 @@ export default { action: 'Action', restoreLatest: 'Restore Latest State', restoreFromCheckpoint: 'Restore From Checkpoint', - restoreFromSavepoint: 'Restore From Savepoint' + restoreFromSavepoint: 'Restore From Savepoint', + stopBeforeRestore: 'Stop, savepoint-stop, or cancel this job before restoring its state.' }, liveMetrics: { pinnedTitle: 'Pinned live metrics', diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts index a6bddc4e2244..5135aaeafe18 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts @@ -75,7 +75,8 @@ export default { action: '操作', restoreLatest: '恢复最新状态', restoreFromCheckpoint: '从 Checkpoint 恢复', - restoreFromSavepoint: '从 Savepoint 恢复' + restoreFromSavepoint: '从 Savepoint 恢复', + stopBeforeRestore: '请先停止、保存点停止或取消此作业,再恢复其状态。' }, liveMetrics: { pinnedTitle: '已固定实时指标', diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/checkpoints.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/checkpoints.spec.ts index ff3a4e11e19a..3b1dff7164a0 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/checkpoints.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/checkpoints.spec.ts @@ -78,7 +78,8 @@ describe('checkpoints', () => { const wrapper = mount(checkpoints, { props: { - jobId: '123456789' + jobId: '123456789', + jobStatus: 'FINISHED' }, global: { plugins: [i18n] @@ -142,7 +143,8 @@ describe('checkpoints', () => { const wrapper = mount(checkpoints, { props: { - jobId: '123456789' + jobId: '123456789', + jobStatus: 'FINISHED' }, global: { plugins: [i18n] @@ -164,4 +166,46 @@ describe('checkpoints', () => { }) wrapper.unmount() }) + + test('blocks restore while the source job is active and enables it after stopping', async () => { + vi.spyOn(JobsService, 'getCheckpointOverview').mockResolvedValue({ + jobId: '123456789', + updatedAt: 1720000000123, + pipelines: [ + { + pipelineId: 1, + counts: { triggered: 1, completed: 1, failed: 0, inProgress: 0, restored: 0 }, + latestCompleted: { + checkpointId: 10, + checkpointType: 'checkpoint', + status: 'COMPLETED' + } + } + ] + }) + vi.spyOn(JobsService, 'getCheckpointHistory').mockResolvedValue([]) + + const wrapper = mount(checkpoints, { + props: { jobId: '123456789', jobStatus: 'RUNNING' }, + global: { plugins: [i18n] } + }) + + await flushPromises() + const restoreButton = wrapper + .findAll('button') + .find((button) => button.text() === 'Restore From Checkpoint') + expect(restoreButton?.attributes('disabled')).toBeDefined() + expect(wrapper.text()).toContain('Stop, savepoint-stop, or cancel this job') + await restoreButton?.trigger('click') + expect(routerState.push).not.toHaveBeenCalled() + + await wrapper.setProps({ jobStatus: 'FINISHED' }) + expect(restoreButton?.attributes('disabled')).toBeUndefined() + await restoreButton?.trigger('click') + expect(routerState.push).toHaveBeenCalledWith({ + name: 'jobs', + query: { restoreMode: 'CHECKPOINT', restoreSourceJobId: '123456789' } + }) + wrapper.unmount() + }) }) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/checkpoints.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/checkpoints.tsx index 840dbbaec48b..0113c2770c11 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/checkpoints.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/checkpoints.tsx @@ -33,6 +33,10 @@ export default defineComponent({ jobId: { type: String, required: true + }, + jobStatus: { + type: String, + default: '' } }, setup(props) { @@ -85,7 +89,11 @@ export default defineComponent({ ) } + const isTerminalState = () => + ['FINISHED', 'FAILED', 'CANCELED', 'SAVEPOINT_DONE'].includes(props.jobStatus) + const restoreLatestState = (restoreMode: RestoreMode) => { + if (!isTerminalState()) return router.push({ name: 'jobs', query: { @@ -176,27 +184,34 @@ export default defineComponent({ {(canRestore('CHECKPOINT') || canRestore('SAVEPOINT')) && ( - - {canRestore('CHECKPOINT') && ( - restoreLatestState('CHECKPOINT')} - > - {t('detail.checkpoints.restoreFromCheckpoint')} - - )} - {canRestore('SAVEPOINT') && ( - restoreLatestState('SAVEPOINT')} - > - {t('detail.checkpoints.restoreFromSavepoint')} - + + {props.jobStatus && !isTerminalState() && ( + {t('detail.checkpoints.stopBeforeRestore')} )} + + {canRestore('CHECKPOINT') && ( + restoreLatestState('CHECKPOINT')} + > + {t('detail.checkpoints.restoreFromCheckpoint')} + + )} + {canRestore('SAVEPOINT') && ( + restoreLatestState('SAVEPOINT')} + > + {t('detail.checkpoints.restoreFromSavepoint')} + + )} + )} {error.value && {error.value}} diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/detail.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/detail.tsx index 4e26353954f9..c71910529716 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/detail.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/detail.tsx @@ -665,7 +665,7 @@ export default defineComponent({ - + From 379efa74e984f486db562ff9903eabd6e9cbfffe Mon Sep 17 00:00:00 2001 From: davidzollo Date: Sun, 25 Oct 2026 05:33:13 -0400 Subject: [PATCH 13/19] [Fix][Zeta] Validate structured member tag values --- docs/en/engines/zeta/rest-api-v2.md | 5 +++-- docs/en/engines/zeta/web-ui.md | 4 +++- docs/zh/engines/zeta/rest-api-v2.md | 5 +++-- docs/zh/engines/zeta/web-ui.md | 4 +++- .../seatunnel/engine/e2e/RestApiIT.java | 11 ++++++++++ .../rest/service/UpdateTagsService.java | 11 ++++++++-- .../rest/service/UpdateTagsServiceTest.java | 20 +++++++++++++++++++ 7 files changed, 52 insertions(+), 8 deletions(-) diff --git a/docs/en/engines/zeta/rest-api-v2.md b/docs/en/engines/zeta/rest-api-v2.md index 1bdf64e9a910..fffdc4385847 100644 --- a/docs/en/engines/zeta/rest-api-v2.md +++ b/docs/en/engines/zeta/rest-api-v2.md @@ -1358,7 +1358,7 @@ For more information about customize encryption, please refer to the documentati #### update node tags ##### Body -`/update-tags` keeps the legacy flat `Map` contract: every top-level key is a tag name and every value is that tag's value. Tag values must be strings; the server stores every value as a string, so nested objects are not a supported value type. No key is reserved, so a key literally named `uuid` or `tags` is stored as an ordinary tag instead of being read as a target member or a nested tag map. The request always applies to the REST node that serves it; to target a specific node, send the request to that node's own REST address. +`/update-tags` keeps the legacy flat `Map` contract: every top-level key is a tag name and every value is that tag's value. String values are recommended; for compatibility, the server converts non-string values to strings (and null to an empty string) rather than rejecting them. Nested objects are converted using Java's map representation, not retained as objects. No key is reserved, so a key literally named `uuid` or `tags` is stored as an ordinary tag instead of being read as a target member or a nested tag map. The request always applies to the REST node that serves it; to target a specific node, send the request to that node's own REST address. ```json { @@ -1427,7 +1427,7 @@ This is the endpoint the Web UI Workers page uses. It is additive: `/update-tags | Field | Required | Type | Description | |--------|----------|--------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `uuid` | yes | string | Member UUID of the node that must serve this request. Read it from `/system-monitoring-information`, whose entries carry `uuid` and `localMember` for every cluster member. | -| `tags` | yes | object | Tag name to tag value map that replaces the node's current tags. An empty object clears all tags. | +| `tags` | yes | object | Tag name to string value map that replaces the node's current tags. An empty object clears all tags. Non-string values are rejected. | ```json { @@ -1467,6 +1467,7 @@ Each error is returned with HTTP status `400` and the following body. | The request body is not a JSON object | `Invalid JSON format in request body.` | | `uuid` is missing or does not match the node serving the request | `Target member uuid must match the REST node serving this request.` | | `tags` is missing or is not a JSON object | `The tags field must be an object.` | +| Any value inside `tags` is not a string | `Tag values must be strings.` | ```json { diff --git a/docs/en/engines/zeta/web-ui.md b/docs/en/engines/zeta/web-ui.md index 183ed5d83734..577f166e299b 100644 --- a/docs/en/engines/zeta/web-ui.md +++ b/docs/en/engines/zeta/web-ui.md @@ -80,9 +80,11 @@ The Job Detail page contains five main tabs: - **Overview**: shows the job DAG, source and sink throughput metrics, flush-signal metrics, and realtime vertex or edge metrics when observability is enabled. - **Exception**: shows the job error message when the job has failed or reported an exception. - **Configuration**: shows the runtime job configuration exposed by the engine. -- **Checkpoints**: shows checkpoint counts, latest completed checkpoint, latest savepoint, and recent checkpoint history. It offers separate checkpoint and savepoint restore actions only when every pipeline has a corresponding restorable state. These actions remain disabled until the source job reaches an end state (`FINISHED`, `FAILED`, `CANCELED`, or `SAVEPOINT_DONE`); the engine checks the status again when the restore is submitted. An enabled action opens the submit panel with the source job ID and restore mode prefilled. If checkpoint state has already been cleaned up, the engine returns `No checkpoint found` and the submit panel shows that error. +- **Checkpoints**: shows checkpoint counts, latest completed checkpoint, latest savepoint, and recent checkpoint history. It offers separate checkpoint and savepoint restore actions only when every pipeline has a corresponding restorable state. These actions remain disabled until the source job reaches an end state (`FINISHED`, `FAILED`, `CANCELED`, or `SAVEPOINT_DONE`); the engine checks the status again when the restore is submitted. An enabled action opens the submit panel with the source job ID and restore mode prefilled. - **Log**: shows job log files returned by the engine log API. +If the engine still sees the source job as active when a restore is submitted, it returns HTTP `400` with `restoreSourceJobId= is still ; stop or cancel the source job before restoring from its checkpoint state`. The submit panel shows this message. If the source job has ended but its checkpoint state was cleaned up, the submit panel instead shows the engine's `No checkpoint found` error. + #### Realtime Observability On the Job Detail page, the DAG view can display realtime metrics for the recent window (3 minutes by default, up to 10 minutes): diff --git a/docs/zh/engines/zeta/rest-api-v2.md b/docs/zh/engines/zeta/rest-api-v2.md index 87ed6a88afb3..514262788d39 100644 --- a/docs/zh/engines/zeta/rest-api-v2.md +++ b/docs/zh/engines/zeta/rest-api-v2.md @@ -1333,7 +1333,7 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload?restoreMode=CHECKPOINT& #### 更新节点tags ##### 请求体 -`/update-tags` 保留旧版扁平 `Map` 契约:每个顶层 key 都是 tag 名,对应的 value 就是该 tag 的值。tag 值必须是字符串;服务端会把每个值按字符串存储,不支持嵌套对象作为值。该接口不保留任何特殊 key,因此名为 `uuid` 或 `tags` 的 key 也只会作为普通 tag 存储,不会被解释为目标成员或嵌套的 tag map。请求始终作用于响应该请求的 REST 节点;如需更新指定节点,请把请求发送到该节点自己的 REST 地址。 +`/update-tags` 保留旧版扁平 `Map` 契约:每个顶层 key 都是 tag 名,对应的 value 就是该 tag 的值。建议使用字符串值;为保持兼容,服务端会把非字符串值转换为字符串(null 转为空字符串),不会拒绝。嵌套对象会转换为 Java map 的字符串表示形式,不会作为对象保存。该接口不保留任何特殊 key,因此名为 `uuid` 或 `tags` 的 key 也只会作为普通 tag 存储,不会被解释为目标成员或嵌套的 tag map。请求始终作用于响应该请求的 REST 节点;如需更新指定节点,请把请求发送到该节点自己的 REST 地址。 ```json { @@ -1402,7 +1402,7 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload?restoreMode=CHECKPOINT& | 字段 | 必填 | 类型 | 说明 | |--------|----|------|-------------------------------------------------------------------------------------------------------------| | `uuid` | 是 | 字符串 | 必须响应本次请求的节点的成员 UUID。可从 `/system-monitoring-information` 获取,其返回的每个集群成员都带有 `uuid` 和 `localMember` 字段。 | -| `tags` | 是 | 对象 | tag 名到 tag 值的映射,会整体替换该节点当前的 tags。空对象表示清空全部 tags。 | +| `tags` | 是 | 对象 | tag 名到字符串值的映射,会整体替换该节点当前的 tags。空对象表示清空全部 tags;非字符串值会被拒绝。 | ```json { @@ -1442,6 +1442,7 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload?restoreMode=CHECKPOINT& | 请求体不是 JSON 对象 | `Invalid JSON format in request body.` | | 缺少 `uuid`,或 `uuid` 与响应请求的节点不一致 | `Target member uuid must match the REST node serving this request.` | | 缺少 `tags`,或 `tags` 不是 JSON 对象 | `The tags field must be an object.` | +| `tags` 中存在非字符串值 | `Tag values must be strings.` | ```json { diff --git a/docs/zh/engines/zeta/web-ui.md b/docs/zh/engines/zeta/web-ui.md index 58671dc7e4b7..5bf1cc89bcd3 100644 --- a/docs/zh/engines/zeta/web-ui.md +++ b/docs/zh/engines/zeta/web-ui.md @@ -78,9 +78,11 @@ Jobs 页面提供 “Submit Job” 面板,可以直接在 Web UI 中提交新 - **Overview**:展示作业 DAG、source 和 sink 吞吐指标、flush signal 指标,以及开启可观测性后的 vertex 或 edge 实时指标。 - **Exception**:当作业失败或上报异常时,展示异常文本。 - **Configuration**:展示引擎暴露的运行时作业配置。 -- **Checkpoints**:展示 checkpoint 计数、最近完成的 checkpoint、最近的 savepoint 和 checkpoint 历史记录。仅当所有 pipeline 都存在对应可恢复状态时,页面才会提供独立的 checkpoint 或 savepoint 恢复操作。来源作业达到结束状态(`FINISHED`、`FAILED`、`CANCELED` 或 `SAVEPOINT_DONE`)之前,这些操作保持禁用;提交恢复请求时引擎还会再次检查状态。启用后的操作会打开提交面板,并自动带入来源作业 ID 和恢复模式。若 checkpoint 状态已被清理,引擎会返回 `No checkpoint found`,提交面板会显示该错误。 +- **Checkpoints**:展示 checkpoint 计数、最近完成的 checkpoint、最近的 savepoint 和 checkpoint 历史记录。仅当所有 pipeline 都存在对应可恢复状态时,页面才会提供独立的 checkpoint 或 savepoint 恢复操作。来源作业达到结束状态(`FINISHED`、`FAILED`、`CANCELED` 或 `SAVEPOINT_DONE`)之前,这些操作保持禁用;提交恢复请求时引擎还会再次检查状态。启用后的操作会打开提交面板,并自动带入来源作业 ID 和恢复模式。 - **Log**:展示引擎日志 API 返回的作业日志文件。 +如果提交恢复请求时引擎仍认为来源作业处于运行中,会返回 HTTP `400` 和 `restoreSourceJobId= is still ; stop or cancel the source job before restoring from its checkpoint state`,提交面板会显示该信息。如果来源作业已经结束,但 checkpoint 状态已被清理,提交面板则会显示引擎返回的 `No checkpoint found` 错误。 + #### 实时可观测性(Realtime Observability) 在 Job Detail 页面中,DAG 图支持展示“最近 N 分钟”的实时指标(默认 3 分钟,最大 10 分钟): diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java index ecf0c73f62d5..dc43a69b6fc1 100644 --- a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java +++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java @@ -1140,6 +1140,17 @@ public void testUpdateLocalMemberTagsOnlyMutatesTheServingMember() { .statusCode(200) .body("workers", equalTo("1")); + given().body(tagRequest(localUuid, "{\"zone\": {\"nested\": \"prod\"}}")) + .post(jettyBase + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) + .then() + .statusCode(400) + .body("status", equalTo("fail")) + .body("message", equalTo("Tag values must be strings.")); + given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?node=node1") + .then() + .statusCode(200) + .body("workers", equalTo("1")); + given().body(tagRequest(localUuid, "{\"zone\": \"prod\"}")) .post(jettyBase + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) .then() diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java index 88a5cf7b3ff9..7ea82804ae94 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java @@ -97,7 +97,8 @@ private void validateTargetMember(Map params, MemberImpl localMe * Extracts tags from the structured request format. * * @param params parsed request parameters. - * @return tag map from the structured request. + * @return tag map from the structured request, with string values only. + * @throws IllegalArgumentException if tags is not an object or contains a non-string value. */ @SuppressWarnings("unchecked") static Map extractStructuredTagParams(Map params) { @@ -105,7 +106,13 @@ static Map extractStructuredTagParams(Map params if (!(tags instanceof Map)) { throw new IllegalArgumentException("The tags field must be an object."); } - return (Map) tags; + Map tagParams = (Map) tags; + for (Object value : tagParams.values()) { + if (!(value instanceof String)) { + throw new IllegalArgumentException("Tag values must be strings."); + } + } + return tagParams; } /** diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsServiceTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsServiceTest.java index 32ae81fed09c..3d20ba51dc0d 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsServiceTest.java +++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsServiceTest.java @@ -36,10 +36,14 @@ void shouldPreserveLegacyTagNames() { Map request = new HashMap<>(); request.put("uuid", "legacy-member-tag"); request.put("tags", nestedTag); + request.put("number", 42); + request.put("empty", null); Map tags = UpdateTagsService.toStringTags(request); assertEquals("legacy-member-tag", tags.get("uuid")); assertEquals(nestedTag.toString(), tags.get("tags")); + assertEquals("42", tags.get("number")); + assertEquals("", tags.get("empty")); } @Test @@ -66,6 +70,22 @@ void shouldRejectStructuredRequestWithoutTagsObject() { assertTrue(error.getMessage().contains("tags field")); } + @Test + void shouldRejectNonStringStructuredTagValues() { + Map tags = new HashMap<>(); + Map request = new HashMap<>(); + request.put("tags", tags); + + for (Object value : new Object[] {42, null, new HashMap()}) { + tags.put("zone", value); + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> UpdateTagsService.extractStructuredTagParams(request)); + assertEquals("Tag values must be strings.", error.getMessage()); + } + } + @Test void shouldExcludeTagContentFromAuditSummary() { Map tags = new HashMap<>(); From e86481f3500c37a627f6e2516b986a0ea40940b0 Mon Sep 17 00:00:00 2001 From: davidzollo Date: Wed, 28 Oct 2026 00:07:31 -0400 Subject: [PATCH 14/19] [Fix][Zeta] Resolve Web UI operation build failures --- .../seatunnel-engine-ui/src/tests/jobs.spec.ts | 3 ++- .../seatunnel-engine-ui/src/tests/managers.spec.ts | 3 ++- .../seatunnel-engine-ui/src/views/managers/index.tsx | 7 +++++-- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts index 7e55f8556113..bb2e0ed56176 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts @@ -44,7 +44,8 @@ vi.mock('vue-router', () => ({ }) })) -vi.mock('@/service/service', () => ({ +vi.mock('@/service/service', async (importOriginal) => ({ + ...(await importOriginal()), get: vi.fn(), post: vi.fn(), isRequestOutcomeUnknown: () => false diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts index 67818abc4c2c..11f718f705f2 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts @@ -276,13 +276,14 @@ describe('managers', () => { expect(wrapper.findComponent(NDataTable).props('columns')).toEqual( expect.arrayContaining([expect.objectContaining({ key: 'details', fixed: 'right' })]) ) + expect(wrapper.findComponent(NDataTable).props('scrollX')).toBe(1200) }) test('worker table scrolls its action column with bounded slot summaries', async () => { const { wrapper } = await setup() await flushPromises() const table = wrapper.findComponent(NDataTable) expect(table.props('tableLayout')).toBe('fixed') - expect(table.props('scrollX')).toBe(1200) + expect(table.props('scrollX')).toBe(1460) expect(table.props('columns')).toEqual( expect.arrayContaining([ expect.objectContaining({ key: 'details', fixed: undefined }), diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx index 8ac7278f044d..52336ab3364e 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx @@ -238,7 +238,10 @@ export default defineComponent({ return entries.map(([key, value]) => `${key}=${value}`).join(', ') } - const monitorValue = (row: NodeResources, field: keyof Monitor) => row.monitor?.[field] ?? '—' + const monitorValue = ( + row: NodeResources, + field: Exclude + ) => row.monitor?.[field] ?? '—' // Monitoring values are flat strings except the member tags, which are a structured map. const monitorFieldText = (field: string, value: unknown) => field === 'tags' && value && typeof value === 'object' @@ -336,7 +339,7 @@ export default defineComponent({ { title: t('managers.details'), key: 'details', - fixed: isMaster.value ? 'right' : undefined, + fixed: isMaster.value ? ('right' as const) : undefined, width: 95, render: (row) => ( Date: Fri, 30 Oct 2026 23:04:05 -0400 Subject: [PATCH 15/19] [Feature][Zeta] Address review on Web UI operation controls - Assert the existing Jetty REST error envelope (": ") in RestApiIT and BasicAuthenticationIT instead of the bare message. - Preserve untouched worker tag entries verbatim in the tag editor: keys that contain "=", values with surrounding whitespace and a literal "__proto__" key round-trip unchanged; only new or edited lines are parsed. - Stop a completed job action from restarting the running-jobs polling loop after the component has been unmounted. --- .../engine/e2e/BasicAuthenticationIT.java | 3 +- .../seatunnel/engine/e2e/RestApiIT.java | 10 ++-- .../src/tests/jobs.spec.ts | 43 ++++++++++++++++ .../src/tests/managers.spec.ts | 35 +++++++++++++ .../src/views/jobs/running-jobs.tsx | 10 +++- .../src/views/managers/index.tsx | 49 +++++++++++++------ 6 files changed, 129 insertions(+), 21 deletions(-) diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/BasicAuthenticationIT.java b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/BasicAuthenticationIT.java index 05af3301eb9d..2fe81663ceee 100644 --- a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/BasicAuthenticationIT.java +++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/BasicAuthenticationIT.java @@ -244,10 +244,11 @@ public void testOperationEndpointsWithCorrectCredentials() { .then() .statusCode(400) .body("status", equalTo("fail")) + // The shared ExceptionHandlingFilter prefixes the message with the exception type. .body( "message", equalTo( - "Target member uuid must match the REST node serving this request.")); + "IllegalArgumentException: Target member uuid must match the REST node serving this request.")); } /** Test submitting a job via REST API with correct credentials. */ diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java index dc43a69b6fc1..c799793671a4 100644 --- a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java +++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java @@ -1122,6 +1122,8 @@ public void testUpdateLocalMemberTagsOnlyMutatesTheServingMember() { 1, members.stream().filter(m -> Boolean.TRUE.equals(m.get("localMember"))).count()); String remoteUuid = node2.getCluster().getLocalMember().getUuid().toString(); + // The Jetty ExceptionHandlingFilter serializes commons-lang3 ExceptionUtils.getMessage(e), + // so every 400 raised by the servlet validation carries the ": " prefix. given().body(tagRequest(remoteUuid, "{\"zone\": \"prod\"}")) .post(jettyBase + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) .then() @@ -1130,7 +1132,7 @@ public void testUpdateLocalMemberTagsOnlyMutatesTheServingMember() { .body( "message", equalTo( - "Target member uuid must match the REST node serving this request.")); + "IllegalArgumentException: Target member uuid must match the REST node serving this request.")); given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?zone=prod") .then() .statusCode(200) @@ -1145,7 +1147,7 @@ public void testUpdateLocalMemberTagsOnlyMutatesTheServingMember() { .then() .statusCode(400) .body("status", equalTo("fail")) - .body("message", equalTo("Tag values must be strings.")); + .body("message", equalTo("IllegalArgumentException: Tag values must be strings.")); given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?node=node1") .then() .statusCode(200) @@ -1191,7 +1193,9 @@ public void testUpdateLocalMemberTagsOnlyMutatesTheServingMember() { .post(jettyBase + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) .then() .statusCode(400) - .body("message", equalTo("The tags field must be an object.")); + .body( + "message", + equalTo("IllegalArgumentException: The tags field must be an object.")); } private static String tagRequest(String uuid, String tagsJson) { diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts index bb2e0ed56176..aa14894428ba 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/jobs.spec.ts @@ -121,6 +121,49 @@ describe('jobs', () => { }) wrapper.unmount() }) + test('Running Jobs does not restart polling when a job action completes after unmount', async () => { + vi.useFakeTimers() + try { + vi.spyOn(JobsService, 'getRunningJobs').mockResolvedValue({ + data: [ + { + jobId: '888413907541032961', + jobName: 'SeaTunnel_Job', + jobStatus: 'RUNNING', + errorMsg: '', + createTime: '2024-09-17 21:19:41', + finishTime: '' + } + ] as Job[], + total: 1 + } as JobPage) + let resolveStop!: (value: Awaited>) => void + vi.spyOn(JobsService, 'stopJob').mockImplementation( + () => + new Promise>>((resolve) => { + resolveStop = resolve + }) + ) + const wrapper = mount(runningJobs, { global: { plugins: [i18n] } }) + await flushPromises() + expect(JobsService.getRunningJobs).toHaveBeenCalledTimes(1) + const confirmations = wrapper.findAllComponents(NPopconfirm) + const onPositiveClick = confirmations[0].props('onPositiveClick') as ( + event: MouseEvent + ) => Promise + const pendingAction = onPositiveClick(new MouseEvent('click')) + // Navigate away while the stop request is still pending, then let it succeed. + wrapper.unmount() + resolveStop({ jobId: '888413907541032961' }) + await pendingAction + await flushPromises() + await vi.advanceTimersByTimeAsync(15_000) + // The success continuation must neither refetch nor re-arm the five second polling loop. + expect(JobsService.getRunningJobs).toHaveBeenCalledTimes(1) + } finally { + vi.useRealTimers() + } + }) test('Finished Jobs component', async () => { const mockData = { data: [ diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts index 11f718f705f2..8e07fda3fd48 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts @@ -223,6 +223,41 @@ describe('managers', () => { // The table is refetched after the mutation instead of trusting the response. expect(managerService.getMonitors).toHaveBeenCalledTimes(2) }) + test('keeps untouched tag strings verbatim and only parses edited lines', async () => { + // Server tags are arbitrary strings: a key may contain "=", a value may carry whitespace and + // "__proto__" is an ordinary key. Saving must not rewrite entries the operator did not touch, + // because the server replaces the whole map and scheduling matches tags exactly. + const existingTags = Object.fromEntries([ + ['zone=region', 'prod'], + ['note', ' a=b '], + ['__proto__', 'literal'] + ] as const) + vi.mocked(managerService.getMonitors).mockResolvedValue([ + { ...monitor(), uuid: 'worker-1', localMember: true, tags: existingTags } + ]) + const { wrapper } = await setup() + await flushPromises() + await wrapper + .findAllComponents(NButton) + .find((button) => button.text() === 'Select')! + .trigger('click') + const textarea = wrapper.find('textarea') + expect(textarea.element.value).toBe('zone=region=prod\nnote= a=b \n__proto__=literal') + await textarea.setValue(`${textarea.element.value}\nowner=team=data`) + const onPositiveClick = wrapper.findAllComponents(NPopconfirm)[1].props('onPositiveClick') as ( + event: MouseEvent + ) => Promise + await onPositiveClick(new MouseEvent('click')) + await flushPromises() + expect(managerService.updateTags).toHaveBeenCalledTimes(1) + const sentTags = vi.mocked(managerService.updateTags).mock.calls[0][0].tags + expect(Object.entries(sentTags)).toEqual([ + ['zone=region', 'prod'], + ['note', ' a=b '], + ['__proto__', 'literal'], + ['owner', 'team=data'] + ]) + }) test('rejects duplicate tag keys before calling the server', async () => { vi.mocked(managerService.getMonitors).mockResolvedValue([ { ...monitor(), uuid: 'worker-1', localMember: true, tags: {} } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/running-jobs.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/running-jobs.tsx index 14629d23b089..40380c111ec2 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/running-jobs.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/running-jobs.tsx @@ -45,7 +45,14 @@ export default defineComponent({ let timer: ReturnType | undefined let fetchVersion = 0 + // Set once the component is unmounted. The version counter only invalidates requests that were + // already in flight; a job action whose POST settles after navigation would otherwise call + // fetch() again and re-arm the polling loop for a component that no longer exists. + let disposed = false const fetch = async () => { + if (disposed) { + return + } if (timer) { clearTimeout(timer) timer = undefined @@ -66,12 +73,13 @@ export default defineComponent({ } } } finally { - if (currentVersion === fetchVersion) { + if (!disposed && currentVersion === fetchVersion) { timer = setTimeout(fetch, 5000) } } } onUnmounted(() => { + disposed = true fetchVersion++ if (timer) { clearTimeout(timer) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx index 52336ab3364e..c59a96662fc0 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx @@ -62,6 +62,11 @@ export default defineComponent({ const tagMessage = ref('') const tagError = ref('') const tagLoading = ref(false) + // Existing tags are arbitrary server strings that the key=value line format cannot always + // represent unambiguously: a key may itself contain "=" and a value may carry surrounding + // whitespace. Each entry is remembered under the exact line it was serialized to, so a line + // the operator did not touch is sent back as the original pair instead of being re-parsed. + let existingTagLines = new Map() let timer: ReturnType | undefined let generation = 0 let disposed = false @@ -146,26 +151,34 @@ export default defineComponent({ document.removeEventListener('visibilitychange', onVisibilityChange) }) + // New or edited lines split on the first "=" only; the key is trimmed, the value is kept + // verbatim because the server accepts any string and trimming would silently change it. + const parseTagLine = (line: string): [string, string] => { + const separatorIndex = line.indexOf('=') + const key = line.substring(0, separatorIndex).trim() + if (!key) { + throw new Error(t('managers.tagEditor.invalid')) + } + return [key, line.substring(separatorIndex + 1)] + } + const parseTags = () => { - const tags: Record = {} - const tagKeys = new Set() + // Collected in a Map and converted with Object.fromEntries so that a literal "__proto__" key + // becomes an own property instead of reaching the prototype setter of a plain object. + const tags = new Map() for (const rawLine of tagContent.value.split('\n')) { - const line = rawLine.trim() - if (!line) { + if (!rawLine.trim()) { continue } - const separatorIndex = line.indexOf('=') - const key = line.substring(0, separatorIndex).trim() - if (!key) { - throw new Error(t('managers.tagEditor.invalid')) - } - if (tagKeys.has(key)) { + // A line that still reads exactly as serialized by selectMonitor is the untouched original + // entry and keeps its exact key and value; only other lines are parsed. + const [key, value] = existingTagLines.get(rawLine) ?? parseTagLine(rawLine) + if (tags.has(key)) { throw new Error(t('managers.tagEditor.duplicate')) } - tagKeys.add(key) - tags[key] = line.substring(separatorIndex + 1).trim() + tags.set(key, value) } - return tags + return Object.fromEntries(tags) } // The poll loop allows one request in flight at a time. If a poll is already running it may @@ -223,9 +236,13 @@ export default defineComponent({ const selectMonitor = (monitor: Monitor) => { selectedMonitor.value = monitor - tagContent.value = Object.entries(monitor.tags || {}) - .map(([key, value]) => `${key}=${value}`) - .join('\n') + existingTagLines = new Map( + Object.entries(monitor.tags || {}).map(([key, value]): [string, [string, string]] => [ + `${key}=${value}`, + [key, value] + ]) + ) + tagContent.value = Array.from(existingTagLines.keys()).join('\n') tagMessage.value = '' tagError.value = '' } From f6358dc6ba4e96a71ab7c5514c77fa2ab524bdfb Mon Sep 17 00:00:00 2001 From: davidzollo Date: Mon, 2 Nov 2026 11:07:58 -0500 Subject: [PATCH 16/19] [Fix][Zeta] Block tag updates for unrepresentable existing tags and document the exact REST error text - The worker tag editor serializes existing tags as key=value lines. Two legal tags such as a=b -> c and a -> b=c read the same, and a line break inside a key or value splits one entry into several lines, so saving the text could silently drop or alter existing placement tags. Selecting such a worker now shows an explanation and disables Update (re-checked in updateTags); Clear Tags stays available as an explicit full replacement. The server contract is unchanged. - The Jetty exception filter prefixes message with the exception class name; the update-local-member-tags error table and example (en, zh) now show the exact IllegalArgumentException: text that the integration tests assert. Co-Authored-By: Claude Sonnet 5.5 --- docs/en/engines/zeta/rest-api-v2.md | 14 +++++----- docs/zh/engines/zeta/rest-api-v2.md | 14 +++++----- .../src/locales/en_US/managers.ts | 2 ++ .../src/locales/zh_CN/managers.ts | 2 ++ .../src/tests/managers.spec.ts | 27 +++++++++++++++++++ .../src/views/managers/index.tsx | 27 +++++++++++++++---- 6 files changed, 67 insertions(+), 19 deletions(-) diff --git a/docs/en/engines/zeta/rest-api-v2.md b/docs/en/engines/zeta/rest-api-v2.md index 1d718731a292..0a05569b41ba 100644 --- a/docs/en/engines/zeta/rest-api-v2.md +++ b/docs/en/engines/zeta/rest-api-v2.md @@ -1498,20 +1498,20 @@ Clear every tag of the node: #### Request parameter exception -Each error is returned with HTTP status `400` and the following body. +Each error is returned with HTTP status `400`. The shared REST exception filter prefixes `message` with the exception class name, so the exact text is `IllegalArgumentException: `. | Condition | `message` | |--------------------------------------------------------------------|-----------------------------------------------------------------| -| The request body is empty | `Request body is empty.` | -| The request body is not a JSON object | `Invalid JSON format in request body.` | -| `uuid` is missing or does not match the node serving the request | `Target member uuid must match the REST node serving this request.` | -| `tags` is missing or is not a JSON object | `The tags field must be an object.` | -| Any value inside `tags` is not a string | `Tag values must be strings.` | +| The request body is empty | `IllegalArgumentException: Request body is empty.` | +| The request body is not a JSON object | `IllegalArgumentException: Invalid JSON format in request body.` | +| `uuid` is missing or does not match the node serving the request | `IllegalArgumentException: Target member uuid must match the REST node serving this request.` | +| `tags` is missing or is not a JSON object | `IllegalArgumentException: The tags field must be an object.` | +| Any value inside `tags` is not a string | `IllegalArgumentException: Tag values must be strings.` | ```json { "status": "fail", - "message": "Target member uuid must match the REST node serving this request." + "message": "IllegalArgumentException: Target member uuid must match the REST node serving this request." } ``` diff --git a/docs/zh/engines/zeta/rest-api-v2.md b/docs/zh/engines/zeta/rest-api-v2.md index d3b34fd56d89..9ed5909b56c4 100644 --- a/docs/zh/engines/zeta/rest-api-v2.md +++ b/docs/zh/engines/zeta/rest-api-v2.md @@ -1488,20 +1488,20 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload?restoreMode=CHECKPOINT& #### 请求参数异常 -以下错误均以 HTTP `400` 返回,响应体格式如下。 +以下错误均以 HTTP `400` 返回。REST 公共异常过滤器会在 `message` 前加上异常类名,因此实际文本为 `IllegalArgumentException: <说明>`。 | 场景 | `message` | |-------------------------------------|---------------------------------------------------------------------| -| 请求体为空 | `Request body is empty.` | -| 请求体不是 JSON 对象 | `Invalid JSON format in request body.` | -| 缺少 `uuid`,或 `uuid` 与响应请求的节点不一致 | `Target member uuid must match the REST node serving this request.` | -| 缺少 `tags`,或 `tags` 不是 JSON 对象 | `The tags field must be an object.` | -| `tags` 中存在非字符串值 | `Tag values must be strings.` | +| 请求体为空 | `IllegalArgumentException: Request body is empty.` | +| 请求体不是 JSON 对象 | `IllegalArgumentException: Invalid JSON format in request body.` | +| 缺少 `uuid`,或 `uuid` 与响应请求的节点不一致 | `IllegalArgumentException: Target member uuid must match the REST node serving this request.` | +| 缺少 `tags`,或 `tags` 不是 JSON 对象 | `IllegalArgumentException: The tags field must be an object.` | +| `tags` 中存在非字符串值 | `IllegalArgumentException: Tag values must be strings.` | ```json { "status": "fail", - "message": "Target member uuid must match the REST node serving this request." + "message": "IllegalArgumentException: Target member uuid must match the REST node serving this request." } ``` diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts index 81ed09c76194..4e3b53f6d88f 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts @@ -57,6 +57,8 @@ export default { invalid: 'Each tag line must use key=value.', contentRequired: 'Enter at least one tag, or use Clear Tags.', duplicate: 'Tag keys must be unique.', + unrepresentable: + 'This worker has tags that cannot be shown as unambiguous key=value lines (a line break, or two tags that read the same). Updating is disabled so no tag is lost; use Clear Tags to replace them all.', local: 'Local', remote: 'Remote', remoteHint: 'Open the target node Web UI to update this worker.', diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts index 3bb710e534a2..45b2f59952e3 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts @@ -56,6 +56,8 @@ export default { invalid: '每行 tag 必须使用 key=value 格式。', contentRequired: '请至少填写一个 Tag,或使用清空 Tags。', duplicate: 'Tag 键不能重复。', + unrepresentable: + '该 Worker 的部分 Tags 无法用无歧义的 key=value 行表示(包含换行,或两个 Tag 显示相同)。为避免丢失 Tag,已禁用更新;如需整体替换请使用清空 Tags。', local: '当前节点', remote: '远端节点', remoteHint: '请打开目标节点自己的 Web UI 更新该 Worker。', diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts index 8e07fda3fd48..510947077f63 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts @@ -258,6 +258,33 @@ describe('managers', () => { ['owner', 'team=data'] ]) }) + test.each([ + // ['a=b','c'] and ['a','b=c'] both read as "a=b=c"; one would be lost on save. + ['colliding pairs', { 'a=b': 'c', a: 'b=c' }], + // A line break inside a value would split one entry into two lines. + ['a line break in a value', { note: 'first\nsecond' }] + ])('blocks updating when existing tags are unrepresentable: %s', async (_name, tags) => { + vi.mocked(managerService.getMonitors).mockResolvedValue([ + { ...monitor(), uuid: 'worker-1', localMember: true, tags } + ]) + const { wrapper } = await setup() + await flushPromises() + await wrapper + .findAllComponents(NButton) + .find((button) => button.text() === 'Select')! + .trigger('click') + expect(wrapper.text()).toContain('cannot be shown as unambiguous key=value lines') + const updateButton = wrapper + .findAllComponents(NButton) + .find((button) => button.text() === 'Update Tags')! + expect(updateButton.props('disabled')).toBe(true) + const onPositiveClick = wrapper.findAllComponents(NPopconfirm)[1].props('onPositiveClick') as ( + event: MouseEvent + ) => Promise + await onPositiveClick(new MouseEvent('click')) + await flushPromises() + expect(managerService.updateTags).not.toHaveBeenCalled() + }) test('rejects duplicate tag keys before calling the server', async () => { vi.mocked(managerService.getMonitors).mockResolvedValue([ { ...monitor(), uuid: 'worker-1', localMember: true, tags: {} } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx index c59a96662fc0..25ab95ac1b45 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx @@ -67,6 +67,11 @@ export default defineComponent({ // whitespace. Each entry is remembered under the exact line it was serialized to, so a line // the operator did not touch is sent back as the original pair instead of being re-parsed. let existingTagLines = new Map() + // True when an existing tag cannot be shown as one unambiguous key=value line (a line break in + // a key or value, or two entries that serialize to the same line). Updating is blocked then, + // because the server replaces the whole map and saving the text would silently drop or alter + // entries; Clear Tags stays available because it is an explicit full replacement. + const tagEditBlocked = ref(false) let timer: ReturnType | undefined let generation = 0 let disposed = false @@ -135,6 +140,7 @@ export default defineComponent({ rows.value = [] selectedAddress.value = undefined selectedMonitor.value = null + tagEditBlocked.value = false tagContent.value = '' tagMessage.value = '' tagError.value = '' @@ -202,6 +208,10 @@ export default defineComponent({ tagError.value = t('managers.tagEditor.workerRequired') return } + if (!clear && tagEditBlocked.value) { + tagError.value = t('managers.tagEditor.unrepresentable') + return + } if (!clear && !tagContent.value.trim()) { tagError.value = t('managers.tagEditor.contentRequired') return @@ -236,15 +246,19 @@ export default defineComponent({ const selectMonitor = (monitor: Monitor) => { selectedMonitor.value = monitor + const entries = Object.entries(monitor.tags || {}) + const lines = entries.map(([key, value]) => `${key}=${value}`) existingTagLines = new Map( - Object.entries(monitor.tags || {}).map(([key, value]): [string, [string, string]] => [ - `${key}=${value}`, + entries.map(([key, value], index): [string, [string, string]] => [ + lines[index], [key, value] ]) ) - tagContent.value = Array.from(existingTagLines.keys()).join('\n') + tagEditBlocked.value = + existingTagLines.size !== entries.length || lines.some((line) => /[\r\n]/.test(line)) + tagContent.value = lines.join('\n') tagMessage.value = '' - tagError.value = '' + tagError.value = tagEditBlocked.value ? t('managers.tagEditor.unrepresentable') : '' } const formatTags = (tags?: Record) => { @@ -458,7 +472,10 @@ export default defineComponent({ type="primary" loading={tagLoading.value} disabled={ - !selectedMonitor.value || !tagContent.value.trim() || tagLoading.value + !selectedMonitor.value || + !tagContent.value.trim() || + tagEditBlocked.value || + tagLoading.value } > {t('managers.tagEditor.update')} From d284cb5aa851e16ba19b4b8710caf5fb46fab18a Mon Sep 17 00:00:00 2001 From: davidzollo Date: Mon, 9 Nov 2026 23:29:04 -0500 Subject: [PATCH 17/19] [Improve][Zeta] Lift the tag-edit block after Clear Tags and document Web UI access control - Web UI: after a successful Clear Tags on a worker whose existing tags were unrepresentable, reset the block and the line cache so newly typed tags can be saved without re-selecting the worker. The unrepresentable-tags test now continues with clear-then-type and asserts the typed tag is sent. - UpdateTagsService: the audit log records tag counts only, because tag content is arbitrary operator input; the comment now says so and the previous map is no longer copied just to count it. - web-ui.md (en, zh): note that the state-changing controls are protected only by the node's REST authentication, which the packaged config leaves off, and link the security page. Co-Authored-By: Claude Fable 5.1 --- docs/en/engines/zeta/web-ui.md | 2 ++ docs/zh/engines/zeta/web-ui.md | 2 ++ .../server/rest/service/UpdateTagsService.java | 16 ++++++++++------ .../src/tests/managers.spec.ts | 16 ++++++++++++++++ .../src/views/managers/index.tsx | 4 ++++ 5 files changed, 34 insertions(+), 6 deletions(-) diff --git a/docs/en/engines/zeta/web-ui.md b/docs/en/engines/zeta/web-ui.md index 577f166e299b..c0702a8b19a5 100644 --- a/docs/en/engines/zeta/web-ui.md +++ b/docs/en/engines/zeta/web-ui.md @@ -46,6 +46,8 @@ part of the redirect target. The Web UI of Apache SeaTunnel is a visual inspection console for SeaTunnel Engine. It helps operators view cluster overview data, running and finished jobs, job detail pages, logs, realtime DAG metrics, and the status of worker and master nodes. The Web UI combines visual inspection with common operational actions. It supports job submission and restore flows, plus confirmed cancel, stop, and savepoint controls for running jobs. Use the REST API or CLI for automation and workflows not exposed by the UI. + +**Access control.** The state-changing controls (submit, restore, stop, savepoint, cancel, worker tag updates) call the same REST endpoints as the CLI and are protected only by the REST authentication configured on the node. The packaged `config/seatunnel.yaml` enables HTTP without authentication, so anyone who can reach the REST port can trigger these actions from a browser. Enable `enable-basic-auth` and HTTPS (optionally with client certificates) as described in [Security](./security.md) before exposing the Web UI beyond a trusted network. ![overview.png](../../../images/ui/overview.png) ## Capability Summary diff --git a/docs/zh/engines/zeta/web-ui.md b/docs/zh/engines/zeta/web-ui.md index 5bf1cc89bcd3..7dded354eba2 100644 --- a/docs/zh/engines/zeta/web-ui.md +++ b/docs/zh/engines/zeta/web-ui.md @@ -44,6 +44,8 @@ Markdown 预览也有同样行为——`/#/overview` 于是变成 `/%23/overview Apache SeaTunnel 的 Web UI 是 SeaTunnel Engine 的可视化巡检控制台。它可以帮助运维人员查看集群概览、运行中和已完成作业、作业详情页、日志、实时 DAG 指标,以及 worker 和 master 节点状态。 Web UI 在可视化巡检之外,也提供常用运维操作:可以提交和恢复作业,并为运行中作业提供需要确认的 cancel、stop 和 savepoint 控件。自动化场景或 UI 未暴露的工作流仍请使用 REST API 或命令行。 + +**访问控制。** 会改变状态的控件(提交、恢复、stop、savepoint、cancel、Worker tag 更新)调用的是与命令行相同的 REST 接口,仅受节点上配置的 REST 认证保护。安装包自带的 `config/seatunnel.yaml` 默认开启 HTTP 且未启用认证,因此任何能访问 REST 端口的人都可以在浏览器中触发这些操作。在把 Web UI 暴露到可信网络之外之前,请按照 [安全](./security.md) 启用 `enable-basic-auth` 和 HTTPS(可选客户端证书)。 ![overview.png](../../../images/ui/overview.png) ## 能力总览 diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java index 7ea82804ae94..4bf72359eb87 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/UpdateTagsService.java @@ -25,7 +25,6 @@ import com.hazelcast.spi.impl.NodeEngineImpl; import lombok.extern.slf4j.Slf4j; -import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; @@ -67,14 +66,15 @@ private MemberImpl getLocalMember() { private JsonObject updateTags(Map tagParams, MemberImpl localMember) { Map tags = toStringTags(tagParams); - // Read before the change, because updateAttribute replaces the whole tag set: without this - // copy the tags a job was scheduled against are gone with no record of what they were. - Map previousTags = new HashMap<>(localMember.getAttributes()); + // updateAttribute replaces the whole tag set, so the previous size is read first. Only + // counts are logged on purpose: tag keys and values are arbitrary operator input and may + // carry secrets, so their content must never reach the server log. + int previousTagCount = localMember.getAttributes().size(); localMember.updateAttribute(tags); log.info( "Node tags updated: node={}, previousTags={}, tags={}", localMember.getAddress(), - summarizeTagsForAudit(previousTags), + summarizeTagCountForAudit(previousTagCount), summarizeTagsForAudit(tags)); return new JsonObject().add("status", "success").add("message", "update node tags done."); } @@ -142,6 +142,10 @@ static Map toStringTags(Map tagParams) { * @return the number of tags without any tag content. */ static String summarizeTagsForAudit(Map tags) { - return tags.size() + " tag(s)"; + return summarizeTagCountForAudit(tags.size()); + } + + private static String summarizeTagCountForAudit(int tagCount) { + return tagCount + " tag(s)"; } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts index 510947077f63..952d1e3f02ed 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/managers.spec.ts @@ -284,6 +284,22 @@ describe('managers', () => { await onPositiveClick(new MouseEvent('click')) await flushPromises() expect(managerService.updateTags).not.toHaveBeenCalled() + // Clear Tags is the explicit way out: after it succeeds the block must be lifted so newly + // typed tags can be saved without selecting the worker again. + const onClearClick = wrapper.findAllComponents(NPopconfirm)[0].props('onPositiveClick') as ( + event: MouseEvent + ) => Promise + await onClearClick(new MouseEvent('click')) + await flushPromises() + expect(managerService.updateTags).toHaveBeenLastCalledWith({ uuid: 'worker-1', tags: {} }) + await wrapper.find('textarea').setValue('zone=prod') + expect(updateButton.props('disabled')).toBe(false) + await onPositiveClick(new MouseEvent('click')) + await flushPromises() + expect(managerService.updateTags).toHaveBeenLastCalledWith({ + uuid: 'worker-1', + tags: { zone: 'prod' } + }) }) test('rejects duplicate tag keys before calling the server', async () => { vi.mocked(managerService.getMonitors).mockResolvedValue([ diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx index 25ab95ac1b45..a5cdf54fade5 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/managers/index.tsx @@ -231,7 +231,11 @@ export default defineComponent({ tags }) if (clear) { + // The worker now has no tags, so nothing is unrepresentable any more and new lines + // typed into the empty editor must be parseable and savable without re-selecting. tagContent.value = '' + existingTagLines = new Map() + tagEditBlocked.value = false } tagMessage.value = t('managers.tagEditor.success') await refreshAfterTagUpdate() From bb0165d59b751dedf2f480adc2fc3a196b884fbb Mon Sep 17 00:00:00 2001 From: DanielLeens <48329107+DanielLeens@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:41:22 -0500 Subject: [PATCH 18/19] [Test][E2E] Use an available SFTP test image Reuse the single-line test fixture update merged in apache/seatunnel#13203. --- .../apache/seatunnel/e2e/connector/file/fstp/SftpFileIT.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-file-sftp-e2e/src/test/java/org/apache/seatunnel/e2e/connector/file/fstp/SftpFileIT.java b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-file-sftp-e2e/src/test/java/org/apache/seatunnel/e2e/connector/file/fstp/SftpFileIT.java index 113e0a590b00..77f41a17c4da 100644 --- a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-file-sftp-e2e/src/test/java/org/apache/seatunnel/e2e/connector/file/fstp/SftpFileIT.java +++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-file-sftp-e2e/src/test/java/org/apache/seatunnel/e2e/connector/file/fstp/SftpFileIT.java @@ -67,7 +67,7 @@ @Slf4j public class SftpFileIT extends TestSuiteBase implements TestResource { - private static final String SFTP_IMAGE = "atmoz/sftp:alpine-3.7"; + private static final String SFTP_IMAGE = "atmoz/sftp:alpine"; private static final String SFTP_CONTAINER_HOST = "sftp"; From 997bfc38696c4ef0f6d1a003343c70866ae447b4 Mon Sep 17 00:00:00 2001 From: DanielLeens <48329107+DanielLeens@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:00:40 -0500 Subject: [PATCH 19/19] [Fix][Zeta] Guard operations REST and batch restore --- docs/en/engines/zeta/rest-api-v2.md | 17 +++- docs/en/engines/zeta/web-ui.md | 4 + docs/zh/engines/zeta/rest-api-v2.md | 17 +++- docs/zh/engines/zeta/web-ui.md | 3 + .../seatunnel/engine/e2e/RestApiIT.java | 16 ++- .../rest/RestHttpPostCommandProcessor.java | 9 -- .../server/rest/service/JobInfoService.java | 98 ++++++++++++------- ...estApiSubmitJobStartWithSavePointTest.java | 74 ++++++++++++++ .../JobInfoServiceRestoreGuardTest.java | 54 ++++++++++ .../src/locales/en_US/managers.ts | 3 +- .../src/locales/zh_CN/managers.ts | 2 +- 11 files changed, 236 insertions(+), 61 deletions(-) diff --git a/docs/en/engines/zeta/rest-api-v2.md b/docs/en/engines/zeta/rest-api-v2.md index c98a192a8978..d884864f1dd3 100644 --- a/docs/en/engines/zeta/rest-api-v2.md +++ b/docs/en/engines/zeta/rest-api-v2.md @@ -917,6 +917,9 @@ starting beyond the end of the result set also returns `400`, while a page start ```json [ { + "uuid":"4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", + "localMember":true, + "tags":{"node":"worker-1"}, "processors":"8", "physical.memory.total":"16.0G", "physical.memory.free":"16.3M", @@ -966,7 +969,7 @@ starting beyond the end of the result set also returns `400`, while a page start ] ``` -Each member is asked in parallel and awaited against one shared deadline (`seatunnel.engine.health-metrics-timeout-seconds`, default `3` seconds). A member that does not answer in time is reported as `{"host": "10.0.0.1", "port": 5801, "error": "timeout"}`; members whose request dispatch or response fails are reported with the corresponding `error` marker. +Each member is asked in parallel and awaited against one shared deadline (`seatunnel.engine.health-metrics-timeout-seconds`, default `3` seconds). Every known member entry includes `uuid`, `localMember`, and its current string-valued `tags`, including entries with an `error` marker. A timeout entry also includes `host`, `port`, and `error: "timeout"`; dispatch and response failures carry the corresponding `error` marker. Tags are visible to anyone who can read this endpoint, including the member listener when enabled. Use tags only for non-secret scheduling metadata; never put credentials or tokens in them.

@@ -1172,6 +1175,10 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload?restoreMode=CHECKPOINT& > | jobId | optional | string | job id | > | jobName | optional | string | job name | > | isStartWithSavePoint | optional | string | if the job is started with save point | +> | restoreMode | optional | string | `NONE`, `SAVEPOINT`, or `CHECKPOINT` | +> | restoreSourceJobId | conditional | string | numeric source job ID; required for `CHECKPOINT`, or use `jobId` for `SAVEPOINT` | + +The server preflights job IDs, restore parameters and source status, dry-run and legacy savepoint requirements, and config decryption for the whole batch before submitting any job. A failure in this preflight leaves all jobs unsubmitted. Submission itself is not transactional: a later config or runtime failure may leave earlier jobs running. A source-status lookup failure returns `500` with a retry message; an active restore source returns `400`. #### Request Body @@ -1436,6 +1443,8 @@ For more information about customize encryption, please refer to the documentati ##### Body `/update-tags` keeps the legacy flat `Map` contract: every top-level key is a tag name and every value is that tag's value. String values are recommended; for compatibility, the server converts non-string values to strings (and null to an empty string) rather than rejecting them. Nested objects are converted using Java's map representation, not retained as objects. No key is reserved, so a key literally named `uuid` or `tags` is stored as an ordinary tag instead of being read as a target member or a nested tag map. The request always applies to the REST node that serves it; to target a specific node, send the request to that node's own REST address. +The legacy endpoint also remains available on the Hazelcast member REST listener, which does not inherit Jetty Basic Auth or mutual TLS. Restrict member-port access to trusted clients. Tag updates replace the entire map; concurrent edits may be overwritten. + ```json { "tag1": "dev_1", @@ -1496,7 +1505,7 @@ This is the endpoint the Web UI Workers page uses. It is additive: `/update-tags #### Authentication -`/update-local-member-tags` is registered on the same servlet context as every other REST endpoint, so it is protected by the same basic authentication and mutual TLS configuration. No separate credentials or settings apply. +`/update-local-member-tags` is available only on the Jetty HTTP listener and uses its configured Basic Auth and mutual TLS settings. It is not available on the Hazelcast member REST listener. The legacy `/update-tags` route remains available there; restrict member-port access to trusted clients. #### Body @@ -1505,6 +1514,8 @@ This is the endpoint the Web UI Workers page uses. It is additive: `/update-tags | `uuid` | yes | string | Member UUID of the node that must serve this request. Read it from `/system-monitoring-information`, whose entries carry `uuid` and `localMember` for every cluster member. | | `tags` | yes | object | Tag name to string value map that replaces the node's current tags. An empty object clears all tags. Non-string values are rejected. | +This is a whole-map, last-write-wins replacement. Re-read the member's current tags before editing; another writer's changes since that read may be overwritten. + ```json { "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", @@ -2158,7 +2169,7 @@ There is no dedicated `pause`, `resume` or `delete` endpoint. Use the existing j | Resume a paused job | Call [`/submit-job`](#submit-a-job) again with `restoreMode=SAVEPOINT`, `restoreSourceJobId=`, and the same job config. The job restores from its latest savepoint for that source job. The legacy `isStartWithSavePoint: true` with the same `jobId` remains supported. | | Delete a job | There is no delete endpoint. Stop the job with [`/stop-job`](#stop-a-job) if it is still running. Once a job reaches a finished state, its record is removed automatically after `history-job-expire-minutes` (default 1440 minutes) elapses -- see [History Job Expiry Configuration](separated-cluster-deployment.md#44-history-job-expiry-configuration). | -**Note:** `restoreMode` requires `restoreSourceJobId`. `isStartWithSavePoint: true` remains a legacy +**Note:** `CHECKPOINT` requires `restoreSourceJobId`; `SAVEPOINT` may use `jobId` when `restoreSourceJobId` is omitted. `isStartWithSavePoint: true` remains a legacy shortcut and requires `jobId` to be provided in the request; submitting without a `jobId` in that case fails with `Please provide jobId when start with save point.` diff --git a/docs/en/engines/zeta/web-ui.md b/docs/en/engines/zeta/web-ui.md index c0702a8b19a5..013c4265a07d 100644 --- a/docs/en/engines/zeta/web-ui.md +++ b/docs/en/engines/zeta/web-ui.md @@ -168,6 +168,10 @@ tags into the **Worker Tags** panel above the table, edit one `key=value` tag pe is rejected unless the Web UI is served by the member being updated. Remote workers are shown for inspection only; open the target node's own Web UI address to change its tags. +Updating replaces the entire tag map. Refresh before editing: changes made by another operator +since selecting the worker may be overwritten. Tags are visible through the system-monitoring API, +so use only non-secret scheduling metadata. + **Limitation:** if the Web UI is reached through a load balancer or reverse proxy that fronts several masters, only the member that happens to serve the request is editable, and tag updates for every other member are rejected. Reach the target member directly when editing tags. diff --git a/docs/zh/engines/zeta/rest-api-v2.md b/docs/zh/engines/zeta/rest-api-v2.md index 914850fe3732..71bf9bb3842d 100644 --- a/docs/zh/engines/zeta/rest-api-v2.md +++ b/docs/zh/engines/zeta/rest-api-v2.md @@ -900,6 +900,9 @@ seatunnel: ```json [ { + "uuid":"4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", + "localMember":true, + "tags":{"node":"worker-1"}, "processors":"8", "physical.memory.total":"16.0G", "physical.memory.free":"16.3M", @@ -949,7 +952,7 @@ seatunnel: ] ``` -每个成员的请求会被并行发出,并共享一个统一截止时间(`seatunnel.engine.health-metrics-timeout-seconds`,默认 `3` 秒)。在截止时间内未应答的成员会以 `{"host": "10.0.0.1", "port": 5801, "error": "timeout"}` 的形式返回;请求分发或响应失败时也会带有对应的 `error` 标记。 +每个成员的请求会被并行发出,并共享一个统一截止时间(`seatunnel.engine.health-metrics-timeout-seconds`,默认 `3` 秒)。每个已知成员的条目均包含 `uuid`、`localMember` 和当前的字符串型 `tags`,包括带 `error` 的条目。超时条目还包含 `host`、`port` 和 `error: "timeout"`;分发或响应失败也会带有对应的 `error` 标记。任何能读取该接口的人(包括启用成员 REST 监听时能访问该端口的人)都能看到 tags。tags 只能用于非敏感的调度元数据,不能存放凭据或令牌。 @@ -1155,6 +1158,10 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload?restoreMode=CHECKPOINT& > | jobId | optional | string | job id | > | jobName | optional | string | job name | > | isStartWithSavePoint | optional | string | if job is started with save point | +> | restoreMode | 可选 | string | `NONE`、`SAVEPOINT` 或 `CHECKPOINT` | +> | restoreSourceJobId | 条件必填 | string | 数字型来源作业 ID;`CHECKPOINT` 时必填,`SAVEPOINT` 可使用 `jobId` | + +服务端会在提交任何作业前,预检整个批次的作业 ID、恢复参数及来源状态、dry-run 与旧版 savepoint 要求,并解密配置。这一预检失败时不会提交作业。但提交阶段不是事务:后续作业的配置或运行时故障可能导致前面的作业已运行。来源作业状态查询失败时返回带重试提示的 `500`;来源作业仍在运行时返回 `400`。 @@ -1423,6 +1430,8 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload?restoreMode=CHECKPOINT& ##### 请求体 `/update-tags` 保留旧版扁平 `Map` 契约:每个顶层 key 都是 tag 名,对应的 value 就是该 tag 的值。建议使用字符串值;为保持兼容,服务端会把非字符串值转换为字符串(null 转为空字符串),不会拒绝。嵌套对象会转换为 Java map 的字符串表示形式,不会作为对象保存。该接口不保留任何特殊 key,因此名为 `uuid` 或 `tags` 的 key 也只会作为普通 tag 存储,不会被解释为目标成员或嵌套的 tag map。请求始终作用于响应该请求的 REST 节点;如需更新指定节点,请把请求发送到该节点自己的 REST 地址。 +旧版接口仍可通过 Hazelcast 成员 REST 监听端口访问,该端口不继承 Jetty 的 Basic Auth 或双向 TLS;必须把成员端口限制在可信客户端范围内。tag 更新会整体替换现有映射,并发修改可能被覆盖。 + ```json { "tag1": "dev_1", @@ -1483,7 +1492,7 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload?restoreMode=CHECKPOINT& #### 认证 -`/update-local-member-tags` 与其他所有 REST 接口注册在同一个 servlet context 上,因此受相同的 basic 认证和双向 TLS 配置保护,不需要额外的凭据或配置。 +`/update-local-member-tags` 只在 Jetty HTTP 监听端口开放,受该端口配置的 Basic Auth 和双向 TLS 保护;Hazelcast 成员 REST 端口不提供此接口。旧版 `/update-tags` 仍可通过成员端口访问,因此必须限制该端口只允许可信客户端访问。 #### 请求体 @@ -1492,6 +1501,8 @@ curl --location 'http://127.0.0.1:8080/submit-job/upload?restoreMode=CHECKPOINT& | `uuid` | 是 | 字符串 | 必须响应本次请求的节点的成员 UUID。可从 `/system-monitoring-information` 获取,其返回的每个集群成员都带有 `uuid` 和 `localMember` 字段。 | | `tags` | 是 | 对象 | tag 名到字符串值的映射,会整体替换该节点当前的 tags。空对象表示清空全部 tags;非字符串值会被拒绝。 | +这是整个映射的后写覆盖操作。编辑前请重新读取当前 tags;读取后其他人的修改可能会被覆盖。 + ```json { "uuid": "4f1c8c53-8d9f-4f5c-b9cc-278f3bbd2d2a", @@ -2135,7 +2146,7 @@ Checkpoint 信息字段: | 恢复一个已暂停的作业 | 再次调用 [`/submit-job`](#提交作业),设置 `restoreMode=SAVEPOINT`、`restoreSourceJobId=` 并传入相同的作业配置。作业会基于该来源作业最近一次的 savepoint 恢复。仍支持使用相同 `jobId` 加 `isStartWithSavePoint: true` 的旧契约。 | | 删除一个作业 | 没有专门的删除接口。如果作业仍在运行,先通过 [`/stop-job`](#停止作业) 停止它;作业进入结束状态后,其记录会在 `history-job-expire-minutes`(默认 1440 分钟)到期后自动清理,参见[历史作业过期配置](separated-cluster-deployment.md#44-历史作业过期配置)。 | -**注意:** 设置 `restoreMode` 时必须提供 `restoreSourceJobId`。`isStartWithSavePoint: true` 仍是旧的快捷方式,必须提供 `jobId`;不提供 `jobId` 会导致请求失败,报错信息为 +**注意:** `CHECKPOINT` 必须提供 `restoreSourceJobId`;`SAVEPOINT` 省略此参数时可使用 `jobId`。`isStartWithSavePoint: true` 仍是旧的快捷方式,必须提供 `jobId`;不提供 `jobId` 会导致请求失败,报错信息为 `Please provide jobId when start with save point.` **恢复保护:** 当来源作业尚未进入结束状态(`FINISHED`、`FAILED`、`CANCELED` 或 `SAVEPOINT_DONE`)时,带 `restoreMode` 的提交会以 HTTP `400` 被拒绝,例如 diff --git a/docs/zh/engines/zeta/web-ui.md b/docs/zh/engines/zeta/web-ui.md index 7dded354eba2..73e32e7aa579 100644 --- a/docs/zh/engines/zeta/web-ui.md +++ b/docs/zh/engines/zeta/web-ui.md @@ -156,6 +156,9 @@ Workers 页面还可以更新本地 worker(即响应当前 Web UI 请求的那 UUID,因此只有当 Web UI 正是由被更新的成员提供服务时请求才会被接受。远端 worker 仅用于查看; 如需修改某个目标节点的 tags,请访问该节点自己的 Web UI 地址。 +更新会整体替换 tag 映射。编辑前请刷新;选择节点后其他人修改的 tags 可能会被覆盖。tags 会通过系统监控接口公开, +只可用于非敏感的调度元数据。 + **限制:** 如果通过负载均衡或反向代理访问 Web UI,且其后端有多个 master,那么只有实际响应本次 请求的成员可以编辑,对其他成员的 tag 更新都会被拒绝。编辑 tags 时请直接访问目标成员。 diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java index 5f64d907c6f0..a6d0a4d48f54 100644 --- a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java +++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/RestApiIT.java @@ -80,6 +80,7 @@ import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; @Slf4j @@ -1090,8 +1091,8 @@ public void testHttpServiceStatusReportsEffectivePortsWithoutSecrets() { /** * The target-validated tag endpoint only mutates the member serving the request: a foreign UUID - * is rejected without side effects, the serving member's UUID applies the tags on both the - * Jetty and the legacy Hazelcast REST port, and an empty map clears them. + * is rejected without side effects, the serving member's UUID applies the tags only on the + * Jetty port, and an empty map clears them. */ @Test public void testUpdateLocalMemberTagsOnlyMutatesTheServingMember() { @@ -1168,23 +1169,18 @@ public void testUpdateLocalMemberTagsOnlyMutatesTheServingMember() { given().body(tagRequest(localUuid, "{\"zone\": \"legacy-port\"}")) .post(hazelcastBase + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) .then() - .statusCode(200) - .body("message", equalTo("update node tags done.")); - given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?zone=legacy-port") - .then() - .statusCode(200) - .body("workers", equalTo("1")); + .statusCode(not(equalTo(200))); given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?zone=prod") .then() .statusCode(200) - .body("workers", equalTo("0")); + .body("workers", equalTo("1")); given().body(tagRequest(localUuid, "{}")) .post(jettyBase + RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS) .then() .statusCode(200) .body("message", equalTo("update node tags done.")); - given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?zone=legacy-port") + given().get(jettyBase + RestConstant.REST_URL_OVERVIEW + "?zone=prod") .then() .statusCode(200) .body("workers", equalTo("0")); diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/RestHttpPostCommandProcessor.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/RestHttpPostCommandProcessor.java index e6cfc8837fbd..0418b53995b5 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/RestHttpPostCommandProcessor.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/RestHttpPostCommandProcessor.java @@ -39,7 +39,6 @@ import static org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_STOP_JOBS; import static org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_SUBMIT_JOB; import static org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_SUBMIT_JOBS; -import static org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_UPDATE_LOCAL_MEMBER_TAGS; import static org.apache.seatunnel.engine.server.rest.RestConstant.REST_URL_UPDATE_TAGS; @Slf4j @@ -87,8 +86,6 @@ public void handle(HttpPostCommand httpPostCommand) { handleStopJob(httpPostCommand); } else if (uri.startsWith(CONTEXT_PATH + REST_URL_ENCRYPT_CONFIG)) { handleEncrypt(httpPostCommand); - } else if (uri.startsWith(CONTEXT_PATH + REST_URL_UPDATE_LOCAL_MEMBER_TAGS)) { - handleUpdateLocalMemberTags(httpPostCommand); } else if (uri.startsWith(CONTEXT_PATH + REST_URL_UPDATE_TAGS)) { handleUpdateTags(httpPostCommand); } else { @@ -136,12 +133,6 @@ private void handleUpdateTags(HttpPostCommand httpPostCommand) { httpPostCommand, updateTagsService.updateTags(httpPostCommand.getData())); } - private void handleUpdateLocalMemberTags(HttpPostCommand httpPostCommand) { - this.prepareResponse( - httpPostCommand, - updateTagsService.updateLocalMemberTags(httpPostCommand.getData())); - } - @Override public void handleRejection(HttpPostCommand httpPostCommand) { handle(httpPostCommand); diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java index b72f8cc74bd9..c3d6dbe5e713 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java @@ -449,16 +449,7 @@ public JsonArray stopJobs(byte[] requestBody) { } public JsonObject submitJob(Map requestParams, byte[] requestBody) { - - if (requestParams.containsKey(RestConstant.DRY_RUN) - && requestParams.get(RestConstant.DRY_RUN) != null) { - throw new IllegalArgumentException("Dry-run is only supported via CLI"); - } - if (Boolean.parseBoolean(requestParams.get(RestConstant.IS_START_WITH_SAVE_POINT)) - && StringUtils.isBlank(requestParams.get(RestConstant.JOB_ID))) { - throw new IllegalArgumentException("Please provide jobId when start with save point."); - } - validateCheckpointRestoreRequest(requestParams); + validateSubmitRequestParams(requestParams); Config config; ConfigFormat configFormat = ConfigFormat.fromString(requestParams.get(CONFIG_FORMAT)); @@ -483,6 +474,12 @@ public JsonObject submitJob(Map requestParams, byte[] requestBod } public JsonObject submitJob(Map requestParams, Config config) { + validateSubmitRequestParams(requestParams); + SeaTunnelServer seaTunnelServer = getSeaTunnelServer(false); + return submitJobInternal(config, requestParams, seaTunnelServer, nodeEngine.getNode()); + } + + private void validateSubmitRequestParams(Map requestParams) { if (requestParams.containsKey(RestConstant.DRY_RUN) && requestParams.get(RestConstant.DRY_RUN) != null) { throw new IllegalArgumentException("Dry-run is only supported via CLI"); @@ -491,40 +488,51 @@ public JsonObject submitJob(Map requestParams, Config config) { && StringUtils.isBlank(requestParams.get(RestConstant.JOB_ID))) { throw new IllegalArgumentException("Please provide jobId when start with save point."); } + for (String idKey : + new String[] {RestConstant.JOB_ID, RestConstant.RESTORE_SOURCE_JOB_ID}) { + String value = requestParams.get(idKey); + if (StringUtils.isNotBlank(value)) { + try { + Long.parseLong(value); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(idKey + " must be a numeric job id.", e); + } + } + } validateCheckpointRestoreRequest(requestParams); - SeaTunnelServer seaTunnelServer = getSeaTunnelServer(false); - return submitJobInternal(config, requestParams, seaTunnelServer, nodeEngine.getNode()); } public JsonArray submitJobs(byte[] requestBody) { List, Config>> configTuples = RestUtil.buildConfigList(requestHandle(requestBody)); - return configTuples.stream() + List, Config>> validatedJobs = + configTuples.stream() + .map( + tuple -> { + String urlParams = mapToUrlParams(tuple._1); + Map requestParams = new HashMap<>(); + RestUtil.buildRequestParams(requestParams, urlParams); + validateSubmitRequestParams(requestParams); + return new Tuple2<>( + requestParams, + ConfigShadeUtils.decryptConfig(tuple._2)); + }) + .collect(Collectors.toList()); + + return validatedJobs.stream() .map( tuple -> { - String urlParams = mapToUrlParams(tuple._1); - Map requestParams = new HashMap<>(); - RestUtil.buildRequestParams(requestParams, urlParams); - if (requestParams.containsKey(RestConstant.DRY_RUN) - && requestParams.get(RestConstant.DRY_RUN) != null) { - throw new IllegalArgumentException( - "Dry-run is only supported via CLI"); - } - validateCheckpointRestoreRequest(requestParams); SeaTunnelServer seaTunnelServer = getSeaTunnelServer(false); - Config decryptConfig = ConfigShadeUtils.decryptConfig(tuple._2); return submitJobInternal( - decryptConfig, - requestParams, - seaTunnelServer, - nodeEngine.getNode()); + tuple._2, tuple._1, seaTunnelServer, nodeEngine.getNode()); }) .collect(JsonArray::new, JsonArray::add, JsonArray::add); } /** - * Validates the explicit restore parameters before parsing the submitted job configuration. + * Validates explicit and legacy restore parameters before parsing the submitted job + * configuration. * *

A blank source ID is equivalent to an omitted source ID. Rejecting it here prevents the * restore path from issuing a lookup for a null source after configuration parsing begins. The @@ -535,14 +543,27 @@ public JsonArray submitJobs(byte[] requestBody) { */ private void validateCheckpointRestoreRequest(Map requestParams) { String restoreModeValue = requestParams.get(RestConstant.RESTORE_MODE); - RestoreMode restoreMode = - restoreModeValue == null || restoreModeValue.trim().isEmpty() - ? RestoreMode.NONE - : RestoreMode.valueOf(restoreModeValue.trim().toUpperCase(Locale.ROOT)); + RestoreMode restoreMode; + try { + restoreMode = + restoreModeValue == null || restoreModeValue.trim().isEmpty() + ? (Boolean.parseBoolean( + requestParams.get( + RestConstant.IS_START_WITH_SAVE_POINT)) + ? RestoreMode.SAVEPOINT + : RestoreMode.NONE) + : RestoreMode.valueOf(restoreModeValue.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException( + "restoreMode must be one of NONE, SAVEPOINT, CHECKPOINT.", e); + } if (!restoreMode.isRestore()) { return; } String restoreSourceJobIdValue = requestParams.get(RestConstant.RESTORE_SOURCE_JOB_ID); + if (restoreMode == RestoreMode.SAVEPOINT && StringUtils.isBlank(restoreSourceJobIdValue)) { + restoreSourceJobIdValue = requestParams.get(RestConstant.JOB_ID); + } if (restoreSourceJobIdValue == null || restoreSourceJobIdValue.trim().isEmpty()) { throw new IllegalArgumentException( "restoreSourceJobId is required when restoreMode=" + restoreMode); @@ -557,8 +578,17 @@ private void validateCheckpointRestoreRequest(Map requestParams) "restoreSourceJobId must be a numeric job id, got: " + restoreSourceJobIdValue, e); } - rejectRestoreFromActiveSourceJob( - restoreMode, restoreSourceJobId, getRestoreSourceJobStatus(restoreSourceJobId)); + JobStatus sourceJobStatus; + try { + sourceJobStatus = getRestoreSourceJobStatus(restoreSourceJobId); + } catch (RuntimeException e) { + throw new IllegalStateException( + "Unable to verify restoreSourceJobId=" + + restoreSourceJobId + + " status; retry when the cluster is healthy.", + e); + } + rejectRestoreFromActiveSourceJob(restoreMode, restoreSourceJobId, sourceJobStatus); } /** diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java index 28e0f7514a8d..1f0cbca496ac 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java +++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/RestApiSubmitJobStartWithSavePointTest.java @@ -54,6 +54,8 @@ import com.hazelcast.config.Config; import com.hazelcast.instance.impl.HazelcastInstanceImpl; import com.hazelcast.internal.json.Json; +import com.hazelcast.internal.json.JsonArray; +import com.hazelcast.internal.json.JsonObject; import java.io.BufferedReader; import java.io.IOException; @@ -302,6 +304,23 @@ public void testSubmitCheckpointRestoreFromActiveSourceJobReturns400() throws Ex refused.body.contains( "restoreSourceJobId=" + sourceJobId + " is still RUNNING"), () -> "responseBody=" + refused.body); + + for (String savepointParams : + new String[] { + "restoreMode=SAVEPOINT&jobId=" + sourceJobId, + "isStartWithSavePoint=true&jobId=" + sourceJobId + }) { + HttpResponse savepointRefused = + postJson( + base + "/submit-job?format=json&" + savepointParams, + getRequestBody()); + Assertions.assertEquals( + 400, savepointRefused.code, () -> "responseBody=" + savepointRefused.body); + Assertions.assertTrue( + savepointRefused.body.contains( + "restoreSourceJobId=" + sourceJobId + " is still RUNNING"), + () -> "responseBody=" + savepointRefused.body); + } } finally { postJson(base + "/stop-job", "{\"jobId\": " + sourceJobId + "}"); } @@ -333,6 +352,61 @@ public void testSubmitCheckpointRestoreFromActiveSourceJobReturns400() throws Ex } } + @Test + public void testBatchPreflightsRestoreBeforeSubmittingAnyJob() throws Exception { + String base = "http://localhost:" + workerRestPort; + HttpResponse submit = + postJson( + base + "/submit-job?format=json&jobName=batch_restore_source", + getStreamingRequestBody()); + Assertions.assertEquals(200, submit.code, () -> "responseBody=" + submit.body); + long sourceJobId = + Long.parseLong(Json.parse(submit.body).asObject().getString("jobId", "")); + long firstJobId = Math.abs(System.nanoTime()); + try { + Awaitility.await() + .atMost(60, TimeUnit.SECONDS) + .pollInterval(500, TimeUnit.MILLISECONDS) + .until( + () -> + masterServer.getCoordinatorService().getJobStatus(sourceJobId) + == JobStatus.RUNNING); + + JsonObject first = Json.parse(getStreamingRequestBody()).asObject(); + first.add( + "params", + new JsonObject() + .add("jobId", Long.toString(firstJobId)) + .add("jobName", "batch_first")); + JsonObject second = Json.parse(getRequestBody()).asObject(); + second.add( + "params", + new JsonObject() + .add("restoreMode", "CHECKPOINT") + .add("restoreSourceJobId", Long.toString(sourceJobId))); + + HttpResponse refused = + postJson( + base + "/submit-jobs", + new JsonArray().add(first).add(second).toString()); + Assertions.assertEquals(400, refused.code, () -> "responseBody=" + refused.body); + Assertions.assertTrue( + refused.body.contains( + "restoreSourceJobId=" + sourceJobId + " is still RUNNING"), + () -> "responseBody=" + refused.body); + Assertions.assertEquals( + JobStatus.UNKNOWABLE, + masterServer.getCoordinatorService().getJobStatus(firstJobId), + "a rejected batch must not submit its earlier jobs"); + } finally { + postJson(base + "/stop-job", "{\"jobId\": " + sourceJobId + "}"); + if (masterServer.getCoordinatorService().getJobStatus(firstJobId) + != JobStatus.UNKNOWABLE) { + postJson(base + "/stop-job", "{\"jobId\": " + firstJobId + "}"); + } + } + } + @Test public void testSubmitSavepointRestoreWithoutSourceJobIdReturns400() throws Exception { String requestUrl = diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/JobInfoServiceRestoreGuardTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/JobInfoServiceRestoreGuardTest.java index 6bf486673a54..415ac9f62a92 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/JobInfoServiceRestoreGuardTest.java +++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/JobInfoServiceRestoreGuardTest.java @@ -17,14 +17,21 @@ package org.apache.seatunnel.engine.server.rest.service; +import org.apache.seatunnel.shade.com.typesafe.config.Config; + import org.apache.seatunnel.engine.common.job.JobStatus; import org.apache.seatunnel.engine.core.job.RestoreMode; +import org.apache.seatunnel.engine.server.SeaTunnelServer; +import org.apache.seatunnel.engine.server.rest.RestConstant; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import java.util.HashMap; +import java.util.Map; + /** * Verifies the restore-source guard used by the REST submit path: a restore is refused while the * source job is still active, and allowed once the source job has ended or is unknown, so the @@ -89,4 +96,51 @@ public void testSavepointModeIsNamedInTheRejection() { RestoreMode.SAVEPOINT, SOURCE_JOB_ID, JobStatus.RUNNING)); Assertions.assertTrue(error.getMessage().contains("savepoint state"), error.getMessage()); } + + @Test + public void testInvalidRestoreModeHasActionableError() { + Map params = new HashMap<>(); + params.put(RestConstant.RESTORE_MODE, "unknown"); + + IllegalArgumentException error = + Assertions.assertThrows( + IllegalArgumentException.class, + () -> new JobInfoService(null).submitJob(params, (Config) null)); + Assertions.assertEquals( + "restoreMode must be one of NONE, SAVEPOINT, CHECKPOINT.", error.getMessage()); + } + + @Test + public void testInvalidJobIdIsRejectedBeforeSubmission() { + Map params = new HashMap<>(); + params.put(RestConstant.JOB_ID, "not-a-job"); + + IllegalArgumentException error = + Assertions.assertThrows( + IllegalArgumentException.class, + () -> new JobInfoService(null).submitJob(params, (Config) null)); + Assertions.assertEquals("jobId must be a numeric job id.", error.getMessage()); + } + + @Test + public void testSourceStatusLookupFailureIsRetryableAndDoesNotLeakDetails() { + Map params = new HashMap<>(); + params.put(RestConstant.RESTORE_MODE, "CHECKPOINT"); + params.put(RestConstant.RESTORE_SOURCE_JOB_ID, Long.toString(SOURCE_JOB_ID)); + JobInfoService service = + new JobInfoService(null) { + @Override + protected SeaTunnelServer getSeaTunnelServer(boolean shouldBeMaster) { + throw new IllegalStateException("internal cluster detail"); + } + }; + + IllegalStateException error = + Assertions.assertThrows( + IllegalStateException.class, + () -> service.submitJob(params, (Config) null)); + Assertions.assertTrue(error.getMessage().contains("retry"), error.getMessage()); + Assertions.assertFalse(error.getMessage().contains("internal cluster detail")); + Assertions.assertEquals("internal cluster detail", error.getCause().getMessage()); + } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts index 4e3b53f6d88f..b591eae33ff5 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/managers.ts @@ -67,7 +67,8 @@ export default { workerRequired: 'Please select a worker first.', confirm: 'Confirm', cancelConfirm: 'Dismiss', - updateConfirmMessage: 'Update tags for this worker?', + updateConfirmMessage: + 'Replace all tags for this worker? Changes made since you selected it will be overwritten.', clearConfirmMessage: 'Clear all tags for this worker?' } } diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts index 45b2f59952e3..ba09f0a16a91 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/managers.ts @@ -66,7 +66,7 @@ export default { workerRequired: '请先选择一个 Worker。', confirm: '确认', cancelConfirm: '关闭', - updateConfirmMessage: '确认更新该 Worker 的 Tags?', + updateConfirmMessage: '确认整体替换该 Worker 的 Tags?选择节点后其他人所做的修改会被覆盖。', clearConfirmMessage: '确认清空该 Worker 的全部 Tags?' } }