diff --git a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/SerialCommandMapper.java b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/SerialCommandMapper.java index 875481e8ca7b..36191dd933c2 100644 --- a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/SerialCommandMapper.java +++ b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/SerialCommandMapper.java @@ -21,6 +21,7 @@ import org.apache.ibatis.annotations.Param; +import java.util.Date; import java.util.List; import com.baomidou.mybatisplus.core.mapper.BaseMapper; @@ -31,4 +32,11 @@ public interface SerialCommandMapper extends BaseMapper { int deleteByWorkflowInstanceId(@Param("workflowInstanceId") int workflowInstanceId); + int launchSerialCommand(@Param("id") Integer id, + @Param("originState") int originState, + @Param("targetState") int targetState, + @Param("updateTime") Date updateTime); + + int deleteByIdAndState(@Param("id") Integer id, @Param("state") int state); + } diff --git a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/repository/SerialCommandDao.java b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/repository/SerialCommandDao.java index 065fd1a7ef40..f9fdab368d83 100644 --- a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/repository/SerialCommandDao.java +++ b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/repository/SerialCommandDao.java @@ -20,6 +20,7 @@ import org.apache.dolphinscheduler.dao.entity.SerialCommand; import org.apache.dolphinscheduler.dao.model.SerialCommandDto; +import java.util.Date; import java.util.List; public interface SerialCommandDao extends IDao { @@ -28,4 +29,8 @@ public interface SerialCommandDao extends IDao { int deleteByWorkflowInstanceId(Integer workflowInstanceId); + boolean launchSerialCommand(Integer id, Date updateTime); + + boolean deleteByIdAndState(Integer id, SerialCommandDto.State state); + } diff --git a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/repository/impl/SerialCommandDaoImpl.java b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/repository/impl/SerialCommandDaoImpl.java index 499a0c3fc774..ff10b559f38f 100644 --- a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/repository/impl/SerialCommandDaoImpl.java +++ b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/repository/impl/SerialCommandDaoImpl.java @@ -23,6 +23,7 @@ import org.apache.dolphinscheduler.dao.repository.BaseDao; import org.apache.dolphinscheduler.dao.repository.SerialCommandDao; +import java.util.Date; import java.util.List; import java.util.stream.Collectors; @@ -47,4 +48,16 @@ public List fetchSerialCommands(int fetchSize) { public int deleteByWorkflowInstanceId(Integer workflowInstanceId) { return mybatisMapper.deleteByWorkflowInstanceId(workflowInstanceId); } + @Override + public boolean launchSerialCommand(Integer id, Date updateTime) { + return mybatisMapper.launchSerialCommand(id, + SerialCommandDto.State.WAITING.getValue(), + SerialCommandDto.State.LAUNCHED.getValue(), + updateTime) > 0; + } + + @Override + public boolean deleteByIdAndState(Integer id, SerialCommandDto.State state) { + return mybatisMapper.deleteByIdAndState(id, state.getValue()) > 0; + } } diff --git a/dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/SerialCommandMapper.xml b/dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/SerialCommandMapper.xml index 964975825214..70590fbde971 100644 --- a/dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/SerialCommandMapper.xml +++ b/dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/SerialCommandMapper.xml @@ -33,4 +33,13 @@ delete from t_ds_serial_command where workflow_instance_id = #{workflowInstanceId} + + update t_ds_serial_command + set state = #{targetState}, update_time = #{updateTime} + where id = #{id} and state = #{originState} + + + + delete from t_ds_serial_command where id = #{id} and state = #{state} + \ No newline at end of file diff --git a/dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/repository/impl/SerialCommandDaoImplTest.java b/dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/repository/impl/SerialCommandDaoImplTest.java new file mode 100644 index 000000000000..0689b09d7739 --- /dev/null +++ b/dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/repository/impl/SerialCommandDaoImplTest.java @@ -0,0 +1,88 @@ +/* + * 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.dao.repository.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.dolphinscheduler.dao.BaseDaoTest; +import org.apache.dolphinscheduler.dao.entity.SerialCommand; +import org.apache.dolphinscheduler.dao.model.SerialCommandDto; +import org.apache.dolphinscheduler.dao.repository.SerialCommandDao; + +import java.util.Date; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +class SerialCommandDaoImplTest extends BaseDaoTest { + + @Autowired + private SerialCommandDao serialCommandDao; + + @Test + void testWaitingCommandCanOnlyBeAcquiredOnce() { + SerialCommand command = insertWaitingCommand(); + Date updateTime = new Date(System.currentTimeMillis() + 1000); + assertTrue(serialCommandDao.launchSerialCommand(command.getId(), updateTime)); + assertFalse(serialCommandDao.launchSerialCommand(command.getId(), new Date())); + SerialCommand acquired = serialCommandDao.queryById(command.getId()); + assertEquals(SerialCommandDto.State.LAUNCHED.getValue(), acquired.getState()); + assertEquals(updateTime, acquired.getUpdateTime()); + } + + @Test + void testStaleWaitingSnapshotCannotDeleteLaunchedCommand() { + SerialCommand command = insertWaitingCommand(); + assertTrue(serialCommandDao.launchSerialCommand(command.getId(), new Date())); + assertFalse(serialCommandDao.deleteByIdAndState(command.getId(), SerialCommandDto.State.WAITING)); + assertNotNull(serialCommandDao.queryById(command.getId())); + } + + @Test + void testWaitingCommandCanOnlyBeDiscardedOnce() { + SerialCommand command = insertWaitingCommand(); + assertTrue(serialCommandDao.deleteByIdAndState(command.getId(), SerialCommandDto.State.WAITING)); + assertFalse(serialCommandDao.deleteByIdAndState(command.getId(), SerialCommandDto.State.WAITING)); + assertNull(serialCommandDao.queryById(command.getId())); + } + + @Test + void testDiscardedCommandCannotBeAcquired() { + SerialCommand command = insertWaitingCommand(); + assertTrue(serialCommandDao.deleteByIdAndState(command.getId(), SerialCommandDto.State.WAITING)); + assertFalse(serialCommandDao.launchSerialCommand(command.getId(), new Date())); + } + + private SerialCommand insertWaitingCommand() { + SerialCommand command = SerialCommand.builder() + .workflowInstanceId(1) + .workflowDefinitionCode(1L) + .workflowDefinitionVersion(1) + .command("{}") + .state(SerialCommandDto.State.WAITING.getValue()) + .createTime(new Date()) + .updateTime(new Date()) + .build(); + assertEquals(1, serialCommandDao.insert(command)); + return command; + } +} diff --git a/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/AbstractSerialCommandHandler.java b/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/AbstractSerialCommandHandler.java index 7a67f220856f..0b68e4374a4e 100644 --- a/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/AbstractSerialCommandHandler.java +++ b/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/AbstractSerialCommandHandler.java @@ -19,7 +19,6 @@ import org.apache.dolphinscheduler.common.enums.WorkflowExecutionStatus; import org.apache.dolphinscheduler.common.utils.DateUtils; -import org.apache.dolphinscheduler.dao.entity.Command; import org.apache.dolphinscheduler.dao.entity.WorkflowInstance; import org.apache.dolphinscheduler.dao.model.SerialCommandDto; import org.apache.dolphinscheduler.dao.repository.CommandDao; @@ -34,8 +33,6 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; @Slf4j @@ -59,40 +56,46 @@ public abstract class AbstractSerialCommandHandler implements ISerialCommandHand @Autowired protected SerialCommandDao serialCommandDao; - protected void launchSerialCommand(SerialCommandDto serialCommand) { - transactionTemplate.execute(new TransactionCallback() { - - @Override - public Void doInTransaction(TransactionStatus status) { - final Command command = serialCommand.getCommand(); - commandDao.insert(command); - - serialCommand.setState(SerialCommandDto.State.LAUNCHED); - serialCommandDao.updateById(serialCommand.toEntity()); - return null; + protected boolean launchSerialCommand(SerialCommandDto serialCommand) { + final boolean launched = Boolean.TRUE.equals(transactionTemplate.execute(status -> { + // Claim before inserting so two WAITING snapshots cannot create two Commands. + if (!serialCommandDao.launchSerialCommand(serialCommand.getId(), DateUtils.getCurrentDate())) { + log.info("Skip launching SerialCommand: {}, it is no longer in WAITING state", serialCommand.getId()); + return false; + } + if (commandDao.insert(serialCommand.getCommand()) != 1) { + throw new IllegalStateException("Failed to insert Command for SerialCommand: " + serialCommand.getId()); } - }); + return true; + })); + if (launched) { + // Keep the snapshot unchanged if the transaction rolls back. + serialCommand.setState(SerialCommandDto.State.LAUNCHED); + } + return launched; } - protected void discardSerialCommandAndStopWorkflowInstanceInDB(SerialCommandDto serialCommand) { - transactionTemplate.execute(new TransactionCallback() { - - @Override - public Void doInTransaction(TransactionStatus status) { - serialCommandDao.deleteById(serialCommand.getId()); - - // todo: call api to stop the workflow instance - final Integer workflowInstanceId = serialCommand.getWorkflowInstanceId(); - final WorkflowInstance workflowInstance = workflowInstanceDao.queryById(workflowInstanceId); - workflowInstance.setEndTime(DateUtils.getCurrentDate()); - workflowInstance.setState(WorkflowExecutionStatus.STOP); - workflowInstanceDao.upsertWorkflowInstance(workflowInstance); - WorkflowInstanceMetrics.recordWorkflowInstanceFinish( - WorkflowExecutionStatus.STOP, - workflowInstance.getWorkflowDefinitionCode()); - return null; + protected boolean discardSerialCommandAndStopWorkflowInstanceInDB(SerialCommandDto serialCommand) { + return Boolean.TRUE.equals(transactionTemplate.execute(status -> { + // A stale WAITING snapshot must not discard a Command another coordinator has launched. + if (!serialCommandDao.deleteByIdAndState(serialCommand.getId(), SerialCommandDto.State.WAITING)) { + log.info("Skip discarding SerialCommand: {}, it is no longer in WAITING state", serialCommand.getId()); + return false; + } + + // todo: call api to stop the workflow instance + final Integer workflowInstanceId = serialCommand.getWorkflowInstanceId(); + final WorkflowInstance workflowInstance = workflowInstanceDao.queryById(workflowInstanceId); + workflowInstance.setEndTime(DateUtils.getCurrentDate()); + workflowInstance.setState(WorkflowExecutionStatus.STOP); + if (!workflowInstanceDao.updateById(workflowInstance)) { + throw new IllegalStateException("Failed to stop WorkflowInstance: " + workflowInstanceId); } - }); + WorkflowInstanceMetrics.recordWorkflowInstanceFinish( + WorkflowExecutionStatus.STOP, + workflowInstance.getWorkflowDefinitionCode()); + return true; + })); } protected void stopWorkflowInstanceInMaster(SerialCommandDto serialCommand) { diff --git a/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandDiscardHandler.java b/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandDiscardHandler.java index f2ce439a8784..3fd4a98076d8 100644 --- a/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandDiscardHandler.java +++ b/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandDiscardHandler.java @@ -41,7 +41,10 @@ public void handle(SerialCommandsGroup serialCommandsGroup) { SerialCommandDto serialCommand = serialCommands.get(i); if (i == 0) { if (serialCommand.getState() == SerialCommandDto.State.WAITING) { - launchSerialCommand(serialCommand); + if (!launchSerialCommand(serialCommand)) { + // Retry this group from a fresh snapshot in the next coordinator round. + return; + } log.info("Launched SerialCommand: {}", serialCommand); } continue; @@ -51,7 +54,9 @@ public void handle(SerialCommandsGroup serialCommandsGroup) { throw new IllegalStateException( "The post SerialCommand except WAITING state but -> " + serialCommand.getState()); } - discardSerialCommandAndStopWorkflowInstanceInDB(serialCommand); + if (!discardSerialCommandAndStopWorkflowInstanceInDB(serialCommand)) { + return; + } log.info("Discard SerialCommand: {}", serialCommand); } } diff --git a/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandPriorityHandler.java b/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandPriorityHandler.java index a6a1745dedab..cf134843cbe1 100644 --- a/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandPriorityHandler.java +++ b/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandPriorityHandler.java @@ -39,15 +39,17 @@ public void handle(SerialCommandsGroup serialCommandsGroup) { for (int i = 0; i < serialCommands.size(); i++) { final SerialCommandDto serialCommand = serialCommands.get(i); if (i == serialCommands.size() - 1) { - if (serialCommand.getState() == SerialCommandDto.State.WAITING) { - launchSerialCommand(serialCommand); + if (serialCommand.getState() == SerialCommandDto.State.WAITING && launchSerialCommand(serialCommand)) { log.info("Launched SerialCommand: {}", serialCommand); } continue; } if (serialCommand.getState() == SerialCommandDto.State.WAITING) { - discardSerialCommandAndStopWorkflowInstanceInDB(serialCommand); + if (!discardSerialCommandAndStopWorkflowInstanceInDB(serialCommand)) { + // Re-read the group before deciding whether a launched predecessor must be stopped. + return; + } log.info("Discard SerialCommand: {}", serialCommand); } else { stopWorkflowInstanceInMaster(serialCommand); diff --git a/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandWaitHandler.java b/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandWaitHandler.java index 453b5ac00053..2751e30b207a 100644 --- a/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandWaitHandler.java +++ b/dolphinscheduler-master/src/main/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandWaitHandler.java @@ -42,8 +42,7 @@ public void handle(SerialCommandsGroup serialCommandsGroup) { return; } final SerialCommandDto serialCommand = serialCommands.get(0); - if (serialCommand.getState() == SerialCommandDto.State.WAITING) { - launchSerialCommand(serialCommand); + if (serialCommand.getState() == SerialCommandDto.State.WAITING && launchSerialCommand(serialCommand)) { log.info("Launched SerialCommand: {}", serialCommand); } } diff --git a/dolphinscheduler-master/src/test/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandHandlerTest.java b/dolphinscheduler-master/src/test/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandHandlerTest.java new file mode 100644 index 000000000000..724b7ee3d375 --- /dev/null +++ b/dolphinscheduler-master/src/test/java/org/apache/dolphinscheduler/server/master/engine/workflow/serial/SerialCommandHandlerTest.java @@ -0,0 +1,254 @@ +/* + * 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.engine.workflow.serial; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.apache.dolphinscheduler.common.enums.CommandType; +import org.apache.dolphinscheduler.common.enums.WorkflowExecutionStatus; +import org.apache.dolphinscheduler.dao.entity.Command; +import org.apache.dolphinscheduler.dao.entity.WorkflowInstance; +import org.apache.dolphinscheduler.dao.model.SerialCommandDto; +import org.apache.dolphinscheduler.dao.repository.CommandDao; +import org.apache.dolphinscheduler.dao.repository.SerialCommandDao; +import org.apache.dolphinscheduler.dao.repository.WorkflowInstanceDao; +import org.apache.dolphinscheduler.extract.master.IWorkflowControlClient; +import org.apache.dolphinscheduler.server.master.config.MasterConfig; + +import java.util.Arrays; +import java.util.Date; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; + +@ExtendWith(MockitoExtension.class) +class SerialCommandHandlerTest { + + @Mock + private SerialCommandDao serialCommandDao; + @Mock + private CommandDao commandDao; + @Mock + private WorkflowInstanceDao workflowInstanceDao; + @Mock + private IWorkflowControlClient workflowControlClient; + @Mock + private MasterConfig masterConfig; + @Mock + private PlatformTransactionManager transactionManager; + @Mock + private TransactionStatus transactionStatus; + + private SerialCommandWaitHandler waitHandler; + private SerialCommandDiscardHandler discardHandler; + private SerialCommandPriorityHandler priorityHandler; + + @BeforeEach + void setUp() { + when(transactionManager.getTransaction(any(TransactionDefinition.class))).thenReturn(transactionStatus); + waitHandler = configure(new SerialCommandWaitHandler()); + discardHandler = configure(new SerialCommandDiscardHandler()); + priorityHandler = configure(new SerialCommandPriorityHandler()); + } + + @Test + void testWaitLaunchesClaimedCommand() { + SerialCommandDto command = command(1, SerialCommandDto.State.WAITING); + when(serialCommandDao.launchSerialCommand(eq(1), any(Date.class))).thenReturn(true); + when(commandDao.insert(command.getCommand())).thenReturn(1); + waitHandler.handle(group(command)); + assertEquals(SerialCommandDto.State.LAUNCHED, command.getState()); + verify(commandDao).insert(command.getCommand()); + verify(transactionManager).commit(transactionStatus); + } + + @Test + void testWaitDoesNotInsertFromStaleWaitingSnapshot() { + SerialCommandDto command = command(1, SerialCommandDto.State.WAITING); + when(serialCommandDao.launchSerialCommand(eq(1), any(Date.class))).thenReturn(false); + waitHandler.handle(group(command)); + verify(commandDao, never()).insert(any()); + assertEquals(SerialCommandDto.State.WAITING, command.getState()); + } + + @Test + void testInsertReturningZeroRollsBackClaim() { + SerialCommandDto command = command(1, SerialCommandDto.State.WAITING); + when(serialCommandDao.launchSerialCommand(eq(1), any(Date.class))).thenReturn(true); + when(commandDao.insert(command.getCommand())).thenReturn(0); + assertThrows(IllegalStateException.class, () -> waitHandler.handle(group(command))); + verify(transactionManager).rollback(transactionStatus); + verify(transactionManager, never()).commit(any()); + assertEquals(SerialCommandDto.State.WAITING, command.getState()); + } + + @Test + void testInsertExceptionDoesNotChangeSnapshotState() { + SerialCommandDto command = command(1, SerialCommandDto.State.WAITING); + when(serialCommandDao.launchSerialCommand(eq(1), any(Date.class))).thenReturn(true); + when(commandDao.insert(command.getCommand())).thenThrow(new IllegalStateException("insert failed")); + assertThrows(IllegalStateException.class, () -> waitHandler.handle(group(command))); + verify(transactionManager).rollback(transactionStatus); + assertEquals(SerialCommandDto.State.WAITING, command.getState()); + } + + @Test + void testDiscardStopsOnlySuccessfullyDeletedWaitingCommand() { + SerialCommandDto head = command(1, SerialCommandDto.State.LAUNCHED); + SerialCommandDto waiting = command(2, SerialCommandDto.State.WAITING); + WorkflowInstance instance = instance(waiting); + when(serialCommandDao.deleteByIdAndState(2, SerialCommandDto.State.WAITING)).thenReturn(true); + when(workflowInstanceDao.queryById(waiting.getWorkflowInstanceId())).thenReturn(instance); + when(workflowInstanceDao.updateById(instance)).thenReturn(true); + discardHandler.handle(group(head, waiting)); + assertEquals(WorkflowExecutionStatus.STOP, instance.getState()); + verify(workflowInstanceDao).updateById(instance); + verify(serialCommandDao, never()).deleteById(any()); + } + + @Test + void testDiscardConflictLeavesRemainingOldSnapshotUntouched() { + SerialCommandDto head = command(1, SerialCommandDto.State.LAUNCHED); + SerialCommandDto conflicting = command(2, SerialCommandDto.State.WAITING); + SerialCommandDto remaining = command(3, SerialCommandDto.State.WAITING); + when(serialCommandDao.deleteByIdAndState(2, SerialCommandDto.State.WAITING)).thenReturn(false); + discardHandler.handle(group(head, conflicting, remaining)); + verify(serialCommandDao, never()).deleteByIdAndState(3, SerialCommandDto.State.WAITING); + verify(workflowInstanceDao, never()).queryById(anyInt()); + verify(commandDao, never()).insert(any()); + } + + @Test + void testDiscardDoesNotContinueAfterLosingHeadClaim() { + SerialCommandDto head = command(1, SerialCommandDto.State.WAITING); + SerialCommandDto remaining = command(2, SerialCommandDto.State.WAITING); + when(serialCommandDao.launchSerialCommand(eq(1), any(Date.class))).thenReturn(false); + discardHandler.handle(group(head, remaining)); + verify(serialCommandDao, never()).deleteByIdAndState(anyInt(), any()); + verify(commandDao, never()).insert(any()); + } + + @Test + void testFailedWorkflowUpdateRollsBackDiscard() { + SerialCommandDto head = command(1, SerialCommandDto.State.LAUNCHED); + SerialCommandDto waiting = command(2, SerialCommandDto.State.WAITING); + WorkflowInstance instance = instance(waiting); + when(serialCommandDao.deleteByIdAndState(2, SerialCommandDto.State.WAITING)).thenReturn(true); + when(workflowInstanceDao.queryById(waiting.getWorkflowInstanceId())).thenReturn(instance); + when(workflowInstanceDao.updateById(instance)).thenReturn(false); + assertThrows(IllegalStateException.class, () -> discardHandler.handle(group(head, waiting))); + verify(transactionManager).rollback(transactionStatus); + } + + @Test + void testPriorityDoesNotLaunchTailAfterDiscardConflict() { + SerialCommandDto previous = command(1, SerialCommandDto.State.WAITING); + SerialCommandDto newest = command(2, SerialCommandDto.State.WAITING); + when(serialCommandDao.deleteByIdAndState(1, SerialCommandDto.State.WAITING)).thenReturn(false); + priorityHandler.handle(group(previous, newest)); + verify(serialCommandDao, never()).launchSerialCommand(anyInt(), any()); + verify(workflowInstanceDao, never()).queryById(anyInt()); + verify(commandDao, never()).insert(any()); + } + + @Test + void testPriorityHandlesFreshSnapshotAfterDiscardConflict() { + SerialCommandDto previous = command(1, SerialCommandDto.State.WAITING); + SerialCommandDto newest = command(2, SerialCommandDto.State.WAITING); + when(serialCommandDao.deleteByIdAndState(1, SerialCommandDto.State.WAITING)).thenReturn(false); + priorityHandler.handle(group(previous, newest)); + verify(commandDao, never()).insert(any()); + + // The next poll sees the predecessor as LAUNCHED and follows the existing stop-RPC path. + SerialCommandDto launched = command(1, SerialCommandDto.State.LAUNCHED); + WorkflowInstance instance = instance(launched); + when(workflowInstanceDao.queryById(launched.getWorkflowInstanceId())).thenReturn(instance); + when(masterConfig.getMasterAddress()).thenReturn("local-master"); + when(serialCommandDao.launchSerialCommand(eq(2), any(Date.class))).thenReturn(true); + when(commandDao.insert(newest.getCommand())).thenReturn(1); + priorityHandler.handle(group(launched, newest)); + verify(workflowControlClient).stopWorkflowInstance(any()); + verify(commandDao).insert(newest.getCommand()); + assertEquals(SerialCommandDto.State.LAUNCHED, newest.getState()); + } + + @Test + void testPriorityDiscardsWaitingPredecessorThenLaunchesNewest() { + SerialCommandDto previous = command(1, SerialCommandDto.State.WAITING); + SerialCommandDto newest = command(2, SerialCommandDto.State.WAITING); + WorkflowInstance instance = instance(previous); + when(serialCommandDao.deleteByIdAndState(1, SerialCommandDto.State.WAITING)).thenReturn(true); + when(workflowInstanceDao.queryById(previous.getWorkflowInstanceId())).thenReturn(instance); + when(workflowInstanceDao.updateById(instance)).thenReturn(true); + when(serialCommandDao.launchSerialCommand(eq(2), any(Date.class))).thenReturn(true); + when(commandDao.insert(newest.getCommand())).thenReturn(1); + priorityHandler.handle(group(previous, newest)); + assertEquals(WorkflowExecutionStatus.STOP, instance.getState()); + assertEquals(SerialCommandDto.State.LAUNCHED, newest.getState()); + verify(workflowControlClient, never()).stopWorkflowInstance(any()); + } + + private T configure(T handler) { + handler.serialCommandDao = serialCommandDao; + handler.commandDao = commandDao; + handler.workflowInstanceDao = workflowInstanceDao; + handler.workflowControlClient = workflowControlClient; + handler.masterConfig = masterConfig; + handler.transactionTemplate = new TransactionTemplate(transactionManager); + return handler; + } + + private SerialCommandsGroup group(SerialCommandDto... commands) { + return SerialCommandsGroup.builder().serialCommands(Arrays.asList(commands)).build(); + } + + private SerialCommandDto command(int id, SerialCommandDto.State state) { + return SerialCommandDto.builder() + .id(id) + .workflowInstanceId(id + 100) + .workflowDefinitionCode(1L) + .workflowDefinitionVersion(1) + .state(state) + .command(Command.builder().commandType(CommandType.START_PROCESS) + .workflowDefinitionCode(1L).workflowDefinitionVersion(1).workflowInstanceId(id + 100).build()) + .build(); + } + + private WorkflowInstance instance(SerialCommandDto command) { + WorkflowInstance instance = new WorkflowInstance(); + instance.setId(command.getWorkflowInstanceId()); + instance.setWorkflowDefinitionCode(command.getWorkflowDefinitionCode()); + instance.setState(WorkflowExecutionStatus.RUNNING_EXECUTION); + instance.setHost("local-master"); + return instance; + } +} diff --git a/dolphinscheduler-registry/dolphinscheduler-registry-api/src/main/java/org/apache/dolphinscheduler/registry/api/ha/AbstractHAServer.java b/dolphinscheduler-registry/dolphinscheduler-registry-api/src/main/java/org/apache/dolphinscheduler/registry/api/ha/AbstractHAServer.java index a79b14d99d5c..11f1c4dcb3ec 100644 --- a/dolphinscheduler-registry/dolphinscheduler-registry-api/src/main/java/org/apache/dolphinscheduler/registry/api/ha/AbstractHAServer.java +++ b/dolphinscheduler-registry/dolphinscheduler-registry-api/src/main/java/org/apache/dolphinscheduler/registry/api/ha/AbstractHAServer.java @@ -50,7 +50,7 @@ public abstract class AbstractHAServer implements HAServer { public AbstractHAServer(final Registry registry, final String selectorPath, final String serverIdentify) { this.registry = registry; this.selectorPath = checkNotNull(selectorPath); - this.serverIdentify = checkNotNull(serverIdentify); + this.serverIdentify = checkNotNull(serverIdentify) + "#" + System.currentTimeMillis(); this.serverStatus = ServerStatus.STAND_BY; this.serverStatusChangeListeners = Lists.newArrayList(new DefaultServerStatusChangeListener()); } diff --git a/dolphinscheduler-registry/dolphinscheduler-registry-api/src/test/java/org/apache/dolphinscheduler/registry/api/ha/AbstractHAServerTest.java b/dolphinscheduler-registry/dolphinscheduler-registry-api/src/test/java/org/apache/dolphinscheduler/registry/api/ha/AbstractHAServerTest.java new file mode 100644 index 000000000000..870f5d4613f0 --- /dev/null +++ b/dolphinscheduler-registry/dolphinscheduler-registry-api/src/test/java/org/apache/dolphinscheduler/registry/api/ha/AbstractHAServerTest.java @@ -0,0 +1,121 @@ +/* + * 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.registry.api.ha; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.apache.dolphinscheduler.registry.api.Registry; + +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class AbstractHAServerTest { + + private static final String SELECTOR_PATH = "/coordinator"; + private static final String ADDRESS = "master-0:5678"; + + private final AtomicReference owner = new AtomicReference<>(); + private Registry registry; + private AbstractHAServer server; + + @BeforeEach + void setUp() { + registry = mock(Registry.class); + when(registry.acquireLock(SELECTOR_PATH + "-lock")).thenReturn(true); + when(registry.exists(SELECTOR_PATH)).thenAnswer(invocation -> owner.get() != null); + when(registry.get(SELECTOR_PATH)).thenAnswer(invocation -> owner.get()); + doAnswer(invocation -> { + owner.set(invocation.getArgument(1)); + return null; + }).when(registry).put(eq(SELECTOR_PATH), anyString(), eq(true)); + server = new AbstractHAServer(registry, SELECTOR_PATH, ADDRESS) { + + @Override + public void close() { + } + }; + } + + @Test + void testInitialElectionWritesAddressAndTimestamp() { + server.start(); + + assertTrue(server.isActive()); + assertTrue(owner.get().startsWith(ADDRESS + "#")); + assertTrue(Long.parseLong(owner.get().substring(ADDRESS.length() + 1)) > 0); + verify(registry).put(SELECTOR_PATH, owner.get(), true); + } + + @Test + void testDoesNotAdoptLegacySelectorAtSameAddress() { + // The predecessor's selector can remain until its Registry lease or session expires. + owner.set(ADDRESS); + + server.start(); + + assertFalse(server.isActive()); + assertEquals(ADDRESS, owner.get()); + verify(registry, never()).put(eq(SELECTOR_PATH), anyString(), eq(true)); + } + + @Test + void testDoesNotAdoptPredecessorWithEarlierTimestamp() { + String predecessor = ADDRESS + "#0"; + owner.set(predecessor); + + server.start(); + + assertFalse(server.isActive()); + assertEquals(predecessor, owner.get()); + verify(registry, never()).put(eq(SELECTOR_PATH), anyString(), eq(true)); + } + + @Test + void testRecheckRecognizesCurrentProcess() { + server.start(); + String identity = owner.get(); + + assertTrue(server.participateElection()); + + assertEquals(identity, owner.get()); + verify(registry, times(1)).put(eq(SELECTOR_PATH), anyString(), eq(true)); + } + + @Test + void testDoesNotReplaceExistingPeerSelector() { + owner.set("master-1:5678#0"); + + server.start(); + + assertFalse(server.isActive()); + assertEquals("master-1:5678#0", owner.get()); + verify(registry, never()).put(eq(SELECTOR_PATH), anyString(), eq(true)); + } +}