Gallardot commented on code in PR #15528:
URL: 
https://github.com/apache/dolphinscheduler/pull/15528#discussion_r1473938389


##########
dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/runner/taskgroup/TaskGroupCoordinator.java:
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.server.master.runner.taskgroup;
+
+import org.apache.dolphinscheduler.common.constants.Constants;
+import org.apache.dolphinscheduler.common.enums.Flag;
+import org.apache.dolphinscheduler.common.enums.TaskGroupQueueStatus;
+import org.apache.dolphinscheduler.common.enums.WorkflowExecutionStatus;
+import org.apache.dolphinscheduler.common.lifecycle.ServerLifeCycleManager;
+import org.apache.dolphinscheduler.common.thread.BaseDaemonThread;
+import org.apache.dolphinscheduler.common.thread.ThreadUtils;
+import org.apache.dolphinscheduler.dao.entity.ProcessInstance;
+import org.apache.dolphinscheduler.dao.entity.TaskGroup;
+import org.apache.dolphinscheduler.dao.entity.TaskGroupQueue;
+import org.apache.dolphinscheduler.dao.entity.TaskInstance;
+import org.apache.dolphinscheduler.dao.repository.ProcessInstanceDao;
+import org.apache.dolphinscheduler.dao.repository.TaskGroupDao;
+import org.apache.dolphinscheduler.dao.repository.TaskGroupQueueDao;
+import org.apache.dolphinscheduler.dao.repository.TaskInstanceDao;
+import 
org.apache.dolphinscheduler.extract.base.client.SingletonJdkDynamicRpcClientProxyFactory;
+import org.apache.dolphinscheduler.extract.master.IWorkflowInstanceService;
+import 
org.apache.dolphinscheduler.extract.master.transportor.TaskInstanceWakeupRequest;
+import 
org.apache.dolphinscheduler.extract.master.transportor.TaskInstanceWakeupResponse;
+import org.apache.dolphinscheduler.plugin.task.api.enums.TaskExecutionStatus;
+import org.apache.dolphinscheduler.plugin.task.api.utils.LogUtils;
+import org.apache.dolphinscheduler.registry.api.RegistryClient;
+import org.apache.dolphinscheduler.registry.api.enums.RegistryNodeType;
+
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.commons.lang3.time.StopWatch;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import lombok.extern.slf4j.Slf4j;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * The TaskGroupCoordinator use to manage the task group slot. The task group 
slot is used to limit the number of {@link TaskInstance} that can be run at the 
same time.
+ * <p>
+ * The {@link TaskGroupQueue} is used to represent the task group slot. When a 
{@link TaskGroupQueue} which inQueue is YES means the {@link TaskGroupQueue} is 
using by a {@link TaskInstance}.
+ * <p>
+ * When the {@link TaskInstance} need to use task group, we should use @{@link 
TaskGroupCoordinator#acquireTaskGroupSlot(TaskInstance)} to acquire the task 
group slot,
+ * this method doesn't block should always acquire successfully, and you 
should directly stop dispatch the task instance.
+ * When the task group slot is available, the TaskGroupCoordinator will wake 
up the waiting {@link TaskInstance} to dispatch.
+ * <pre>
+ *     if(needAcquireTaskGroupSlot(taskInstance)) {
+ *         taskGroupCoordinator.acquireTaskGroupSlot(taskInstance);
+ *         return;
+ *     }
+ * </pre>
+ * <p>
+ * When the {@link TaskInstance} is finished, we should use @{@link 
TaskGroupCoordinator#releaseTaskGroupSlot(TaskInstance)} to release the task 
group slot.
+ * <pre>
+ *     if(needToReleaseTaskGroupSlot(taskInstance)) {
+ *         taskGroupCoordinator.releaseTaskGroupSlot(taskInstance);
+ *     }
+ * </pre>
+ */
+@Slf4j
+@Component
+public class TaskGroupCoordinator extends BaseDaemonThread {
+
+    @Autowired
+    private RegistryClient registryClient;
+
+    @Autowired
+    private TaskGroupDao taskGroupDao;
+
+    @Autowired
+    private TaskGroupQueueDao taskGroupQueueDao;
+
+    @Autowired
+    private TaskInstanceDao taskInstanceDao;
+
+    @Autowired
+    private ProcessInstanceDao processInstanceDao;
+
+    public TaskGroupCoordinator() {
+        super("TaskGroupCoordinator");
+    }
+
+    @Override
+    public synchronized void start() {
+        log.info("TaskGroupCoordinator starting...");
+        super.start();
+        log.info("TaskGroupCoordinator started...");
+    }
+
+    @Override
+    public void run() {
+        while (!ServerLifeCycleManager.isStopped()) {
+            try {
+                if (!ServerLifeCycleManager.isRunning()) {
+                    continue;
+                }
+                try {
+                    
registryClient.getLock(RegistryNodeType.MASTER_TASK_GROUP_COORDINATOR_LOCK.getRegistryPath());
+                    StopWatch taskGroupCoordinatorRoundTimeCost = 
StopWatch.createStarted();
+
+                    amendTaskGroupUseSize();
+                    amendTaskGroupQueueStatus();
+                    dealWithForceStartTaskGroupQueue();
+                    dealWithWaitingTaskGroupQueue();
+
+                    taskGroupCoordinatorRoundTimeCost.stop();
+                    log.info("TaskGroupCoordinator round time cost: {}/ms",
+                            taskGroupCoordinatorRoundTimeCost.getTime());
+                } finally {
+                    
registryClient.releaseLock(RegistryNodeType.MASTER_TASK_GROUP_COORDINATOR_LOCK.getRegistryPath());
+                }
+            } catch (Throwable e) {
+                log.error("TaskGroupCoordinator error", e);
+            } finally {
+                // sleep 5s
+                ThreadUtils.sleep(Constants.SLEEP_TIME_MILLIS * 5);
+            }
+        }
+    }
+
+    /**
+     * Make sure the TaskGroup useSize is equal to the TaskGroupQueue which 
status is {@link TaskGroupQueueStatus#ACQUIRE_SUCCESS} and forceStart is {@link 
org.apache.dolphinscheduler.common.enums.Flag#NO}.
+     */
+    private void amendTaskGroupUseSize() {
+        // The TaskGroup useSize should equal to the TaskGroupQueue which 
inQueue is YES and forceStart is NO
+        List<TaskGroup> taskGroups = taskGroupDao.queryAllTaskGroups();
+        if (CollectionUtils.isEmpty(taskGroups)) {
+            return;
+        }
+        for (TaskGroup taskGroup : taskGroups) {
+            List<TaskGroupQueue> taskGroupQueues =
+                    
taskGroupQueueDao.queryAcquiredTaskGroupQueueByGroupId(taskGroup.getId());
+            int actualUseSize = taskGroupQueues.size();
+            if (taskGroup.getUseSize() == actualUseSize) {
+                continue;
+            }
+            log.warn("The TaskGroup: {} useSize is {}, but the actual use size 
is {}, will amend it",
+                    taskGroup.getName(),
+                    taskGroup.getUseSize(), actualUseSize);
+            taskGroup.setUseSize(actualUseSize);
+            taskGroupDao.updateById(taskGroup);
+        }
+    }
+
+    /**
+     * Make sure the TaskGroupQueue status is {@link 
TaskGroupQueueStatus#RELEASE} when the related {@link TaskInstance} is not 
exist or status is finished.
+     */
+    private void amendTaskGroupQueueStatus() {
+        List<TaskGroupQueue> taskGroupQueues = 
taskGroupQueueDao.queryAllInQueueTaskGroupQueue();
+        List<Integer> taskInstanceIds = taskGroupQueues.stream()
+                .map(TaskGroupQueue::getTaskId)
+                .collect(Collectors.toList());
+        Map<Integer, TaskInstance> taskInstanceMap = 
taskInstanceDao.queryByIds(taskInstanceIds)
+                .stream()
+                .collect(Collectors.toMap(TaskInstance::getId, 
Function.identity()));
+
+        for (TaskGroupQueue taskGroupQueue : taskGroupQueues) {
+            int taskId = taskGroupQueue.getTaskId();
+            TaskInstance taskInstance = taskInstanceMap.get(taskId);
+
+            if (taskInstance == null) {
+                log.warn("The TaskInstance: {} is not exist, will release the 
TaskGroupQueue: {}", taskId,
+                        taskGroupQueue);
+                releaseTaskGroupQueueSlot(taskGroupQueue);
+                continue;
+            }
+
+            if (taskInstance.getState().isFinished()) {
+                log.warn("The TaskInstance: {} state: {} finished, will 
release the TaskGroupQueue: {}",
+                        taskInstance.getName(), taskInstance.getState(), 
taskGroupQueue);
+                releaseTaskGroupQueueSlot(taskGroupQueue);
+                continue;

Review Comment:
   Useless code



-- 
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