Light, fluffy, and always free - The AWS Local Emulator alternative
fix(codepipeline): preserve external actions while stopping (#3726)
XuJianb3d46d502479
diff --git a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.javaindex 2aa25e049a..51aab941fe 100644--- a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java+++ b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java@@ -516,8 +516,10 @@ public class CodePipelineService {throw new AwsException("PipelineExecutionNotStoppableException","Pipeline execution is already in a terminal state", 400);}- execution.setStopRequested(true);+ // Publish the stop mode before the stop signal. The provider polling loop reads+ // stopRequested first, so observing it also observes the matching abandon value.execution.setAbandon(request.path("abandon").asBoolean(false));+ execution.setStopRequested(true);execution.setStatus("Stopping");execution.setStatusSummary(request.path("reason").asText("Stop requested."));execution.setLastUpdateTime(now());@@ -1142,16 +1144,21 @@ public class CodePipelineService {null, null, null, null, null, null, null);state.setExternalExecutionId(build.getId());while (!Boolean.TRUE.equals(build.getBuildComplete())) {- if (execution.isStopRequested()) {- codeBuildService.stopBuild(execution.getRegion(), execution.getAccountId(), build.getId());- break;+ if (abandonExternalActionIfRequested(execution, state)) {+ return;}TimeUnit.MILLISECONDS.sleep(POLL_INTERVAL_MS);build = codeBuildService.getBuild(execution.getRegion(), execution.getAccountId(), build.getId());}+ if (abandonExternalActionIfRequested(execution, state)) {+ return;+ }if (!"SUCCEEDED".equals(build.getBuildStatus())) {- throw new AwsException("ActionExecutionFailed",- "CodeBuild build " + build.getId() + " finished with " + build.getBuildStatus(), 400);+ String message = "CodeBuild build " + build.getId() + " finished with " + build.getBuildStatus();+ if (recordExternalActionFailureWhileStopping(execution, state, message)) {+ return;+ }+ throw new AwsException("ActionExecutionFailed", message, 400);}}@@ -1170,16 +1177,42 @@ public class CodePipelineService {state.setExternalExecutionId(deploymentId);Deployment deployment = codeDeployService.getDeployment(execution.getRegion(), deploymentId);while (!List.of("Succeeded", "Failed", "Stopped").contains(deployment.getStatus())) {- if (execution.isStopRequested()) {- codeDeployService.stopDeployment(execution.getRegion(), deploymentId);+ if (abandonExternalActionIfRequested(execution, state)) {+ return;}TimeUnit.MILLISECONDS.sleep(POLL_INTERVAL_MS);deployment = codeDeployService.getDeployment(execution.getRegion(), deploymentId);}+ if (abandonExternalActionIfRequested(execution, state)) {+ return;+ }if (!"Succeeded".equals(deployment.getStatus())) {- throw new AwsException("ActionExecutionFailed",- "CodeDeploy deployment finished with " + deployment.getStatus(), 400);+ String message = "CodeDeploy deployment finished with " + deployment.getStatus();+ if (recordExternalActionFailureWhileStopping(execution, state, message)) {+ return;+ }+ throw new AwsException("ActionExecutionFailed", message, 400);+ }+ }++ private boolean abandonExternalActionIfRequested(CodePipelineExecution execution, ActionExecution state) {+ if (!execution.isStopRequested() || !execution.isAbandon()) {+ return false;}+ state.setStatus("Abandoned");+ state.setSummary("Action abandoned.");+ return true;+ }++ private boolean recordExternalActionFailureWhileStopping(CodePipelineExecution execution,+ ActionExecution state, String message) {+ if (!execution.isStopRequested()) {+ return false;+ }+ state.setStatus("Failed");+ state.setSummary(message);+ state.setErrorDetails(Map.of("code", "ActionExecutionFailed", "message", message));+ return true;}private void executeLambda(CodePipelineExecution execution, JsonNode action, ActionExecution state) {diff --git a/src/main/java/io/github/hectorvent/floci/services/codepipeline/model/CodePipelineExecution.java b/src/main/java/io/github/hectorvent/floci/services/codepipeline/model/CodePipelineExecution.javaindex 8c9441b753..c489557f4d 100644--- a/src/main/java/io/github/hectorvent/floci/services/codepipeline/model/CodePipelineExecution.java+++ b/src/main/java/io/github/hectorvent/floci/services/codepipeline/model/CodePipelineExecution.java@@ -32,8 +32,8 @@ public class CodePipelineExecution {private List<ActionExecution> actionExecutions = new ArrayList<>();private Map<String, String> stageExecutionStatuses = new LinkedHashMap<>();private String currentStage;- private boolean stopRequested;- private boolean abandon;+ private volatile boolean stopRequested;+ private volatile boolean abandon;private String rollbackTargetPipelineExecutionId;public String getAccountId() {diff --git a/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineServiceTest.javaindex 3cf3fa8722..db4c8aeef4 100644--- a/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineServiceTest.java@@ -7,7 +7,9 @@ import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.codebuild.CodeBuildService;+import io.github.hectorvent.floci.services.codebuild.model.Build;import io.github.hectorvent.floci.services.codedeploy.CodeDeployService;+import io.github.hectorvent.floci.services.codedeploy.model.Deployment;import io.github.hectorvent.floci.services.codepipeline.model.CodePipelinePipeline;import io.github.hectorvent.floci.services.lambda.LambdaService;import io.github.hectorvent.floci.services.s3.S3Service;@@ -19,12 +21,17 @@ import java.util.concurrent.CompletableFuture;import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;+import java.util.concurrent.atomic.AtomicReference;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;class CodePipelineServiceTest {@@ -170,6 +177,169 @@ class CodePipelineServiceTest {}}+ @Test+ void stoppingCodeBuildWaitsForSuccessWithoutStoppingTheBuild() throws Exception {+ CodeBuildService codeBuildService = mock(CodeBuildService.class);+ AtomicReference<Build> currentBuild = new AtomicReference<>(build("IN_PROGRESS", false));+ CountDownLatch buildStarted = new CountDownLatch(1);+ when(codeBuildService.startBuild(anyString(), anyString(), anyString(),+ any(), any(), any(), any(), any(), any(), any())).thenAnswer(invocation -> {+ buildStarted.countDown();+ return currentBuild.get();+ });+ when(codeBuildService.getBuild(anyString(), anyString(), anyString()))+ .thenAnswer(invocation -> currentBuild.get());+ CodePipelineService pipelineService = serviceWith(codeBuildService, mock(CodeDeployService.class));+ String pipelineName = "codebuild-stop-wait";++ try {+ createExternalActionPipeline(pipelineService, pipelineName, """+ {+ "name": "BuildAction",+ "actionTypeId": {+ "category": "Build",+ "owner": "AWS",+ "provider": "CodeBuild",+ "version": "1"+ },+ "configuration": {"ProjectName": "build-project"}+ }+ """);+ String executionId = startExecution(pipelineService, pipelineName);+ assertTrue(buildStarted.await(2, TimeUnit.SECONDS));++ stopExecution(pipelineService, pipelineName, executionId, false);+ waitForExecutionStatus(pipelineService, pipelineName, executionId, "Stopping");+ currentBuild.set(build("SUCCEEDED", true));++ waitForExecutionStatus(pipelineService, pipelineName, executionId, "Stopped");+ JsonNode state = pipelineState(pipelineService, pipelineName);+ assertEquals("Stopped", state.path("stageStates").path(0)+ .path("latestExecution").path("status").asText());+ assertEquals("Succeeded", state.path("stageStates").path(0).path("actionStates").path(0)+ .path("latestExecution").path("status").asText());+ verify(codeBuildService, never()).stopBuild(anyString(), anyString(), anyString());+ } finally {+ pipelineService.shutdown();+ }+ }++ @Test+ void stoppingCodeDeployWaitsForFailureWithoutFailingThePipeline() throws Exception {+ CodeDeployService codeDeployService = mock(CodeDeployService.class);+ AtomicReference<Deployment> currentDeployment = new AtomicReference<>(deployment("InProgress"));+ CountDownLatch deploymentStarted = new CountDownLatch(1);+ when(codeDeployService.createDeployment(anyString(), anyString(), anyString(),+ any(), any(), anyString())).thenAnswer(invocation -> {+ deploymentStarted.countDown();+ return "deployment-1";+ });+ when(codeDeployService.getDeployment(anyString(), anyString()))+ .thenAnswer(invocation -> currentDeployment.get());+ CodePipelineService pipelineService = serviceWith(mock(CodeBuildService.class), codeDeployService);+ String pipelineName = "codedeploy-stop-wait";++ try {+ createExternalActionPipeline(pipelineService, pipelineName, """+ {+ "name": "DeployAction",+ "actionTypeId": {+ "category": "Deploy",+ "owner": "AWS",+ "provider": "CodeDeploy",+ "version": "1"+ },+ "configuration": {+ "ApplicationName": "application",+ "DeploymentGroupName": "deployment-group"+ }+ }+ """);+ String executionId = startExecution(pipelineService, pipelineName);+ assertTrue(deploymentStarted.await(2, TimeUnit.SECONDS));++ stopExecution(pipelineService, pipelineName, executionId, false);+ waitForExecutionStatus(pipelineService, pipelineName, executionId, "Stopping");+ currentDeployment.set(deployment("Failed"));++ waitForExecutionStatus(pipelineService, pipelineName, executionId, "Stopped");+ JsonNode state = pipelineState(pipelineService, pipelineName);+ assertEquals("Failed", state.path("stageStates").path(0)+ .path("latestExecution").path("status").asText());+ assertEquals("Failed", state.path("stageStates").path(0).path("actionStates").path(0)+ .path("latestExecution").path("status").asText());+ verify(codeDeployService, never()).stopDeployment(anyString(), anyString());+ } finally {+ pipelineService.shutdown();+ }+ }++ @Test+ void abandoningExternalActionsStopsWaitingWithoutStoppingThem() throws Exception {+ CodeBuildService codeBuildService = mock(CodeBuildService.class);+ CodeDeployService codeDeployService = mock(CodeDeployService.class);+ CountDownLatch actionsStarted = new CountDownLatch(2);+ Build runningBuild = build("IN_PROGRESS", false);+ Deployment runningDeployment = deployment("InProgress");+ when(codeBuildService.startBuild(anyString(), anyString(), anyString(),+ any(), any(), any(), any(), any(), any(), any())).thenAnswer(invocation -> {+ actionsStarted.countDown();+ return runningBuild;+ });+ when(codeBuildService.getBuild(anyString(), anyString(), anyString())).thenReturn(runningBuild);+ when(codeDeployService.createDeployment(anyString(), anyString(), anyString(),+ any(), any(), anyString())).thenAnswer(invocation -> {+ actionsStarted.countDown();+ return "deployment-1";+ });+ when(codeDeployService.getDeployment(anyString(), anyString())).thenReturn(runningDeployment);+ CodePipelineService pipelineService = serviceWith(codeBuildService, codeDeployService);+ String pipelineName = "external-actions-abandon";++ try {+ createExternalActionPipeline(pipelineService, pipelineName, """+ {+ "name": "BuildAction",+ "actionTypeId": {+ "category": "Build",+ "owner": "AWS",+ "provider": "CodeBuild",+ "version": "1"+ },+ "configuration": {"ProjectName": "build-project"}+ },+ {+ "name": "DeployAction",+ "actionTypeId": {+ "category": "Deploy",+ "owner": "AWS",+ "provider": "CodeDeploy",+ "version": "1"+ },+ "configuration": {+ "ApplicationName": "application",+ "DeploymentGroupName": "deployment-group"+ }+ }+ """);+ String executionId = startExecution(pipelineService, pipelineName);+ assertTrue(actionsStarted.await(2, TimeUnit.SECONDS));++ stopExecution(pipelineService, pipelineName, executionId, true);++ waitForExecutionStatus(pipelineService, pipelineName, executionId, "Stopped");+ JsonNode state = pipelineState(pipelineService, pipelineName);+ assertEquals("Abandoned", state.path("stageStates").path(0).path("actionStates").path(0)+ .path("latestExecution").path("status").asText());+ assertEquals("Abandoned", state.path("stageStates").path(0).path("actionStates").path(1)+ .path("latestExecution").path("status").asText());+ verify(codeBuildService, never()).stopBuild(anyString(), anyString(), anyString());+ verify(codeDeployService, never()).stopDeployment(anyString(), anyString());+ } finally {+ pipelineService.shutdown();+ }+ }+@Testvoid aStartAfterShutdownIsRefusedAndTheExecutionIsPersistedAsFailed() throws Exception {handle("CreatePipeline", """@@ -221,6 +391,100 @@ class CodePipelineServiceTest {return service.handle(action, mapper.readTree(body), REGION, ACCOUNT);}+ private CodePipelineService serviceWith(CodeBuildService codeBuildService,+ CodeDeployService codeDeployService) {+ return new CodePipelineService(+ new InMemoryStorageFactory(), mapper, codeBuildService, codeDeployService,+ mock(LambdaService.class), mock(S3Service.class));+ }++ private void createExternalActionPipeline(CodePipelineService pipelineService,+ String pipelineName, String actions) throws Exception {+ handle(pipelineService, "CreatePipeline", """+ {+ "pipeline": {+ "name": "%s",+ "roleArn": "arn:aws:iam::000000000000:role/codepipeline-role",+ "artifactStore": {"type": "S3", "location": "codepipeline-artifacts"},+ "stages": [{+ "name": "External",+ "actions": [%s]+ }, {+ "name": "Complete",+ "actions": [{+ "name": "ManualApproval",+ "actionTypeId": {+ "category": "Approval",+ "owner": "AWS",+ "provider": "Manual",+ "version": "1"+ }+ }]+ }]+ }+ }+ """.formatted(pipelineName, actions));+ }++ private String startExecution(CodePipelineService pipelineService, String pipelineName) throws Exception {+ return handle(pipelineService, "StartPipelineExecution", """+ {"name": "%s"}+ """.formatted(pipelineName)).path("pipelineExecutionId").asText();+ }++ private void stopExecution(CodePipelineService pipelineService, String pipelineName,+ String executionId, boolean abandon) throws Exception {+ handle(pipelineService, "StopPipelineExecution", """+ {+ "pipelineName": "%s",+ "pipelineExecutionId": "%s",+ "abandon": %s+ }+ """.formatted(pipelineName, executionId, abandon));+ }++ private JsonNode waitForExecutionStatus(CodePipelineService pipelineService, String pipelineName,+ String executionId, String expectedStatus) throws Exception {+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);+ JsonNode execution;+ do {+ execution = handle(pipelineService, "GetPipelineExecution", """+ {"pipelineName": "%s", "pipelineExecutionId": "%s"}+ """.formatted(pipelineName, executionId)).path("pipelineExecution");+ if (expectedStatus.equals(execution.path("status").asText())) {+ return execution;+ }+ Thread.sleep(25);+ } while (System.nanoTime() < deadline);+ throw new AssertionError("Pipeline did not reach " + expectedStatus+ + "; last status was " + execution.path("status").asText());+ }++ private JsonNode pipelineState(CodePipelineService pipelineService, String pipelineName) throws Exception {+ return handle(pipelineService, "GetPipelineState", """+ {"name": "%s"}+ """.formatted(pipelineName));+ }++ private JsonNode handle(CodePipelineService pipelineService, String action, String body) throws Exception {+ return pipelineService.handle(action, mapper.readTree(body), REGION, ACCOUNT);+ }++ private Build build(String status, boolean complete) {+ Build build = new Build();+ build.setId("build-1");+ build.setBuildStatus(status);+ build.setBuildComplete(complete);+ return build;+ }++ private Deployment deployment(String status) {+ Deployment deployment = new Deployment();+ deployment.setDeploymentId("deployment-1");+ deployment.setStatus(status);+ return deployment;+ }+private static final class InMemoryStorageFactory extends StorageFactory {private InMemoryStorageFactory() {super(null, null);