You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shardingsphere.apache.org by ki...@apache.org on 2020/12/03 10:53:23 UTC

[shardingsphere] branch master updated: Block all tasks when the state is locked (#8495)

This is an automated email from the ASF dual-hosted git repository.

kimmking 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 c9b2a11  Block all tasks when the state is locked (#8495)
c9b2a11 is described below

commit c9b2a115a1a2442281af81a90857fbb3ed59a598
Author: Haoran Meng <me...@gmail.com>
AuthorDate: Thu Dec 3 18:52:55 2020 +0800

    Block all tasks when the state is locked (#8495)
---
 .../mysql/constant/MySQLServerErrorCode.java       |  4 +-
 .../shardingsphere/infra/lock/LockContext.java     | 40 +++++++++++++++++++
 .../infra/lock/StandardLockStrategy.java           | 11 +++++-
 .../shardingsphere/infra/state/StateContext.java   | 15 ++++++--
 .../proxy/frontend/state/impl/LockProxyState.java  | 45 +++++++++++++++++++++-
 .../frontend/mysql/MySQLErrPacketFactory.java      |  4 ++
 6 files changed, 112 insertions(+), 7 deletions(-)

diff --git a/shardingsphere-db-protocol/shardingsphere-db-protocol-mysql/src/main/java/org/apache/shardingsphere/db/protocol/mysql/constant/MySQLServerErrorCode.java b/shardingsphere-db-protocol/shardingsphere-db-protocol-mysql/src/main/java/org/apache/shardingsphere/db/protocol/mysql/constant/MySQLServerErrorCode.java
index 13ff010..e54f707 100644
--- a/shardingsphere-db-protocol/shardingsphere-db-protocol-mysql/src/main/java/org/apache/shardingsphere/db/protocol/mysql/constant/MySQLServerErrorCode.java
+++ b/shardingsphere-db-protocol/shardingsphere-db-protocol-mysql/src/main/java/org/apache/shardingsphere/db/protocol/mysql/constant/MySQLServerErrorCode.java
@@ -56,7 +56,9 @@ public enum MySQLServerErrorCode implements SQLErrorCode {
     
     ER_ERROR_ON_MODIFYING_GTID_EXECUTED_TABLE(3176, "HY000", 
             "Please do not modify the %s table with an XA transaction. This is an internal system table used to store GTIDs for committed transactions. " 
-                    + "Although modifying it can lead to an inconsistent GTID state, if neccessary you can modify it with a non-XA transaction.");
+                    + "Although modifying it can lead to an inconsistent GTID state, if neccessary you can modify it with a non-XA transaction."),
+    
+    ER_LOCKING_SERVICE_TIMEOUT(3133, "HY000", "Message: Service lock wait timeout exceeded");
     
     private final int errorCode;
     
diff --git a/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/lock/LockContext.java b/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/lock/LockContext.java
index cb5a258..b5870a4 100644
--- a/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/lock/LockContext.java
+++ b/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/lock/LockContext.java
@@ -20,7 +20,11 @@ package org.apache.shardingsphere.infra.lock;
 import lombok.AccessLevel;
 import lombok.NoArgsConstructor;
 
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
 
 /**
  * Lock context.
@@ -30,6 +34,12 @@ public final class LockContext {
     
     private static final AtomicReference<LockStrategy> LOCK_STRATEGY = new AtomicReference<>();
     
+    private static final Lock LOCK = new ReentrantLock();
+    
+    private static final Condition CONDITION = LOCK.newCondition();
+    
+    private static final long TIME_OUT_SECONDS = 60L;
+    
     /**
      * Init lock strategy.
      * 
@@ -47,4 +57,34 @@ public final class LockContext {
     public static LockStrategy getLockStrategy() {
         return LOCK_STRATEGY.get();
     }
+    
+    /**
+     * Waiting for unlock.
+     * 
+     * @return false if wait timeout exceeded, else true
+     */
+    public static boolean await() {
+        LOCK.lock();
+        try {
+            return CONDITION.await(TIME_OUT_SECONDS, TimeUnit.SECONDS);
+            // CHECKSTYLE:OFF
+        } catch (InterruptedException e) {
+            // CHECKSTYLE:ON
+        } finally {
+            LOCK.unlock();
+        }
+        return false;
+    }
+    
+    /**
+     * Notify all blocked tasks.
+     */
+    public static void signalAll() {
+        LOCK.lock();
+        try {
+            CONDITION.signalAll();
+        } finally {
+            LOCK.unlock();
+        }
+    }
 }
diff --git a/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/lock/StandardLockStrategy.java b/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/lock/StandardLockStrategy.java
index b889313..a4d4fc8 100644
--- a/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/lock/StandardLockStrategy.java
+++ b/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/lock/StandardLockStrategy.java
@@ -17,6 +17,10 @@
 
 package org.apache.shardingsphere.infra.lock;
 
+import org.apache.shardingsphere.infra.state.StateContext;
+import org.apache.shardingsphere.infra.state.StateEvent;
+import org.apache.shardingsphere.infra.state.StateType;
+
 import java.util.concurrent.locks.ReentrantLock;
 
 /**
@@ -28,11 +32,16 @@ public final class StandardLockStrategy implements LockStrategy {
     
     @Override
     public boolean tryLock() {
-        return lock.tryLock();
+        boolean result = lock.tryLock();
+        if (result) {
+            StateContext.switchState(new StateEvent(StateType.LOCK, true));
+        }
+        return result;
     }
     
     @Override
     public void releaseLock() {
         lock.unlock();
+        StateContext.switchState(new StateEvent(StateType.OK, true));
     }
 }
diff --git a/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/state/StateContext.java b/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/state/StateContext.java
index 4948aef..6d7ecd1 100644
--- a/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/state/StateContext.java
+++ b/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/state/StateContext.java
@@ -19,6 +19,7 @@ package org.apache.shardingsphere.infra.state;
 
 import lombok.AccessLevel;
 import lombok.NoArgsConstructor;
+import org.apache.shardingsphere.infra.lock.LockContext;
 
 import java.util.concurrent.atomic.AtomicReference;
 
@@ -38,13 +39,19 @@ public final class StateContext {
     public static void switchState(final StateEvent event) {
         if (StateType.CIRCUIT_BREAK == event.getType() && event.isOn()) {
             CURRENT_STATE.set(StateType.CIRCUIT_BREAK);
-            return;
-        }
-        if (StateType.LOCK == event.getType()) {
+        } else if (StateType.LOCK == event.getType()) {
             CURRENT_STATE.set(StateType.LOCK);
+        } else {
+            CURRENT_STATE.set(StateType.OK);    
+        }
+        signalAll();
+    }
+    
+    private static void signalAll() {
+        if (getCurrentState() == StateType.LOCK) {
             return;
         }
-        CURRENT_STATE.set(StateType.OK);
+        LockContext.signalAll();
     }
     
     /**
diff --git a/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-core/src/main/java/org/apache/shardingsphere/proxy/frontend/state/impl/LockProxyState.java b/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-core/src/main/java/org/apache/shardingsphere/proxy/frontend/state/impl/LockProxyState.java
index 727a62c..989df9d 100644
--- a/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-core/src/main/java/org/apache/shardingsphere/proxy/frontend/state/impl/LockProxyState.java
+++ b/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-core/src/main/java/org/apache/shardingsphere/proxy/frontend/state/impl/LockProxyState.java
@@ -18,17 +18,60 @@
 package org.apache.shardingsphere.proxy.frontend.state.impl;
 
 import io.netty.channel.ChannelHandlerContext;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.shardingsphere.db.protocol.packet.DatabasePacket;
+import org.apache.shardingsphere.infra.config.properties.ConfigurationPropertyKey;
+import org.apache.shardingsphere.infra.lock.LockContext;
+import org.apache.shardingsphere.infra.state.StateContext;
+import org.apache.shardingsphere.infra.state.StateType;
 import org.apache.shardingsphere.proxy.backend.communication.jdbc.connection.BackendConnection;
+import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
+import org.apache.shardingsphere.proxy.backend.exception.BackendException;
+import org.apache.shardingsphere.proxy.backend.exception.CircuitBreakException;
+import org.apache.shardingsphere.proxy.backend.exception.LockWaitTimeoutException;
+import org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask;
+import org.apache.shardingsphere.proxy.frontend.executor.CommandExecutorSelector;
 import org.apache.shardingsphere.proxy.frontend.spi.DatabaseProtocolFrontendEngine;
 import org.apache.shardingsphere.proxy.frontend.state.ProxyState;
 
+import java.util.Optional;
+import java.util.concurrent.ExecutorService;
+
 /**
  * Lock proxy state.
  */
+@Slf4j
 public final class LockProxyState implements ProxyState {
     
     @Override
     public void execute(final ChannelHandlerContext context, final Object message, final DatabaseProtocolFrontendEngine databaseProtocolFrontendEngine, final BackendConnection backendConnection) {
-        throw new UnsupportedOperationException("LockProxyState");
+        block(context, databaseProtocolFrontendEngine);
+        if (StateContext.getCurrentState() == StateType.OK) {
+            doExecute(context, message, databaseProtocolFrontendEngine, backendConnection);
+        } else if (StateContext.getCurrentState() == StateType.CIRCUIT_BREAK) {
+            doError(context, databaseProtocolFrontendEngine, new CircuitBreakException());
+        }
+    }
+    
+    private void block(final ChannelHandlerContext context, final DatabaseProtocolFrontendEngine databaseProtocolFrontendEngine) {
+        if (!LockContext.await()) {
+            doError(context, databaseProtocolFrontendEngine, new LockWaitTimeoutException());
+            return;
+        }
+    }
+    
+    private void doExecute(final ChannelHandlerContext context, final Object message, final DatabaseProtocolFrontendEngine databaseProtocolFrontendEngine, final BackendConnection backendConnection) {
+        boolean supportHint = ProxyContext.getInstance().getMetaDataContexts().getProps().<Boolean>getValue(ConfigurationPropertyKey.PROXY_HINT_ENABLED);
+        boolean isOccupyThreadForPerConnection = databaseProtocolFrontendEngine.getFrontendContext().isOccupyThreadForPerConnection();
+        ExecutorService executorService = CommandExecutorSelector.getExecutorService(
+                isOccupyThreadForPerConnection, supportHint, backendConnection.getTransactionStatus().getTransactionType(), context.channel().id());
+        Runnable commandExecutorTask = new CommandExecutorTask(databaseProtocolFrontendEngine, backendConnection, context, message);
+        executorService.execute(commandExecutorTask);
+    }
+    
+    private void doError(final ChannelHandlerContext context, final DatabaseProtocolFrontendEngine databaseProtocolFrontendEngine, final BackendException backendException) {
+        context.writeAndFlush(databaseProtocolFrontendEngine.getCommandExecuteEngine().getErrorPacket(backendException));
+        Optional<DatabasePacket<?>> databasePacket = databaseProtocolFrontendEngine.getCommandExecuteEngine().getOtherPacket();
+        databasePacket.ifPresent(context::writeAndFlush);
     }
 }
diff --git a/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-mysql/src/main/java/org/apache/shardingsphere/proxy/frontend/mysql/MySQLErrPacketFactory.java b/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-mysql/src/main/java/org/apache/shardingsphere/proxy/frontend/mysql/MySQLErrPacketFactory.java
index 413919c..4d23f85 100644
--- a/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-mysql/src/main/java/org/apache/shardingsphere/proxy/frontend/mysql/MySQLErrPacketFactory.java
+++ b/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-mysql/src/main/java/org/apache/shardingsphere/proxy/frontend/mysql/MySQLErrPacketFactory.java
@@ -26,6 +26,7 @@ import org.apache.shardingsphere.infra.config.exception.ShardingSphereConfigurat
 import org.apache.shardingsphere.proxy.backend.exception.CircuitBreakException;
 import org.apache.shardingsphere.proxy.backend.exception.DBCreateExistsException;
 import org.apache.shardingsphere.proxy.backend.exception.DBDropExistsException;
+import org.apache.shardingsphere.proxy.backend.exception.LockWaitTimeoutException;
 import org.apache.shardingsphere.proxy.backend.exception.NoDatabaseSelectedException;
 import org.apache.shardingsphere.proxy.backend.exception.RuleNotExistsException;
 import org.apache.shardingsphere.proxy.backend.exception.TableModifyInTransactionException;
@@ -98,6 +99,9 @@ public final class MySQLErrPacketFactory {
         if (cause instanceof RuleNotExistsException) {
             return new MySQLErrPacket(1, MySQLServerErrorCode.ER_SP_DOES_NOT_EXIST);
         }
+        if (cause instanceof LockWaitTimeoutException) {
+            return new MySQLErrPacket(1, MySQLServerErrorCode.ER_LOCKING_SERVICE_TIMEOUT);
+        }
         return new MySQLErrPacket(1, CommonErrorCode.UNKNOWN_EXCEPTION, cause.getMessage());
     }
 }