SbloodyS commented on code in PR #16352:
URL: 
https://github.com/apache/dolphinscheduler/pull/16352#discussion_r1687454776


##########
dolphinscheduler-registry/dolphinscheduler-registry-plugins/dolphinscheduler-registry-raft/src/main/java/org/apache/dolphinscheduler/plugin/registry/raft/RaftConnectionStateManager.java:
##########
@@ -0,0 +1,141 @@
+/*
+ * 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.dolphinscheduler.plugin.registry.raft;
+
+import org.apache.dolphinscheduler.registry.api.ConnectionListener;
+import org.apache.dolphinscheduler.registry.api.ConnectionState;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import lombok.extern.slf4j.Slf4j;
+
+import com.alipay.sofa.jraft.RouteTable;
+import com.alipay.sofa.jraft.option.CliOptions;
+import com.alipay.sofa.jraft.rpc.CliClientService;
+import com.alipay.sofa.jraft.rpc.impl.cli.CliClientServiceImpl;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+
+@Slf4j
+public class RaftConnectionStateManager implements IRaftConnectionStateManager 
{
+
+    private static final String DEFAULT_REGION_ID = "--1";
+    private ConnectionState currentConnectionState;
+    private static final Duration CONNECT_STATE_CHECK_INTERVENE = 
Duration.ofSeconds(2);
+    private final RaftRegistryProperties properties;
+    private final List<ConnectionListener> connectionListeners = new 
CopyOnWriteArrayList<>();
+    private final ScheduledExecutorService scheduledExecutorService;
+    private final CliOptions cliOptions;
+    private final CliClientService cliClientService;
+
+    public RaftConnectionStateManager(RaftRegistryProperties properties) {
+        this.properties = properties;
+        this.cliOptions = new CliOptions();
+        this.cliOptions.setMaxRetry(3);
+        this.cliOptions.setTimeoutMs(5000);

Review Comment:
   Too many magic numbers. We should avoid this.



##########
dolphinscheduler-registry/dolphinscheduler-registry-plugins/dolphinscheduler-registry-raft/src/main/java/org/apache/dolphinscheduler/plugin/registry/raft/RaftRegistry.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.dolphinscheduler.plugin.registry.raft;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import org.apache.dolphinscheduler.common.thread.ThreadUtils;
+import 
org.apache.dolphinscheduler.plugin.registry.raft.client.IRaftRegisterClient;
+import 
org.apache.dolphinscheduler.plugin.registry.raft.client.RaftRegisterClient;
+import org.apache.dolphinscheduler.registry.api.ConnectionListener;
+import org.apache.dolphinscheduler.registry.api.Registry;
+import org.apache.dolphinscheduler.registry.api.RegistryException;
+import org.apache.dolphinscheduler.registry.api.SubscribeListener;
+
+import java.time.Duration;
+import java.util.Collection;
+
+import lombok.NonNull;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+public class RaftRegistry implements Registry {
+
+    private static final long RECONNECT_WAIT_TIME_MS = 50L;

Review Comment:
   Magic number.



##########
dolphinscheduler-registry/dolphinscheduler-registry-plugins/dolphinscheduler-registry-raft/src/main/java/org/apache/dolphinscheduler/plugin/registry/raft/RaftConnectionStateManager.java:
##########
@@ -0,0 +1,141 @@
+/*
+ * 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.dolphinscheduler.plugin.registry.raft;
+
+import org.apache.dolphinscheduler.registry.api.ConnectionListener;
+import org.apache.dolphinscheduler.registry.api.ConnectionState;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import lombok.extern.slf4j.Slf4j;
+
+import com.alipay.sofa.jraft.RouteTable;
+import com.alipay.sofa.jraft.option.CliOptions;
+import com.alipay.sofa.jraft.rpc.CliClientService;
+import com.alipay.sofa.jraft.rpc.impl.cli.CliClientServiceImpl;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+
+@Slf4j
+public class RaftConnectionStateManager implements IRaftConnectionStateManager 
{
+
+    private static final String DEFAULT_REGION_ID = "--1";
+    private ConnectionState currentConnectionState;
+    private static final Duration CONNECT_STATE_CHECK_INTERVENE = 
Duration.ofSeconds(2);
+    private final RaftRegistryProperties properties;
+    private final List<ConnectionListener> connectionListeners = new 
CopyOnWriteArrayList<>();
+    private final ScheduledExecutorService scheduledExecutorService;
+    private final CliOptions cliOptions;
+    private final CliClientService cliClientService;
+
+    public RaftConnectionStateManager(RaftRegistryProperties properties) {
+        this.properties = properties;
+        this.cliOptions = new CliOptions();
+        this.cliOptions.setMaxRetry(3);
+        this.cliOptions.setTimeoutMs(5000);
+        this.cliClientService = new CliClientServiceImpl();
+        this.scheduledExecutorService = Executors.newScheduledThreadPool(
+                1,
+                new 
ThreadFactoryBuilder().setNameFormat("ConnectionStateRefreshThread").setDaemon(true).build());
+    }
+    @Override
+    public void start() {
+        cliClientService.init(cliOptions);
+        scheduledExecutorService.scheduleWithFixedDelay(
+                new ConnectionStateRefreshTask(connectionListeners),
+                CONNECT_STATE_CHECK_INTERVENE.toMillis(),
+                CONNECT_STATE_CHECK_INTERVENE.toMillis(),
+                TimeUnit.MILLISECONDS);
+    }
+    @Override
+    public void addConnectionListener(ConnectionListener listener) {
+        connectionListeners.add(listener);
+    }
+
+    @Override
+    public ConnectionState getConnectionState() {
+        return currentConnectionState;
+    }
+
+    class ConnectionStateRefreshTask implements Runnable {
+
+        private final List<ConnectionListener> connectionListeners;
+        ConnectionStateRefreshTask(List<ConnectionListener> 
connectionListeners) {
+            this.connectionListeners = connectionListeners;
+        }
+
+        @Override
+        public void run() {
+            try {
+                ConnectionState newConnectionState = 
getCurrentConnectionState();
+                if (newConnectionState == currentConnectionState) {
+                    // no state change
+                    return;
+                }
+                if (newConnectionState == ConnectionState.DISCONNECTED
+                        && currentConnectionState == 
ConnectionState.CONNECTED) {
+                    currentConnectionState = ConnectionState.DISCONNECTED;
+                    triggerListeners(ConnectionState.DISCONNECTED);
+                } else if (newConnectionState == ConnectionState.CONNECTED
+                        && currentConnectionState == 
ConnectionState.DISCONNECTED) {
+                    currentConnectionState = ConnectionState.CONNECTED;
+                    triggerListeners(ConnectionState.RECONNECTED);
+                } else if (currentConnectionState == null) {
+                    currentConnectionState = newConnectionState;
+                    triggerListeners(currentConnectionState);
+                }
+            } catch (Exception ex) {
+                log.error("raft registry connection state check failed", ex);
+                currentConnectionState = ConnectionState.DISCONNECTED;
+                triggerListeners(ConnectionState.DISCONNECTED);
+            }
+        }
+
+        private ConnectionState getCurrentConnectionState() {
+            try {
+                String groupId = properties.getClusterName() + 
DEFAULT_REGION_ID;
+                if (RouteTable.getInstance().refreshLeader(cliClientService, 
groupId, 2000).isOk()) {

Review Comment:
   Same here.



##########
dolphinscheduler-registry/dolphinscheduler-registry-plugins/dolphinscheduler-registry-raft/src/main/java/org/apache/dolphinscheduler/plugin/registry/raft/RaftLockManager.java:
##########
@@ -0,0 +1,139 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.dolphinscheduler.plugin.registry.raft;
+
+import org.apache.dolphinscheduler.common.thread.ThreadUtils;
+import org.apache.dolphinscheduler.common.utils.NetUtils;
+import org.apache.dolphinscheduler.common.utils.OSUtils;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import com.alipay.sofa.jraft.rhea.client.RheaKVStore;
+import com.alipay.sofa.jraft.rhea.util.concurrent.DistributedLock;
+import com.alipay.sofa.jraft.util.ExecutorServiceHelper;
+
+public class RaftLockManager implements IRaftLockManager {
+
+    private final Map<String, LockEntry> distributedLockMap = new 
ConcurrentHashMap<>();
+    private final RheaKVStore rheaKvStore;
+    private final RaftRegistryProperties raftRegistryProperties;
+    private static final ScheduledExecutorService WATCH_DOG = 
Executors.newSingleThreadScheduledExecutor();

Review Comment:
   ```suggestion
       private static final ScheduledExecutorService scheduledExecutorService = 
Executors.newSingleThreadScheduledExecutor();
   ```



##########
dolphinscheduler-registry/dolphinscheduler-registry-plugins/dolphinscheduler-registry-raft/src/main/java/org/apache/dolphinscheduler/plugin/registry/raft/RaftLockManager.java:
##########
@@ -0,0 +1,139 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.dolphinscheduler.plugin.registry.raft;
+
+import org.apache.dolphinscheduler.common.thread.ThreadUtils;
+import org.apache.dolphinscheduler.common.utils.NetUtils;
+import org.apache.dolphinscheduler.common.utils.OSUtils;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import com.alipay.sofa.jraft.rhea.client.RheaKVStore;
+import com.alipay.sofa.jraft.rhea.util.concurrent.DistributedLock;
+import com.alipay.sofa.jraft.util.ExecutorServiceHelper;
+
+public class RaftLockManager implements IRaftLockManager {
+
+    private final Map<String, LockEntry> distributedLockMap = new 
ConcurrentHashMap<>();
+    private final RheaKVStore rheaKvStore;
+    private final RaftRegistryProperties raftRegistryProperties;
+    private static final ScheduledExecutorService WATCH_DOG = 
Executors.newSingleThreadScheduledExecutor();
+    private static final String LOCK_OWNER_PREFIX = NetUtils.getHost() + "_" + 
OSUtils.getProcessID() + "_";
+
+    public RaftLockManager(RheaKVStore rheaKVStore, RaftRegistryProperties 
raftRegistryProperties) {
+        this.rheaKvStore = rheaKVStore;
+        this.raftRegistryProperties = raftRegistryProperties;
+    }
+
+    @Override
+    public boolean acquireLock(String lockKey) {
+        final String lockOwner = getLockOwnerPrefix();
+        if (isThreadReentrant(lockKey, lockOwner)) {
+            return true;
+        }
+
+        final DistributedLock<byte[]> distributedLock = 
rheaKvStore.getDistributedLock(lockKey,
+                raftRegistryProperties.getDistributedLockTimeout().toMillis(), 
TimeUnit.MILLISECONDS, WATCH_DOG);
+
+        while (true) {
+            if (distributedLock.tryLock()) {
+                distributedLockMap.put(lockKey, 
LockEntry.builder().distributedLock(distributedLock)
+                        .lockOwner(lockOwner)
+                        .build());
+                return true;
+            } else {
+                // fail to acquire lock
+                
ThreadUtils.sleep(raftRegistryProperties.getDistributedLockRetryInterval().toMillis());
+            }
+        }
+    }
+
+    @Override
+    public boolean acquireLock(String lockKey, long timeout) {
+        final String lockOwner = getLockOwnerPrefix();
+        if (isThreadReentrant(lockKey, lockOwner)) {
+            return true;
+        }
+        final long endTime = System.currentTimeMillis() + timeout;
+        final DistributedLock<byte[]> distributedLock = 
rheaKvStore.getDistributedLock(lockKey,
+                raftRegistryProperties.getDistributedLockTimeout().toMillis(), 
TimeUnit.MILLISECONDS, WATCH_DOG);
+
+        while (System.currentTimeMillis() < endTime) {
+            if (distributedLock.tryLock()) {
+                distributedLockMap.put(lockKey, 
LockEntry.builder().distributedLock(distributedLock)
+                        .lockOwner(lockOwner)
+                        .build());
+                return true;
+            } else {
+                // fail to acquire lock
+                
ThreadUtils.sleep(raftRegistryProperties.getDistributedLockRetryInterval().toMillis());
+            }
+        }
+
+        return false;
+    }
+
+    private boolean isThreadReentrant(String lockKey, String lockOwner) {
+        final LockEntry lockEntry = distributedLockMap.get(lockKey);
+        return lockEntry != null && lockOwner.equals(lockEntry.getLockOwner());
+    }
+
+    @Override
+    public boolean releaseLock(String lockKey) {
+        final String lockOwner = getLockOwnerPrefix();
+        final LockEntry lockEntry = distributedLockMap.get(lockKey);
+        if (lockEntry == null || !lockOwner.equals(lockEntry.getLockOwner())) {
+            return false;
+        }
+
+        final DistributedLock<byte[]> distributedLock = 
distributedLockMap.get(lockKey).getDistributedLock();
+        if (distributedLock != null) {
+            distributedLock.unlock();
+        }
+        distributedLockMap.remove(lockKey);
+        return true;
+    }
+
+    public static String getLockOwnerPrefix() {
+        return LOCK_OWNER_PREFIX + Thread.currentThread().getName();
+    }
+
+    @Data
+    @AllArgsConstructor
+    @NoArgsConstructor
+    @Builder
+    public static class LockEntry {
+
+        private DistributedLock<byte[]> distributedLock;
+        private String lockOwner;
+    }

Review Comment:
   It's better to split into individual files.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to