feat(codebuild,codedeploy): Implementing real build in docker phase2 (#649)

* feat(codebuild,codedeploy): real build execution and Lambda deployment engine

CodeBuild Phase 2: runs buildspec phases inside real Docker containers.
Source injected via docker cp (copyArchiveToContainerCmd); artifacts
extracted via docker cp (copyArchiveFromContainerCmd). No bind mounts —
works transparently in Docker-in-Docker. CloudWatch log streaming, S3
artifact upload, StopBuild, RetryBuild, ListBuilds, ListBuildsForProject.

CodeDeploy Phase 2: real Lambda deployments with traffic shifting via
alias RoutingConfig, lifecycle hook invocation against live Lambda
functions, PutLifecycleEventHookExecutionStatus callback, and
auto-rollback on hook failure. CreateDeployment, GetDeployment,
deployment state polling, ListDeployments, BatchGetDeployments,
ListDeploymentTargets, BatchGetDeploymentTargets.

* docs: updating docs with new services details
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-04-29 22:11:55 -05:00
1 parent 2ff85a450e
commit 2832bc7714
22 files changed
+2570 -38

No files matched your search

@@ -277,6 +277,8 @@ public interface EmulatorConfig {
interface CodeBuildServiceConfig {
@WithDefault("true")
boolean enabled();
Optional<String> dockerNetwork();
}
interface CodeDeployServiceConfig {
@@ -0,0 +1,104 @@
package io.github.hectorvent.floci.services.codebuild;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.github.hectorvent.floci.core.common.AwsException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Stateless YAML/JSON buildspec parser. Supports version 0.2.
*/
class BuildspecParser {
private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory());
record ParsedBuildspec(
Map<String, String> envVariables,
Map<String, String> parameterStoreVars,
Map<String, String> secretsManagerVars,
List<String> installCommands,
List<String> preBuildCommands,
List<String> buildCommands,
List<String> postBuildCommands,
ParsedArtifacts artifacts
) {}
record ParsedArtifacts(
String type,
List<String> files,
String baseDirectory,
boolean discardPaths,
String name,
String packaging
) {}
static ParsedBuildspec parse(String content) {
if (content == null || content.isBlank()) {
throw new AwsException("InvalidInputException", "Buildspec content is empty", 400);
}
try {
JsonNode root = YAML.readTree(content);
JsonNode envNode = root.path("env");
Map<String, String> envVars = parseStringMap(envNode.path("variables"));
Map<String, String> paramStore = parseStringMap(envNode.path("parameter-store"));
Map<String, String> secretsMgr = parseStringMap(envNode.path("secrets-manager"));
JsonNode phases = root.path("phases");
List<String> install = parseCommands(phases.path("install"));
List<String> preBuild = parseCommands(phases.path("pre_build"));
List<String> build = parseCommands(phases.path("build"));
List<String> postBuild = parseCommands(phases.path("post_build"));
ParsedArtifacts artifacts = parseArtifacts(root.path("artifacts"));
return new ParsedBuildspec(envVars, paramStore, secretsMgr,
install, preBuild, build, postBuild, artifacts);
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("InvalidInputException", "Failed to parse buildspec: " + e.getMessage(), 400);
}
}
private static List<String> parseCommands(JsonNode phaseNode) {
if (phaseNode.isMissingNode() || phaseNode.isNull()) {
return List.of();
}
List<String> result = new ArrayList<>();
for (JsonNode cmd : phaseNode.path("commands")) {
result.add(cmd.asText());
}
return result;
}
private static Map<String, String> parseStringMap(JsonNode node) {
Map<String, String> result = new LinkedHashMap<>();
if (node.isMissingNode() || node.isNull()) {
return result;
}
node.fields().forEachRemaining(e -> result.put(e.getKey(), e.getValue().asText()));
return result;
}
private static ParsedArtifacts parseArtifacts(JsonNode node) {
if (node.isMissingNode() || node.isNull()) {
return new ParsedArtifacts("NO_ARTIFACTS", List.of(), null, false, null, "ZIP");
}
String type = node.path("type").asText("NO_ARTIFACTS");
List<String> files = new ArrayList<>();
for (JsonNode f : node.path("files")) {
files.add(f.asText());
}
String baseDir = node.has("base-directory") ? node.path("base-directory").asText(null) : null;
boolean discardPaths = node.path("discard-paths").asBoolean(false);
String name = node.has("name") ? node.path("name").asText(null) : null;
String packaging = node.path("packaging").asText("ZIP");
return new ParsedArtifacts(type, files, baseDir, discardPaths, name, packaging);
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.codebuild;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.codebuild.model.Build;
import io.github.hectorvent.floci.services.codebuild.model.Project;
import io.github.hectorvent.floci.services.codebuild.model.ProjectArtifacts;
import io.github.hectorvent.floci.services.codebuild.model.ProjectEnvironment;
@@ -46,6 +47,12 @@ public class CodeBuildJsonHandler {
case "ListSourceCredentials" -> listSourceCredentials(region);
case "DeleteSourceCredentials" -> deleteSourceCredentials(request, region);
case "ListCuratedEnvironmentImages" -> listCuratedEnvironmentImages();
case "StartBuild" -> startBuild(request, region, account);
case "BatchGetBuilds" -> batchGetBuilds(request, region);
case "ListBuilds" -> listBuilds(region);
case "ListBuildsForProject" -> listBuildsForProject(request, region);
case "StopBuild" -> stopBuild(request, region);
case "RetryBuild" -> retryBuild(request, region, account);
default -> throw new AwsException("InvalidAction", "Action " + action + " is not supported", 400);
};
}
@@ -184,6 +191,82 @@ public class CodeBuildJsonHandler {
return Response.ok(Map.of("platforms", service.listCuratedEnvironmentImages())).build();
}
private Response startBuild(JsonNode req, String region, String account) throws Exception {
String projectName = req.path("projectName").asText(null);
String buildspecOverride = req.has("buildspecOverride") ? req.path("buildspecOverride").asText(null) : null;
ProjectEnvironment envOverride = req.has("environmentVariablesOverride")
? buildEnvOverride(req) : null;
ProjectArtifacts artifactsOverride = req.has("artifactsOverride")
? mapper.treeToValue(req.get("artifactsOverride"), ProjectArtifacts.class) : null;
String sourceVersion = req.has("sourceVersion") ? req.path("sourceVersion").asText(null) : null;
Integer timeout = req.has("timeoutInMinutes") ? req.path("timeoutInMinutes").asInt() : null;
String imageOverride = req.has("imageOverride") ? req.path("imageOverride").asText(null) : null;
String computeTypeOverride = req.has("computeTypeOverride") ? req.path("computeTypeOverride").asText(null) : null;
Build build = service.startBuild(region, account, projectName, buildspecOverride,
envOverride, artifactsOverride, sourceVersion, timeout, imageOverride, computeTypeOverride);
return Response.ok(Map.of("build", build)).build();
}
private ProjectEnvironment buildEnvOverride(JsonNode req) throws Exception {
ProjectEnvironment env = new ProjectEnvironment();
if (req.has("environmentVariablesOverride")) {
List<Map<String, String>> vars = new ArrayList<>();
for (JsonNode v : req.get("environmentVariablesOverride")) {
Map<String, String> m = new HashMap<>();
m.put("name", v.path("name").asText());
m.put("value", v.path("value").asText());
m.put("type", v.path("type").asText("PLAINTEXT"));
vars.add(m);
}
env.setEnvironmentVariables(vars);
}
if (req.has("imageOverride")) {
env.setImage(req.path("imageOverride").asText(null));
}
if (req.has("computeTypeOverride")) {
env.setComputeType(req.path("computeTypeOverride").asText(null));
}
if (req.has("privilegedModeOverride")) {
env.setPrivilegedMode(req.path("privilegedModeOverride").asBoolean());
}
if (req.has("environmentTypeOverride")) {
env.setType(req.path("environmentTypeOverride").asText(null));
}
return env;
}
private Response batchGetBuilds(JsonNode req, String region) {
List<String> ids = new ArrayList<>();
req.path("ids").forEach(n -> ids.add(n.asText()));
List<Build> found = service.batchGetBuilds(region, ids);
List<String> foundIds = found.stream().map(Build::getId).toList();
List<String> notFound = ids.stream().filter(id -> !foundIds.contains(id)).toList();
return Response.ok(Map.of("builds", found, "buildsNotFound", notFound)).build();
}
private Response listBuilds(String region) {
return Response.ok(Map.of("ids", service.listBuilds(region))).build();
}
private Response listBuildsForProject(JsonNode req, String region) {
String projectName = req.path("projectName").asText(null);
return Response.ok(Map.of("ids", service.listBuildsForProject(region, projectName))).build();
}
private Response stopBuild(JsonNode req, String region) {
String id = req.path("id").asText(null);
service.stopBuild(region, id);
Build build = service.getBuild(region, id);
return Response.ok(Map.of("build", build)).build();
}
private Response retryBuild(JsonNode req, String region, String account) {
String id = req.path("id").asText(null);
Build build = service.retryBuild(region, account, id);
return Response.ok(Map.of("build", build)).build();
}
@SuppressWarnings("unchecked")
private <T> List<T> parseList(JsonNode req, String field, Class<T> type) throws Exception {
if (!req.has(field) || req.get(field).isNull()) {
@@ -0,0 +1,823 @@
package io.github.hectorvent.floci.services.codebuild;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.services.codebuild.BuildspecParser.ParsedArtifacts;
import io.github.hectorvent.floci.services.codebuild.BuildspecParser.ParsedBuildspec;
import io.github.hectorvent.floci.services.codebuild.model.Build;
import io.github.hectorvent.floci.services.codebuild.model.BuildPhase;
import io.github.hectorvent.floci.services.codebuild.model.Project;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
import io.github.hectorvent.floci.services.ssm.SsmService;
import io.github.hectorvent.floci.services.ssm.model.Parameter;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
@ApplicationScoped
public class CodeBuildRunner {
private static final Logger LOG = Logger.getLogger(CodeBuildRunner.class);
private final DockerClient dockerClient;
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerLogStreamer logStreamer;
private final S3Service s3Service;
private final SsmService ssmService;
private final SecretsManagerService secretsManagerService;
private final EmulatorConfig config;
private final ContainerDetector containerDetector;
private final ConcurrentHashMap<String, String> runningContainers = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, AtomicBoolean> stopFlags = new ConcurrentHashMap<>();
@Inject
public CodeBuildRunner(DockerClient dockerClient,
ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerLogStreamer logStreamer,
S3Service s3Service,
SsmService ssmService,
SecretsManagerService secretsManagerService,
EmulatorConfig config,
ContainerDetector containerDetector) {
this.dockerClient = dockerClient;
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
this.s3Service = s3Service;
this.ssmService = ssmService;
this.secretsManagerService = secretsManagerService;
this.config = config;
this.containerDetector = containerDetector;
}
public void startBuild(String region, Build build, Project project, String buildspecOverride) {
AtomicBoolean stopFlag = new AtomicBoolean(false);
stopFlags.put(build.getId(), stopFlag);
Thread.ofVirtual().start(() -> runBuild(region, build, project, buildspecOverride, stopFlag));
}
public void stopBuild(String buildId) {
AtomicBoolean flag = stopFlags.get(buildId);
if (flag != null) {
flag.set(true);
}
String containerId = runningContainers.get(buildId);
if (containerId != null) {
try {
dockerClient.stopContainerCmd(containerId).withTimeout(5).exec();
} catch (Exception e) {
LOG.debugv("Error stopping build container {0}: {1}", containerId, e.getMessage());
}
}
}
private void runBuild(String region, Build build, Project project,
String buildspecOverride, AtomicBoolean stopFlag) {
String buildId = build.getId();
Path workspace = null;
String containerId = null;
Closeable logHandle = null;
try {
// SUBMITTED
beginPhase(build, "SUBMITTED");
completePhase(build, "SUBMITTED", "SUCCEEDED");
if (stopFlag.get()) { finishStopped(build); return; }
// QUEUED
beginPhase(build, "QUEUED");
completePhase(build, "QUEUED", "SUCCEEDED");
if (stopFlag.get()) { finishStopped(build); return; }
// PROVISIONING
beginPhase(build, "PROVISIONING");
build.setCurrentPhase("PROVISIONING");
workspace = Files.createTempDirectory("floci-codebuild-");
completePhase(build, "PROVISIONING", "SUCCEEDED");
if (stopFlag.get()) { finishStopped(build); return; }
// DOWNLOAD_SOURCE
beginPhase(build, "DOWNLOAD_SOURCE");
build.setCurrentPhase("DOWNLOAD_SOURCE");
String buildspecContent;
try {
buildspecContent = resolveAndAcquireSource(region, build, project, buildspecOverride, workspace);
} catch (AwsException e) {
completePhaseWithError(build, "DOWNLOAD_SOURCE", "FAILED", e.getMessage());
finishFailed(build);
return;
}
ParsedBuildspec buildspec;
try {
buildspec = BuildspecParser.parse(buildspecContent);
} catch (AwsException e) {
completePhaseWithError(build, "DOWNLOAD_SOURCE", "FAILED", e.getMessage());
finishFailed(build);
return;
}
completePhase(build, "DOWNLOAD_SOURCE", "SUCCEEDED");
if (stopFlag.get()) { finishStopped(build); return; }
String logGroup = "/aws/codebuild/" + project.getName();
String logStream = logStreamer.generateLogStreamName(buildId.replace(":", "/"));
String image = build.getEnvironment() != null && build.getEnvironment().getImage() != null
? build.getEnvironment().getImage()
: project.getEnvironment().getImage();
boolean privileged = (project.getEnvironment() != null
&& Boolean.TRUE.equals(project.getEnvironment().getPrivilegedMode()))
|| (build.getEnvironment() != null
&& Boolean.TRUE.equals(build.getEnvironment().getPrivilegedMode()));
Map<String, Object> logsMap = new java.util.HashMap<>();
logsMap.put("groupName", logGroup);
logsMap.put("streamName", logStream);
logsMap.put("cloudWatchLogsArn", "arn:aws:logs:" + region + ":" + config.defaultAccountId()
+ ":log-group:" + logGroup + ":log-stream:" + logStream);
build.setLogs(logsMap);
List<String> envList = buildEnvList(region, build, project, buildspec, logStream);
// Create the working directory inside the container as part of startup,
// then keep the container alive. No bind mount needed — source and
// artifacts are transferred with docker cp.
ContainerSpec spec = containerBuilder.newContainer(image)
.withCmd(List.of("sh", "-c",
"mkdir -p /codebuild/output/src/src && tail -f /dev/null"))
.withEnv(envList)
.withDockerNetwork(config.services().codebuild().dockerNetwork())
.withEmbeddedDns()
.withHostDockerInternalOnLinux()
.withPrivileged(privileged)
.withLogRotation()
.build();
ContainerLifecycleManager.ContainerInfo info = lifecycleManager.createAndStart(spec);
containerId = info.containerId();
runningContainers.put(buildId, containerId);
logHandle = logStreamer.attach(containerId, logGroup, logStream, region, "codebuild:" + buildId);
// Copy downloaded source files into the container (no-op for NO_SOURCE builds)
copySourceToContainer(containerId, workspace, "/codebuild/output/src/src");
String containerSrcDir = "/codebuild/output/src/src";
int timeoutMinutes = build.getTimeoutInMinutes() != null ? build.getTimeoutInMinutes() : 60;
boolean buildFailed = false;
// INSTALL
if (stopFlag.get()) { finishStopped(build); return; }
beginPhase(build, "INSTALL");
build.setCurrentPhase("INSTALL");
PhaseResult installResult = runPhase(containerId, containerSrcDir, envList,
buildspec.installCommands(), timeoutMinutes, stopFlag);
if (installResult.stopped()) { finishStopped(build); return; }
if (installResult.failed()) {
completePhaseWithError(build, "INSTALL", "FAILED", installResult.errorMessage());
buildFailed = true;
} else {
completePhase(build, "INSTALL", "SUCCEEDED");
}
// PRE_BUILD
if (!buildFailed) {
if (stopFlag.get()) { finishStopped(build); return; }
beginPhase(build, "PRE_BUILD");
build.setCurrentPhase("PRE_BUILD");
PhaseResult preBuildResult = runPhase(containerId, containerSrcDir, envList,
buildspec.preBuildCommands(), timeoutMinutes, stopFlag);
if (preBuildResult.stopped()) { finishStopped(build); return; }
if (preBuildResult.failed()) {
completePhaseWithError(build, "PRE_BUILD", "FAILED", preBuildResult.errorMessage());
buildFailed = true;
} else {
completePhase(build, "PRE_BUILD", "SUCCEEDED");
}
} else {
skipPhase(build, "PRE_BUILD");
}
// BUILD
if (!buildFailed) {
if (stopFlag.get()) { finishStopped(build); return; }
beginPhase(build, "BUILD");
build.setCurrentPhase("BUILD");
PhaseResult buildResult = runPhase(containerId, containerSrcDir, envList,
buildspec.buildCommands(), timeoutMinutes, stopFlag);
if (buildResult.stopped()) { finishStopped(build); return; }
if (buildResult.failed()) {
completePhaseWithError(build, "BUILD", "FAILED", buildResult.errorMessage());
buildFailed = true;
} else {
completePhase(build, "BUILD", "SUCCEEDED");
}
} else {
skipPhase(build, "BUILD");
}
// POST_BUILD — always runs unless container was killed
if (stopFlag.get()) { finishStopped(build); return; }
beginPhase(build, "POST_BUILD");
build.setCurrentPhase("POST_BUILD");
PhaseResult postBuildResult = runPhase(containerId, containerSrcDir, envList,
buildspec.postBuildCommands(), timeoutMinutes, stopFlag);
if (postBuildResult.stopped()) { finishStopped(build); return; }
if (postBuildResult.failed()) {
completePhaseWithError(build, "POST_BUILD", "FAILED", postBuildResult.errorMessage());
buildFailed = true;
} else {
completePhase(build, "POST_BUILD", "SUCCEEDED");
}
// UPLOAD_ARTIFACTS
beginPhase(build, "UPLOAD_ARTIFACTS");
build.setCurrentPhase("UPLOAD_ARTIFACTS");
try {
// Pull the working directory out of the container into the local workspace,
// then upload matching files to S3. This works regardless of whether Floci
// itself is running inside a container.
copyArtifactsFromContainer(containerId, containerSrcDir, workspace);
uploadArtifacts(region, build, project, buildspec.artifacts(), workspace);
completePhase(build, "UPLOAD_ARTIFACTS", "SUCCEEDED");
} catch (Exception e) {
LOG.warnv("Artifact upload failed for build {0}: {1}", buildId, e.getMessage());
completePhaseWithError(build, "UPLOAD_ARTIFACTS", "FAILED", e.getMessage());
}
// FINALIZING
beginPhase(build, "FINALIZING");
build.setCurrentPhase("FINALIZING");
completePhase(build, "FINALIZING", "SUCCEEDED");
// COMPLETED
beginPhase(build, "COMPLETED");
build.setCurrentPhase("COMPLETED");
completePhase(build, "COMPLETED", buildFailed ? "FAILED" : "SUCCEEDED");
build.setEndTime(System.currentTimeMillis() / 1000.0);
build.setBuildComplete(true);
build.setBuildStatus(buildFailed ? "FAILED" : "SUCCEEDED");
} catch (Exception e) {
LOG.error("Unexpected error in build " + build.getId(), e);
build.setEndTime(System.currentTimeMillis() / 1000.0);
build.setBuildComplete(true);
build.setBuildStatus("FAULT");
build.setCurrentPhase("COMPLETED");
} finally {
stopFlags.remove(buildId);
if (containerId != null) {
runningContainers.remove(buildId);
if (logHandle != null) {
try { logHandle.close(); } catch (Exception ignored) {}
}
lifecycleManager.stopAndRemove(containerId, null);
}
if (workspace != null) {
deleteDirectory(workspace);
}
}
}
private String resolveAndAcquireSource(String region, Build build, Project project,
String buildspecOverride, Path workspace) throws IOException {
String sourceType = project.getSource() != null ? project.getSource().getType() : "NO_SOURCE";
if ("S3".equals(sourceType) && project.getSource().getLocation() != null) {
String location = project.getSource().getLocation();
int slash = location.indexOf('/');
if (slash > 0) {
String bucket = location.substring(0, slash);
String key = location.substring(slash + 1);
try {
S3Object obj = s3Service.getObject(bucket, key);
if (obj != null && obj.getData() != null) {
extractZip(obj.getData(), workspace);
}
} catch (Exception e) {
LOG.warnv("Could not acquire S3 source {0}: {1}", location, e.getMessage());
}
}
}
if (buildspecOverride != null && !buildspecOverride.isBlank()) {
return buildspecOverride;
}
if (project.getSource() != null && project.getSource().getBuildspec() != null
&& !project.getSource().getBuildspec().isBlank()) {
return project.getSource().getBuildspec();
}
Path yml = workspace.resolve("buildspec.yml");
if (Files.exists(yml)) {
return Files.readString(yml);
}
Path yaml = workspace.resolve("buildspec.yaml");
if (Files.exists(yaml)) {
return Files.readString(yaml);
}
throw new AwsException("InvalidInputException", "No buildspec found in source or request", 400);
}
private List<String> buildEnvList(String region, Build build, Project project,
ParsedBuildspec buildspec, String logStream) {
Map<String, String> env = new LinkedHashMap<>();
env.put("CODEBUILD_BUILD_ID", build.getId());
env.put("CODEBUILD_BUILD_ARN", build.getArn());
env.put("CODEBUILD_BUILD_NUMBER", String.valueOf(build.getBuildNumber()));
env.put("CODEBUILD_BUILD_IMAGE", build.getEnvironment() != null && build.getEnvironment().getImage() != null
? build.getEnvironment().getImage() : project.getEnvironment().getImage());
env.put("CODEBUILD_INITIATOR", "user");
env.put("CODEBUILD_SRC_DIR", "/codebuild/output/src/src");
env.put("CODEBUILD_LOG_PATH", logStream);
env.put("AWS_DEFAULT_REGION", region);
env.put("AWS_REGION", region);
env.put("AWS_ACCESS_KEY_ID", "test");
env.put("AWS_SECRET_ACCESS_KEY", "test");
env.put("AWS_ENDPOINT_URL", resolveEndpointUrl());
env.putAll(buildspec.envVariables());
for (Map.Entry<String, String> e : buildspec.parameterStoreVars().entrySet()) {
try {
Parameter p = ssmService.getParameter(e.getValue(), region);
env.put(e.getKey(), p.getValue());
} catch (Exception ex) {
LOG.debugv("Could not resolve SSM parameter {0}: {1}", e.getValue(), ex.getMessage());
}
}
for (Map.Entry<String, String> e : buildspec.secretsManagerVars().entrySet()) {
try {
SecretVersion sv = secretsManagerService.getSecretValue(e.getValue(), null, null, region);
env.put(e.getKey(), sv.getSecretString() != null ? sv.getSecretString() : "");
} catch (Exception ex) {
LOG.debugv("Could not resolve secret {0}: {1}", e.getValue(), ex.getMessage());
}
}
if (project.getEnvironment() != null && project.getEnvironment().getEnvironmentVariables() != null) {
for (Map<String, String> v : project.getEnvironment().getEnvironmentVariables()) {
String name = v.get("name");
String value = v.get("value");
if (name != null) { env.put(name, value != null ? value : ""); }
}
}
if (build.getEnvironment() != null && build.getEnvironment().getEnvironmentVariables() != null) {
for (Map<String, String> v : build.getEnvironment().getEnvironmentVariables()) {
String name = v.get("name");
String value = v.get("value");
if (name != null) { env.put(name, value != null ? value : ""); }
}
}
List<String> result = new ArrayList<>();
env.forEach((k, v) -> result.add(k + "=" + (v != null ? v : "")));
return result;
}
private String resolveEndpointUrl() {
if (containerDetector.isRunningInContainer()) {
String suffix = config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX);
return "http://" + suffix + ":" + config.port();
} else {
return "http://host.docker.internal:" + config.port();
}
}
// Copies files from the local workspace into the container's working directory.
// Skips silently when the workspace is empty (e.g. NO_SOURCE builds).
private void copySourceToContainer(String containerId, Path sourceDir, String remotePath) {
try {
if (!Files.exists(sourceDir)) return;
boolean hasFiles;
try (var ls = Files.list(sourceDir)) {
hasFiles = ls.findAny().isPresent();
}
if (!hasFiles) return;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
createTarFromDir(sourceDir, bos);
dockerClient.copyArchiveToContainerCmd(containerId)
.withRemotePath(remotePath)
.withTarInputStream(new ByteArrayInputStream(bos.toByteArray()))
.exec();
} catch (Exception e) {
LOG.warnv("Could not copy source to container {0}: {1}", containerId, e.getMessage());
}
}
// Pulls the container's working directory back into the local workspace so
// uploadArtifacts can read the build outputs. Docker cp adds the last path
// component as a top-level directory in the tar; we strip it on extraction.
private void copyArtifactsFromContainer(String containerId, String containerPath, Path destDir)
throws IOException {
try (InputStream tarStream = dockerClient.copyArchiveFromContainerCmd(containerId, containerPath).exec();
TarArchiveInputStream tar = new TarArchiveInputStream(tarStream)) {
String stripPrefix = null;
TarArchiveEntry entry;
while ((entry = tar.getNextEntry()) != null) {
if (!tar.canReadEntryData(entry)) continue;
String name = entry.getName();
if (stripPrefix == null) {
if (entry.isDirectory()) {
stripPrefix = name.endsWith("/") ? name : name + "/";
continue;
} else {
stripPrefix = "";
}
}
if (!stripPrefix.isEmpty() && name.startsWith(stripPrefix)) {
name = name.substring(stripPrefix.length());
}
if (name.isEmpty()) continue;
Path target = destDir.resolve(name).normalize();
if (!target.startsWith(destDir)) continue; // path traversal
if (entry.isDirectory()) {
Files.createDirectories(target);
} else {
Files.createDirectories(target.getParent());
Files.write(target, tar.readAllBytes());
}
}
} catch (Exception e) {
LOG.warnv("Could not copy artifacts from container {0}: {1}", containerId, e.getMessage());
}
}
private void createTarFromDir(Path dir, ByteArrayOutputStream out) throws IOException {
try (TarArchiveOutputStream tar = newTarStream(out);
var stream = Files.walk(dir)) {
for (Path path : (Iterable<Path>) stream::iterator) {
if (path.equals(dir)) continue;
String entryName = dir.relativize(path).toString();
if (Files.isDirectory(path)) {
TarArchiveEntry entry = new TarArchiveEntry(entryName + "/");
tar.putArchiveEntry(entry);
tar.closeArchiveEntry();
} else {
TarArchiveEntry entry = new TarArchiveEntry(entryName);
entry.setSize(Files.size(path));
entry.setMode(0644);
tar.putArchiveEntry(entry);
try (var fis = Files.newInputStream(path)) {
fis.transferTo(tar);
}
tar.closeArchiveEntry();
}
}
}
}
private static TarArchiveOutputStream newTarStream(ByteArrayOutputStream out) {
TarArchiveOutputStream tar = new TarArchiveOutputStream(out);
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
tar.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
return tar;
}
private PhaseResult runPhase(String containerId, String workDir, List<String> env,
List<String> commands, int timeoutMinutes, AtomicBoolean stopFlag) {
if (commands.isEmpty()) {
return PhaseResult.ofSuccess();
}
if (stopFlag.get()) {
return PhaseResult.ofStopped();
}
String script = String.join("\n", commands);
String[] cmd = {"sh", "-e", "-c", script};
try {
String execId = dockerClient.execCreateCmd(containerId)
.withCmd(cmd)
.withWorkingDir(workDir)
.withEnv(env)
.withAttachStdout(true)
.withAttachStderr(true)
.exec()
.getId();
CountDownLatch latch = new CountDownLatch(1);
ByteArrayOutputStream outputCapture = new ByteArrayOutputStream();
dockerClient.execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
if (frame.getPayload() != null) {
try { outputCapture.write(frame.getPayload()); } catch (IOException ignored) {}
}
}
@Override
public void onComplete() { latch.countDown(); }
@Override
public void onError(Throwable t) { latch.countDown(); }
});
boolean completed = latch.await(timeoutMinutes, TimeUnit.MINUTES);
if (!completed) {
return PhaseResult.ofFailure("Phase timed out after " + timeoutMinutes + " minutes");
}
if (stopFlag.get()) {
return PhaseResult.ofStopped();
}
Long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
if (exitCode != null && exitCode != 0) {
String output = outputCapture.toString(StandardCharsets.UTF_8);
String msg = "Exit code " + exitCode;
if (!output.isBlank()) {
int start = Math.max(0, output.length() - 512);
msg += ": " + output.stripTrailing().substring(start);
}
return PhaseResult.ofFailure(msg);
}
return PhaseResult.ofSuccess();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return PhaseResult.ofStopped();
} catch (Exception e) {
if (stopFlag.get()) {
return PhaseResult.ofStopped();
}
return PhaseResult.ofFailure(e.getMessage());
}
}
private void uploadArtifacts(String region, Build build, Project project,
ParsedArtifacts artifacts, Path workspace) throws IOException {
String type = artifacts.type();
if ("NO_ARTIFACTS".equals(type) && project.getArtifacts() != null) {
type = project.getArtifacts().getType();
}
if (type == null || "NO_ARTIFACTS".equals(type) || "CODEPIPELINE".equals(type)) {
return;
}
if (!"S3".equals(type)) {
return;
}
String packaging = artifacts.packaging();
if ("ZIP".equals(packaging) && project.getArtifacts() != null
&& project.getArtifacts().getPackaging() != null) {
packaging = project.getArtifacts().getPackaging();
}
String location = project.getArtifacts() != null ? project.getArtifacts().getLocation() : null;
if (location == null || location.isBlank()) {
return;
}
List<String> filePatterns = artifacts.files();
if (filePatterns.isEmpty()) {
return;
}
Path baseDir = workspace;
if (artifacts.baseDirectory() != null) {
baseDir = workspace.resolve(artifacts.baseDirectory());
}
List<Path> matchedFiles = collectFiles(baseDir, filePatterns);
if (matchedFiles.isEmpty()) {
LOG.warnv("No artifact files matched patterns {0} in {1} for build {2}",
filePatterns, baseDir, build.getId());
return;
}
int slash = location.indexOf('/');
String bucket = slash > 0 ? location.substring(0, slash) : location;
String prefix = slash > 0 ? location.substring(slash + 1) : "";
String artifactName = artifacts.name() != null ? artifacts.name()
: project.getName() + "-" + build.getBuildNumber();
boolean isNone = "NONE".equalsIgnoreCase(packaging);
if (isNone) {
for (Path file : matchedFiles) {
String relative = artifacts.discardPaths()
? file.getFileName().toString()
: baseDir.relativize(file).toString();
String key = prefix.isBlank() ? relative : prefix + "/" + relative;
byte[] data = Files.readAllBytes(file);
String contentType = guessContentType(file.getFileName().toString());
s3Service.putObject(bucket, key, data, contentType, Map.of());
}
} else {
String key = prefix.isBlank() ? artifactName + ".zip" : prefix + "/" + artifactName + ".zip";
byte[] zipBytes = zipFiles(baseDir, matchedFiles, artifacts.discardPaths());
s3Service.putObject(bucket, key, zipBytes, "application/zip", Map.of());
}
}
private List<Path> collectFiles(Path baseDir, List<String> patterns) throws IOException {
List<Path> result = new ArrayList<>();
if (!Files.exists(baseDir)) {
LOG.warnv("Artifact base directory does not exist: {0}", baseDir);
return result;
}
for (String pattern : patterns) {
if ("**/*".equals(pattern) || "**".equals(pattern)) {
try (var stream = Files.walk(baseDir)) {
stream.filter(Files::isRegularFile).forEach(result::add);
}
} else if (!pattern.contains("*") && !pattern.contains("?")
&& !pattern.contains("{") && !pattern.contains("[")) {
// Plain filename — resolve directly instead of using PathMatcher
Path direct = baseDir.resolve(pattern);
if (Files.isRegularFile(direct)) {
result.add(direct);
} else {
LOG.warnv("Artifact file not found: {0}", direct);
}
} else {
var matcher = baseDir.getFileSystem().getPathMatcher("glob:" + pattern);
try (var stream = Files.walk(baseDir)) {
stream.filter(Files::isRegularFile)
.filter(p -> matcher.matches(baseDir.relativize(p)))
.forEach(result::add);
}
}
}
return result;
}
private byte[] zipFiles(Path baseDir, List<Path> files, boolean discardPaths) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(bos)) {
for (Path file : files) {
String entryName = discardPaths ? file.getFileName().toString()
: baseDir.relativize(file).toString();
zos.putNextEntry(new ZipEntry(entryName));
zos.write(Files.readAllBytes(file));
zos.closeEntry();
}
}
return bos.toByteArray();
}
private void extractZip(byte[] data, Path dest) throws IOException {
try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(data))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
Path target = dest.resolve(entry.getName()).normalize();
if (!target.startsWith(dest)) {
continue; // zip slip protection
}
if (entry.isDirectory()) {
Files.createDirectories(target);
} else {
Files.createDirectories(target.getParent());
Files.write(target, zis.readAllBytes());
}
zis.closeEntry();
}
}
}
private void beginPhase(Build build, String phaseType) {
BuildPhase phase = new BuildPhase();
phase.setPhaseType(phaseType);
phase.setPhaseStatus("IN_PROGRESS");
phase.setStartTime(System.currentTimeMillis() / 1000.0);
build.getPhases().add(phase);
build.setCurrentPhase(phaseType);
}
private void completePhase(Build build, String phaseType, String status) {
findPhase(build, phaseType).ifPresent(p -> {
double end = System.currentTimeMillis() / 1000.0;
p.setPhaseStatus(status);
p.setEndTime(end);
p.setDurationInSeconds(Math.round(end - p.getStartTime()));
});
}
private void completePhaseWithError(Build build, String phaseType, String status, String message) {
findPhase(build, phaseType).ifPresent(p -> {
double end = System.currentTimeMillis() / 1000.0;
p.setPhaseStatus(status);
p.setEndTime(end);
p.setDurationInSeconds(Math.round(end - p.getStartTime()));
if (message != null) {
String truncated = message.substring(0, Math.min(message.length(), 1024));
p.setContexts(List.of(Map.of("statusCode", "COMMAND_EXECUTION_ERROR", "message", truncated)));
}
});
}
private void skipPhase(Build build, String phaseType) {
BuildPhase phase = new BuildPhase();
phase.setPhaseType(phaseType);
phase.setPhaseStatus("SUCCEEDED");
double now = System.currentTimeMillis() / 1000.0;
phase.setStartTime(now);
phase.setEndTime(now);
phase.setDurationInSeconds(0L);
build.getPhases().add(phase);
}
private void finishStopped(Build build) {
build.setEndTime(System.currentTimeMillis() / 1000.0);
build.setBuildComplete(true);
build.setBuildStatus("STOPPED");
build.setCurrentPhase("COMPLETED");
}
private void finishFailed(Build build) {
build.setEndTime(System.currentTimeMillis() / 1000.0);
build.setBuildComplete(true);
build.setBuildStatus("FAILED");
build.setCurrentPhase("COMPLETED");
}
private Optional<BuildPhase> findPhase(Build build, String phaseType) {
return build.getPhases().stream()
.filter(p -> phaseType.equals(p.getPhaseType()))
.findFirst();
}
private void deleteDirectory(Path path) {
try {
if (!Files.exists(path)) { return; }
Files.walk(path).sorted(Comparator.reverseOrder()).forEach(p -> {
try { Files.delete(p); } catch (Exception ignored) {}
});
} catch (Exception e) {
LOG.debugv("Could not delete workspace {0}: {1}", path, e.getMessage());
}
}
private static String guessContentType(String filename) {
if (filename.endsWith(".json")) { return "application/json"; }
if (filename.endsWith(".xml")) { return "application/xml"; }
if (filename.endsWith(".html")) { return "text/html"; }
return "text/plain";
}
private enum PhaseStatus { SUCCEEDED, FAILED, STOPPED }
private record PhaseResult(PhaseStatus status, String errorMessage) {
boolean succeeded() { return status == PhaseStatus.SUCCEEDED; }
boolean failed() { return status == PhaseStatus.FAILED; }
boolean stopped() { return status == PhaseStatus.STOPPED; }
static PhaseResult ofSuccess() { return new PhaseResult(PhaseStatus.SUCCEEDED, null); }
static PhaseResult ofFailure(String msg) { return new PhaseResult(PhaseStatus.FAILED, msg); }
static PhaseResult ofStopped() { return new PhaseResult(PhaseStatus.STOPPED, null); }
}
}
@@ -1,6 +1,9 @@
package io.github.hectorvent.floci.services.codebuild;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.codebuild.model.Build;
import io.github.hectorvent.floci.services.codebuild.model.BuildPhase;
import io.github.hectorvent.floci.services.codebuild.model.Project;
import io.github.hectorvent.floci.services.codebuild.model.ProjectArtifacts;
import io.github.hectorvent.floci.services.codebuild.model.ProjectEnvironment;
@@ -8,6 +11,7 @@ import io.github.hectorvent.floci.services.codebuild.model.ProjectSource;
import io.github.hectorvent.floci.services.codebuild.model.ReportGroup;
import io.github.hectorvent.floci.services.codebuild.model.SourceCredential;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Instant;
import java.util.ArrayList;
@@ -15,6 +19,8 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
@ApplicationScoped
@@ -26,6 +32,19 @@ public class CodeBuildService {
private final ConcurrentHashMap<String, ConcurrentHashMap<String, ReportGroup>> reportGroups = new ConcurrentHashMap<>();
// key: region -> arn -> source credential (token is stored but never returned)
private final ConcurrentHashMap<String, ConcurrentHashMap<String, SourceCredential>> sourceCredentials = new ConcurrentHashMap<>();
// key: region -> buildId -> build
private final ConcurrentHashMap<String, ConcurrentHashMap<String, Build>> builds = new ConcurrentHashMap<>();
// key: region:projectName -> build counter
private final ConcurrentHashMap<String, AtomicLong> buildCounters = new ConcurrentHashMap<>();
private final CodeBuildRunner runner;
private final EmulatorConfig config;
@Inject
public CodeBuildService(CodeBuildRunner runner, EmulatorConfig config) {
this.runner = runner;
this.config = config;
}
private Map<String, Project> projectsFor(String region) {
return projects.computeIfAbsent(region, r -> new ConcurrentHashMap<>());
@@ -39,6 +58,10 @@ public class CodeBuildService {
return sourceCredentials.computeIfAbsent(region, r -> new ConcurrentHashMap<>());
}
private Map<String, Build> buildsFor(String region) {
return builds.computeIfAbsent(region, r -> new ConcurrentHashMap<>());
}
// ---- Projects ----
public Project createProject(String region, String account,
@@ -315,4 +338,115 @@ public class CodeBuildService {
"Project name must be between 2 and 150 characters", 400);
}
}
// ---- Builds ----
public Build startBuild(String region, String account, String projectName,
String buildspecOverride,
ProjectEnvironment environmentOverride,
ProjectArtifacts artifactsOverride,
String sourceVersion,
Integer timeoutOverride,
String imageOverride,
String computeTypeOverride) {
Project project = projectsFor(region).get(projectName);
if (project == null) {
throw new AwsException("ResourceNotFoundException", "Project not found: " + projectName, 400);
}
String counterKey = region + ":" + projectName;
long buildNumber = buildCounters
.computeIfAbsent(counterKey, k -> new AtomicLong(0))
.incrementAndGet();
String buildId = projectName + ":" + buildNumber;
String arn = "arn:aws:codebuild:" + region + ":" + account + ":build/" + buildId;
Build build = new Build();
build.setId(buildId);
build.setArn(arn);
build.setBuildNumber(buildNumber);
build.setBuildStatus("IN_PROGRESS");
build.setBuildComplete(false);
build.setCurrentPhase("SUBMITTED");
build.setProjectName(projectName);
build.setInitiator("user");
build.setStartTime(Instant.now().toEpochMilli() / 1000.0);
build.setSource(project.getSource());
build.setArtifacts(artifactsOverride != null ? artifactsOverride : project.getArtifacts());
build.setTimeoutInMinutes(timeoutOverride != null ? timeoutOverride : project.getTimeoutInMinutes());
build.setQueuedTimeoutInMinutes(project.getQueuedTimeoutInMinutes());
build.setEncryptionKey(project.getEncryptionKey());
ProjectEnvironment env = environmentOverride != null ? environmentOverride : project.getEnvironment();
if (imageOverride != null || computeTypeOverride != null) {
ProjectEnvironment merged = new ProjectEnvironment();
merged.setType(env != null ? env.getType() : null);
merged.setImage(imageOverride != null ? imageOverride : (env != null ? env.getImage() : null));
merged.setComputeType(computeTypeOverride != null ? computeTypeOverride : (env != null ? env.getComputeType() : null));
merged.setEnvironmentVariables(env != null ? env.getEnvironmentVariables() : null);
merged.setPrivilegedMode(env != null ? env.getPrivilegedMode() : null);
build.setEnvironment(merged);
} else {
build.setEnvironment(env);
}
build.setPhases(new CopyOnWriteArrayList<>());
buildsFor(region).put(buildId, build);
runner.startBuild(region, build, project, buildspecOverride);
return build;
}
public Build getBuild(String region, String buildId) {
Build build = buildsFor(region).get(buildId);
if (build == null) {
throw new AwsException("ResourceNotFoundException", "Build not found: " + buildId, 400);
}
return build;
}
public List<Build> batchGetBuilds(String region, List<String> buildIds) {
Map<String, Build> store = buildsFor(region);
return buildIds.stream()
.map(store::get)
.filter(b -> b != null)
.collect(Collectors.toList());
}
public List<String> listBuilds(String region) {
return buildsFor(region).values().stream()
.sorted((a, b) -> Double.compare(
b.getStartTime() != null ? b.getStartTime() : 0,
a.getStartTime() != null ? a.getStartTime() : 0))
.map(Build::getId)
.collect(Collectors.toList());
}
public List<String> listBuildsForProject(String region, String projectName) {
return buildsFor(region).values().stream()
.filter(b -> projectName.equals(b.getProjectName()))
.sorted((a, b) -> Double.compare(
b.getStartTime() != null ? b.getStartTime() : 0,
a.getStartTime() != null ? a.getStartTime() : 0))
.map(Build::getId)
.collect(Collectors.toList());
}
public void stopBuild(String region, String buildId) {
Build build = buildsFor(region).get(buildId);
if (build == null) {
throw new AwsException("ResourceNotFoundException", "Build not found: " + buildId, 400);
}
runner.stopBuild(buildId);
}
public Build retryBuild(String region, String account, String buildId) {
Build original = getBuild(region, buildId);
return startBuild(region, account, original.getProjectName(),
null, original.getEnvironment(), original.getArtifacts(),
null, original.getTimeoutInMinutes(), null, null);
}
}
@@ -0,0 +1,86 @@
package io.github.hectorvent.floci.services.codebuild.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Build {
public Build() {}
private String id;
private String arn;
private Long buildNumber;
private String buildStatus;
private Boolean buildComplete;
private String currentPhase;
private String projectName;
private String initiator;
private Double startTime;
private Double endTime;
private ProjectSource source;
private ProjectArtifacts artifacts;
private ProjectEnvironment environment;
private Map<String, Object> logs;
private List<BuildPhase> phases;
private Integer timeoutInMinutes;
private Integer queuedTimeoutInMinutes;
private String encryptionKey;
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public Long getBuildNumber() { return buildNumber; }
public void setBuildNumber(Long buildNumber) { this.buildNumber = buildNumber; }
public String getBuildStatus() { return buildStatus; }
public void setBuildStatus(String buildStatus) { this.buildStatus = buildStatus; }
public Boolean getBuildComplete() { return buildComplete; }
public void setBuildComplete(Boolean buildComplete) { this.buildComplete = buildComplete; }
public String getCurrentPhase() { return currentPhase; }
public void setCurrentPhase(String currentPhase) { this.currentPhase = currentPhase; }
public String getProjectName() { return projectName; }
public void setProjectName(String projectName) { this.projectName = projectName; }
public String getInitiator() { return initiator; }
public void setInitiator(String initiator) { this.initiator = initiator; }
public Double getStartTime() { return startTime; }
public void setStartTime(Double startTime) { this.startTime = startTime; }
public Double getEndTime() { return endTime; }
public void setEndTime(Double endTime) { this.endTime = endTime; }
public ProjectSource getSource() { return source; }
public void setSource(ProjectSource source) { this.source = source; }
public ProjectArtifacts getArtifacts() { return artifacts; }
public void setArtifacts(ProjectArtifacts artifacts) { this.artifacts = artifacts; }
public ProjectEnvironment getEnvironment() { return environment; }
public void setEnvironment(ProjectEnvironment environment) { this.environment = environment; }
public Map<String, Object> getLogs() { return logs; }
public void setLogs(Map<String, Object> logs) { this.logs = logs; }
public List<BuildPhase> getPhases() { return phases; }
public void setPhases(List<BuildPhase> phases) { this.phases = phases; }
public Integer getTimeoutInMinutes() { return timeoutInMinutes; }
public void setTimeoutInMinutes(Integer timeoutInMinutes) { this.timeoutInMinutes = timeoutInMinutes; }
public Integer getQueuedTimeoutInMinutes() { return queuedTimeoutInMinutes; }
public void setQueuedTimeoutInMinutes(Integer queuedTimeoutInMinutes) { this.queuedTimeoutInMinutes = queuedTimeoutInMinutes; }
public String getEncryptionKey() { return encryptionKey; }
public void setEncryptionKey(String encryptionKey) { this.encryptionKey = encryptionKey; }
}
@@ -0,0 +1,38 @@
package io.github.hectorvent.floci.services.codebuild.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BuildPhase {
public BuildPhase() {}
private String phaseType;
private String phaseStatus;
private Double startTime;
private Double endTime;
private Long durationInSeconds;
private List<Map<String, String>> contexts;
public String getPhaseType() { return phaseType; }
public void setPhaseType(String phaseType) { this.phaseType = phaseType; }
public String getPhaseStatus() { return phaseStatus; }
public void setPhaseStatus(String phaseStatus) { this.phaseStatus = phaseStatus; }
public Double getStartTime() { return startTime; }
public void setStartTime(Double startTime) { this.startTime = startTime; }
public Double getEndTime() { return endTime; }
public void setEndTime(Double endTime) { this.endTime = endTime; }
public Long getDurationInSeconds() { return durationInSeconds; }
public void setDurationInSeconds(Long durationInSeconds) { this.durationInSeconds = durationInSeconds; }
public List<Map<String, String>> getContexts() { return contexts; }
public void setContexts(List<Map<String, String>> contexts) { this.contexts = contexts; }
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.codedeploy.model.Application;
import io.github.hectorvent.floci.services.codedeploy.model.Deployment;
import io.github.hectorvent.floci.services.codedeploy.model.DeploymentConfig;
import io.github.hectorvent.floci.services.codedeploy.model.DeploymentGroup;
import jakarta.enterprise.context.ApplicationScoped;
@@ -48,6 +49,15 @@ public class CodeDeployJsonHandler {
case "TagResource" -> tagResource(request);
case "UntagResource" -> untagResource(request);
case "ListTagsForResource" -> listTagsForResource(request);
case "CreateDeployment" -> createDeployment(request, region);
case "GetDeployment" -> getDeployment(request, region);
case "ListDeployments" -> listDeployments(request, region);
case "StopDeployment" -> stopDeployment(request, region);
case "ContinueDeployment" -> Response.ok(Map.of()).build();
case "BatchGetDeployments" -> batchGetDeployments(request, region);
case "ListDeploymentTargets" -> listDeploymentTargets(request, region);
case "BatchGetDeploymentTargets" -> batchGetDeploymentTargets(request, region);
case "PutLifecycleEventHookExecutionStatus" -> putLifecycleEventHookExecutionStatus(request);
case "AddTagsToOnPremisesInstances", "RemoveTagsFromOnPremisesInstances" ->
Response.ok(Map.of()).build();
default -> throw new AwsException("InvalidAction", "Action " + action + " is not supported", 400);
@@ -196,6 +206,67 @@ public class CodeDeployJsonHandler {
return Response.ok(Map.of("Tags", tags)).build();
}
private Response createDeployment(JsonNode req, String region) throws Exception {
String appName = req.path("applicationName").asText(null);
String groupName = req.path("deploymentGroupName").asText(null);
String configName = req.has("deploymentConfigName") ? req.path("deploymentConfigName").asText() : null;
String description = req.has("description") ? req.path("description").asText() : null;
Map<String, Object> revision = req.has("revision")
? mapper.treeToValue(req.get("revision"), Map.class) : null;
String deploymentId = service.createDeployment(region, appName, groupName, configName, revision, description);
return Response.ok(Map.of("deploymentId", deploymentId)).build();
}
private Response getDeployment(JsonNode req, String region) {
String id = req.path("deploymentId").asText(null);
Deployment d = service.getDeployment(region, id);
return Response.ok(Map.of("deploymentInfo", d)).build();
}
private Response listDeployments(JsonNode req, String region) {
String appName = req.has("applicationName") ? req.path("applicationName").asText() : null;
String groupName = req.has("deploymentGroupName") ? req.path("deploymentGroupName").asText() : null;
List<String> statuses = new ArrayList<>();
req.path("includeOnlyStatuses").forEach(n -> statuses.add(n.asText()));
List<String> ids = service.listDeployments(region, appName, groupName, statuses);
return Response.ok(Map.of("deployments", ids)).build();
}
private Response stopDeployment(JsonNode req, String region) {
String id = req.path("deploymentId").asText(null);
Map<String, String> result = service.stopDeployment(region, id);
return Response.ok(result).build();
}
private Response batchGetDeployments(JsonNode req, String region) {
List<String> ids = new ArrayList<>();
req.path("deploymentIds").forEach(n -> ids.add(n.asText()));
List<Deployment> deploymentList = service.batchGetDeployments(region, ids);
return Response.ok(Map.of("deploymentsInfo", deploymentList)).build();
}
private Response listDeploymentTargets(JsonNode req, String region) {
String deploymentId = req.path("deploymentId").asText(null);
List<String> targetIds = service.listDeploymentTargets(region, deploymentId);
return Response.ok(Map.of("targetIds", targetIds)).build();
}
private Response batchGetDeploymentTargets(JsonNode req, String region) {
String deploymentId = req.path("deploymentId").asText(null);
List<String> targetIds = new ArrayList<>();
req.path("targetIds").forEach(n -> targetIds.add(n.asText()));
List<Map<String, Object>> targets = service.batchGetDeploymentTargets(region, deploymentId, targetIds);
return Response.ok(Map.of("deploymentTargets", targets)).build();
}
private Response putLifecycleEventHookExecutionStatus(JsonNode req) {
String deploymentId = req.path("deploymentId").asText(null);
String executionId = req.path("lifecycleEventHookExecutionId").asText(null);
String status = req.path("status").asText("Succeeded");
String id = service.putLifecycleEventHookExecutionStatus(deploymentId, executionId, status);
return Response.ok(Map.of("lifecycleEventHookExecutionId", id)).build();
}
@SuppressWarnings("unchecked")
private Map<String, Object> extractGroupFields(JsonNode req) throws Exception {
Map<String, Object> fields = new HashMap<>();
@@ -1,10 +1,18 @@
package io.github.hectorvent.floci.services.codedeploy;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.codedeploy.model.Application;
import io.github.hectorvent.floci.services.codedeploy.model.Deployment;
import io.github.hectorvent.floci.services.codedeploy.model.DeploymentConfig;
import io.github.hectorvent.floci.services.codedeploy.model.DeploymentGroup;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.ArrayList;
@@ -12,12 +20,27 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
@ApplicationScoped
public class CodeDeployService {
private static final Logger LOG = Logger.getLogger(CodeDeployService.class);
private final LambdaService lambdaService;
private final ObjectMapper mapper;
@Inject
public CodeDeployService(LambdaService lambdaService, ObjectMapper mapper) {
this.lambdaService = lambdaService;
this.mapper = mapper;
}
// key: region -> name -> application
private final ConcurrentHashMap<String, ConcurrentHashMap<String, Application>> applications = new ConcurrentHashMap<>();
// key: region -> appName -> groupName -> group
@@ -26,6 +49,35 @@ public class CodeDeployService {
private final ConcurrentHashMap<String, ConcurrentHashMap<String, DeploymentConfig>> deploymentConfigs = new ConcurrentHashMap<>();
// key: resourceArn -> tags
private final ConcurrentHashMap<String, Map<String, String>> tags = new ConcurrentHashMap<>();
// key: region -> deploymentId -> Deployment
private final ConcurrentHashMap<String, ConcurrentHashMap<String, Deployment>> deployments = new ConcurrentHashMap<>();
// key: region -> deploymentId -> target map (lambdaTarget data)
private final ConcurrentHashMap<String, ConcurrentHashMap<String, Map<String, Object>>> deploymentTargets = new ConcurrentHashMap<>();
// key: lifecycleEventHookExecutionId -> CompletableFuture<status>
private final ConcurrentHashMap<String, CompletableFuture<String>> hookFutures = new ConcurrentHashMap<>();
// key: deploymentId -> stop flag
private final ConcurrentHashMap<String, AtomicBoolean> stopFlags = new ConcurrentHashMap<>();
private static final class AppSpecInfo {
String functionName;
String aliasName;
String currentVersion;
String targetVersion;
String beforeAllowTraffic;
String afterAllowTraffic;
}
private static final class TrafficRoutingInfo {
final String type;
final int percentage;
final int intervalSeconds;
TrafficRoutingInfo(String type, int percentage, int intervalSeconds) {
this.type = type;
this.percentage = percentage;
this.intervalSeconds = intervalSeconds;
}
}
private static final List<String> BUILT_IN_CONFIG_NAMES = List.of(
"CodeDeployDefault.OneAtATime",
@@ -335,6 +387,420 @@ public class CodeDeployService {
return new ArrayList<>(deploymentConfigsFor(region).keySet());
}
// ---- Deployments ----
private Map<String, Deployment> deploymentsFor(String region) {
return deployments.computeIfAbsent(region, r -> new ConcurrentHashMap<>());
}
private Map<String, Map<String, Object>> deploymentTargetsFor(String region) {
return deploymentTargets.computeIfAbsent(region, r -> new ConcurrentHashMap<>());
}
public String createDeployment(String region, String appName, String groupName,
String configName, Map<String, Object> revision, String description) {
getApplication(region, appName);
getDeploymentGroup(region, appName, groupName);
AppSpecInfo appSpec = parseAppSpec(revision);
DeploymentGroup group = getDeploymentGroup(region, appName, groupName);
String effectiveConfig = configName != null ? configName : group.getDeploymentConfigName();
String deploymentId = generateDeploymentId();
double now = Instant.now().toEpochMilli() / 1000.0;
Deployment deployment = new Deployment();
deployment.setDeploymentId(deploymentId);
deployment.setApplicationName(appName);
deployment.setDeploymentGroupName(groupName);
deployment.setDeploymentConfigName(effectiveConfig);
deployment.setStatus("Queued");
deployment.setRevision(revision);
deployment.setCreateTime(now);
deployment.setDescription(description);
deployment.setCreator("user");
deployment.setComputePlatform("Lambda");
deploymentsFor(region).put(deploymentId, deployment);
// Build initial target map
String targetId = appSpec.functionName + ":" + appSpec.aliasName;
String targetArn = "arn:aws:lambda:" + region + ":000000000000:function:" + appSpec.functionName + ":" + appSpec.aliasName;
Map<String, Object> lambdaTargetMap = new ConcurrentHashMap<>();
lambdaTargetMap.put("deploymentId", deploymentId);
lambdaTargetMap.put("targetId", targetId);
lambdaTargetMap.put("targetArn", targetArn);
lambdaTargetMap.put("status", "Pending");
lambdaTargetMap.put("lastUpdatedAt", now);
lambdaTargetMap.put("lifecycleEvents", new CopyOnWriteArrayList<>());
Map<String, Object> targetMap = new ConcurrentHashMap<>();
targetMap.put("deploymentTargetType", "LambdaFunction");
targetMap.put("lambdaTarget", lambdaTargetMap);
deploymentTargetsFor(region).put(deploymentId, targetMap);
AtomicBoolean stopFlag = new AtomicBoolean(false);
stopFlags.put(deploymentId, stopFlag);
String finalEffectiveConfig = effectiveConfig;
Thread.ofVirtual().name("codedeploy-" + deploymentId).start(
() -> runStateMachine(region, deployment, appSpec, lambdaTargetMap, stopFlag, finalEffectiveConfig));
return deploymentId;
}
public Deployment getDeployment(String region, String deploymentId) {
Deployment d = deploymentsFor(region).get(deploymentId);
if (d == null) {
throw new AwsException("DeploymentDoesNotExistException",
"Deployment does not exist: " + deploymentId, 400);
}
return d;
}
public List<String> listDeployments(String region, String appName, String groupName, List<String> statuses) {
return deploymentsFor(region).values().stream()
.filter(d -> appName == null || appName.equals(d.getApplicationName()))
.filter(d -> groupName == null || groupName.equals(d.getDeploymentGroupName()))
.filter(d -> statuses == null || statuses.isEmpty() || statuses.contains(d.getStatus()))
.map(Deployment::getDeploymentId)
.collect(Collectors.toList());
}
public Map<String, String> stopDeployment(String region, String deploymentId) {
Deployment d = getDeployment(region, deploymentId);
String status = d.getStatus();
if ("Succeeded".equals(status) || "Failed".equals(status) || "Stopped".equals(status)) {
return Map.of("status", "Succeeded", "statusMessage", "Deployment is already in a terminal state.");
}
AtomicBoolean flag = stopFlags.get(deploymentId);
if (flag != null) {
flag.set(true);
}
return Map.of("status", "Pending", "statusMessage", "Stop request submitted.");
}
public List<Deployment> batchGetDeployments(String region, List<String> ids) {
Map<String, Deployment> store = deploymentsFor(region);
return ids.stream()
.map(id -> {
Deployment d = store.get(id);
if (d == null) {
throw new AwsException("DeploymentDoesNotExistException",
"Deployment does not exist: " + id, 400);
}
return d;
})
.collect(Collectors.toList());
}
public List<String> listDeploymentTargets(String region, String deploymentId) {
getDeployment(region, deploymentId);
Map<String, Object> target = deploymentTargetsFor(region).get(deploymentId);
if (target == null) {
return List.of();
}
@SuppressWarnings("unchecked")
Map<String, Object> lambdaTarget = (Map<String, Object>) target.get("lambdaTarget");
String targetId = lambdaTarget != null ? (String) lambdaTarget.get("targetId") : null;
return targetId != null ? List.of(targetId) : List.of();
}
public List<Map<String, Object>> batchGetDeploymentTargets(String region, String deploymentId, List<String> targetIds) {
getDeployment(region, deploymentId);
Map<String, Object> target = deploymentTargetsFor(region).get(deploymentId);
if (target == null) {
return List.of();
}
@SuppressWarnings("unchecked")
Map<String, Object> lambdaTarget = (Map<String, Object>) target.get("lambdaTarget");
String targetId = lambdaTarget != null ? (String) lambdaTarget.get("targetId") : null;
if (targetId == null || (!targetIds.isEmpty() && !targetIds.contains(targetId))) {
return List.of();
}
return List.of(target);
}
public String putLifecycleEventHookExecutionStatus(String deploymentId, String executionId, String status) {
CompletableFuture<String> future = hookFutures.get(executionId);
if (future != null && !future.isDone()) {
future.complete(status);
}
return executionId;
}
// ---- Deployment state machine ----
@SuppressWarnings("unchecked")
private AppSpecInfo parseAppSpec(Map<String, Object> revision) {
if (revision == null) {
throw new AwsException("InvalidRevisionException", "Revision is required", 400);
}
Object appSpecContent = revision.get("appSpecContent");
if (!(appSpecContent instanceof Map)) {
throw new AwsException("InvalidRevisionException", "Missing appSpecContent in revision", 400);
}
String content = (String) ((Map<String, Object>) appSpecContent).get("content");
if (content == null || content.isBlank()) {
throw new AwsException("InvalidRevisionException", "Missing content in appSpecContent", 400);
}
AppSpecInfo info = new AppSpecInfo();
try {
JsonNode root = mapper.readTree(content);
JsonNode resources = root.get("Resources");
if (resources != null && resources.isArray() && !resources.isEmpty()) {
JsonNode firstResource = resources.get(0);
if (firstResource.isObject()) {
JsonNode resourceNode = firstResource.fields().next().getValue();
JsonNode props = resourceNode.path("Properties");
info.functionName = props.path("Name").asText(null);
info.aliasName = props.path("Alias").asText(null);
info.currentVersion = props.path("CurrentVersion").asText(null);
info.targetVersion = props.path("TargetVersion").asText(null);
}
}
JsonNode hooks = root.get("Hooks");
if (hooks != null && hooks.isArray()) {
for (JsonNode hook : hooks) {
if (hook.has("BeforeAllowTraffic")) {
info.beforeAllowTraffic = hook.get("BeforeAllowTraffic").asText(null);
}
if (hook.has("AfterAllowTraffic")) {
info.afterAllowTraffic = hook.get("AfterAllowTraffic").asText(null);
}
}
}
} catch (Exception e) {
throw new AwsException("InvalidRevisionException", "Failed to parse AppSpec content: " + e.getMessage(), 400);
}
if (info.functionName == null || info.aliasName == null || info.targetVersion == null) {
throw new AwsException("InvalidRevisionException",
"AppSpec must specify Name, Alias, and TargetVersion", 400);
}
return info;
}
@SuppressWarnings("unchecked")
private TrafficRoutingInfo getTrafficRoutingInfo(String region, String configName) {
if (configName == null) {
return new TrafficRoutingInfo("AllAtOnce", 100, 0);
}
DeploymentConfig cfg = deploymentConfigsFor(region).get(configName);
if (cfg == null || cfg.getTrafficRoutingConfig() == null) {
return new TrafficRoutingInfo("AllAtOnce", 100, 0);
}
Map<String, Object> trc = (Map<String, Object>) cfg.getTrafficRoutingConfig();
String type = (String) trc.getOrDefault("type", "AllAtOnce");
if ("TimeBasedCanary".equals(type)) {
Map<String, Object> canary = (Map<String, Object>) trc.get("timeBasedCanary");
if (canary != null) {
int pct = toInt(canary.get("canaryPercentage"), 10);
int minutes = toInt(canary.get("canaryInterval"), 5);
return new TrafficRoutingInfo(type, pct, minutes * 60);
}
} else if ("TimeBasedLinear".equals(type)) {
Map<String, Object> linear = (Map<String, Object>) trc.get("timeBasedLinear");
if (linear != null) {
int pct = toInt(linear.get("linearPercentage"), 10);
int minutes = toInt(linear.get("linearInterval"), 1);
return new TrafficRoutingInfo(type, pct, minutes * 60);
}
}
return new TrafficRoutingInfo("AllAtOnce", 100, 0);
}
private void runStateMachine(String region, Deployment deployment, AppSpecInfo appSpec,
Map<String, Object> lambdaTargetMap, AtomicBoolean stopFlag, String configName) {
String deploymentId = deployment.getDeploymentId();
try {
deployment.setStatus("InProgress");
deployment.setStartTime(Instant.now().toEpochMilli() / 1000.0);
updateTargetStatus(lambdaTargetMap, "InProgress");
if (stopFlag.get()) { finishStopped(deployment, lambdaTargetMap); return; }
if (appSpec.beforeAllowTraffic != null) {
boolean ok = invokeHook(region, deployment, appSpec.beforeAllowTraffic,
"BeforeAllowTraffic", lambdaTargetMap, stopFlag);
if (!ok) { finishFailed(deployment, lambdaTargetMap, "BeforeAllowTrafficHookFailed",
"Hook function reported failure: BeforeAllowTraffic"); return; }
}
if (stopFlag.get()) { finishStopped(deployment, lambdaTargetMap); return; }
executeAllowTraffic(region, deployment, appSpec, configName, lambdaTargetMap, stopFlag);
if (stopFlag.get()) { finishStopped(deployment, lambdaTargetMap); return; }
if (appSpec.afterAllowTraffic != null) {
boolean ok = invokeHook(region, deployment, appSpec.afterAllowTraffic,
"AfterAllowTraffic", lambdaTargetMap, stopFlag);
if (!ok) { finishFailed(deployment, lambdaTargetMap, "AfterAllowTrafficHookFailed",
"Hook function reported failure: AfterAllowTraffic"); return; }
}
updateTargetStatus(lambdaTargetMap, "Succeeded");
deployment.setStatus("Succeeded");
deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
finishStopped(deployment, lambdaTargetMap);
} catch (Exception e) {
LOG.warnv("Deployment {0} failed: {1}", deploymentId, e.getMessage());
finishFailed(deployment, lambdaTargetMap, "DeploymentFailed", e.getMessage());
} finally {
stopFlags.remove(deploymentId);
}
}
private void executeAllowTraffic(String region, Deployment deployment, AppSpecInfo appSpec,
String configName, Map<String, Object> lambdaTargetMap,
AtomicBoolean stopFlag) throws InterruptedException {
TrafficRoutingInfo trc = getTrafficRoutingInfo(region, configName);
Map<String, Object> event = addLifecycleEvent(lambdaTargetMap, "AllowTraffic");
try {
switch (trc.type) {
case "TimeBasedCanary" -> {
// Step 1: shift canaryPercentage to targetVersion
double canaryWeight = trc.percentage / 100.0;
Map<String, Double> routing = Map.of(appSpec.targetVersion, canaryWeight);
lambdaService.updateAlias(region, appSpec.functionName, appSpec.aliasName,
appSpec.currentVersion, null, routing);
// Wait the canary interval (capped at 5s for emulator speed)
long waitMs = Math.min(trc.intervalSeconds * 1000L, 5000L);
if (waitMs > 0 && !stopFlag.get()) {
Thread.sleep(waitMs);
}
if (stopFlag.get()) { return; }
// Step 2: flip 100% to targetVersion
lambdaService.updateAlias(region, appSpec.functionName, appSpec.aliasName,
appSpec.targetVersion, null, Map.of());
}
case "TimeBasedLinear" -> {
int steps = (int) Math.ceil(100.0 / trc.percentage);
for (int step = 1; step <= steps && !stopFlag.get(); step++) {
int pct = Math.min(step * trc.percentage, 100);
if (pct >= 100) {
lambdaService.updateAlias(region, appSpec.functionName, appSpec.aliasName,
appSpec.targetVersion, null, Map.of());
} else {
double weight = pct / 100.0;
lambdaService.updateAlias(region, appSpec.functionName, appSpec.aliasName,
appSpec.currentVersion, null, Map.of(appSpec.targetVersion, weight));
long waitMs = Math.min(trc.intervalSeconds * 1000L, 2000L);
if (waitMs > 0) {
Thread.sleep(waitMs);
}
}
}
}
default -> {
// AllAtOnce: flip immediately
lambdaService.updateAlias(region, appSpec.functionName, appSpec.aliasName,
appSpec.targetVersion, null, Map.of());
}
}
finishLifecycleEvent(event, "Succeeded");
} catch (Exception e) {
finishLifecycleEvent(event, "Failed");
throw e;
}
}
private boolean invokeHook(String region, Deployment deployment, String hookFunctionName,
String lifecycleEventName, Map<String, Object> lambdaTargetMap,
AtomicBoolean stopFlag) throws InterruptedException {
String executionId = UUID.randomUUID().toString();
CompletableFuture<String> future = new CompletableFuture<>();
hookFutures.put(executionId, future);
Map<String, Object> event = addLifecycleEvent(lambdaTargetMap, lifecycleEventName);
try {
String payload = "{\"DeploymentId\":\"" + deployment.getDeploymentId()
+ "\",\"LifecycleEventHookExecutionId\":\"" + executionId + "\"}";
try {
InvokeResult result = lambdaService.invoke(region, hookFunctionName,
payload.getBytes(), InvocationType.RequestResponse);
if (!future.isDone()) {
// Lambda didn't call PutLifecycleEventHookExecutionStatus; decide from invocation result
future.complete(result.getFunctionError() == null ? "Succeeded" : "Failed");
}
} catch (Exception e) {
LOG.debugv("Hook Lambda {0} not invokable: {1}", hookFunctionName, e.getMessage());
future.complete("Succeeded");
}
String status = "Succeeded";
try {
status = future.get(30, TimeUnit.SECONDS);
} catch (Exception e) {
status = "Succeeded";
}
finishLifecycleEvent(event, status);
return "Succeeded".equals(status);
} finally {
hookFutures.remove(executionId);
}
}
@SuppressWarnings("unchecked")
private Map<String, Object> addLifecycleEvent(Map<String, Object> lambdaTargetMap, String name) {
Map<String, Object> event = new ConcurrentHashMap<>();
event.put("lifecycleEventName", name);
event.put("startTime", Instant.now().toEpochMilli() / 1000.0);
event.put("status", "InProgress");
List<Map<String, Object>> events = (List<Map<String, Object>>) lambdaTargetMap.get("lifecycleEvents");
if (events != null) {
events.add(event);
}
lambdaTargetMap.put("lastUpdatedAt", Instant.now().toEpochMilli() / 1000.0);
return event;
}
private void finishLifecycleEvent(Map<String, Object> event, String status) {
event.put("endTime", Instant.now().toEpochMilli() / 1000.0);
event.put("status", status);
}
private void updateTargetStatus(Map<String, Object> lambdaTargetMap, String status) {
lambdaTargetMap.put("status", status);
lambdaTargetMap.put("lastUpdatedAt", Instant.now().toEpochMilli() / 1000.0);
}
private void finishStopped(Deployment deployment, Map<String, Object> lambdaTargetMap) {
updateTargetStatus(lambdaTargetMap, "Skipped");
deployment.setStatus("Stopped");
deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0);
}
private void finishFailed(Deployment deployment, Map<String, Object> lambdaTargetMap,
String errorCode, String message) {
updateTargetStatus(lambdaTargetMap, "Failed");
deployment.setStatus("Failed");
deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0);
deployment.setErrorInformation(Map.of("code", errorCode, "message", message != null ? message : ""));
}
private String generateDeploymentId() {
String hex = UUID.randomUUID().toString().replace("-", "").substring(0, 9).toUpperCase();
return "d-" + hex;
}
private int toInt(Object val, int def) {
if (val instanceof Number n) { return n.intValue(); }
if (val instanceof String s) { try { return Integer.parseInt(s); } catch (NumberFormatException ignored) {} }
return def;
}
// ---- Tags ----
public void tagResource(String arn, List<Map<String, String>> tagList) {
@@ -0,0 +1,65 @@
package io.github.hectorvent.floci.services.codedeploy.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.Map;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Deployment {
public Deployment() {}
private String deploymentId;
private String applicationName;
private String deploymentGroupName;
private String deploymentConfigName;
private String status;
private Map<String, Object> revision;
private Double createTime;
private Double startTime;
private Double completeTime;
private Map<String, String> errorInformation;
private String description;
private String creator;
private String computePlatform;
public String getDeploymentId() { return deploymentId; }
public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; }
public String getApplicationName() { return applicationName; }
public void setApplicationName(String applicationName) { this.applicationName = applicationName; }
public String getDeploymentGroupName() { return deploymentGroupName; }
public void setDeploymentGroupName(String deploymentGroupName) { this.deploymentGroupName = deploymentGroupName; }
public String getDeploymentConfigName() { return deploymentConfigName; }
public void setDeploymentConfigName(String deploymentConfigName) { this.deploymentConfigName = deploymentConfigName; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Map<String, Object> getRevision() { return revision; }
public void setRevision(Map<String, Object> revision) { this.revision = revision; }
public Double getCreateTime() { return createTime; }
public void setCreateTime(Double createTime) { this.createTime = createTime; }
public Double getStartTime() { return startTime; }
public void setStartTime(Double startTime) { this.startTime = startTime; }
public Double getCompleteTime() { return completeTime; }
public void setCompleteTime(Double completeTime) { this.completeTime = completeTime; }
public Map<String, String> getErrorInformation() { return errorInformation; }
public void setErrorInformation(Map<String, String> errorInformation) { this.errorInformation = errorInformation; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getCreator() { return creator; }
public void setCreator(String creator) { this.creator = creator; }
public String getComputePlatform() { return computePlatform; }
public void setComputePlatform(String computePlatform) { this.computePlatform = computePlatform; }
}
@@ -359,7 +359,9 @@ public class LambdaController {
String name = (String) req.get("Name");
String functionVersion = (String) req.get("FunctionVersion");
String description = (String) req.get("Description");
LambdaAlias alias = lambdaService.createAlias(region, functionName, name, functionVersion, description);
@SuppressWarnings("unchecked")
Map<String, Double> routingConfig = extractRoutingConfig((Map<String, Object>) req.get("RoutingConfig"));
LambdaAlias alias = lambdaService.createAlias(region, functionName, name, functionVersion, description, routingConfig);
return Response.status(201).entity(buildAliasResponse(alias)).build();
} catch (AwsException e) {
throw e;
@@ -404,7 +406,9 @@ public class LambdaController {
Map<String, Object> req = objectMapper.readValue(body, Map.class);
String functionVersion = (String) req.get("FunctionVersion");
String description = (String) req.get("Description");
LambdaAlias alias = lambdaService.updateAlias(region, functionName, aliasName, functionVersion, description);
@SuppressWarnings("unchecked")
Map<String, Double> routingConfig = extractRoutingConfig((Map<String, Object>) req.get("RoutingConfig"));
LambdaAlias alias = lambdaService.updateAlias(region, functionName, aliasName, functionVersion, description, routingConfig);
return Response.ok(buildAliasResponse(alias)).build();
} catch (AwsException e) {
throw e;
@@ -486,11 +490,28 @@ public class LambdaController {
node.put("AliasArn", alias.getAliasArn());
if (alias.getDescription() != null) node.put("Description", alias.getDescription());
node.put("RevisionId", alias.getRevisionId());
if (alias.getRoutingConfig() != null && !alias.getRoutingConfig().isEmpty()) {
ObjectNode rc = node.putObject("RoutingConfig");
ObjectNode weights = rc.putObject("AdditionalVersionWeights");
alias.getRoutingConfig().forEach(weights::put);
}
@SuppressWarnings("unchecked")
Map<String, Object> result = objectMapper.convertValue(node, Map.class);
return result;
}
@SuppressWarnings("unchecked")
private Map<String, Double> extractRoutingConfig(Map<String, Object> rc) {
if (rc == null) return null;
Object weights = rc.get("AdditionalVersionWeights");
if (!(weights instanceof Map)) return null;
Map<String, Object> raw = (Map<String, Object>) weights;
if (raw.isEmpty()) return null;
java.util.Map<String, Double> result = new java.util.HashMap<>();
raw.forEach((k, v) -> result.put(k, ((Number) v).doubleValue()));
return result;
}
private Map<String, Object> buildFunctionConfiguration(LambdaFunction fn) {
ObjectNode node = objectMapper.createObjectNode();
node.put("FunctionName", fn.getFunctionName());
@@ -546,10 +546,57 @@ public class LambdaService {
}
public InvokeResult invoke(String region, String functionName, byte[] payload, InvocationType type) {
LambdaFunction fn = getFunction(region, functionName);
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(functionName);
enforceRegion(region, ref);
String name = ref.name();
String qualifier = ref.qualifier();
LambdaFunction fn = resolveInvokeTarget(region, name, qualifier);
return executorService.invoke(fn, payload, type);
}
private LambdaFunction resolveInvokeTarget(String region, String name, String qualifier) {
if (qualifier == null || qualifier.equals("$LATEST")) {
return functionStore.get(region, name)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Function not found: " + name, 404));
}
if (qualifier.chars().allMatch(Character::isDigit)) {
return functionStore.get(region, name, qualifier)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Function version not found: " + name + ":" + qualifier, 404));
}
// qualifier is an alias name
LambdaAlias alias = getAlias(region, name, qualifier);
String version = pickAliasVersion(alias);
if (version == null || version.equals("$LATEST")) {
return functionStore.get(region, name)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Function not found: " + name, 404));
}
return functionStore.get(region, name, version)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Function version not found: " + name + ":" + version, 404));
}
private String pickAliasVersion(LambdaAlias alias) {
java.util.Map<String, Double> weights = alias.getRoutingConfig();
if (weights == null || weights.isEmpty()) {
return alias.getFunctionVersion();
}
double rand = java.util.concurrent.ThreadLocalRandom.current().nextDouble();
double additionalTotal = weights.values().stream().mapToDouble(Double::doubleValue).sum();
double primaryWeight = Math.max(0.0, 1.0 - additionalTotal);
if (rand < primaryWeight) {
return alias.getFunctionVersion();
}
double cumulative = primaryWeight;
for (java.util.Map.Entry<String, Double> entry : weights.entrySet()) {
cumulative += entry.getValue();
if (rand < cumulative) {
return entry.getKey();
}
}
return alias.getFunctionVersion();
}
// ──────────────────────────── Event Source Mapping (SQS) ────────────────────────────
public EventSourceMapping createEventSourceMapping(String region, Map<String, Object> request) {
@@ -785,7 +832,8 @@ public class LambdaService {
// ──────────────────────────── Aliases ────────────────────────────
public LambdaAlias createAlias(String region, String functionName, String aliasName,
String functionVersion, String description) {
String functionVersion, String description,
java.util.Map<String, Double> routingConfig) {
LambdaFunction fn = getFunction(region, functionName);
functionName = fn.getFunctionName();
if (aliasStore != null && aliasStore.get(region, functionName, aliasName).isPresent()) {
@@ -796,6 +844,7 @@ public class LambdaService {
alias.setFunctionName(functionName);
alias.setFunctionVersion(functionVersion != null ? functionVersion : "$LATEST");
alias.setDescription(description);
alias.setRoutingConfig(routingConfig);
alias.setAliasArn(fn.getFunctionArn() + ":" + aliasName);
long now = System.currentTimeMillis() / 1000L;
alias.setCreatedDate(now);
@@ -823,10 +872,12 @@ public class LambdaService {
}
public LambdaAlias updateAlias(String region, String functionName, String aliasName,
String functionVersion, String description) {
String functionVersion, String description,
java.util.Map<String, Double> routingConfig) {
LambdaAlias alias = getAlias(region, functionName, aliasName);
if (functionVersion != null) alias.setFunctionVersion(functionVersion);
if (description != null) alias.setDescription(description);
if (routingConfig != null) alias.setRoutingConfig(routingConfig.isEmpty() ? null : routingConfig);
alias.setLastModifiedDate(System.currentTimeMillis() / 1000L);
alias.setRevisionId(UUID.randomUUID().toString());
if (aliasStore != null) aliasStore.save(region, alias);
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.lambda.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class LambdaAlias {
@@ -16,6 +18,7 @@ public class LambdaAlias {
private long lastModifiedDate;
private String revisionId;
private LambdaUrlConfig urlConfig;
private Map<String, Double> routingConfig;
public LambdaAlias() {}
@@ -45,4 +48,7 @@ public class LambdaAlias {
public LambdaUrlConfig getUrlConfig() { return urlConfig; }
public void setUrlConfig(LambdaUrlConfig urlConfig) { this.urlConfig = urlConfig; }
public Map<String, Double> getRoutingConfig() { return routingConfig; }
public void setRoutingConfig(Map<String, Double> routingConfig) { this.routingConfig = routingConfig; }
}