Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,326 @@
/*
* 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.iotdb.confignode.it.load;

import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
import org.apache.iotdb.common.rpc.thrift.TRegionReplicaSet;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.commons.client.sync.SyncConfigNodeIServiceClient;
import org.apache.iotdb.commons.cluster.NodeStatus;
import org.apache.iotdb.commons.cluster.RegionRoleType;
import org.apache.iotdb.confignode.rpc.thrift.TDataNodeConfigurationResp;
import org.apache.iotdb.confignode.rpc.thrift.TRegionInfo;
import org.apache.iotdb.confignode.rpc.thrift.TRegionRouteMapResp;
import org.apache.iotdb.confignode.rpc.thrift.TShowRegionReq;
import org.apache.iotdb.confignode.rpc.thrift.TShowRegionResp;
import org.apache.iotdb.consensus.ConsensusFactory;
import org.apache.iotdb.it.env.EnvFactory;
import org.apache.iotdb.it.env.cluster.config.MppCommonConfig;
import org.apache.iotdb.it.env.cluster.node.DataNodeWrapper;
import org.apache.iotdb.it.framework.IoTDBTestRunner;
import org.apache.iotdb.itbase.category.ClusterIT;
import org.apache.iotdb.rpc.TSStatusCode;
import org.apache.iotdb.rpc.UrlUtils;

import org.apache.thrift.TException;
import org.awaitility.Awaitility;
import org.junit.After;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static org.apache.iotdb.common.rpc.thrift.TConsensusGroupType.DataRegion;
import static org.apache.iotdb.common.rpc.thrift.TConsensusGroupType.SchemaRegion;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;

@RunWith(IoTDBTestRunner.class)
@Category(ClusterIT.class)
public class IoTDBFixedOrderRegionGroupIT {

private static final String DATABASE = "root.fixed_c";
private static final String EARLIER_DATABASE = "root.fixed_0";
private static final String FALLBACK_DATABASE = "root.fixed_b";

@After
public void tearDown() {
EnvFactory.getEnv().cleanClusterEnvironment();
}

@Test
public void testIoTConsensus() throws Exception {
verifyFixedOrder(ConsensusFactory.IOT_CONSENSUS);
}

@Test
public void testIoTConsensusV2() throws Exception {
verifyFixedOrder(ConsensusFactory.IOT_CONSENSUS_V2);
}

@Test
public void testRatisSchemaAndDataLeaderTransfer() throws Exception {
configureFixedOrder(ConsensusFactory.RATIS_CONSENSUS, 3, 3);
EnvFactory.getEnv().initClusterEnvironment(1, 3);
try (SyncConfigNodeIServiceClient client =
(SyncConfigNodeIServiceClient) EnvFactory.getEnv().getLeaderConfigNodeConnection()) {
List<Integer> nodes = registeredNodes(client);
DataNodeWrapper primary = EnvFactory.getEnv().dataNodeIdToWrapper(nodes.get(0)).get();
try (Connection connection = EnvFactory.getEnv().getConnection(primary);
Statement statement = connection.createStatement()) {
statement.execute("CREATE DATABASE " + DATABASE);
statement.execute("CREATE TIMESERIES " + DATABASE + ".d0.s INT64");
insert(statement, DATABASE + ".d0", 1);
awaitBothLeaders(client, nodes, nodes.get(0));
statement.execute("SET SYSTEM TO READONLY ON LOCAL");
awaitBothLeaders(client, nodes, nodes.get(1));
statement.execute("SET SYSTEM TO RUNNING ON LOCAL");
awaitBothLeaders(client, nodes, nodes.get(0));
}
}
}

private static void awaitBothLeaders(
SyncConfigNodeIServiceClient client, List<Integer> nodes, int leader) {
awaitGroups(client, SchemaRegion, DATABASE, 1, nodes, leader);
awaitGroups(client, DataRegion, DATABASE, 1, nodes, leader);
}

private void configureFixedOrder(String protocol, int schemaRF, int dataRF) {
EnvFactory.getEnv()
.getConfig()
.getCommonConfig()
.setDataRegionConsensusProtocolClass(protocol)
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
.setSchemaReplicationFactor(schemaRF)
.setDataReplicationFactor(dataRF)
.setRegionGroupAllocatePolicy("DB_FIXED_ORDER")
.setDataRegionGroupExtensionPolicy("PROACTIVE")
.setDataRegionPerDataNode(12)
.setEnableAuditLog(false);
EnvFactory.getEnv()
.getConfig()
.getConfigNodeConfig()
.setLeaderDistributionPolicy("DB_FIXED_ORDER");
}

private void verifyFixedOrder(String protocol) throws Exception {
configureFixedOrder(protocol, 1, 2);
EnvFactory.getEnv()
.getConfig()
.getDataNodeConfig()
.setMetricReporterType(Collections.singletonList("PROMETHEUS"));
Properties liveMetrics = new Properties();
liveMetrics.setProperty("prometheus_reporter_async_update", "false");
((MppCommonConfig) EnvFactory.getEnv().getConfig().getDataNodeCommonConfig())
.updateProperties(liveMetrics);
EnvFactory.getEnv().initClusterEnvironment(1, 3);

try (SyncConfigNodeIServiceClient client =
(SyncConfigNodeIServiceClient) EnvFactory.getEnv().getLeaderConfigNodeConnection()) {
List<Integer> nodes = registeredNodes(client);
List<Integer> originalOrder = Arrays.asList(nodes.get(2), nodes.get(0));
List<Integer> newOrder = Arrays.asList(nodes.get(0), nodes.get(1));
DataNodeWrapper primary = EnvFactory.getEnv().dataNodeIdToWrapper(nodes.get(2)).get();
DataNodeWrapper second = EnvFactory.getEnv().dataNodeIdToWrapper(nodes.get(0)).get();
DataNodeWrapper nonMember = EnvFactory.getEnv().dataNodeIdToWrapper(nodes.get(1)).get();

// Pin sessions before changing node health so the failure probe uses a healthy non-member.
try (Connection local = EnvFactory.getEnv().getConnection(primary);
Statement statement = local.createStatement();
Connection peer = EnvFactory.getEnv().getConnection(second);
Statement secondStatement = peer.createStatement();
Connection observer = EnvFactory.getEnv().getConnection(nonMember);
Statement observerStatement = observer.createStatement()) {
for (String database : Arrays.asList(FALLBACK_DATABASE, DATABASE, "root.fixed_a")) {
statement.execute("CREATE DATABASE " + database);
}
statement.execute("CREATE TIMESERIES " + DATABASE + ".d0.s INT64");
statement.execute("CREATE TIMESERIES " + DATABASE + ".d1.s INT64");
insert(statement, DATABASE + ".d0", 1);
awaitGroups(client, DataRegion, DATABASE, 1, originalOrder, nodes.get(2));
// PROACTIVE allocates a second group for d1 while the catalog and DataNodes are fixed.
insert(statement, DATABASE + ".d1", 1);
awaitGroups(client, DataRegion, DATABASE, 2, originalOrder, nodes.get(2));

// Inserting an earlier database changes the ranking only for future allocations.
statement.execute("CREATE DATABASE " + EARLIER_DATABASE);
statement.execute("CREATE TIMESERIES " + EARLIER_DATABASE + ".d0.s INT64");
insert(statement, EARLIER_DATABASE + ".d0", 1);
awaitGroups(client, DataRegion, EARLIER_DATABASE, 1, newOrder, nodes.get(0));
observerStatement.execute("CREATE TIMESERIES " + FALLBACK_DATABASE + ".d0.s INT64");
assertTrue(regions(client, DataRegion, FALLBACK_DATABASE).isEmpty());

// Warm the schema before measuring the remote scheduling timer. An intentional remote write
// through the same entry is the positive control; consensus replication has its own path.
long before = remoteDispatchCount(primary);
insert(statement, EARLIER_DATABASE + ".d0", 2);
long afterRemote = remoteDispatchCount(primary);
assertTrue("Expected cross-node write dispatch", afterRemote > before);
insert(statement, DATABASE + ".d0", 2);
insert(statement, DATABASE + ".d1", 2);
assertEquals(
"Both old and new groups should dispatch locally",
afterRemote,
remoteDispatchCount(primary));

statement.execute("SET SYSTEM TO READONLY ON LOCAL");
awaitGroups(client, DataRegion, DATABASE, 2, originalOrder, nodes.get(0));
// fixed_b's window starts at the read-only primary. Both writable DNs must host the group.
insert(observerStatement, FALLBACK_DATABASE + ".d0", 1);
assertEquals(
newOrder,
regions(client, DataRegion, FALLBACK_DATABASE).stream()
.map(TRegionInfo::getDataNodeId)
.sorted()
.collect(Collectors.toList()));
secondStatement.execute("SET SYSTEM TO READONLY ON LOCAL");
EnvFactory.getEnv()
.ensureNodeStatus(
Arrays.asList(primary, second),
Arrays.asList(NodeStatus.ReadOnly, NodeStatus.ReadOnly));
SQLException rejected =
assertThrows(SQLException.class, () -> insert(observerStatement, DATABASE + ".d0", 99));
assertEquals(
rejected.getMessage(),
TSStatusCode.SYSTEM_READ_ONLY.getStatusCode(),
rejected.getErrorCode());
awaitGroups(client, DataRegion, DATABASE, 2, originalOrder, nodes.get(0));
secondStatement.execute("SET SYSTEM TO RUNNING ON LOCAL");
statement.execute("SET SYSTEM TO RUNNING ON LOCAL");
awaitGroups(client, DataRegion, DATABASE, 2, originalOrder, nodes.get(2));
insert(observerStatement, DATABASE + ".d0", 3);
try (ResultSet rows = statement.executeQuery("SELECT count(s) FROM " + DATABASE + ".d0")) {
assertTrue(rows.next());
assertEquals(3, rows.getLong(1));
}
}

// A lost heartbeat triggers takeover without an explicit status change from the primary.
primary.stopForcibly();
awaitGroups(client, DataRegion, DATABASE, 2, originalOrder, nodes.get(0));
primary.start();
awaitGroups(client, DataRegion, DATABASE, 2, originalOrder, nodes.get(2));
}
}

private static List<Integer> registeredNodes(SyncConfigNodeIServiceClient client)
throws TException {
TDataNodeConfigurationResp registrations = client.getDataNodeConfiguration(-1);
assertSuccess(registrations.getStatus());
List<Integer> nodes = new ArrayList<>(registrations.getDataNodeConfigurationMap().keySet());
Collections.sort(nodes);
assertEquals(3, nodes.size());
return nodes;
}

private static void insert(Statement statement, String device, int time) throws Exception {
statement.execute("INSERT INTO " + device + "(time,s) VALUES (" + time + "," + time + ")");
}

private static List<TRegionInfo> regions(
SyncConfigNodeIServiceClient client, TConsensusGroupType type, String database)
throws TException {
TShowRegionResp regions =
client.showRegion(
new TShowRegionReq()
.setConsensusGroupType(type)
.setDatabases(Collections.singletonList(database)));
assertSuccess(regions.getStatus());
return regions.getRegionInfoList();
}

private static void awaitGroups(
SyncConfigNodeIServiceClient client,
TConsensusGroupType type,
String database,
int groupCount,
List<Integer> members,
int expectedLeader) {
Awaitility.await()
.atMost(60, TimeUnit.SECONDS)
.untilAsserted(
() -> {
List<TRegionInfo> regions = regions(client, type, database);
TRegionRouteMapResp routes = client.getLatestRegionRouteMap();
assertSuccess(routes.getStatus());
assertEquals(groupCount * members.size(), regions.size());
Set<TConsensusGroupId> groupIds = new HashSet<>();
for (TRegionInfo region : regions) {
assertEquals(database, region.getDatabase());
assertEquals(type, region.getConsensusGroupId().getType());
groupIds.add(region.getConsensusGroupId());
assertEquals(
expectedLeader == region.getDataNodeId(),
RegionRoleType.Leader.getRoleType().equals(region.getRoleType()));
}
assertEquals("Group count for " + database, groupCount, groupIds.size());
for (TConsensusGroupId group : groupIds) {
TRegionReplicaSet route = routes.getRegionRouteMap().get(group);
assertNotNull(group.toString(), route);
assertEquals(
new HashSet<>(members),
route.getDataNodeLocations().stream()
.map(TDataNodeLocation::getDataNodeId)
.collect(Collectors.toSet()));
assertEquals(expectedLeader, route.getDataNodeLocations().get(0).getDataNodeId());
}
});
}

private static long remoteDispatchCount(DataNodeWrapper entry) {
String metrics =
EnvFactory.getEnv()
.getUrlContent(
"http://"
+ UrlUtils.formatTEndPointIpv4AndIpv6Url(entry.getIp(), entry.getMetricPort())
+ "/metrics",
null);
for (String line : metrics.split("\n")) {
if (line.startsWith("performance_overview_schedule_detail_seconds_count{")
&& line.contains("stage=\"remote_scheduler\"")) {
return Long.parseLong(line.substring(line.lastIndexOf(' ') + 1).trim());
}
}
throw new AssertionError("Missing remote scheduling timer on " + entry.getId());
}

private static void assertSuccess(TSStatus status) {
assertEquals(
status.getMessage(), TSStatusCode.SUCCESS_STATUS.getStatusCode(), status.getCode());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,9 @@ public final class ConfigNodeMessages {
public static final String UNKNOWN_HOST_WHEN_CHECKING_SEED_CONFIGNODE_IP =
"Unknown host when checking seed configNode IP {}";
public static final String UNKNOWN_LEADER_DISTRIBUTION_POLICY =
"Unknown leader_distribution_policy: %s, please set to \"GREEDY\" or \"CFS\" or \"HASH\"";
"Unknown leader_distribution_policy: %s. Supported values are GREEDY, CFS, HASH and DB_FIXED_ORDER.";
public static final String EXCEPTION_DB_FIXED_ORDER_REQUIRES_REGION_GROUP_ALLOCATE_POLICY_DB_FIXED_ORDER_LEADER_DISTRIBUTION_POLICY_DB_FIXED_ORDER_AND_ROUTE_PRIORITY_POLICY_LEADER_EA87C6A2 =
"DB_FIXED_ORDER requires region_group_allocate_policy=DB_FIXED_ORDER, leader_distribution_policy=DB_FIXED_ORDER and route_priority_policy=LEADER";
public static final String UNKNOWN_PHYSICALPLAN_CONFIGPHYSICALPLANTYPE =
"unknown PhysicalPlan configPhysicalPlanType: ";
public static final String UNKNOWN_READ_CONSISTENCY_LEVEL_PLEASE_SET_TO =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@
package org.apache.iotdb.confignode.i18n;

public final class ManagerMessages {
public static final String EXCEPTION_DB_FIXED_ORDER_ONLY_ALLOCATES_NEW_REGIONGROUPS_CC123FDF =
"DB_FIXED_ORDER only allocates new RegionGroups.";

public static final String
LOG_USING_PGP_FOR_NEW_REGIONGROUPS_IN_DATABASE_ARG_BECAUSE_DATANODE_ARG_IN_THE_DB_FIXED_ORDER_WINDOW_ARG_IS_INELIGIBLE_36527B92 =
"Using PGP for new RegionGroups in database {} because DataNode {} in the DB_FIXED_ORDER window {} is ineligible";

public static final String
EXCEPTION_FAILED_TO_CREATE_OR_ALTER_TOPIC_REALTIME_MODE_ARG_CONFLICTS_WITH_ARG_ARG_D08CF59B =
"Failed to create or alter topic, realtime.mode=%s conflicts with %s=%s";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,9 @@ public final class ConfigNodeMessages {
public static final String UNKNOWN_HOST_WHEN_CHECKING_SEED_CONFIGNODE_IP =
"检查 seed configNode IP {} 时遇到未知主机";
public static final String UNKNOWN_LEADER_DISTRIBUTION_POLICY =
"未知 leader_distribution_policy:%s,请设置为 \"GREEDY\"、\"CFS\" 或 \"HASH\"";
"未知 leader_distribution_policy:%s。支持的策略为 GREEDY、CFS、HASH 和 DB_FIXED_ORDER。";
public static final String EXCEPTION_DB_FIXED_ORDER_REQUIRES_REGION_GROUP_ALLOCATE_POLICY_DB_FIXED_ORDER_LEADER_DISTRIBUTION_POLICY_DB_FIXED_ORDER_AND_ROUTE_PRIORITY_POLICY_LEADER_EA87C6A2 =
"使用 DB_FIXED_ORDER 时,必须同时设置 region_group_allocate_policy=DB_FIXED_ORDER、leader_distribution_policy=DB_FIXED_ORDER 和 route_priority_policy=LEADER";
public static final String UNKNOWN_PHYSICALPLAN_CONFIGPHYSICALPLANTYPE =
"未知的 PhysicalPlan configPhysicalPlanType: ";
public static final String UNKNOWN_READ_CONSISTENCY_LEVEL_PLEASE_SET_TO =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@
package org.apache.iotdb.confignode.i18n;

public final class ManagerMessages {
public static final String EXCEPTION_DB_FIXED_ORDER_ONLY_ALLOCATES_NEW_REGIONGROUPS_CC123FDF =
"DB_FIXED_ORDER 仅用于新建 RegionGroup。";

public static final String
LOG_USING_PGP_FOR_NEW_REGIONGROUPS_IN_DATABASE_ARG_BECAUSE_DATANODE_ARG_IN_THE_DB_FIXED_ORDER_WINDOW_ARG_IS_INELIGIBLE_36527B92 =
"数据库 {} 的新 RegionGroup 回退到 PGP,因为 DataNode {} 不符合 DB_FIXED_ORDER 窗口 {} 的放置条件";

public static final String
EXCEPTION_FAILED_TO_CREATE_OR_ALTER_TOPIC_REALTIME_MODE_ARG_CONFLICTS_WITH_ARG_ARG_D08CF59B =
"创建或修改主题失败,realtime.mode=%s 与 %s=%s 冲突";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,13 @@ public String getLeaderDistributionPolicy() {
return leaderDistributionPolicy;
}

static boolean isSupportedLeaderDistributionPolicy(String policy) {
return AbstractLeaderBalancer.CFS_POLICY.equals(policy)
|| AbstractLeaderBalancer.GREEDY_POLICY.equals(policy)
|| AbstractLeaderBalancer.HASH_POLICY.equals(policy)
|| AbstractLeaderBalancer.DB_FIXED_ORDER_POLICY.equals(policy);
}

public void setLeaderDistributionPolicy(String leaderDistributionPolicy) {
this.leaderDistributionPolicy = leaderDistributionPolicy;
}
Expand Down
Loading
Loading