diff --git a/compatibility-tests/sdk-test-awscli/test/lambda-microvms.bats b/compatibility-tests/sdk-test-awscli/test/lambda-microvms.bats new file mode 100644 index 0000000000..1802575324 --- /dev/null +++ b/compatibility-tests/sdk-test-awscli/test/lambda-microvms.bats @@ -0,0 +1,256 @@ +#!/usr/bin/env bats +# Lambda MicroVMs integration tests +# +# Two AWS service models sit behind these commands: `lambda-microvms` (images +# and MicroVMs) and `lambda-core` (network connectors). Both sign as lambda. + +setup() { + load 'test_helper/common-setup' + IMAGE_NAME="" + MICROVM_ID="" + CONNECTOR_ID="" + BASE_IMAGE_ARN="arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1" + BUILD_ROLE_ARN="arn:aws:iam::000000000000:role/microvm-build" +} + +teardown() { + if [ -n "$MICROVM_ID" ]; then + aws_cmd lambda-microvms terminate-microvm --microvm-identifier "$MICROVM_ID" >/dev/null 2>&1 || true + fi + if [ -n "$IMAGE_NAME" ]; then + aws_cmd lambda-microvms delete-microvm-image --image-identifier "$IMAGE_NAME" >/dev/null 2>&1 || true + fi + if [ -n "$CONNECTOR_ID" ]; then + aws_cmd lambda-core delete-network-connector --id "$CONNECTOR_ID" >/dev/null 2>&1 || true + fi +} + +create_image() { + local name="$1" + aws_cmd lambda-microvms create-microvm-image \ + --name "$name" \ + --base-image-arn "$BASE_IMAGE_ARN" \ + --build-role-arn "$BUILD_ROLE_ARN" \ + --code-artifact "uri=s3://bucket/code.zip" +} + +# ============================================ +# Image lifecycle +# ============================================ + +@test "MicroVMs: create image" { + IMAGE_NAME=$(unique_name "cli-img") + run create_image "$IMAGE_NAME" + assert_success + name=$(json_get "$output" '.name') + state=$(json_get "$output" '.state') + version=$(json_get "$output" '.imageVersion') + arn=$(json_get "$output" '.imageArn') + [ "$name" = "$IMAGE_NAME" ] + [ "$state" = "CREATING" ] + [ "$version" = "1.0" ] + [[ "$arn" =~ ^arn:aws:lambda: ]] +} + +@test "MicroVMs: image settles to CREATED with an active version" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + + run aws_cmd lambda-microvms get-microvm-image --image-identifier "$IMAGE_NAME" + assert_success + state=$(json_get "$output" '.state') + latest=$(json_get "$output" '.latestActiveImageVersion') + [ "$state" = "CREATED" ] + [ "$latest" = "1.0" ] +} + +@test "MicroVMs: list images includes the created image" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + + run aws_cmd lambda-microvms list-microvm-images + assert_success + assert_output --partial "$IMAGE_NAME" +} + +@test "MicroVMs: version and build converge to SUCCESSFUL" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + + run aws_cmd lambda-microvms list-microvm-image-builds \ + --image-identifier "$IMAGE_NAME" --image-version 1.0 + assert_success + build_id=$(json_get "$output" '.items[0].buildId') + build_state=$(json_get "$output" '.items[0].buildState') + [ "$build_state" = "SUCCESSFUL" ] + [ -n "$build_id" ] + + run aws_cmd lambda-microvms get-microvm-image-build \ + --image-identifier "$IMAGE_NAME" --image-version 1.0 --build-id "$build_id" + assert_success + arch=$(json_get "$output" '.architecture') + [ "$arch" = "ARM_64" ] + + run aws_cmd lambda-microvms get-microvm-image-version \ + --image-identifier "$IMAGE_NAME" --image-version 1.0 + assert_success + status=$(json_get "$output" '.status') + [ "$status" = "ACTIVE" ] +} + +@test "MicroVMs: invalid image name is rejected" { + run create_image "bad name!" + assert_failure + assert_output --partial "ValidationException" +} + +@test "MicroVMs: get a nonexistent image returns not found" { + run aws_cmd lambda-microvms get-microvm-image --image-identifier "cli-no-such-image" + assert_failure + assert_output --partial "ResourceNotFound" +} + +@test "MicroVMs: managed catalog lists a base image" { + run aws_cmd lambda-microvms list-managed-microvm-images + assert_success + arn=$(json_get "$output" '.items[0].imageArn') + [ -n "$arn" ] +} + +# ============================================ +# MicroVM lifecycle +# ============================================ + +@test "MicroVMs: run a MicroVM and read it back running" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + + run aws_cmd lambda-microvms run-microvm --image-identifier "$IMAGE_NAME" + assert_success + MICROVM_ID=$(json_get "$output" '.microvmId') + state=$(json_get "$output" '.state') + duration=$(json_get "$output" '.maximumDurationInSeconds') + [[ "$MICROVM_ID" =~ ^microvm- ]] + [ "$state" = "PENDING" ] + [ "$duration" = "28800" ] + + run aws_cmd lambda-microvms get-microvm --microvm-identifier "$MICROVM_ID" + assert_success + state=$(json_get "$output" '.state') + [ "$state" = "RUNNING" ] +} + +@test "MicroVMs: run against a missing image returns not found" { + run aws_cmd lambda-microvms run-microvm --image-identifier "cli-no-such-image" + assert_failure + assert_output --partial "ResourceNotFound" +} + +@test "MicroVMs: an image with a running MicroVM refuses delete" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + out=$(aws_cmd lambda-microvms run-microvm --image-identifier "$IMAGE_NAME") + MICROVM_ID=$(json_get "$out" '.microvmId') + + run aws_cmd lambda-microvms delete-microvm-image --image-identifier "$IMAGE_NAME" + assert_failure + assert_output --partial "running microvms" +} + +@test "MicroVMs: terminate is idempotent only once" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + out=$(aws_cmd lambda-microvms run-microvm --image-identifier "$IMAGE_NAME") + microvm_id=$(json_get "$out" '.microvmId') + + run aws_cmd lambda-microvms terminate-microvm --microvm-identifier "$microvm_id" + assert_success + + run aws_cmd lambda-microvms get-microvm --microvm-identifier "$microvm_id" + assert_success + state=$(json_get "$output" '.state') + [ "$state" = "TERMINATED" ] + + # Terminal-state mutations are a ValidationException, not a second success. + run aws_cmd lambda-microvms terminate-microvm --microvm-identifier "$microvm_id" + assert_failure + assert_output --partial "state cannot be changed" +} + +# ============================================ +# Tagging +# ============================================ + +@test "MicroVMs: tag, read and untag an image ARN" { + IMAGE_NAME=$(unique_name "cli-img") + out=$(create_image "$IMAGE_NAME") + image_arn=$(json_get "$out" '.imageArn') + + run aws_cmd lambda-microvms tag-resource --resource "$image_arn" --tags team=conformance + assert_success + + run aws_cmd lambda-microvms list-tags --resource "$image_arn" + assert_success + team=$(json_get "$output" '.Tags.team') + [ "$team" = "conformance" ] + + run aws_cmd lambda-microvms untag-resource --resource "$image_arn" --tag-keys team + assert_success + + run aws_cmd lambda-microvms list-tags --resource "$image_arn" + assert_success + team=$(json_get "$output" '.Tags.team') + [ "$team" = "null" ] || [ -z "$team" ] +} + +# ============================================ +# Network connectors (lambda-core) +# ============================================ + +@test "MicroVMs: network connector lifecycle" { + name=$(unique_name "cli-conn") + run aws_cmd lambda-core create-network-connector \ + --name "$name" \ + --operator-role "arn:aws:iam::000000000000:role/microvm-connector-operator" \ + --configuration "VpcEgressConfiguration={AssociatedComputeResourceTypes=MicroVm,NetworkProtocol=IPv4,SubnetIds=subnet-0000000000000cli1,SecurityGroupIds=sg-0000000000000cli1}" + assert_success + CONNECTOR_ID=$(json_get "$output" '.Id') + state=$(json_get "$output" '.State') + [ -n "$CONNECTOR_ID" ] + [ "$state" = "PENDING" ] + + run aws_cmd lambda-core get-network-connector --id "$CONNECTOR_ID" + assert_success + state=$(json_get "$output" '.State') + got_name=$(json_get "$output" '.Name') + [ "$state" = "ACTIVE" ] + [ "$got_name" = "$name" ] + + run aws_cmd lambda-core list-network-connectors + assert_success + assert_output --partial "$CONNECTOR_ID" + + run aws_cmd lambda-core delete-network-connector --id "$CONNECTOR_ID" + assert_success + CONNECTOR_ID="" +} + +@test "MicroVMs: get a nonexistent connector returns not found" { + run aws_cmd lambda-core get-network-connector --id "nc-00000000000000cli" + assert_failure + assert_output --partial "ResourceNotFound" +} + +# ============================================ +# Region isolation +# ============================================ + +@test "MicroVMs: an image created in one region is not visible in another" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + + run aws --endpoint-url "$FLOCI_ENDPOINT" --region eu-west-1 --output json \ + lambda-microvms get-microvm-image --image-identifier "$IMAGE_NAME" 2>&1 + assert_failure + assert_output --partial "ResourceNotFound" +} diff --git a/docs/services/index.md b/docs/services/index.md index 00d8e489a8..f55d22aad9 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -18,6 +18,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [DynamoDB](dynamodb.md) | `POST /` + `X-Amz-Target: DynamoDB_20120810.*` | JSON 1.1 | 28 | | [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 | | [Lambda](lambda.md) | `/2015-03-31/functions/...` | REST JSON | 30 | +| [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 22 | | [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 64 | | [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 48 + data-plane | | [IAM](iam.md) | `POST /` with `Action=` param | Query | 76 | diff --git a/docs/services/lambda-microvms.md b/docs/services/lambda-microvms.md new file mode 100644 index 0000000000..3b78bd3fef --- /dev/null +++ b/docs/services/lambda-microvms.md @@ -0,0 +1,62 @@ +# Lambda MicroVMs + +**Protocol:** REST JSON +**Endpoints:** `http://localhost:4566/2025-09-09/...` (images, MicroVMs) and `http://localhost:4566/2026-04-04/...` (network connectors) + +Two AWS service models, not one. `Lambda Microvms` (apiVersion 2025-09-09) carries MicroVM images, versions, builds and MicroVMs. `Lambda Core` (apiVersion 2026-04-30) carries VPC egress network connectors under the `/2026-04-04/` prefix. Both sign as `lambda`, so both are served under Floci's existing lambda service and are enabled by it. Tagging rides the classic `/2017-03-31/tags/` routes. + +## Supported Actions + +### Images, versions and builds + +| Action | Description | +| --- | --- | +| `CreateMicrovmImage` | Create an image from an S3 code artifact; mints version 1.0 and its builds | +| `GetMicrovmImage` | Image summary | +| `ListMicrovmImages` | List images | +| `UpdateMicrovmImage` | Full replace; mints a new version and walks the image to `UPDATED` | +| `DeleteMicrovmImage` | Asynchronous delete, answers `DELETING` | +| `ListMicrovmImageVersions` | List versions of an image | +| `GetMicrovmImageVersion` | Version detail, including the parent image's build spec | +| `UpdateMicrovmImageVersion` | Set a version's status `ACTIVE` / `INACTIVE` | +| `DeleteMicrovmImageVersion` | Asynchronous version delete | +| `ListMicrovmImageBuilds` | Builds for a version — one per Graviton generation | +| `GetMicrovmImageBuild` | Build detail, including the snapshot size breakdown | +| `ListManagedMicrovmImages` | The managed base-image catalog | +| `ListManagedMicrovmImageVersions` | Versions of a managed base image | + +### MicroVMs + +| Action | Description | +| --- | --- | +| `RunMicrovm` | Launch a MicroVM from an image | +| `GetMicrovm` | MicroVM detail | +| `ListMicrovms` | List MicroVMs — a five-member summary per item | +| `TerminateMicrovm` | Terminate; terminated MicroVMs stay listed | + +### Network connectors + +| Action | Description | +| --- | --- | +| `CreateNetworkConnector` | Create a VPC egress connector | +| `GetNetworkConnector` | Connector detail | +| `ListNetworkConnectors` | List connectors — a six-member summary per item | +| `UpdateNetworkConnector` | Replace the connector configuration | +| `DeleteNetworkConnector` | Asynchronous delete, answers `DELETING` | + +## Emulation Behavior + +- **Instant convergence:** builds, image state and connector state settle immediately rather than on a timer. Where that would produce an inconsistent body it is handled explicitly — a create or update reports the transitional state and does **not** name the version it is minting as active, because a client reading otherwise would launch a MicroVM off a version that does not exist yet. +- **Per-operation projections:** an image is returned in four different shapes and a connector in four. Create and Update carry full detail, Get is a smaller summary, and only the list summaries carry `Type`. Absent members are absent rather than null — a connector that has never been updated has no `LastUpdateStatus` at all. +- **Members the model marks optional but the service enforces:** a connector requires `ClientToken`, `OperatorRole`, `NetworkProtocol` and `AssociatedComputeResourceTypes`. A client written from the Smithy model alone receives four validation errors in turn. +- **ARN or bare identifier:** images, MicroVMs and connectors resolve by either in URI paths. +- **Builds per generation:** each version is built once per Graviton generation the service targets, so a version has more than one build. +- **Not emulated:** auth tokens, the per-VM endpoint, idle and suspend timers, and suspend/resume. Those belong to a full-fidelity MicroVMs emulator rather than to CloudFormation provisioning; see [m80](https://github.com/INTENTIUS/m80). + +## CloudFormation + +`AWS::Lambda::MicrovmImage` and `AWS::Lambda::NetworkConnector` provision and delete through the resource registry, so a template declaring either is handled rather than skipped. + +## Verification + +Response shapes come from the vendored AWS service models and, where those are silent or disagree with the service, from responses recorded against live AWS. The [m80 conformance suite](https://github.com/INTENTIUS/m80) replays those recordings against an endpoint: 26 checks across the image, MicroVM and connector lifecycles, 0 failures. diff --git a/mkdocs.yml b/mkdocs.yml index 1b78a0e8c9..b220ae8a18 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -81,6 +81,7 @@ nav: - S3: services/s3.md - DynamoDB: services/dynamodb.md - Lambda: services/lambda.md + - Lambda MicroVMs: services/lambda-microvms.md - API Gateway: services/api-gateway.md - Cognito: services/cognito.md - KMS: services/kms.md diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index d2fd226ee7..6fdb4a7580 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -14,6 +14,8 @@ import io.github.hectorvent.floci.services.iot.IotController; import io.github.hectorvent.floci.services.iot.IotDataController; import io.github.hectorvent.floci.services.pipes.PipesController; import io.github.hectorvent.floci.services.lambda.LambdaController; +import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsController; +import io.github.hectorvent.floci.services.lambdamicrovms.LambdaNetworkConnectorsController; import io.github.hectorvent.floci.services.opensearch.OpenSearchController; import io.github.hectorvent.floci.services.cloudfront.CloudFrontController; import io.github.hectorvent.floci.services.route53.Route53Controller; @@ -82,7 +84,10 @@ public class ResolvedServiceCatalog { "lambda", storageMode(config.storage().services().lambda().mode(), config.storage().mode()), config.storage().services().lambda().flushIntervalMs(), null, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON), - Set.of(), Set.of("lambda"), Set.of(), Set.of(LambdaController.class)), + Set.of(), Set.of("lambda"), Set.of(), + Set.of(LambdaController.class, + LambdaMicrovmsController.class, + LambdaNetworkConnectorsController.class)), descriptor("apigateway", "apigateway", config.services().apigateway().enabled(), true, "apigateway", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON), diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisioner.java new file mode 100644 index 0000000000..63b7dfb9b2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisioner.java @@ -0,0 +1,119 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * CloudFormation provisioning for AWS Lambda MicroVMs: + * {@code AWS::Lambda::MicrovmImage} and {@code AWS::Lambda::NetworkConnector}. + * + *
Connector configuration nests under + * {@code Configuration.VpcEgressConfiguration}, whose {@code SecurityGroupIds} + * entries commonly arrive as {@code Fn::GetAtt} references to a security + * group's {@code GroupId} — each array element resolves through the engine + * individually. An image's {@code EgressNetworkConnectors} likewise arrive as + * references to connector ARNs.
+ */ +@ApplicationScoped +public class LambdaMicrovmsCfnProvisioner implements CfnResourceProvisioner { + + private final LambdaMicrovmsService microvmsService; + + @Inject + public LambdaMicrovmsCfnProvisioner(LambdaMicrovmsService microvmsService) { + this.microvmsService = microvmsService; + } + + @Override + public SetRoutes live under the {@code /2025-09-09} prefix and collide with nothing + * the classic Lambda controllers serve. Registered under the lambda service + * descriptor because requests sign as {@code lambda}.
+ */ +@Path("/2025-09-09") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class LambdaMicrovmsController { + + /** + * The memory tier an image gets when the request names none. The service + * reports {@code resources} on the create response even though nothing in + * the request or in the CloudFormation resource type sets it. + */ + private static final int DEFAULT_MEMORY_MIB = 2048; + + /** + * Snapshot sizes as recorded from a real build. An emulator cannot produce + * true sizes, and a client that reads them wants plausible magnitudes + * rather than zeros. + */ + private static final long CODE_INSTALL_SIZE_BYTES = 186400768L; + private static final long DISK_SNAPSHOT_SIZE_BYTES = 25600000L; + private static final long MEMORY_SNAPSHOT_SIZE_BYTES = 609087488L; + + /** + * Every image carries a managed default egress connector, attached by the + * service rather than by the caller. The account segment is the literal + * {@code aws} because the connector is AWS-owned, not the caller's. + */ + private static final String MANAGED_EGRESS_CONNECTOR_FORMAT = + "arn:aws:lambda:%s:aws:network-connector:aws-network-connector:INTERNET_EGRESS"; + + private final LambdaMicrovmsService service; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public LambdaMicrovmsController(LambdaMicrovmsService service, + RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.service = service; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + // ---------------------------------------------------------------- images + + @POST + @Path("/microvm-images") + public Response createMicrovmImage(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + JsonNode request = parse(body); + JsonNode codeArtifact = request.path("codeArtifact"); + MicrovmImage image = service.createImage( + region, + regionResolver.getAccountId(), + text(request, "name"), + text(request, "baseImageArn"), + text(request, "buildRoleArn"), + codeArtifact.isMissingNode() ? null : text(codeArtifact, "uri"), + text(request, "description")); + return Response.status(201).entity(imageNode(image, ImageShape.CREATE)).build(); + } + + @GET + @Path("/microvm-images") + public Response listMicrovmImages(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("items"); + for (MicrovmImage image : service.listImages(region)) { + items.add(imageNode(image, ImageShape.LIST)); + } + root.putNull("nextToken"); + return Response.ok(root).build(); + } + + @GET + @Path("/microvm-images/{imageIdentifier}") + public Response getMicrovmImage(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(imageNode(service.getImage(region, imageIdentifier), ImageShape.GET)).build(); + } + + @PUT + @Path("/microvm-images/{imageIdentifier}") + public Response updateMicrovmImage(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier, + String body) { + String region = regionResolver.resolveRegion(headers); + JsonNode request = parse(body); + JsonNode updArtifact = request.path("codeArtifact"); + // Read the active version before the update mints a new one. + String activeBefore = service.getImage(region, imageIdentifier).latestActiveImageVersion; + MicrovmImage image = service.updateImage(region, imageIdentifier, + text(request, "baseImageArn"), text(request, "buildRoleArn"), + updArtifact.isMissingNode() ? null : text(updArtifact, "uri"), + text(request, "description")); + return Response.ok(imageNode(image, ImageShape.UPDATE, activeBefore)).build(); + } + + @DELETE + @Path("/microvm-images/{imageIdentifier}") + public Response deleteMicrovmImage(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier) { + String region = regionResolver.resolveRegion(headers); + MicrovmImage deleted = service.getImage(region, imageIdentifier); + service.deleteImage(region, imageIdentifier); + // Recorded live: the delete response carries the ARN and DELETING state. + ObjectNode node = objectMapper.createObjectNode(); + node.put("imageIdentifier", deleted.imageArn); + node.put("state", "DELETING"); + return Response.ok(node).build(); + } + + // -------------------------------------------------------------- versions + + @GET + @Path("/microvm-images/{imageIdentifier}/versions") + public Response listVersions(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier) { + String region = regionResolver.resolveRegion(headers); + MicrovmImage image = service.getImage(region, imageIdentifier); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("items"); + for (MicrovmImageVersion version : image.versions) { + items.add(versionNode(image, version)); + } + root.putNull("nextToken"); + return Response.ok(root).build(); + } + + @GET + @Path("/microvm-images/{imageIdentifier}/versions/{imageVersion}") + public Response getVersion(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier, + @PathParam("imageVersion") String imageVersion) { + String region = regionResolver.resolveRegion(headers); + MicrovmImage image = service.getImage(region, imageIdentifier); + return Response.ok(versionNode(image, service.getVersion(region, imageIdentifier, imageVersion))).build(); + } + + @PATCH + @Path("/microvm-images/{imageIdentifier}/versions/{imageVersion}") + public Response updateVersion(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier, + @PathParam("imageVersion") String imageVersion, + String body) { + String region = regionResolver.resolveRegion(headers); + JsonNode request = parse(body); + MicrovmImage image = service.getImage(region, imageIdentifier); + MicrovmImageVersion version = service.updateVersionStatus( + region, imageIdentifier, imageVersion, text(request, "status")); + return Response.ok(versionNode(image, version)).build(); + } + + @DELETE + @Path("/microvm-images/{imageIdentifier}/versions/{imageVersion}") + public Response deleteVersion(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier, + @PathParam("imageVersion") String imageVersion) { + String region = regionResolver.resolveRegion(headers); + MicrovmImage image = service.getImage(region, imageIdentifier); + service.deleteVersion(region, imageIdentifier, imageVersion); + // Recorded: the delete echoes what it is deleting, in DELETING. + ObjectNode node = objectMapper.createObjectNode(); + node.put("imageIdentifier", image.imageArn); + node.put("imageVersion", imageVersion); + node.put("state", "DELETING"); + return Response.ok(node).build(); + } + + // ---------------------------------------------------------------- builds + + @GET + @Path("/microvm-images/{imageIdentifier}/versions/{imageVersion}/builds") + public Response listBuilds(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier, + @PathParam("imageVersion") String imageVersion) { + String region = regionResolver.resolveRegion(headers); + MicrovmImage image = service.getImage(region, imageIdentifier); + MicrovmImageVersion version = service.getVersion(region, imageIdentifier, imageVersion); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("items"); + for (MicrovmBuild build : version.builds) { + items.add(buildNode(image, version, build)); + } + root.putNull("nextToken"); + return Response.ok(root).build(); + } + + @GET + @Path("/microvm-images/{imageIdentifier}/versions/{imageVersion}/builds/{buildId}") + public Response getBuild(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier, + @PathParam("imageVersion") String imageVersion, + @PathParam("buildId") String buildId) { + String region = regionResolver.resolveRegion(headers); + MicrovmImage image = service.getImage(region, imageIdentifier); + MicrovmImageVersion version = service.getVersion(region, imageIdentifier, imageVersion); + MicrovmBuild build = version.builds.stream() + .filter(b -> b.buildId.equals(buildId)) + .findFirst() + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "MicroVM image build not found: " + buildId, 404)); + return Response.ok(buildNode(image, version, build, true)).build(); + } + + // -------------------------------------------------------- managed images + + @GET + @Path("/managed-microvm-images") + public Response listManagedImages(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(catalogNode(service.listManagedImages(region))).build(); + } + + @GET + @Path("/managed-microvm-images/{imageIdentifier}/versions") + public Response listManagedImageVersions(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(catalogNode(service.listManagedImageVersions(region, imageIdentifier))).build(); + } + + // ------------------------------------------------------------------- vms + + @POST + @Path("/microvms") + public Response runMicrovm(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + JsonNode request = parse(body); + Microvm vm = service.runMicrovm(region, regionResolver.getAccountId(), + text(request, "imageIdentifier")); + return Response.ok(vmNode(vm)).build(); + } + + @GET + @Path("/microvms") + public Response listMicrovms(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("items"); + for (Microvm vm : service.listMicrovms(region)) { + items.add(vmSummaryNode(vm)); + } + root.putNull("nextToken"); + return Response.ok(root).build(); + } + + @GET + @Path("/microvms/{microvmIdentifier}") + public Response getMicrovm(@Context HttpHeaders headers, + @PathParam("microvmIdentifier") String microvmIdentifier) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(vmNode(service.getMicrovm(region, microvmIdentifier))).build(); + } + + @DELETE + @Path("/microvms/{microvmIdentifier}") + public Response terminateMicrovm(@Context HttpHeaders headers, + @PathParam("microvmIdentifier") String microvmIdentifier) { + String region = regionResolver.resolveRegion(headers); + service.terminateMicrovm(region, microvmIdentifier); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + // ------------------------------------------------------------- rendering + + /** + * The four shapes an image is returned in. The module previously modelled + * two through a boolean; the live service has four, and they differ by + * more than one member each. + * + *{@code CREATE} and {@code UPDATE} return full detail and differ only + * in the state they claim and in tags — create sends tags as null, update + * omits the member. {@code GET} is a much smaller summary carrying tags as + * an object, and {@code LIST} is smaller again, without tags or + * updatedAt.
+ */ + private enum ImageShape { CREATE, UPDATE, GET, LIST } + + private ObjectNode imageNode(MicrovmImage image, ImageShape shape) { + return imageNode(image, shape, null); + } + + /** + * @param activeBeforeUpdate the version that was active before an update + * minted a new one. An update reports it rather + * than the version it just created, because the + * new one is not built yet at the moment the PUT + * answers. + */ + private ObjectNode imageNode(MicrovmImage image, ImageShape shape, String activeBeforeUpdate) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("name", image.name); + node.put("imageArn", image.imageArn); + node.put("createdAt", epoch(image.createdAt)); + + boolean detail = shape == ImageShape.CREATE || shape == ImageShape.UPDATE; + // A mutation reports the state it is entering, not the one it left. + switch (shape) { + case CREATE -> node.put("state", "CREATING"); + case UPDATE -> node.put("state", "UPDATING"); + default -> node.put("state", image.state); + } + + // Builds converge instantly here, so an image has an active version the + // moment it exists. A mutation response must not say the version it is + // creating is already active: it reports a transitional state, and a + // body claiming CREATING or UPDATING while naming that version as + // active contradicts itself. A reconciler reading it would launch a + // MicroVM off a version that, against the live service, does not exist + // yet. Create therefore reports null and update reports whatever was + // active before it ran. + String active = switch (shape) { + case CREATE -> null; + case UPDATE -> activeBeforeUpdate; + default -> image.latestActiveImageVersion; + }; + if (active == null) { + node.putNull("latestActiveImageVersion"); + } else { + node.put("latestActiveImageVersion", active); + } + node.putNull("latestFailedImageVersion"); + + // updatedAt is on everything but the list item. + if (shape != ImageShape.LIST) { + node.put("updatedAt", epoch(image.updatedAt)); + } + + if (detail) { + if (image.description == null) { + node.putNull("description"); + } else { + node.put("description", image.description); + } + node.put("baseImageArn", image.baseImageArn); + node.put("baseImageVersion", image.baseImageVersion); + node.put("buildRoleArn", image.buildRoleArn); + node.putObject("codeArtifact").put("uri", image.codeArtifactUri); + node.put("imageVersion", image.versions.get(image.versions.size() - 1).imageVersion); + // Neither is settable — not by the request, not by the + // CloudFormation resource type. The service fills them in. + node.putArray("resources").addObject().put("minimumMemoryInMiB", DEFAULT_MEMORY_MIB); + node.putArray("egressNetworkConnectors") + .add(String.format(MANAGED_EGRESS_CONNECTOR_FORMAT, regionOf(image.imageArn))); + } + + // Create sends tags as null, Get sends an object, Update omits the + // member and List does too. The asymmetry is the service's. + if (shape == ImageShape.CREATE) { + node.putNull("tags"); + } else if (shape == ImageShape.GET) { + ObjectNode tags = node.putObject("tags"); + image.tags.forEach(tags::put); + } + return node; + } + + private ObjectNode versionNode(MicrovmImage image, MicrovmImageVersion version) { + // A version response repeats the parent image's whole build spec. The + // data is all on the image, which this method already receives; it was + // simply never written out. + ObjectNode node = objectMapper.createObjectNode(); + node.put("imageArn", image.imageArn); + node.put("imageVersion", version.imageVersion); + node.put("state", version.state); + node.put("status", version.status); + node.put("createdAt", epoch(version.createdAt)); + node.put("updatedAt", epoch(image.updatedAt)); + node.put("baseImageArn", image.baseImageArn); + node.put("baseImageVersion", image.baseImageVersion); + node.put("buildRoleArn", image.buildRoleArn); + node.putObject("codeArtifact").put("uri", image.codeArtifactUri); + // A version's description is its own and nothing sets it. It stays null + // even once the parent image has one, which is why it cannot simply be + // read off the image. + node.putNull("description"); + node.putNull("stateReason"); + // A version sends tags as null, unlike the image Get which sends an + // object. Recorded. + node.putNull("tags"); + node.putArray("resources").addObject().put("minimumMemoryInMiB", DEFAULT_MEMORY_MIB); + node.putArray("egressNetworkConnectors") + .add(String.format(MANAGED_EGRESS_CONNECTOR_FORMAT, regionOf(image.imageArn))); + return node; + } + + private ObjectNode buildNode(MicrovmImage image, MicrovmImageVersion version, MicrovmBuild build) { + return buildNode(image, version, build, false); + } + + /** + * @param withSnapshot Get carries a snapshotBuild breakdown that the list + * item does not. + */ + private ObjectNode buildNode(MicrovmImage image, MicrovmImageVersion version, + MicrovmBuild build, boolean withSnapshot) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("buildId", build.buildId); + node.put("buildState", build.buildState); + node.put("architecture", "ARM_64"); + node.put("chipset", "GRAVITON"); + node.put("chipsetGeneration", build.chipsetGeneration); + node.put("imageArn", image.imageArn); + node.put("imageVersion", version.imageVersion); + node.put("createdAt", epoch(build.createdAt)); + node.putNull("stateReason"); + node.putNull("terminationReasonCode"); + if (withSnapshot) { + ObjectNode snapshot = node.putObject("snapshotBuild"); + snapshot.put("codeInstallSizeInBytes", CODE_INSTALL_SIZE_BYTES); + snapshot.put("diskSnapshotSizeInBytes", DISK_SNAPSHOT_SIZE_BYTES); + snapshot.put("memorySnapshotSizeInBytes", MEMORY_SNAPSHOT_SIZE_BYTES); + } + return node; + } + + /** + * Region segment of an ARN: {@code arn:aws:lambda:Scope is CloudFormation-sufficient: images with a version/build lifecycle + * that converges immediately, basic MicroVM CRUD, and network connectors. + * Tokens, per-VM endpoints, idle timers, and drift behaviors are out of scope + * — the m80 emulator owns full fidelity; this module exists so + * {@code AWS::Lambda::MicrovmImage} and {@code AWS::Lambda::NetworkConnector} + * provision through the CloudFormation engine and SDK clients can exercise the + * basic control plane locally.
+ * + *State enums mirror the service model: image {@code CREATING → CREATED}, + * version/build {@code SUCCESSFUL}, VM {@code PENDING → RUNNING → + * TERMINATING → TERMINATED}, connector {@code PENDING → ACTIVE}. Mutations + * return the transient state and settle instantly, so a follow-up read + * observes the resting state.
+ */ +@ApplicationScoped +public class LambdaMicrovmsService { + + private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z0-9-_]{1,64}"); + private static final int MAX_CONNECTOR_SUBNETS = 16; + + private final RegionResolver regionResolver; + private final StorageFactory storageFactory; + + /** + * Keyed {@code region/id}. The account is not part of the key here: the backend prefixes every + * key with the caller's account and strips it again on read, which is the same account the + * {@link RegionResolver} resolves, so two accounts sharing a region still cannot see each + * other's images, MicroVMs or connectors. + */ + private Map