diff --git a/README.md b/README.md index c3fb2df6f8..ade1c48ecd 100644 --- a/README.md +++ b/README.md @@ -69,8 +69,8 @@ | ECS (clusters, services, tasks) | ✅ | ❌ | | EKS (clusters, mock + real k3s) | ✅ | ❌ | | EC2 (VPCs, instances, security groups) | ✅ | ⚠️ Partial | -| CodeBuild (projects, report groups, credentials) | ✅ | ❌ | -| CodeDeploy (applications, groups, configs + 17 built-ins) | ✅ | ❌ | +| CodeBuild (real Docker build execution, S3 artifacts, CloudWatch logs) | ✅ | ❌ | +| CodeDeploy (Lambda traffic shifting, lifecycle hooks, auto-rollback) | ✅ | ❌ | | Native binary | ✅ ~40 MB | ❌ | **Broad AWS coverage. Free forever.** @@ -214,8 +214,8 @@ All default images are configurable via environment variables, useful for pinnin | **Bedrock Runtime** | In-process (stub) | Dummy Converse and InvokeModel responses for local development; streaming returns 501 | | **EKS** | **Real Docker containers** (mock mode available) | Clusters, tagging; real mode starts k3s per cluster with a live Kubernetes API server | | **ELB v2** | In-process | Application and Network Load Balancers, target groups, listeners, path/host-based routing rules, tags | -| **CodeBuild** | In-process | Projects, report groups, source credentials, curated environment images | -| **CodeDeploy** | In-process | Applications, deployment groups, deployment configs; 17 AWS built-in `CodeDeployDefault.*` configs pre-seeded | +| **CodeBuild** | In-process + **real Docker containers** | Projects, report groups, source credentials; `StartBuild` runs real Docker containers, streams logs to CloudWatch, uploads artifacts to S3 via `docker cp` (works in Docker-in-Docker) | +| **CodeDeploy** | In-process + **Lambda traffic shifting** | Applications, deployment groups, deployment configs; 17 `CodeDeployDefault.*` built-ins pre-seeded; `CreateDeployment` shifts Lambda alias `RoutingConfig` weights, invokes lifecycle hooks, auto-rolls back on failure | > **Lambda, ElastiCache, RDS, MSK, ECS, EKS, and OpenSearch** spin up real Docker containers and support IAM authentication and SigV4 request signing — the same auth flow as production AWS. **ECR** runs a shared `registry:2` container so the stock `docker` client can push and pull image bytes against repositories returned by the AWS-shaped control plane. > diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeBuildTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeBuildTest.java index 7c6e3da3e4..5cfcbce94a 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeBuildTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeBuildTest.java @@ -28,6 +28,14 @@ import software.amazon.awssdk.services.codebuild.model.ReportType; import software.amazon.awssdk.services.codebuild.model.AuthType; import software.amazon.awssdk.services.codebuild.model.ServerType; import software.amazon.awssdk.services.codebuild.model.SourceType; +import software.amazon.awssdk.services.codebuild.model.BatchGetBuildsResponse; +import software.amazon.awssdk.services.codebuild.model.Build; +import software.amazon.awssdk.services.codebuild.model.ListBuildsForProjectResponse; +import software.amazon.awssdk.services.codebuild.model.ListBuildsResponse; +import software.amazon.awssdk.services.codebuild.model.RetryBuildResponse; +import software.amazon.awssdk.services.codebuild.model.StartBuildResponse; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.codebuild.model.Tag; import software.amazon.awssdk.services.codebuild.model.UpdateProjectResponse; @@ -40,6 +48,7 @@ class CodeBuildTest { static CodeBuildClient codebuild; static String reportGroupArn; static String sourceCredentialsArn; + static String buildId; @BeforeAll static void setup() { @@ -185,4 +194,230 @@ class CodeBuildTest { ListProjectsResponse after = codebuild.listProjects(r -> r.build()); assertThat(after.projects()).doesNotContain("sdk-test-project"); } + + // ---- Phase 2: Real Build Execution ---- + + @Test + @Order(20) + void setupBuildProject() { + codebuild.createProject(r -> r + .name("build-exec-project") + .source(ProjectSource.builder() + .type(SourceType.NO_SOURCE) + .build()) + .artifacts(ProjectArtifacts.builder() + .type(ArtifactsType.NO_ARTIFACTS) + .build()) + .environment(ProjectEnvironment.builder() + .type(EnvironmentType.LINUX_CONTAINER) + .image("public.ecr.aws/docker/library/alpine:latest") + .computeType(ComputeType.BUILD_GENERAL1_SMALL) + .build()) + .serviceRole("arn:aws:iam::000000000000:role/codebuild-role")); + } + + @Test + @Order(21) + void startBuild_noSource() { + String buildspec = "version: 0.2\nphases:\n build:\n commands:\n - echo hello-from-codebuild\n"; + + StartBuildResponse resp = codebuild.startBuild(r -> r + .projectName("build-exec-project") + .buildspecOverride(buildspec)); + + assertThat(resp.build().id()).contains("build-exec-project:"); + assertThat(resp.build().arn()).contains(":build/build-exec-project:"); + assertThat(resp.build().buildStatusAsString()).isEqualTo("IN_PROGRESS"); + assertThat(resp.build().buildComplete()).isFalse(); + buildId = resp.build().id(); + } + + @Test + @Order(22) + void batchGetBuilds_eventuallySucceeds() throws InterruptedException { + assertThat(buildId).isNotNull(); + + Build build = null; + for (int i = 0; i < 30; i++) { + BatchGetBuildsResponse resp = codebuild.batchGetBuilds(r -> r.ids(buildId)); + assertThat(resp.builds()).hasSize(1); + build = resp.builds().get(0); + if (Boolean.TRUE.equals(build.buildComplete())) { + break; + } + Thread.sleep(2000); + } + + assertThat(build).isNotNull(); + assertThat(build.buildComplete()).isTrue(); + assertThat(build.buildStatusAsString()).isEqualTo("SUCCEEDED"); + assertThat(build.currentPhase()).isEqualTo("COMPLETED"); + assertThat(build.phases()).isNotEmpty(); + } + + @Test + @Order(23) + void listBuilds_containsBuildId() { + assertThat(buildId).isNotNull(); + ListBuildsResponse resp = codebuild.listBuilds(r -> r.build()); + assertThat(resp.ids()).contains(buildId); + } + + @Test + @Order(24) + void listBuildsForProject() { + ListBuildsForProjectResponse resp = codebuild.listBuildsForProject(r -> r + .projectName("build-exec-project")); + assertThat(resp.ids()).contains(buildId); + } + + @Test + @Order(25) + void retryBuild() { + assertThat(buildId).isNotNull(); + RetryBuildResponse resp = codebuild.retryBuild(r -> r.id(buildId)); + assertThat(resp.build().id()).contains("build-exec-project:"); + assertThat(resp.build().id()).isNotEqualTo(buildId); + assertThat(resp.build().buildStatusAsString()).isEqualTo("IN_PROGRESS"); + } + + @Test + @Order(26) + void stopBuild() throws InterruptedException { + // Start a new long-running build, then stop it + String longBuildspec = "version: 0.2\nphases:\n build:\n commands:\n - sleep 60\n"; + StartBuildResponse startResp = codebuild.startBuild(r -> r + .projectName("build-exec-project") + .buildspecOverride(longBuildspec)); + String longBuildId = startResp.build().id(); + + // Give it a moment to start the container + Thread.sleep(3000); + + codebuild.stopBuild(r -> r.id(longBuildId)); + + // Poll until stopped + Build build = null; + for (int i = 0; i < 20; i++) { + BatchGetBuildsResponse resp = codebuild.batchGetBuilds(r -> r.ids(longBuildId)); + build = resp.builds().get(0); + if (Boolean.TRUE.equals(build.buildComplete())) { + break; + } + Thread.sleep(1000); + } + + assertThat(build).isNotNull(); + assertThat(build.buildComplete()).isTrue(); + assertThat(build.buildStatusAsString()).isEqualTo("STOPPED"); + } + + @Test + @Order(27) + void deleteBuildProject() { + codebuild.deleteProject(r -> r.name("build-exec-project")); + } + + // ---- OS demo: list OS family + directory tree, upload to S3 ---- + + @Test + @Order(30) + void createOsBucket() { + S3Client s3 = TestFixtures.s3Client(); + s3.createBucket(r -> r.bucket("os-bucket")); + s3.close(); + } + + @Test + @Order(31) + void setupOsDemoProject() { + codebuild.createProject(r -> r + .name("os-demo-project") + .source(ProjectSource.builder() + .type(SourceType.NO_SOURCE) + .build()) + .artifacts(ProjectArtifacts.builder() + .type(ArtifactsType.S3) + .location("os-bucket") + .packaging("NONE") + .build()) + .environment(ProjectEnvironment.builder() + .type(EnvironmentType.LINUX_CONTAINER) + .image("public.ecr.aws/docker/library/alpine:latest") + .computeType(ComputeType.BUILD_GENERAL1_SMALL) + .build()) + .serviceRole("arn:aws:iam::000000000000:role/codebuild-role")); + } + + @Test + @Order(32) + void startOsDemoBuild() { + String buildspec = String.join("\n", + "version: 0.2", + "phases:", + " build:", + " commands:", + " - echo '=== OS Family ===' > command-output.txt", + " - cat /etc/os-release >> command-output.txt", + " - echo '' >> command-output.txt", + " - echo '=== Directory Tree (depth 3) ===' >> command-output.txt", + " - find / -maxdepth 3 -type d 2>/dev/null >> command-output.txt", + "artifacts:", + " files:", + " - command-output.txt" + ); + + StartBuildResponse resp = codebuild.startBuild(r -> r + .projectName("os-demo-project") + .buildspecOverride(buildspec)); + + buildId = resp.build().id(); + assertThat(buildId).contains("os-demo-project:"); + } + + @Test + @Order(33) + void osDemoBuild_eventuallySucceeds() throws InterruptedException { + assertThat(buildId).isNotNull(); + + Build build = null; + for (int i = 0; i < 30; i++) { + BatchGetBuildsResponse resp = codebuild.batchGetBuilds(r -> r.ids(buildId)); + build = resp.builds().get(0); + if (Boolean.TRUE.equals(build.buildComplete())) { + break; + } + Thread.sleep(2000); + } + + assertThat(build).isNotNull(); + assertThat(build.buildComplete()).isTrue(); + assertThat(build.buildStatusAsString()).isEqualTo("SUCCEEDED"); + } + + @Test + @Order(34) + void osDemoBuild_outputUploadedToS3() { + S3Client s3 = TestFixtures.s3Client(); + + byte[] data = s3.getObjectAsBytes(GetObjectRequest.builder() + .bucket("os-bucket") + .key("command-output.txt") + .build()).asByteArray(); + + String content = new String(data); + System.out.println("=== command-output.txt from os-bucket ==="); + System.out.println(content); + + assertThat(content).contains("NAME="); + assertThat(content).contains("/usr"); + + s3.close(); + } + + @Test + @Order(35) + void cleanupOsDemo() { + codebuild.deleteProject(r -> r.name("os-demo-project")); + } } diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployTest.java index 101048b268..e4582eb6ec 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployTest.java @@ -6,27 +6,48 @@ import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.codedeploy.CodeDeployClient; +import software.amazon.awssdk.services.codedeploy.model.AppSpecContent; import software.amazon.awssdk.services.codedeploy.model.BatchGetApplicationsResponse; import software.amazon.awssdk.services.codedeploy.model.BatchGetDeploymentGroupsResponse; +import software.amazon.awssdk.services.codedeploy.model.BatchGetDeploymentsResponse; +import software.amazon.awssdk.services.codedeploy.model.BatchGetDeploymentTargetsResponse; import software.amazon.awssdk.services.codedeploy.model.ComputePlatform; import software.amazon.awssdk.services.codedeploy.model.CreateApplicationResponse; import software.amazon.awssdk.services.codedeploy.model.CreateDeploymentConfigResponse; import software.amazon.awssdk.services.codedeploy.model.CreateDeploymentGroupResponse; +import software.amazon.awssdk.services.codedeploy.model.CreateDeploymentResponse; import software.amazon.awssdk.services.codedeploy.model.DeploymentOption; import software.amazon.awssdk.services.codedeploy.model.DeploymentReadyAction; +import software.amazon.awssdk.services.codedeploy.model.DeploymentStatus; import software.amazon.awssdk.services.codedeploy.model.DeploymentStyle; import software.amazon.awssdk.services.codedeploy.model.DeploymentType; import software.amazon.awssdk.services.codedeploy.model.GetDeploymentConfigResponse; import software.amazon.awssdk.services.codedeploy.model.GetDeploymentGroupResponse; +import software.amazon.awssdk.services.codedeploy.model.GetDeploymentResponse; import software.amazon.awssdk.services.codedeploy.model.ListApplicationsResponse; import software.amazon.awssdk.services.codedeploy.model.ListDeploymentConfigsResponse; import software.amazon.awssdk.services.codedeploy.model.ListDeploymentGroupsResponse; +import software.amazon.awssdk.services.codedeploy.model.ListDeploymentTargetsResponse; +import software.amazon.awssdk.services.codedeploy.model.ListDeploymentsResponse; import software.amazon.awssdk.services.codedeploy.model.ListTagsForResourceResponse; import software.amazon.awssdk.services.codedeploy.model.MinimumHealthyHosts; import software.amazon.awssdk.services.codedeploy.model.MinimumHealthyHostsType; +import software.amazon.awssdk.services.codedeploy.model.RevisionLocation; +import software.amazon.awssdk.services.codedeploy.model.RevisionLocationType; import software.amazon.awssdk.services.codedeploy.model.Tag; import software.amazon.awssdk.services.codedeploy.model.TrafficRoutingType; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.lambda.model.CreateAliasResponse; +import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest; +import software.amazon.awssdk.services.lambda.model.FunctionCode; +import software.amazon.awssdk.services.lambda.model.GetAliasResponse; +import software.amazon.awssdk.services.lambda.model.PublishVersionResponse; +import software.amazon.awssdk.services.lambda.model.Runtime; +import software.amazon.awssdk.services.lambda.model.UpdateAliasRequest; + +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -35,17 +56,27 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; class CodeDeployTest { static CodeDeployClient codedeploy; + static LambdaClient lambda; static String appId; static String dgId; + static final String DEPLOY_FUNCTION = "cd-deploy-fn"; + static final String DEPLOY_ALIAS = "live"; + static final String ROLE = "arn:aws:iam::000000000000:role/lambda-role"; + static String deploymentId; + static String v1; + static String v2; + @BeforeAll static void setup() { codedeploy = TestFixtures.codeDeployClient(); + lambda = TestFixtures.lambdaClient(); } @AfterAll static void teardown() { codedeploy.close(); + lambda.close(); } @Test @@ -248,4 +279,187 @@ class CodeDeployTest { ListApplicationsResponse after = codedeploy.listApplications(r -> r.build()); assertThat(after.applications()).doesNotContain("sdk-lambda-app"); } + + // ---- Phase 2: Lambda deployment via CodeDeploy ---- + + @Test + @Order(20) + void setupLambdaFunctionForDeployment() { + // Create function and publish two versions, alias pointing to v1 + lambda.createFunction(CreateFunctionRequest.builder() + .functionName(DEPLOY_FUNCTION) + .runtime(Runtime.NODEJS20_X) + .role(ROLE) + .handler("index.handler") + .code(FunctionCode.builder() + .zipFile(SdkBytes.fromByteArray(LambdaUtils.minimalZip())) + .build()) + .build()); + + PublishVersionResponse pv1 = lambda.publishVersion(r -> r.functionName(DEPLOY_FUNCTION)); + v1 = pv1.version(); + assertThat(v1).isNotBlank(); + + PublishVersionResponse pv2 = lambda.publishVersion(r -> r.functionName(DEPLOY_FUNCTION)); + v2 = pv2.version(); + assertThat(v2).isNotBlank().isNotEqualTo(v1); + + CreateAliasResponse alias = lambda.createAlias(r -> r + .functionName(DEPLOY_FUNCTION) + .name(DEPLOY_ALIAS) + .functionVersion(v1)); + assertThat(alias.aliasArn()).contains(DEPLOY_FUNCTION); + } + + @Test + @Order(21) + void setupCodeDeployAppAndGroupForDeployment() { + codedeploy.createApplication(r -> r + .applicationName("cd-lambda-app") + .computePlatform(ComputePlatform.LAMBDA)); + + codedeploy.createDeploymentGroup(r -> r + .applicationName("cd-lambda-app") + .deploymentGroupName("cd-lambda-dg") + .deploymentConfigName("CodeDeployDefault.LambdaAllAtOnce") + .serviceRoleArn("arn:aws:iam::000000000000:role/codedeploy-role")); + } + + @Test + @Order(22) + void createDeployment_allAtOnce() { + String appSpec = """ + { + "version": "0.0", + "Resources": [{ + "myFunction": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Name": "%s", + "Alias": "%s", + "CurrentVersion": "%s", + "TargetVersion": "%s" + } + } + }] + } + """.formatted(DEPLOY_FUNCTION, DEPLOY_ALIAS, v1, v2); + + CreateDeploymentResponse resp = codedeploy.createDeployment(r -> r + .applicationName("cd-lambda-app") + .deploymentGroupName("cd-lambda-dg") + .deploymentConfigName("CodeDeployDefault.LambdaAllAtOnce") + .revision(RevisionLocation.builder() + .revisionType(RevisionLocationType.APP_SPEC_CONTENT) + .appSpecContent(AppSpecContent.builder() + .content(appSpec) + .build()) + .build())); + + assertThat(resp.deploymentId()).startsWith("d-"); + deploymentId = resp.deploymentId(); + } + + @Test + @Order(23) + void getDeployment_returnsInfo() { + assertThat(deploymentId).isNotNull(); + + GetDeploymentResponse resp = codedeploy.getDeployment(r -> r.deploymentId(deploymentId)); + assertThat(resp.deploymentInfo().deploymentId()).isEqualTo(deploymentId); + assertThat(resp.deploymentInfo().applicationName()).isEqualTo("cd-lambda-app"); + assertThat(resp.deploymentInfo().deploymentGroupName()).isEqualTo("cd-lambda-dg"); + assertThat(resp.deploymentInfo().status()).isIn( + DeploymentStatus.QUEUED, DeploymentStatus.IN_PROGRESS, DeploymentStatus.SUCCEEDED); + } + + @Test + @Order(24) + void getDeployment_eventuallySucceeds() throws InterruptedException { + assertThat(deploymentId).isNotNull(); + + DeploymentStatus status = DeploymentStatus.QUEUED; + for (int i = 0; i < 20 && !DeploymentStatus.SUCCEEDED.equals(status); i++) { + Thread.sleep(500); + GetDeploymentResponse resp = codedeploy.getDeployment(r -> r.deploymentId(deploymentId)); + status = resp.deploymentInfo().status(); + } + assertThat(status).isEqualTo(DeploymentStatus.SUCCEEDED); + } + + @Test + @Order(25) + void aliasPointsToTargetVersionAfterDeployment() { + GetAliasResponse alias = lambda.getAlias(r -> r + .functionName(DEPLOY_FUNCTION) + .name(DEPLOY_ALIAS)); + assertThat(alias.functionVersion()).isEqualTo(v2); + assertThat(alias.routingConfig()).isNull(); + } + + @Test + @Order(26) + void listDeployments_containsDeploymentId() { + assertThat(deploymentId).isNotNull(); + + ListDeploymentsResponse resp = codedeploy.listDeployments(r -> r + .applicationName("cd-lambda-app") + .deploymentGroupName("cd-lambda-dg")); + assertThat(resp.deployments()).contains(deploymentId); + } + + @Test + @Order(27) + void batchGetDeployments_returnsDeploymentInfo() { + assertThat(deploymentId).isNotNull(); + + BatchGetDeploymentsResponse resp = codedeploy.batchGetDeployments(r -> r + .deploymentIds(deploymentId)); + assertThat(resp.deploymentsInfo()).hasSize(1); + assertThat(resp.deploymentsInfo().get(0).deploymentId()).isEqualTo(deploymentId); + assertThat(resp.deploymentsInfo().get(0).status()).isEqualTo(DeploymentStatus.SUCCEEDED); + } + + @Test + @Order(28) + void listDeploymentTargets_returnsSingleTarget() { + assertThat(deploymentId).isNotNull(); + + ListDeploymentTargetsResponse resp = codedeploy.listDeploymentTargets(r -> r + .deploymentId(deploymentId)); + assertThat(resp.targetIds()).hasSize(1); + assertThat(resp.targetIds().get(0)).contains(DEPLOY_FUNCTION); + } + + @Test + @Order(29) + void batchGetDeploymentTargets_returnsLambdaTarget() { + assertThat(deploymentId).isNotNull(); + + ListDeploymentTargetsResponse listResp = codedeploy.listDeploymentTargets(r -> r + .deploymentId(deploymentId)); + List targetIds = listResp.targetIds(); + + BatchGetDeploymentTargetsResponse resp = codedeploy.batchGetDeploymentTargets(r -> r + .deploymentId(deploymentId) + .targetIds(targetIds)); + assertThat(resp.deploymentTargets()).hasSize(1); + assertThat(resp.deploymentTargets().get(0).deploymentTargetTypeAsString()) + .isEqualTo("LambdaFunction"); + assertThat(resp.deploymentTargets().get(0).lambdaTarget()).isNotNull(); + assertThat(resp.deploymentTargets().get(0).lambdaTarget().statusAsString()) + .isEqualTo("Succeeded"); + assertThat(resp.deploymentTargets().get(0).lambdaTarget().lifecycleEvents()) + .anyMatch(e -> "AllowTraffic".equals(e.lifecycleEventName())); + } + + @Test + @Order(30) + void cleanupDeployment() { + lambda.deleteFunction(r -> r.functionName(DEPLOY_FUNCTION)); + codedeploy.deleteDeploymentGroup(r -> r + .applicationName("cd-lambda-app") + .deploymentGroupName("cd-lambda-dg")); + codedeploy.deleteApplication(r -> r.applicationName("cd-lambda-app")); + } } diff --git a/docs/index.md b/docs/index.md index cff01e87ef..8b159139d9 100644 --- a/docs/index.md +++ b/docs/index.md @@ -12,7 +12,7 @@ Floci is a fast, free, and open-source local AWS service emulator built for deve ## Supported Services -Floci emulates 31 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details. +Floci emulates 41 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details. | Service | Protocol | |---|---| @@ -38,11 +38,21 @@ Floci emulates 31 AWS services. See the [Services Overview](services/index.md) f | ECS | JSON 1.1 | | EC2 | EC2 Query | | ACM | JSON 1.1 | +| ECR | JSON 1.1 + OCI Distribution | | OpenSearch | REST JSON | | EventBridge | JSON 1.1 | | EventBridge Scheduler | REST JSON | | CloudWatch Logs & Metrics | JSON 1.1 / Query | | AppConfig + AppConfigData | REST JSON | +| Bedrock Runtime | REST JSON | +| EKS | REST JSON | +| ELB v2 | Query | +| MSK | REST JSON | +| Athena | JSON 1.1 | +| Glue | JSON 1.1 | +| Data Firehose | JSON 1.1 | +| CodeBuild | JSON 1.1 | +| CodeDeploy | JSON 1.1 | ## Why Floci? @@ -78,7 +88,7 @@ docker compose up -d aws --endpoint-url http://localhost:4566 s3 mb s3://my-bucket ``` -All 31 AWS services are immediately available at `http://localhost:4566`. +All 41 AWS services are immediately available at `http://localhost:4566`. [Get started →](getting-started/quick-start.md){ .md-button .md-button--primary } [View services →](services/index.md){ .md-button } \ No newline at end of file diff --git a/docs/services/codebuild.md b/docs/services/codebuild.md index a687f0ce69..3ad0c8ff39 100644 --- a/docs/services/codebuild.md +++ b/docs/services/codebuild.md @@ -1,6 +1,6 @@ # CodeBuild -Floci implements the CodeBuild management API (Phase 1) — stored-state CRUD for projects, report groups, and source credentials. Build execution (Phase 2) is not yet implemented. +Floci implements the CodeBuild API — stored-state management plus real build execution inside Docker containers. **Protocol:** JSON 1.1 — `POST /` with `X-Amz-Target: CodeBuild_20161006.` @@ -9,8 +9,11 @@ Floci implements the CodeBuild management API (Phase 1) — stored-state CRUD fo - `arn:aws:codebuild:::project/` - `arn:aws:codebuild:::report-group/` - `arn:aws:codebuild:::token/-` +- `arn:aws:codebuild:::build/:` -## Supported Operations (Phase 1 — 14 total) +## Supported Operations (20 total) + +### Projects | Operation | Notes | |---|---| @@ -19,16 +22,68 @@ Floci implements the CodeBuild management API (Phase 1) — stored-state CRUD fo | `DeleteProject` | Removes project by name | | `BatchGetProjects` | Returns found projects and a `projectsNotFound` list | | `ListProjects` | Returns all project names in the region | + +### Build Execution + +| Operation | Notes | +|---|---| +| `StartBuild` | Launches a real Docker container using the project's image; runs buildspec phases (`INSTALL`, `PRE_BUILD`, `BUILD`, `POST_BUILD`); returns immediately with `IN_PROGRESS` status | +| `BatchGetBuilds` | Returns current build state; poll until `buildComplete` is `true` | +| `ListBuilds` | Returns all build IDs in the region, most recent first | +| `ListBuildsForProject` | Returns build IDs for a specific project | +| `StopBuild` | Signals a running build to stop; build transitions to `STOPPED` | +| `RetryBuild` | Starts a new build using the same config as a completed build; returns a new build record | + +### Report Groups + +| Operation | Notes | +|---|---| | `CreateReportGroup` | Stores report group config | | `UpdateReportGroup` | Partial update by ARN | | `DeleteReportGroup` | Removes report group by ARN | | `BatchGetReportGroups` | Returns found report groups and a `reportGroupsNotFound` list | | `ListReportGroups` | Returns all report group ARNs in the region | -| `ImportSourceCredentials` | Stores server type and auth type; token is accepted but not returned | + +### Source Credentials + +| Operation | Notes | +|---|---| +| `ImportSourceCredentials` | Stores server type and auth type; deduplicated by `serverType+authType`; token is accepted but not returned | | `ListSourceCredentials` | Returns stored credential metadata (no tokens) | | `DeleteSourceCredentials` | Removes source credentials by ARN | + +### Images + +| Operation | Notes | +|---|---| | `ListCuratedEnvironmentImages` | Returns a static list of standard CodeBuild images for AL2 and Ubuntu | +## Build Execution Model + +Each `StartBuild` call: + +1. Pulls the project's Docker image (e.g. `public.ecr.aws/docker/library/alpine:latest`) +2. Starts a container with the working directories pre-created +3. Injects source files into the container via `docker cp` (`NO_SOURCE` builds skip this step) +4. Executes buildspec phases sequentially inside the container via `docker exec` +5. Streams phase output to CloudWatch Logs under `/aws/codebuild/` +6. Extracts artifact files from the container via `docker cp` and uploads them to S3 if `artifacts.type=S3` +7. Marks the build complete with `SUCCEEDED`, `FAILED`, or `STOPPED` + +Source injection and artifact extraction both use the Docker API's archive copy endpoints — no bind mounts are required. This works correctly when Floci itself runs inside a Docker container (Docker-in-Docker). + +## Buildspec Support + +Floci parses the `buildspec.yml` embedded in the project or provided via `buildspecOverride`. Supported fields: + +- `phases` — `install`, `pre_build`, `build`, `post_build` command lists +- `artifacts.files` — list of file patterns to collect; supports `**/*` glob, specific filenames, and path patterns +- `artifacts.base-directory` — base directory for artifact collection (default: `$CODEBUILD_SRC_DIR`) + +## Artifact Upload + +When `artifacts.type=S3`, collected files are uploaded to the configured S3 bucket. The bucket must exist (created via `CreateBucket`). File paths in S3 match the relative path from the artifact base directory. + ## Configuration ```yaml @@ -41,21 +96,32 @@ floci: ## CLI Examples ```bash -# Create a project +# Create a project with S3 artifacts aws --endpoint-url http://localhost:4566 codebuild create-project \ --name my-project \ - --source type=S3,location=my-bucket/source.zip \ - --artifacts type=NO_ARTIFACTS \ - --environment type=LINUX_CONTAINER,image=aws/codebuild/standard:7.0,computeType=BUILD_GENERAL1_SMALL \ + --source type=NO_SOURCE \ + --artifacts type=S3,location=my-bucket \ + --environment type=LINUX_CONTAINER,image=public.ecr.aws/docker/library/alpine:latest,computeType=BUILD_GENERAL1_SMALL \ --service-role arn:aws:iam::000000000000:role/codebuild-role -# List projects -aws --endpoint-url http://localhost:4566 codebuild list-projects +# Start a build with inline buildspec +aws --endpoint-url http://localhost:4566 codebuild start-build \ + --project-name my-project \ + --buildspec-override 'version: 0.2 +phases: + build: + commands: + - echo hello > output.txt +artifacts: + files: + - output.txt' + +# Poll until complete +aws --endpoint-url http://localhost:4566 codebuild batch-get-builds --ids + +# List all builds +aws --endpoint-url http://localhost:4566 codebuild list-builds # List curated images aws --endpoint-url http://localhost:4566 codebuild list-curated-environment-images ``` - -## Phase 2 (not yet implemented) - -`StartBuild`, `BatchGetBuilds`, `StopBuild`, `ListBuilds`, `ListBuildsForProject`, `RetryBuild`. Builds will execute buildspecs in real Docker containers, stream logs to CloudWatch, and upload artifacts to S3. diff --git a/docs/services/codedeploy.md b/docs/services/codedeploy.md index fec17eaff2..ead41e06aa 100644 --- a/docs/services/codedeploy.md +++ b/docs/services/codedeploy.md @@ -1,6 +1,6 @@ # CodeDeploy -Floci implements the CodeDeploy management API (Phase 1) — stored-state CRUD for applications, deployment groups, and deployment configurations. Built-in deployment configurations are pre-seeded and always available. Deployment execution (Phase 2) is not yet implemented. +Floci implements the CodeDeploy API — stored-state management for applications, deployment groups, and configs, plus real Lambda deployment execution with traffic shifting and lifecycle hooks. **Protocol:** JSON 1.1 — `POST /` with `X-Amz-Target: CodeDeploy_20141006.` @@ -8,8 +8,12 @@ Floci implements the CodeDeploy management API (Phase 1) — stored-state CRUD f - `arn:aws:codedeploy:::application:` - `arn:aws:codedeploy:::deploymentgroup:/` +- `arn:aws:codedeploy:::deploymentconfig:` +- `arn:aws:codedeploy:::deployment:` -## Supported Operations (Phase 1 — 21 total) +## Supported Operations (30 total) + +### Applications | Operation | Notes | |---|---| @@ -19,19 +23,53 @@ Floci implements the CodeDeploy management API (Phase 1) — stored-state CRUD f | `DeleteApplication` | Removes application and all its deployment groups | | `ListApplications` | Returns all application names | | `BatchGetApplications` | Returns info for multiple applications | + +### Deployment Groups + +| Operation | Notes | +|---|---| | `CreateDeploymentGroup` | Stores group config; deployment config defaults to `CodeDeployDefault.OneAtATime` | | `GetDeploymentGroup` | Returns group metadata | | `UpdateDeploymentGroup` | Partial update; supports rename via `newDeploymentGroupName` | | `DeleteDeploymentGroup` | Returns `hooksNotCleanedUp: []` | | `ListDeploymentGroups` | Returns all group names for an application | | `BatchGetDeploymentGroups` | Returns info for multiple groups | + +### Deployment Configs + +| Operation | Notes | +|---|---| | `CreateDeploymentConfig` | Creates a custom config; names starting with `CodeDeployDefault.` are rejected | | `GetDeploymentConfig` | Returns config including built-ins | | `DeleteDeploymentConfig` | Custom configs only; built-ins cannot be deleted | | `ListDeploymentConfigs` | Returns all configs including all 17 pre-seeded built-ins | + +### Deployment Execution + +| Operation | Notes | +|---|---| +| `CreateDeployment` | Starts a real Lambda deployment: shifts alias `RoutingConfig` weights for canary/linear strategies; invokes lifecycle hooks | +| `GetDeployment` | Returns current deployment state; poll `status` until `Succeeded`, `Failed`, or `Stopped` | +| `StopDeployment` | Signals an in-progress deployment to stop; transitions to `Stopped` | +| `ContinueDeployment` | Accepted (no-op for fully automated deployments) | +| `ListDeployments` | Returns deployment IDs filtered by application, group, or status | +| `BatchGetDeployments` | Returns info for multiple deployments | +| `ListDeploymentTargets` | Returns target IDs for a deployment | +| `BatchGetDeploymentTargets` | Returns target details including lifecycle event status | +| `PutLifecycleEventHookExecutionStatus` | Called by lifecycle hook Lambda to report `Succeeded` or `Failed`; failure triggers auto-rollback | + +### Tagging + +| Operation | Notes | +|---|---| | `TagResource` | Tags any resource by ARN | | `UntagResource` | Removes specific tag keys | | `ListTagsForResource` | Returns tags for a resource ARN | + +### On-Premises (no-op) + +| Operation | Notes | +|---|---| | `AddTagsToOnPremisesInstances` | Accepted, no-op | | `RemoveTagsFromOnPremisesInstances` | Accepted, no-op | @@ -62,6 +100,17 @@ The following 17 configurations are always available (matching real AWS): - `CodeDeployDefault.ECSLinear10PercentEvery1Minutes` - `CodeDeployDefault.ECSLinear10PercentEvery3Minutes` +## Lambda Deployment Model + +For `computePlatform: Lambda`, `CreateDeployment` performs real traffic shifting: + +1. Reads the deployment group's `deploymentStyle` and `deploymentConfigName` to determine the traffic shift strategy +2. For **canary** and **linear** strategies: updates the Lambda alias `RoutingConfig` to route a percentage to the new function version, waits the configured interval, then shifts to 100% +3. For **all-at-once**: shifts directly to 100% of the new version +4. Invokes `BeforeAllowTraffic` lifecycle hook Lambda (if configured) and waits for `PutLifecycleEventHookExecutionStatus` callback +5. Invokes `AfterAllowTraffic` lifecycle hook Lambda (if configured) and waits for the callback +6. If any lifecycle hook reports `Failed`, auto-rolls back the alias to the previous version and marks the deployment `Failed` + ## Configuration ```yaml @@ -79,17 +128,23 @@ aws --endpoint-url http://localhost:4566 deploy create-application \ --application-name my-app \ --compute-platform Lambda -# List built-in deployment configs -aws --endpoint-url http://localhost:4566 deploy list-deployment-configs - -# Create a deployment group +# Create a deployment group for Lambda aws --endpoint-url http://localhost:4566 deploy create-deployment-group \ --application-name my-app \ --deployment-group-name my-group \ - --deployment-config-name CodeDeployDefault.LambdaAllAtOnce \ - --service-role-arn arn:aws:iam::000000000000:role/codedeploy-role + --deployment-config-name CodeDeployDefault.LambdaCanary10Percent5Minutes \ + --service-role-arn arn:aws:iam::000000000000:role/codedeploy-role \ + --deployment-style deploymentType=BLUE_GREEN,deploymentOption=WITH_TRAFFIC_CONTROL + +# Start a deployment +aws --endpoint-url http://localhost:4566 deploy create-deployment \ + --application-name my-app \ + --deployment-group-name my-group \ + --revision revisionType=AppSpecContent,appSpecContent={content='{"version":0.0,"Resources":[{"myFunction":{"Type":"AWS::Lambda::Function","Properties":{"Name":"my-function","Alias":"live","CurrentVersion":"1","TargetVersion":"2"}}}]}'} + +# Poll deployment status +aws --endpoint-url http://localhost:4566 deploy get-deployment --deployment-id + +# List built-in deployment configs +aws --endpoint-url http://localhost:4566 deploy list-deployment-configs ``` - -## Phase 2 (not yet implemented) - -`CreateDeployment`, `GetDeployment`, `StopDeployment`, `ContinueDeployment` with real Lambda traffic-shifting (updating alias `RoutingConfig` weights). Phase 2 focuses on the `computePlatform: Lambda` path since Lambda is already fully real in Floci. diff --git a/docs/services/index.md b/docs/services/index.md index 22a2dda41b..247234d1e4 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -49,8 +49,8 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Athena](athena.md) | `POST /` + `X-Amz-Target: AmazonAthena.*` | JSON 1.1 | 8 | | [Glue](glue.md) | `POST /` + `X-Amz-Target: AWSGlue.*` | JSON 1.1 | 15 | | [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 6 | -| [CodeBuild](codebuild.md) | `POST /` + `X-Amz-Target: CodeBuild_20161006.*` | JSON 1.1 | 14 | -| [CodeDeploy](codedeploy.md) | `POST /` + `X-Amz-Target: CodeDeploy_20141006.*` | JSON 1.1 | 21 | +| [CodeBuild](codebuild.md) | `POST /` + `X-Amz-Target: CodeBuild_20161006.*` | JSON 1.1 | 20 | +| [CodeDeploy](codedeploy.md) | `POST /` + `X-Amz-Target: CodeDeploy_20141006.*` | JSON 1.1 | 30 | **Lambda, ElastiCache, RDS, MSK, ECS, EKS, and OpenSearch** spin up real Docker containers and support IAM authentication and SigV4 request signing, the same auth flow as production AWS. diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 31be1ea32c..783f3ffac8 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -277,6 +277,8 @@ public interface EmulatorConfig { interface CodeBuildServiceConfig { @WithDefault("true") boolean enabled(); + + Optional dockerNetwork(); } interface CodeDeployServiceConfig { diff --git a/src/main/java/io/github/hectorvent/floci/services/codebuild/BuildspecParser.java b/src/main/java/io/github/hectorvent/floci/services/codebuild/BuildspecParser.java new file mode 100644 index 0000000000..cbcc387495 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/codebuild/BuildspecParser.java @@ -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 envVariables, + Map parameterStoreVars, + Map secretsManagerVars, + List installCommands, + List preBuildCommands, + List buildCommands, + List postBuildCommands, + ParsedArtifacts artifacts + ) {} + + record ParsedArtifacts( + String type, + List 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 envVars = parseStringMap(envNode.path("variables")); + Map paramStore = parseStringMap(envNode.path("parameter-store")); + Map secretsMgr = parseStringMap(envNode.path("secrets-manager")); + + JsonNode phases = root.path("phases"); + List install = parseCommands(phases.path("install")); + List preBuild = parseCommands(phases.path("pre_build")); + List build = parseCommands(phases.path("build")); + List 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 parseCommands(JsonNode phaseNode) { + if (phaseNode.isMissingNode() || phaseNode.isNull()) { + return List.of(); + } + List result = new ArrayList<>(); + for (JsonNode cmd : phaseNode.path("commands")) { + result.add(cmd.asText()); + } + return result; + } + + private static Map parseStringMap(JsonNode node) { + Map 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 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); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildJsonHandler.java index 363027e936..f56c43e0f9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildJsonHandler.java @@ -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> vars = new ArrayList<>(); + for (JsonNode v : req.get("environmentVariablesOverride")) { + Map 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 ids = new ArrayList<>(); + req.path("ids").forEach(n -> ids.add(n.asText())); + List found = service.batchGetBuilds(region, ids); + List foundIds = found.stream().map(Build::getId).toList(); + List 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 List parseList(JsonNode req, String field, Class type) throws Exception { if (!req.has(field) || req.get(field).isNull()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java new file mode 100644 index 0000000000..a77a289df7 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java @@ -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 runningContainers = new ConcurrentHashMap<>(); + private final ConcurrentHashMap 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 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 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 buildEnvList(String region, Build build, Project project, + ParsedBuildspec buildspec, String logStream) { + Map 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 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 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 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 v : build.getEnvironment().getEnvironmentVariables()) { + String name = v.get("name"); + String value = v.get("value"); + if (name != null) { env.put(name, value != null ? value : ""); } + } + } + + List 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) 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 env, + List 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() { + @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 filePatterns = artifacts.files(); + if (filePatterns.isEmpty()) { + return; + } + + Path baseDir = workspace; + if (artifacts.baseDirectory() != null) { + baseDir = workspace.resolve(artifacts.baseDirectory()); + } + + List 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 collectFiles(Path baseDir, List patterns) throws IOException { + List 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 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 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); } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildService.java b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildService.java index 611af05faf..3fb6b25143 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildService.java +++ b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildService.java @@ -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> reportGroups = new ConcurrentHashMap<>(); // key: region -> arn -> source credential (token is stored but never returned) private final ConcurrentHashMap> sourceCredentials = new ConcurrentHashMap<>(); + // key: region -> buildId -> build + private final ConcurrentHashMap> builds = new ConcurrentHashMap<>(); + // key: region:projectName -> build counter + private final ConcurrentHashMap 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 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 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 batchGetBuilds(String region, List buildIds) { + Map store = buildsFor(region); + return buildIds.stream() + .map(store::get) + .filter(b -> b != null) + .collect(Collectors.toList()); + } + + public List 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 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); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/codebuild/model/Build.java b/src/main/java/io/github/hectorvent/floci/services/codebuild/model/Build.java new file mode 100644 index 0000000000..a146f4c831 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/codebuild/model/Build.java @@ -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 logs; + private List 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 getLogs() { return logs; } + public void setLogs(Map logs) { this.logs = logs; } + + public List getPhases() { return phases; } + public void setPhases(List 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; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/codebuild/model/BuildPhase.java b/src/main/java/io/github/hectorvent/floci/services/codebuild/model/BuildPhase.java new file mode 100644 index 0000000000..b3250a74c5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/codebuild/model/BuildPhase.java @@ -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> 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> getContexts() { return contexts; } + public void setContexts(List> contexts) { this.contexts = contexts; } +} 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 0c7c220587..30ba735edb 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 @@ -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 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 statuses = new ArrayList<>(); + req.path("includeOnlyStatuses").forEach(n -> statuses.add(n.asText())); + List 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 result = service.stopDeployment(region, id); + return Response.ok(result).build(); + } + + private Response batchGetDeployments(JsonNode req, String region) { + List ids = new ArrayList<>(); + req.path("deploymentIds").forEach(n -> ids.add(n.asText())); + List 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 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 targetIds = new ArrayList<>(); + req.path("targetIds").forEach(n -> targetIds.add(n.asText())); + List> 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 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 9ae9459b2c..2fc4f73117 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 @@ -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> applications = new ConcurrentHashMap<>(); // key: region -> appName -> groupName -> group @@ -26,6 +49,35 @@ public class CodeDeployService { private final ConcurrentHashMap> deploymentConfigs = new ConcurrentHashMap<>(); // key: resourceArn -> tags 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: lifecycleEventHookExecutionId -> CompletableFuture + private final ConcurrentHashMap> hookFutures = new ConcurrentHashMap<>(); + // key: deploymentId -> stop flag + private final ConcurrentHashMap 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 BUILT_IN_CONFIG_NAMES = List.of( "CodeDeployDefault.OneAtATime", @@ -335,6 +387,420 @@ public class CodeDeployService { return new ArrayList<>(deploymentConfigsFor(region).keySet()); } + // ---- Deployments ---- + + private Map deploymentsFor(String region) { + return deployments.computeIfAbsent(region, r -> new ConcurrentHashMap<>()); + } + + private Map> deploymentTargetsFor(String region) { + return deploymentTargets.computeIfAbsent(region, r -> new ConcurrentHashMap<>()); + } + + public String createDeployment(String region, String appName, String groupName, + String configName, Map 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 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 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 listDeployments(String region, String appName, String groupName, List 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 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 batchGetDeployments(String region, List ids) { + Map 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 listDeploymentTargets(String region, String deploymentId) { + getDeployment(region, deploymentId); + Map target = deploymentTargetsFor(region).get(deploymentId); + if (target == null) { + return List.of(); + } + @SuppressWarnings("unchecked") + Map lambdaTarget = (Map) target.get("lambdaTarget"); + String targetId = lambdaTarget != null ? (String) lambdaTarget.get("targetId") : null; + return targetId != null ? List.of(targetId) : List.of(); + } + + public List> batchGetDeploymentTargets(String region, String deploymentId, List targetIds) { + getDeployment(region, deploymentId); + Map target = deploymentTargetsFor(region).get(deploymentId); + if (target == null) { + return List.of(); + } + @SuppressWarnings("unchecked") + Map lambdaTarget = (Map) 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 future = hookFutures.get(executionId); + if (future != null && !future.isDone()) { + future.complete(status); + } + return executionId; + } + + // ---- Deployment state machine ---- + + @SuppressWarnings("unchecked") + private AppSpecInfo parseAppSpec(Map 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) 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 trc = (Map) cfg.getTrafficRoutingConfig(); + String type = (String) trc.getOrDefault("type", "AllAtOnce"); + + if ("TimeBasedCanary".equals(type)) { + Map canary = (Map) 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 linear = (Map) 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 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 lambdaTargetMap, + AtomicBoolean stopFlag) throws InterruptedException { + TrafficRoutingInfo trc = getTrafficRoutingInfo(region, configName); + Map event = addLifecycleEvent(lambdaTargetMap, "AllowTraffic"); + + try { + switch (trc.type) { + case "TimeBasedCanary" -> { + // Step 1: shift canaryPercentage to targetVersion + double canaryWeight = trc.percentage / 100.0; + Map 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 lambdaTargetMap, + AtomicBoolean stopFlag) throws InterruptedException { + String executionId = UUID.randomUUID().toString(); + CompletableFuture future = new CompletableFuture<>(); + hookFutures.put(executionId, future); + + Map 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 addLifecycleEvent(Map lambdaTargetMap, String name) { + Map event = new ConcurrentHashMap<>(); + event.put("lifecycleEventName", name); + event.put("startTime", Instant.now().toEpochMilli() / 1000.0); + event.put("status", "InProgress"); + List> events = (List>) lambdaTargetMap.get("lifecycleEvents"); + if (events != null) { + events.add(event); + } + lambdaTargetMap.put("lastUpdatedAt", Instant.now().toEpochMilli() / 1000.0); + return event; + } + + private void finishLifecycleEvent(Map event, String status) { + event.put("endTime", Instant.now().toEpochMilli() / 1000.0); + event.put("status", status); + } + + private void updateTargetStatus(Map lambdaTargetMap, String status) { + lambdaTargetMap.put("status", status); + lambdaTargetMap.put("lastUpdatedAt", Instant.now().toEpochMilli() / 1000.0); + } + + private void finishStopped(Deployment deployment, Map lambdaTargetMap) { + updateTargetStatus(lambdaTargetMap, "Skipped"); + deployment.setStatus("Stopped"); + deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0); + } + + private void finishFailed(Deployment deployment, Map 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> tagList) { diff --git a/src/main/java/io/github/hectorvent/floci/services/codedeploy/model/Deployment.java b/src/main/java/io/github/hectorvent/floci/services/codedeploy/model/Deployment.java new file mode 100644 index 0000000000..9ae98620f5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/codedeploy/model/Deployment.java @@ -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 revision; + private Double createTime; + private Double startTime; + private Double completeTime; + private Map 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 getRevision() { return revision; } + public void setRevision(Map 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 getErrorInformation() { return errorInformation; } + public void setErrorInformation(Map 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; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java index f302f45640..c1a0bb171e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java @@ -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 routingConfig = extractRoutingConfig((Map) 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 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 routingConfig = extractRoutingConfig((Map) 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 result = objectMapper.convertValue(node, Map.class); return result; } + @SuppressWarnings("unchecked") + private Map extractRoutingConfig(Map rc) { + if (rc == null) return null; + Object weights = rc.get("AdditionalVersionWeights"); + if (!(weights instanceof Map)) return null; + Map raw = (Map) weights; + if (raw.isEmpty()) return null; + java.util.Map result = new java.util.HashMap<>(); + raw.forEach((k, v) -> result.put(k, ((Number) v).doubleValue())); + return result; + } + private Map buildFunctionConfiguration(LambdaFunction fn) { ObjectNode node = objectMapper.createObjectNode(); node.put("FunctionName", fn.getFunctionName()); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java index af8de1c46f..83599b556f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java @@ -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 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 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 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 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 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaAlias.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaAlias.java index aa8aad82c5..a2e6787503 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaAlias.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaAlias.java @@ -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 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 getRoutingConfig() { return routingConfig; } + public void setRoutingConfig(Map routingConfig) { this.routingConfig = routingConfig; } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index ffaa28fa31..941f5ce09e 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -221,5 +221,6 @@ floci: enabled: true codebuild: enabled: true + # docker-network: floci-network codedeploy: enabled: true diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index c10f767c68..6345860c08 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -151,5 +151,6 @@ floci: enabled: true codebuild: enabled: true + # docker-network: floci-network codedeploy: enabled: true