Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(codepipeline): retry failed stages in place (#3513)

Franklin G. Mendoza196d1586daf0
diff --git a/docs/services/codepipeline.md b/docs/services/codepipeline.md
index d306809cab..1cdd6af52c 100644
--- a/docs/services/codepipeline.md
+++ b/docs/services/codepipeline.md
@@ -30,6 +30,15 @@ omitted or set to `true`. Floci establishes a baseline for the configured object
execution when its version ID or ETag changes, recording `PollForSourceChanges` as the execution
trigger. Set `PollForSourceChanges` to `false` to disable this polling path.
+`RetryStageExecution` resumes the same pipeline execution at a failed stage. `FAILED_ACTIONS`
+reruns failed or not-yet-started actions while preserving successful actions; `ALL_ACTIONS` reruns
+the complete stage. Runtime artifacts from failed executions are retained for the retry until a newer
+execution fails the same stage, and a successful retry continues with the stages that follow rather
+than restarting from the source.
+A retried execution counts toward the `QUEUED`/`PARALLEL` active-execution limit, and a second retry of
+the same execution while it is still running, including while sibling actions of a failed action
+finish, returns `ConflictException`.
+
The following providers execute against local Floci services:
| Category | Provider | Behavior |
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.java
index 51aab941fe..94d7f58f2e 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
@@ -77,6 +77,9 @@ public class CodePipelineService {
// until the running execution finished.
private final KeyedLockPool startLocks = new KeyedLockPool();
private final Map<String, byte[]> runtimeArtifacts = new ConcurrentHashMap<>();
+ // An execution's status turns Failed as soon as one action fails, while its runner is still waiting
+ // on sibling actions. Retries check this set so they never overlap a runner that has not finished.
+ private final Set<String> activeRuns = ConcurrentHashMap.newKeySet();
@Inject
@SuppressWarnings("unchecked")
@@ -404,6 +407,7 @@ public class CodePipelineService {
pipelineStore.deleteForAccount(account, pipelineKey(region, name));
for (String key : executionStore.keysForAccount(account)) {
if (key.startsWith(region + ":" + name + ":")) {
+ executionStore.getForAccount(account, key).ifPresent(this::clearRuntimeArtifacts);
executionStore.deleteForAccount(account, key);
}
}
@@ -496,12 +500,7 @@ public class CodePipelineService {
return true;
}
return startLocks.withLock(lockKey(execution), () -> {
- long active = executions(execution.getAccountId(), execution.getRegion(), execution.getPipelineName())
- .stream()
- .filter(candidate -> "InProgress".equals(candidate.getStatus())
- || "Stopping".equals(candidate.getStatus()))
- .count();
- if (active >= MAX_ACTIVE_EXECUTIONS) {
+ if (activeExecutionCount(execution) >= MAX_ACTIVE_EXECUTIONS) {
return false;
}
putExecution(execution);
@@ -509,6 +508,13 @@ public class CodePipelineService {
});
}
+ private long activeExecutionCount(CodePipelineExecution execution) {
+ return executions(execution.getAccountId(), execution.getRegion(), execution.getPipelineName()).stream()
+ .filter(candidate -> "InProgress".equals(candidate.getStatus())
+ || "Stopping".equals(candidate.getStatus()))
+ .count();
+ }
+
private ObjectNode stopPipelineExecution(JsonNode request, String region, String account) {
CodePipelineExecution execution = requireExecution(
account, region, text(request, "pipelineName"), text(request, "pipelineExecutionId"));
@@ -571,8 +577,9 @@ public class CodePipelineService {
"succeededInStage requires stageName", 400);
}
String stage = stageNameNode.asText();
- executions = executions.stream().filter(e -> actionExecutionsForStage(e, stage).stream()
- .allMatch(a -> "Succeeded".equals(a.getStatus()))).toList();
+ executions = executions.stream()
+ .filter(e -> "Succeeded".equals(stageExecutionStatus(e, stage)))
+ .toList();
}
if (request.hasNonNull("maxResults")) {
JsonNode maxResultsNode = request.get("maxResults");
@@ -636,10 +643,10 @@ public class CodePipelineService {
String actionName = action.path("name").asText();
actionState.put("actionName", actionName);
if (latest != null) {
- latest.getActionExecutions().stream()
- .filter(a -> stageName.equals(a.getStageName()) && actionName.equals(a.getActionName()))
- .findFirst()
- .ifPresent(a -> actionState.set("latestExecution", actionStateNode(a)));
+ ActionExecution latestAction = latestActionExecution(latest, stageName, actionName);
+ if (latestAction != null) {
+ actionState.set("latestExecution", actionStateNode(latestAction));
+ }
}
}
CodePipelineExecution latestStageExecution = pipelineExecutions.stream()
@@ -743,10 +750,88 @@ public class CodePipelineService {
private ObjectNode retryStageExecution(JsonNode request, String region, String account) {
String pipelineName = text(request, "pipelineName");
- CodePipelineExecution source = requireExecution(
- account, region, pipelineName, text(request, "pipelineExecutionId"));
+ String stageName = text(request, "stageName");
+ String executionId = text(request, "pipelineExecutionId");
+ String retryMode = text(request, "retryMode");
+ if (!List.of("FAILED_ACTIONS", "ALL_ACTIONS").contains(retryMode)) {
+ throw new AwsException("ValidationException",
+ "retryMode must be one of [FAILED_ACTIONS, ALL_ACTIONS]", 400);
+ }
+
+ CodePipelinePipeline pipeline = requirePipeline(account, region, pipelineName);
+ JsonNode stage = stageByName(pipeline, stageName);
+ CodePipelineExecution execution = requireExecution(account, region, pipelineName, executionId);
+ Map<String, String> latestStatuses = startLocks.withLock(lockKey(execution),
+ () -> admitRetry(pipeline, execution, stageName, retryMode));
+ try {
+ executor.submit(() -> runRetriedStage(pipeline, execution, stage, retryMode, latestStatuses));
+ } catch (RejectedExecutionException exception) {
+ activeRuns.remove(runKey(execution));
+ execution.setStatus("Failed");
+ execution.setStatusSummary("Stage retry could not be scheduled.");
+ execution.setLastUpdateTime(now());
+ putExecution(execution);
+ throw new AwsException("ConflictException",
+ "Your request cannot be handled because the pipeline is busy handling ongoing activities. "
+ + "Try again later.", 400);
+ }
+ return mapper.createObjectNode().put("pipelineExecutionId", executionId);
+ }
+
+ // Runs under startLocks so two concurrent retries cannot both pass the status checks,
+ // and so a retry counts against the same active-execution cap StartPipelineExecution enforces.
+ private Map<String, String> admitRetry(CodePipelinePipeline pipeline, CodePipelineExecution execution,
+ String stageName, String retryMode) {
+ String executionId = execution.getPipelineExecutionId();
+ boolean laterFailureInStage = executions(execution.getAccountId(), execution.getRegion(),
+ execution.getPipelineName()).stream()
+ .takeWhile(candidate -> !executionId.equals(candidate.getPipelineExecutionId()))
+ .map(candidate -> latestActionStatuses(candidate, stageName))
+ .anyMatch(statuses -> statuses.values().stream().anyMatch("Failed"::equals));
+ if (laterFailureInStage) {
+ throw new AwsException("NotLatestPipelineExecutionException",
+ "A later pipeline execution has failed in stage " + stageName, 400);
+ }
+ if (!Objects.equals(execution.getPipelineVersion(), pipeline.getVersion())) {
+ throw new AwsException("StageNotRetryableException",
+ "The pipeline structure changed after this execution started", 400);
+ }
+ if ("InProgress".equals(execution.getStatus()) || "Stopping".equals(execution.getStatus())
+ || activeRuns.contains(runKey(execution))) {
+ throw new AwsException("ConflictException", "Pipeline execution is still in progress", 400);
+ }
+ Map<String, String> latestStatuses = latestActionStatuses(execution, stageName);
+ boolean hasFailedAction = latestStatuses.values().stream().anyMatch("Failed"::equals);
+ boolean stoppedStageRetry = "Stopped".equals(execution.getStatus())
+ && "ALL_ACTIONS".equals(retryMode)
+ && "Stopped".equals(execution.getStageExecutionStatuses().get(stageName));
+ if (!hasFailedAction && !stoppedStageRetry) {
+ throw new AwsException("StageNotRetryableException",
+ "The stage contains no retryable actions", 400);
+ }
+ if (execution.isArtifactsReleased()) {
+ throw new AwsException("StageNotRetryableException",
+ "The artifacts this stage consumes are no longer retained for this execution", 400);
+ }
+ if (List.of("QUEUED", "PARALLEL").contains(execution.getExecutionMode())
+ && activeExecutionCount(execution) >= MAX_ACTIVE_EXECUTIONS) {
+ throw new AwsException("ConcurrentPipelineExecutionsLimitExceededException",
+ "The pipeline has reached the limit for concurrent pipeline executions", 400);
+ }
+
+ execution.setStatus("InProgress");
+ execution.setStatusSummary("Retrying stage " + stageName + ".");
+ execution.setStopRequested(false);
+ execution.setAbandon(false);
+ execution.setLastUpdateTime(now());
+ putExecution(execution);
+ activeRuns.add(runKey(execution));
+ return latestStatuses;
+ }
+
+ private ObjectNode startExecutionFrom(CodePipelineExecution source, String region, String account) {
ObjectNode start = mapper.createObjectNode();
- start.put("name", pipelineName);
+ start.put("name", source.getPipelineName());
start.set("sourceRevisions", mapper.valueToTree(source.getSourceRevisions()));
ArrayNode vars = start.putArray("variables");
source.getVariables().forEach(v -> vars.addObject()
@@ -758,9 +843,7 @@ public class CodePipelineService {
private ObjectNode rollbackStage(JsonNode request, String region, String account) {
CodePipelineExecution target = requireExecution(
account, region, text(request, "pipelineName"), text(request, "targetPipelineExecutionId"));
- ObjectNode started = retryStageExecution(mapper.createObjectNode()
- .put("pipelineName", target.getPipelineName())
- .put("pipelineExecutionId", target.getPipelineExecutionId()), region, account);
+ ObjectNode started = startExecutionFrom(target, region, account);
CodePipelineExecution rollback = requireExecution(
account, region, target.getPipelineName(), started.path("pipelineExecutionId").asText());
rollback.setExecutionType("ROLLBACK");
@@ -974,33 +1057,10 @@ public class CodePipelineService {
}
private void runExecution(CodePipelinePipeline pipeline, CodePipelineExecution execution) {
+ activeRuns.add(runKey(execution));
Runnable work = () -> {
try {
- for (JsonNode stage : pipeline.getDeclaration().path("stages")) {
- waitForTransition(pipeline, execution, stage.path("name").asText());
- if (finishIfStopped(execution)) {
- return;
- }
- String stageName = stage.path("name").asText();
- execution.setCurrentStage(stageName);
- execution.getStageExecutionStatuses().put(stageName, "InProgress");
- execution.setLastUpdateTime(now());
- putExecution(execution);
- runStage(pipeline, execution, stage);
- if ("Failed".equals(execution.getStatus())) {
- execution.getStageExecutionStatuses().put(stageName, "Failed");
- return;
- }
- if (finishIfStopped(execution)) {
- return;
- }
- execution.getStageExecutionStatuses().put(stageName, "Succeeded");
- execution.setCurrentStage(null);
- execution.setLastUpdateTime(now());
- putExecution(execution);
- }
- execution.setStatus("Succeeded");
- execution.setStatusSummary("Pipeline execution succeeded.");
+ runStagesFrom(pipeline, execution, 0);
} catch (Exception e) {
if (execution.getCurrentStage() != null) {
execution.getStageExecutionStatuses().put(execution.getCurrentStage(), "Failed");
@@ -1009,12 +1069,13 @@ public class CodePipelineService {
execution.setStatusSummary(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage());
LOG.errorf(e, "CodePipeline execution %s failed", execution.getPipelineExecutionId());
} finally {
- execution.setCurrentStage(null);
- execution.setLastUpdateTime(now());
- putExecution(execution);
- clearRuntimeArtifacts(execution);
+ finishExecutionRun(execution);
}
};
+ runInExecutionMode(execution, work);
+ }
+
+ private void runInExecutionMode(CodePipelineExecution execution, Runnable work) {
if ("QUEUED".equals(execution.getExecutionMode())) {
pipelineLocks.withLock(lockKey(execution), work);
} else {
@@ -1022,7 +1083,142 @@ public class CodePipelineService {
}
}
+ private void runRetriedStage(CodePipelinePipeline pipeline, CodePipelineExecution execution, JsonNode stage,
+ String retryMode, Map<String, String> previousStatuses) {
+ runInExecutionMode(execution, () -> runRetriedStageNow(pipeline, execution, stage, retryMode,
+ previousStatuses));
+ }
+
+ private void runRetriedStageNow(CodePipelinePipeline pipeline, CodePipelineExecution execution, JsonNode stage,
+ String retryMode, Map<String, String> previousStatuses) {
+ String stageName = stage.path("name").asText();
+ try {
+ int stageIndex = stageIndex(pipeline, stageName);
+ execution.setCurrentStage(stageName);
+ execution.getStageExecutionStatuses().put(stageName, "InProgress");
+ execution.setLastUpdateTime(now());
+ putExecution(execution);
+ runStage(pipeline, execution, stage, retryMode, previousStatuses);
+ if ("Failed".equals(execution.getStatus())) {
+ execution.getStageExecutionStatuses().put(stageName, "Failed");
+ return;
+ }
+ if (finishIfStopped(execution)) {
+ return;
+ }
+ execution.getStageExecutionStatuses().put(stageName, "Succeeded");
+ execution.setCurrentStage(null);
+ execution.setLastUpdateTime(now());
+ putExecution(execution);
+ runStagesFrom(pipeline, execution, stageIndex + 1);
+ } catch (Exception e) {
+ if (execution.getCurrentStage() != null) {
+ execution.getStageExecutionStatuses().put(execution.getCurrentStage(), "Failed");
+ }
+ execution.setStatus("Failed");
+ execution.setStatusSummary(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage());
+ LOG.errorf(e, "CodePipeline retry for execution %s failed", execution.getPipelineExecutionId());
+ } finally {
+ finishExecutionRun(execution);
+ }
+ }
+
+ private void runStagesFrom(CodePipelinePipeline pipeline, CodePipelineExecution execution, int startIndex)
+ throws InterruptedException {
+ JsonNode stages = pipeline.getDeclaration().path("stages");
+ for (int i = startIndex; i < stages.size(); i++) {
+ JsonNode stage = stages.get(i);
+ String stageName = stage.path("name").asText();
+ waitForTransition(pipeline, execution, stageName);
+ if (finishIfStopped(execution)) {
+ return;
+ }
+ execution.setCurrentStage(stageName);
+ execution.getStageExecutionStatuses().put(stageName, "InProgress");
+ execution.setLastUpdateTime(now());
+ putExecution(execution);
+ runStage(pipeline, execution, stage);
+ if ("Failed".equals(execution.getStatus())) {
+ execution.getStageExecutionStatuses().put(stageName, "Failed");
+ return;
+ }
+ if (finishIfStopped(execution)) {
+ return;
+ }
+ execution.getStageExecutionStatuses().put(stageName, "Succeeded");
+ execution.setCurrentStage(null);
+ execution.setLastUpdateTime(now());
+ putExecution(execution);
+ }
+ execution.setStatus("Succeeded");
+ execution.setStatusSummary("Pipeline execution succeeded.");
+ }
+
+ private void finishExecutionRun(CodePipelineExecution execution) {
+ startLocks.withLock(lockKey(execution), () -> {
+ try {
+ execution.setCurrentStage(null);
+ execution.setLastUpdateTime(now());
+ putExecution(execution);
+ boolean pipelineDeleted = pipelineStore.getForAccount(execution.getAccountId(),
+ pipelineKey(execution.getRegion(), execution.getPipelineName())).isEmpty();
+ if (pipelineDeleted) {
+ clearRuntimeArtifacts(execution);
+ } else if ("Failed".equals(execution.getStatus()) || "Stopped".equals(execution.getStatus())) {
+ if ("Failed".equals(execution.getStatus())) {
+ releaseArtifactsOutdatedBy(execution);
+ }
+ releaseArtifactsIfAlreadyOutdated(execution);
+ } else {
+ clearRuntimeArtifacts(execution);
+ }
+ } finally {
+ activeRuns.remove(runKey(execution));
+ }
+ });
+ }
+
+ // Failed and stopped executions keep their artifacts so a stage retry can reuse them. Once a newer
+ // execution fails the same stage, the older one can no longer be retried there, so its artifacts go.
+ // An older execution whose runner is still finishing is skipped here and releases itself when it ends.
+ private void releaseArtifactsOutdatedBy(CodePipelineExecution failed) {
+ executions(failed.getAccountId(), failed.getRegion(), failed.getPipelineName()).stream()
+ .dropWhile(candidate -> !failed.getPipelineExecutionId().equals(candidate.getPipelineExecutionId()))
+ .skip(1)
+ .filter(older -> "Failed".equals(older.getStatus()) || "Stopped".equals(older.getStatus()))
+ .filter(older -> !older.isArtifactsReleased() && !activeRuns.contains(runKey(older)))
+ .filter(older -> outdatedBy(older, failed))
+ .forEach(this::releaseArtifacts);
+ }
+
+ private void releaseArtifactsIfAlreadyOutdated(CodePipelineExecution execution) {
+ boolean outdated = executions(execution.getAccountId(), execution.getRegion(), execution.getPipelineName())
+ .stream()
+ .takeWhile(candidate -> !execution.getPipelineExecutionId().equals(candidate.getPipelineExecutionId()))
+ .anyMatch(newer -> outdatedBy(execution, newer));
+ if (outdated) {
+ releaseArtifacts(execution);
+ }
+ }
+
+ private boolean outdatedBy(CodePipelineExecution older, CodePipelineExecution newer) {
+ return older.getStageExecutionStatuses().entrySet().stream()
+ .filter(entry -> "Failed".equals(entry.getValue()) || "Stopped".equals(entry.getValue()))
+ .anyMatch(entry -> latestActionStatuses(newer, entry.getKey()).containsValue("Failed"));
+ }
+
+ private void releaseArtifacts(CodePipelineExecution execution) {
+ clearRuntimeArtifacts(execution);
+ execution.setArtifactsReleased(true);
+ putExecution(execution);
+ }
+
private void runStage(CodePipelinePipeline pipeline, CodePipelineExecution execution, JsonNode stage) {
+ runStage(pipeline, execution, stage, "ALL_ACTIONS", Map.of());
+ }
+
+ private void runStage(CodePipelinePipeline pipeline, CodePipelineExecution execution, JsonNode stage,
+ String retryMode, Map<String, String> previousStatuses) {
Map<Integer, List<JsonNode>> groups = new LinkedHashMap<>();
for (JsonNode action : stage.path("actions")) {
groups.computeIfAbsent(action.path("runOrder").asInt(1), ignored -> new ArrayList<>()).add(action);
@@ -1031,7 +1227,10 @@ public class CodePipelineService {
if ("Failed".equals(execution.getStatus()) || execution.isStopRequested()) {
return;
}
- List<CompletableFuture<Void>> futures = entry.getValue().stream()
+ List<JsonNode> actions = entry.getValue().stream()
+ .filter(action -> shouldRunRetriedAction(action, retryMode, previousStatuses))
+ .toList();
+ List<CompletableFuture<Void>> futures = actions.stream()
.map(action -> CompletableFuture.runAsync(
() -> runAction(pipeline, execution, stage.path("name").asText(), action), executor))
.toList();
@@ -1042,6 +1241,13 @@ public class CodePipelineService {
});
}
+ private boolean shouldRunRetriedAction(JsonNode action, String retryMode, Map<String, String> previousStatuses) {
+ if ("ALL_ACTIONS".equals(retryMode)) {
+ return true;
+ }
+ return !"Succeeded".equals(previousStatuses.get(action.path("name").asText()));
+ }
+
private void runAction(CodePipelinePipeline pipeline, CodePipelineExecution execution,
String stageName, JsonNode action) {
ActionExecution state = new ActionExecution();
@@ -1493,15 +1699,54 @@ public class CodePipelineService {
});
}
- private void requireStage(CodePipelinePipeline pipeline, String stageName) {
+ private JsonNode stageByName(CodePipelinePipeline pipeline, String stageName) {
for (JsonNode stage : pipeline.getDeclaration().path("stages")) {
if (stageName.equals(stage.path("name").asText())) {
- return;
+ return stage;
+ }
+ }
+ throw new AwsException("StageNotFoundException", "Stage not found: " + stageName, 400);
+ }
+
+ private int stageIndex(CodePipelinePipeline pipeline, String stageName) {
+ JsonNode stages = pipeline.getDeclaration().path("stages");
+ for (int i = 0; i < stages.size(); i++) {
+ if (stageName.equals(stages.get(i).path("name").asText())) {
+ return i;
}
}
throw new AwsException("StageNotFoundException", "Stage not found: " + stageName, 400);
}
+ private Map<String, String> latestActionStatuses(CodePipelineExecution execution, String stageName) {
+ Map<String, String> statuses = new LinkedHashMap<>();
+ synchronized (execution) {
+ for (ActionExecution action : execution.getActionExecutions()) {
+ if (stageName.equals(action.getStageName())) {
+ statuses.put(action.getActionName(), action.getStatus());
+ }
+ }
+ }
+ return statuses;
+ }
+
+ private ActionExecution latestActionExecution(CodePipelineExecution execution, String stageName,
+ String actionName) {
+ ActionExecution latest = null;
+ synchronized (execution) {
+ for (ActionExecution action : execution.getActionExecutions()) {
+ if (stageName.equals(action.getStageName()) && actionName.equals(action.getActionName())) {
+ latest = action;
+ }
+ }
+ }
+ return latest;
+ }
+
+ private void requireStage(CodePipelinePipeline pipeline, String stageName) {
+ stageByName(pipeline, stageName);
+ }
+
private void requireAction(CodePipelinePipeline pipeline, String stageName, String actionName) {
for (JsonNode stage : pipeline.getDeclaration().path("stages")) {
if (stageName.equals(stage.path("name").asText())) {
@@ -1520,7 +1765,7 @@ public class CodePipelineService {
ObjectNode node = mapper.valueToTree(execution);
node.remove(List.of("accountId", "region", "startTime", "lastUpdateTime",
"sourceRevisions", "actionExecutions", "currentStage", "stopRequested", "abandon",
- "rollbackTargetPipelineExecutionId"));
+ "rollbackTargetPipelineExecutionId", "stageExecutionStatuses", "artifactsReleased"));
if (execution.getRollbackTargetPipelineExecutionId() != null) {
node.putObject("rollbackMetadata").put(
"rollbackTargetPipelineExecutionId", execution.getRollbackTargetPipelineExecutionId());
@@ -1611,7 +1856,7 @@ public class CodePipelineService {
private String stageExecutionStatus(CodePipelineExecution execution, String stage) {
List<ActionExecution> actions = actionExecutionsForStage(execution, stage);
- if (actions.stream().anyMatch(action -> "Failed".equals(action.getStatus()))) {
+ if (latestActionStatuses(execution, stage).containsValue("Failed")) {
return "Failed";
}
String trackedStatus = execution.getStageExecutionStatuses().get(stage);
@@ -1736,6 +1981,10 @@ public class CodePipelineService {
return action.path("configuration").path("BucketName").asText("codepipeline-artifacts");
}
+ private static String runKey(CodePipelineExecution execution) {
+ return execution.getAccountId() + ":" + execution.getPipelineExecutionId();
+ }
+
private void clearRuntimeArtifacts(CodePipelineExecution execution) {
String prefix = execution.getAccountId() + ":" + execution.getPipelineExecutionId() + ":";
runtimeArtifacts.keySet().removeIf(key -> key.startsWith(prefix));
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.java
index c489557f4d..8809b37c57 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
@@ -34,6 +34,7 @@ public class CodePipelineExecution {
private String currentStage;
private volatile boolean stopRequested;
private volatile boolean abandon;
+ private volatile boolean artifactsReleased;
private String rollbackTargetPipelineExecutionId;
public String getAccountId() {
@@ -197,6 +198,14 @@ public class CodePipelineExecution {
this.abandon = abandon;
}
+ public boolean isArtifactsReleased() {
+ return artifactsReleased;
+ }
+
+ public void setArtifactsReleased(boolean artifactsReleased) {
+ this.artifactsReleased = artifactsReleased;
+ }
+
public String getRollbackTargetPipelineExecutionId() {
return rollbackTargetPipelineExecutionId;
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineIntegrationTest.java
index 0b6493c821..0782fe9a23 100644
--- a/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineIntegrationTest.java
@@ -10,9 +10,17 @@ import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.given;
+import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
@@ -544,6 +552,597 @@ class CodePipelineIntegrationTest {
""".formatted(pipelineName)).then().statusCode(200);
}
+ @Test
+ void retryStageExecutionReusesExecutionAndRetainedArtifacts() throws Exception {
+ createBucket("retry-stage-source");
+ createBucket("retry-stage-success");
+ putObject("retry-stage-source", "source.zip", "retry artifact");
+
+ String pipelineName = "retry-stage-pipeline";
+ post("CreatePipeline", pipeline(pipelineName, """
+ {
+ "name": "Source",
+ "actions": [{
+ "name": "SourceObject",
+ "actionTypeId": {
+ "category": "Source",
+ "owner": "AWS",
+ "provider": "S3",
+ "version": "1"
+ },
+ "configuration": {
+ "S3Bucket": "retry-stage-source",
+ "S3ObjectKey": "source.zip"
+ },
+ "outputArtifacts": [{"name": "SourceOutput"}],
+ "runOrder": 1
+ }]
+ },
+ {
+ "name": "Deploy",
+ "actions": [{
+ "name": "SuccessfulDeploy",
+ "actionTypeId": {
+ "category": "Deploy",
+ "owner": "AWS",
+ "provider": "S3",
+ "version": "1"
+ },
+ "configuration": {
+ "BucketName": "retry-stage-success",
+ "ObjectKey": "successful.zip"
+ },
+ "inputArtifacts": [{"name": "SourceOutput"}],
+ "runOrder": 1
+ }, {
+ "name": "FailedDeploy",
+ "actionTypeId": {
+ "category": "Deploy",
+ "owner": "AWS",
+ "provider": "S3",
+ "version": "1"
+ },
+ "configuration": {
+ "BucketName": "retry-stage-destination",
+ "ObjectKey": "deployed.zip"
+ },
+ "inputArtifacts": [{"name": "SourceOutput"}],
+ "runOrder": 1
+ }]
+ }
+ """))
+ .then()
+ .statusCode(200);
+
+ String executionId = post("StartPipelineExecution", """
+ {"name": "%s"}
+ """.formatted(pipelineName))
+ .then()
+ .statusCode(200)
+ .extract().path("pipelineExecutionId");
+
+ waitForExecution(pipelineName, executionId, "Failed");
+
+ post("ListActionExecutions", """
+ {
+ "pipelineName": "%s",
+ "filter": {"pipelineExecutionId": "%s"}
+ }
+ """.formatted(pipelineName, executionId))
+ .then()
+ .statusCode(200)
+ .body("actionExecutionDetails", hasSize(3))
+ .body("actionExecutionDetails.findAll { it.actionName == 'SourceObject' }", hasSize(1))
+ .body("actionExecutionDetails.find { it.actionName == 'SuccessfulDeploy' }.status",
+ equalTo("Succeeded"))
+ .body("actionExecutionDetails.find { it.actionName == 'FailedDeploy' }.status", equalTo("Failed"));
+
+ createBucket("retry-stage-destination");
+
+ retryStage(pipelineName, "Deploy", executionId, "FAILED_ACTIONS")
+ .then()
+ .statusCode(200)
+ .body("pipelineExecutionId", equalTo(executionId));
+
+ waitForExecution(pipelineName, executionId, "Succeeded");
+
+ post("GetPipelineExecution", """
+ {"pipelineName": "%s", "pipelineExecutionId": "%s"}
+ """.formatted(pipelineName, executionId))
+ .then()
+ .statusCode(200)
+ .body("pipelineExecution.pipelineExecutionId", equalTo(executionId))
+ .body("pipelineExecution.artifactsReleased", nullValue())
+ .body("pipelineExecution.stageExecutionStatuses", nullValue());
+
+ given()
+ .get("/retry-stage-destination/deployed.zip")
+ .then()
+ .statusCode(200)
+ .body(equalTo("retry artifact"));
+
+ post("ListPipelineExecutions", """
+ {"pipelineName": "%s"}
+ """.formatted(pipelineName))
+ .then()
+ .statusCode(200)
+ .body("pipelineExecutionSummaries", hasSize(1))
+ .body("pipelineExecutionSummaries[0].pipelineExecutionId", equalTo(executionId))
+ .body("pipelineExecutionSummaries[0].status", equalTo("Succeeded"));
+
+ post("ListActionExecutions", """
+ {
+ "pipelineName": "%s",
+ "filter": {"pipelineExecutionId": "%s"}
+ }
+ """.formatted(pipelineName, executionId))
+ .then()
+ .statusCode(200)
+ .body("actionExecutionDetails", hasSize(4))
+ .body("actionExecutionDetails.findAll { it.actionName == 'SourceObject' }", hasSize(1))
+ .body("actionExecutionDetails.findAll { it.actionName == 'SuccessfulDeploy' }", hasSize(1))
+ .body("actionExecutionDetails.findAll { it.actionName == 'FailedDeploy' }", hasSize(2))
+ .body("actionExecutionDetails.find { it.actionName == 'FailedDeploy' }.status", equalTo("Succeeded"));
+
+ post("GetPipelineState", """
+ {"name": "%s"}
+ """.formatted(pipelineName))
+ .then()
+ .statusCode(200)
+ .body("stageStates.find { it.stageName == 'Deploy' }.actionStates"
+ + ".find { it.actionName == 'SuccessfulDeploy' }.latestExecution.status", equalTo("Succeeded"))
+ .body("stageStates.find { it.stageName == 'Deploy' }.actionStates"
+ + ".find { it.actionName == 'FailedDeploy' }.latestExecution.status", equalTo("Succeeded"));
+
+ post("DeletePipeline", """
+ {"name": "%s"}
+ """.formatted(pipelineName)).then().statusCode(200);
+ }
+
+ @Test
+ void retryStageExecutionAllActionsRerunsSuccessfulActions() throws Exception {
+ createBucket("retry-all-source");
+ createBucket("retry-all-success");
+ putObject("retry-all-source", "source.zip", "retry all artifact");
+
+ String pipelineName = "retry-all-pipeline";
+ post("CreatePipeline", pipeline(pipelineName, """
+ {
+ "name": "Source",
+ "actions": [{
+ "name": "SourceObject",
+ "actionTypeId": {
+ "category": "Source", "owner": "AWS", "provider": "S3", "version": "1"
+ },
+ "configuration": {
+ "S3Bucket": "retry-all-source", "S3ObjectKey": "source.zip"
+ },
+ "outputArtifacts": [{"name": "SourceOutput"}]
+ }]
+ },
+ {
+ "name": "Deploy",
+ "actions": [{
+ "name": "SuccessfulDeploy",
+ "actionTypeId": {
+ "category": "Deploy", "owner": "AWS", "provider": "S3", "version": "1"
+ },
+ "configuration": {
+ "BucketName": "retry-all-success", "ObjectKey": "successful.zip"
+ },
+ "inputArtifacts": [{"name": "SourceOutput"}],
+ "runOrder": 1
+ }, {
+ "name": "FailedDeploy",
+ "actionTypeId": {
+ "category": "Deploy", "owner": "AWS", "provider": "S3", "version": "1"
+ },
+ "configuration": {
+ "BucketName": "retry-all-destination", "ObjectKey": "deployed.zip"
+ },
+ "inputArtifacts": [{"name": "SourceOutput"}],
+ "runOrder": 1
+ }]
+ }
+ """))
+ .then().statusCode(200);
+
+ String executionId = post("StartPipelineExecution", """
+ {"name": "%s"}
+ """.formatted(pipelineName))
+ .then().statusCode(200).extract().path("pipelineExecutionId");
+ waitForExecution(pipelineName, executionId, "Failed");
+ createBucket("retry-all-destination");
+
+ retryStage(pipelineName, "Deploy", executionId, "ALL_ACTIONS")
+ .then().statusCode(200).body("pipelineExecutionId", equalTo(executionId));
+ waitForExecution(pipelineName, executionId, "Succeeded");
+
+ post("ListActionExecutions", """
+ {
+ "pipelineName": "%s",
+ "filter": {"pipelineExecutionId": "%s"}
+ }
+ """.formatted(pipelineName, executionId))
+ .then()
+ .statusCode(200)
+ .body("actionExecutionDetails.findAll { it.actionName == 'SourceObject' }", hasSize(1))
+ .body("actionExecutionDetails.findAll { it.actionName == 'SuccessfulDeploy' }", hasSize(2))
+ .body("actionExecutionDetails.findAll { it.actionName == 'FailedDeploy' }", hasSize(2));
+
+ post("DeletePipeline", """
+ {"name": "%s"}
+ """.formatted(pipelineName)).then().statusCode(200);
+ }
+
+ @Test
+ void retryStageExecutionValidatesRetryability() throws Exception {
+ String pipelineName = "retry-validation-pipeline";
+ post("CreatePipeline", pipeline(pipelineName, """
+ {
+ "name": "Source",
+ "actions": [{
+ "name": "SourceObject",
+ "actionTypeId": {
+ "category": "Source",
+ "owner": "AWS",
+ "provider": "S3",
+ "version": "1"
+ },
+ "configuration": {
+ "S3Bucket": "missing-retry-source",
+ "S3ObjectKey": "source.zip"
+ },
+ "outputArtifacts": [{"name": "SourceOutput"}]
+ }]
+ },
+ {
+ "name": "Deploy",
+ "actions": [{
+ "name": "DeployObject",
+ "actionTypeId": {
+ "category": "Deploy",
+ "owner": "AWS",
+ "provider": "S3",
+ "version": "1"
+ },
+ "configuration": {
+ "BucketName": "unused-retry-destination",
+ "ObjectKey": "deployed.zip"
+ },
+ "inputArtifacts": [{"name": "SourceOutput"}]
+ }]
+ }
+ """))
+ .then()
+ .statusCode(200);
+
+ String executionId = post("StartPipelineExecution", """
+ {"name": "%s"}
+ """.formatted(pipelineName))
+ .then()
+ .statusCode(200)
+ .extract().path("pipelineExecutionId");
+
+ waitForExecution(pipelineName, executionId, "Failed");
+
+ post("RetryStageExecution", """
+ {
+ "pipelineName": "%s",
+ "stageName": "Source",
+ "pipelineExecutionId": "%s",
+ "retryMode": "INVALID"
+ }
+ """.formatted(pipelineName, executionId))
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("ValidationException"));
+
+ post("RetryStageExecution", """
+ {
+ "pipelineName": "%s",
+ "stageName": "Missing",
+ "pipelineExecutionId": "%s",
+ "retryMode": "FAILED_ACTIONS"
+ }
+ """.formatted(pipelineName, executionId))
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("StageNotFoundException"));
+
+ post("UpdatePipeline", pipeline(pipelineName, """
+ {
+ "name": "Source",
+ "actions": [{
+ "name": "SourceObjectV2",
+ "actionTypeId": {
+ "category": "Source", "owner": "AWS", "provider": "S3", "version": "1"
+ },
+ "configuration": {
+ "S3Bucket": "missing-retry-source", "S3ObjectKey": "source.zip"
+ },
+ "outputArtifacts": [{"name": "SourceOutput"}]
+ }]
+ },
+ {
+ "name": "Deploy",
+ "actions": [{
+ "name": "DeployObject",
+ "actionTypeId": {
+ "category": "Deploy", "owner": "AWS", "provider": "S3", "version": "1"
+ },
+ "configuration": {
+ "BucketName": "unused-retry-destination", "ObjectKey": "deployed.zip"
+ },
+ "inputArtifacts": [{"name": "SourceOutput"}]
+ }]
+ }
+ """))
+ .then().statusCode(200);
+
+ post("RetryStageExecution", """
+ {
+ "pipelineName": "%s",
+ "stageName": "Source",
+ "pipelineExecutionId": "%s",
+ "retryMode": "FAILED_ACTIONS"
+ }
+ """.formatted(pipelineName, executionId))
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("StageNotRetryableException"));
+
+ post("DeletePipeline", """
+ {"name": "%s"}
+ """.formatted(pipelineName)).then().statusCode(200);
+ }
+
+ @Test
+ void retryStageExecutionAdmitsOneOfConcurrentRetries() throws Exception {
+ String pipelineName = "retry-concurrent-pipeline";
+ post("CreatePipeline", approvalPipeline(pipelineName, "PARALLEL")).then().statusCode(200);
+ String executionId = startExecution(pipelineName);
+ waitForApprovalToken(pipelineName);
+ stopExecutions(pipelineName, List.of(executionId));
+ waitForExecution(pipelineName, executionId, "Stopped");
+
+ int callersPerBurst = 8;
+ ExecutorService callers = Executors.newFixedThreadPool(callersPerBurst);
+ try {
+ await("one retry to be admitted once the stopped run has finished").atMost(Duration.ofSeconds(5))
+ .pollDelay(Duration.ZERO).pollInterval(Duration.ofMillis(50))
+ .until(() -> {
+ List<Response> completed = retryConcurrently(callers, callersPerBurst,
+ pipelineName, "Approve", executionId, "ALL_ACTIONS");
+ long admitted = completed.stream().filter(r -> r.statusCode() == 200).count();
+ assertTrue(admitted <= 1, "more than one concurrent retry was admitted");
+ assertTrue(completed.stream().filter(r -> r.statusCode() != 200)
+ .allMatch(r -> r.statusCode() == 400
+ && r.jsonPath().getString("__type").contains("ConflictException")));
+ return admitted == 1;
+ });
+ } finally {
+ callers.shutdownNow();
+ post("StopPipelineExecution", """
+ {"pipelineName": "%s", "pipelineExecutionId": "%s", "abandon": true}
+ """.formatted(pipelineName, executionId));
+ }
+ }
+
+ @Test
+ void retryStageExecutionRejectsStageCompletedBeforeInboundStop() throws Exception {
+ String pipelineName = "retry-inbound-stop-pipeline";
+ post("CreatePipeline", approvalPipeline(pipelineName, "PARALLEL")).then().statusCode(200);
+ post("DisableStageTransition", """
+ {
+ "pipelineName": "%s",
+ "stageName": "Complete",
+ "transitionType": "Inbound",
+ "reason": "hold"
+ }
+ """.formatted(pipelineName)).then().statusCode(200);
+ String executionId = startExecution(pipelineName);
+ post("PutApprovalResult", """
+ {
+ "pipelineName": "%s",
+ "stageName": "Approve",
+ "actionName": "ManualApproval",
+ "token": "%s",
+ "result": {"status": "Approved", "summary": "ok"}
+ }
+ """.formatted(pipelineName, waitForApprovalToken(pipelineName))).then().statusCode(200);
+ waitForStageStatus(pipelineName, "Approve", "Succeeded");
+ stopExecutions(pipelineName, List.of(executionId));
+ waitForExecution(pipelineName, executionId, "Stopped");
+
+ retryStage(pipelineName, "Approve", executionId, "ALL_ACTIONS")
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("StageNotRetryableException"));
+ }
+
+ @Test
+ void retryStageExecutionCountsAgainstActiveExecutionLimit() throws Exception {
+ String pipelineName = "retry-limit-pipeline";
+ post("CreatePipeline", approvalPipeline(pipelineName, "PARALLEL")).then().statusCode(200);
+ String stoppedId = startExecution(pipelineName);
+ waitForApprovalToken(pipelineName);
+ stopExecutions(pipelineName, List.of(stoppedId));
+ waitForExecution(pipelineName, stoppedId, "Stopped");
+
+ List<String> executionIds = new ArrayList<>();
+ try {
+ while (executionIds.size() < 50) {
+ executionIds.add(startExecution(pipelineName));
+ }
+ waitForActiveExecutions(pipelineName, 50);
+
+ retryStage(pipelineName, "Approve", stoppedId, "ALL_ACTIONS")
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("ConcurrentPipelineExecutionsLimitExceededException"));
+ } finally {
+ stopExecutions(pipelineName, executionIds);
+ }
+ }
+
+ @Test
+ void retryStageExecutionReleasesArtifactsOfOutdatedExecution() throws Exception {
+ createBucket("retry-outdated-source");
+ putObject("retry-outdated-source", "source.zip", "outdated artifact");
+ String pipelineName = "retry-outdated-pipeline";
+ post("CreatePipeline", pipeline(pipelineName, """
+ {
+ "name": "Source",
+ "actions": [{
+ "name": "SourceObject",
+ "actionTypeId": {"category": "Source", "owner": "AWS", "provider": "S3", "version": "1"},
+ "configuration": {"S3Bucket": "retry-outdated-source", "S3ObjectKey": "source.zip"},
+ "outputArtifacts": [{"name": "SourceOutput"}]
+ }]
+ },
+ {
+ "name": "Deploy",
+ "actions": [{
+ "name": "DeployObject",
+ "actionTypeId": {"category": "Deploy", "owner": "AWS", "provider": "S3", "version": "1"},
+ "configuration": {"BucketName": "retry-outdated-destination", "ObjectKey": "deployed.zip"},
+ "inputArtifacts": [{"name": "SourceOutput"}]
+ }]
+ }
+ """)).then().statusCode(200);
+
+ String olderId = startExecution(pipelineName);
+ waitForExecution(pipelineName, olderId, "Failed");
+ String newerId = startExecution(pipelineName);
+ waitForExecution(pipelineName, newerId, "Failed");
+
+ retryStage(pipelineName, "Deploy", olderId, "FAILED_ACTIONS")
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("NotLatestPipelineExecutionException"));
+
+ createBucket("retry-outdated-destination");
+ retryStage(pipelineName, "Deploy", newerId, "FAILED_ACTIONS").then().statusCode(200);
+ waitForExecution(pipelineName, newerId, "Succeeded");
+
+ retryStage(pipelineName, "Deploy", olderId, "FAILED_ACTIONS")
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("StageNotRetryableException"));
+
+ post("DeletePipeline", """
+ {"name": "%s"}
+ """.formatted(pipelineName)).then().statusCode(200);
+ }
+
+ @Test
+ void retryStageExecutionRejectsRetryWhileSiblingActionStillRuns() throws Exception {
+ String pipelineName = "retry-sibling-running-pipeline";
+ post("CreatePipeline", pipeline(pipelineName, """
+ {
+ "name": "Deploy",
+ "actions": [{
+ "name": "ManualApproval",
+ "actionTypeId": {"category": "Approval", "owner": "AWS", "provider": "Manual", "version": "1"},
+ "runOrder": 1
+ }, {
+ "name": "UnsupportedDeploy",
+ "actionTypeId": {"category": "Deploy", "owner": "AWS", "provider": "ECS", "version": "1"},
+ "configuration": {"ClusterName": "none", "ServiceName": "none"},
+ "runOrder": 1
+ }]
+ },
+ {
+ "name": "Release",
+ "actions": [{
+ "name": "ReleaseApproval",
+ "actionTypeId": {"category": "Approval", "owner": "AWS", "provider": "Manual", "version": "1"}
+ }]
+ }
+ """)).then().statusCode(200);
+
+ String executionId = startExecution(pipelineName);
+ waitForExecution(pipelineName, executionId, "Failed");
+ String approvalToken = waitForApprovalToken(pipelineName);
+
+ post("RetryStageExecution", """
+ {
+ "pipelineName": "%s",
+ "stageName": "Deploy",
+ "pipelineExecutionId": "%s",
+ "retryMode": "FAILED_ACTIONS"
+ }
+ """.formatted(pipelineName, executionId))
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("ConflictException"));
+
+ post("PutApprovalResult", """
+ {
+ "pipelineName": "%s",
+ "stageName": "Deploy",
+ "actionName": "ManualApproval",
+ "token": "%s",
+ "result": {"status": "Approved", "summary": "done"}
+ }
+ """.formatted(pipelineName, approvalToken)).then().statusCode(200);
+ post("ListActionExecutions", """
+ {"pipelineName": "%s", "filter": {"pipelineExecutionId": "%s"}}
+ """.formatted(pipelineName, executionId))
+ .then()
+ .statusCode(200)
+ .body("actionExecutionDetails.findAll { it.actionName == 'ManualApproval' }", hasSize(1));
+ }
+
+ @Test
+ void retryStageExecutionRetriesCodeBuildStageFedByUnstoredArtifact() throws Exception {
+ createBucket("retry-codebuild-source");
+ putObject("retry-codebuild-source", "source.zip", "codebuild artifact");
+ String pipelineName = "retry-codebuild-chain-pipeline";
+ post("CreatePipeline", pipeline(pipelineName, """
+ {
+ "name": "Source",
+ "actions": [{
+ "name": "SourceObject",
+ "actionTypeId": {"category": "Source", "owner": "AWS", "provider": "S3", "version": "1"},
+ "configuration": {"S3Bucket": "retry-codebuild-source", "S3ObjectKey": "source.zip"},
+ "outputArtifacts": [{"name": "SourceOutput"}]
+ }]
+ },
+ {
+ "name": "Test",
+ "actions": [{
+ "name": "RunTests",
+ "actionTypeId": {"category": "Test", "owner": "AWS", "provider": "CodeBuild", "version": "1"},
+ "configuration": {"ProjectName": "retry-codebuild-missing-project"},
+ "inputArtifacts": [{"name": "BuildOutput"}]
+ }]
+ }
+ """)).then().statusCode(200);
+
+ String executionId = startExecution(pipelineName);
+ waitForExecution(pipelineName, executionId, "Failed");
+ post("ListActionExecutions", """
+ {"pipelineName": "%s", "filter": {"pipelineExecutionId": "%s"}}
+ """.formatted(pipelineName, executionId))
+ .then()
+ .statusCode(200)
+ .body("actionExecutionDetails.find { it.actionName == 'RunTests' }"
+ + ".output.executionResult.errorDetails.message", containsString("Project not found"));
+
+ retryStage(pipelineName, "Test", executionId, "FAILED_ACTIONS")
+ .then()
+ .statusCode(200)
+ .body("pipelineExecutionId", equalTo(executionId));
+ waitForExecution(pipelineName, executionId, "Failed");
+ waitForActionExecutionCount(pipelineName, executionId, "RunTests", 2);
+
+ post("DeletePipeline", """
+ {"name": "%s"}
+ """.formatted(pipelineName)).then().statusCode(200);
+ }
+
@Test
void listPipelineExecutionsValidatesFilterAndMaxResults() {
String pipelineName = "list-executions-validation-pipeline";
@@ -1690,6 +2289,27 @@ class CodePipelineIntegrationTest {
throw new AssertionError("Approval action did not reach " + expectedStatus + ", last status: " + status);
}
+ private void waitForStageStatus(String pipelineName, String stageName, String expected) {
+ await("stage " + stageName + " to reach " + expected).atMost(Duration.ofSeconds(5))
+ .pollDelay(Duration.ZERO).pollInterval(Duration.ofMillis(50))
+ .until(() -> post("GetPipelineState", """
+ {"name": "%s"}
+ """.formatted(pipelineName))
+ .jsonPath().getString("stageStates.find { it.stageName == '%s' }.latestExecution.status"
+ .formatted(stageName)), equalTo(expected));
+ }
+
+ private void waitForActionExecutionCount(String pipelineName, String executionId, String actionName,
+ int expected) {
+ await(actionName + " to run " + expected + " times").atMost(Duration.ofSeconds(5))
+ .pollDelay(Duration.ZERO).pollInterval(Duration.ofMillis(50))
+ .until(() -> post("ListActionExecutions", """
+ {"pipelineName": "%s", "filter": {"pipelineExecutionId": "%s"}}
+ """.formatted(pipelineName, executionId))
+ .jsonPath().getList("actionExecutionDetails.findAll { it.actionName == '%s' }"
+ .formatted(actionName)).size(), equalTo(expected));
+ }
+
private String waitForApprovalToken(String pipelineName) throws Exception {
return waitForApprovalToken(pipelineName, 0);
}
@@ -1779,6 +2399,56 @@ class CodePipelineIntegrationTest {
}
}
+ // A retry sent while the previous run is still finishing is rejected with ConflictException,
+ // which AWS documents as "try again later".
+ private static Response retryStage(String pipelineName, String stageName, String executionId,
+ String retryMode) {
+ AtomicReference<Response> response = new AtomicReference<>();
+ await("the previous run of " + executionId + " to finish").atMost(Duration.ofSeconds(5))
+ .pollDelay(Duration.ZERO).pollInterval(Duration.ofMillis(50))
+ .until(() -> {
+ response.set(post("RetryStageExecution",
+ retryBody(pipelineName, stageName, executionId, retryMode)));
+ return !isConflict(response.get());
+ });
+ return response.get();
+ }
+
+ private static List<Response> retryConcurrently(ExecutorService callers, int count, String pipelineName,
+ String stageName, String executionId, String retryMode)
+ throws Exception {
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<Response>> futures = new ArrayList<>();
+ for (int i = 0; i < count; i++) {
+ futures.add(callers.submit(() -> {
+ start.await();
+ return post("RetryStageExecution", retryBody(pipelineName, stageName, executionId, retryMode));
+ }));
+ }
+ start.countDown();
+ List<Response> responses = new ArrayList<>();
+ for (Future<Response> future : futures) {
+ responses.add(future.get(10, TimeUnit.SECONDS));
+ }
+ return responses;
+ }
+
+ private static String retryBody(String pipelineName, String stageName, String executionId, String retryMode) {
+ return """
+ {
+ "pipelineName": "%s",
+ "stageName": "%s",
+ "pipelineExecutionId": "%s",
+ "retryMode": "%s"
+ }
+ """.formatted(pipelineName, stageName, executionId, retryMode);
+ }
+
+ private static boolean isConflict(Response response) {
+ return response.statusCode() == 400
+ && String.valueOf(response.jsonPath().getString("__type")).contains("ConflictException");
+ }
+
private static Response post(String action, String body) {
return given()
.header("X-Amz-Target", TARGET + action)