From e402c6ec180afcd71a798f9470f082b9b596a490 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Wed, 6 May 2026 23:36:50 -0500 Subject: [PATCH] =?UTF-8?q?feat(codedeploy):=20Server=20platform=20?= =?UTF-8?q?=E2=80=94=20on-premises=20instance=20management,=20Server=20App?= =?UTF-8?q?Spec=20YAML,=20lifecycle=20events,=20SSM=20hook=20execution=20(?= =?UTF-8?q?#731)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add 7 on-premises instance operations: RegisterOnPremisesInstance, DeregisterOnPremisesInstance, GetOnPremisesInstance, BatchGetOnPremisesInstances, ListOnPremisesInstances, AddTagsToOnPremisesInstances, RemoveTagsFromOnPremisesInstances - Add Server AppSpec YAML parsing (jackson-dataformat-yaml) extracting os and hooks map (hookName → [{location, timeout, runas}]) - Resolve deployment targets from EC2 tag filters (via Ec2Service) and on-premises instance tag filters; fall back to all registered on-premises instances when no filters are configured - Run lifecycle events in order (ApplicationStop → DownloadBundle → ValidateService) on a virtual thread per deployment; DownloadBundle and Install auto-succeed as infrastructure steps - Execute AppSpec hook scripts via SSM Run Command when the instance is registered in SSM; graceful degradation (treat as succeeded) when SSM is not available for an instance - Refactor deploymentTargets from two-level to three-level (region→deploymentId→targetId→wrapper) to support multi-instance Server deployments alongside existing Lambda/ECS single-target shape - Add SsmCommandService helpers: isInstanceRegistered, sendCommandToInstance, getCommandInvocationStatus - Add OnPremisesInstance model with instanceName, instanceArn, iamSessionArn, iamUserArn, registerTime, deregisterTime, tags, registrationStatus --- CHANGELOG.md | 2 + .../codedeploy/CodeDeployJsonHandler.java | 62 ++- .../codedeploy/CodeDeployService.java | 460 +++++++++++++++++- .../codedeploy/model/OnPremisesInstance.java | 48 ++ .../floci/services/ssm/SsmCommandService.java | 48 ++ .../CodeDeployServerIntegrationTest.java | 262 ++++++++++ 6 files changed, 853 insertions(+), 29 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/codedeploy/model/OnPremisesInstance.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployServerIntegrationTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c19afe01d..d29ba2cf52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - **ssm:** Run Command — `SendCommand`, `GetCommandInvocation`, `ListCommands`, `ListCommandInvocations`, `CancelCommand`, `DescribeInstanceInformation`; `UpdateInstanceInformation` (agent registration); `ec2messages` polling protocol (`GetMessages`, `AcknowledgeMessage`, `SendReply`, `FailMessage`, `DeleteMessage`, `GetEndpoint`) so the real `amazon-ssm-agent` running inside EC2 containers can register, receive commands, and report output +- **codedeploy:** Server platform (Phase 4) — on-premises instance management (`RegisterOnPremisesInstance`, `DeregisterOnPremisesInstance`, `GetOnPremisesInstance`, `BatchGetOnPremisesInstances`, `ListOnPremisesInstances`, `AddTagsToOnPremisesInstances`, `RemoveTagsFromOnPremisesInstances`); Server AppSpec YAML parsing; EC2 and on-premises instance resolution by tag filters; full lifecycle event execution (`ApplicationStop` → `DownloadBundle` → `BeforeInstall` → `Install` → `AfterInstall` → `ApplicationStart` → `ValidateService`); SSM Run Command integration for hook script execution with graceful degradation when SSM is unavailable; per-instance `InstanceTarget` tracking in `ListDeploymentTargets`/`BatchGetDeploymentTargets` +- **elbv2:** Lambda targets — ALB listeners can forward to Lambda functions; ALB event format with `queryStringParameters`, `multiValueQueryStringParameters`, `headers`, `multiValueHeaders`, `body`, `isBase64Encoded`; Lambda→ALB response mapping; Lambda target groups always return healthy without HTTP probing ## [1.5.12] - 2026-05-04 diff --git a/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployJsonHandler.java index 30ba735edb..b4038bf6c8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployJsonHandler.java @@ -7,6 +7,7 @@ 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.codedeploy.model.OnPremisesInstance; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; @@ -58,8 +59,13 @@ public class CodeDeployJsonHandler { case "ListDeploymentTargets" -> listDeploymentTargets(request, region); case "BatchGetDeploymentTargets" -> batchGetDeploymentTargets(request, region); case "PutLifecycleEventHookExecutionStatus" -> putLifecycleEventHookExecutionStatus(request); - case "AddTagsToOnPremisesInstances", "RemoveTagsFromOnPremisesInstances" -> - Response.ok(Map.of()).build(); + case "RegisterOnPremisesInstance" -> registerOnPremisesInstance(request, region); + case "DeregisterOnPremisesInstance" -> deregisterOnPremisesInstance(request, region); + case "GetOnPremisesInstance" -> getOnPremisesInstance(request, region); + case "BatchGetOnPremisesInstances" -> batchGetOnPremisesInstances(request, region); + case "ListOnPremisesInstances" -> listOnPremisesInstances(request, region); + case "AddTagsToOnPremisesInstances" -> addTagsToOnPremisesInstances(request, region); + case "RemoveTagsFromOnPremisesInstances" -> removeTagsFromOnPremisesInstances(request, region); default -> throw new AwsException("InvalidAction", "Action " + action + " is not supported", 400); }; } @@ -267,6 +273,58 @@ public class CodeDeployJsonHandler { return Response.ok(Map.of("lifecycleEventHookExecutionId", id)).build(); } + private Response registerOnPremisesInstance(JsonNode req, String region) { + String instanceName = req.path("instanceName").asText(null); + String iamSessionArn = req.has("iamSessionArn") ? req.path("iamSessionArn").asText() : null; + String iamUserArn = req.has("iamUserArn") ? req.path("iamUserArn").asText() : null; + service.registerOnPremisesInstance(region, instanceName, iamSessionArn, iamUserArn); + return Response.ok(Map.of()).build(); + } + + private Response deregisterOnPremisesInstance(JsonNode req, String region) { + String instanceName = req.path("instanceName").asText(null); + service.deregisterOnPremisesInstance(region, instanceName); + return Response.ok(Map.of()).build(); + } + + private Response getOnPremisesInstance(JsonNode req, String region) { + String instanceName = req.path("instanceName").asText(null); + OnPremisesInstance inst = service.getOnPremisesInstance(region, instanceName); + return Response.ok(Map.of("instanceInfo", inst)).build(); + } + + private Response batchGetOnPremisesInstances(JsonNode req, String region) { + List names = new ArrayList<>(); + req.path("instanceNames").forEach(n -> names.add(n.asText())); + List found = service.batchGetOnPremisesInstances(region, names); + List foundNames = found.stream().map(OnPremisesInstance::getInstanceName).toList(); + List missing = names.stream().filter(n -> !foundNames.contains(n)).toList(); + return Response.ok(Map.of("instanceInfos", found, "instanceNames", missing)).build(); + } + + private Response listOnPremisesInstances(JsonNode req, String region) { + String registrationStatus = req.has("registrationStatus") ? req.path("registrationStatus").asText() : null; + List> tagFilters = parseTags(req, "tagFilters"); + List names = service.listOnPremisesInstances(region, registrationStatus, tagFilters); + return Response.ok(Map.of("instanceNames", names)).build(); + } + + private Response addTagsToOnPremisesInstances(JsonNode req, String region) { + List> tags = parseTags(req, "tags"); + List names = new ArrayList<>(); + req.path("instanceNames").forEach(n -> names.add(n.asText())); + service.addTagsToOnPremisesInstances(region, names, tags); + return Response.ok(Map.of()).build(); + } + + private Response removeTagsFromOnPremisesInstances(JsonNode req, String region) { + List> tags = parseTags(req, "tags"); + List names = new ArrayList<>(); + req.path("instanceNames").forEach(n -> names.add(n.asText())); + service.removeTagsFromOnPremisesInstances(region, names, tags); + return Response.ok(Map.of()).build(); + } + @SuppressWarnings("unchecked") private Map extractGroupFields(JsonNode req) throws Exception { Map fields = new HashMap<>(); diff --git a/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java b/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java index 946ed3dbb2..79b1623bbb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java +++ b/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java @@ -2,17 +2,21 @@ package io.github.hectorvent.floci.services.codedeploy; 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.AwsArnUtils; 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.codedeploy.model.OnPremisesInstance; +import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ecs.EcsService; import io.github.hectorvent.floci.services.ecs.model.TaskSet; import io.github.hectorvent.floci.services.elbv2.ElbV2Service; import io.github.hectorvent.floci.services.elbv2.model.TargetGroup; import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.ssm.SsmCommandService; import io.github.hectorvent.floci.services.lambda.model.InvocationType; import io.github.hectorvent.floci.services.lambda.model.InvokeResult; import jakarta.enterprise.context.ApplicationScoped; @@ -40,15 +44,22 @@ public class CodeDeployService { private final LambdaService lambdaService; private final EcsService ecsService; private final ElbV2Service elbV2Service; + private final SsmCommandService ssmCommandService; + private final Ec2Service ec2Service; private final ObjectMapper mapper; + private final ObjectMapper yamlMapper; @Inject public CodeDeployService(LambdaService lambdaService, EcsService ecsService, - ElbV2Service elbV2Service, ObjectMapper mapper) { + ElbV2Service elbV2Service, SsmCommandService ssmCommandService, + Ec2Service ec2Service, ObjectMapper mapper) { this.lambdaService = lambdaService; this.ecsService = ecsService; this.elbV2Service = elbV2Service; + this.ssmCommandService = ssmCommandService; + this.ec2Service = ec2Service; this.mapper = mapper; + this.yamlMapper = new ObjectMapper(new YAMLFactory()); } // key: region -> name -> application @@ -61,8 +72,10 @@ public class CodeDeployService { private final ConcurrentHashMap> tags = new ConcurrentHashMap<>(); // key: region -> deploymentId -> Deployment private final ConcurrentHashMap> deployments = new ConcurrentHashMap<>(); - // key: region -> deploymentId -> target map (lambdaTarget data) - private final ConcurrentHashMap>> deploymentTargets = new ConcurrentHashMap<>(); + // key: region -> deploymentId -> targetId -> DeploymentTarget wrapper + private final ConcurrentHashMap>>> deploymentTargets = new ConcurrentHashMap<>(); + // key: region -> instanceName -> OnPremisesInstance + private final ConcurrentHashMap> onPremisesInstances = new ConcurrentHashMap<>(); // key: lifecycleEventHookExecutionId -> CompletableFuture private final ConcurrentHashMap> hookFutures = new ConcurrentHashMap<>(); // key: deploymentId -> stop flag @@ -77,6 +90,11 @@ public class CodeDeployService { String afterAllowTraffic; } + private static final class ServerAppSpecInfo { + String os; + Map>> hooks; // hookName → [{location, timeout, runas}] + } + private static final class EcsAppSpecInfo { String taskDefinition; String containerName; @@ -413,10 +431,14 @@ public class CodeDeployService { return deployments.computeIfAbsent(region, r -> new ConcurrentHashMap<>()); } - private Map> deploymentTargetsFor(String region) { + private Map>> deploymentTargetsFor(String region) { return deploymentTargets.computeIfAbsent(region, r -> new ConcurrentHashMap<>()); } + private Map onPremisesFor(String region) { + return onPremisesInstances.computeIfAbsent(region, r -> new ConcurrentHashMap<>()); + } + public String createDeployment(String region, String appName, String groupName, String configName, Map revision, String description) { Application app = getApplication(region, appName); @@ -431,6 +453,10 @@ public class CodeDeployService { return createEcsDeployment(region, appName, groupName, group, configName, revision, description); } + if ("Server".equals(computePlatform)) { + return createServerDeployment(region, appName, groupName, group, configName, revision, description); + } + AppSpecInfo appSpec = parseAppSpec(revision); String effectiveConfig = configName != null ? configName : group.getDeploymentConfigName(); @@ -464,7 +490,9 @@ public class CodeDeployService { Map targetMap = new ConcurrentHashMap<>(); targetMap.put("deploymentTargetType", "LambdaFunction"); targetMap.put("lambdaTarget", lambdaTargetMap); - deploymentTargetsFor(region).put(deploymentId, targetMap); + ConcurrentHashMap> targets = new ConcurrentHashMap<>(); + targets.put(targetId, targetMap); + deploymentTargetsFor(region).put(deploymentId, targets); AtomicBoolean stopFlag = new AtomicBoolean(false); stopFlags.put(deploymentId, stopFlag); @@ -523,36 +551,26 @@ public class CodeDeployService { public List listDeploymentTargets(String region, String deploymentId) { getDeployment(region, deploymentId); - Map target = deploymentTargetsFor(region).get(deploymentId); - if (target == null) { + Map> targets = deploymentTargetsFor(region).get(deploymentId); + if (targets == null) { return List.of(); } - String targetId = extractTargetId(target); - return targetId != null ? List.of(targetId) : List.of(); + return new ArrayList<>(targets.keySet()); } public List> batchGetDeploymentTargets(String region, String deploymentId, List targetIds) { getDeployment(region, deploymentId); - Map target = deploymentTargetsFor(region).get(deploymentId); - if (target == null) { + Map> targets = deploymentTargetsFor(region).get(deploymentId); + if (targets == null) { return List.of(); } - String targetId = extractTargetId(target); - if (targetId == null || (!targetIds.isEmpty() && !targetIds.contains(targetId))) { - return List.of(); + if (targetIds.isEmpty()) { + return new ArrayList<>(targets.values()); } - return List.of(target); - } - - @SuppressWarnings("unchecked") - private String extractTargetId(Map target) { - String type = (String) target.get("deploymentTargetType"); - if ("ECSTarget".equals(type)) { - Map ecsTarget = (Map) target.get("ecsTarget"); - return ecsTarget != null ? (String) ecsTarget.get("targetId") : null; - } - Map lambdaTarget = (Map) target.get("lambdaTarget"); - return lambdaTarget != null ? (String) lambdaTarget.get("targetId") : null; + return targetIds.stream() + .map(targets::get) + .filter(t -> t != null) + .collect(Collectors.toList()); } public String putLifecycleEventHookExecutionStatus(String deploymentId, String executionId, String status) { @@ -566,6 +584,392 @@ public class CodeDeployService { // ---- Deployment state machine ---- @SuppressWarnings("unchecked") + // ---- On-Premises Instances ---- + + public OnPremisesInstance registerOnPremisesInstance(String region, String instanceName, + String iamSessionArn, String iamUserArn) { + Map store = onPremisesFor(region); + OnPremisesInstance inst = new OnPremisesInstance(); + inst.setInstanceName(instanceName); + inst.setInstanceArn(AwsArnUtils.Arn.of("codedeploy", region, "000000000000", + "instance/" + instanceName).toString()); + inst.setIamSessionArn(iamSessionArn); + inst.setIamUserArn(iamUserArn); + inst.setRegisterTime(Instant.now().toEpochMilli() / 1000.0); + inst.setRegistrationStatus("Registered"); + store.put(instanceName, inst); + return inst; + } + + public void deregisterOnPremisesInstance(String region, String instanceName) { + OnPremisesInstance inst = requireOnPremisesInstance(region, instanceName); + inst.setDeregisterTime(Instant.now().toEpochMilli() / 1000.0); + inst.setRegistrationStatus("Deregistered"); + } + + public OnPremisesInstance getOnPremisesInstance(String region, String instanceName) { + return requireOnPremisesInstance(region, instanceName); + } + + public List batchGetOnPremisesInstances(String region, List names) { + return names.stream().map(n -> requireOnPremisesInstance(region, n)).collect(Collectors.toList()); + } + + public List listOnPremisesInstances(String region, String registrationStatus, + List> tagFilters) { + return onPremisesFor(region).values().stream() + .filter(i -> registrationStatus == null || registrationStatus.equals(i.getRegistrationStatus())) + .filter(i -> tagFilters == null || tagFilters.isEmpty() || matchesTagFilters(i.getTags(), tagFilters)) + .map(OnPremisesInstance::getInstanceName) + .collect(Collectors.toList()); + } + + public void addTagsToOnPremisesInstances(String region, List instanceNames, List> newTags) { + for (String name : instanceNames) { + OnPremisesInstance inst = requireOnPremisesInstance(region, name); + for (Map t : newTags) { + inst.getTags().removeIf(e -> e.get("Key").equals(t.get("Key"))); + inst.getTags().add(t); + } + } + } + + public void removeTagsFromOnPremisesInstances(String region, List instanceNames, List> tagsToRemove) { + for (String name : instanceNames) { + OnPremisesInstance inst = requireOnPremisesInstance(region, name); + for (Map t : tagsToRemove) { + inst.getTags().removeIf(e -> e.get("Key").equals(t.get("Key"))); + } + } + } + + private OnPremisesInstance requireOnPremisesInstance(String region, String instanceName) { + OnPremisesInstance inst = onPremisesFor(region).get(instanceName); + if (inst == null) { + throw new AwsException("InstanceNameRequiredException", + "On-premises instance not found: " + instanceName, 400); + } + return inst; + } + + // ---- Server Platform Deployment ---- + + @SuppressWarnings("unchecked") + private String createServerDeployment(String region, String appName, String groupName, + DeploymentGroup group, String configName, + Map revision, String description) { + ServerAppSpecInfo appSpec = parseServerAppSpec(revision); + 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("Server"); + deploymentsFor(region).put(deploymentId, deployment); + + // Resolve target instances + List instanceIds = resolveServerTargets(region, group); + if (instanceIds.isEmpty()) { + deployment.setStatus("Failed"); + deployment.setCompleteTime(now); + deployment.setErrorInformation(Map.of("code", "NoInstancesReachable", + "message", "No instances found for deployment group")); + return deploymentId; + } + + ConcurrentHashMap> allTargets = new ConcurrentHashMap<>(); + List> instanceTargetMaps = new ArrayList<>(); + for (String instanceId : instanceIds) { + Map instanceTargetMap = new ConcurrentHashMap<>(); + instanceTargetMap.put("deploymentId", deploymentId); + instanceTargetMap.put("targetId", instanceId); + instanceTargetMap.put("targetArn", instanceId); + instanceTargetMap.put("status", "Pending"); + instanceTargetMap.put("lastUpdatedAt", now); + instanceTargetMap.put("lifecycleEvents", new CopyOnWriteArrayList<>()); + + Map targetWrapper = new ConcurrentHashMap<>(); + targetWrapper.put("deploymentTargetType", "InstanceTarget"); + targetWrapper.put("instanceTarget", instanceTargetMap); + allTargets.put(instanceId, targetWrapper); + instanceTargetMaps.add(instanceTargetMap); + } + deploymentTargetsFor(region).put(deploymentId, allTargets); + + AtomicBoolean stopFlag = new AtomicBoolean(false); + stopFlags.put(deploymentId, stopFlag); + + Thread.ofVirtual().name("codedeploy-server-" + deploymentId).start( + () -> runServerStateMachine(region, deployment, appSpec, instanceIds, + instanceTargetMaps, stopFlag)); + return deploymentId; + } + + private void runServerStateMachine(String region, Deployment deployment, + ServerAppSpecInfo appSpec, List instanceIds, + List> instanceTargetMaps, + AtomicBoolean stopFlag) { + String deploymentId = deployment.getDeploymentId(); + try { + deployment.setStatus("InProgress"); + deployment.setStartTime(Instant.now().toEpochMilli() / 1000.0); + instanceTargetMaps.forEach(m -> updateTargetStatus(m, "InProgress")); + + boolean anyFailed = false; + for (int i = 0; i < instanceIds.size(); i++) { + if (stopFlag.get()) { + instanceTargetMaps.forEach(m -> updateTargetStatus(m, "Skipped")); + deployment.setStatus("Stopped"); + deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0); + return; + } + String instanceId = instanceIds.get(i); + Map targetMap = instanceTargetMaps.get(i); + boolean ok = runInstanceDeployment(region, deployment, appSpec, instanceId, targetMap, stopFlag); + if (!ok) { + anyFailed = true; + } + } + + if (anyFailed) { + deployment.setStatus("Failed"); + deployment.setErrorInformation(Map.of("code", "DeploymentFailed", + "message", "One or more instances failed deployment")); + } else { + deployment.setStatus("Succeeded"); + } + deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0); + + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + instanceTargetMaps.forEach(m -> updateTargetStatus(m, "Skipped")); + deployment.setStatus("Stopped"); + deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0); + } catch (Exception e) { + LOG.warnv("Server deployment {0} failed: {1}", deploymentId, e.getMessage()); + instanceTargetMaps.forEach(m -> updateTargetStatus(m, "Failed")); + deployment.setStatus("Failed"); + deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0); + deployment.setErrorInformation(Map.of("code", "DeploymentFailed", + "message", e.getMessage() != null ? e.getMessage() : "Unknown error")); + } finally { + stopFlags.remove(deploymentId); + } + } + + private boolean runInstanceDeployment(String region, Deployment deployment, + ServerAppSpecInfo appSpec, String instanceId, + Map targetMap, + AtomicBoolean stopFlag) throws InterruptedException { + List lifecycleOrder = List.of( + "ApplicationStop", "DownloadBundle", "BeforeInstall", + "Install", "AfterInstall", "ApplicationStart", "ValidateService"); + + for (String eventName : lifecycleOrder) { + if (stopFlag.get()) { + updateTargetStatus(targetMap, "Skipped"); + return false; + } + + List> hookSteps = appSpec.hooks != null + ? appSpec.hooks.get(eventName) : null; + + Map event = addLifecycleEvent(targetMap, eventName); + + // DownloadBundle and Install are infrastructure steps — always succeed + if ("DownloadBundle".equals(eventName) || "Install".equals(eventName)) { + finishLifecycleEvent(event, "Succeeded"); + continue; + } + + if (hookSteps == null || hookSteps.isEmpty()) { + finishLifecycleEvent(event, "Skipped"); + continue; + } + + boolean stepOk = executeHookStepsOnInstance(region, instanceId, hookSteps, event); + if (!stepOk) { + updateTargetStatus(targetMap, "Failed"); + return false; + } + } + + updateTargetStatus(targetMap, "Succeeded"); + return true; + } + + @SuppressWarnings("unchecked") + private boolean executeHookStepsOnInstance(String region, String instanceId, + List> hookSteps, + Map event) throws InterruptedException { + for (Map step : hookSteps) { + String location = (String) step.get("location"); + int timeout = toInt(step.get("timeout"), 300); + String runas = (String) step.getOrDefault("runas", "root"); + + if (location == null) { + continue; + } + + // Check if instance is registered with SSM + boolean hasSsm = ssmCommandService.isInstanceRegistered(instanceId, region); + if (!hasSsm) { + LOG.debugv("Instance {0} not in SSM, marking hook {1} as Succeeded", instanceId, location); + continue; + } + + try { + String script = "sh " + location; + if (!"root".equals(runas)) { + script = "sudo -u " + runas + " sh " + location; + } + String commandId = ssmCommandService.sendCommandToInstance( + instanceId, "AWS-RunShellScript", Map.of("commands", List.of(script)), + timeout, region); + + // Poll until done (max timeout seconds, capped at 30s for emulator) + long deadline = System.currentTimeMillis() + Math.min(timeout * 1000L, 30_000L); + String invocationStatus = "InProgress"; + while (System.currentTimeMillis() < deadline && "InProgress".equals(invocationStatus)) { + Thread.sleep(500); + invocationStatus = ssmCommandService.getCommandInvocationStatus(commandId, instanceId, region); + } + + if (!"Success".equals(invocationStatus) && !"InProgress".equals(invocationStatus)) { + finishLifecycleEvent(event, "Failed"); + return false; + } + } catch (Exception e) { + LOG.debugv("SSM execution failed for {0} on {1}: {2}", location, instanceId, e.getMessage()); + // Graceful degradation: if SSM fails, treat as succeeded + } + } + finishLifecycleEvent(event, "Succeeded"); + return true; + } + + @SuppressWarnings("unchecked") + private ServerAppSpecInfo parseServerAppSpec(Map revision) { + if (revision == null) { + throw new AwsException("InvalidRevisionException", "Revision is required", 400); + } + + String content = null; + Object appSpecContent = revision.get("appSpecContent"); + if (appSpecContent instanceof Map asc) { + content = (String) ((Map) asc).get("content"); + } + + ServerAppSpecInfo info = new ServerAppSpecInfo(); + info.os = "linux"; + info.hooks = new java.util.LinkedHashMap<>(); + + if (content == null || content.isBlank()) { + return info; + } + + try { + JsonNode root = yamlMapper.readTree(content); + if (root.has("os")) { + info.os = root.get("os").asText("linux"); + } + JsonNode hooksNode = root.get("hooks"); + if (hooksNode != null && hooksNode.isObject()) { + hooksNode.fields().forEachRemaining(entry -> { + String hookName = entry.getKey(); + JsonNode steps = entry.getValue(); + List> stepList = new ArrayList<>(); + if (steps.isArray()) { + steps.forEach(s -> { + Map step = new java.util.LinkedHashMap<>(); + if (s.has("location")) { step.put("location", s.get("location").asText()); } + if (s.has("timeout")) { step.put("timeout", s.get("timeout").asInt(300)); } + if (s.has("runas")) { step.put("runas", s.get("runas").asText("root")); } + stepList.add(step); + }); + } + info.hooks.put(hookName, stepList); + }); + } + } catch (Exception e) { + throw new AwsException("InvalidRevisionException", + "Failed to parse Server AppSpec: " + e.getMessage(), 400); + } + return info; + } + + @SuppressWarnings("unchecked") + private List resolveServerTargets(String region, DeploymentGroup group) { + List instanceIds = new ArrayList<>(); + + // EC2 instances by tag filters + List> ec2TagFilters = group.getEc2TagFilters(); + if (ec2TagFilters != null && !ec2TagFilters.isEmpty()) { + Map> filters = new java.util.LinkedHashMap<>(); + for (Map filter : ec2TagFilters) { + String key = filter.get("Key"); + String value = filter.get("Value"); + if (key != null && value != null) { + filters.computeIfAbsent("tag:" + key, k -> new ArrayList<>()).add(value); + } + } + try { + ec2Service.describeInstances(region, null, filters).stream() + .flatMap(r -> r.getInstances().stream()) + .map(inst -> inst.getInstanceId()) + .filter(id -> id != null) + .forEach(instanceIds::add); + } catch (Exception e) { + LOG.debugv("EC2 tag filter lookup failed: {0}", e.getMessage()); + } + } + + // On-premises instances by tag filters + List> onPremFilters = group.getOnPremisesInstanceTagFilters(); + if (onPremFilters != null && !onPremFilters.isEmpty()) { + onPremisesFor(region).values().stream() + .filter(inst -> "Registered".equals(inst.getRegistrationStatus())) + .filter(inst -> matchesTagFilters(inst.getTags(), onPremFilters)) + .map(OnPremisesInstance::getInstanceName) + .forEach(instanceIds::add); + } + + // If no filters specified, include all registered on-premises instances + if ((ec2TagFilters == null || ec2TagFilters.isEmpty()) + && (onPremFilters == null || onPremFilters.isEmpty())) { + onPremisesFor(region).values().stream() + .filter(inst -> "Registered".equals(inst.getRegistrationStatus())) + .map(OnPremisesInstance::getInstanceName) + .forEach(instanceIds::add); + } + + return instanceIds; + } + + private boolean matchesTagFilters(List> instanceTags, + List> filters) { + for (Map filter : filters) { + String key = filter.get("Key"); + String value = filter.get("Value"); + if (key == null) { continue; } + boolean found = instanceTags.stream() + .anyMatch(t -> key.equals(t.get("Key")) + && (value == null || value.equals(t.get("Value")))); + if (!found) { return false; } + } + return true; + } + private AppSpecInfo parseAppSpec(Map revision) { if (revision == null) { throw new AwsException("InvalidRevisionException", "Revision is required", 400); @@ -752,7 +1156,9 @@ public class CodeDeployService { Map targetMap = new ConcurrentHashMap<>(); targetMap.put("deploymentTargetType", "ECSTarget"); targetMap.put("ecsTarget", ecsTargetMap); - deploymentTargetsFor(region).put(deploymentId, targetMap); + ConcurrentHashMap> ecsTargets = new ConcurrentHashMap<>(); + ecsTargets.put(targetId, targetMap); + deploymentTargetsFor(region).put(deploymentId, ecsTargets); AtomicBoolean stopFlag = new AtomicBoolean(false); stopFlags.put(deploymentId, stopFlag); diff --git a/src/main/java/io/github/hectorvent/floci/services/codedeploy/model/OnPremisesInstance.java b/src/main/java/io/github/hectorvent/floci/services/codedeploy/model/OnPremisesInstance.java new file mode 100644 index 0000000000..0b9df6fb29 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/codedeploy/model/OnPremisesInstance.java @@ -0,0 +1,48 @@ +package io.github.hectorvent.floci.services.codedeploy.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class OnPremisesInstance { + + private String instanceName; + private String instanceArn; + private String iamSessionArn; + private String iamUserArn; + private Double registerTime; + private Double deregisterTime; + private List> tags = new ArrayList<>(); + private String registrationStatus; + + public OnPremisesInstance() {} + + public String getInstanceName() { return instanceName; } + public void setInstanceName(String instanceName) { this.instanceName = instanceName; } + + public String getInstanceArn() { return instanceArn; } + public void setInstanceArn(String instanceArn) { this.instanceArn = instanceArn; } + + public String getIamSessionArn() { return iamSessionArn; } + public void setIamSessionArn(String iamSessionArn) { this.iamSessionArn = iamSessionArn; } + + public String getIamUserArn() { return iamUserArn; } + public void setIamUserArn(String iamUserArn) { this.iamUserArn = iamUserArn; } + + public Double getRegisterTime() { return registerTime; } + public void setRegisterTime(Double registerTime) { this.registerTime = registerTime; } + + public Double getDeregisterTime() { return deregisterTime; } + public void setDeregisterTime(Double deregisterTime) { this.deregisterTime = deregisterTime; } + + public List> getTags() { return tags; } + public void setTags(List> tags) { this.tags = tags; } + + public String getRegistrationStatus() { return registrationStatus; } + public void setRegistrationStatus(String registrationStatus) { this.registrationStatus = registrationStatus; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmCommandService.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmCommandService.java index 199d02df92..d3cb308406 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmCommandService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmCommandService.java @@ -363,6 +363,54 @@ public class SsmCommandService { messageIndex.remove(messageId); } + // ── CodeDeploy integration helpers ───────────────────────────────────── + + public boolean isInstanceRegistered(String instanceId, String region) { + return instanceStore.get(instanceKey(region, instanceId)).isPresent(); + } + + public String sendCommandToInstance(String instanceId, String documentName, + Map> parameters, + int timeoutSeconds, String region) { + String commandId = UUID.randomUUID().toString(); + Instant now = Instant.now(); + + Command command = new Command(); + command.setCommandId(commandId); + command.setDocumentName(documentName); + command.setDocumentVersion("$DEFAULT"); + command.setParameters(parameters); + command.setInstanceIds(List.of(instanceId)); + command.setRequestedDateTime(now); + command.setStatus("InProgress"); + command.setStatusDetails("InProgress"); + command.setTimeoutSeconds(timeoutSeconds); + command.setTargetCount(1); + command.setRegion(region); + command.setExpiresAfter(now.plusSeconds(timeoutSeconds)); + commandStore.put(commandKey(region, commandId), command); + + CommandInvocation inv = new CommandInvocation(); + inv.setCommandId(commandId); + inv.setInstanceId(instanceId); + inv.setDocumentName(documentName); + inv.setDocumentVersion("$DEFAULT"); + inv.setRequestedDateTime(now); + inv.setStatus("Pending"); + inv.setStatusDetails("Pending"); + inv.setRegion(region); + invocationStore.put(invocationKey(region, commandId, instanceId), inv); + + queueMessage(commandId, instanceId, documentName, parameters, timeoutSeconds, region); + return commandId; + } + + public String getCommandInvocationStatus(String commandId, String instanceId, String region) { + return invocationStore.get(invocationKey(region, commandId, instanceId)) + .map(CommandInvocation::getStatus) + .orElse("Failed"); + } + // ── Internal helpers ──────────────────────────────────────────────────── private void queueMessage(String commandId, String instanceId, String documentName, diff --git a/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployServerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployServerIntegrationTest.java new file mode 100644 index 0000000000..5113270ae7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployServerIntegrationTest.java @@ -0,0 +1,262 @@ +package io.github.hectorvent.floci.services.codedeploy; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.*; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CodeDeployServerIntegrationTest { + + private static final String CT = "application/x-amz-json-1.1"; + + private static String deploymentId; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + // ── On-premises instance CRUD ────────────────────────────────────────── + + @Test + @Order(1) + void registerOnPremisesInstance() { + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.RegisterOnPremisesInstance") + .body(""" + { + "instanceName": "on-prem-test-1", + "iamUserArn": "arn:aws:iam::000000000000:user/codedeploy-agent" + } + """) + .when().post("/") + .then().statusCode(200); + } + + @Test + @Order(2) + void getOnPremisesInstance() { + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.GetOnPremisesInstance") + .body("{\"instanceName\":\"on-prem-test-1\"}") + .when().post("/") + .then().statusCode(200) + .body("instanceInfo.instanceName", equalTo("on-prem-test-1")) + .body("instanceInfo.registrationStatus", equalTo("Registered")) + .body("instanceInfo.iamUserArn", equalTo("arn:aws:iam::000000000000:user/codedeploy-agent")); + } + + @Test + @Order(3) + void addTagsToOnPremisesInstance() { + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.AddTagsToOnPremisesInstances") + .body(""" + { + "instanceNames": ["on-prem-test-1"], + "tags": [{"Key": "Env", "Value": "test"}, {"Key": "Role", "Value": "web"}] + } + """) + .when().post("/") + .then().statusCode(200); + } + + @Test + @Order(4) + void listOnPremisesInstancesRegistered() { + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.ListOnPremisesInstances") + .body("{\"registrationStatus\":\"Registered\"}") + .when().post("/") + .then().statusCode(200) + .body("instanceNames", hasItem("on-prem-test-1")); + } + + @Test + @Order(5) + void batchGetOnPremisesInstances() { + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.BatchGetOnPremisesInstances") + .body("{\"instanceNames\":[\"on-prem-test-1\"]}") + .when().post("/") + .then().statusCode(200) + .body("instanceInfos", hasSize(1)) + .body("instanceInfos[0].instanceName", equalTo("on-prem-test-1")) + .body("instanceInfos[0].registrationStatus", equalTo("Registered")); + } + + @Test + @Order(6) + void removeTagsFromOnPremisesInstance() { + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.RemoveTagsFromOnPremisesInstances") + .body(""" + { + "instanceNames": ["on-prem-test-1"], + "tags": [{"Key": "Role", "Value": "web"}] + } + """) + .when().post("/") + .then().statusCode(200); + } + + // ── Server platform deployment ───────────────────────────────────────── + + @Test + @Order(7) + void createServerApplication() { + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.CreateApplication") + .body("{\"applicationName\":\"server-test-app\",\"computePlatform\":\"Server\"}") + .when().post("/") + .then().statusCode(200) + .body("applicationId", notNullValue()); + } + + @Test + @Order(8) + void createServerDeploymentGroup() { + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.CreateDeploymentGroup") + .body(""" + { + "applicationName": "server-test-app", + "deploymentGroupName": "server-test-group", + "deploymentConfigName": "CodeDeployDefault.AllAtOnce", + "serviceRoleArn": "arn:aws:iam::000000000000:role/CodeDeployRole", + "onPremisesInstanceTagFilters": [{"Key": "Env", "Value": "test", "Type": "KEY_AND_VALUE"}] + } + """) + .when().post("/") + .then().statusCode(200) + .body("deploymentGroupId", notNullValue()); + } + + @Test + @Order(9) + void createServerDeployment() { + String appSpec = """ + os: linux + hooks: + ApplicationStart: + - location: scripts/start_server.sh + timeout: 30 + """; + + String escapedAppSpec = appSpec.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n"); + + deploymentId = given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.CreateDeployment") + .body(""" + { + "applicationName": "server-test-app", + "deploymentGroupName": "server-test-group", + "description": "Test server deployment", + "revision": { + "revisionType": "AppSpecContent", + "appSpecContent": { + "content": "%s" + } + } + } + """.formatted(escapedAppSpec)) + .when().post("/") + .then().statusCode(200) + .body("deploymentId", notNullValue()) + .extract().jsonPath().getString("deploymentId"); + } + + @Test + @Order(10) + void getServerDeploymentCompletesSuccessfully() throws InterruptedException { + // Poll until final state (max 5s) + String status = "Queued"; + for (int i = 0; i < 50 && !"Succeeded".equals(status) && !"Failed".equals(status); i++) { + Thread.sleep(100); + status = given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.GetDeployment") + .body("{\"deploymentId\":\"" + deploymentId + "\"}") + .when().post("/") + .then().statusCode(200) + .extract().jsonPath().getString("deploymentInfo.status"); + } + Assertions.assertEquals("Succeeded", status, "Server deployment did not reach Succeeded state"); + } + + @Test + @Order(11) + void listDeploymentTargetsForServerDeployment() { + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.ListDeploymentTargets") + .body("{\"deploymentId\":\"" + deploymentId + "\"}") + .when().post("/") + .then().statusCode(200) + .body("targetIds", hasItem("on-prem-test-1")); + } + + @Test + @Order(12) + void batchGetDeploymentTargetsForServer() { + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.BatchGetDeploymentTargets") + .body(""" + { + "deploymentId": "%s", + "targetIds": ["on-prem-test-1"] + } + """.formatted(deploymentId)) + .when().post("/") + .then().statusCode(200) + .body("deploymentTargets", hasSize(1)) + .body("deploymentTargets[0].deploymentTargetType", equalTo("InstanceTarget")) + .body("deploymentTargets[0].instanceTarget.targetId", equalTo("on-prem-test-1")) + .body("deploymentTargets[0].instanceTarget.status", equalTo("Succeeded")); + } + + @Test + @Order(13) + void deregisterOnPremisesInstance() { + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.DeregisterOnPremisesInstance") + .body("{\"instanceName\":\"on-prem-test-1\"}") + .when().post("/") + .then().statusCode(200); + + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.GetOnPremisesInstance") + .body("{\"instanceName\":\"on-prem-test-1\"}") + .when().post("/") + .then().statusCode(200) + .body("instanceInfo.registrationStatus", equalTo("Deregistered")); + } + + @Test + @Order(14) + void listOnPremisesInstancesDeregistered() { + given() + .contentType(CT) + .header("X-Amz-Target", "CodeDeploy_20141006.ListOnPremisesInstances") + .body("{\"registrationStatus\":\"Deregistered\"}") + .when().post("/") + .then().statusCode(200) + .body("instanceNames", hasItem("on-prem-test-1")); + } +}