You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shardingsphere.apache.org by ji...@apache.org on 2023/03/06 09:01:18 UTC
[shardingsphere] branch master updated: Add DistSQL LOCK CLUSTER (#24441)
This is an automated email from the ASF dual-hosted git repository.
jianglongtao pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shardingsphere.git
The following commit(s) were added to refs/heads/master by this push:
new c36500e594d Add DistSQL LOCK CLUSTER (#24441)
c36500e594d is described below
commit c36500e594d97148cd12658ddd58a93c361ef290
Author: ChenJiaHao <Pa...@163.com>
AuthorDate: Mon Mar 6 17:00:58 2023 +0800
Add DistSQL LOCK CLUSTER (#24441)
* Add DistSQL LOCK CLUSTER
* Fix unit test
* Refactor get cluster lock key
* Fix code style
* Fix code style
* Remove proxy backend spi module
* Refactor sql statement check for cluster state
---
.../exporter/impl/proxy/ProxyStateExporter.java | 4 +-
.../impl/proxy/ProxyStateExporterTest.java | 4 +-
distsql/parser/src/main/antlr4/imports/Keyword.g4 | 12 ++++
.../parser/src/main/antlr4/imports/RALStatement.g4 | 8 +++
.../parser/autogen/KernelDistSQLStatement.g4 | 1 +
.../core/kernel/KernelDistSQLStatementVisitor.java | 7 +++
.../ral/updatable/LockClusterStatement.java | 13 ++--
docs/document/content/dev-manual/mode.cn.md | 18 +++---
docs/document/content/dev-manual/mode.en.md | 19 +++---
.../user-manual/error-code/sql-error-code.cn.md | 17 ++---
.../user-manual/error-code/sql-error-code.en.md | 17 ++---
.../infra/instance/ComputeNodeInstance.java | 8 +--
.../{StateType.java => cluster/ClusterState.java} | 8 +--
.../infra/state/cluster/ClusterStateContext.java | 28 ++++++---
.../InstanceState.java} | 6 +-
.../InstanceStateContext.java} | 26 ++++----
.../infra/instance/InstanceContextTest.java | 14 ++---
...textTest.java => InstanceStateContextTest.java} | 26 ++++----
.../datasource/ShardingSphereDataSourceTest.java | 6 +-
.../driver/state/DriverStateContextTest.java | 4 +-
.../mode/manager/ContextManager.java | 16 +++++
.../event/ComputeNodeStatusChangedEvent.java | 4 +-
.../mode/metadata/persist/node/ComputeNode.java | 9 +++
.../mode/manager/ContextManagerTest.java | 7 +++
.../cluster/ClusterContextManagerBuilder.java | 6 ++
.../cluster/coordinator/RegistryCenter.java | 21 +++++++
.../cluster/event/ClusterLockDeletedEvent.java} | 13 ++--
.../status/cluster/event/ClusterStateEvent.java} | 12 ++--
.../cluster/event/ClusterStatusChangedEvent.java} | 12 ++--
.../cluster/service/ClusterStatusService.java | 52 ++++++++++++++++
.../subscriber/ClusterStatusSubscriber.java | 48 +++++++++++++++
.../watcher/ClusterStateChangedWatcher.java | 58 +++++++++++++++++
.../watcher/lock/ClusterLockDeletedWatcher.java | 51 +++++++++++++++
.../compute/service/ComputeNodeStatusService.java | 4 +-
.../subscriber/StateChangedSubscriber.java | 31 ++++++++--
....cluster.coordinator.registry.GovernanceWatcher | 2 +
.../cluster/service/ClusterStatusServiceTest.java | 49 +++++++++++++++
.../watcher/ClusterStateChangedWatcherTest.java | 58 +++++++++++++++++
.../service/ComputeNodeStatusServiceTest.java | 8 +--
.../ComputeNodeStateChangedWatcherTest.java | 6 +-
.../subscriber/StateChangedSubscriberTest.java | 23 ++++++-
.../proxy/backend/context/ProxyContext.java | 8 +--
.../backend}/exception/ReadOnlyException.java | 6 +-
.../backend/exception/UnavailableException.java} | 12 ++--
.../handler/ProxyBackendHandlerFactory.java | 20 ++++--
.../distsql/ral/updatable/LockClusterUpdater.java | 72 ++++++++++++++++++++++
.../ral/updatable/SetInstanceStatusUpdater.java | 6 +-
.../lock/impl/ClusterReadWriteLockStrategy.java | 47 ++++++++++++++
.../lock/impl/ClusterWriteLockStrategy.java | 48 +++++++++++++++
.../backend/lock/spi/ClusterLockStrategy.java | 13 ++--
.../backend/state/impl/ReadOnlyProxyState.java | 51 +++++++++++++++
.../backend/state/impl/UnavailableProxyState.java | 52 ++++++++++++++++
.../proxy/backend/state/spi/ProxyClusterState.java | 22 +++----
...ingsphere.distsql.handler.ral.update.RALUpdater | 1 +
...here.proxy.backend.lock.spi.ClusterLockStrategy | 8 +--
...phere.proxy.backend.state.spi.ProxyClusterState | 8 +--
.../proxy/backend/context/ProxyContextTest.java | 4 +-
.../handler/ProxyBackendHandlerFactoryTest.java | 2 +
.../queryable/ShowComputeNodeInfoExecutorTest.java | 4 +-
.../queryable/ShowComputeNodesExecutorTest.java | 6 +-
...pdaterTest.java => LockClusterUpdaterTest.java} | 43 ++++++-------
.../updatable/SetInstanceStatusUpdaterTest.java | 4 +-
.../org/apache/shardingsphere/proxy/Bootstrap.java | 2 +-
.../proxy/frontend/state/ProxyState.java | 3 +-
.../proxy/frontend/state/ProxyStateContext.java | 17 ++---
.../ral/impl/UpdatableRALStatementAssert.java | 5 ++
.../impl/updatable/LockClusterStatementAssert.java | 51 +++++++++++++++
.../ral/LockClusterStatementTestCase.java | 20 +++---
68 files changed, 1029 insertions(+), 242 deletions(-)
diff --git a/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/proxy/ProxyStateExporter.java b/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/proxy/ProxyStateExporter.java
index adf62df1a3d..fd476cd5f60 100644
--- a/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/proxy/ProxyStateExporter.java
+++ b/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/proxy/ProxyStateExporter.java
@@ -22,7 +22,7 @@ import org.apache.shardingsphere.agent.plugin.metrics.core.collector.type.GaugeM
import org.apache.shardingsphere.agent.plugin.metrics.core.config.MetricCollectorType;
import org.apache.shardingsphere.agent.plugin.metrics.core.config.MetricConfiguration;
import org.apache.shardingsphere.agent.plugin.metrics.core.exporter.MetricsExporter;
-import org.apache.shardingsphere.infra.state.StateContext;
+import org.apache.shardingsphere.infra.state.instance.InstanceStateContext;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
import java.util.Collections;
@@ -41,7 +41,7 @@ public final class ProxyStateExporter implements MetricsExporter {
if (null == ProxyContext.getInstance().getContextManager()) {
return Optional.empty();
}
- Optional<StateContext> stateContext = ProxyContext.getInstance().getStateContext();
+ Optional<InstanceStateContext> stateContext = ProxyContext.getInstance().getInstanceStateContext();
if (!stateContext.isPresent()) {
return Optional.empty();
}
diff --git a/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/proxy/ProxyStateExporterTest.java b/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/proxy/ProxyStateExporterTest.java
index d1725f0c4cc..0be8a6e4d5c 100644
--- a/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/proxy/ProxyStateExporterTest.java
+++ b/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/proxy/ProxyStateExporterTest.java
@@ -29,7 +29,7 @@ import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaData;
import org.apache.shardingsphere.infra.instance.mode.ModeContextManager;
import org.apache.shardingsphere.infra.lock.LockContext;
import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData;
-import org.apache.shardingsphere.infra.state.StateContext;
+import org.apache.shardingsphere.infra.state.instance.InstanceStateContext;
import org.apache.shardingsphere.infra.util.eventbus.EventBusContext;
import org.apache.shardingsphere.mode.manager.ContextManager;
import org.apache.shardingsphere.mode.manager.standalone.workerid.generator.StandaloneWorkerIdGenerator;
@@ -73,7 +73,7 @@ public final class ProxyStateExporterTest {
public void assertExportWithContextManager() {
ContextManager contextManager = mockContextManager();
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
- when(ProxyContext.getInstance().getStateContext()).thenReturn(Optional.of(mock(StateContext.class, RETURNS_DEEP_STUBS)));
+ when(ProxyContext.getInstance().getInstanceStateContext()).thenReturn(Optional.of(mock(InstanceStateContext.class, RETURNS_DEEP_STUBS)));
Optional<GaugeMetricFamilyMetricsCollector> collector = new ProxyStateExporter().export("FIXTURE");
assertTrue(collector.isPresent());
assertThat(collector.get().toString(), is("0"));
diff --git a/distsql/parser/src/main/antlr4/imports/Keyword.g4 b/distsql/parser/src/main/antlr4/imports/Keyword.g4
index 2210bebad55..246204dcc5a 100644
--- a/distsql/parser/src/main/antlr4/imports/Keyword.g4
+++ b/distsql/parser/src/main/antlr4/imports/Keyword.g4
@@ -342,3 +342,15 @@ LIKE
NOT
: N O T
;
+
+LOCK
+ : L O C K
+ ;
+
+CLUSTER
+ : C L U S T E R
+ ;
+
+LOCK_STRATEGY
+ : L O C K UL_ S T R A T E G Y
+ ;
diff --git a/distsql/parser/src/main/antlr4/imports/RALStatement.g4 b/distsql/parser/src/main/antlr4/imports/RALStatement.g4
index d127cfc2c14..867a6ea03f2 100644
--- a/distsql/parser/src/main/antlr4/imports/RALStatement.g4
+++ b/distsql/parser/src/main/antlr4/imports/RALStatement.g4
@@ -103,6 +103,10 @@ alterMigrationRule
: ALTER MIGRATION RULE inventoryIncrementalRule?
;
+lockCluster
+ : LOCK CLUSTER WITH lockStrategy
+ ;
+
inventoryIncrementalRule
: LP_ readDefinition? (COMMA_? writeDefinition)? (COMMA_? streamChannel)? RP_
;
@@ -171,6 +175,10 @@ fromSegment
: FROM STORAGE UNIT storageUnitName (SCHEMA schemaName)?
;
+lockStrategy
+ : LOCK_STRATEGY LP_ algorithmDefinition RP_
+ ;
+
label
: IDENTIFIER_
;
diff --git a/distsql/parser/src/main/antlr4/org/apache/shardingsphere/distsql/parser/autogen/KernelDistSQLStatement.g4 b/distsql/parser/src/main/antlr4/org/apache/shardingsphere/distsql/parser/autogen/KernelDistSQLStatement.g4
index 7153f3112a7..212e77299db 100644
--- a/distsql/parser/src/main/antlr4/org/apache/shardingsphere/distsql/parser/autogen/KernelDistSQLStatement.g4
+++ b/distsql/parser/src/main/antlr4/org/apache/shardingsphere/distsql/parser/autogen/KernelDistSQLStatement.g4
@@ -51,5 +51,6 @@ execute
| convertYamlConfiguration
| showMigrationRule
| alterMigrationRule
+ | lockCluster
) SEMI?
;
diff --git a/distsql/parser/src/main/java/org/apache/shardingsphere/distsql/parser/core/kernel/KernelDistSQLStatementVisitor.java b/distsql/parser/src/main/java/org/apache/shardingsphere/distsql/parser/core/kernel/KernelDistSQLStatementVisitor.java
index 281c4acb097..86385dd2e04 100644
--- a/distsql/parser/src/main/java/org/apache/shardingsphere/distsql/parser/core/kernel/KernelDistSQLStatementVisitor.java
+++ b/distsql/parser/src/main/java/org/apache/shardingsphere/distsql/parser/core/kernel/KernelDistSQLStatementVisitor.java
@@ -37,6 +37,7 @@ import org.apache.shardingsphere.distsql.parser.autogen.KernelDistSQLStatementPa
import org.apache.shardingsphere.distsql.parser.autogen.KernelDistSQLStatementParser.InstanceIdContext;
import org.apache.shardingsphere.distsql.parser.autogen.KernelDistSQLStatementParser.InventoryIncrementalRuleContext;
import org.apache.shardingsphere.distsql.parser.autogen.KernelDistSQLStatementParser.LabelComputeNodeContext;
+import org.apache.shardingsphere.distsql.parser.autogen.KernelDistSQLStatementParser.LockClusterContext;
import org.apache.shardingsphere.distsql.parser.autogen.KernelDistSQLStatementParser.PasswordContext;
import org.apache.shardingsphere.distsql.parser.autogen.KernelDistSQLStatementParser.PropertiesDefinitionContext;
import org.apache.shardingsphere.distsql.parser.autogen.KernelDistSQLStatementParser.PropertyContext;
@@ -87,6 +88,7 @@ import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.AlterInv
import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.ImportDatabaseConfigurationStatement;
import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.ImportMetaDataStatement;
import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.LabelComputeNodeStatement;
+import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.LockClusterStatement;
import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.RefreshDatabaseMetaDataStatement;
import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.RefreshTableMetaDataStatement;
import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.SetDistVariableStatement;
@@ -357,6 +359,11 @@ public final class KernelDistSQLStatementVisitor extends KernelDistSQLStatementB
return null == ctx ? null : (AlgorithmSegment) visit(ctx);
}
+ @Override
+ public ASTNode visitLockCluster(final LockClusterContext ctx) {
+ return new LockClusterStatement((AlgorithmSegment) visitAlgorithmDefinition(ctx.lockStrategy().algorithmDefinition()));
+ }
+
@Override
public ASTNode visitAlgorithmDefinition(final AlgorithmDefinitionContext ctx) {
return new AlgorithmSegment(getIdentifierValue(ctx.algorithmTypeName()), buildProperties(ctx.propertiesDefinition()));
diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java b/distsql/statement/src/main/java/org/apache/shardingsphere/distsql/parser/statement/ral/updatable/LockClusterStatement.java
similarity index 70%
copy from mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
copy to distsql/statement/src/main/java/org/apache/shardingsphere/distsql/parser/statement/ral/updatable/LockClusterStatement.java
index d7f1df5bb67..b1520eccc4b 100644
--- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
+++ b/distsql/statement/src/main/java/org/apache/shardingsphere/distsql/parser/statement/ral/updatable/LockClusterStatement.java
@@ -15,20 +15,19 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.mode.metadata.compute.event;
+package org.apache.shardingsphere.distsql.parser.statement.ral.updatable;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.distsql.parser.segment.AlgorithmSegment;
+import org.apache.shardingsphere.distsql.parser.statement.ral.UpdatableRALStatement;
/**
- * Compute node status changed event.
+ * Lock cluster statement.
*/
@RequiredArgsConstructor
@Getter
-public final class ComputeNodeStatusChangedEvent {
+public final class LockClusterStatement extends UpdatableRALStatement {
- private final String instanceId;
-
- private final StateType state;
+ private final AlgorithmSegment lockStrategy;
}
diff --git a/docs/document/content/dev-manual/mode.cn.md b/docs/document/content/dev-manual/mode.cn.md
index 3450932aecc..46339d1f9c2 100644
--- a/docs/document/content/dev-manual/mode.cn.md
+++ b/docs/document/content/dev-manual/mode.cn.md
@@ -52,11 +52,13 @@ chapter = true
### 已知实现
-| *配置标识* | *详细说明* | *全限定类名* |
-| ----------------------------------------------------------------------- | --------------------------------------| ---------------------------- |
-| Types: ADDED, UPDATED, DELETED; WatchingKeys: /nodes/compute_nodes | 计算节点状态变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.watcher.ComputeNodeStateChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/watcher/ComputeNodeStateChangedWatcher.java) |
-| Types: ADDED, UPDATED, DELETED; WatchingKeys: /metadata/${databaseName} | 元数据变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.metadata.watcher.MetaDataChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/metadata/watcher/MetaDataChangedWatcher.java) |
-| Types: ADDED, UPDATED; WatchingKeys: /props | 属性变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.PropertiesChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/config/watcher/PropertiesChangedWatcher.java) |
-| Types: UPDATED; WatchingKeys: /rules | 全局规则变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.GlobalRuleChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/config/watcher/GlobalRuleChangedWatcher.java) |
-| Types: ADDED, UPDATED, DELETED; WatchingKeys: /sys_data | 系统库变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.ShardingSphereDataChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/data/ShardingSphereDataChangedWatcher.java) |
-| Types: ADDED, UPDATED, DELETED; WatchingKeys: /nodes/storage_nodes | 存储节点状态变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.storage.watcher.StorageNodeStateChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/storage/watcher/StorageNodeStateChangedWatcher.java) |
+| *配置标识* | *详细说明* | *全限定类名* |
+|---------------------------------------------------------------------------|-------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| Types: ADDED, UPDATED, DELETED; WatchingKeys: /nodes/compute_nodes/status | 集群状态变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.watcher.ClusterStateChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/ClusterStateChangedWatcher.java) |
+| Types: ADDED, UPDATED, DELETED; WatchingKeys: /nodes/compute_nodes | 计算节点状态变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.watcher.ComputeNodeStateChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/watcher/ComputeNodeStateChangedWatcher.java) |
+| Types: ADDED, UPDATED, DELETED; WatchingKeys: /metadata/${databaseName} | 元数据变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.metadata.watcher.MetaDataChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/metadata/watcher/MetaDataChangedWatcher.java) |
+| Types: ADDED, UPDATED; WatchingKeys: /props | 属性变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.PropertiesChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/config/watcher/PropertiesChangedWatcher.java) |
+| Types: UPDATED; WatchingKeys: /rules | 全局规则变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.GlobalRuleChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/config/watcher/GlobalRuleChangedWatcher.java) |
+| Types: ADDED, UPDATED, DELETED; WatchingKeys: /sys_data | 系统库变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.ShardingSphereDataChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/data/ShardingSphereDataChangedWatcher.java) |
+| Types: ADDED, UPDATED, DELETED; WatchingKeys: /nodes/storage_nodes | 存储节点状态变化监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.storage.watcher.StorageNodeStateChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/storage/watcher/StorageNodeStateChangedWatcher.java) |
+| Types: DELETED; WatchingKeys: /lock/exclusive/locks/cluster_lock | 集群锁释放监听器 | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.watcher.lock.ClusterLockDeletedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/lock/ClusterLockDeletedWatcher.java) |
diff --git a/docs/document/content/dev-manual/mode.en.md b/docs/document/content/dev-manual/mode.en.md
index fe5e00b8e0a..f80fec4572f 100644
--- a/docs/document/content/dev-manual/mode.en.md
+++ b/docs/document/content/dev-manual/mode.en.md
@@ -52,12 +52,13 @@ Governance listener definition
### Implementation classes
-| *Configuration Type* | *Description* | *Fully-qualified class name* |
-| ----------------------------------------------------------------------- | --------------------------------------------- | ---------------------------- |
-| Types: ADDED, UPDATED, DELETED; WatchingKeys: /nodes/compute_nodes | Compute node state change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.watcher.ComputeNodeStateChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/watcher/ComputeNodeStateChangedWatcher.java) |
-| Types: ADDED, UPDATED, DELETED; WatchingKeys: /metadata/${databaseName} | Metadata change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.metadata.watcher.MetaDataChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/metadata/watcher/MetaDataChangedWatcher.java) |
-| Types: ADDED, UPDATED; WatchingKeys: /props | Property change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.PropertiesChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/config/watcher/PropertiesChangedWatcher.java) |
-| Types: UPDATED; WatchingKeys: /rules | The global rule configuration change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.GlobalRuleChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/config/watcher/GlobalRuleChangedWatcher.java) |
-| Types: ADDED, UPDATED, DELETED; WatchingKeys: /sys_data | System database change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.ShardingSphereDataChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/data/ShardingSphereDataChangedWatcher.java) |
-| Types: ADDED, UPDATED, DELETED; WatchingKeys: /nodes/storage_nodes | Storage node state change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.storage.watcher.StorageNodeStateChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/storage/watcher/StorageNodeStateChangedWatcher.java) |
-
+| *Configuration Type* | *Description* | *Fully-qualified class name* |
+|---------------------------------------------------------------------------|-----------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| Types: ADDED, UPDATED, DELETED; WatchingKeys: /nodes/compute_nodes/status | Cluster state change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.watcher.ClusterStateChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/ClusterStateChangedWatcher.java) |
+| Types: ADDED, UPDATED, DELETED; WatchingKeys: /nodes/compute_nodes | Compute node state change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.watcher.ComputeNodeStateChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/watcher/ComputeNodeStateChangedWatcher.java) |
+| Types: ADDED, UPDATED, DELETED; WatchingKeys: /metadata/${databaseName} | Metadata change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.metadata.watcher.MetaDataChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/metadata/watcher/MetaDataChangedWatcher.java) |
+| Types: ADDED, UPDATED; WatchingKeys: /props | Property change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.PropertiesChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/config/watcher/PropertiesChangedWatcher.java) |
+| Types: UPDATED; WatchingKeys: /rules | The global rule configuration change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.GlobalRuleChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/config/watcher/GlobalRuleChangedWatcher.java) |
+| Types: ADDED, UPDATED, DELETED; WatchingKeys: /sys_data | System database change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.ShardingSphereDataChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/data/ShardingSphereDataChangedWatcher.java) |
+| Types: ADDED, UPDATED, DELETED; WatchingKeys: /nodes/storage_nodes | Storage node state change listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.storage.watcher.StorageNodeStateChangedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/storage/watcher/StorageNodeStateChangedWatcher.java) |
+| Types: DELETED; WatchingKeys: /lock/exclusive/locks/cluster_lock | Cluster lock release listener | [`org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.watcher.lock.ClusterLockDeletedWatcher`](https://github.com/apache/shardingsphere/blob/master/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/lock/ClusterLockDeletedWatcher.java) |
diff --git a/docs/document/content/user-manual/error-code/sql-error-code.cn.md b/docs/document/content/user-manual/error-code/sql-error-code.cn.md
index 65c504568aa..72d55d22532 100644
--- a/docs/document/content/user-manual/error-code/sql-error-code.cn.md
+++ b/docs/document/content/user-manual/error-code/sql-error-code.cn.md
@@ -48,15 +48,16 @@ SQL 错误码以标准的 SQL State,Vendor Code 和详细错误信息提供,
### 连接
-| SQL State | Vendor Code | 错误信息 |
-| --------- | ----------- | ------ |
-| 08000 | 13000 | Can not register driver, reason is: %s |
-| 01000 | 13010 | Circuit break open, the request has been ignored. |
-| 01000 | 13011 | The current instance is read-only, Not allowed write traffic. |
+| SQL State | Vendor Code | 错误信息 |
+|-----------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| 08000 | 13000 | Can not register driver, reason is: %s |
+| 01000 | 13010 | Circuit break open, the request has been ignored. |
+| 01000 | 13011 | The cluster status is read-only. |
+| 01000 | 13012 | The cluster status is unavailable. |
| 08000 | 13020 | Can not get %d connections one time, partition succeed connection(%d) have released. Please consider increasing the \`maxPoolSize\` of the data sources or decreasing the \`max-connections-size-per-query\` in properties. |
-| 08000 | 13030 | Connection has been closed. |
-| 08000 | 13031 | Result set has been closed. |
-| HY000 | 13090 | Load datetime from database failed, reason: %s |
+| 08000 | 13030 | Connection has been closed. |
+| 08000 | 13031 | Result set has been closed. |
+| HY000 | 13090 | Load datetime from database failed, reason: %s |
### 事务
diff --git a/docs/document/content/user-manual/error-code/sql-error-code.en.md b/docs/document/content/user-manual/error-code/sql-error-code.en.md
index cc2043bed40..2a289c3fd5c 100644
--- a/docs/document/content/user-manual/error-code/sql-error-code.en.md
+++ b/docs/document/content/user-manual/error-code/sql-error-code.en.md
@@ -48,15 +48,16 @@ SQL error codes provide by standard `SQL State`, `Vendor Code` and `Reason`, whi
### Connection
-| SQL State | Vendor Code | Reason |
-| --------- | ----------- | ------ |
-| 08000 | 13000 | Can not register driver, reason is: %s |
-| 01000 | 13010 | Circuit break open, the request has been ignored. |
-| 01000 | 13011 | The current instance is read-only, Not allowed write traffic. |
+| SQL State | Vendor Code | Reason |
+|-----------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| 08000 | 13000 | Can not register driver, reason is: %s |
+| 01000 | 13010 | Circuit break open, the request has been ignored. |
+| 01000 | 13011 | The cluster status is read-only. |
+| 01000 | 13012 | The cluster status is unavailable. |
| 08000 | 13020 | Can not get %d connections one time, partition succeed connection(%d) have released. Please consider increasing the \`maxPoolSize\` of the data sources or decreasing the \`max-connections-size-per-query\` in properties. |
-| 08000 | 13030 | Connection has been closed. |
-| 08000 | 13031 | Result set has been closed. |
-| HY000 | 13090 | Load datetime from database failed, reason: %s |
+| 08000 | 13030 | Connection has been closed. |
+| 08000 | 13031 | Result set has been closed. |
+| HY000 | 13090 | Load datetime from database failed, reason: %s |
### Transaction
diff --git a/infra/common/src/main/java/org/apache/shardingsphere/infra/instance/ComputeNodeInstance.java b/infra/common/src/main/java/org/apache/shardingsphere/infra/instance/ComputeNodeInstance.java
index 70f8647766d..24817cedc67 100644
--- a/infra/common/src/main/java/org/apache/shardingsphere/infra/instance/ComputeNodeInstance.java
+++ b/infra/common/src/main/java/org/apache/shardingsphere/infra/instance/ComputeNodeInstance.java
@@ -20,8 +20,8 @@ package org.apache.shardingsphere.infra.instance;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaData;
-import org.apache.shardingsphere.infra.state.StateContext;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.state.instance.InstanceStateContext;
+import org.apache.shardingsphere.infra.state.instance.InstanceState;
import java.util.Collection;
import java.util.LinkedList;
@@ -34,7 +34,7 @@ public final class ComputeNodeInstance {
private final InstanceMetaData metaData;
- private final StateContext state = new StateContext();
+ private final InstanceStateContext state = new InstanceStateContext();
private Collection<String> labels = new LinkedList<>();
@@ -63,7 +63,7 @@ public final class ComputeNodeInstance {
* @param status status
*/
public void switchState(final String status) {
- state.switchState(StateType.CIRCUIT_BREAK, StateType.CIRCUIT_BREAK.name().equals(status));
+ state.switchState(InstanceState.CIRCUIT_BREAK, InstanceState.CIRCUIT_BREAK.name().equals(status));
}
/**
diff --git a/infra/common/src/main/java/org/apache/shardingsphere/infra/state/StateType.java b/infra/common/src/main/java/org/apache/shardingsphere/infra/state/cluster/ClusterState.java
similarity index 86%
copy from infra/common/src/main/java/org/apache/shardingsphere/infra/state/StateType.java
copy to infra/common/src/main/java/org/apache/shardingsphere/infra/state/cluster/ClusterState.java
index e68c1d7e329..f3fbb5d96d0 100644
--- a/infra/common/src/main/java/org/apache/shardingsphere/infra/state/StateType.java
+++ b/infra/common/src/main/java/org/apache/shardingsphere/infra/state/cluster/ClusterState.java
@@ -15,12 +15,12 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.infra.state;
+package org.apache.shardingsphere.infra.state.cluster;
/**
- * State type.
+ * Cluster state.
*/
-public enum StateType {
+public enum ClusterState {
- OK, CIRCUIT_BREAK, LOCK
+ OK, READ_ONLY, UNAVAILABLE
}
diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java b/infra/common/src/main/java/org/apache/shardingsphere/infra/state/cluster/ClusterStateContext.java
similarity index 59%
copy from mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
copy to infra/common/src/main/java/org/apache/shardingsphere/infra/state/cluster/ClusterStateContext.java
index d7f1df5bb67..10d9ce6d025 100644
--- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
+++ b/infra/common/src/main/java/org/apache/shardingsphere/infra/state/cluster/ClusterStateContext.java
@@ -15,20 +15,30 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.mode.metadata.compute.event;
+package org.apache.shardingsphere.infra.state.cluster;
import lombok.Getter;
-import lombok.RequiredArgsConstructor;
-import org.apache.shardingsphere.infra.state.StateType;
/**
- * Compute node status changed event.
+ * Cluster state context.
*/
-@RequiredArgsConstructor
-@Getter
-public final class ComputeNodeStatusChangedEvent {
+public final class ClusterStateContext {
- private final String instanceId;
+ @Getter
+ private ClusterState currentState = ClusterState.OK;
- private final StateType state;
+ /**
+ * Switch state.
+ *
+ * @param state state
+ */
+ public void switchState(final ClusterState state) {
+ if (currentState == state) {
+ return;
+ }
+ if (ClusterState.OK != currentState && ClusterState.OK != state) {
+ throw new IllegalStateException("Cluster is locked");
+ }
+ currentState = state;
+ }
}
diff --git a/infra/common/src/main/java/org/apache/shardingsphere/infra/state/StateType.java b/infra/common/src/main/java/org/apache/shardingsphere/infra/state/instance/InstanceState.java
similarity index 89%
copy from infra/common/src/main/java/org/apache/shardingsphere/infra/state/StateType.java
copy to infra/common/src/main/java/org/apache/shardingsphere/infra/state/instance/InstanceState.java
index e68c1d7e329..d03ccb48e3e 100644
--- a/infra/common/src/main/java/org/apache/shardingsphere/infra/state/StateType.java
+++ b/infra/common/src/main/java/org/apache/shardingsphere/infra/state/instance/InstanceState.java
@@ -15,12 +15,12 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.infra.state;
+package org.apache.shardingsphere.infra.state.instance;
/**
- * State type.
+ * Instance state.
*/
-public enum StateType {
+public enum InstanceState {
OK, CIRCUIT_BREAK, LOCK
}
diff --git a/infra/common/src/main/java/org/apache/shardingsphere/infra/state/StateContext.java b/infra/common/src/main/java/org/apache/shardingsphere/infra/state/instance/InstanceStateContext.java
similarity index 65%
rename from infra/common/src/main/java/org/apache/shardingsphere/infra/state/StateContext.java
rename to infra/common/src/main/java/org/apache/shardingsphere/infra/state/instance/InstanceStateContext.java
index f39126bc4e3..0e7fb863d96 100644
--- a/infra/common/src/main/java/org/apache/shardingsphere/infra/state/StateContext.java
+++ b/infra/common/src/main/java/org/apache/shardingsphere/infra/state/instance/InstanceStateContext.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.infra.state;
+package org.apache.shardingsphere.infra.state.instance;
import java.util.Collections;
import java.util.Deque;
@@ -23,23 +23,23 @@ import java.util.Optional;
import java.util.concurrent.ConcurrentLinkedDeque;
/**
- * State context.
+ * Instance state context.
*/
-public final class StateContext {
+public final class InstanceStateContext {
- private final Deque<StateType> currentState = new ConcurrentLinkedDeque<>(Collections.singleton(StateType.OK));
+ private final Deque<InstanceState> currentState = new ConcurrentLinkedDeque<>(Collections.singleton(InstanceState.OK));
/**
* Switch state.
- *
- * @param type state type
- * @param on true if state type is valid, false if not
+ *
+ * @param state state
+ * @param on true if state is valid, false if not
*/
- public void switchState(final StateType type, final boolean on) {
+ public void switchState(final InstanceState state, final boolean on) {
if (on) {
- currentState.push(type);
+ currentState.push(state);
} else {
- if (getCurrentState().equals(type)) {
+ if (getCurrentState().equals(state)) {
recoverState();
}
}
@@ -52,9 +52,9 @@ public final class StateContext {
/**
* Get current state.
*
- * @return current state type
+ * @return current state
*/
- public StateType getCurrentState() {
- return Optional.ofNullable(currentState.peek()).orElse(StateType.OK);
+ public InstanceState getCurrentState() {
+ return Optional.ofNullable(currentState.peek()).orElse(InstanceState.OK);
}
}
diff --git a/infra/common/src/test/java/org/apache/shardingsphere/infra/instance/InstanceContextTest.java b/infra/common/src/test/java/org/apache/shardingsphere/infra/instance/InstanceContextTest.java
index 674a627e711..d54d80512a0 100644
--- a/infra/common/src/test/java/org/apache/shardingsphere/infra/instance/InstanceContextTest.java
+++ b/infra/common/src/test/java/org/apache/shardingsphere/infra/instance/InstanceContextTest.java
@@ -22,7 +22,7 @@ import org.apache.shardingsphere.infra.instance.fixture.WorkerIdGeneratorFixture
import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaData;
import org.apache.shardingsphere.infra.instance.mode.ModeContextManager;
import org.apache.shardingsphere.infra.lock.LockContext;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.state.instance.InstanceState;
import org.apache.shardingsphere.infra.util.eventbus.EventBusContext;
import org.junit.Test;
@@ -56,14 +56,14 @@ public final class InstanceContextTest {
when(instanceMetaData.getId()).thenReturn("foo_instance_id");
InstanceContext context = new InstanceContext(new ComputeNodeInstance(instanceMetaData),
new WorkerIdGeneratorFixture(Integer.MIN_VALUE), modeConfig, modeContextManager, lockContext, eventBusContext);
- StateType actual = context.getInstance().getState().getCurrentState();
- assertThat(actual, is(StateType.OK));
- context.updateInstanceStatus(instanceMetaData.getId(), StateType.CIRCUIT_BREAK.name());
+ InstanceState actual = context.getInstance().getState().getCurrentState();
+ assertThat(actual, is(InstanceState.OK));
+ context.updateInstanceStatus(instanceMetaData.getId(), InstanceState.CIRCUIT_BREAK.name());
actual = context.getInstance().getState().getCurrentState();
- assertThat(actual, is(StateType.CIRCUIT_BREAK));
- context.updateInstanceStatus(instanceMetaData.getId(), StateType.OK.name());
+ assertThat(actual, is(InstanceState.CIRCUIT_BREAK));
+ context.updateInstanceStatus(instanceMetaData.getId(), InstanceState.OK.name());
actual = context.getInstance().getState().getCurrentState();
- assertThat(actual, is(StateType.OK));
+ assertThat(actual, is(InstanceState.OK));
}
@Test
diff --git a/infra/common/src/test/java/org/apache/shardingsphere/infra/state/StateContextTest.java b/infra/common/src/test/java/org/apache/shardingsphere/infra/state/InstanceStateContextTest.java
similarity index 52%
rename from infra/common/src/test/java/org/apache/shardingsphere/infra/state/StateContextTest.java
rename to infra/common/src/test/java/org/apache/shardingsphere/infra/state/InstanceStateContextTest.java
index f1d7e629d9d..5bbbb973bda 100644
--- a/infra/common/src/test/java/org/apache/shardingsphere/infra/state/StateContextTest.java
+++ b/infra/common/src/test/java/org/apache/shardingsphere/infra/state/InstanceStateContextTest.java
@@ -17,34 +17,36 @@
package org.apache.shardingsphere.infra.state;
+import org.apache.shardingsphere.infra.state.instance.InstanceStateContext;
+import org.apache.shardingsphere.infra.state.instance.InstanceState;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
-public final class StateContextTest {
+public final class InstanceStateContextTest {
- private final StateContext stateContext = new StateContext();
+ private final InstanceStateContext instanceStateContext = new InstanceStateContext();
@Test
public void assertSwitchStateWithCircuitBreakOn() {
- stateContext.switchState(StateType.CIRCUIT_BREAK, true);
- assertThat(stateContext.getCurrentState(), is(StateType.CIRCUIT_BREAK));
- stateContext.switchState(StateType.CIRCUIT_BREAK, false);
+ instanceStateContext.switchState(InstanceState.CIRCUIT_BREAK, true);
+ assertThat(instanceStateContext.getCurrentState(), is(InstanceState.CIRCUIT_BREAK));
+ instanceStateContext.switchState(InstanceState.CIRCUIT_BREAK, false);
}
@Test
public void assertSwitchStateWithCircuitBreakOff() {
- stateContext.switchState(StateType.CIRCUIT_BREAK, false);
- assertThat(stateContext.getCurrentState(), is(StateType.OK));
+ instanceStateContext.switchState(InstanceState.CIRCUIT_BREAK, false);
+ assertThat(instanceStateContext.getCurrentState(), is(InstanceState.OK));
}
@Test
public void assertSwitchStateWithMultiState() {
- stateContext.switchState(StateType.CIRCUIT_BREAK, true);
- stateContext.switchState(StateType.LOCK, true);
- assertThat(stateContext.getCurrentState(), is(StateType.LOCK));
- stateContext.switchState(StateType.LOCK, false);
- assertThat(stateContext.getCurrentState(), is(StateType.CIRCUIT_BREAK));
+ instanceStateContext.switchState(InstanceState.CIRCUIT_BREAK, true);
+ instanceStateContext.switchState(InstanceState.LOCK, true);
+ assertThat(instanceStateContext.getCurrentState(), is(InstanceState.LOCK));
+ instanceStateContext.switchState(InstanceState.LOCK, false);
+ assertThat(instanceStateContext.getCurrentState(), is(InstanceState.CIRCUIT_BREAK));
}
}
diff --git a/jdbc/core/src/test/java/org/apache/shardingsphere/driver/jdbc/core/datasource/ShardingSphereDataSourceTest.java b/jdbc/core/src/test/java/org/apache/shardingsphere/driver/jdbc/core/datasource/ShardingSphereDataSourceTest.java
index 2dab45a10d0..2026dd8e9f4 100644
--- a/jdbc/core/src/test/java/org/apache/shardingsphere/driver/jdbc/core/datasource/ShardingSphereDataSourceTest.java
+++ b/jdbc/core/src/test/java/org/apache/shardingsphere/driver/jdbc/core/datasource/ShardingSphereDataSourceTest.java
@@ -23,7 +23,7 @@ import org.apache.shardingsphere.driver.jdbc.core.connection.ShardingSphereConne
import org.apache.shardingsphere.infra.config.rule.RuleConfiguration;
import org.apache.shardingsphere.infra.database.DefaultDatabase;
import org.apache.shardingsphere.infra.executor.sql.execute.engine.ConnectionMode;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.state.instance.InstanceState;
import org.apache.shardingsphere.mode.manager.ContextManager;
import org.apache.shardingsphere.parser.config.SQLParserRuleConfiguration;
import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
@@ -62,7 +62,7 @@ public final class ShardingSphereDataSourceTest {
ShardingSphereDataSource actual = new ShardingSphereDataSource(DefaultDatabase.LOGIC_NAME, null);
ContextManager contextManager = getContextManager(actual);
assertNotNull(contextManager.getMetaDataContexts().getMetaData().getDatabase(DefaultDatabase.LOGIC_NAME));
- assertThat(contextManager.getInstanceContext().getInstance().getState().getCurrentState(), is(StateType.OK));
+ assertThat(contextManager.getInstanceContext().getInstance().getState().getCurrentState(), is(InstanceState.OK));
assertTrue(contextManager.getDataSourceMap(DefaultDatabase.LOGIC_NAME).isEmpty());
}
@@ -73,7 +73,7 @@ public final class ShardingSphereDataSourceTest {
ShardingSphereDataSource actual = createShardingSphereDataSource(new MockedDataSource(connection));
ContextManager contextManager = getContextManager(actual);
assertNotNull(contextManager.getMetaDataContexts().getMetaData().getDatabase(DefaultDatabase.LOGIC_NAME));
- assertThat(contextManager.getInstanceContext().getInstance().getState().getCurrentState(), is(StateType.OK));
+ assertThat(contextManager.getInstanceContext().getInstance().getState().getCurrentState(), is(InstanceState.OK));
assertThat(contextManager.getDataSourceMap(DefaultDatabase.LOGIC_NAME).size(), is(1));
assertThat(contextManager.getDataSourceMap(DefaultDatabase.LOGIC_NAME).get("ds").getConnection().getMetaData().getURL(), is("jdbc:mock://127.0.0.1/foo_ds"));
}
diff --git a/jdbc/core/src/test/java/org/apache/shardingsphere/driver/state/DriverStateContextTest.java b/jdbc/core/src/test/java/org/apache/shardingsphere/driver/state/DriverStateContextTest.java
index 4c7b5445437..8505665b1a2 100644
--- a/jdbc/core/src/test/java/org/apache/shardingsphere/driver/state/DriverStateContextTest.java
+++ b/jdbc/core/src/test/java/org/apache/shardingsphere/driver/state/DriverStateContextTest.java
@@ -25,7 +25,7 @@ import org.apache.shardingsphere.infra.database.type.dialect.MySQLDatabaseType;
import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData;
import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
import org.apache.shardingsphere.infra.metadata.database.rule.ShardingSphereRuleMetaData;
-import org.apache.shardingsphere.infra.state.StateContext;
+import org.apache.shardingsphere.infra.state.instance.InstanceStateContext;
import org.apache.shardingsphere.mode.manager.ContextManager;
import org.apache.shardingsphere.mode.metadata.MetaDataContexts;
import org.apache.shardingsphere.mode.metadata.persist.MetaDataPersistService;
@@ -65,7 +65,7 @@ public final class DriverStateContextTest {
MetaDataContexts metaDataContexts = new MetaDataContexts(
mock(MetaDataPersistService.class), new ShardingSphereMetaData(databases, globalRuleMetaData, new ConfigurationProperties(new Properties())));
when(contextManager.getMetaDataContexts()).thenReturn(metaDataContexts);
- when(contextManager.getInstanceContext().getInstance().getState()).thenReturn(new StateContext());
+ when(contextManager.getInstanceContext().getInstance().getState()).thenReturn(new InstanceStateContext());
}
private Map<String, ShardingSphereDatabase> mockDatabases() {
diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/manager/ContextManager.java b/mode/core/src/main/java/org/apache/shardingsphere/mode/manager/ContextManager.java
index 73f1a009d6a..547f2631bd8 100644
--- a/mode/core/src/main/java/org/apache/shardingsphere/mode/manager/ContextManager.java
+++ b/mode/core/src/main/java/org/apache/shardingsphere/mode/manager/ContextManager.java
@@ -48,6 +48,8 @@ import org.apache.shardingsphere.infra.rule.builder.global.GlobalRulesBuilder;
import org.apache.shardingsphere.infra.rule.identifier.type.DataNodeContainedRule;
import org.apache.shardingsphere.infra.rule.identifier.type.MutableDataNodeRule;
import org.apache.shardingsphere.infra.rule.identifier.type.ResourceHeldRule;
+import org.apache.shardingsphere.infra.state.cluster.ClusterStateContext;
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
import org.apache.shardingsphere.infra.yaml.data.pojo.YamlShardingSphereRowData;
import org.apache.shardingsphere.infra.yaml.data.swapper.YamlShardingSphereRowDataSwapper;
import org.apache.shardingsphere.mode.manager.switcher.ResourceSwitchManager;
@@ -82,6 +84,8 @@ public final class ContextManager implements AutoCloseable {
private final ExecutorEngine executorEngine;
+ private final ClusterStateContext clusterStateContext = new ClusterStateContext();
+
public ContextManager(final MetaDataContexts metaDataContexts, final InstanceContext instanceContext) {
this.metaDataContexts = metaDataContexts;
this.instanceContext = instanceContext;
@@ -671,6 +675,18 @@ public final class ContextManager implements AutoCloseable {
metaDataContexts.getShardingSphereData().getDatabase(databaseName).getSchema(schemaName).getTable(tableName).getRows().removeIf(each -> uniqueKey.equals(each.getUniqueKey()));
}
+ /**
+ * Update cluster state.
+ *
+ * @param status status
+ */
+ public void updateClusterState(final String status) {
+ try {
+ clusterStateContext.switchState(ClusterState.valueOf(status));
+ } catch (IllegalArgumentException ignore) {
+ }
+ }
+
@Override
public void close() {
executorEngine.close();
diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java b/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
index d7f1df5bb67..bb6ad1dae5d 100644
--- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
+++ b/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
@@ -19,7 +19,7 @@ package org.apache.shardingsphere.mode.metadata.compute.event;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.state.instance.InstanceState;
/**
* Compute node status changed event.
@@ -30,5 +30,5 @@ public final class ComputeNodeStatusChangedEvent {
private final String instanceId;
- private final StateType state;
+ private final InstanceState state;
}
diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/persist/node/ComputeNode.java b/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/persist/node/ComputeNode.java
index db85780a37e..4db674b4e77 100644
--- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/persist/node/ComputeNode.java
+++ b/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/persist/node/ComputeNode.java
@@ -163,6 +163,15 @@ public final class ComputeNode {
return matcher.find() ? matcher.group(2) : "";
}
+ /**
+ * Get cluster status node path.
+ *
+ * @return cluster status node path
+ */
+ public static String getClusterStatusNodePath() {
+ return String.join("/", "", ROOT_NODE, COMPUTE_NODE, STATUS_NODE);
+ }
+
/**
* Get instance status node path.
*
diff --git a/mode/core/src/test/java/org/apache/shardingsphere/mode/manager/ContextManagerTest.java b/mode/core/src/test/java/org/apache/shardingsphere/mode/manager/ContextManagerTest.java
index da2391d7264..5ae124ccc3a 100644
--- a/mode/core/src/test/java/org/apache/shardingsphere/mode/manager/ContextManagerTest.java
+++ b/mode/core/src/test/java/org/apache/shardingsphere/mode/manager/ContextManagerTest.java
@@ -34,6 +34,7 @@ import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSp
import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereTable;
import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereView;
import org.apache.shardingsphere.infra.rule.identifier.type.MutableDataNodeRule;
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
import org.apache.shardingsphere.mode.metadata.MetaDataContexts;
import org.apache.shardingsphere.mode.metadata.persist.MetaDataPersistService;
import org.apache.shardingsphere.mode.metadata.persist.service.DatabaseMetaDataPersistService;
@@ -292,6 +293,12 @@ public final class ContextManagerTest {
return result;
}
+ @Test
+ public void assertUpdateClusterStatus() {
+ contextManager.updateClusterState("READ_ONLY");
+ assertThat(contextManager.getClusterStateContext().getCurrentState(), is(ClusterState.READ_ONLY));
+ }
+
@Test
public void assertClose() throws Exception {
contextManager.close();
diff --git a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/ClusterContextManagerBuilder.java b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/ClusterContextManagerBuilder.java
index b8fb20d4a1d..aeb4096a388 100644
--- a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/ClusterContextManagerBuilder.java
+++ b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/ClusterContextManagerBuilder.java
@@ -92,12 +92,18 @@ public final class ClusterContextManagerBuilder implements ContextManagerBuilder
}
private void registerOnline(final MetaDataPersistService persistService, final RegistryCenter registryCenter, final ContextManagerBuilderParameter param, final ContextManager contextManager) {
+ loadClusterStatus(registryCenter, contextManager);
contextManager.getInstanceContext().getInstance().setLabels(param.getLabels());
contextManager.getInstanceContext().getAllClusterInstances().addAll(registryCenter.getComputeNodeStatusService().loadAllComputeNodeInstances());
new ContextManagerSubscriberFacade(persistService, registryCenter, contextManager);
registryCenter.onlineInstance(contextManager.getInstanceContext().getInstance());
}
+ private void loadClusterStatus(final RegistryCenter registryCenter, final ContextManager contextManager) {
+ registryCenter.persistClusterState(contextManager);
+ contextManager.updateClusterState(registryCenter.getClusterStatusService().loadClusterStatus());
+ }
+
@Override
public String getType() {
return "Cluster";
diff --git a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/RegistryCenter.java b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/RegistryCenter.java
index af1553a40b8..67ca1caee94 100644
--- a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/RegistryCenter.java
+++ b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/RegistryCenter.java
@@ -17,20 +17,25 @@
package org.apache.shardingsphere.mode.manager.cluster.coordinator;
+import com.google.common.base.Strings;
import lombok.Getter;
import org.apache.shardingsphere.infra.config.database.DatabaseConfiguration;
import org.apache.shardingsphere.infra.instance.ComputeNodeInstance;
import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaData;
import org.apache.shardingsphere.infra.instance.metadata.jdbc.JDBCInstanceMetaData;
import org.apache.shardingsphere.infra.util.eventbus.EventBusContext;
+import org.apache.shardingsphere.mode.manager.ContextManager;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.lock.GlobalLockPersistService;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcherFactory;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.metadata.subscriber.ShardingSphereSchemaDataRegistrySubscriber;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.service.ClusterStatusService;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.subscriber.ClusterStatusSubscriber;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.service.ComputeNodeStatusService;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.subscriber.ComputeNodeStatusSubscriber;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.storage.service.StorageNodeStatusService;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.storage.subscriber.StorageNodeStatusSubscriber;
import org.apache.shardingsphere.mode.manager.cluster.process.subscriber.ProcessRegistrySubscriber;
+import org.apache.shardingsphere.mode.metadata.persist.node.ComputeNode;
import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepository;
import org.apache.shardingsphere.mode.repository.cluster.lock.holder.DistributedLockHolder;
import org.apache.shardingsphere.mode.repository.cluster.lock.impl.props.DefaultLockTypedProperties;
@@ -49,6 +54,9 @@ public final class RegistryCenter {
@Getter
private final StorageNodeStatusService storageNodeStatusService;
+ @Getter
+ private final ClusterStatusService clusterStatusService;
+
@Getter
private final ComputeNodeStatusService computeNodeStatusService;
@@ -71,6 +79,7 @@ public final class RegistryCenter {
this.instanceMetaData = instanceMetaData;
this.databaseConfigs = databaseConfigs;
storageNodeStatusService = new StorageNodeStatusService(repository);
+ clusterStatusService = new ClusterStatusService(repository);
computeNodeStatusService = new ComputeNodeStatusService(repository);
globalLockPersistService = new GlobalLockPersistService(initDistributedLockHolder(repository));
listenerFactory = new GovernanceWatcherFactory(repository, eventBusContext, getJDBCDatabaseName());
@@ -88,6 +97,7 @@ public final class RegistryCenter {
private void createSubscribers(final ClusterPersistRepository repository) {
new ComputeNodeStatusSubscriber(this, repository);
+ new ClusterStatusSubscriber(repository, eventBusContext);
new StorageNodeStatusSubscriber(repository, eventBusContext);
new ProcessRegistrySubscriber(repository, eventBusContext);
new ShardingSphereSchemaDataRegistrySubscriber(repository, globalLockPersistService, eventBusContext);
@@ -104,4 +114,15 @@ public final class RegistryCenter {
computeNodeStatusService.persistInstanceState(computeNodeInstance.getCurrentInstanceId(), computeNodeInstance.getState());
listenerFactory.watchListeners();
}
+
+ /**
+ * Persist cluster state.
+ *
+ * @param contextManager context manager
+ */
+ public void persistClusterState(final ContextManager contextManager) {
+ if (Strings.isNullOrEmpty(repository.getDirectly(ComputeNode.getClusterStatusNodePath()))) {
+ clusterStatusService.persistClusterState(contextManager.getClusterStateContext());
+ }
+ }
}
diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/event/ClusterLockDeletedEvent.java
similarity index 69%
copy from mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
copy to mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/event/ClusterLockDeletedEvent.java
index d7f1df5bb67..f38dac50838 100644
--- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
+++ b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/event/ClusterLockDeletedEvent.java
@@ -15,20 +15,19 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.mode.metadata.compute.event;
+package org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceEvent;
/**
- * Compute node status changed event.
+ * Cluster lock deleted event.
*/
@RequiredArgsConstructor
@Getter
-public final class ComputeNodeStatusChangedEvent {
+public final class ClusterLockDeletedEvent implements GovernanceEvent {
- private final String instanceId;
-
- private final StateType state;
+ private final ClusterState state;
}
diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/event/ClusterStateEvent.java
similarity index 74%
copy from mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
copy to mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/event/ClusterStateEvent.java
index d7f1df5bb67..bb6f03c3933 100644
--- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
+++ b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/event/ClusterStateEvent.java
@@ -15,20 +15,18 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.mode.metadata.compute.event;
+package org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceEvent;
/**
- * Compute node status changed event.
+ * Cluster state event.
*/
@RequiredArgsConstructor
@Getter
-public final class ComputeNodeStatusChangedEvent {
+public final class ClusterStateEvent implements GovernanceEvent {
- private final String instanceId;
-
- private final StateType state;
+ private final String status;
}
diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/event/ClusterStatusChangedEvent.java
similarity index 76%
copy from mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
copy to mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/event/ClusterStatusChangedEvent.java
index d7f1df5bb67..88948bd713d 100644
--- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
+++ b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/event/ClusterStatusChangedEvent.java
@@ -15,20 +15,18 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.mode.metadata.compute.event;
+package org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
/**
- * Compute node status changed event.
+ * Cluster status changed event.
*/
@RequiredArgsConstructor
@Getter
-public final class ComputeNodeStatusChangedEvent {
+public final class ClusterStatusChangedEvent {
- private final String instanceId;
-
- private final StateType state;
+ private final ClusterState state;
}
diff --git a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/service/ClusterStatusService.java b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/service/ClusterStatusService.java
new file mode 100644
index 00000000000..fcfd5a7afeb
--- /dev/null
+++ b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/service/ClusterStatusService.java
@@ -0,0 +1,52 @@
+/*
+ * 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.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.service;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.shardingsphere.infra.state.cluster.ClusterStateContext;
+import org.apache.shardingsphere.mode.metadata.persist.node.ComputeNode;
+import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepository;
+
+/**
+ * Cluster status service.
+ */
+@RequiredArgsConstructor
+@Slf4j
+public final class ClusterStatusService {
+
+ private final ClusterPersistRepository repository;
+
+ /**
+ * Persist cluster state.
+ *
+ * @param state cluster state context
+ */
+ public void persistClusterState(final ClusterStateContext state) {
+ repository.persist(ComputeNode.getClusterStatusNodePath(), state.getCurrentState().name());
+ }
+
+ /**
+ * Load cluster status.
+ *
+ * @return cluster status
+ */
+ public String loadClusterStatus() {
+ return repository.getDirectly(ComputeNode.getClusterStatusNodePath());
+ }
+}
diff --git a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/subscriber/ClusterStatusSubscriber.java b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/subscriber/ClusterStatusSubscriber.java
new file mode 100644
index 00000000000..2a0b041d9ca
--- /dev/null
+++ b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/subscriber/ClusterStatusSubscriber.java
@@ -0,0 +1,48 @@
+/*
+ * 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.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.subscriber;
+
+import com.google.common.eventbus.Subscribe;
+import org.apache.shardingsphere.infra.util.eventbus.EventBusContext;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event.ClusterStatusChangedEvent;
+import org.apache.shardingsphere.mode.metadata.persist.node.ComputeNode;
+import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepository;
+
+/**
+ * Cluster status subscriber.
+ */
+@SuppressWarnings("UnstableApiUsage")
+public final class ClusterStatusSubscriber {
+
+ private final ClusterPersistRepository repository;
+
+ public ClusterStatusSubscriber(final ClusterPersistRepository repository, final EventBusContext eventBusContext) {
+ this.repository = repository;
+ eventBusContext.register(this);
+ }
+
+ /**
+ * Update cluster status.
+ *
+ * @param event cluster status changed event
+ */
+ @Subscribe
+ public void update(final ClusterStatusChangedEvent event) {
+ repository.persist(ComputeNode.getClusterStatusNodePath(), event.getState().name());
+ }
+}
diff --git a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/ClusterStateChangedWatcher.java b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/ClusterStateChangedWatcher.java
new file mode 100644
index 00000000000..f0ac4c8a543
--- /dev/null
+++ b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/ClusterStateChangedWatcher.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.watcher;
+
+import com.google.common.base.Strings;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceEvent;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcher;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event.ClusterStateEvent;
+import org.apache.shardingsphere.mode.metadata.persist.node.ComputeNode;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent.Type;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Optional;
+
+/**
+ * Cluster state changed watcher.
+ */
+public final class ClusterStateChangedWatcher implements GovernanceWatcher<GovernanceEvent> {
+
+ @Override
+ public Collection<String> getWatchingKeys(final String databaseName) {
+ return Collections.singleton(ComputeNode.getClusterStatusNodePath());
+ }
+
+ @Override
+ public Collection<Type> getWatchingTypes() {
+ return Arrays.asList(Type.ADDED, Type.UPDATED, Type.DELETED);
+ }
+
+ @Override
+ public Optional<GovernanceEvent> createGovernanceEvent(final DataChangedEvent event) {
+ String clusterStatus = ComputeNode.getClusterStatusNodePath();
+ if (!Strings.isNullOrEmpty(clusterStatus)) {
+ if (event.getKey().equals(ComputeNode.getClusterStatusNodePath()) && Type.DELETED != event.getType()) {
+ return Optional.of(new ClusterStateEvent(event.getValue()));
+ }
+ }
+ return Optional.empty();
+ }
+}
diff --git a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/lock/ClusterLockDeletedWatcher.java b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/lock/ClusterLockDeletedWatcher.java
new file mode 100644
index 00000000000..7db331a6b12
--- /dev/null
+++ b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/lock/ClusterLockDeletedWatcher.java
@@ -0,0 +1,51 @@
+/*
+ * 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.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.watcher.lock;
+
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
+import org.apache.shardingsphere.mode.lock.GlobalLockDefinition;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceEvent;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcher;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event.ClusterLockDeletedEvent;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent.Type;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Optional;
+
+/**
+ * Cluster lock deleted watcher.
+ */
+public final class ClusterLockDeletedWatcher implements GovernanceWatcher<GovernanceEvent> {
+
+ @Override
+ public Collection<String> getWatchingKeys(final String databaseName) {
+ return Collections.singleton(new GlobalLockDefinition("cluster_lock").getLockKey());
+ }
+
+ @Override
+ public Collection<Type> getWatchingTypes() {
+ return Collections.singleton(Type.DELETED);
+ }
+
+ @Override
+ public Optional<GovernanceEvent> createGovernanceEvent(final DataChangedEvent event) {
+ return Optional.of(new ClusterLockDeletedEvent(ClusterState.OK));
+ }
+}
diff --git a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/service/ComputeNodeStatusService.java b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/service/ComputeNodeStatusService.java
index 183a81766b8..cb412011bee 100644
--- a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/service/ComputeNodeStatusService.java
+++ b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/service/ComputeNodeStatusService.java
@@ -25,7 +25,7 @@ import org.apache.shardingsphere.infra.instance.ComputeNodeInstance;
import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaData;
import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaDataFactory;
import org.apache.shardingsphere.infra.instance.metadata.InstanceType;
-import org.apache.shardingsphere.infra.state.StateContext;
+import org.apache.shardingsphere.infra.state.instance.InstanceStateContext;
import org.apache.shardingsphere.infra.util.yaml.YamlEngine;
import org.apache.shardingsphere.infra.instance.ComputeNodeData;
import org.apache.shardingsphere.mode.metadata.persist.node.ComputeNode;
@@ -74,7 +74,7 @@ public final class ComputeNodeStatusService {
* @param instanceId instance id
* @param state state context
*/
- public void persistInstanceState(final String instanceId, final StateContext state) {
+ public void persistInstanceState(final String instanceId, final InstanceStateContext state) {
repository.persistEphemeral(ComputeNode.getInstanceStatusNodePath(instanceId), state.getCurrentState().name());
}
diff --git a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/subscriber/StateChangedSubscriber.java b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/subscriber/StateChangedSubscriber.java
index c65e0916761..e58cad0900a 100644
--- a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/subscriber/StateChangedSubscriber.java
+++ b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/subscriber/StateChangedSubscriber.java
@@ -26,6 +26,9 @@ import org.apache.shardingsphere.infra.rule.identifier.type.DynamicDataSourceCon
import org.apache.shardingsphere.infra.rule.identifier.type.StaticDataSourceContainedRule;
import org.apache.shardingsphere.mode.manager.ContextManager;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.RegistryCenter;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event.ClusterLockDeletedEvent;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event.ClusterStateEvent;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event.ClusterStatusChangedEvent;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.event.InstanceOfflineEvent;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.event.InstanceOnlineEvent;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.event.LabelsEvent;
@@ -56,7 +59,7 @@ public final class StateChangedSubscriber {
/**
* Renew disabled data source names.
- *
+ *
* @param event Storage node changed event
*/
@Subscribe
@@ -80,7 +83,7 @@ public final class StateChangedSubscriber {
/**
* Renew primary data source names.
- *
+ *
* @param event primary state changed event
*/
@Subscribe
@@ -95,9 +98,29 @@ public final class StateChangedSubscriber {
}
}
+ /**
+ * Reset cluster state.
+ *
+ * @param event cluster lock deleted event
+ */
+ @Subscribe
+ public synchronized void renew(final ClusterLockDeletedEvent event) {
+ contextManager.getInstanceContext().getEventBusContext().post(new ClusterStatusChangedEvent(event.getState()));
+ }
+
+ /**
+ * Renew cluster state.
+ *
+ * @param event cluster state event
+ */
+ @Subscribe
+ public synchronized void renew(final ClusterStateEvent event) {
+ contextManager.updateClusterState(event.getStatus());
+ }
+
/**
* Renew instance status.
- *
+ *
* @param event state event
*/
@Subscribe
@@ -107,7 +130,7 @@ public final class StateChangedSubscriber {
/**
* Renew instance worker id.
- *
+ *
* @param event worker id event
*/
@Subscribe
diff --git a/mode/type/cluster/core/src/main/resources/META-INF/services/org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcher b/mode/type/cluster/core/src/main/resources/META-INF/services/org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcher
index 10a83bdd843..e5b3eab147a 100644
--- a/mode/type/cluster/core/src/main/resources/META-INF/services/org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcher
+++ b/mode/type/cluster/core/src/main/resources/META-INF/services/org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcher
@@ -20,4 +20,6 @@ org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.metadata.wat
org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.GlobalRuleChangedWatcher
org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.PropertiesChangedWatcher
org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.watcher.ComputeNodeStateChangedWatcher
+org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.watcher.ClusterStateChangedWatcher
+org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.watcher.lock.ClusterLockDeletedWatcher
org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.data.ShardingSphereDataChangedWatcher
diff --git a/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/service/ClusterStatusServiceTest.java b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/service/ClusterStatusServiceTest.java
new file mode 100644
index 00000000000..9518d787cc8
--- /dev/null
+++ b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/service/ClusterStatusServiceTest.java
@@ -0,0 +1,49 @@
+/*
+ * 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.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.service;
+
+import org.apache.shardingsphere.infra.state.cluster.ClusterStateContext;
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
+import org.apache.shardingsphere.mode.metadata.persist.node.ComputeNode;
+import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepository;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import static org.mockito.Mockito.verify;
+
+@RunWith(MockitoJUnitRunner.class)
+public final class ClusterStatusServiceTest {
+
+ @Mock
+ private ClusterPersistRepository repository;
+
+ @Test
+ public void assertPersistClusterState() {
+ ClusterStatusService clusterStatusService = new ClusterStatusService(repository);
+ clusterStatusService.persistClusterState(new ClusterStateContext());
+ verify(repository).persist(ComputeNode.getClusterStatusNodePath(), ClusterState.OK.name());
+ }
+
+ @Test
+ public void assertLoadClusterStatus() {
+ new ClusterStatusService(repository).loadClusterStatus();
+ verify(repository).getDirectly(ComputeNode.getClusterStatusNodePath());
+ }
+}
diff --git a/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/ClusterStateChangedWatcherTest.java b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/ClusterStateChangedWatcherTest.java
new file mode 100644
index 00000000000..9b0c32bb96b
--- /dev/null
+++ b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/cluster/watcher/ClusterStateChangedWatcherTest.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.watcher;
+
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceEvent;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event.ClusterStateEvent;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent.Type;
+import org.junit.Test;
+
+import java.util.Optional;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+public final class ClusterStateChangedWatcherTest {
+
+ @Test
+ public void assertCreateEventWhenReadOnly() {
+ Optional<GovernanceEvent> actual = new ClusterStateChangedWatcher()
+ .createGovernanceEvent(new DataChangedEvent("/nodes/compute_nodes/status", ClusterState.READ_ONLY.name(), Type.UPDATED));
+ assertTrue(actual.isPresent());
+ assertThat(((ClusterStateEvent) actual.get()).getStatus(), is(ClusterState.READ_ONLY.name()));
+ }
+
+ @Test
+ public void assertCreateEventWhenUnavailable() {
+ Optional<GovernanceEvent> actual = new ClusterStateChangedWatcher()
+ .createGovernanceEvent(new DataChangedEvent("/nodes/compute_nodes/status", ClusterState.UNAVAILABLE.name(), Type.UPDATED));
+ assertTrue(actual.isPresent());
+ assertThat(((ClusterStateEvent) actual.get()).getStatus(), is(ClusterState.UNAVAILABLE.name()));
+ }
+
+ @Test
+ public void assertCreateEventWhenEnabled() {
+ Optional<GovernanceEvent> actual = new ClusterStateChangedWatcher()
+ .createGovernanceEvent(new DataChangedEvent("/nodes/compute_nodes/status", ClusterState.OK.name(), Type.UPDATED));
+ assertTrue(actual.isPresent());
+ assertThat(((ClusterStateEvent) actual.get()).getStatus(), is(ClusterState.OK.name()));
+ }
+}
diff --git a/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/service/ComputeNodeStatusServiceTest.java b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/service/ComputeNodeStatusServiceTest.java
index 12b7ed51a7d..f79550d56e2 100644
--- a/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/service/ComputeNodeStatusServiceTest.java
+++ b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/service/ComputeNodeStatusServiceTest.java
@@ -23,8 +23,8 @@ import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaData;
import org.apache.shardingsphere.infra.instance.metadata.InstanceType;
import org.apache.shardingsphere.infra.instance.metadata.proxy.ProxyInstanceMetaData;
import org.apache.shardingsphere.infra.instance.utils.IpUtils;
-import org.apache.shardingsphere.infra.state.StateContext;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.state.instance.InstanceStateContext;
+import org.apache.shardingsphere.infra.state.instance.InstanceState;
import org.apache.shardingsphere.infra.util.yaml.YamlEngine;
import org.apache.shardingsphere.mode.metadata.persist.node.ComputeNode;
import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepository;
@@ -76,8 +76,8 @@ public final class ComputeNodeStatusServiceTest {
ComputeNodeStatusService computeNodeStatusService = new ComputeNodeStatusService(repository);
InstanceMetaData instanceMetaData = new ProxyInstanceMetaData("foo_instance_id", 3307);
final String instanceId = instanceMetaData.getId();
- computeNodeStatusService.persistInstanceState(instanceId, new StateContext());
- verify(repository).persistEphemeral(ComputeNode.getInstanceStatusNodePath(instanceId), StateType.OK.name());
+ computeNodeStatusService.persistInstanceState(instanceId, new InstanceStateContext());
+ verify(repository).persistEphemeral(ComputeNode.getInstanceStatusNodePath(instanceId), InstanceState.OK.name());
}
@Test
diff --git a/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/watcher/ComputeNodeStateChangedWatcherTest.java b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/watcher/ComputeNodeStateChangedWatcherTest.java
index 48ad78ab48f..4c5fd920dce 100644
--- a/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/watcher/ComputeNodeStateChangedWatcherTest.java
+++ b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/registry/status/compute/watcher/ComputeNodeStateChangedWatcherTest.java
@@ -17,7 +17,7 @@
package org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.watcher;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.state.instance.InstanceState;
import org.apache.shardingsphere.infra.util.yaml.YamlEngine;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceEvent;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.event.LabelsEvent;
@@ -38,9 +38,9 @@ public final class ComputeNodeStateChangedWatcherTest {
@Test
public void assertCreateEventWhenDisabled() {
Optional<GovernanceEvent> actual = new ComputeNodeStateChangedWatcher()
- .createGovernanceEvent(new DataChangedEvent("/nodes/compute_nodes/status/foo_instance_id", StateType.CIRCUIT_BREAK.name(), Type.ADDED));
+ .createGovernanceEvent(new DataChangedEvent("/nodes/compute_nodes/status/foo_instance_id", InstanceState.CIRCUIT_BREAK.name(), Type.ADDED));
assertTrue(actual.isPresent());
- assertThat(((StateEvent) actual.get()).getStatus(), is(StateType.CIRCUIT_BREAK.name()));
+ assertThat(((StateEvent) actual.get()).getStatus(), is(InstanceState.CIRCUIT_BREAK.name()));
assertThat(((StateEvent) actual.get()).getInstanceId(), is("foo_instance_id"));
}
diff --git a/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/subscriber/StateChangedSubscriberTest.java b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/subscriber/StateChangedSubscriberTest.java
index 63afd73bbeb..11aba4a7bcf 100644
--- a/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/subscriber/StateChangedSubscriberTest.java
+++ b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/subscriber/StateChangedSubscriberTest.java
@@ -33,12 +33,15 @@ import org.apache.shardingsphere.infra.rule.ShardingSphereRule;
import org.apache.shardingsphere.infra.rule.identifier.type.DynamicDataSourceContainedRule;
import org.apache.shardingsphere.infra.rule.identifier.type.ResourceHeldRule;
import org.apache.shardingsphere.infra.rule.identifier.type.StaticDataSourceContainedRule;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
+import org.apache.shardingsphere.infra.state.instance.InstanceState;
import org.apache.shardingsphere.infra.util.eventbus.EventBusContext;
import org.apache.shardingsphere.mode.manager.ContextManager;
import org.apache.shardingsphere.mode.manager.ContextManagerBuilderParameter;
import org.apache.shardingsphere.mode.manager.cluster.ClusterContextManagerBuilder;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.RegistryCenter;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event.ClusterLockDeletedEvent;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event.ClusterStateEvent;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.event.InstanceOfflineEvent;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.event.InstanceOnlineEvent;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.event.LabelsEvent;
@@ -142,11 +145,25 @@ public final class StateChangedSubscriberTest {
verify(dynamicDataSourceRule).restartHeartBeatJob(any());
}
+ @Test
+ public void assertResetClusterStatus() {
+ ClusterLockDeletedEvent mockLockDeletedEvent = new ClusterLockDeletedEvent(ClusterState.OK);
+ subscriber.renew(mockLockDeletedEvent);
+ assertThat(contextManager.getClusterStateContext().getCurrentState(), is(ClusterState.OK));
+ }
+
+ @Test
+ public void assertRenewClusterStatus() {
+ ClusterStateEvent mockClusterStateEvent = new ClusterStateEvent("READ_ONLY");
+ subscriber.renew(mockClusterStateEvent);
+ assertThat(contextManager.getClusterStateContext().getCurrentState(), is(ClusterState.READ_ONLY));
+ }
+
@Test
public void assertRenewInstanceStatus() {
- StateEvent mockStateEvent = new StateEvent(contextManager.getInstanceContext().getInstance().getMetaData().getId(), StateType.OK.name());
+ StateEvent mockStateEvent = new StateEvent(contextManager.getInstanceContext().getInstance().getMetaData().getId(), InstanceState.OK.name());
subscriber.renew(mockStateEvent);
- assertThat(contextManager.getInstanceContext().getInstance().getState().getCurrentState(), is(StateType.OK));
+ assertThat(contextManager.getInstanceContext().getInstance().getState().getCurrentState(), is(InstanceState.OK));
}
@Test
diff --git a/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/context/ProxyContext.java b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/context/ProxyContext.java
index 190562f312d..2bf7d74b929 100644
--- a/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/context/ProxyContext.java
+++ b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/context/ProxyContext.java
@@ -23,7 +23,7 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.dialect.exception.syntax.database.NoDatabaseSelectedException;
import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
-import org.apache.shardingsphere.infra.state.StateContext;
+import org.apache.shardingsphere.infra.state.instance.InstanceStateContext;
import org.apache.shardingsphere.mode.manager.ContextManager;
import org.apache.shardingsphere.proxy.backend.connector.jdbc.datasource.JDBCBackendDataSource;
@@ -95,11 +95,11 @@ public final class ProxyContext {
}
/**
- * Get state context.
+ * Get instance state context.
*
- * @return state context
+ * @return instance state context
*/
- public Optional<StateContext> getStateContext() {
+ public Optional<InstanceStateContext> getInstanceStateContext() {
return null == contextManager.getInstanceContext() ? Optional.empty() : Optional.ofNullable(contextManager.getInstanceContext().getInstance().getState());
}
}
diff --git a/proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/exception/ReadOnlyException.java b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/exception/ReadOnlyException.java
similarity index 82%
copy from proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/exception/ReadOnlyException.java
copy to proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/exception/ReadOnlyException.java
index 1e0e394fe7a..cc3640450ff 100644
--- a/proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/exception/ReadOnlyException.java
+++ b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/exception/ReadOnlyException.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.proxy.frontend.exception;
+package org.apache.shardingsphere.proxy.backend.exception;
import org.apache.shardingsphere.infra.exception.ConnectionSQLException;
import org.apache.shardingsphere.infra.util.exception.external.sql.sqlstate.XOpenSQLState;
@@ -25,9 +25,9 @@ import org.apache.shardingsphere.infra.util.exception.external.sql.sqlstate.XOpe
*/
public final class ReadOnlyException extends ConnectionSQLException {
- private static final long serialVersionUID = 6339672680026286798L;
+ private static final long serialVersionUID = 3834132923835083492L;
public ReadOnlyException() {
- super(XOpenSQLState.GENERAL_WARNING, 11, "The current instance is read-only, Not allowed write traffic.");
+ super(XOpenSQLState.GENERAL_WARNING, 11, "The cluster status is read-only.");
}
}
diff --git a/proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/exception/ReadOnlyException.java b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/exception/UnavailableException.java
similarity index 72%
rename from proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/exception/ReadOnlyException.java
rename to proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/exception/UnavailableException.java
index 1e0e394fe7a..e703b51507f 100644
--- a/proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/exception/ReadOnlyException.java
+++ b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/exception/UnavailableException.java
@@ -15,19 +15,19 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.proxy.frontend.exception;
+package org.apache.shardingsphere.proxy.backend.exception;
import org.apache.shardingsphere.infra.exception.ConnectionSQLException;
import org.apache.shardingsphere.infra.util.exception.external.sql.sqlstate.XOpenSQLState;
/**
- * Read only exception.
+ * Unavailable exception.
*/
-public final class ReadOnlyException extends ConnectionSQLException {
+public final class UnavailableException extends ConnectionSQLException {
- private static final long serialVersionUID = 6339672680026286798L;
+ private static final long serialVersionUID = 6036684043129887739L;
- public ReadOnlyException() {
- super(XOpenSQLState.GENERAL_WARNING, 11, "The current instance is read-only, Not allowed write traffic.");
+ public UnavailableException() {
+ super(XOpenSQLState.GENERAL_WARNING, 12, "The cluster status is unavailable.");
}
}
diff --git a/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/handler/ProxyBackendHandlerFactory.java b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/handler/ProxyBackendHandlerFactory.java
index a9ac02ce2d0..acdc577aedb 100644
--- a/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/handler/ProxyBackendHandlerFactory.java
+++ b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/handler/ProxyBackendHandlerFactory.java
@@ -33,11 +33,14 @@ import org.apache.shardingsphere.infra.database.type.DatabaseType;
import org.apache.shardingsphere.infra.executor.audit.SQLAuditEngine;
import org.apache.shardingsphere.infra.hint.HintValueContext;
import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
import org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;
import org.apache.shardingsphere.infra.util.exception.external.sql.type.generic.UnsupportedSQLOperationException;
import org.apache.shardingsphere.infra.util.spi.ShardingSphereServiceLoader;
+import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;
import org.apache.shardingsphere.parser.rule.SQLParserRule;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
+import org.apache.shardingsphere.proxy.backend.distsql.DistSQLStatementContext;
import org.apache.shardingsphere.proxy.backend.handler.admin.DatabaseAdminBackendHandlerFactory;
import org.apache.shardingsphere.proxy.backend.handler.data.DatabaseBackendHandlerFactory;
import org.apache.shardingsphere.proxy.backend.handler.database.DatabaseOperateBackendHandlerFactory;
@@ -46,6 +49,7 @@ import org.apache.shardingsphere.proxy.backend.handler.extra.ExtraProxyBackendHa
import org.apache.shardingsphere.proxy.backend.handler.skip.SkipBackendHandler;
import org.apache.shardingsphere.proxy.backend.handler.transaction.TransactionBackendHandlerFactory;
import org.apache.shardingsphere.proxy.backend.session.ConnectionSession;
+import org.apache.shardingsphere.proxy.backend.state.spi.ProxyClusterState;
import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;
import org.apache.shardingsphere.sql.parser.sql.common.statement.dal.EmptyStatement;
import org.apache.shardingsphere.sql.parser.sql.common.statement.dal.FlushStatement;
@@ -101,12 +105,8 @@ public final class ProxyBackendHandlerFactory {
if (sqlStatement instanceof EmptyStatement) {
return new SkipBackendHandler(sqlStatement);
}
- if (sqlStatement instanceof DistSQLStatement) {
- checkUnsupportedDistSQLStatementInTransaction(sqlStatement, connectionSession);
- return DistSQLBackendHandlerFactory.newInstance((DistSQLStatement) sqlStatement, connectionSession);
- }
- SQLStatementContext<?> sqlStatementContext = SQLStatementContextFactory.newInstance(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData(),
- sqlStatement, connectionSession.getDefaultDatabaseName());
+ SQLStatementContext<?> sqlStatementContext = sqlStatement instanceof DistSQLStatement ? new DistSQLStatementContext((DistSQLStatement) sqlStatement)
+ : SQLStatementContextFactory.newInstance(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData(), sqlStatement, connectionSession.getDefaultDatabaseName());
QueryContext queryContext = new QueryContext(sqlStatementContext, sql, Collections.emptyList(), hintValueContext);
connectionSession.setQueryContext(queryContext);
return newInstance(databaseType, queryContext, connectionSession, false);
@@ -129,6 +129,7 @@ public final class ProxyBackendHandlerFactory {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
databaseType.handleRollbackOnly(connectionSession.getTransactionStatus().isRollbackOnly(), sqlStatement);
checkUnsupportedSQLStatement(sqlStatement);
+ checkClusterState(sqlStatement);
if (sqlStatement instanceof EmptyStatement) {
return new SkipBackendHandler(sqlStatement);
}
@@ -208,4 +209,11 @@ public final class ProxyBackendHandlerFactory {
throw new UnsupportedSQLOperationException("Unsupported operation");
}
}
+
+ private static void checkClusterState(final SQLStatement sqlStatement) {
+ ClusterState clusterCurrentState = ProxyContext.getInstance().getContextManager().getClusterStateContext().getCurrentState();
+ if (ClusterState.OK != clusterCurrentState) {
+ TypedSPILoader.getService(ProxyClusterState.class, clusterCurrentState.name()).check(sqlStatement);
+ }
+ }
}
diff --git a/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/LockClusterUpdater.java b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/LockClusterUpdater.java
new file mode 100644
index 00000000000..47060b5bc26
--- /dev/null
+++ b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/LockClusterUpdater.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.shardingsphere.proxy.backend.handler.distsql.ral.updatable;
+
+import lombok.RequiredArgsConstructor;
+import lombok.Setter;
+import org.apache.shardingsphere.distsql.handler.exception.algorithm.InvalidAlgorithmConfigurationException;
+import org.apache.shardingsphere.distsql.handler.exception.algorithm.MissingRequiredAlgorithmException;
+import org.apache.shardingsphere.distsql.handler.ral.update.RALUpdater;
+import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.LockClusterStatement;
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
+import org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;
+import org.apache.shardingsphere.infra.util.exception.external.sql.type.generic.UnsupportedSQLOperationException;
+import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;
+import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
+import org.apache.shardingsphere.proxy.backend.lock.spi.ClusterLockStrategy;
+
+/**
+ * Lock cluster updater.
+ */
+@RequiredArgsConstructor
+@Setter
+public final class LockClusterUpdater implements RALUpdater<LockClusterStatement> {
+
+ @Override
+ public void executeUpdate(final String databaseName, final LockClusterStatement sqlStatement) {
+ checkMode();
+ checkState();
+ checkAlgorithm(sqlStatement);
+ TypedSPILoader.getService(ClusterLockStrategy.class, sqlStatement.getLockStrategy().getName()).lock();
+ }
+
+ private void checkMode() {
+ ShardingSpherePreconditions.checkState(ProxyContext.getInstance().getContextManager().getInstanceContext().isCluster(),
+ () -> new UnsupportedSQLOperationException("Only allowed in cluster mode"));
+ }
+
+ private void checkState() {
+ ClusterState currentState = ProxyContext.getInstance().getContextManager().getClusterStateContext().getCurrentState();
+ ShardingSpherePreconditions.checkState(ClusterState.OK == currentState, () -> new IllegalStateException("Cluster is already locked"));
+ }
+
+ private void checkAlgorithm(final LockClusterStatement sqlStatement) {
+ ShardingSpherePreconditions.checkState(isStrategyDefinitionExists(sqlStatement), MissingRequiredAlgorithmException::new);
+ ShardingSpherePreconditions.checkState(TypedSPILoader.contains(ClusterLockStrategy.class, sqlStatement.getLockStrategy().getName()),
+ () -> new InvalidAlgorithmConfigurationException("cluster lock"));
+ }
+
+ private boolean isStrategyDefinitionExists(final LockClusterStatement sqlStatement) {
+ return null != sqlStatement.getLockStrategy();
+ }
+
+ @Override
+ public String getType() {
+ return LockClusterStatement.class.getName();
+ }
+}
diff --git a/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/SetInstanceStatusUpdater.java b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/SetInstanceStatusUpdater.java
index 06e4ad211e5..c00bd732594 100644
--- a/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/SetInstanceStatusUpdater.java
+++ b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/SetInstanceStatusUpdater.java
@@ -19,7 +19,7 @@ package org.apache.shardingsphere.proxy.backend.handler.distsql.ral.updatable;
import org.apache.shardingsphere.distsql.handler.ral.update.RALUpdater;
import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.SetInstanceStatusStatement;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.state.instance.InstanceState;
import org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;
import org.apache.shardingsphere.infra.util.exception.external.sql.type.generic.UnsupportedSQLOperationException;
import org.apache.shardingsphere.mode.manager.ContextManager;
@@ -42,7 +42,7 @@ public final class SetInstanceStatusUpdater implements RALUpdater<SetInstanceSta
} else {
checkEnablingIsValid(contextManager, instanceId);
}
- contextManager.getInstanceContext().getEventBusContext().post(new ComputeNodeStatusChangedEvent(instanceId, isDisable ? StateType.CIRCUIT_BREAK : StateType.OK));
+ contextManager.getInstanceContext().getEventBusContext().post(new ComputeNodeStatusChangedEvent(instanceId, isDisable ? InstanceState.CIRCUIT_BREAK : InstanceState.OK));
}
private void checkEnablingIsValid(final ContextManager contextManager, final String instanceId) {
@@ -55,7 +55,7 @@ public final class SetInstanceStatusUpdater implements RALUpdater<SetInstanceSta
() -> new UnsupportedSQLOperationException(String.format("`%s` is the currently in use instance and cannot be disabled", instanceId)));
ShardingSpherePreconditions.checkState(contextManager.getInstanceContext().getComputeNodeInstanceById(instanceId).isPresent(),
() -> new UnsupportedSQLOperationException(String.format("`%s` does not exist", instanceId)));
- ShardingSpherePreconditions.checkState(StateType.CIRCUIT_BREAK != contextManager.getInstanceContext().getComputeNodeInstanceById(instanceId).get().getState().getCurrentState(),
+ ShardingSpherePreconditions.checkState(InstanceState.CIRCUIT_BREAK != contextManager.getInstanceContext().getComputeNodeInstanceById(instanceId).get().getState().getCurrentState(),
() -> new UnsupportedSQLOperationException(String.format("`%s` compute node has been disabled", instanceId)));
}
diff --git a/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/lock/impl/ClusterReadWriteLockStrategy.java b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/lock/impl/ClusterReadWriteLockStrategy.java
new file mode 100644
index 00000000000..92cd1f4d962
--- /dev/null
+++ b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/lock/impl/ClusterReadWriteLockStrategy.java
@@ -0,0 +1,47 @@
+/*
+ * 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.shardingsphere.proxy.backend.lock.impl;
+
+import org.apache.shardingsphere.infra.lock.LockContext;
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
+import org.apache.shardingsphere.mode.lock.GlobalLockDefinition;
+import org.apache.shardingsphere.mode.manager.ContextManager;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event.ClusterStatusChangedEvent;
+import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
+import org.apache.shardingsphere.proxy.backend.lock.spi.ClusterLockStrategy;
+
+/**
+ * Cluster read-write lock strategy.
+ */
+public class ClusterReadWriteLockStrategy implements ClusterLockStrategy {
+
+ @Override
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ public void lock() {
+ ContextManager contextManager = ProxyContext.getInstance().getContextManager();
+ LockContext lockContext = contextManager.getInstanceContext().getLockContext();
+ if (lockContext.tryLock(new GlobalLockDefinition("cluster_lock"), -1)) {
+ contextManager.getInstanceContext().getEventBusContext().post(new ClusterStatusChangedEvent(ClusterState.UNAVAILABLE));
+ }
+ }
+
+ @Override
+ public String getType() {
+ return "READ_WRITE";
+ }
+}
diff --git a/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/lock/impl/ClusterWriteLockStrategy.java b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/lock/impl/ClusterWriteLockStrategy.java
new file mode 100644
index 00000000000..94a2d1b5f8f
--- /dev/null
+++ b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/lock/impl/ClusterWriteLockStrategy.java
@@ -0,0 +1,48 @@
+/*
+ * 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.shardingsphere.proxy.backend.lock.impl;
+
+import org.apache.shardingsphere.infra.lock.LockContext;
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
+import org.apache.shardingsphere.mode.lock.GlobalLockDefinition;
+import org.apache.shardingsphere.mode.manager.ContextManager;
+import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.cluster.event.ClusterStatusChangedEvent;
+import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
+import org.apache.shardingsphere.proxy.backend.lock.spi.ClusterLockStrategy;
+
+/**
+ * Cluster write lock strategy.
+ */
+public class ClusterWriteLockStrategy implements ClusterLockStrategy {
+
+ @Override
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ public void lock() {
+ ContextManager contextManager = ProxyContext.getInstance().getContextManager();
+ LockContext lockContext = contextManager.getInstanceContext().getLockContext();
+ if (lockContext.tryLock(new GlobalLockDefinition("cluster_lock"), -1)) {
+ contextManager.getInstanceContext().getEventBusContext().post(new ClusterStatusChangedEvent(ClusterState.READ_ONLY));
+ // TODO lock csn
+ }
+ }
+
+ @Override
+ public String getType() {
+ return "WRITE";
+ }
+}
diff --git a/infra/common/src/main/java/org/apache/shardingsphere/infra/state/StateType.java b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/lock/spi/ClusterLockStrategy.java
similarity index 75%
rename from infra/common/src/main/java/org/apache/shardingsphere/infra/state/StateType.java
rename to proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/lock/spi/ClusterLockStrategy.java
index e68c1d7e329..9fef9f0fd52 100644
--- a/infra/common/src/main/java/org/apache/shardingsphere/infra/state/StateType.java
+++ b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/lock/spi/ClusterLockStrategy.java
@@ -15,12 +15,17 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.infra.state;
+package org.apache.shardingsphere.proxy.backend.lock.spi;
+
+import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPI;
/**
- * State type.
+ * Cluster lock strategy.
*/
-public enum StateType {
+public interface ClusterLockStrategy extends TypedSPI {
- OK, CIRCUIT_BREAK, LOCK
+ /**
+ * Lock cluster.
+ */
+ void lock();
}
diff --git a/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/state/impl/ReadOnlyProxyState.java b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/state/impl/ReadOnlyProxyState.java
new file mode 100644
index 00000000000..d0e7d6f0bb4
--- /dev/null
+++ b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/state/impl/ReadOnlyProxyState.java
@@ -0,0 +1,51 @@
+/*
+ * 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.shardingsphere.proxy.backend.state.impl;
+
+import org.apache.shardingsphere.distsql.parser.statement.ral.UpdatableRALStatement;
+import org.apache.shardingsphere.distsql.parser.statement.rdl.RDLStatement;
+import org.apache.shardingsphere.proxy.backend.exception.ReadOnlyException;
+import org.apache.shardingsphere.proxy.backend.state.spi.ProxyClusterState;
+import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;
+import org.apache.shardingsphere.sql.parser.sql.common.statement.ddl.DDLStatement;
+import org.apache.shardingsphere.sql.parser.sql.common.statement.dml.DeleteStatement;
+import org.apache.shardingsphere.sql.parser.sql.common.statement.dml.InsertStatement;
+import org.apache.shardingsphere.sql.parser.sql.common.statement.dml.UpdateStatement;
+
+/**
+ * ReadOnly proxy state.
+ */
+public final class ReadOnlyProxyState implements ProxyClusterState {
+
+ @Override
+ public void check(final SQLStatement sqlStatement) {
+ if (isUnsupportedStatement(sqlStatement)) {
+ throw new ReadOnlyException();
+ }
+ }
+
+ private boolean isUnsupportedStatement(final SQLStatement sqlStatement) {
+ return sqlStatement instanceof InsertStatement || sqlStatement instanceof UpdateStatement || sqlStatement instanceof DeleteStatement || sqlStatement instanceof DDLStatement
+ || sqlStatement instanceof UpdatableRALStatement || sqlStatement instanceof RDLStatement;
+ }
+
+ @Override
+ public String getType() {
+ return "READ_ONLY";
+ }
+}
diff --git a/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/state/impl/UnavailableProxyState.java b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/state/impl/UnavailableProxyState.java
new file mode 100644
index 00000000000..9ec5f46ddd2
--- /dev/null
+++ b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/state/impl/UnavailableProxyState.java
@@ -0,0 +1,52 @@
+/*
+ * 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.shardingsphere.proxy.backend.state.impl;
+
+import org.apache.shardingsphere.distsql.parser.statement.ral.QueryableRALStatement;
+import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.ImportMetaDataStatement;
+import org.apache.shardingsphere.distsql.parser.statement.rql.RQLStatement;
+import org.apache.shardingsphere.proxy.backend.exception.UnavailableException;
+import org.apache.shardingsphere.proxy.backend.state.spi.ProxyClusterState;
+import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;
+import org.apache.shardingsphere.sql.parser.sql.common.statement.dal.ShowStatement;
+import org.apache.shardingsphere.sql.parser.sql.dialect.statement.mysql.dal.MySQLShowDatabasesStatement;
+import org.apache.shardingsphere.sql.parser.sql.dialect.statement.mysql.dal.MySQLUseStatement;
+
+/**
+ * Unavailable proxy state.
+ */
+public final class UnavailableProxyState implements ProxyClusterState {
+
+ @Override
+ public void check(final SQLStatement sqlStatement) {
+ if (isSupportedStatement(sqlStatement)) {
+ return;
+ }
+ throw new UnavailableException();
+ }
+
+ private boolean isSupportedStatement(final SQLStatement sqlStatement) {
+ return sqlStatement instanceof ImportMetaDataStatement || sqlStatement instanceof ShowStatement || sqlStatement instanceof QueryableRALStatement || sqlStatement instanceof RQLStatement
+ || sqlStatement instanceof MySQLShowDatabasesStatement || sqlStatement instanceof MySQLUseStatement;
+ }
+
+ @Override
+ public String getType() {
+ return "UNAVAILABLE";
+ }
+}
diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/state/spi/ProxyClusterState.java
similarity index 66%
copy from mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
copy to proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/state/spi/ProxyClusterState.java
index d7f1df5bb67..175c9bb71de 100644
--- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
+++ b/proxy/backend/core/src/main/java/org/apache/shardingsphere/proxy/backend/state/spi/ProxyClusterState.java
@@ -15,20 +15,20 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.mode.metadata.compute.event;
+package org.apache.shardingsphere.proxy.backend.state.spi;
-import lombok.Getter;
-import lombok.RequiredArgsConstructor;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPI;
+import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;
/**
- * Compute node status changed event.
+ * Proxy cluster state.
*/
-@RequiredArgsConstructor
-@Getter
-public final class ComputeNodeStatusChangedEvent {
+public interface ProxyClusterState extends TypedSPI {
- private final String instanceId;
-
- private final StateType state;
+ /**
+ * Check sql statement.
+ *
+ * @param sqlStatement sql statement
+ */
+ void check(SQLStatement sqlStatement);
}
diff --git a/proxy/backend/core/src/main/resources/META-INF/services/org.apache.shardingsphere.distsql.handler.ral.update.RALUpdater b/proxy/backend/core/src/main/resources/META-INF/services/org.apache.shardingsphere.distsql.handler.ral.update.RALUpdater
index c1f5c018ee1..44eecacfe90 100644
--- a/proxy/backend/core/src/main/resources/META-INF/services/org.apache.shardingsphere.distsql.handler.ral.update.RALUpdater
+++ b/proxy/backend/core/src/main/resources/META-INF/services/org.apache.shardingsphere.distsql.handler.ral.update.RALUpdater
@@ -24,4 +24,5 @@ org.apache.shardingsphere.proxy.backend.handler.distsql.ral.updatable.ImportMeta
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.updatable.AlterReadwriteSplittingStorageUnitStatusStatementUpdater
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.updatable.SetDistVariableUpdater
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.updatable.RefreshDatabaseMetaDataUpdater
+org.apache.shardingsphere.proxy.backend.handler.distsql.ral.updatable.LockClusterUpdater
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.updatable.RefreshTableMetaDataUpdater
diff --git a/mode/type/cluster/core/src/main/resources/META-INF/services/org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcher b/proxy/backend/core/src/main/resources/META-INF/services/org.apache.shardingsphere.proxy.backend.lock.spi.ClusterLockStrategy
similarity index 53%
copy from mode/type/cluster/core/src/main/resources/META-INF/services/org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcher
copy to proxy/backend/core/src/main/resources/META-INF/services/org.apache.shardingsphere.proxy.backend.lock.spi.ClusterLockStrategy
index 10a83bdd843..1fafee094fc 100644
--- a/mode/type/cluster/core/src/main/resources/META-INF/services/org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcher
+++ b/proxy/backend/core/src/main/resources/META-INF/services/org.apache.shardingsphere.proxy.backend.lock.spi.ClusterLockStrategy
@@ -15,9 +15,5 @@
# limitations under the License.
#
-org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.storage.watcher.StorageNodeStateChangedWatcher
-org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.metadata.watcher.MetaDataChangedWatcher
-org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.GlobalRuleChangedWatcher
-org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.PropertiesChangedWatcher
-org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.watcher.ComputeNodeStateChangedWatcher
-org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.data.ShardingSphereDataChangedWatcher
+org.apache.shardingsphere.proxy.backend.lock.impl.ClusterWriteLockStrategy
+org.apache.shardingsphere.proxy.backend.lock.impl.ClusterReadWriteLockStrategy
diff --git a/mode/type/cluster/core/src/main/resources/META-INF/services/org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcher b/proxy/backend/core/src/main/resources/META-INF/services/org.apache.shardingsphere.proxy.backend.state.spi.ProxyClusterState
similarity index 53%
copy from mode/type/cluster/core/src/main/resources/META-INF/services/org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcher
copy to proxy/backend/core/src/main/resources/META-INF/services/org.apache.shardingsphere.proxy.backend.state.spi.ProxyClusterState
index 10a83bdd843..ca2c25bcffb 100644
--- a/mode/type/cluster/core/src/main/resources/META-INF/services/org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.GovernanceWatcher
+++ b/proxy/backend/core/src/main/resources/META-INF/services/org.apache.shardingsphere.proxy.backend.state.spi.ProxyClusterState
@@ -15,9 +15,5 @@
# limitations under the License.
#
-org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.storage.watcher.StorageNodeStateChangedWatcher
-org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.metadata.watcher.MetaDataChangedWatcher
-org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.GlobalRuleChangedWatcher
-org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.config.watcher.PropertiesChangedWatcher
-org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.watcher.ComputeNodeStateChangedWatcher
-org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.data.ShardingSphereDataChangedWatcher
+org.apache.shardingsphere.proxy.backend.state.impl.ReadOnlyProxyState
+org.apache.shardingsphere.proxy.backend.state.impl.UnavailableProxyState
diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/context/ProxyContextTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/context/ProxyContextTest.java
index f7d90f16d29..e16679370d5 100644
--- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/context/ProxyContextTest.java
+++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/context/ProxyContextTest.java
@@ -68,8 +68,8 @@ public final class ProxyContextTest {
MetaDataContexts metaDataContexts = new MetaDataContexts(mock(MetaDataPersistService.class), new ShardingSphereMetaData());
ProxyContext.init(new ContextManager(metaDataContexts, mock(InstanceContext.class, RETURNS_DEEP_STUBS)));
assertThat(ProxyContext.getInstance().getContextManager().getMetaDataContexts(), is(ProxyContext.getInstance().getContextManager().getMetaDataContexts()));
- assertTrue(ProxyContext.getInstance().getStateContext().isPresent());
- assertThat(ProxyContext.getInstance().getStateContext(), is(ProxyContext.getInstance().getStateContext()));
+ assertTrue(ProxyContext.getInstance().getInstanceStateContext().isPresent());
+ assertThat(ProxyContext.getInstance().getInstanceStateContext(), is(ProxyContext.getInstance().getInstanceStateContext()));
}
@Test
diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/ProxyBackendHandlerFactoryTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/ProxyBackendHandlerFactoryTest.java
index 202bc02c513..18cb5619c78 100644
--- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/ProxyBackendHandlerFactoryTest.java
+++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/ProxyBackendHandlerFactoryTest.java
@@ -24,6 +24,7 @@ import org.apache.shardingsphere.infra.database.DefaultDatabase;
import org.apache.shardingsphere.infra.database.type.DatabaseType;
import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
import org.apache.shardingsphere.infra.metadata.database.rule.ShardingSphereRuleMetaData;
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
import org.apache.shardingsphere.infra.util.exception.external.sql.type.generic.UnsupportedSQLOperationException;
import org.apache.shardingsphere.infra.util.spi.type.typed.TypedSPILoader;
import org.apache.shardingsphere.mode.manager.ContextManager;
@@ -89,6 +90,7 @@ public final class ProxyBackendHandlerFactoryTest {
when(backendConnection.getConnectionSession()).thenReturn(connectionSession);
when(connectionSession.getBackendConnection()).thenReturn(backendConnection);
ContextManager contextManager = mockContextManager();
+ when(contextManager.getClusterStateContext().getCurrentState()).thenReturn(ClusterState.OK);
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
}
diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ShowComputeNodeInfoExecutorTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ShowComputeNodeInfoExecutorTest.java
index c0813c2cb58..e0eec1b4f05 100644
--- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ShowComputeNodeInfoExecutorTest.java
+++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ShowComputeNodeInfoExecutorTest.java
@@ -22,7 +22,7 @@ import org.apache.shardingsphere.infra.config.mode.ModeConfiguration;
import org.apache.shardingsphere.infra.instance.InstanceContext;
import org.apache.shardingsphere.infra.instance.metadata.proxy.ProxyInstanceMetaData;
import org.apache.shardingsphere.infra.merge.result.impl.local.LocalDataQueryResultRow;
-import org.apache.shardingsphere.infra.state.StateContext;
+import org.apache.shardingsphere.infra.state.instance.InstanceStateContext;
import org.apache.shardingsphere.mode.repository.standalone.StandalonePersistRepositoryConfiguration;
import org.junit.Test;
@@ -74,7 +74,7 @@ public final class ShowComputeNodeInfoExecutorTest {
private InstanceContext createInstanceContext() {
InstanceContext result = mock(InstanceContext.class, RETURNS_DEEP_STUBS);
when(result.getInstance().getMetaData()).thenReturn(new ProxyInstanceMetaData("127.0.0.1@3309", "127.0.0.1@3309", "foo_version"));
- when(result.getInstance().getState()).thenReturn(new StateContext());
+ when(result.getInstance().getState()).thenReturn(new InstanceStateContext());
when(result.getModeConfiguration()).thenReturn(new ModeConfiguration("Standalone", new StandalonePersistRepositoryConfiguration("H2", new Properties())));
when(result.getInstance().getWorkerId()).thenReturn(0);
return result;
diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ShowComputeNodesExecutorTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ShowComputeNodesExecutorTest.java
index a112ed23492..10d33a09af1 100644
--- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ShowComputeNodesExecutorTest.java
+++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ShowComputeNodesExecutorTest.java
@@ -24,7 +24,7 @@ import org.apache.shardingsphere.infra.instance.ComputeNodeInstance;
import org.apache.shardingsphere.infra.instance.InstanceContext;
import org.apache.shardingsphere.infra.instance.metadata.proxy.ProxyInstanceMetaData;
import org.apache.shardingsphere.infra.merge.result.impl.local.LocalDataQueryResultRow;
-import org.apache.shardingsphere.infra.state.StateContext;
+import org.apache.shardingsphere.infra.state.instance.InstanceStateContext;
import org.apache.shardingsphere.mode.repository.standalone.StandalonePersistRepositoryConfiguration;
import org.junit.Test;
@@ -92,7 +92,7 @@ public final class ShowComputeNodesExecutorTest {
private InstanceContext createStandaloneInstanceContext() {
InstanceContext result = mock(InstanceContext.class, RETURNS_DEEP_STUBS);
when(result.getInstance().getMetaData()).thenReturn(new ProxyInstanceMetaData("127.0.0.1@3308", "127.0.0.1@3308", "foo_version"));
- when(result.getInstance().getState()).thenReturn(new StateContext());
+ when(result.getInstance().getState()).thenReturn(new InstanceStateContext());
when(result.getModeConfiguration()).thenReturn(new ModeConfiguration("Standalone", new StandalonePersistRepositoryConfiguration("H2", new Properties())));
when(result.getInstance().getWorkerId()).thenReturn(0);
return result;
@@ -103,7 +103,7 @@ public final class ShowComputeNodesExecutorTest {
when(result.getModeConfiguration()).thenReturn(new ModeConfiguration("Cluster", mock(PersistRepositoryConfiguration.class)));
ComputeNodeInstance computeNodeInstance = mock(ComputeNodeInstance.class, RETURNS_DEEP_STUBS);
when(computeNodeInstance.getMetaData()).thenReturn(new ProxyInstanceMetaData("127.0.0.1@3309", "127.0.0.1@3309", "foo_version"));
- when(computeNodeInstance.getState()).thenReturn(new StateContext());
+ when(computeNodeInstance.getState()).thenReturn(new InstanceStateContext());
when(computeNodeInstance.getWorkerId()).thenReturn(1);
when(result.getAllClusterInstances()).thenReturn(Collections.singleton(computeNodeInstance));
return result;
diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/SetInstanceStatusUpdaterTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/LockClusterUpdaterTest.java
similarity index 55%
copy from proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/SetInstanceStatusUpdaterTest.java
copy to proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/LockClusterUpdaterTest.java
index 62a039535c5..2b58d8d52e4 100644
--- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/SetInstanceStatusUpdaterTest.java
+++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/LockClusterUpdaterTest.java
@@ -17,8 +17,10 @@
package org.apache.shardingsphere.proxy.backend.handler.distsql.ral.updatable;
-import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.SetInstanceStatusStatement;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.distsql.handler.exception.algorithm.InvalidAlgorithmConfigurationException;
+import org.apache.shardingsphere.distsql.parser.segment.AlgorithmSegment;
+import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.LockClusterStatement;
+import org.apache.shardingsphere.infra.state.cluster.ClusterState;
import org.apache.shardingsphere.infra.util.exception.external.sql.type.generic.UnsupportedSQLOperationException;
import org.apache.shardingsphere.mode.manager.ContextManager;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
@@ -27,6 +29,8 @@ import org.apache.shardingsphere.test.mock.StaticMockSettings;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import java.util.Properties;
+
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
@@ -34,44 +38,33 @@ import static org.mockito.Mockito.when;
@ExtendWith(AutoMockExtension.class)
@StaticMockSettings(ProxyContext.class)
-public final class SetInstanceStatusUpdaterTest {
+public final class LockClusterUpdaterTest {
@Test
- public void assertExecuteWithNotNotClusterMode() {
+ public void assertExecuteWithNotClusterMode() {
ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS);
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
- SetInstanceStatusUpdater updater = new SetInstanceStatusUpdater();
- assertThrows(UnsupportedSQLOperationException.class, () -> updater.executeUpdate("foo", new SetInstanceStatusStatement("ENABLE", "instanceID")));
- }
-
- @Test
- public void assertExecuteWithNotExistsInstanceID() {
- ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS);
- when(contextManager.getInstanceContext().isCluster()).thenReturn(true);
- when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
- SetInstanceStatusUpdater updater = new SetInstanceStatusUpdater();
- assertThrows(UnsupportedSQLOperationException.class, () -> updater.executeUpdate("foo", new SetInstanceStatusStatement("ENABLE", "instanceID")));
+ LockClusterUpdater updater = new LockClusterUpdater();
+ assertThrows(UnsupportedSQLOperationException.class, () -> updater.executeUpdate("foo", new LockClusterStatement(new AlgorithmSegment("FOO", new Properties()))));
}
@Test
- public void assertExecuteWithCurrentUsingInstance() {
+ public void assertExecuteWithLockedCluster() {
ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS);
when(contextManager.getInstanceContext().isCluster()).thenReturn(true);
- when(contextManager.getInstanceContext().getInstance().getCurrentInstanceId()).thenReturn("instanceID");
+ when(contextManager.getClusterStateContext().getCurrentState()).thenReturn(ClusterState.UNAVAILABLE);
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
- SetInstanceStatusUpdater updater = new SetInstanceStatusUpdater();
- assertThrows(UnsupportedSQLOperationException.class, () -> updater.executeUpdate("foo", new SetInstanceStatusStatement("DISABLE", "instanceID")));
+ LockClusterUpdater updater = new LockClusterUpdater();
+ assertThrows(IllegalStateException.class, () -> updater.executeUpdate("foo", new LockClusterStatement(new AlgorithmSegment("FOO", new Properties()))));
}
@Test
- public void assertExecuteWithAlreadyDisableInstance() {
+ public void assertExecuteWithWrongAlgorithm() {
ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS);
when(contextManager.getInstanceContext().isCluster()).thenReturn(true);
- when(contextManager.getInstanceContext().getInstance().getCurrentInstanceId()).thenReturn("currentInstance");
- when(contextManager.getInstanceContext().getComputeNodeInstanceById("instanceID").isPresent()).thenReturn(true);
- when(contextManager.getInstanceContext().getComputeNodeInstanceById("instanceID").get().getState().getCurrentState()).thenReturn(StateType.CIRCUIT_BREAK);
+ when(contextManager.getClusterStateContext().getCurrentState()).thenReturn(ClusterState.OK);
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
- SetInstanceStatusUpdater updater = new SetInstanceStatusUpdater();
- assertThrows(UnsupportedSQLOperationException.class, () -> updater.executeUpdate("foo", new SetInstanceStatusStatement("DISABLE", "instanceID")));
+ LockClusterUpdater updater = new LockClusterUpdater();
+ assertThrows(InvalidAlgorithmConfigurationException.class, () -> updater.executeUpdate("foo", new LockClusterStatement(new AlgorithmSegment("FOO", new Properties()))));
}
}
diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/SetInstanceStatusUpdaterTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/SetInstanceStatusUpdaterTest.java
index 62a039535c5..4cc94910e3b 100644
--- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/SetInstanceStatusUpdaterTest.java
+++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/SetInstanceStatusUpdaterTest.java
@@ -18,7 +18,7 @@
package org.apache.shardingsphere.proxy.backend.handler.distsql.ral.updatable;
import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.SetInstanceStatusStatement;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.state.instance.InstanceState;
import org.apache.shardingsphere.infra.util.exception.external.sql.type.generic.UnsupportedSQLOperationException;
import org.apache.shardingsphere.mode.manager.ContextManager;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
@@ -69,7 +69,7 @@ public final class SetInstanceStatusUpdaterTest {
when(contextManager.getInstanceContext().isCluster()).thenReturn(true);
when(contextManager.getInstanceContext().getInstance().getCurrentInstanceId()).thenReturn("currentInstance");
when(contextManager.getInstanceContext().getComputeNodeInstanceById("instanceID").isPresent()).thenReturn(true);
- when(contextManager.getInstanceContext().getComputeNodeInstanceById("instanceID").get().getState().getCurrentState()).thenReturn(StateType.CIRCUIT_BREAK);
+ when(contextManager.getInstanceContext().getComputeNodeInstanceById("instanceID").get().getState().getCurrentState()).thenReturn(InstanceState.CIRCUIT_BREAK);
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
SetInstanceStatusUpdater updater = new SetInstanceStatusUpdater();
assertThrows(UnsupportedSQLOperationException.class, () -> updater.executeUpdate("foo", new SetInstanceStatusStatement("DISABLE", "instanceID")));
diff --git a/proxy/bootstrap/src/main/java/org/apache/shardingsphere/proxy/Bootstrap.java b/proxy/bootstrap/src/main/java/org/apache/shardingsphere/proxy/Bootstrap.java
index a56626aac6b..53a69f8f5bb 100644
--- a/proxy/bootstrap/src/main/java/org/apache/shardingsphere/proxy/Bootstrap.java
+++ b/proxy/bootstrap/src/main/java/org/apache/shardingsphere/proxy/Bootstrap.java
@@ -41,7 +41,7 @@ public final class Bootstrap {
/**
* Main entrance.
- *
+ *
* @param args startup arguments
* @throws IOException IO exception
* @throws SQLException SQL exception
diff --git a/proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/state/ProxyState.java b/proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/state/ProxyState.java
index 6baf2402107..23c8c850fcd 100644
--- a/proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/state/ProxyState.java
+++ b/proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/state/ProxyState.java
@@ -28,7 +28,8 @@ public interface ProxyState {
/**
* Execute command.
- * @param context channel handler context
+ *
+ * @param context channel handler context
* @param message message
* @param databaseProtocolFrontendEngine database protocol frontend engine
* @param connectionSession connection session
diff --git a/proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/state/ProxyStateContext.java b/proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/state/ProxyStateContext.java
index 776cd423594..2de36e2de5b 100644
--- a/proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/state/ProxyStateContext.java
+++ b/proxy/frontend/core/src/main/java/org/apache/shardingsphere/proxy/frontend/state/ProxyStateContext.java
@@ -20,13 +20,13 @@ package org.apache.shardingsphere.proxy.frontend.state;
import io.netty.channel.ChannelHandlerContext;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
-import org.apache.shardingsphere.infra.state.StateType;
+import org.apache.shardingsphere.infra.state.instance.InstanceState;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
import org.apache.shardingsphere.proxy.backend.session.ConnectionSession;
import org.apache.shardingsphere.proxy.frontend.spi.DatabaseProtocolFrontendEngine;
import org.apache.shardingsphere.proxy.frontend.state.impl.CircuitBreakProxyState;
-import org.apache.shardingsphere.proxy.frontend.state.impl.OKProxyState;
import org.apache.shardingsphere.proxy.frontend.state.impl.LockProxyState;
+import org.apache.shardingsphere.proxy.frontend.state.impl.OKProxyState;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -37,23 +37,24 @@ import java.util.concurrent.ConcurrentHashMap;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ProxyStateContext {
- private static final Map<StateType, ProxyState> STATES = new ConcurrentHashMap<>(3, 1);
+ private static final Map<InstanceState, ProxyState> STATES = new ConcurrentHashMap<>(3, 1);
static {
- STATES.put(StateType.OK, new OKProxyState());
- STATES.put(StateType.LOCK, new LockProxyState());
- STATES.put(StateType.CIRCUIT_BREAK, new CircuitBreakProxyState());
+ STATES.put(InstanceState.OK, new OKProxyState());
+ STATES.put(InstanceState.LOCK, new LockProxyState());
+ STATES.put(InstanceState.CIRCUIT_BREAK, new CircuitBreakProxyState());
}
/**
* Execute command.
- * @param context channel handler context
+ *
+ * @param context channel handler context
* @param message message
* @param databaseProtocolFrontendEngine database protocol frontend engine
* @param connectionSession connection session
*/
public static void execute(final ChannelHandlerContext context, final Object message,
final DatabaseProtocolFrontendEngine databaseProtocolFrontendEngine, final ConnectionSession connectionSession) {
- ProxyContext.getInstance().getStateContext().ifPresent(optional -> STATES.get(optional.getCurrentState()).execute(context, message, databaseProtocolFrontendEngine, connectionSession));
+ ProxyContext.getInstance().getInstanceStateContext().ifPresent(optional -> STATES.get(optional.getCurrentState()).execute(context, message, databaseProtocolFrontendEngine, connectionSession));
}
}
diff --git a/test/it/parser/src/main/java/org/apache/shardingsphere/test/it/sql/parser/internal/asserts/statement/ral/impl/UpdatableRALStatementAssert.java b/test/it/parser/src/main/java/org/apache/shardingsphere/test/it/sql/parser/internal/asserts/statement/ral/impl/UpdatableRALStatementAssert.java
index 9840612f15e..64a0ebd8fac 100644
--- a/test/it/parser/src/main/java/org/apache/shardingsphere/test/it/sql/parser/internal/asserts/statement/ral/impl/UpdatableRALStatementAssert.java
+++ b/test/it/parser/src/main/java/org/apache/shardingsphere/test/it/sql/parser/internal/asserts/statement/ral/impl/UpdatableRALStatementAssert.java
@@ -20,6 +20,7 @@ package org.apache.shardingsphere.test.it.sql.parser.internal.asserts.statement.
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.distsql.parser.statement.ral.UpdatableRALStatement;
+import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.LockClusterStatement;
import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.AlterComputeNodeStatement;
import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.ImportDatabaseConfigurationStatement;
import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.ImportMetaDataStatement;
@@ -38,6 +39,7 @@ import org.apache.shardingsphere.test.it.sql.parser.internal.asserts.statement.r
import org.apache.shardingsphere.test.it.sql.parser.internal.asserts.statement.ral.impl.updatable.ImportDatabaseConfigurationStatementAssert;
import org.apache.shardingsphere.test.it.sql.parser.internal.asserts.statement.ral.impl.updatable.ImportMetaDataStatementAssert;
import org.apache.shardingsphere.test.it.sql.parser.internal.asserts.statement.ral.impl.updatable.LabelComputeNodeStatementAssert;
+import org.apache.shardingsphere.test.it.sql.parser.internal.asserts.statement.ral.impl.updatable.LockClusterStatementAssert;
import org.apache.shardingsphere.test.it.sql.parser.internal.asserts.statement.ral.impl.updatable.RefreshTableMetaDataStatementAssert;
import org.apache.shardingsphere.test.it.sql.parser.internal.asserts.statement.ral.impl.updatable.SetDistVariableStatementAssert;
import org.apache.shardingsphere.test.it.sql.parser.internal.asserts.statement.ral.impl.updatable.UnlabelComputeNodeStatementAssert;
@@ -49,6 +51,7 @@ import org.apache.shardingsphere.test.it.sql.parser.internal.cases.parser.jaxb.s
import org.apache.shardingsphere.test.it.sql.parser.internal.cases.parser.jaxb.statement.ral.ImportDatabaseConfigurationStatementTestCase;
import org.apache.shardingsphere.test.it.sql.parser.internal.cases.parser.jaxb.statement.ral.ImportMetaDataStatementTestCase;
import org.apache.shardingsphere.test.it.sql.parser.internal.cases.parser.jaxb.statement.ral.LabelComputeNodeStatementTestCase;
+import org.apache.shardingsphere.test.it.sql.parser.internal.cases.parser.jaxb.statement.ral.LockClusterStatementTestCase;
import org.apache.shardingsphere.test.it.sql.parser.internal.cases.parser.jaxb.statement.ral.RefreshTableMetaDataStatementTestCase;
import org.apache.shardingsphere.test.it.sql.parser.internal.cases.parser.jaxb.statement.ral.SetDistVariableStatementTestCase;
import org.apache.shardingsphere.test.it.sql.parser.internal.cases.parser.jaxb.statement.ral.UnlabelComputeNodeStatementTestCase;
@@ -92,6 +95,8 @@ public final class UpdatableRALStatementAssert {
} else if (actual instanceof AlterReadwriteSplittingStorageUnitStatusStatement) {
AlterReadwriteSplittingStorageUnitStatusStatementAssert.assertIs(assertContext,
(AlterReadwriteSplittingStorageUnitStatusStatement) actual, (AlterReadwriteSplittingStorageUnitStatusStatementTestCase) expected);
+ } else if (actual instanceof LockClusterStatement) {
+ LockClusterStatementAssert.assertIs(assertContext, (LockClusterStatement) actual, (LockClusterStatementTestCase) expected);
}
}
}
diff --git a/test/it/parser/src/main/java/org/apache/shardingsphere/test/it/sql/parser/internal/asserts/statement/ral/impl/updatable/LockClusterStatementAssert.java b/test/it/parser/src/main/java/org/apache/shardingsphere/test/it/sql/parser/internal/asserts/statement/ral/impl/updatable/LockClusterStatementAssert.java
new file mode 100644
index 00000000000..3dca89ceaed
--- /dev/null
+++ b/test/it/parser/src/main/java/org/apache/shardingsphere/test/it/sql/parser/internal/asserts/statement/ral/impl/updatable/LockClusterStatementAssert.java
@@ -0,0 +1,51 @@
+/*
+ * 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.shardingsphere.test.it.sql.parser.internal.asserts.statement.ral.impl.updatable;
+
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.apache.shardingsphere.distsql.parser.statement.ral.updatable.LockClusterStatement;
+import org.apache.shardingsphere.test.it.sql.parser.internal.asserts.SQLCaseAssertContext;
+import org.apache.shardingsphere.test.it.sql.parser.internal.cases.parser.jaxb.statement.ral.LockClusterStatementTestCase;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertNull;
+
+/**
+ * Lock cluster statement assert.
+ */
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class LockClusterStatementAssert {
+
+ /**
+ * Assert lock cluster statement is correct with expected parser result.
+ *
+ * @param assertContext assert context
+ * @param actual actual lock cluster statement
+ * @param expected expected lock cluster statement test case
+ */
+ public static void assertIs(final SQLCaseAssertContext assertContext, final LockClusterStatement actual,
+ final LockClusterStatementTestCase expected) {
+ if (null == expected) {
+ assertNull(assertContext.getText("Actual statement should not exist."), actual);
+ } else {
+ assertThat(actual.getLockStrategy(), is(expected.getLockStrategy()));
+ }
+ }
+}
diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java b/test/it/parser/src/main/java/org/apache/shardingsphere/test/it/sql/parser/internal/cases/parser/jaxb/statement/ral/LockClusterStatementTestCase.java
similarity index 61%
copy from mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
copy to test/it/parser/src/main/java/org/apache/shardingsphere/test/it/sql/parser/internal/cases/parser/jaxb/statement/ral/LockClusterStatementTestCase.java
index d7f1df5bb67..57c3362a90f 100644
--- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/compute/event/ComputeNodeStatusChangedEvent.java
+++ b/test/it/parser/src/main/java/org/apache/shardingsphere/test/it/sql/parser/internal/cases/parser/jaxb/statement/ral/LockClusterStatementTestCase.java
@@ -15,20 +15,22 @@
* limitations under the License.
*/
-package org.apache.shardingsphere.mode.metadata.compute.event;
+package org.apache.shardingsphere.test.it.sql.parser.internal.cases.parser.jaxb.statement.ral;
import lombok.Getter;
-import lombok.RequiredArgsConstructor;
-import org.apache.shardingsphere.infra.state.StateType;
+import lombok.Setter;
+import org.apache.shardingsphere.distsql.parser.segment.AlgorithmSegment;
+import org.apache.shardingsphere.test.it.sql.parser.internal.cases.parser.jaxb.SQLParserTestCase;
+
+import javax.xml.bind.annotation.XmlElement;
/**
- * Compute node status changed event.
+ * Lock cluster statement test case.
*/
-@RequiredArgsConstructor
@Getter
-public final class ComputeNodeStatusChangedEvent {
-
- private final String instanceId;
+@Setter
+public final class LockClusterStatementTestCase extends SQLParserTestCase {
- private final StateType state;
+ @XmlElement(name = "lock-strategy")
+ private AlgorithmSegment lockStrategy;
}