mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(codepipeline): emit EventBridge state-change events and SNS approval notifications (#4616)
* feat(codepipeline): emit EventBridge state-change events and SNS approval notifications Publishes pipeline, stage, and action execution state changes to the default bus and notifies NotificationArn topics for manual approvals. * fix(codepipeline): match the approval message and event timestamps to the user guide Mint the pipeline ARN with AwsArnUtils.Arn.of, publish the approval notification as the pipeline's account, emit expires and start-time as ISO-8601, add externalEntityLink, drop the dead console links, truncate the SNS subject to 100 characters, and use warnv. * fix(codepipeline): restore the approval console links and keep event timestamp precision consoleLink and approvalReviewLink point at the AWS console URLs from the user guide, expires is to the minute, and start-time keeps its milliseconds. Terminal event dispatch uses switch expressions.
This commit is contained in:
1 parent
86c06247e3
commit
a833551d03
5 files changed
+617
-5
No files matched your search
+180
@@ -0,0 +1,180 @@
|
||||
package io.github.hectorvent.floci.services.codepipeline;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.codepipeline.model.CodePipelineExecution;
|
||||
import io.github.hectorvent.floci.services.codepipeline.model.CodePipelineExecution.ActionExecution;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Publishes the {@code aws.codepipeline} state-change events (pipeline, stage, and action)
|
||||
* to the default EventBridge bus, and the SNS approval-needed notification, matching the
|
||||
* shapes real CodePipeline emits. All publishing is best-effort: a failing delivery never
|
||||
* fails the pipeline execution.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CodePipelineEventPublisher {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CodePipelineEventPublisher.class);
|
||||
private static final int MAX_SNS_SUBJECT_LENGTH = 100;
|
||||
private static final String CONSOLE_URL = "https://console.aws.amazon.com/codepipeline/home";
|
||||
/** The approval message's {@code expires} is to the minute, e.g. 2016-07-07T20:22Z. */
|
||||
private static final DateTimeFormatter MINUTE_FORMAT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm'Z'").withZone(ZoneOffset.UTC);
|
||||
|
||||
private final EventBridgeService eventBridgeService;
|
||||
private final SnsService snsService;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
public CodePipelineEventPublisher(EventBridgeService eventBridgeService,
|
||||
SnsService snsService, ObjectMapper mapper) {
|
||||
this.eventBridgeService = eventBridgeService;
|
||||
this.snsService = snsService;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
public void pipelineStateChange(CodePipelineExecution execution, String state) {
|
||||
ObjectNode detail = baseDetail(execution);
|
||||
detail.put("state", state);
|
||||
detail.put("execution-mode", execution.getExecutionMode());
|
||||
if (execution.getStartTime() != null) {
|
||||
detail.put("start-time", isoTimestamp(execution.getStartTime()));
|
||||
}
|
||||
publish(execution, "CodePipeline Pipeline Execution State Change", detail);
|
||||
}
|
||||
|
||||
public void stageStateChange(CodePipelineExecution execution, String stageName, String state) {
|
||||
ObjectNode detail = baseDetail(execution);
|
||||
detail.put("stage", stageName);
|
||||
detail.put("state", state);
|
||||
publish(execution, "CodePipeline Stage Execution State Change", detail);
|
||||
}
|
||||
|
||||
public void actionStateChange(CodePipelineExecution execution, ActionExecution action, String state) {
|
||||
ObjectNode detail = baseDetail(execution);
|
||||
detail.put("stage", action.getStageName());
|
||||
detail.put("action", action.getActionName());
|
||||
detail.put("state", state);
|
||||
detail.put("region", execution.getRegion());
|
||||
detail.putObject("type")
|
||||
.put("owner", action.getOwner())
|
||||
.put("provider", action.getProvider())
|
||||
.put("category", action.getCategory())
|
||||
.put("version", "1");
|
||||
if (action.getExternalExecutionId() != null || action.getSummary() != null
|
||||
|| action.getErrorDetails() != null) {
|
||||
ObjectNode result = detail.putObject("execution-result");
|
||||
if (action.getExternalExecutionId() != null) {
|
||||
result.put("external-execution-id", action.getExternalExecutionId());
|
||||
}
|
||||
if (action.getSummary() != null) {
|
||||
result.put("external-execution-summary", action.getSummary());
|
||||
}
|
||||
if (action.getErrorDetails() != null) {
|
||||
Object code = action.getErrorDetails().get("code");
|
||||
if (code != null) {
|
||||
result.put("error-code", code.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
publish(execution, "CodePipeline Action Execution State Change", detail);
|
||||
}
|
||||
|
||||
/**
|
||||
* The SNS notification a Manual approval action sends when it starts waiting.
|
||||
*
|
||||
* <p>Runs on a worker thread with no request context, so the publish is wrapped in
|
||||
* {@link RequestScopes#runAs} to resolve the topic in the pipeline's own account.
|
||||
* The subject is truncated to the 100 characters SNS allows.</p>
|
||||
*/
|
||||
public void approvalNeeded(CodePipelineExecution execution, ActionExecution action,
|
||||
String notificationArn, String customData,
|
||||
String externalEntityLink, double expires) {
|
||||
try {
|
||||
ObjectNode message = mapper.createObjectNode();
|
||||
String consoleLink = CONSOLE_URL + "?region=" + execution.getRegion()
|
||||
+ "#/view/" + execution.getPipelineName();
|
||||
message.put("region", execution.getRegion());
|
||||
message.put("consoleLink", consoleLink);
|
||||
ObjectNode approval = message.putObject("approval");
|
||||
approval.put("pipelineName", execution.getPipelineName());
|
||||
approval.put("stageName", action.getStageName());
|
||||
approval.put("actionName", action.getActionName());
|
||||
approval.put("token", action.getToken());
|
||||
approval.put("expires", MINUTE_FORMAT.format(Instant.ofEpochSecond((long) expires)));
|
||||
approval.put("approvalReviewLink", consoleLink + "/" + action.getStageName()
|
||||
+ "/" + action.getActionName() + "/approve/" + action.getToken());
|
||||
if (customData != null && !customData.isBlank()) {
|
||||
approval.put("customData", customData);
|
||||
}
|
||||
if (externalEntityLink != null && !externalEntityLink.isBlank()) {
|
||||
approval.put("externalEntityLink", externalEntityLink);
|
||||
}
|
||||
String subject = "APPROVAL NEEDED: AWS CodePipeline " + execution.getPipelineName()
|
||||
+ " for stage " + action.getStageName()
|
||||
+ " action " + action.getActionName();
|
||||
String truncated = subject.length() > MAX_SNS_SUBJECT_LENGTH
|
||||
? subject.substring(0, MAX_SNS_SUBJECT_LENGTH) : subject;
|
||||
RequestScopes.runAs(execution.getAccountId(), () -> snsService.publish(
|
||||
notificationArn, null, message.toString(), truncated, execution.getRegion()));
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("CodePipeline approval notification to {0} skipped: {1}",
|
||||
notificationArn, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** Epoch seconds (with fraction) as the ISO-8601 UTC timestamp CodePipeline emits, e.g. 2023-10-26T13:31:39.604Z. */
|
||||
private static String isoTimestamp(double epochSeconds) {
|
||||
return Instant.ofEpochMilli(Math.round(epochSeconds * 1000)).toString();
|
||||
}
|
||||
|
||||
private ObjectNode baseDetail(CodePipelineExecution execution) {
|
||||
ObjectNode detail = mapper.createObjectNode();
|
||||
detail.put("pipeline", execution.getPipelineName());
|
||||
detail.put("execution-id", execution.getPipelineExecutionId());
|
||||
if (execution.getPipelineVersion() != null) {
|
||||
detail.put("version", execution.getPipelineVersion());
|
||||
}
|
||||
return detail;
|
||||
}
|
||||
|
||||
private void publish(CodePipelineExecution execution, String detailType, ObjectNode detail) {
|
||||
try {
|
||||
Map<String, Object> entry = new HashMap<>();
|
||||
entry.put("Source", "aws.codepipeline");
|
||||
entry.put("DetailType", detailType);
|
||||
entry.put("Detail", detail.toString());
|
||||
entry.put("EventBusName", "default");
|
||||
entry.put("Region", execution.getRegion());
|
||||
// Always emit Resources (possibly empty): EventBridge pattern matching reads the
|
||||
// key unconditionally for rules with a "resources" filter.
|
||||
ArrayNode resources = mapper.createArrayNode();
|
||||
resources.add(AwsArnUtils.Arn.of("codepipeline", execution.getRegion(),
|
||||
execution.getAccountId(), execution.getPipelineName()).toString());
|
||||
entry.put("Resources", resources);
|
||||
// This runs on a pipeline-execution worker thread with no request context, so the
|
||||
// two-argument overload would fall back to the default (management) account and a
|
||||
// member account's EventBridge rules would never see the event. Name the bus's
|
||||
// account explicitly.
|
||||
eventBridgeService.putEvents(List.of(entry), execution.getRegion(),
|
||||
execution.getAccountId());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("CodePipeline event {0} not published: {1}", detailType, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
-5
@@ -109,6 +109,7 @@ public class CodePipelineService {
|
||||
private final CodeDeployService codeDeployService;
|
||||
private final LambdaService lambdaService;
|
||||
private final S3Service s3Service;
|
||||
private final CodePipelineEventPublisher eventPublisher;
|
||||
private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
private final ScheduledExecutorService sourcePoller = Executors.newSingleThreadScheduledExecutor();
|
||||
private final KeyedLockPool pipelineLocks = new KeyedLockPool();
|
||||
@@ -134,18 +135,35 @@ public class CodePipelineService {
|
||||
CodeBuildService codeBuildService, CodeDeployService codeDeployService,
|
||||
LambdaService lambdaService, S3Service s3Service) {
|
||||
this(storageFactory, mapper, codeBuildService, codeDeployService, lambdaService, s3Service,
|
||||
DEFAULT_SOURCE_POLL_INTERVAL_MS);
|
||||
detachedEventPublisher(mapper), DEFAULT_SOURCE_POLL_INTERVAL_MS);
|
||||
}
|
||||
|
||||
public CodePipelineService(StorageFactory storageFactory, ObjectMapper mapper,
|
||||
CodeBuildService codeBuildService, CodeDeployService codeDeployService,
|
||||
LambdaService lambdaService, S3Service s3Service,
|
||||
EmulatorConfig config) {
|
||||
this(storageFactory, mapper, codeBuildService, codeDeployService, lambdaService, s3Service,
|
||||
config, detachedEventPublisher(mapper));
|
||||
}
|
||||
|
||||
@Inject
|
||||
public CodePipelineService(StorageFactory storageFactory, ObjectMapper mapper,
|
||||
CodeBuildService codeBuildService, CodeDeployService codeDeployService,
|
||||
LambdaService lambdaService, S3Service s3Service,
|
||||
EmulatorConfig config) {
|
||||
EmulatorConfig config, CodePipelineEventPublisher eventPublisher) {
|
||||
this(storageFactory, mapper, codeBuildService, codeDeployService, lambdaService, s3Service,
|
||||
eventPublisher,
|
||||
resolveSourcePollInterval(config.services().codepipeline().sourcePollIntervalMs()));
|
||||
}
|
||||
|
||||
/**
|
||||
* A publisher with no EventBridge or SNS behind it, for the constructors built without CDI.
|
||||
* Publishing is best-effort, so each event is logged as undeliverable and dropped.
|
||||
*/
|
||||
private static CodePipelineEventPublisher detachedEventPublisher(ObjectMapper mapper) {
|
||||
return new CodePipelineEventPublisher(null, null, mapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* A zero or negative interval would make {@code scheduleWithFixedDelay} throw from the startup
|
||||
* observer and stop the whole emulator becoming ready. A misconfigured value is not worth
|
||||
@@ -164,7 +182,7 @@ public class CodePipelineService {
|
||||
private CodePipelineService(StorageFactory storageFactory, ObjectMapper mapper,
|
||||
CodeBuildService codeBuildService, CodeDeployService codeDeployService,
|
||||
LambdaService lambdaService, S3Service s3Service,
|
||||
long sourcePollIntervalMs) {
|
||||
CodePipelineEventPublisher eventPublisher, long sourcePollIntervalMs) {
|
||||
this.pipelineStore = storageFactory.create(
|
||||
"codepipeline", "codepipeline-pipelines.json", new TypeReference<Map<String, CodePipelinePipeline>>() {});
|
||||
this.executionStore = storageFactory.create(
|
||||
@@ -176,6 +194,7 @@ public class CodePipelineService {
|
||||
this.codeDeployService = codeDeployService;
|
||||
this.lambdaService = lambdaService;
|
||||
this.s3Service = s3Service;
|
||||
this.eventPublisher = eventPublisher;
|
||||
this.sourcePollIntervalMs = sourcePollIntervalMs;
|
||||
}
|
||||
|
||||
@@ -243,6 +262,7 @@ public class CodePipelineService {
|
||||
execution.setActionExecutions(new ArrayList<>());
|
||||
execution.setStageExecutionStatuses(new LinkedHashMap<>());
|
||||
putExecution(execution);
|
||||
eventPublisher.pipelineStateChange(execution, "RESUMED");
|
||||
executor.submit(() -> runExecution(pipeline, execution));
|
||||
}, () -> {
|
||||
execution.setStatus("Failed");
|
||||
@@ -561,6 +581,7 @@ public class CodePipelineService {
|
||||
"The pipeline has reached the limit for concurrent pipeline executions", 400);
|
||||
}
|
||||
applyExecutionMode(execution);
|
||||
eventPublisher.pipelineStateChange(execution, "STARTED");
|
||||
try {
|
||||
executor.submit(() -> runExecution(pipeline, execution));
|
||||
} catch (RejectedExecutionException exception) {
|
||||
@@ -568,6 +589,7 @@ public class CodePipelineService {
|
||||
execution.setStatusSummary("Pipeline execution could not be scheduled.");
|
||||
execution.setLastUpdateTime(now());
|
||||
putExecution(execution);
|
||||
eventPublisher.pipelineStateChange(execution, "FAILED");
|
||||
throw new AwsException("ConflictException",
|
||||
"Your request cannot be handled because the pipeline is busy handling ongoing activities. "
|
||||
+ "Try again later.", 400);
|
||||
@@ -622,6 +644,7 @@ public class CodePipelineService {
|
||||
});
|
||||
}
|
||||
putExecution(execution);
|
||||
eventPublisher.pipelineStateChange(execution, "STOPPING");
|
||||
return mapper.createObjectNode().put("pipelineExecutionId", execution.getPipelineExecutionId());
|
||||
}
|
||||
|
||||
@@ -1220,18 +1243,22 @@ public class CodePipelineService {
|
||||
execution.getStageExecutionStatuses().put(stageName, "InProgress");
|
||||
execution.setLastUpdateTime(now());
|
||||
putExecution(execution);
|
||||
eventPublisher.stageStateChange(execution, stageName, "STARTED");
|
||||
runStage(pipeline, execution, stage);
|
||||
if ("Failed".equals(execution.getStatus())) {
|
||||
execution.getStageExecutionStatuses().put(stageName, "Failed");
|
||||
eventPublisher.stageStateChange(execution, stageName, "FAILED");
|
||||
return;
|
||||
}
|
||||
if (finishIfStopped(execution)) {
|
||||
eventPublisher.stageStateChange(execution, stageName, "STOPPED");
|
||||
return;
|
||||
}
|
||||
execution.getStageExecutionStatuses().put(stageName, "Succeeded");
|
||||
execution.setCurrentStage(null);
|
||||
execution.setLastUpdateTime(now());
|
||||
putExecution(execution);
|
||||
eventPublisher.stageStateChange(execution, stageName, "SUCCEEDED");
|
||||
}
|
||||
execution.setStatus("Succeeded");
|
||||
execution.setStatusSummary("Pipeline execution succeeded.");
|
||||
@@ -1259,6 +1286,15 @@ public class CodePipelineService {
|
||||
activeRuns.remove(runKey(execution));
|
||||
}
|
||||
});
|
||||
String terminalState = switch (execution.getStatus()) {
|
||||
case "Succeeded" -> "SUCCEEDED";
|
||||
case "Failed" -> "FAILED";
|
||||
case "Stopped" -> "STOPPED";
|
||||
default -> null;
|
||||
};
|
||||
if (terminalState != null) {
|
||||
eventPublisher.pipelineStateChange(execution, terminalState);
|
||||
}
|
||||
}
|
||||
|
||||
// Failed and stopped executions keep their artifacts so a stage retry can reuse them. Once a newer
|
||||
@@ -1349,6 +1385,7 @@ public class CodePipelineService {
|
||||
execution.getActionExecutions().add(state);
|
||||
putExecution(execution);
|
||||
}
|
||||
eventPublisher.actionStateChange(execution, state, "STARTED");
|
||||
try {
|
||||
executeProvider(pipeline, execution, action, state);
|
||||
if ("InProgress".equals(state.getStatus())) {
|
||||
@@ -1368,6 +1405,15 @@ public class CodePipelineService {
|
||||
} finally {
|
||||
state.setLastUpdateTime(now());
|
||||
putExecution(execution);
|
||||
String terminalState = switch (state.getStatus()) {
|
||||
case "Succeeded" -> "SUCCEEDED";
|
||||
case "Failed" -> "FAILED";
|
||||
case "Abandoned" -> "ABANDONED";
|
||||
default -> null;
|
||||
};
|
||||
if (terminalState != null) {
|
||||
eventPublisher.actionStateChange(execution, state, terminalState);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1377,7 +1423,7 @@ public class CodePipelineService {
|
||||
String owner = state.getOwner();
|
||||
String provider = state.getProvider();
|
||||
if ("Approval".equals(category) && "Manual".equals(provider)) {
|
||||
waitForApproval(execution, state);
|
||||
waitForApproval(execution, action, state);
|
||||
return;
|
||||
}
|
||||
if ("Source".equals(category) && "GitHub".equals(provider) && "ThirdParty".equals(owner)
|
||||
@@ -1827,10 +1873,18 @@ public class CodePipelineService {
|
||||
state.setExternalExecutionId(result.path("pipelineExecutionId").asText());
|
||||
}
|
||||
|
||||
private void waitForApproval(CodePipelineExecution execution, ActionExecution state) throws InterruptedException {
|
||||
private void waitForApproval(CodePipelineExecution execution, JsonNode action,
|
||||
ActionExecution state) throws InterruptedException {
|
||||
state.setToken(UUID.randomUUID().toString());
|
||||
state.setSummary("Waiting for approval.");
|
||||
putExecution(execution);
|
||||
String notificationArn = action.path("configuration").path("NotificationArn").asText(null);
|
||||
if (notificationArn != null && !notificationArn.isBlank()) {
|
||||
eventPublisher.approvalNeeded(execution, state, notificationArn,
|
||||
action.path("configuration").path("CustomData").asText(null),
|
||||
action.path("configuration").path("ExternalEntityLink").asText(null),
|
||||
now() + TimeUnit.DAYS.toSeconds(7));
|
||||
}
|
||||
while ("InProgress".equals(state.getStatus()) && !execution.isStopRequested()) {
|
||||
TimeUnit.MILLISECONDS.sleep(POLL_INTERVAL_MS);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user