You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by fa...@apache.org on 2025/02/05 03:00:08 UTC
(seatunnel) branch dev updated: [Feature][Core] Add slot allocation strategy (#8233)
This is an automated email from the ASF dual-hosted git repository.
fanjia pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
The following commit(s) were added to refs/heads/dev by this push:
new c4a7afc282 [Feature][Core] Add slot allocation strategy (#8233)
c4a7afc282 is described below
commit c4a7afc2821509a0d064f3926319f72789bc0d7b
Author: Jast <sh...@apache.org>
AuthorDate: Wed Feb 5 11:00:02 2025 +0800
[Feature][Core] Add slot allocation strategy (#8233)
---
.../seatunnel-engine/slot-allocation-strategy.md | 111 +++++
docs/sidebars.js | 3 +-
.../seatunnel-engine/slot-allocation-strategy.md | 98 ++++
seatunnel-dist/release-docs/LICENSE | 3 +
.../connector-seatunnel-e2e-base/pom.xml | 7 +
.../seatunnel/engine/e2e/JobClientJobProxyIT.java | 13 +-
.../SlotRatioAllocateStrategyIT.java | 251 ++++++++++
.../SystemLoadAllocateStrategyIT.java | 275 ++++++++++
.../allocate_strategy_no_tag_with_system_load.conf | 53 ++
.../allocate_strategy_tag1_with_system_load.conf | 56 +++
.../allocate_strategy_tag2_with_system_load.conf | 56 +++
.../allocate_strategy_with_slot_ratio.conf | 53 ++
seatunnel-engine/pom.xml | 6 +
.../config/YamlSeaTunnelDomConfigProcessor.java | 4 +
.../common/config/server/AllocateStrategy.java | 72 +++
.../common/config/server/ServerConfigOptions.java | 7 +
.../common/config/server/SlotServiceConfig.java | 3 +
seatunnel-engine/seatunnel-engine-server/pom.xml | 4 +
.../seatunnel/engine/server/master/JobMaster.java | 24 +
.../resourcemanager/AbstractResourceManager.java | 41 +-
.../server/resourcemanager/ResourceManager.java | 4 +
.../resourcemanager/ResourceRequestHandler.java | 28 +-
.../allocation/strategy/RandomStrategy.java} | 25 +-
.../strategy/SlotAllocationStrategy.java} | 23 +-
.../allocation/strategy/SlotRatioStrategy.java | 81 +++
.../allocation/strategy/SystemLoadStrategy.java | 83 +++
.../resource/SlotAssignedProfile.java} | 23 +-
.../resourcemanager/resource/SystemLoadInfo.java} | 20 +-
.../resourcemanager/worker/WorkerProfile.java | 24 +-
.../server/service/slot/DefaultSlotService.java | 82 ++-
.../engine/server/utils/SystemLoadCalculate.java | 218 ++++++++
.../resourcemanager/FixSlotResourceTest.java | 33 +-
.../resourcemanager/ResourceManagerTest.java | 9 +-
.../server/utils/SystemLoadCalculateTest.java | 555 +++++++++++++++++++++
tools/dependencies/known-dependencies.txt | 3 +
35 files changed, 2254 insertions(+), 97 deletions(-)
diff --git a/docs/en/seatunnel-engine/slot-allocation-strategy.md b/docs/en/seatunnel-engine/slot-allocation-strategy.md
new file mode 100644
index 0000000000..2020dc57ab
--- /dev/null
+++ b/docs/en/seatunnel-engine/slot-allocation-strategy.md
@@ -0,0 +1,111 @@
+# Slot Allocation Strategy
+
+Slot allocation strategy is an important part of SeaTunnel Engine, which determines how SeaTunnel Engine allocates tasks to different slots. The slot allocation strategy is a configurable component, and users can configure the slot allocation strategy according to their needs.
+
+**Configuration method:**
+
+Set the parameter `slot-allocation-strategy`, optional values are `RANDOM`, `SYSTEM_LOAD`, `SLOT_RATIO`.
+
+Example:
+
+```yaml
+seatunnel:
+ engine:
+ slot-service:
+ slot-allocation-strategy: RANDOM
+```
+
+## RANDOM (default value)
+
+The random allocation strategy is the default slot allocation strategy of SeaTunnel Engine, which randomly allocates tasks to different slots.
+
+## SYSTEM_LOAD
+
+The system load strategy allocates slots based on the system load, dynamically adjusting the slot allocation according to the system load.
+
+### 1. **Design of time weight**
+
+Time weight reflects the impact of time on scheduling priority:
+
+- Recent data is given higher weight, and historical data gradually decays.
+
+- Using the distribution $4, 2, 2, 1, 1$ and normalizing it, the time weight for each statistic is:
+
+ $$ \text{Time weight ratio} = \frac{\text{Current weight}}{10} $$
+
+> When the cluster is just started and there are less than 5 data points, normalization is done separately, and the calculation formula will be dynamically adjusted, which will not be elaborated here.
+
+### 2. **Resource utilization calculation**
+
+Evaluate the idle rate of CPU and memory resources comprehensively according to the weight:
+
+$$ \text{Resource idle rate} = \frac{(1 - \text{CPU utilization}) \cdot \text{CPU weight} + (1 - \text{Memory utilization}) \cdot \text{Memory weight}}{\text{CPU weight} + \text{Memory weight}} $$
+
+- $(1 - \text{CPU utilization})$ and $(1 - \text{Memory utilization})$ in the formula are idle rates.
+
+- The weights of CPU and memory can be adjusted according to specific needs (e.g., $0.6$ and $0.4$), flexibly adapting to different scenarios.
+
+### 3. **Time decay and scheduling priority formula**
+
+After introducing time weight decay, the formula for calculating scheduling priority is:
+
+$$
+\text{Comprehensive resource idle rate} = \sum_{i=1}^{5} \left( \frac{(1 - \text{CPU utilization}_i) \cdot \text{CPU weight} + (1 - \text{Memory utilization}_i) \cdot \text{Memory weight}}{\text{CPU weight} + \text{Memory weight}} \cdot \text{Time weight}_i \right)
+$$
+
+### 4. **Dynamic adjustment of resource idle rate for slot allocation**
+
+When allocating multiple slots, considering the real-time update and dynamic simulation of resource status (because the resource load of the same task will not change quickly):
+
+- **Resource ratio used by each slot** = (1 - Comprehensive resource idle rate) ÷ Number of allocated slots
+
+- Update the idle rate of the corresponding node after allocating the slot:
+
+ $$ \text{Idle rate after slot allocation} = \text{Comprehensive resource idle rate} - \text{Resource ratio used by each slot} $$
+
+- By default, a single slot uses 10% of resources (it is not known how much resources a slot occupies when it is first started, so it is set to 10% by default. The reason for not setting it too low is to prevent allocating too many resources and causing the node to be overloaded. The next time monitoring information is captured, it will be relatively accurate).
+
+This method makes scheduling more in line with the actual resource usage.
+
+### 5. **Introduction of balance factor**
+
+Only dynamically adjusting the resource idle rate through slot allocation may also have errors. We introduce a balance factor based on the number of slots to measure the current load status of the node and avoid over-concentration of scheduling resource allocation:
+
+> This number can be counted in real-time to optimize the scheduling priority indicator.
+
+$$
+\text{BalanceFactor}_i = 1 - \frac{S_{\text{used},i}}{S_{\text{total},i}}
+$$
+
+- $S_{\text{used},i}$: Number of slots allocated to node $i$.
+- $S_{\text{total},i}$: Total number of slots of node $i$.
+
+Adjust the scheduling priority through the balance factor:
+
+$$
+W_i = \alpha \cdot \text{Idle rate after slot allocation}_i + \beta \cdot \text{BalanceFactor}_i
+$$
+
+**Parameter meaning**:
+- $\alpha$: Weight focusing on resource utilization: 0.7
+- $\beta$: Weight of the balance factor to prevent single-point overload: 0.3
+
+### 6. **Dynamic adjustment logic**
+
+- Collect CPU and memory utilization regularly, maintaining the most recent 5 statistics.
+- Dynamically update weights for the same task, gradually decaying old data.
+- Dynamic balance based on slot usage.
+
+> Explanation:
+> For example, if we have two nodes and need to allocate 10 slots, A has 10 idle slots, and B has 20 idle slots. After calculating the weights of the 10 slots through steps 4 and 5, the weights of node A are higher than those of node B.
+> Then we still think that node A should allocate resources. This may be because the slot configuration of node B in the cluster is not optimal (the slot configuration of the worker node is too small).
+
+## SLOT_RATIO
+
+The slot ratio strategy schedules based on the slot usage rate, with higher priority given to slots with lower usage rates.
+
+**Calculation logic**:
+
+1. Get the total number of slots of the worker.
+2. Get the number of unallocated slots.
+3. Usage rate = (Total number of slots - Number of unallocated slots) / Total number of slots.
\ No newline at end of file
diff --git a/docs/sidebars.js b/docs/sidebars.js
index 453c5d4605..9bf23b5e7b 100644
--- a/docs/sidebars.js
+++ b/docs/sidebars.js
@@ -213,7 +213,8 @@ const sidebars = {
"seatunnel-engine/user-command",
"seatunnel-engine/logging",
"seatunnel-engine/telemetry",
- "seatunnel-engine/web-ui"
+ "seatunnel-engine/web-ui",
+ "seatunnel-engine/slot-allocation-strategy"
]
},
{
diff --git a/docs/zh/seatunnel-engine/slot-allocation-strategy.md b/docs/zh/seatunnel-engine/slot-allocation-strategy.md
new file mode 100644
index 0000000000..3d29a6eaca
--- /dev/null
+++ b/docs/zh/seatunnel-engine/slot-allocation-strategy.md
@@ -0,0 +1,98 @@
+---
+sidebar_position: 15
+---
+
+# Slot分配策略
+
+Slot分配策略是SeaTunnel Engine的一个重要组成部分,它决定了SeaTunnel Engine如何将任务分配到不同的Slot上。Slot分配策略是一个可配置的组件,用户可以根据自己的需求来配置Slot分配策略。
+
+**配置方法:**
+
+设置参数`slot-allocation-strategy`, 可选值有`RANDOM`, `SYSTEM_LOAD`, `SLOT_RATIO`。
+
+例:
+```yaml
+seatunnel:
+ engine:
+ slot-service:
+ slot-allocation-strategy: RANDOM
+...
+```
+
+## RANDOM(默认值)
+
+随机分配策略是SeaTunnel Engine默认的Slot分配策略,它将任务随机分配到不同的Slot上。
+
+## SYSTEM_LOAD
+
+系统负载策略是根据系统的负载情况来分配Slot的策略,它会根据系统的负载情况来动态调整Slot的分配。
+
+### 1. **时间权重的设计**
+时间权重体现了时间对调度优先级的影响:
+- 最近的数据赋予较高权重,历史数据逐渐衰减。
+- 采用分布 $4, 2, 2, 1, 1$ 并归一化后,每次统计的时间权重为:
+ $$ \text{时间权重比例} = \frac{\text{当前权重}}{10} $$
+
+> 当集群刚启动时,数据不足5条,会单独做归一化,这里计算公式会动态调整,不做赘述。
+
+### 2. **资源利用率计算**
+将 CPU 和内存资源的空闲率按照权重进行综合评估:
+$$ \text{资源空闲率} = \frac{(1 - \text{CPU利用率}) \cdot \text{CPU权重} + (1 - \text{内存利用率}) \cdot \text{内存权重}}{\text{CPU权重} + \text{内存权重}} $$
+
+- 公式中的 $(1 - \text{CPU利用率})$ 和 $(1 - \text{内存利用率})$ 是空闲率。
+- CPU 和内存的权重可根据具体需求调整(如 $0.6$ 和 $0.4$),灵活适应不同场景。
+
+### 3. **时间衰减与调度优先级公式**
+
+引入时间权重衰减后,计算调度优先级的公式为:
+$$
+\text{综合资源空闲率} = \sum_{i=1}^{5} \left( \frac{(1 - \text{CPU利用率}_i) \cdot \text{CPU权重} + (1 - \text{内存利用率}_i) \cdot \text{内存权重}}{\text{CPU权重} + \text{内存权重}} \cdot \text{时间权重}_i \right)
+$$
+
+### 4. **Slot分配的资源空闲率动态调整**
+分配多个 Slot 时,考虑到资源状态的实时更新和动态模拟(因为同一任务资源快速分配负载是不会变化):
+- **每个 Slot 使用的资源比** = (1-综合资源空闲率) ÷ 已分配的 Slot 数量
+- 分配 Slot 后更新对应节点的空闲率:
+ $$ \text{Slot分配后的空闲率} = \text{综合资源空闲率} - \text{每 Slot 使用的资源比} $$
+- 默认单个Slot使用10%资源(首次启动无法得知但Slot占用资源,这里默认设置为10%,不设置太低的原因是防止分配过多资源导致该节点负载太高。等下一次监控信息捕获到就会相对准确。)
+
+这种方法属于与计算使得调度更加贴合实际资源使用情况。
+
+### 5. **平衡因子引入**
+只通过Slot动态调整更新资源空闲率可能也会存在误差,我们引入基于Slot数量的平衡因子,衡量节点当前负载状态,避免调度资源分配过于集中:
+> 该数量可以实时统计到,用来优化调度优先级指标
+
+$$
+\text{BalanceFactor}_i = 1 - \frac{S_{\text{used},i}}{S_{\text{total},i}}
+$$
+
+- $S_{\text{used},i}$:节点 $i$ 已分配的 Slot 数。
+- $S_{\text{total},i}$:节点 $i$ 的 Slot 总数。
+
+通过平衡因子调整调度优先级:
+$$
+W_i = \alpha \cdot \text{Slot分配后的空闲率}_i + \beta \cdot \text{BalanceFactor}_i
+$$
+
+**参数意义**:
+- $\alpha$:侧重资源利用率的权重:0.7
+- $\beta$:平衡因子的权重,防止单点过载。:0.3
+
+### 6. **动态调整逻辑**
+- 定时采集 CPU 和内存利用率,维持最近 5 次的统计数据。
+- 同一任务动态更新权重,对旧数据逐步衰减。
+- 根据Slot使用,动态平衡。
+
+> 说明:
+> 比如我们有两个节点,需要申请10个Slot,A有10个空闲Slot,B有20个空闲Slot,当通过第四步、第五步计算后,10个Slot的权重计算,A节点权重都比B节点权重高。
+> 那么我们仍认为A节点应该分配资源,此时可能是因为集群B节点Slot数量配置不是最佳导致(Worker节点Slot配置少了)。
+
+## SLOT_RATIO
+
+Slot比例策略是根据Slot的使用率来进行调度,使用率越低的Slot优先级越高。
+
+**计算逻辑**:
+1. 获取Worker总Slot数
+2. 获取未分配Slot数。
+3. 使用率 = (总插槽数 - 未分配插槽数) / 总插槽数。
+
diff --git a/seatunnel-dist/release-docs/LICENSE b/seatunnel-dist/release-docs/LICENSE
index 40e85cfa6f..f68045e4f5 100644
--- a/seatunnel-dist/release-docs/LICENSE
+++ b/seatunnel-dist/release-docs/LICENSE
@@ -307,6 +307,8 @@ The text of each license is the standard Apache 2.0 license.
(Apache-2.0) kerby-pkix (org.apache.kerby:kerby-pkix:1.0.1 - https://github.com/apache/directory-kerby)
(Apache-2.0) kerby-util (org.apache.kerby:kerby-util:1.0.1 - https://github.com/apache/directory-kerby)
(Apache-2.0) kerby-xdr (org.apache.kerby:kerby-xdr:1.0.1 - https://github.com/apache/directory-kerby)
+ (Apache-2.0) jna (net.java.dev.jna:jna:5.15.0 - https://github.com/java-native-access/jna)
+ (Apache-2.0) jna-platform (net.java.dev.jna:jna-platform:5.15.0 - https://github.com/java-native-access/jna)
(Apache-2.0) token-provider (org.apache.kerby:token-provider:1.0.1 - https://github.com/apache/directory-kerby)
(Apache-2.0) snappy-java (org.xerial.snappy:snappy-java:1.0.5 - https://github.com/xerial/snappy-java)
(Apache-2.0) snappy-java (org.xerial.snappy:snappy-java:1.1.8.3 - https://github.com/xerial/snappy-java)
@@ -396,6 +398,7 @@ The text of each license is also included at licenses/LICENSE-[project].txt.
(MIT License) jcl-over-slf4j (org.slf4j:jcl-over-slf4j:1.7.25 - http://www.slf4j.org)
(MIT License) animal-sniffer-annotations (org.codehaus.mojo:animal-sniffer-annotations:1.17 - https://mvnrepository.com/artifact/org.codehaus.mojo/animal-sniffer-annotations/1.17)
(MIT License) checker-qual (org.checkerframework:checker-qual:3.10.0 - https://mvnrepository.com/)
+ (MIT License) oshi-core (com.github.oshi:oshi-core:6.6.5 - https://github.com/oshi/oshi)
========================================================================
EPL-1.0 and Apache-2.0 licenses
diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/pom.xml b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/pom.xml
index 6fbdfc826b..d8f18347ec 100644
--- a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/pom.xml
+++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/pom.xml
@@ -126,6 +126,13 @@
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>com.github.oshi</groupId>
+ <artifactId>oshi-core</artifactId>
+ <version>6.6.5</version>
+ <scope>test</scope>
+ </dependency>
+
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-buffer</artifactId>
diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/JobClientJobProxyIT.java b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/JobClientJobProxyIT.java
index febdaa332d..82402ff2d4 100644
--- a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/JobClientJobProxyIT.java
+++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/JobClientJobProxyIT.java
@@ -60,7 +60,8 @@ public class JobClientJobProxyIT extends SeaTunnelEngineContainer {
Assertions.assertTrue(
server.getLogs()
.contains(
- "Restore time 3, pipeline Job stream_fake_to_inmemory_with_error.conf"));
+ "Restore time 3, pipeline Job stream_fake_to_inmemory_with_error.conf"),
+ server.getLogs());
}
@Test
@@ -77,14 +78,16 @@ public class JobClientJobProxyIT extends SeaTunnelEngineContainer {
Container.ExecResult execResult =
executeJob(server, "/stream_fake_to_inmemory_with_throwable_error.conf");
Assertions.assertNotEquals(0, execResult.getExitCode());
- Assertions.assertTrue(execResult.getStderr().contains("table fake sink throw error"));
+ Assertions.assertTrue(
+ execResult.getStderr().contains("table fake sink throw error"),
+ execResult.getStderr());
}
@Test
public void testSaveModeOnMasterOrClient() throws IOException, InterruptedException {
Container.ExecResult execResult =
executeJob(server, "/savemode/fake_to_inmemory_savemode.conf");
- Assertions.assertEquals(0, execResult.getExitCode());
+ Assertions.assertEquals(0, execResult.getExitCode(), execResult.getStderr());
int serverLogLength = 0;
String serverLogs = server.getLogs();
Assertions.assertTrue(
@@ -102,7 +105,7 @@ public class JobClientJobProxyIT extends SeaTunnelEngineContainer {
// restore will not execute savemode
execResult = restoreJob(server, "/savemode/fake_to_inmemory_savemode.conf", "1");
- Assertions.assertEquals(0, execResult.getExitCode());
+ Assertions.assertEquals(0, execResult.getExitCode(), execResult.getStderr());
// clear old logs
serverLogLength += serverLogs.length();
serverLogs = server.getLogs().substring(serverLogLength);
@@ -112,7 +115,7 @@ public class JobClientJobProxyIT extends SeaTunnelEngineContainer {
// test savemode on client side
Container.ExecResult execResult2 =
executeJob(server, "/savemode/fake_to_inmemory_savemode_client.conf");
- Assertions.assertEquals(0, execResult2.getExitCode());
+ Assertions.assertEquals(0, execResult2.getExitCode(), execResult2.getStderr());
// clear old logs
serverLogLength += serverLogs.length();
serverLogs = server.getLogs().substring(serverLogLength);
diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/allocatestrategy/SlotRatioAllocateStrategyIT.java b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/allocatestrategy/SlotRatioAllocateStrategyIT.java
new file mode 100644
index 0000000000..c870cfbd6d
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/allocatestrategy/SlotRatioAllocateStrategyIT.java
@@ -0,0 +1,251 @@
+/*
+ * 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.e2e.allocatestrategy;
+
+import org.apache.seatunnel.common.config.Common;
+import org.apache.seatunnel.common.config.DeployMode;
+import org.apache.seatunnel.common.constants.JobMode;
+import org.apache.seatunnel.engine.client.SeaTunnelClient;
+import org.apache.seatunnel.engine.client.job.ClientJobProxy;
+import org.apache.seatunnel.engine.common.config.ConfigProvider;
+import org.apache.seatunnel.engine.common.config.JobConfig;
+import org.apache.seatunnel.engine.common.config.SeaTunnelConfig;
+import org.apache.seatunnel.engine.common.config.server.AllocateStrategy;
+import org.apache.seatunnel.engine.common.config.server.SlotServiceConfig;
+import org.apache.seatunnel.engine.e2e.TestUtils;
+import org.apache.seatunnel.engine.server.SeaTunnelServer;
+import org.apache.seatunnel.engine.server.SeaTunnelServerStarter;
+import org.apache.seatunnel.engine.server.resourcemanager.ResourceManager;
+import org.apache.seatunnel.engine.server.resourcemanager.worker.WorkerProfile;
+
+import org.awaitility.Awaitility;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import com.hazelcast.client.config.ClientConfig;
+import com.hazelcast.cluster.Address;
+import com.hazelcast.instance.impl.HazelcastInstanceImpl;
+import com.hazelcast.spi.impl.NodeEngineImpl;
+import lombok.NonNull;
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.seatunnel.shade.com.google.common.base.Preconditions.checkArgument;
+
+/** Test task allocation strategy */
+@Slf4j
+public class SlotRatioAllocateStrategyIT {
+
+ public static final String DYNAMIC_TEST_CASE_NAME = "dynamic_test_case_name";
+
+ public static final String DYNAMIC_JOB_MODE = "dynamic_job_mode";
+
+ public static final String DYNAMIC_TEST_ROW_NUM_PER_PARALLELISM =
+ "dynamic_test_row_num_per_parallelism";
+
+ public static final String DYNAMIC_TEST_PARALLELISM = "dynamic_test_parallelism";
+
+ /**
+ * Test steps:<br>
+ * 1. Start a task with 4 parallelisms, which actually occupies 5 slots <br>
+ * 2. Expected result: one node occupies 2 slots, and one node occupies 3 slots <br>
+ * 3. Start a task with 6 parallelisms, which actually occupies 7 slots <br>
+ * 4. Including the first task, a total of 12 slots are occupied <br>
+ * 5. Expected result: each of the two nodes occupies 6 slots <br>
+ */
+ @Test
+ public void testSlotRatioStrategy() throws Exception {
+ String testCaseName = "testSlotRatioStrategy";
+ String testClusterName = "TestSlotRatioStrategy";
+ long testRowNumber = 100;
+
+ HazelcastInstanceImpl node1 = null;
+ HazelcastInstanceImpl node2 = null;
+ SeaTunnelClient engineClient = null;
+
+ SeaTunnelConfig seaTunnelConfig = ConfigProvider.locateAndGetSeaTunnelConfig();
+ seaTunnelConfig.getHazelcastConfig().getNetworkConfig().setPort(5805);
+ seaTunnelConfig.getEngineConfig().getHttpConfig().setEnabled(false);
+ seaTunnelConfig
+ .getHazelcastConfig()
+ .setClusterName(TestUtils.getClusterName(testClusterName));
+ SlotServiceConfig slotServiceConfig =
+ seaTunnelConfig.getEngineConfig().getSlotServiceConfig();
+ slotServiceConfig.setSlotNum(10);
+ slotServiceConfig.setDynamicSlot(false);
+ // enable slot ratio strategy
+ slotServiceConfig.setAllocateStrategy(AllocateStrategy.SLOT_RATIO);
+
+ try {
+ node1 = SeaTunnelServerStarter.createHazelcastInstance(seaTunnelConfig);
+ node2 = SeaTunnelServerStarter.createHazelcastInstance(seaTunnelConfig);
+
+ // waiting all node added to cluster
+ HazelcastInstanceImpl finalNode = node1;
+ Awaitility.await()
+ .atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(
+ () ->
+ Assertions.assertEquals(
+ 2, finalNode.getCluster().getMembers().size()));
+
+ // Waiting for worker heartbeat registration
+ Thread.sleep(10000);
+ Common.setDeployMode(DeployMode.CLIENT);
+ JobConfig jobConfig = new JobConfig();
+ jobConfig.setName(testCaseName);
+
+ ClientConfig clientConfig = ConfigProvider.locateAndGetClientConfig();
+ clientConfig.setClusterName(TestUtils.getClusterName(testClusterName));
+ engineClient = new SeaTunnelClient(clientConfig);
+ // Start a task
+ ClientJobProxy clientJobProxyStepOne =
+ engineClient
+ .createExecutionContext(
+ createTestResources(
+ testCaseName,
+ JobMode.STREAMING,
+ testRowNumber,
+ 4,
+ "allocate-strategy/allocate_strategy_with_slot_ratio.conf"),
+ jobConfig,
+ seaTunnelConfig)
+ .execute();
+
+ NodeEngineImpl nodeEngine = node1.node.nodeEngine;
+ Address node2Address = node2.node.address;
+ Address node1Address = node1.node.address;
+
+ // Get the number of occupied slots through resourceManager
+ SeaTunnelServer server = nodeEngine.getService(SeaTunnelServer.SERVICE_NAME);
+ ResourceManager resourceManager = server.getCoordinatorService().getResourceManager();
+
+ // SLOT_RATION strategy, the task will eventually occupy 5 slots and will be distributed
+ // to two nodes, one node occupies 2 slots and the other occupies 3 slots.
+ Awaitility.await()
+ .atMost(600, TimeUnit.SECONDS)
+ .untilAsserted(
+ () -> {
+ ConcurrentMap<Address, WorkerProfile> registerWorker =
+ resourceManager.getRegisterWorker();
+ int node1AssignedSlotsNum =
+ registerWorker.get(node1Address).getAssignedSlots().length;
+ int node2AssignedSlotsNum =
+ registerWorker.get(node2Address).getAssignedSlots().length;
+ Assertions.assertTrue(
+ node1AssignedSlotsNum == 2 || node1AssignedSlotsNum == 3);
+ Assertions.assertTrue(
+ node2AssignedSlotsNum == 2 || node2AssignedSlotsNum == 3);
+ Assertions.assertEquals(
+ 5, node1AssignedSlotsNum + node2AssignedSlotsNum);
+ });
+
+ // Start a task with 6 parallelism, which will occupy 7 slots in total, and the
+ // SLOT_RATION strategy will be evenly distributed to two nodes
+ ClientJobProxy clientJobProxyStepTwo =
+ engineClient
+ .createExecutionContext(
+ createTestResources(
+ testCaseName,
+ JobMode.STREAMING,
+ testRowNumber,
+ 6,
+ "allocate-strategy/allocate_strategy_with_slot_ratio.conf"),
+ jobConfig,
+ seaTunnelConfig)
+ .execute();
+
+ // The task will eventually occupy 7 slots. Together with the first task, it will occupy
+ // a total of 12 slots. The SLOT_RATION strategy will evenly distribute them to the two
+ // nodes.
+ Awaitility.await()
+ .atMost(600, TimeUnit.SECONDS)
+ .untilAsserted(
+ () -> {
+ ConcurrentMap<Address, WorkerProfile> registerWorker =
+ resourceManager.getRegisterWorker();
+ int node1AssignedSlotsNum =
+ registerWorker.get(node1Address).getAssignedSlots().length;
+ int node2AssignedSlotsNum =
+ registerWorker.get(node2Address).getAssignedSlots().length;
+ Assertions.assertEquals(6, node1AssignedSlotsNum);
+ Assertions.assertEquals(6, node2AssignedSlotsNum);
+ });
+
+ clientJobProxyStepOne.cancelJob();
+ clientJobProxyStepTwo.cancelJob();
+ clientJobProxyStepOne.waitForJobCompleteV2();
+ clientJobProxyStepTwo.waitForJobCompleteV2();
+
+ } finally {
+ if (engineClient != null) {
+ engineClient.close();
+ }
+ if (node1 != null) {
+ node1.shutdown();
+ }
+ if (node2 != null) {
+ node2.shutdown();
+ }
+ }
+ }
+
+ /**
+ * Create the test job config file basic on cluster_batch_fake_to_localfile_template.conf It
+ * will delete the test sink target path before return the final job config file path
+ *
+ * @param testCaseName testCaseName
+ * @param jobMode jobMode
+ * @param rowNumber row.num per FakeSource parallelism
+ * @param parallelism FakeSource parallelism
+ */
+ private String createTestResources(
+ @NonNull String testCaseName,
+ @NonNull JobMode jobMode,
+ long rowNumber,
+ int parallelism,
+ String templateFile)
+ throws IOException {
+ checkArgument(rowNumber > 0, "rowNumber must greater than 0");
+ checkArgument(parallelism > 0, "parallelism must greater than 0");
+ Map<String, String> valueMap = new HashMap<>();
+ valueMap.put(DYNAMIC_TEST_CASE_NAME, testCaseName);
+ valueMap.put(DYNAMIC_JOB_MODE, jobMode.toString());
+ valueMap.put(DYNAMIC_TEST_ROW_NUM_PER_PARALLELISM, String.valueOf(rowNumber));
+ valueMap.put(DYNAMIC_TEST_PARALLELISM, String.valueOf(parallelism));
+
+ String targetConfigFilePath =
+ File.separator
+ + "tmp"
+ + File.separator
+ + "test_conf"
+ + File.separator
+ + testCaseName
+ + ".conf";
+
+ TestUtils.createTestConfigFileFromTemplate(templateFile, valueMap, targetConfigFilePath);
+
+ return targetConfigFilePath;
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/allocatestrategy/SystemLoadAllocateStrategyIT.java b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/allocatestrategy/SystemLoadAllocateStrategyIT.java
new file mode 100644
index 0000000000..5380442e83
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/allocatestrategy/SystemLoadAllocateStrategyIT.java
@@ -0,0 +1,275 @@
+/*
+ * 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.e2e.allocatestrategy;
+
+import org.apache.seatunnel.common.config.Common;
+import org.apache.seatunnel.common.config.DeployMode;
+import org.apache.seatunnel.common.constants.JobMode;
+import org.apache.seatunnel.engine.client.SeaTunnelClient;
+import org.apache.seatunnel.engine.client.job.ClientJobProxy;
+import org.apache.seatunnel.engine.common.config.ConfigProvider;
+import org.apache.seatunnel.engine.common.config.JobConfig;
+import org.apache.seatunnel.engine.common.config.SeaTunnelConfig;
+import org.apache.seatunnel.engine.common.config.server.AllocateStrategy;
+import org.apache.seatunnel.engine.common.config.server.SlotServiceConfig;
+import org.apache.seatunnel.engine.e2e.TestUtils;
+import org.apache.seatunnel.engine.server.SeaTunnelServer;
+import org.apache.seatunnel.engine.server.SeaTunnelServerStarter;
+import org.apache.seatunnel.engine.server.resourcemanager.ResourceManager;
+import org.apache.seatunnel.engine.server.resourcemanager.worker.WorkerProfile;
+
+import org.awaitility.Awaitility;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import com.hazelcast.client.config.ClientConfig;
+import com.hazelcast.cluster.Address;
+import com.hazelcast.config.MemberAttributeConfig;
+import com.hazelcast.instance.impl.HazelcastInstanceImpl;
+import com.hazelcast.spi.impl.NodeEngineImpl;
+import lombok.NonNull;
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.seatunnel.shade.com.google.common.base.Preconditions.checkArgument;
+
+/** Test task allocation strategy */
+@Slf4j
+public class SystemLoadAllocateStrategyIT {
+
+ public static final String DYNAMIC_TEST_CASE_NAME = "dynamic_test_case_name";
+
+ public static final String DYNAMIC_JOB_MODE = "dynamic_job_mode";
+
+ public static final String DYNAMIC_TEST_ROW_NUM_PER_PARALLELISM =
+ "dynamic_test_row_num_per_parallelism";
+
+ public static final String DYNAMIC_TEST_PARALLELISM = "dynamic_test_parallelism";
+
+ /**
+ * Test steps: <br>
+ * 1. Start two tasks and occupy 5 slots on two nodes respectively <br>
+ * 2. Start 3 parallel tasks ,occupy 4 slots<br>
+ * 3. Expected result: Each node of the two nodes occupies 7 slots respectively <br>
+ */
+ @Test
+ public void testSystemLoadStrategy() throws Exception {
+ String testCaseName = "testSystemLoadStrategy";
+ String testClusterName = "TestSystemLoadStrategy";
+ long testRowNumber = 100;
+ int testParallelism = 4;
+
+ HazelcastInstanceImpl node1 = null;
+ HazelcastInstanceImpl node2 = null;
+ SeaTunnelClient engineClient = null;
+
+ SeaTunnelConfig seaTunnelConfig = ConfigProvider.locateAndGetSeaTunnelConfig();
+ seaTunnelConfig
+ .getHazelcastConfig()
+ .setClusterName(TestUtils.getClusterName(testClusterName));
+ SlotServiceConfig slotServiceConfig =
+ seaTunnelConfig.getEngineConfig().getSlotServiceConfig();
+ slotServiceConfig.setSlotNum(10);
+ slotServiceConfig.setDynamicSlot(false);
+ // enable system load strategy
+ slotServiceConfig.setAllocateStrategy(AllocateStrategy.SYSTEM_LOAD);
+
+ // Set the node tag and submit a task that occupies 5 slots to each of the two nodes
+ MemberAttributeConfig node1Tags = new MemberAttributeConfig();
+ node1Tags.setAttribute("strategy", "system_load1");
+ seaTunnelConfig.getHazelcastConfig().setMemberAttributeConfig(node1Tags);
+ seaTunnelConfig.getHazelcastConfig().getNetworkConfig().setPort(5808);
+ seaTunnelConfig.getEngineConfig().getHttpConfig().setEnabled(false);
+ try {
+ node1 = SeaTunnelServerStarter.createHazelcastInstance(seaTunnelConfig);
+ MemberAttributeConfig node2Tags = new MemberAttributeConfig();
+ node2Tags.setAttribute("strategy", "system_load2");
+ seaTunnelConfig.getHazelcastConfig().setMemberAttributeConfig(node2Tags);
+ node2 = SeaTunnelServerStarter.createHazelcastInstance(seaTunnelConfig);
+
+ // waiting all node added to cluster
+ HazelcastInstanceImpl finalNode = node1;
+ Awaitility.await()
+ .atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(
+ () ->
+ Assertions.assertEquals(
+ 2, finalNode.getCluster().getMembers().size()));
+
+ // Waiting for worker heartbeat registration
+ Thread.sleep(10000);
+ Common.setDeployMode(DeployMode.CLIENT);
+ JobConfig jobConfig = new JobConfig();
+ jobConfig.setName(testCaseName);
+
+ ClientConfig clientConfig = ConfigProvider.locateAndGetClientConfig();
+ clientConfig.setClusterName(TestUtils.getClusterName(testClusterName));
+ engineClient = new SeaTunnelClient(clientConfig);
+ ClientJobProxy clientJobProxyStepOne1 =
+ engineClient
+ .createExecutionContext(
+ createTestResources(
+ testCaseName,
+ JobMode.STREAMING,
+ testRowNumber,
+ testParallelism,
+ "allocate-strategy/allocate_strategy_tag1_with_system_load.conf"),
+ jobConfig,
+ seaTunnelConfig)
+ .execute();
+
+ ClientJobProxy clientJobProxyStepOne2 =
+ engineClient
+ .createExecutionContext(
+ createTestResources(
+ testCaseName,
+ JobMode.STREAMING,
+ testRowNumber,
+ testParallelism,
+ "allocate-strategy/allocate_strategy_tag2_with_system_load.conf"),
+ jobConfig,
+ seaTunnelConfig)
+ .execute();
+
+ NodeEngineImpl nodeEngine = node1.node.nodeEngine;
+ Address node2Address = node2.node.address;
+ Address node1Address = node1.node.address;
+
+ SeaTunnelServer server = nodeEngine.getService(SeaTunnelServer.SERVICE_NAME);
+ ResourceManager resourceManager = server.getCoordinatorService().getResourceManager();
+
+ Awaitility.await()
+ .atMost(600, TimeUnit.SECONDS)
+ .untilAsserted(
+ () -> {
+ ConcurrentMap<Address, WorkerProfile> registerWorker =
+ resourceManager.getRegisterWorker();
+ int node1AssignedSlotsNum =
+ registerWorker.get(node1Address).getAssignedSlots().length;
+ int node2AssignedSlotsNum =
+ registerWorker.get(node2Address).getAssignedSlots().length;
+ Assertions.assertTrue(node1AssignedSlotsNum == 5);
+ Assertions.assertTrue(node2AssignedSlotsNum == 5);
+ Assertions.assertEquals(
+ 10, node1AssignedSlotsNum + node2AssignedSlotsNum);
+ });
+ log.info("The first step is completed");
+
+ // Waiting to collect the node's System Load information
+ Thread.sleep(60000);
+
+ // Start a task that occupies 4 slots
+ jobConfig = new JobConfig();
+ jobConfig.setName(testCaseName);
+
+ log.info("Start a task that occupies 4 slots");
+ ClientJobProxy clientJobProxyStepTwo =
+ engineClient
+ .createExecutionContext(
+ createTestResources(
+ testCaseName,
+ JobMode.STREAMING,
+ testRowNumber,
+ 3,
+ "allocate-strategy/allocate_strategy_no_tag_with_system_load.conf"),
+ jobConfig,
+ seaTunnelConfig)
+ .execute();
+
+ // Because e2e runs on the same node, the CPU and memory are almost the same, but we
+ // introduced a balance factor (step 5). So the final result should also be balanced.
+ // That is, the two nodes occupy 7 slots respectively.
+ Awaitility.await()
+ .atMost(600, TimeUnit.SECONDS)
+ .untilAsserted(
+ () -> {
+ ConcurrentMap<Address, WorkerProfile> registerWorker =
+ resourceManager.getRegisterWorker();
+ int node1AssignedSlotsNum =
+ registerWorker.get(node1Address).getAssignedSlots().length;
+ int node2AssignedSlotsNum =
+ registerWorker.get(node2Address).getAssignedSlots().length;
+ Assertions.assertEquals(7, node1AssignedSlotsNum);
+ Assertions.assertEquals(7, node2AssignedSlotsNum);
+ });
+ log.info("The second step is completed");
+
+ clientJobProxyStepOne1.cancelJob();
+ clientJobProxyStepOne2.cancelJob();
+ clientJobProxyStepTwo.cancelJob();
+ clientJobProxyStepOne1.waitForJobCompleteV2();
+ clientJobProxyStepOne2.waitForJobCompleteV2();
+ clientJobProxyStepTwo.waitForJobCompleteV2();
+
+ } finally {
+ if (engineClient != null) {
+ engineClient.close();
+ }
+ if (node1 != null) {
+ node1.shutdown();
+ }
+ if (node2 != null) {
+ node2.shutdown();
+ }
+ }
+ }
+
+ /**
+ * Create the test job config file basic on cluster_batch_fake_to_localfile_template.conf It
+ * will delete the test sink target path before return the final job config file path
+ *
+ * @param testCaseName testCaseName
+ * @param jobMode jobMode
+ * @param rowNumber row.num per FakeSource parallelism
+ * @param parallelism FakeSource parallelism
+ */
+ private String createTestResources(
+ @NonNull String testCaseName,
+ @NonNull JobMode jobMode,
+ long rowNumber,
+ int parallelism,
+ String templateFile)
+ throws IOException {
+ checkArgument(rowNumber > 0, "rowNumber must greater than 0");
+ checkArgument(parallelism > 0, "parallelism must greater than 0");
+ Map<String, String> valueMap = new HashMap<>();
+ valueMap.put(DYNAMIC_TEST_CASE_NAME, testCaseName);
+ valueMap.put(DYNAMIC_JOB_MODE, jobMode.toString());
+ valueMap.put(DYNAMIC_TEST_ROW_NUM_PER_PARALLELISM, String.valueOf(rowNumber));
+ valueMap.put(DYNAMIC_TEST_PARALLELISM, String.valueOf(parallelism));
+
+ String targetConfigFilePath =
+ File.separator
+ + "tmp"
+ + File.separator
+ + "test_conf"
+ + File.separator
+ + testCaseName
+ + ".conf";
+
+ TestUtils.createTestConfigFileFromTemplate(templateFile, valueMap, targetConfigFilePath);
+
+ return targetConfigFilePath;
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/resources/allocate-strategy/allocate_strategy_no_tag_with_system_load.conf b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/resources/allocate-strategy/allocate_strategy_no_tag_with_system_load.conf
new file mode 100644
index 0000000000..75f4b5942b
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/resources/allocate-strategy/allocate_strategy_no_tag_with_system_load.conf
@@ -0,0 +1,53 @@
+#
+# 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.
+#
+######
+###### This config file is a demonstration of streaming processing in seatunnel config
+######
+
+env {
+ job.mode = "${dynamic_job_mode}" # dynamic_job_mode will be replace to the final file name before test run
+ checkpoint.interval = 5000
+}
+
+source {
+ # This is a example source plugin **only for test and demonstrate the feature source plugin**
+ FakeSource {
+ row.num = ${dynamic_test_row_num_per_parallelism}
+ split.num = 5
+ split.read-interval = 3000
+ map.size = 10
+ array.size = 10
+ bytes.length = 10
+ string.length = 10
+ parallelism = ${dynamic_test_parallelism}
+ schema = {
+ fields {
+ c_string = string
+ c_boolean = boolean
+ }
+ }
+ }
+}
+
+transform {
+}
+
+sink {
+ Console{
+
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/resources/allocate-strategy/allocate_strategy_tag1_with_system_load.conf b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/resources/allocate-strategy/allocate_strategy_tag1_with_system_load.conf
new file mode 100644
index 0000000000..d53c00f3f9
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/resources/allocate-strategy/allocate_strategy_tag1_with_system_load.conf
@@ -0,0 +1,56 @@
+#
+# 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.
+#
+######
+###### This config file is a demonstration of streaming processing in seatunnel config
+######
+
+env {
+ job.mode = "${dynamic_job_mode}" # dynamic_job_mode will be replace to the final file name before test run
+ checkpoint.interval = 5000
+ tag_filter {
+ strategy = "system_load1"
+ }
+}
+
+source {
+ # This is a example source plugin **only for test and demonstrate the feature source plugin**
+ FakeSource {
+ row.num = ${dynamic_test_row_num_per_parallelism}
+ split.num = 5
+ split.read-interval = 3000
+ map.size = 10
+ array.size = 10
+ bytes.length = 10
+ string.length = 10
+ parallelism = ${dynamic_test_parallelism}
+ schema = {
+ fields {
+ c_string = string
+ c_boolean = boolean
+ }
+ }
+ }
+}
+
+transform {
+}
+
+sink {
+ Console{
+
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/resources/allocate-strategy/allocate_strategy_tag2_with_system_load.conf b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/resources/allocate-strategy/allocate_strategy_tag2_with_system_load.conf
new file mode 100644
index 0000000000..bfa834dcdf
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/resources/allocate-strategy/allocate_strategy_tag2_with_system_load.conf
@@ -0,0 +1,56 @@
+#
+# 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.
+#
+######
+###### This config file is a demonstration of streaming processing in seatunnel config
+######
+
+env {
+ job.mode = "${dynamic_job_mode}" # dynamic_job_mode will be replace to the final file name before test run
+ checkpoint.interval = 5000
+ tag_filter {
+ strategy = "system_load2"
+ }
+}
+
+source {
+ # This is a example source plugin **only for test and demonstrate the feature source plugin**
+ FakeSource {
+ row.num = ${dynamic_test_row_num_per_parallelism}
+ split.num = 5
+ split.read-interval = 3000
+ map.size = 10
+ array.size = 10
+ bytes.length = 10
+ string.length = 10
+ parallelism = ${dynamic_test_parallelism}
+ schema = {
+ fields {
+ c_string = string
+ c_boolean = boolean
+ }
+ }
+ }
+}
+
+transform {
+}
+
+sink {
+ Console{
+
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/resources/allocate-strategy/allocate_strategy_with_slot_ratio.conf b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/resources/allocate-strategy/allocate_strategy_with_slot_ratio.conf
new file mode 100644
index 0000000000..75f4b5942b
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/resources/allocate-strategy/allocate_strategy_with_slot_ratio.conf
@@ -0,0 +1,53 @@
+#
+# 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.
+#
+######
+###### This config file is a demonstration of streaming processing in seatunnel config
+######
+
+env {
+ job.mode = "${dynamic_job_mode}" # dynamic_job_mode will be replace to the final file name before test run
+ checkpoint.interval = 5000
+}
+
+source {
+ # This is a example source plugin **only for test and demonstrate the feature source plugin**
+ FakeSource {
+ row.num = ${dynamic_test_row_num_per_parallelism}
+ split.num = 5
+ split.read-interval = 3000
+ map.size = 10
+ array.size = 10
+ bytes.length = 10
+ string.length = 10
+ parallelism = ${dynamic_test_parallelism}
+ schema = {
+ fields {
+ c_string = string
+ c_boolean = boolean
+ }
+ }
+ }
+}
+
+transform {
+}
+
+sink {
+ Console{
+
+ }
+}
diff --git a/seatunnel-engine/pom.xml b/seatunnel-engine/pom.xml
index dcff054063..7a6b16bd0b 100644
--- a/seatunnel-engine/pom.xml
+++ b/seatunnel-engine/pom.xml
@@ -38,6 +38,7 @@
<properties>
<!-- SeaTunnel Engine use -->
<disruptor.version>3.4.4</disruptor.version>
+ <oshi.version>6.6.5</oshi.version>
</properties>
<dependencyManagement>
@@ -55,6 +56,11 @@
<version>${disruptor.version}</version>
</dependency>
<!-- SeaTunnel engine use end -->
+ <dependency>
+ <groupId>com.github.oshi</groupId>
+ <artifactId>oshi-core</artifactId>
+ <version>${oshi.version}</version>
+ </dependency>
</dependencies>
</dependencyManagement>
diff --git a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/YamlSeaTunnelDomConfigProcessor.java b/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/YamlSeaTunnelDomConfigProcessor.java
index 310485a524..4c4d62132c 100644
--- a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/YamlSeaTunnelDomConfigProcessor.java
+++ b/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/YamlSeaTunnelDomConfigProcessor.java
@@ -17,6 +17,7 @@
package org.apache.seatunnel.engine.common.config;
+import org.apache.seatunnel.engine.common.config.server.AllocateStrategy;
import org.apache.seatunnel.engine.common.config.server.CheckpointConfig;
import org.apache.seatunnel.engine.common.config.server.CheckpointStorageConfig;
import org.apache.seatunnel.engine.common.config.server.ConnectorJarHAStorageConfig;
@@ -100,6 +101,9 @@ public class YamlSeaTunnelDomConfigProcessor extends AbstractDomConfigProcessor
} else if (ServerConfigOptions.SLOT_NUM.key().equals(name)) {
slotServiceConfig.setSlotNum(
getIntegerValue(ServerConfigOptions.SLOT_NUM.key(), getTextContent(node)));
+ } else if (ServerConfigOptions.SLOT_ALLOCATE_STRATEGY.key().equals(name)) {
+ slotServiceConfig.setAllocateStrategy(
+ AllocateStrategy.valueOf(getTextContent(node).toUpperCase()));
} else {
LOGGER.warning("Unrecognized element: " + name);
}
diff --git a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/AllocateStrategy.java b/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/AllocateStrategy.java
new file mode 100644
index 0000000000..569816e7b0
--- /dev/null
+++ b/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/AllocateStrategy.java
@@ -0,0 +1,72 @@
+/*
+ * 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.common.config.server;
+
+import java.io.Serializable;
+
+/**
+ * Scheduling and Resource Allocation Logic <br>
+ * <br>
+ * 1. <b>Time Weight Design</b>: Time weight affects scheduling priority, where recent data has
+ * higher weights <br>
+ * and older data decays. Weights follow a distribution of {4, 2, 2, 1, 1}, normalized as: <br>
+ * `timeWeight = currentWeight / 10.0`. When fewer than 5 data points are available (e.g., during
+ * startup), <br>
+ * weights are dynamically adjusted. <br>
+ * <br>
+ * 2. <b>Resource Utilization Calculation</b>: CPU and memory idle rates are combined using weighted
+ * evaluation: <br>
+ * `resourceIdleRate = ((1 - cpuUtilization) * cpuWeight + (1 - memoryUtilization) * memoryWeight) /
+ * (cpuWeight + memoryWeight)`. <br>
+ * The weights (e.g., `cpuWeight = 0.6`, `memoryWeight = 0.4`) are customizable based on specific
+ * needs. <br>
+ * <br>
+ * 3. <b>Time Decay and Priority Formula</b>: With time-weight decay applied, the aggregated
+ * resource idle rate is: <br>
+ * `aggregatedResourceIdleRate = Σ[((1 - cpuUtilization[i]) * cpuWeight + (1 - memoryUtilization[i])
+ * * memoryWeight) / (cpuWeight + memoryWeight) * timeWeight[i]]` for the latest 5 data points. <br>
+ * <br>
+ * 4. <b>Dynamic Adjustment During Slot Allocation</b>: Allocating slots updates idle rates
+ * dynamically: <br>
+ * - Per-slot resource usage: `perSlotResourceUsage = (1 - aggregatedResourceIdleRate) /
+ * allocatedSlots`. <br>
+ * - Updated idle rate: `updatedIdleRate = aggregatedResourceIdleRate - perSlotResourceUsage`. <br>
+ * A default slot usage of 10% prevents over-allocation and ensures reasonable load distribution
+ * until monitoring data refines the estimate. <br>
+ * <br>
+ * 5. <b>Balance Factor</b>: To avoid resource concentration, a balance factor adjusts scheduling
+ * priority: <br>
+ * `balanceFactor = 1 - (slotsUsed / totalSlots)`. The overall priority is weighted as: <br>
+ * `weightedPriority = alpha * updatedIdleRate + beta * balanceFactor`, where `alpha` (e.g., 0.7)
+ * emphasizes resource utilization and `beta` (e.g., 0.3) ensures load balance. <br>
+ * <br>
+ * 6. <b>Dynamic Adjustment Logic</b>: Periodic collection of CPU and memory utilization data
+ * (latest 5 entries) <br>
+ * ensures real-time updates. Slot allocations dynamically balance resources, preventing overloads
+ * and refining decisions. <br>
+ * <br>
+ * Example: If Node A has 10 free slots and Node B has 20, but Node A consistently shows higher
+ * priority after <br>
+ * applying these formulas, it may indicate suboptimal slot configuration on Node B, requiring
+ * adjustment. <br>
+ */
+public enum AllocateStrategy implements Serializable {
+ SYSTEM_LOAD,
+ SLOT_RATIO,
+ RANDOM
+}
diff --git a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/ServerConfigOptions.java b/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/ServerConfigOptions.java
index e0de761742..119d8c9c61 100644
--- a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/ServerConfigOptions.java
+++ b/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/ServerConfigOptions.java
@@ -115,6 +115,13 @@ public class ServerConfigOptions {
.defaultValue(new CheckpointStorageConfig())
.withDescription("The checkpoint storage configuration.");
+ public static final Option<AllocateStrategy> SLOT_ALLOCATE_STRATEGY =
+ Options.key("slot-allocate-strategy")
+ .enumType(AllocateStrategy.class)
+ .defaultValue(AllocateStrategy.RANDOM)
+ .withDescription(
+ "When the strategy is SLOT_RATIO, the system allocates tasks based on the slot usage ratio, with priority given to workers with low usage rates; When the strategy is SYSTEM_LOAD, the system allocates tasks based on server load, with priority given to workers with lower load.");
+
public static final Option<SlotServiceConfig> SLOT_SERVICE =
Options.key("slot-service")
.type(new TypeReference<SlotServiceConfig>() {})
diff --git a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java b/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java
index 51f8945969..92f70fda3b 100644
--- a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java
+++ b/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java
@@ -26,6 +26,9 @@ import static com.hazelcast.internal.util.Preconditions.checkPositive;
@Data
public class SlotServiceConfig implements Serializable {
+ private AllocateStrategy allocateStrategy =
+ ServerConfigOptions.SLOT_ALLOCATE_STRATEGY.defaultValue();
+
private boolean dynamicSlot = ServerConfigOptions.DYNAMIC_SLOT.defaultValue();
private int slotNum = ServerConfigOptions.SLOT_NUM.defaultValue();
diff --git a/seatunnel-engine/seatunnel-engine-server/pom.xml b/seatunnel-engine/seatunnel-engine-server/pom.xml
index 152e741282..7e36f2c98e 100644
--- a/seatunnel-engine/seatunnel-engine-server/pom.xml
+++ b/seatunnel-engine/seatunnel-engine-server/pom.xml
@@ -28,6 +28,10 @@
<name>SeaTunnel : Engine : Server</name>
<dependencies>
+ <dependency>
+ <groupId>com.github.oshi</groupId>
+ <artifactId>oshi-core</artifactId>
+ </dependency>
<dependency>
<groupId>org.apache.seatunnel</groupId>
<artifactId>seatunnel-engine-core</artifactId>
diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java
index a8fa0de57a..e97b10b450 100644
--- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java
@@ -68,7 +68,11 @@ import org.apache.seatunnel.engine.server.execution.TaskGroupLocation;
import org.apache.seatunnel.engine.server.execution.TaskLocation;
import org.apache.seatunnel.engine.server.metrics.JobMetricsUtil;
import org.apache.seatunnel.engine.server.metrics.SeaTunnelMetricsContext;
+import org.apache.seatunnel.engine.server.resourcemanager.AbstractResourceManager;
import org.apache.seatunnel.engine.server.resourcemanager.ResourceManager;
+import org.apache.seatunnel.engine.server.resourcemanager.allocation.strategy.SlotAllocationStrategy;
+import org.apache.seatunnel.engine.server.resourcemanager.allocation.strategy.SlotRatioStrategy;
+import org.apache.seatunnel.engine.server.resourcemanager.allocation.strategy.SystemLoadStrategy;
import org.apache.seatunnel.engine.server.resourcemanager.resource.SlotProfile;
import org.apache.seatunnel.engine.server.task.operation.CleanTaskGroupContextOperation;
import org.apache.seatunnel.engine.server.task.operation.GetTaskGroupMetricsOperation;
@@ -373,6 +377,24 @@ public class JobMaster {
*/
public boolean preApplyResources(SubPlan subPlan) {
+ // When starting to apply for task resources, reset the worker's slot allocation information
+ // Mainly used in two scenarios:
+ // 1. When based on the SYSTEM_LOAD strategy, the system load cannot change dynamically, and
+ // the resources used by each slot need to be calculated and inferred
+ // 2. When based on the SLOT_RATIO strategy, registerWorker is not updated in real time, and
+ // is used to record the slot application status
+ // ((AbstractResourceManager) resourceManager)
+ // .setWorkerAssignedSlots(new ConcurrentHashMap<>());
+ SlotAllocationStrategy slotAllocationStrategy =
+ ((AbstractResourceManager) resourceManager).getSlotAllocationStrategy();
+ if (slotAllocationStrategy instanceof SlotRatioStrategy) {
+ ((SlotRatioStrategy) slotAllocationStrategy)
+ .setWorkerAssignedSlots(new ConcurrentHashMap<>());
+ } else if (slotAllocationStrategy instanceof SystemLoadStrategy) {
+ ((SystemLoadStrategy) slotAllocationStrategy)
+ .setWorkerAssignedSlots(new ConcurrentHashMap<>());
+ }
+
Map<TaskGroupLocation, CompletableFuture<SlotProfile>> preApplyResourceFutures =
new HashMap<>();
@@ -470,6 +492,7 @@ public class JobMaster {
private void preApplyResourcesForSubPlan(
SubPlan subPlan,
Map<TaskGroupLocation, CompletableFuture<SlotProfile>> preApplyResourceFutures) {
+
Map<TaskGroupLocation, CompletableFuture<SlotProfile>> coordinatorFutures = new HashMap<>();
subPlan.getCoordinatorVertexList()
.forEach(
@@ -490,6 +513,7 @@ public class JobMaster {
preApplyResourceFutures.putAll(coordinatorFutures);
preApplyResourceFutures.putAll(taskFutures);
+ LOGGER.fine("preApplyResourceFutures size: " + preApplyResourceFutures.size());
}
public void run() {
diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/AbstractResourceManager.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/AbstractResourceManager.java
index 6d44bda504..32cf63e06e 100644
--- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/AbstractResourceManager.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/AbstractResourceManager.java
@@ -20,6 +20,10 @@ package org.apache.seatunnel.engine.server.resourcemanager;
import org.apache.seatunnel.engine.common.config.EngineConfig;
import org.apache.seatunnel.engine.common.runtime.ExecutionMode;
import org.apache.seatunnel.engine.common.utils.concurrent.CompletableFuture;
+import org.apache.seatunnel.engine.server.resourcemanager.allocation.strategy.RandomStrategy;
+import org.apache.seatunnel.engine.server.resourcemanager.allocation.strategy.SlotAllocationStrategy;
+import org.apache.seatunnel.engine.server.resourcemanager.allocation.strategy.SlotRatioStrategy;
+import org.apache.seatunnel.engine.server.resourcemanager.allocation.strategy.SystemLoadStrategy;
import org.apache.seatunnel.engine.server.resourcemanager.opeartion.ReleaseSlotOperation;
import org.apache.seatunnel.engine.server.resourcemanager.opeartion.ResetResourceOperation;
import org.apache.seatunnel.engine.server.resourcemanager.opeartion.SyncWorkerProfileOperation;
@@ -33,6 +37,7 @@ import com.hazelcast.cluster.Member;
import com.hazelcast.internal.services.MembershipServiceEvent;
import com.hazelcast.spi.impl.NodeEngine;
import com.hazelcast.spi.impl.operationservice.Operation;
+import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
@@ -40,6 +45,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
@@ -49,21 +55,36 @@ public abstract class AbstractResourceManager implements ResourceManager {
private static final long DEFAULT_WORKER_CHECK_INTERVAL = 500;
- protected final ConcurrentMap<Address, WorkerProfile> registerWorker;
+ @Getter public final ConcurrentMap<Address, WorkerProfile> registerWorker;
private final NodeEngine nodeEngine;
private final ExecutionMode mode;
- private final EngineConfig engineConfig;
+ @Getter private final EngineConfig engineConfig;
private volatile boolean isRunning = true;
+ @Getter private final SlotAllocationStrategy slotAllocationStrategy;
+
public AbstractResourceManager(NodeEngine nodeEngine, EngineConfig engineConfig) {
this.registerWorker = new ConcurrentHashMap<>();
this.nodeEngine = nodeEngine;
this.engineConfig = engineConfig;
this.mode = engineConfig.getMode();
+
+ switch (engineConfig.getSlotServiceConfig().getAllocateStrategy()) {
+ case SYSTEM_LOAD:
+ this.slotAllocationStrategy = new SystemLoadStrategy();
+ break;
+ case SLOT_RATIO:
+ this.slotAllocationStrategy = new SlotRatioStrategy();
+ break;
+ case RANDOM:
+ default:
+ this.slotAllocationStrategy = new RandomStrategy();
+ break;
+ }
}
@Override
@@ -98,6 +119,7 @@ public abstract class AbstractResourceManager implements ResourceManager {
}))
.collect(Collectors.toList());
futures.forEach(CompletableFuture::join);
+
log.info("registerWorker: {}", registerWorker);
}
@@ -151,7 +173,8 @@ public abstract class AbstractResourceManager implements ResourceManager {
log.error("No matched worker with tag filter {}.", tagFilter);
throw new NoEnoughResourceException();
}
- return new ResourceRequestHandler(jobId, resourceProfile, matchedWorker, this)
+ return new ResourceRequestHandler(
+ jobId, resourceProfile, matchedWorker, this, slotAllocationStrategy)
.request(tagFilter);
}
@@ -240,6 +263,18 @@ public abstract class AbstractResourceManager implements ResourceManager {
log.debug("received worker heartbeat from: " + workerProfile.getAddress());
}
registerWorker.put(workerProfile.getAddress(), workerProfile);
+
+ this.updateWorkerLoad(workerProfile);
+ }
+
+ /** Update worker load info. */
+ private void updateWorkerLoad(WorkerProfile workerProfile) {
+ if (slotAllocationStrategy instanceof SystemLoadStrategy
+ && Objects.nonNull(workerProfile.getSystemLoadInfo())) {
+ ((SystemLoadStrategy) slotAllocationStrategy)
+ .updateWorkerLoad(
+ workerProfile.getAddress(), workerProfile.getSystemLoadInfo());
+ }
}
@Override
diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceManager.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceManager.java
index 31a5f5922e..18623873c0 100644
--- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceManager.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceManager.java
@@ -22,10 +22,12 @@ import org.apache.seatunnel.engine.server.resourcemanager.resource.ResourceProfi
import org.apache.seatunnel.engine.server.resourcemanager.resource.SlotProfile;
import org.apache.seatunnel.engine.server.resourcemanager.worker.WorkerProfile;
+import com.hazelcast.cluster.Address;
import com.hazelcast.internal.services.MembershipServiceEvent;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.ConcurrentMap;
public interface ResourceManager {
void init();
@@ -67,4 +69,6 @@ public interface ResourceManager {
List<SlotProfile> getAssignedSlots(Map<String, String> tags);
int workerCount(Map<String, String> tags);
+
+ ConcurrentMap<Address, WorkerProfile> getRegisterWorker();
}
diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceRequestHandler.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceRequestHandler.java
index 107b0190d0..92767e6fc1 100644
--- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceRequestHandler.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceRequestHandler.java
@@ -19,8 +19,10 @@ package org.apache.seatunnel.engine.server.resourcemanager;
import org.apache.seatunnel.shade.com.google.common.annotations.VisibleForTesting;
+import org.apache.seatunnel.engine.common.config.server.AllocateStrategy;
import org.apache.seatunnel.engine.common.runtime.DeployType;
import org.apache.seatunnel.engine.common.utils.concurrent.CompletableFuture;
+import org.apache.seatunnel.engine.server.resourcemanager.allocation.strategy.SlotAllocationStrategy;
import org.apache.seatunnel.engine.server.resourcemanager.opeartion.RequestSlotOperation;
import org.apache.seatunnel.engine.server.resourcemanager.resource.ResourceProfile;
import org.apache.seatunnel.engine.server.resourcemanager.resource.SlotProfile;
@@ -39,6 +41,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
+import java.util.stream.Collectors;
import static com.hazelcast.jet.impl.util.ExceptionUtil.withTryCatch;
@@ -63,17 +66,25 @@ public class ResourceRequestHandler {
private final AbstractResourceManager resourceManager;
+ private final AllocateStrategy allocateStrategy;
+
+ private final SlotAllocationStrategy slotAllocationStrategy;
+
public ResourceRequestHandler(
long jobId,
List<ResourceProfile> resourceProfile,
ConcurrentMap<Address, WorkerProfile> registerWorker,
- AbstractResourceManager resourceManager) {
+ AbstractResourceManager resourceManager,
+ SlotAllocationStrategy slotAllocationStrategy) {
this.completableFuture = new CompletableFuture<>();
this.resultSlotProfiles = new ConcurrentHashMap<>();
this.jobId = jobId;
this.resourceProfile = resourceProfile;
this.registerWorker = registerWorker;
this.resourceManager = resourceManager;
+ this.allocateStrategy =
+ resourceManager.getEngineConfig().getSlotServiceConfig().getAllocateStrategy();
+ this.slotAllocationStrategy = slotAllocationStrategy;
}
public CompletableFuture<List<SlotProfile>> request(Map<String, String> tags) {
@@ -145,6 +156,7 @@ public class ResourceRequestHandler {
private List<CompletableFuture<SlotAndWorkerProfile>> requestSlots(
List<ResourceProfile> requestProfile) {
List<CompletableFuture<SlotAndWorkerProfile>> allRequestFuture = new ArrayList<>();
+
for (int i = 0; i < requestProfile.size(); i++) {
ResourceProfile r = requestProfile.get(i);
Optional<WorkerProfile> workerProfile = preCheckWorkerResource(r);
@@ -208,12 +220,10 @@ public class ResourceRequestHandler {
@VisibleForTesting
public Optional<WorkerProfile> preCheckWorkerResource(ResourceProfile r) {
- // Shuffle the order to ensure random selection of workers
List<WorkerProfile> workerProfiles =
Arrays.asList(registerWorker.values().toArray(new WorkerProfile[0]));
- Collections.shuffle(workerProfiles);
- // Check if there are still unassigned slots
- Optional<WorkerProfile> workerProfile =
+
+ List<WorkerProfile> availableWorkers =
workerProfiles.stream()
.filter(
worker ->
@@ -222,10 +232,16 @@ public class ResourceRequestHandler {
slot ->
slot.getResourceProfile()
.enoughThan(r)))
- .findAny();
+ .collect(Collectors.toList());
+
+ Optional<WorkerProfile> workerProfile =
+ slotAllocationStrategy.selectWorker(availableWorkers);
if (!workerProfile.isPresent()) {
// Check if there are still unassigned resources
+ if (allocateStrategy == AllocateStrategy.RANDOM) {
+ Collections.shuffle(workerProfiles);
+ }
workerProfile =
workerProfiles.stream()
.filter(WorkerProfile::isDynamicSlot)
diff --git a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/allocation/strategy/RandomStrategy.java
similarity index 58%
copy from seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java
copy to seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/allocation/strategy/RandomStrategy.java
index 51f8945969..2c268bab13 100644
--- a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/allocation/strategy/RandomStrategy.java
@@ -15,23 +15,20 @@
* limitations under the License.
*/
-package org.apache.seatunnel.engine.common.config.server;
+package org.apache.seatunnel.engine.server.resourcemanager.allocation.strategy;
-import lombok.Data;
+import org.apache.seatunnel.engine.server.resourcemanager.worker.WorkerProfile;
-import java.io.Serializable;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
-import static com.hazelcast.internal.util.Preconditions.checkPositive;
+/** RandomStrategy is a strategy that selects the worker randomly. */
+public class RandomStrategy implements SlotAllocationStrategy {
-@Data
-public class SlotServiceConfig implements Serializable {
-
- private boolean dynamicSlot = ServerConfigOptions.DYNAMIC_SLOT.defaultValue();
-
- private int slotNum = ServerConfigOptions.SLOT_NUM.defaultValue();
-
- public void setSlotNum(int slotNum) {
- checkPositive(slotNum, ServerConfigOptions.SLOT_NUM + " must be > 0");
- this.slotNum = slotNum;
+ @Override
+ public Optional<WorkerProfile> selectWorker(List<WorkerProfile> availableWorkers) {
+ Collections.shuffle(availableWorkers);
+ return availableWorkers.stream().findFirst();
}
}
diff --git a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/allocation/strategy/SlotAllocationStrategy.java
similarity index 59%
copy from seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java
copy to seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/allocation/strategy/SlotAllocationStrategy.java
index 51f8945969..e63419f2b8 100644
--- a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/allocation/strategy/SlotAllocationStrategy.java
@@ -15,23 +15,14 @@
* limitations under the License.
*/
-package org.apache.seatunnel.engine.common.config.server;
+package org.apache.seatunnel.engine.server.resourcemanager.allocation.strategy;
-import lombok.Data;
+import org.apache.seatunnel.engine.server.resourcemanager.worker.WorkerProfile;
-import java.io.Serializable;
+import java.util.List;
+import java.util.Optional;
-import static com.hazelcast.internal.util.Preconditions.checkPositive;
-
-@Data
-public class SlotServiceConfig implements Serializable {
-
- private boolean dynamicSlot = ServerConfigOptions.DYNAMIC_SLOT.defaultValue();
-
- private int slotNum = ServerConfigOptions.SLOT_NUM.defaultValue();
-
- public void setSlotNum(int slotNum) {
- checkPositive(slotNum, ServerConfigOptions.SLOT_NUM + " must be > 0");
- this.slotNum = slotNum;
- }
+/** Slot allocation strategy interface. */
+public interface SlotAllocationStrategy {
+ Optional<WorkerProfile> selectWorker(List<WorkerProfile> availableWorkers);
}
diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/allocation/strategy/SlotRatioStrategy.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/allocation/strategy/SlotRatioStrategy.java
new file mode 100644
index 0000000000..bac21bfdc7
--- /dev/null
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/allocation/strategy/SlotRatioStrategy.java
@@ -0,0 +1,81 @@
+/*
+ * 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.resourcemanager.allocation.strategy;
+
+import org.apache.seatunnel.engine.server.resourcemanager.resource.SlotAssignedProfile;
+import org.apache.seatunnel.engine.server.resourcemanager.worker.WorkerProfile;
+
+import com.hazelcast.cluster.Address;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/** SlotRatioStrategy is a strategy that selects the worker with the lowest slot usage rate. */
+public class SlotRatioStrategy implements SlotAllocationStrategy {
+
+ @Getter @Setter private Map<Address, SlotAssignedProfile> workerAssignedSlots;
+
+ @Override
+ public Optional<WorkerProfile> selectWorker(List<WorkerProfile> availableWorkers) {
+
+ Optional<WorkerProfile> workerProfile =
+ availableWorkers.stream().min(Comparator.comparingDouble(this::calculateSlotUsage));
+ workerProfile.ifPresent(
+ profile -> {
+ workerAssignedSlots.merge(
+ profile.getAddress(),
+ new SlotAssignedProfile(0.0, 1, profile.getAssignedSlots().length),
+ (oldVal, newVal) ->
+ new SlotAssignedProfile(
+ 0.0,
+ oldVal.getCurrentTaskAssignedSlotsNum() + 1,
+ oldVal.getAssignedSlotsNum()));
+ });
+ return workerProfile;
+ }
+
+ /**
+ * Calculate the slot usage rate of the worker
+ *
+ * @param worker WorkerProfile
+ * @return slot usage rate, range 0.0-1.0
+ */
+ private double calculateSlotUsage(WorkerProfile worker) {
+ SlotAssignedProfile slotAssignedProfile = workerAssignedSlots.get(worker.getAddress());
+ // If we manually record the number of assigned slots, we use that number, since
+ // worker.getAssignedSlots is not updated in real time.
+ int assignedSlots =
+ (slotAssignedProfile != null)
+ ? slotAssignedProfile.getCurrentTaskAssignedSlotsNum()
+ : worker.getAssignedSlots().length;
+ workerAssignedSlots.put(
+ worker.getAddress(), new SlotAssignedProfile(0.0, assignedSlots, 0));
+
+ int totalSlots = worker.getUnassignedSlots().length + worker.getAssignedSlots().length;
+ if (totalSlots == 0) {
+ // When using dynamic slots, the default usage rate is 50%
+ return 0.5;
+ }
+
+ return (double) assignedSlots / totalSlots;
+ }
+}
diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/allocation/strategy/SystemLoadStrategy.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/allocation/strategy/SystemLoadStrategy.java
new file mode 100644
index 0000000000..c36f36d048
--- /dev/null
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/allocation/strategy/SystemLoadStrategy.java
@@ -0,0 +1,83 @@
+/*
+ * 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.resourcemanager.allocation.strategy;
+
+import org.apache.seatunnel.shade.com.google.common.collect.EvictingQueue;
+
+import org.apache.seatunnel.engine.server.resourcemanager.resource.SlotAssignedProfile;
+import org.apache.seatunnel.engine.server.resourcemanager.resource.SystemLoadInfo;
+import org.apache.seatunnel.engine.server.resourcemanager.worker.WorkerProfile;
+import org.apache.seatunnel.engine.server.utils.SystemLoadCalculate;
+
+import com.hazelcast.cluster.Address;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+
+/** SystemLoadStrategy is a strategy that selects the worker with the lowest system load. */
+public class SystemLoadStrategy implements SlotAllocationStrategy {
+ private final Map<Address, EvictingQueue<SystemLoadInfo>> workerLoadMap;
+
+ @Getter @Setter private Map<Address, SlotAssignedProfile> workerAssignedSlots;
+
+ public SystemLoadStrategy(Map<Address, EvictingQueue<SystemLoadInfo>> workerLoadMap) {
+ this.workerLoadMap = workerLoadMap;
+ }
+
+ public SystemLoadStrategy() {
+ this.workerLoadMap = new ConcurrentHashMap<>();
+ }
+
+ public void updateWorkerLoad(Address address, SystemLoadInfo systemLoadInfo) {
+ workerLoadMap.computeIfAbsent(address, k -> EvictingQueue.create(5)).add(systemLoadInfo);
+ }
+
+ @Override
+ public Optional<WorkerProfile> selectWorker(List<WorkerProfile> availableWorkers) {
+ Optional<WorkerProfile> workerProfile =
+ availableWorkers.stream()
+ .max(
+ Comparator.comparingDouble(
+ w -> calculateWeight(w, workerAssignedSlots)));
+
+ workerProfile.ifPresent(
+ profile -> {
+ workerAssignedSlots.merge(
+ profile.getAddress(),
+ new SlotAssignedProfile(0.0, 1, profile.getAssignedSlots().length),
+ (oldVal, newVal) ->
+ new SlotAssignedProfile(
+ oldVal.getSingleSlotUseResource(),
+ oldVal.getCurrentTaskAssignedSlotsNum() + 1,
+ oldVal.getAssignedSlotsNum()));
+ });
+ return workerProfile;
+ }
+
+ public Double calculateWeight(
+ WorkerProfile workerProfile, Map<Address, SlotAssignedProfile> workerAssignedSlots) {
+ SystemLoadCalculate systemLoadCalculate = new SystemLoadCalculate();
+ return systemLoadCalculate.calculate(
+ workerLoadMap.get(workerProfile.getAddress()), workerProfile, workerAssignedSlots);
+ }
+}
diff --git a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/resource/SlotAssignedProfile.java
similarity index 61%
copy from seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java
copy to seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/resource/SlotAssignedProfile.java
index 51f8945969..e505fd7123 100644
--- a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/resource/SlotAssignedProfile.java
@@ -15,23 +15,22 @@
* limitations under the License.
*/
-package org.apache.seatunnel.engine.common.config.server;
+package org.apache.seatunnel.engine.server.resourcemanager.resource;
+import lombok.AllArgsConstructor;
import lombok.Data;
-import java.io.Serializable;
-
-import static com.hazelcast.internal.util.Preconditions.checkPositive;
-
+/** Record resource usage */
@Data
-public class SlotServiceConfig implements Serializable {
+@AllArgsConstructor
+public class SlotAssignedProfile {
- private boolean dynamicSlot = ServerConfigOptions.DYNAMIC_SLOT.defaultValue();
+ /** Record the resource usage of a single slot */
+ private double singleSlotUseResource;
- private int slotNum = ServerConfigOptions.SLOT_NUM.defaultValue();
+ /** The number of slots currently assigned to the task. */
+ private Integer currentTaskAssignedSlotsNum;
- public void setSlotNum(int slotNum) {
- checkPositive(slotNum, ServerConfigOptions.SLOT_NUM + " must be > 0");
- this.slotNum = slotNum;
- }
+ /** The number of slots currently assigned to the worker. */
+ private Integer assignedSlotsNum;
}
diff --git a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/resource/SystemLoadInfo.java
similarity index 63%
copy from seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java
copy to seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/resource/SystemLoadInfo.java
index 51f8945969..5af0062b4b 100644
--- a/seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/SlotServiceConfig.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/resource/SystemLoadInfo.java
@@ -15,23 +15,19 @@
* limitations under the License.
*/
-package org.apache.seatunnel.engine.common.config.server;
+package org.apache.seatunnel.engine.server.resourcemanager.resource;
+import lombok.AllArgsConstructor;
import lombok.Data;
+import lombok.NoArgsConstructor;
import java.io.Serializable;
-import static com.hazelcast.internal.util.Preconditions.checkPositive;
-
+@AllArgsConstructor
+@NoArgsConstructor
@Data
-public class SlotServiceConfig implements Serializable {
-
- private boolean dynamicSlot = ServerConfigOptions.DYNAMIC_SLOT.defaultValue();
-
- private int slotNum = ServerConfigOptions.SLOT_NUM.defaultValue();
+public class SystemLoadInfo implements Serializable {
- public void setSlotNum(int slotNum) {
- checkPositive(slotNum, ServerConfigOptions.SLOT_NUM + " must be > 0");
- this.slotNum = slotNum;
- }
+ private Double memPercentage;
+ private Double cpuPercentage;
}
diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/worker/WorkerProfile.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/worker/WorkerProfile.java
index f357a690da..d898e8c123 100644
--- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/worker/WorkerProfile.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/worker/WorkerProfile.java
@@ -19,13 +19,13 @@ package org.apache.seatunnel.engine.server.resourcemanager.worker;
import org.apache.seatunnel.engine.server.resourcemanager.resource.ResourceProfile;
import org.apache.seatunnel.engine.server.resourcemanager.resource.SlotProfile;
+import org.apache.seatunnel.engine.server.resourcemanager.resource.SystemLoadInfo;
import org.apache.seatunnel.engine.server.serializable.ResourceDataSerializerHook;
import com.hazelcast.cluster.Address;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
-import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.IOException;
@@ -35,7 +35,6 @@ import java.util.Map;
* Used to describe the status of the current Worker, including address and resource assign status
*/
@Data
-@AllArgsConstructor
public class WorkerProfile implements IdentifiedDataSerializable {
private Address address;
@@ -52,11 +51,30 @@ public class WorkerProfile implements IdentifiedDataSerializable {
private Map<String, String> attributes;
+ private SystemLoadInfo systemLoadInfo;
+
public WorkerProfile(Address address) {
this.address = address;
this.unassignedResource = new ResourceProfile();
}
+ public WorkerProfile(
+ Address address,
+ ResourceProfile profile,
+ ResourceProfile unassignedResource,
+ boolean dynamicSlot,
+ SlotProfile[] assignedSlots,
+ SlotProfile[] unassignedSlots,
+ Map<String, String> attributes) {
+ this.address = address;
+ this.profile = profile;
+ this.unassignedResource = unassignedResource;
+ this.dynamicSlot = dynamicSlot;
+ this.assignedSlots = assignedSlots;
+ this.unassignedSlots = unassignedSlots;
+ this.attributes = attributes;
+ }
+
public WorkerProfile() {
address = new Address();
}
@@ -86,6 +104,7 @@ public class WorkerProfile implements IdentifiedDataSerializable {
}
out.writeBoolean(dynamicSlot);
out.writeObject(attributes);
+ out.writeObject(systemLoadInfo);
}
@Override
@@ -105,5 +124,6 @@ public class WorkerProfile implements IdentifiedDataSerializable {
}
dynamicSlot = in.readBoolean();
attributes = in.readObject();
+ systemLoadInfo = in.readObject();
}
}
diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/service/slot/DefaultSlotService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/service/slot/DefaultSlotService.java
index 3a5e27171c..f0903ee155 100644
--- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/service/slot/DefaultSlotService.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/service/slot/DefaultSlotService.java
@@ -17,6 +17,7 @@
package org.apache.seatunnel.engine.server.service.slot;
+import org.apache.seatunnel.engine.common.config.server.AllocateStrategy;
import org.apache.seatunnel.engine.common.config.server.SlotServiceConfig;
import org.apache.seatunnel.engine.common.utils.IdGenerator;
import org.apache.seatunnel.engine.server.TaskExecutionService;
@@ -25,6 +26,7 @@ import org.apache.seatunnel.engine.server.resourcemanager.resource.CPU;
import org.apache.seatunnel.engine.server.resourcemanager.resource.Memory;
import org.apache.seatunnel.engine.server.resourcemanager.resource.ResourceProfile;
import org.apache.seatunnel.engine.server.resourcemanager.resource.SlotProfile;
+import org.apache.seatunnel.engine.server.resourcemanager.resource.SystemLoadInfo;
import org.apache.seatunnel.engine.server.resourcemanager.worker.WorkerProfile;
import org.apache.seatunnel.engine.server.utils.NodeEngineUtil;
@@ -33,7 +35,14 @@ import com.hazelcast.logging.Logger;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.impl.operationservice.Operation;
import com.hazelcast.spi.impl.operationservice.impl.InvocationFuture;
+import lombok.SneakyThrows;
+import oshi.SystemInfo;
+import oshi.hardware.CentralProcessor;
+import oshi.hardware.HardwareAbstractionLayer;
+import java.lang.management.ManagementFactory;
+import java.lang.management.MemoryMXBean;
+import java.lang.management.MemoryUsage;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@@ -41,6 +50,7 @@ import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/** The slot service of seatunnel server, used for manage slot in worker. */
@@ -48,6 +58,7 @@ public class DefaultSlotService implements SlotService {
private static final ILogger LOGGER = Logger.getLogger(DefaultSlotService.class);
private static final long DEFAULT_HEARTBEAT_TIMEOUT = 5000;
+ private static final int SYSTEM_LOAD_SEND_INTERVAL = 2;
private final NodeEngineImpl nodeEngine;
private AtomicReference<ResourceProfile> unassignedResource;
@@ -96,13 +107,41 @@ public class DefaultSlotService implements SlotService {
initFixedSlots();
}
unassignedResource.set(getNodeResource());
+ AtomicInteger systemLoadSendCountDown = new AtomicInteger(SYSTEM_LOAD_SEND_INTERVAL);
scheduledExecutorService.scheduleAtFixedRate(
() -> {
try {
LOGGER.fine(
"start send heartbeat to resource manager, this address: "
+ nodeEngine.getClusterService().getThisAddress());
- sendToMaster(new WorkerHeartbeatOperation(getWorkerProfile())).join();
+ // Must first obtain SYSTEM_LOAD and then obtain workProfile. If you obtain
+ // workProfile first and then obtain SYSTEM_LOAD, resource information will
+ // be reported inaccurately.
+ SystemLoadInfo systemLoadInfo =
+ Optional.of(systemLoadSendCountDown.decrementAndGet())
+ .filter(
+ count ->
+ count == 0
+ && config.getAllocateStrategy()
+ == AllocateStrategy
+ .SYSTEM_LOAD)
+ .map(
+ count -> {
+ systemLoadSendCountDown.set(
+ SYSTEM_LOAD_SEND_INTERVAL);
+ SystemLoadInfo info = new SystemLoadInfo();
+ info.setCpuPercentage(getCpuPercentage());
+ info.setMemPercentage(getMemPercentage());
+ LOGGER.fine("send system load info to master");
+ return info;
+ })
+ .orElse(null);
+
+ WorkerProfile workerProfile = getWorkerProfile();
+ Optional.ofNullable(systemLoadInfo)
+ .ifPresent(workerProfile::setSystemLoadInfo);
+
+ sendToMaster(new WorkerHeartbeatOperation(workerProfile)).join();
} catch (Exception e) {
LOGGER.warning(
"failed send heartbeat to resource manager, will retry later. this address: "
@@ -276,4 +315,45 @@ public class DefaultSlotService implements SlotService {
public <E> InvocationFuture<E> sendToMaster(Operation operation) {
return NodeEngineUtil.sendOperationToMasterNode(nodeEngine, operation);
}
+
+ public double getMemPercentage() {
+ MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean();
+ MemoryUsage heapMemoryUsage = memoryMxBean.getHeapMemoryUsage();
+ return ((double) heapMemoryUsage.getUsed() / (double) heapMemoryUsage.getMax());
+ }
+
+ @SneakyThrows
+ public double getCpuPercentage() {
+ // Create a SystemInfo object to access hardware information
+ SystemInfo si = new SystemInfo();
+ // Get the hardware abstraction layer
+ HardwareAbstractionLayer hal = si.getHardware();
+ // Get the central processor
+ CentralProcessor processor = hal.getProcessor();
+ // Get the previous CPU load ticks
+ long[] prevTicks = processor.getSystemCpuLoadTicks();
+ // Sleep for 1 second to measure the CPU load over time
+ Thread.sleep(1000);
+ // Get the current CPU load ticks
+ long[] ticks = processor.getSystemCpuLoadTicks();
+
+ // Calculate the difference in CPU ticks for each type
+ long user =
+ ticks[CentralProcessor.TickType.USER.getIndex()]
+ - prevTicks[CentralProcessor.TickType.USER.getIndex()];
+ long nice =
+ ticks[CentralProcessor.TickType.NICE.getIndex()]
+ - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
+ long sys =
+ ticks[CentralProcessor.TickType.SYSTEM.getIndex()]
+ - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
+ long idle =
+ ticks[CentralProcessor.TickType.IDLE.getIndex()]
+ - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
+ // Calculate the total CPU ticks
+ long totalCpu = user + nice + sys + idle;
+
+ // Calculate and return the CPU usage percentage
+ return ((double) (totalCpu - idle) / (double) totalCpu);
+ }
}
diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/utils/SystemLoadCalculate.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/utils/SystemLoadCalculate.java
new file mode 100644
index 0000000000..5234beb7bc
--- /dev/null
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/utils/SystemLoadCalculate.java
@@ -0,0 +1,218 @@
+/*
+ * 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.utils;
+
+import org.apache.seatunnel.shade.com.google.common.collect.EvictingQueue;
+
+import org.apache.seatunnel.engine.server.resourcemanager.resource.SlotAssignedProfile;
+import org.apache.seatunnel.engine.server.resourcemanager.resource.SystemLoadInfo;
+import org.apache.seatunnel.engine.server.resourcemanager.worker.WorkerProfile;
+
+import com.hazelcast.cluster.Address;
+
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.Objects;
+
+public class SystemLoadCalculate {
+ // Maximum number of records supported
+ private static final int MAX_TIME_WINDOW = 5;
+ // Time weight ratio configuration, arranged from new to old. Any length can be configured, and
+ // the actual use will take min(current number of records, length of the weight array)
+ private static final double[] TIME_WEIGHT_RATIOS = {4.0, 2.0, 2.0, 1.0, 1.0};
+ // Resource weight configuration
+ private static final double CPU_WEIGHT = 0.5;
+ private static final double MEMORY_WEIGHT = 0.5;
+
+ final double RESOURCE_AVAILABILITY_WEIGHT = 0.7;
+ final double SLOT_WEIGHT = 0.3;
+
+ private static class UtilizationData {
+ private final double cpuUtilization;
+ private final double memoryUtilization;
+
+ public UtilizationData(double cpuUtilization, double memoryUtilization) {
+ this.cpuUtilization = cpuUtilization;
+ this.memoryUtilization = memoryUtilization;
+ }
+ }
+
+ private final LinkedList<UtilizationData> utilizationHistory;
+
+ public SystemLoadCalculate() {
+ this.utilizationHistory = new LinkedList<>();
+ }
+
+ /** Add new resource utilization data */
+ public void addUtilizationData(double cpuUtilization, double memoryUtilization) {
+ // Validate input data
+ if (cpuUtilization < 0
+ || cpuUtilization > 1
+ || memoryUtilization < 0
+ || memoryUtilization > 1) {
+ throw new IllegalArgumentException("Utilization values must be between 0 and 1");
+ }
+
+ if (utilizationHistory.size() >= MAX_TIME_WINDOW) {
+ utilizationHistory.removeLast(); // Remove the oldest record
+ }
+ utilizationHistory.addFirst(new UtilizationData(cpuUtilization, memoryUtilization));
+ }
+
+ /** Generate corresponding time weights based on the actual number of records */
+ private double[] generateTimeWeights() {
+ int size = utilizationHistory.size();
+ if (size == 0) return new double[0];
+
+ // Determine the actual number of weights to use
+ int weightCount = Math.min(size, TIME_WEIGHT_RATIOS.length);
+ double[] weights = new double[size];
+ double totalWeight = 0;
+
+ // Allocate weights according to the configured ratio
+ for (int i = 0; i < size; i++) {
+ weights[i] =
+ (i < weightCount) ? TIME_WEIGHT_RATIOS[i] : TIME_WEIGHT_RATIOS[weightCount - 1];
+ totalWeight += weights[i];
+ }
+
+ // Normalize weights so that the sum is 1
+ for (int i = 0; i < size; i++) {
+ weights[i] /= totalWeight;
+ }
+
+ return weights;
+ }
+
+ /** Calculate scheduling priority */
+ public double calculateSchedulingPriority() {
+ if (utilizationHistory.isEmpty()) {
+ return 1.0; // If there is no historical data, return the highest priority
+ }
+
+ double[] timeWeights = generateTimeWeights();
+ double prioritySum = 0.0;
+ int index = 0;
+
+ for (UtilizationData data : utilizationHistory) {
+ // Calculate resource availability at the current time point
+ double resourceAvailability = calculateResourceAvailability(data);
+ // Apply time weight
+ prioritySum += resourceAvailability * timeWeights[index++];
+ }
+
+ return prioritySum;
+ }
+
+ public double calculate(
+ EvictingQueue<SystemLoadInfo> systemLoads,
+ WorkerProfile workerProfile,
+ Map<Address, SlotAssignedProfile> workerAssignedSlots) {
+ if (Objects.isNull(systemLoads) || systemLoads.isEmpty()) {
+ // If the node load is not obtained, zero is returned. This only happens when the
+ // service is just started and the load status has not yet been obtained.
+ return 0.0;
+ }
+ systemLoads.forEach(
+ v -> {
+ Double cpuPercentage = v.getCpuPercentage();
+ Double memPercentage = v.getMemPercentage();
+ this.addUtilizationData(cpuPercentage, memPercentage);
+ });
+ // step3.The comprehensive resource idle rate calculated
+ double comprehensiveResourceAvailability = this.calculateSchedulingPriority();
+ // step4
+ double resourceAvailabilityStep4 =
+ this.calculateComprehensiveResourceAvailability(
+ comprehensiveResourceAvailability, workerProfile, workerAssignedSlots);
+ // step5
+ double slotWeight = this.balanceFactor(workerProfile, workerAssignedSlots);
+ return this.calculateResourceAvailability(resourceAvailabilityStep4, slotWeight);
+ }
+
+ public double calculateResourceAvailability(
+ double resourceAvailabilityStep4, double slotWeight) {
+ return RESOURCE_AVAILABILITY_WEIGHT * resourceAvailabilityStep4 + SLOT_WEIGHT * slotWeight;
+ }
+
+ /** Calculate resource availability at a single point in time */
+ private double calculateResourceAvailability(UtilizationData data) {
+ double cpuAvailability = 1.0 - data.cpuUtilization;
+ double memoryAvailability = 1.0 - data.memoryUtilization;
+
+ return (cpuAvailability * CPU_WEIGHT + memoryAvailability * MEMORY_WEIGHT)
+ / (CPU_WEIGHT + MEMORY_WEIGHT);
+ }
+
+ /** step4. The comprehensive resource idle rate calculated */
+ public double calculateComprehensiveResourceAvailability(
+ double comprehensiveResourceAvailability,
+ WorkerProfile workerProfile,
+ Map<Address, SlotAssignedProfile> workerAssignedSlots) {
+ // Start step 4
+ // Number of assigned slots
+ int assignedSlotsNum = workerProfile.getAssignedSlots().length;
+ // Resource usage per slot, default is 0.1
+ double singleSlotUseResource = 0.1;
+ SlotAssignedProfile slotAssignedProfile;
+ if (workerAssignedSlots.get(workerProfile.getAddress()) == null) {
+ if (assignedSlotsNum != 0) {
+ singleSlotUseResource =
+ Math.round(
+ ((1.0 - comprehensiveResourceAvailability)
+ / assignedSlotsNum)
+ * 100.0)
+ / 100.0;
+ }
+ slotAssignedProfile =
+ workerAssignedSlots.getOrDefault(
+ workerProfile.getAddress(),
+ new SlotAssignedProfile(singleSlotUseResource, 0, assignedSlotsNum));
+ } else {
+ slotAssignedProfile = workerAssignedSlots.get(workerProfile.getAddress());
+ singleSlotUseResource = slotAssignedProfile.getSingleSlotUseResource();
+ }
+
+ Integer assignedTimesForTask = slotAssignedProfile.getCurrentTaskAssignedSlotsNum();
+ // Calculate the weight of the current task on the Worker node, step 4 completed
+ comprehensiveResourceAvailability =
+ comprehensiveResourceAvailability - (assignedTimesForTask * singleSlotUseResource);
+ return comprehensiveResourceAvailability;
+ }
+
+ public double balanceFactor(
+ WorkerProfile workerProfile, Map<Address, SlotAssignedProfile> workerAssignedSlots) {
+ SlotAssignedProfile slotAssignedProfile =
+ workerAssignedSlots.get(workerProfile.getAddress());
+ if (slotAssignedProfile != null) {
+ return balanceFactor(
+ workerProfile,
+ slotAssignedProfile.getCurrentTaskAssignedSlotsNum()
+ + slotAssignedProfile.getAssignedSlotsNum());
+ } else {
+ return balanceFactor(workerProfile, workerProfile.getAssignedSlots().length);
+ }
+ }
+
+ public double balanceFactor(WorkerProfile workerProfile, Integer assignedSlots) {
+ return 1.0
+ - ((double) assignedSlots
+ / (workerProfile.getAssignedSlots().length
+ + workerProfile.getUnassignedSlots().length));
+ }
+}
diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/resourcemanager/FixSlotResourceTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/resourcemanager/FixSlotResourceTest.java
index 53cc68b942..6dc44f5a31 100644
--- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/resourcemanager/FixSlotResourceTest.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/resourcemanager/FixSlotResourceTest.java
@@ -50,16 +50,13 @@ public class FixSlotResourceTest extends AbstractSeaTunnelServerTest<FixSlotReso
@Test
public void testEnoughResource() throws ExecutionException, InterruptedException {
+ ResourceManager resourceManager = server.getCoordinatorService().getResourceManager();
// wait all slot ready
await().atMost(20000, TimeUnit.MILLISECONDS)
.untilAsserted(
() -> {
Assertions.assertEquals(
- totalSlots,
- server.getCoordinatorService()
- .getResourceManager()
- .getUnassignedSlots(null)
- .size());
+ totalSlots, resourceManager.getUnassignedSlots(null).size());
});
long jobId = System.currentTimeMillis();
List<ResourceProfile> resourceProfiles = new ArrayList<>();
@@ -67,16 +64,14 @@ public class FixSlotResourceTest extends AbstractSeaTunnelServerTest<FixSlotReso
resourceProfiles.add(new ResourceProfile());
resourceProfiles.add(new ResourceProfile());
List<SlotProfile> slotProfiles =
- server.getCoordinatorService()
- .getResourceManager()
- .applyResources(jobId, resourceProfiles, null)
- .get();
+ resourceManager.applyResources(jobId, resourceProfiles, null).get();
Assertions.assertEquals(slotProfiles.size(), 3);
- server.getCoordinatorService().getResourceManager().releaseResources(jobId, slotProfiles);
+ resourceManager.releaseResources(jobId, slotProfiles);
}
@Test
public void testNotEnoughResource() throws ExecutionException, InterruptedException {
+ ResourceManager resourceManager = server.getCoordinatorService().getResourceManager();
long jobId = System.currentTimeMillis();
List<ResourceProfile> resourceProfiles = new ArrayList<>();
resourceProfiles.add(new ResourceProfile());
@@ -84,10 +79,7 @@ public class FixSlotResourceTest extends AbstractSeaTunnelServerTest<FixSlotReso
resourceProfiles.add(new ResourceProfile());
resourceProfiles.add(new ResourceProfile());
try {
- server.getCoordinatorService()
- .getResourceManager()
- .applyResources(jobId, resourceProfiles, null)
- .get();
+ resourceManager.applyResources(jobId, resourceProfiles, null).get();
} catch (ExecutionException e) {
Assertions.assertTrue(e.getMessage().contains("NoEnoughResourceException"));
}
@@ -96,19 +88,12 @@ public class FixSlotResourceTest extends AbstractSeaTunnelServerTest<FixSlotReso
.untilAsserted(
() -> {
Assertions.assertEquals(
- totalSlots,
- server.getCoordinatorService()
- .getResourceManager()
- .getUnassignedSlots(null)
- .size());
+ totalSlots, resourceManager.getUnassignedSlots(null).size());
});
resourceProfiles.remove(0);
List<SlotProfile> slotProfiles =
- server.getCoordinatorService()
- .getResourceManager()
- .applyResources(jobId, resourceProfiles, null)
- .get();
+ resourceManager.applyResources(jobId, resourceProfiles, null).get();
Assertions.assertEquals(slotProfiles.size(), 3);
- server.getCoordinatorService().getResourceManager().releaseResources(jobId, slotProfiles);
+ resourceManager.releaseResources(jobId, slotProfiles);
}
}
diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceManagerTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceManagerTest.java
index 5ac803064a..22bfbfd95d 100644
--- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceManagerTest.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceManagerTest.java
@@ -17,7 +17,9 @@
package org.apache.seatunnel.engine.server.resourcemanager;
+import org.apache.seatunnel.engine.common.config.server.AllocateStrategy;
import org.apache.seatunnel.engine.server.AbstractSeaTunnelServerTest;
+import org.apache.seatunnel.engine.server.resourcemanager.allocation.strategy.RandomStrategy;
import org.apache.seatunnel.engine.server.resourcemanager.resource.CPU;
import org.apache.seatunnel.engine.server.resourcemanager.resource.Memory;
import org.apache.seatunnel.engine.server.resourcemanager.resource.ResourceProfile;
@@ -98,6 +100,10 @@ public class ResourceManagerTest extends AbstractSeaTunnelServerTest<ResourceMan
public void testApplyResourceWithRandomResult()
throws ExecutionException, InterruptedException {
FakeResourceManager resourceManager = new FakeResourceManager(nodeEngine);
+ resourceManager
+ .getEngineConfig()
+ .getSlotServiceConfig()
+ .setAllocateStrategy(AllocateStrategy.RANDOM);
boolean hasDifferentWorker = false;
for (int i = 0; i < 5; i++) {
List<ResourceProfile> resourceProfiles = new ArrayList<>();
@@ -200,7 +206,8 @@ public class ResourceManagerTest extends AbstractSeaTunnelServerTest<ResourceMan
jobId,
resourceProfiles,
registerWorker,
- (AbstractResourceManager) this.resourceManager)
+ (AbstractResourceManager) this.resourceManager,
+ new RandomStrategy())
.preCheckWorkerResource(new ResourceProfile());
Assertions.assertEquals(result.isPresent(), dynamicSlot);
}
diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/utils/SystemLoadCalculateTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/utils/SystemLoadCalculateTest.java
new file mode 100644
index 0000000000..b98bad5f6c
--- /dev/null
+++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/utils/SystemLoadCalculateTest.java
@@ -0,0 +1,555 @@
+/*
+ * 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.utils;
+
+import org.apache.seatunnel.shade.com.google.common.collect.EvictingQueue;
+
+import org.apache.seatunnel.engine.common.config.EngineConfig;
+import org.apache.seatunnel.engine.common.config.server.ServerConfigOptions;
+import org.apache.seatunnel.engine.common.config.server.SlotServiceConfig;
+import org.apache.seatunnel.engine.server.resourcemanager.AbstractResourceManager;
+import org.apache.seatunnel.engine.server.resourcemanager.allocation.strategy.SystemLoadStrategy;
+import org.apache.seatunnel.engine.server.resourcemanager.resource.ResourceProfile;
+import org.apache.seatunnel.engine.server.resourcemanager.resource.SlotAssignedProfile;
+import org.apache.seatunnel.engine.server.resourcemanager.resource.SlotProfile;
+import org.apache.seatunnel.engine.server.resourcemanager.resource.SystemLoadInfo;
+import org.apache.seatunnel.engine.server.resourcemanager.worker.WorkerProfile;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import com.hazelcast.cluster.Address;
+import lombok.extern.slf4j.Slf4j;
+
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.when;
+
+@Slf4j
+public class SystemLoadCalculateTest {
+
+ private SystemLoadCalculate systemLoadCalculate;
+
+ @BeforeEach
+ void setUp() {
+ systemLoadCalculate = new SystemLoadCalculate();
+ }
+
+ @Test
+ @DisplayName("Step0: A newly created LoadBalancer should return the highest priority of 1.0")
+ void newLoadBalancerShouldReturnMaxPriority() {
+ Assertions.assertEquals(1.0, systemLoadCalculate.calculateSchedulingPriority());
+ }
+
+ @Test
+ @DisplayName("Step1-3: Adding invalid utilization data should throw an exception")
+ void shouldThrowExceptionForInvalidUtilizationData() {
+ Assertions.assertAll(
+ () ->
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> systemLoadCalculate.addUtilizationData(-0.1, 0.5)),
+ () ->
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> systemLoadCalculate.addUtilizationData(0.5, 1.1)),
+ () ->
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> systemLoadCalculate.addUtilizationData(1.1, 0.5)));
+ }
+
+ @Test
+ @DisplayName("Step1-3: Test weight calculation for 3 records")
+ void shouldCalculateCorrectPriorityForThreeRecords() {
+ // Add 3 records
+ // Oldest record
+ systemLoadCalculate.addUtilizationData(0.5, 0.4); // CPU: 50%, Memory: 40%
+ systemLoadCalculate.addUtilizationData(0.7, 0.6); // CPU: 70%, Memory: 60%
+ // Newest record
+ systemLoadCalculate.addUtilizationData(0.6, 0.5); // CPU: 60%, Memory: 50%
+
+ double priority = systemLoadCalculate.calculateSchedulingPriority();
+
+ // Manually calculate the expected result
+ // Weight distribution should be [4/8, 2/8, 2/8]
+ double expectedPriority =
+ // Newest record (1-0.6)*0.5 + (1-0.5)*0.5 * (4/8)
+ ((((1.0 - 0.6) * 0.5) + ((1.0 - 0.5) * 0.5)) * (4.0 / 8.0))
+ +
+ // Second record (1-0.7)*0.5 + (1-0.6)*0.5 * (2/8)
+ ((((1.0 - 0.7) * 0.5) + ((1.0 - 0.6) * 0.5)) * (2.0 / 8.0))
+ +
+ // Oldest record (1-0.5)*0.5 + (1-0.4)*0.5 * (2/8)
+ ((((1.0 - 0.5) * 0.5) + ((1.0 - 0.4) * 0.5)) * (2.0 / 8.0));
+
+ Assertions.assertEquals(expectedPriority, priority);
+ }
+
+ @Test
+ @DisplayName("Step1-3: Test weight calculation for 5 records")
+ void shouldCalculateCorrectPriorityForFiveRecords() {
+ // Add 5 records, from oldest to newest
+ systemLoadCalculate.addUtilizationData(0.3, 0.2);
+ systemLoadCalculate.addUtilizationData(0.4, 0.3);
+ systemLoadCalculate.addUtilizationData(0.5, 0.4);
+ systemLoadCalculate.addUtilizationData(0.7, 0.6);
+ systemLoadCalculate.addUtilizationData(0.6, 0.5);
+
+ double priority = systemLoadCalculate.calculateSchedulingPriority();
+
+ // Manually calculate the expected result
+ // Weight distribution should be [4/10, 2/10, 2/10, 1/10, 1/10]
+ double expectedPriority =
+ // Newest record: (1-0.6)*0.5 + (1-0.5)*0.5 * (4/10)
+ ((((1.0 - 0.6) * 0.5) + ((1.0 - 0.5) * 0.5)) * (4.0 / 10.0))
+ +
+ // Second record: (1-0.7)*0.5 + (1-0.6)*0.5 * (2/10)
+ ((((1.0 - 0.7) * 0.5) + ((1.0 - 0.6) * 0.5)) * (2.0 / 10.0))
+ +
+ // Third record: (1-0.5)*0.5 + (1-0.4)*0.5 * (2/10)
+ ((((1.0 - 0.5) * 0.5) + ((1.0 - 0.4) * 0.5)) * (2.0 / 10.0))
+ +
+ // Fourth record: (1-0.4)*0.5 + (1-0.3)*0.5 * (1/10)
+ ((((1.0 - 0.4) * 0.5) + ((1.0 - 0.3) * 0.5)) * (1.0 / 10.0))
+ +
+ // Oldest record: (1-0.3)*0.5 + (1-0.2)*0.5 * (1/10)
+ ((((1.0 - 0.3) * 0.5) + ((1.0 - 0.2) * 0.5)) * (1.0 / 10.0));
+
+ Assertions.assertEquals(expectedPriority, priority);
+ }
+
+ @Test
+ @DisplayName(
+ "Step1-3: Detailed verification of adding 6 records (verifying the maximum window limit of 5)")
+ void detailedCalculationForSixRecords() {
+ SystemLoadCalculate systemLoadCalculate = new SystemLoadCalculate();
+
+ // Add 6 records in chronological order (from oldest to newest)
+ // The first record will be discarded because it exceeds the window limit of 5
+ systemLoadCalculate.addUtilizationData(0.2, 0.1); // Oldest record (will be discarded)
+ systemLoadCalculate.addUtilizationData(0.3, 0.2); // Now the oldest record
+ systemLoadCalculate.addUtilizationData(0.4, 0.3); // Fourth record
+ systemLoadCalculate.addUtilizationData(0.5, 0.4); // Third record
+ systemLoadCalculate.addUtilizationData(0.7, 0.6); // Second record
+ systemLoadCalculate.addUtilizationData(0.6, 0.5); // Newest record
+
+ double expectedPriority =
+ // Newest record: (1-0.6)*0.5 + (1-0.5)*0.5 * (4/10)
+ ((((1.0 - 0.6) * 0.5) + ((1.0 - 0.5) * 0.5)) * (4.0 / 10.0))
+ +
+ // Second record: (1-0.7)*0.5 + (1-0.6)*0.5 * (2/10)
+ ((((1.0 - 0.7) * 0.5) + ((1.0 - 0.6) * 0.5)) * (2.0 / 10.0))
+ +
+ // Third record: (1-0.5)*0.5 + (1-0.4)*0.5 * (2/10)
+ ((((1.0 - 0.5) * 0.5) + ((1.0 - 0.4) * 0.5)) * (2.0 / 10.0))
+ +
+ // Fourth record: (1-0.4)*0.5 + (1-0.3)*0.5 * (1/10)
+ ((((1.0 - 0.4) * 0.5) + ((1.0 - 0.3) * 0.5)) * (1.0 / 10.0))
+ +
+ // Oldest record: (1-0.3)*0.5 + (1-0.2)*0.5 * (1/10)
+ ((((1.0 - 0.3) * 0.5) + ((1.0 - 0.2) * 0.5)) * (1.0 / 10.0));
+
+ double actualPriority = systemLoadCalculate.calculateSchedulingPriority();
+
+ Assertions.assertEquals(expectedPriority, actualPriority);
+ }
+
+ @Test
+ @DisplayName("Step4: Test calculateComprehensiveResourceAvailability method")
+ void testCalculateComprehensiveResourceAvailability() throws UnknownHostException {
+ // Assume that the overall resource idle rate is 0.8, and the Worker node has been
+ // continuously allocated 3 slots. This value is calculated based on the actual memory and
+ // CPU.
+ double comprehensiveResourceAvailability = 0.8;
+
+ SystemLoadCalculate systemLoadCalculate = new SystemLoadCalculate();
+ WorkerProfile workerProfile = Mockito.mock(WorkerProfile.class);
+ Address address = new Address("127.0.0.1", 5701);
+ when(workerProfile.getAddress()).thenReturn(address);
+ when(workerProfile.getAssignedSlots()).thenReturn(new SlotProfile[5]);
+ when(workerProfile.getUnassignedSlots()).thenReturn(new SlotProfile[3]);
+ Map<Address, SlotAssignedProfile> workerAssignedSlots = new ConcurrentHashMap<>();
+
+ // Each task has a fixed slot resource
+ double singleSlotResource =
+ Math.round(((1 - comprehensiveResourceAvailability) / 5) * 100.0) / 100.0;
+ int times = 0;
+
+ // When the worker has not been assigned, the overall resource idle rate remains unchanged
+ double result =
+ systemLoadCalculate.calculateComprehensiveResourceAvailability(
+ comprehensiveResourceAvailability, workerProfile, workerAssignedSlots);
+ double expected = comprehensiveResourceAvailability - (singleSlotResource * times);
+ Assertions.assertEquals(expected, result, 0.01);
+ Assertions.assertEquals(
+ comprehensiveResourceAvailability - (singleSlotResource * times), result, 0.01);
+ Assertions.assertEquals(0.8, result, 0.01);
+
+ // The worker has been assigned 1 slot
+ times = 1;
+ workerAssignedSlots.put(address, new SlotAssignedProfile(singleSlotResource, 1, 0));
+ when(workerProfile.getAssignedSlots()).thenReturn(new SlotProfile[6]);
+ when(workerProfile.getUnassignedSlots()).thenReturn(new SlotProfile[2]);
+ result =
+ systemLoadCalculate.calculateComprehensiveResourceAvailability(
+ comprehensiveResourceAvailability, workerProfile, workerAssignedSlots);
+ expected = comprehensiveResourceAvailability - (singleSlotResource * times);
+ Assertions.assertEquals(expected, result, 0.01);
+ Assertions.assertEquals(
+ comprehensiveResourceAvailability - (singleSlotResource * times), result, 0.01);
+ Assertions.assertEquals(0.76, result, 0.01);
+
+ // The worker has been assigned 2 slots
+ times = 2;
+ workerAssignedSlots.put(address, new SlotAssignedProfile(singleSlotResource, 2, 0));
+ when(workerProfile.getAssignedSlots()).thenReturn(new SlotProfile[7]);
+ when(workerProfile.getUnassignedSlots()).thenReturn(new SlotProfile[1]);
+ result =
+ systemLoadCalculate.calculateComprehensiveResourceAvailability(
+ comprehensiveResourceAvailability, workerProfile, workerAssignedSlots);
+ expected = comprehensiveResourceAvailability - (singleSlotResource * times);
+ Assertions.assertEquals(expected, result, 0.01);
+ Assertions.assertEquals(
+ comprehensiveResourceAvailability - (singleSlotResource * times), result, 0.01);
+ Assertions.assertEquals(0.72, result, 0.01);
+
+ // If there is no unassigned slot, it will not be executed.
+
+ }
+
+ @Test
+ @DisplayName("Step5: Test balanceFactor method")
+ void testBalanceFactor() {
+ WorkerProfile workerProfile = Mockito.mock(WorkerProfile.class);
+ when(workerProfile.getAssignedSlots()).thenReturn(new SlotProfile[3]);
+ when(workerProfile.getUnassignedSlots()).thenReturn(new SlotProfile[7]);
+ double balanceFactor = systemLoadCalculate.balanceFactor(workerProfile, 3);
+ Assertions.assertEquals(0.7, balanceFactor, 0.01);
+ }
+
+ @Test
+ @DisplayName("All: Test the overall calculation logic")
+ void testLoadBalancer() throws UnknownHostException {
+
+ // Verification plan 1: Split each step and verify whether the settlement indicators of each
+ // link are accurate
+ SystemLoadCalculate systemLoadCalculate = new SystemLoadCalculate();
+
+ // Add 6 records in chronological order (from oldest to newest)
+ // The first record will be discarded because it exceeds the window limit of 5
+ systemLoadCalculate.addUtilizationData(0.2, 0.1); // Oldest record (will be discarded)
+ systemLoadCalculate.addUtilizationData(0.3, 0.2); // Now the oldest record
+ systemLoadCalculate.addUtilizationData(0.4, 0.3); // Fourth record
+ systemLoadCalculate.addUtilizationData(0.5, 0.4); // Third record
+ systemLoadCalculate.addUtilizationData(0.7, 0.6); // Second record
+ systemLoadCalculate.addUtilizationData(0.6, 0.5); // Newest record
+ double comprehensiveResourceAvailability =
+ systemLoadCalculate.calculateSchedulingPriority();
+ Address address = new Address("127.0.0.1", 5701);
+ WorkerProfile workerProfile = Mockito.mock(WorkerProfile.class);
+ when(workerProfile.getAddress()).thenReturn(address);
+ when(workerProfile.getAssignedSlots()).thenReturn(new SlotProfile[5]);
+ when(workerProfile.getUnassignedSlots()).thenReturn(new SlotProfile[3]);
+ Map<Address, SlotAssignedProfile> workerAssignedSlots = new ConcurrentHashMap<>();
+
+ // Each task has a fixed Slot resource
+ double singleSlotResource =
+ Math.round(((1 - comprehensiveResourceAvailability) / 5) * 100.0) / 100.0;
+ int times = 0;
+
+ // When the worker has not been assigned, the overall resource idle rate remains unchanged
+ double result =
+ systemLoadCalculate.calculateComprehensiveResourceAvailability(
+ comprehensiveResourceAvailability, workerProfile, workerAssignedSlots);
+ double expected = comprehensiveResourceAvailability - (singleSlotResource * times);
+ Assertions.assertEquals(expected, result, 0.01);
+ Assertions.assertEquals(
+ comprehensiveResourceAvailability - (singleSlotResource * times), result, 0.01);
+ Assertions.assertEquals(0.5, result, 0.01);
+
+ // The worker has been assigned 1 slot
+ times = 1;
+ workerAssignedSlots.put(address, new SlotAssignedProfile(singleSlotResource, 1, 0));
+ when(workerProfile.getAssignedSlots()).thenReturn(new SlotProfile[6]);
+ when(workerProfile.getUnassignedSlots()).thenReturn(new SlotProfile[2]);
+ result =
+ systemLoadCalculate.calculateComprehensiveResourceAvailability(
+ comprehensiveResourceAvailability, workerProfile, workerAssignedSlots);
+ expected = comprehensiveResourceAvailability - (singleSlotResource * times);
+ Assertions.assertEquals(expected, result, 0.01);
+ Assertions.assertEquals(
+ comprehensiveResourceAvailability - (singleSlotResource * times), result, 0.01);
+ Assertions.assertEquals(0.4, result, 0.01);
+
+ workerAssignedSlots.put(address, new SlotAssignedProfile(singleSlotResource, 2, 0));
+ when(workerProfile.getAssignedSlots()).thenReturn(new SlotProfile[7]);
+ when(workerProfile.getUnassignedSlots()).thenReturn(new SlotProfile[1]);
+ result =
+ systemLoadCalculate.calculateComprehensiveResourceAvailability(
+ comprehensiveResourceAvailability, workerProfile, workerAssignedSlots);
+ double balanceFactor = systemLoadCalculate.balanceFactor(workerProfile, 7);
+ Assertions.assertEquals(0.12, balanceFactor, 0.01);
+
+ double finalResult = 0.7 * 0.3 + 0.125 * 0.3;
+ Assertions.assertEquals(
+ finalResult,
+ systemLoadCalculate.calculateResourceAvailability(result, balanceFactor),
+ 0.01);
+
+ // Verification plan 2: simulate the actual scenario and call the calculateWeight method to
+ // verify the final result and whether it is consistent with the result of step 1
+ Map<Address, EvictingQueue<SystemLoadInfo>> workerLoadMap = new ConcurrentHashMap<>();
+ workerLoadMap
+ .computeIfAbsent(address, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.3, 0.2));
+ workerLoadMap
+ .computeIfAbsent(address, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.4, 0.3));
+ workerLoadMap
+ .computeIfAbsent(address, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.5, 0.4));
+ workerLoadMap
+ .computeIfAbsent(address, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.7, 0.6));
+ workerLoadMap
+ .computeIfAbsent(address, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.6, 0.5));
+
+ // Mock current node resources
+ WorkerProfile workerProfile2 = Mockito.mock(WorkerProfile.class);
+ when(workerProfile2.getAssignedSlots()).thenReturn(new SlotProfile[5]);
+ when(workerProfile2.getUnassignedSlots()).thenReturn(new SlotProfile[3]);
+ when(workerProfile2.getAddress()).thenReturn(address);
+
+ Map<Address, SlotAssignedProfile> workerAssignedSlots2 = new ConcurrentHashMap<>();
+ List<ResourceProfile> resourceProfiles = new ArrayList<>();
+ resourceProfiles.add(new ResourceProfile());
+ // Mock ResourceManager
+ AbstractResourceManager rm = Mockito.mock(AbstractResourceManager.class);
+ when(rm.getEngineConfig()).thenReturn(Mockito.mock(EngineConfig.class));
+ when(rm.getEngineConfig().getSlotServiceConfig())
+ .thenReturn(Mockito.mock(SlotServiceConfig.class));
+ when(rm.getEngineConfig().getSlotServiceConfig().getAllocateStrategy())
+ .thenReturn(ServerConfigOptions.SLOT_ALLOCATE_STRATEGY.defaultValue());
+ // Simulate ResourceRequestHandler to call calculateWeight to calculate weight
+ SystemLoadStrategy systemLoadStrategy = new SystemLoadStrategy(workerLoadMap);
+ systemLoadStrategy.calculateWeight(workerProfile2, workerAssignedSlots2);
+ // Mock Application Resources
+ workerAssignedSlots2.put(address, new SlotAssignedProfile(singleSlotResource, 1, 5));
+ when(workerProfile2.getAssignedSlots()).thenReturn(new SlotProfile[6]);
+ when(workerProfile2.getUnassignedSlots()).thenReturn(new SlotProfile[2]);
+ systemLoadStrategy.calculateWeight(workerProfile2, workerAssignedSlots2);
+
+ workerAssignedSlots2.put(address, new SlotAssignedProfile(singleSlotResource, 2, 5));
+ when(workerProfile2.getAssignedSlots()).thenReturn(new SlotProfile[7]);
+ when(workerProfile2.getUnassignedSlots()).thenReturn(new SlotProfile[1]);
+ // Verity
+ Assertions.assertEquals(
+ systemLoadStrategy.calculateWeight(workerProfile2, workerAssignedSlots2),
+ finalResult);
+ }
+
+ /**
+ * Test Multi-Node System Load Balancing:
+ *
+ * <p>This test simulates the load distribution between two nodes, gradually increasing each
+ * node's load to verify the system's load balancing algorithm. The main steps include creating
+ * nodes, adding load information, configuring resource management components, calculating node
+ * weights, and finally allocating slots based on these weights.
+ *
+ * <p>Specific Process: <br>
+ * - Initialize two nodes (address1 and address2), each with a pre-added 5 load entries. <br>
+ * - Configure ResourceManager and ResourceRequestHandler for handling resource requests and
+ * calculating weights. <br>
+ * - Create workerProfile1 and workerProfile2, representing two worker nodes, and set their
+ * allocated and unallocated slots. <br>
+ * - Initially, it is expected that the first node has a higher weight (0.78 vs the second
+ * node's 0.41), leading to the preference of the first node for allocation. <br>
+ * - Gradually allocate slots to the first node (from 1 to 4), recalculating weights after each
+ * allocation and noting changes: <br>
+ * - After allocating 1 slot: the first node's weight drops to 0.68; <br>
+ * - After allocating 2 slots: the first node's weight drops to 0.58; <br>
+ * - After allocating 3 slots: the first node's weight drops to 0.48; <br>
+ * - After allocating 4 slots: the first node's weight drops to 0.38, at which point the second
+ * node has a higher weight (0.41), switching preference to the second node. <br>
+ * - Finally, allocate one slot to the second node, updating its weight to 0.31, and again
+ * choosing the first node for allocation. <br>
+ * <br>
+ * Each slot consumes a fixed amount of resources, set to 0.1 in this test case. This test
+ * ensures that the load balancing algorithm can make reasonable resource allocation decisions
+ * based on the current load situation of the nodes. <br>
+ */
+ @Test
+ @DisplayName("All: Test multiple node system load")
+ void testMultipleNodeSystemLoad() throws UnknownHostException {
+ Address address1 = new Address("127.0.0.1", 5701);
+ Address address2 = new Address("127.0.0.1", 5702);
+
+ // Simulate the actual scenario and call the calculateWeight method to verify the final
+ // result
+ Map<Address, EvictingQueue<SystemLoadInfo>> workerLoadMap = new ConcurrentHashMap<>();
+ workerLoadMap
+ .computeIfAbsent(address1, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.2, 0.1));
+ workerLoadMap
+ .computeIfAbsent(address1, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.3, 0.2));
+ workerLoadMap
+ .computeIfAbsent(address1, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.4, 0.3));
+ workerLoadMap
+ .computeIfAbsent(address1, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.4, 0.4));
+ workerLoadMap
+ .computeIfAbsent(address1, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.3, 0.3));
+
+ workerLoadMap
+ .computeIfAbsent(address2, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.8, 0.7));
+ workerLoadMap
+ .computeIfAbsent(address2, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.9, 0.8));
+ workerLoadMap
+ .computeIfAbsent(address2, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.85, 0.75));
+ workerLoadMap
+ .computeIfAbsent(address2, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.9, 0.85));
+ workerLoadMap
+ .computeIfAbsent(address2, v -> EvictingQueue.create(5))
+ .offer(new SystemLoadInfo(0.88, 0.8));
+
+ // Mock current node resources
+ WorkerProfile workerProfile2 = Mockito.mock(WorkerProfile.class);
+ when(workerProfile2.getAssignedSlots()).thenReturn(new SlotProfile[0]);
+ when(workerProfile2.getUnassignedSlots()).thenReturn(new SlotProfile[10]);
+ when(workerProfile2.getAddress()).thenReturn(address2);
+
+ List<ResourceProfile> resourceProfiles = new ArrayList<>();
+ resourceProfiles.add(new ResourceProfile());
+
+ // Mock ResourceManager
+ AbstractResourceManager rm = Mockito.mock(AbstractResourceManager.class);
+ when(rm.getEngineConfig()).thenReturn(Mockito.mock(EngineConfig.class));
+ when(rm.getEngineConfig().getSlotServiceConfig())
+ .thenReturn(Mockito.mock(SlotServiceConfig.class));
+ when(rm.getEngineConfig().getSlotServiceConfig().getAllocateStrategy())
+ .thenReturn(ServerConfigOptions.SLOT_ALLOCATE_STRATEGY.defaultValue());
+
+ WorkerProfile workerProfile1 = Mockito.mock(WorkerProfile.class);
+ when(workerProfile1.getAssignedSlots()).thenReturn(new SlotProfile[0]);
+ when(workerProfile1.getUnassignedSlots()).thenReturn(new SlotProfile[10]);
+ when(workerProfile1.getAddress()).thenReturn(address1);
+ // Simulate ResourceRequestHandler to call calculateWeight to calculate weight
+ SystemLoadStrategy systemLoadStrategy = new SystemLoadStrategy(workerLoadMap);
+ Map<Address, SlotAssignedProfile> workerAssignedSlots1 = new ConcurrentHashMap<>();
+ Double calculateWeight1 =
+ systemLoadStrategy.calculateWeight(workerProfile1, workerAssignedSlots1);
+ log.info("Node1 initialization weight: {}", calculateWeight1);
+
+ Map<Address, SlotAssignedProfile> workerAssignedSlots2 = new ConcurrentHashMap<>();
+ Double calculateWeight2 =
+ systemLoadStrategy.calculateWeight(workerProfile2, workerAssignedSlots2);
+ log.info("Node2 initialization weight: {}", calculateWeight2);
+
+ // First node load is low, second node load is high, first node weight should be greater
+ // than second node
+ Assertions.assertTrue(calculateWeight1 > calculateWeight2);
+
+ // Tip: Here, we default to singleSlotUseResource=0.1 for easy verification of the accuracy
+ // of the results. The singleSlotUseResource for the load can refer to the class:
+ // org.apache.setannel.engine.E2e.allocatestgy SystemLoadAllocateStrategyIT
+ double singleSlotUseResource = 0.1;
+
+ // First node is assigned a slot
+ workerAssignedSlots1.put(address1, new SlotAssignedProfile(singleSlotUseResource, 1, 0));
+ when(workerProfile1.getAssignedSlots()).thenReturn(new SlotProfile[1]);
+ when(workerProfile1.getUnassignedSlots()).thenReturn(new SlotProfile[9]);
+ calculateWeight1 = systemLoadStrategy.calculateWeight(workerProfile1, workerAssignedSlots1);
+ calculateWeight2 = systemLoadStrategy.calculateWeight(workerProfile2, workerAssignedSlots2);
+ log.info(
+ "First allocation weight: Node 1: {}, Node 2: {}",
+ calculateWeight1,
+ calculateWeight2);
+ Assertions.assertTrue(calculateWeight1 > calculateWeight2);
+
+ // First node is assigned two slots
+ workerAssignedSlots1.put(address1, new SlotAssignedProfile(singleSlotUseResource, 2, 0));
+ when(workerProfile1.getAssignedSlots()).thenReturn(new SlotProfile[2]);
+ when(workerProfile1.getUnassignedSlots()).thenReturn(new SlotProfile[8]);
+ calculateWeight1 = systemLoadStrategy.calculateWeight(workerProfile1, workerAssignedSlots1);
+ calculateWeight2 = systemLoadStrategy.calculateWeight(workerProfile2, workerAssignedSlots2);
+ log.info(
+ "Second allocation weight: Node 1: {}, Node 2: {}",
+ calculateWeight1,
+ calculateWeight2);
+ Assertions.assertTrue(calculateWeight1 > calculateWeight2);
+
+ // First node is assigned three slots
+ workerAssignedSlots1.put(address1, new SlotAssignedProfile(singleSlotUseResource, 3, 0));
+ when(workerProfile1.getAssignedSlots()).thenReturn(new SlotProfile[3]);
+ when(workerProfile1.getUnassignedSlots()).thenReturn(new SlotProfile[7]);
+ calculateWeight1 = systemLoadStrategy.calculateWeight(workerProfile1, workerAssignedSlots1);
+ calculateWeight2 = systemLoadStrategy.calculateWeight(workerProfile2, workerAssignedSlots2);
+ log.info(
+ "Third allocation weight: Node 1: {}, Node 2: {}",
+ calculateWeight1,
+ calculateWeight2);
+ Assertions.assertTrue(calculateWeight1 > calculateWeight2);
+
+ // First node is assigned four slots
+ workerAssignedSlots1.put(address1, new SlotAssignedProfile(singleSlotUseResource, 4, 0));
+ when(workerProfile1.getAssignedSlots()).thenReturn(new SlotProfile[4]);
+ when(workerProfile1.getUnassignedSlots()).thenReturn(new SlotProfile[6]);
+ calculateWeight1 = systemLoadStrategy.calculateWeight(workerProfile1, workerAssignedSlots1);
+ calculateWeight2 = systemLoadStrategy.calculateWeight(workerProfile2, workerAssignedSlots2);
+ log.info(
+ "Fourth allocation weight: Node 1: {}, Node 2: {}",
+ calculateWeight1,
+ calculateWeight2);
+
+ // After applying for resources five times, the weight of the first node should be less than
+ // the second node because the estimated resource usage rate of a single slot is 0.1
+ Assertions.assertTrue(calculateWeight1 < calculateWeight2);
+
+ // Second node is assigned one slot
+ workerAssignedSlots2.put(address2, new SlotAssignedProfile(singleSlotUseResource, 1, 0));
+ when(workerProfile1.getAssignedSlots()).thenReturn(new SlotProfile[1]);
+ when(workerProfile1.getUnassignedSlots()).thenReturn(new SlotProfile[9]);
+ calculateWeight1 = systemLoadStrategy.calculateWeight(workerProfile1, workerAssignedSlots1);
+ calculateWeight2 = systemLoadStrategy.calculateWeight(workerProfile2, workerAssignedSlots2);
+ log.info(
+ "Fifth allocation weight: Node 1: {}, Node 2: {}",
+ calculateWeight1,
+ calculateWeight2);
+
+ // After applying for resources five times, the weight of the first node should be less than
+ // the second node because the estimated resource usage rate of a single slot is 0.1
+ Assertions.assertTrue(calculateWeight1 > calculateWeight2);
+ }
+}
diff --git a/tools/dependencies/known-dependencies.txt b/tools/dependencies/known-dependencies.txt
index c951314953..567cd10659 100755
--- a/tools/dependencies/known-dependencies.txt
+++ b/tools/dependencies/known-dependencies.txt
@@ -70,6 +70,9 @@ jetty-util-9.4.56.v20240826.jar
jetty-util-ajax-9.4.56.v20240826.jar
javax.servlet-api-3.1.0.jar
seatunnel-jetty9-9.4.56-2.3.10-SNAPSHOT-optional.jar
+jna-5.15.0.jar
+jna-platform-5.15.0.jar
+oshi-core-6.6.5.jar
arrow-format-15.0.1.jar
arrow-memory-core-15.0.1.jar
arrow-memory-netty-15.0.1.jar