diff --git a/docker/ec2/ami-images/image-build-metadata.yaml b/docker/ec2/ami-images/image-build-metadata.yaml new file mode 100644 index 0000000000..bd4a6430fd --- /dev/null +++ b/docker/ec2/ami-images/image-build-metadata.yaml @@ -0,0 +1,30 @@ +releaseId: ubuntu-24.04 +images: + - id: ubuntu-24.04-arm64 + catalogImageId: ami-ubuntu2404-cloud-arm64 + catalogAliases: + - ami-ubuntu2404-cloud + family: ubuntu + version: "24.04" + architecture: arm64 + aws: + region: us-east-1 + ownerId: "099720109477" + imageId: ami-ubuntu2404-arm64 + name: ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-arm64-server-20260515 + creationDate: "2026-05-15T00:00:00.000Z" + virtualizationType: hvm + rootDeviceType: ebs + canonical: + baseUrl: https://cloud-images.ubuntu.com/releases/noble/release + rootfs: ubuntu-24.04-server-cloudimg-arm64-root.tar.xz + rootfsSha256: 15188696da114a3ffd3d3554f5858a0c3ac257933656e85feb4e0e83ad542b4a + manifest: ubuntu-24.04-server-cloudimg-arm64.manifest + docker: + image: floci/ami-ubuntu:24.04-arm64 + guest: + runtime: systemd + cloudInit: true + smokePackages: + - systemd + - cloud-init diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 7940dc2fa9..bf006dfbef 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -4,7 +4,7 @@ ## Instance Execution Model -`RunInstances` launches a **real Docker container** for each instance. The container is kept alive with `tail -f /dev/null` so any base image works regardless of its default CMD. The lifecycle maps directly to Docker: +`RunInstances` launches a **real Docker container** for each instance. By default, the container is kept alive with `tail -f /dev/null` so any base image works regardless of its default CMD. Catalog entries that opt into the `systemd` guest runtime start `/sbin/init` instead, with the Docker mounts needed for a systemd-based cloud-image guest. | EC2 state | Docker operation | |---|---| @@ -31,12 +31,45 @@ metadata. | `ami-ubuntu2204` | | `public.ecr.aws/docker/library/ubuntu:22.04` | | `ami-ubuntu2404-arm64` | `ami-ubuntu2404` | `public.ecr.aws/docker/library/ubuntu:24.04` | | `ami-ubuntu2404-amd64` | | `public.ecr.aws/docker/library/ubuntu:24.04` | +| `ami-ubuntu2404-cloud-arm64` | `ami-ubuntu2404-cloud` | `floci/ami-ubuntu:24.04-arm64` | | `ami-debian12` | | `public.ecr.aws/docker/library/debian:12` | | `ami-alpine` | | `public.ecr.aws/docker/library/alpine:latest` | | `ami-0abcdef1234567893` | | `public.ecr.aws/amazonlinux/amazonlinux:2023` | Any unrecognized AMI ID (including real AWS AMI IDs like `ami-0abc12345678`) falls back to the catalog `defaultDockerImage` (`public.ecr.aws/amazonlinux/amazonlinux:2023` by default). +### Cloud-image-derived AMI guests + +The `ami-ubuntu2404-cloud` entry is an experimental Ubuntu 24.04 guest image built from Canonical cloud-image artifacts, not from the Docker-library `ubuntu:24.04` image. It is intended for EC2 workflows that need packages such as `systemd` and `cloud-init` to match a real Ubuntu cloud image more closely. + +This mode is opt-in by AMI selection, not by a global configuration switch. +Existing catalog entries, including `ami-ubuntu2404`, keep their current +Docker-library image mapping and default `tail -f /dev/null` container +lifecycle. The cloud-image-derived entry is a separate AMI ID and alias, so +`DescribeImages` can advertise it while existing callers continue to get the +old behavior unless they choose `ami-ubuntu2404-cloud-arm64` or the +`ami-ubuntu2404-cloud` alias. + +The Java metadata-driven builder lives at `io.github.hectorvent.floci.tools.ami.AmiImageTool`. Its recipe is checked in at `docker/ec2/ami-images/image-build-metadata.yaml`, and generated context/provenance defaults to `target/ami-images//`. + +```bash +./mvnw -q -DskipTests compile exec:java \ + -Dexec.mainClass=io.github.hectorvent.floci.tools.ami.AmiImageTool \ + -Dexec.args="plan --image-id ubuntu-24.04-arm64" + +./mvnw -q -DskipTests compile exec:java \ + -Dexec.mainClass=io.github.hectorvent.floci.tools.ami.AmiImageTool \ + -Dexec.args="generate --image-id ubuntu-24.04-arm64" + +./mvnw -q -DskipTests compile exec:java \ + -Dexec.mainClass=io.github.hectorvent.floci.tools.ami.AmiImageTool \ + -Dexec.args="build --image-id ubuntu-24.04-arm64" + +./mvnw -q -DskipTests compile exec:java \ + -Dexec.mainClass=io.github.hectorvent.floci.tools.ami.AmiImageTool \ + -Dexec.args="smoke --image-id ubuntu-24.04-arm64" +``` + ## SSH Key Injection If `KeyName` is specified at launch, Floci looks up the stored key pair's public key material (set via `ImportKeyPair`) and copies it into `/root/.ssh/authorized_keys` inside the container at boot. It then attempts to start `sshd` if present. The SSH port (container port 22) is mapped to a host port from the configured range (default 2200–2299). diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java index f8b96eb81f..1d3168a443 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java @@ -89,6 +89,7 @@ public class ContainerBuilder { private final List extraHosts = new ArrayList<>(); private LogConfig logConfig; private boolean privileged; + private String cgroupnsMode; private final List dnsServers = new ArrayList<>(); Builder(String image, EmulatorConfig config, DockerHostResolver dockerHostResolver, @@ -315,6 +316,11 @@ public class ContainerBuilder { return this; } + public Builder withCgroupnsMode(String cgroupnsMode) { + this.cgroupnsMode = cgroupnsMode; + return this; + } + /** * Injects Floci's embedded DNS server into the container so virtual-hosted * S3 hostnames (my-bucket.localhost.floci.io) resolve to Floci's Docker @@ -357,6 +363,7 @@ public class ContainerBuilder { List.copyOf(extraHosts), logConfig, privileged, + cgroupnsMode, List.copyOf(dnsServers), workingDir ); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java index 51451f3ec5..26f37d64cb 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java @@ -362,6 +362,10 @@ public class ContainerLifecycleManager { hostConfig.withPrivileged(true); } + if (spec.cgroupnsMode() != null && !spec.cgroupnsMode().isBlank()) { + hostConfig.withCgroupnsMode(spec.cgroupnsMode()); + } + // Memory limit if (spec.hasMemoryLimit()) { hostConfig.withMemory(spec.memoryBytes()); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java index 35856e4b88..9ba5f4f467 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java @@ -25,6 +25,7 @@ import java.util.Map; * @param extraHosts Extra /etc/hosts entries as "hostname:ip" strings * @param logConfig Docker log driver configuration (null = daemon default) * @param privileged Whether to run the container in privileged mode (required for k3s) + * @param cgroupnsMode Docker cgroup namespace mode (for example, "host") * @param dnsServers DNS server IPs to inject into the container (e.g. Floci's embedded DNS) * @param workingDir Working directory inside the container (overrides image WORKDIR) */ @@ -43,6 +44,7 @@ public record ContainerSpec( List extraHosts, LogConfig logConfig, boolean privileged, + String cgroupnsMode, List dnsServers, String workingDir ) { @@ -51,7 +53,7 @@ public record ContainerSpec( * All other fields will be null or empty lists. */ public ContainerSpec(String image) { - this(image, null, List.of(), null, null, null, Map.of(), List.of(), null, List.of(), List.of(), List.of(), null, false, List.of(), null); + this(image, null, List.of(), null, null, null, Map.of(), List.of(), null, List.of(), List.of(), List.of(), null, false, null, List.of(), null); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/AmiImageResolver.java b/src/main/java/io/github/hectorvent/floci/services/ec2/AmiImageResolver.java index 503231f099..4f50c12d1e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/AmiImageResolver.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/AmiImageResolver.java @@ -27,17 +27,26 @@ public class AmiImageResolver { * Falls back to the catalog default image for unrecognised IDs. */ public String resolve(String imageId) { + return resolveImage(imageId).dockerImage(); + } + + public ResolvedAmiImage resolveImage(String imageId) { if (imageId == null || imageId.isBlank()) { LOG.warnv("No imageId provided; using default image {0}", imageCatalog.defaultDockerImage()); - return imageCatalog.defaultDockerImage(); + return ResolvedAmiImage.minimal(imageCatalog.defaultDockerImage()); } return imageCatalog.findByIdOrAlias(imageId) - .map(image -> image.dockerImage) + .map(image -> new ResolvedAmiImage( + image.dockerImage, + image.guestRuntime == null || image.guestRuntime.isBlank() + ? ResolvedAmiImage.DEFAULT_RUNTIME + : image.guestRuntime, + Boolean.TRUE.equals(image.cloudInit))) .orElseGet(() -> { LOG.warnv("Unknown AMI ID {0}; falling back to default image {1}", imageId, imageCatalog.defaultDockerImage()); - return imageCatalog.defaultDockerImage(); + return ResolvedAmiImage.minimal(imageCatalog.defaultDockerImage()); }); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java index d4cdfa1657..5474a16b42 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java @@ -15,6 +15,8 @@ import com.github.dockerjava.api.exception.NotFoundException; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.Mount; +import com.github.dockerjava.api.model.MountType; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; @@ -99,6 +101,10 @@ public class Ec2ContainerManager { * @param region AWS region (for CloudWatch log group naming) */ public void launch(Instance instance, String dockerImage, String publicKey, String region) { + launch(instance, ResolvedAmiImage.minimal(dockerImage), publicKey, region); + } + + public void launch(Instance instance, ResolvedAmiImage image, String publicKey, String region) { instance.setState(InstanceState.pending()); executor.submit(() -> { @@ -118,9 +124,9 @@ public class Ec2ContainerManager { String imdsEndpoint = "http://" + flociHost + ":" + imdsPort; String serviceEndpoint = "http://" + flociHost + ":4566"; - // Build container spec — use tail -f /dev/null to keep container alive - // regardless of the base image's default CMD. - ContainerSpec spec = containerBuilder.newContainer(dockerImage) + // Build container spec — minimal images keep the historic tail + // command, while cloud-image AMI guests can boot their init. + ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image.dockerImage()) .withName(containerName) .withEmbeddedDns() .withDockerNetwork(Optional.empty()) @@ -133,8 +139,15 @@ public class Ec2ContainerManager { // needs network administration privileges in the local // container to attach that link-local address. .withPrivileged(true) - .withCmd(List.of("tail", "-f", "/dev/null")) - .build(); + .withCmd(image.systemd() ? List.of("/sbin/init") : List.of("tail", "-f", "/dev/null")); + if (image.systemd()) { + specBuilder + .withCgroupnsMode("host") + .withMount(new Mount().withType(MountType.TMPFS).withTarget("/run")) + .withMount(new Mount().withType(MountType.TMPFS).withTarget("/run/lock")) + .withBind("/sys/fs/cgroup", "/sys/fs/cgroup"); + } + ContainerSpec spec = specBuilder.build(); // Create container without starting it String containerId = lifecycleManager.create(spec); diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ImageCatalog.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ImageCatalog.java index 758010cdc4..a7a54af25b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ImageCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ImageCatalog.java @@ -148,6 +148,9 @@ public class Ec2ImageCatalog { public String imageOwnerAlias; public String creationDate; public Boolean advertised; + public String guestRuntime; + public Boolean cloudInit; + public String provenance; public boolean advertised() { return advertised == null || advertised; diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 6d3e995ac4..96bc2d078a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -617,7 +617,7 @@ public class Ec2Service { reservation.getInstances().add(inst); if (!config.services().ec2().mock()) { - String dockerImage = amiImageResolver.resolve(imageId); + ResolvedAmiImage dockerImage = amiImageResolver.resolveImage(imageId); String publicKey = null; if (keyName != null) { KeyPair kp = findKeyPair(region, keyName); diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/ResolvedAmiImage.java b/src/main/java/io/github/hectorvent/floci/services/ec2/ResolvedAmiImage.java new file mode 100644 index 0000000000..f5303291ba --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/ResolvedAmiImage.java @@ -0,0 +1,14 @@ +package io.github.hectorvent.floci.services.ec2; + +public record ResolvedAmiImage(String dockerImage, String guestRuntime, boolean cloudInit) { + public static final String DEFAULT_RUNTIME = "minimal"; + public static final String SYSTEMD_RUNTIME = "systemd"; + + public static ResolvedAmiImage minimal(String dockerImage) { + return new ResolvedAmiImage(dockerImage, DEFAULT_RUNTIME, false); + } + + public boolean systemd() { + return SYSTEMD_RUNTIME.equals(guestRuntime); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/tools/ami/AmiImageTool.java b/src/main/java/io/github/hectorvent/floci/tools/ami/AmiImageTool.java new file mode 100644 index 0000000000..cc407f071e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/tools/ami/AmiImageTool.java @@ -0,0 +1,449 @@ +package io.github.hectorvent.floci.tools.ami; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; + +public final class AmiImageTool { + public static final Path DEFAULT_METADATA = Path.of("docker/ec2/ami-images/image-build-metadata.yaml"); + public static final Path DEFAULT_OUTPUT = Path.of("target/ami-images"); + private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory()); + private static final HttpClient HTTP = HttpClient.newHttpClient(); + + private AmiImageTool() {} + + public static void main(String[] args) throws Exception { + Options options = Options.parse(args); + Metadata metadata = loadMetadata(options.metadata); + List images = options.imageId == null ? metadata.images : List.of(findImage(metadata, options.imageId)); + for (ImageSpec image : images) { + switch (options.command) { + case "plan" -> System.out.println(plan(image)); + case "resolve" -> resolve(image, options.output, true); + case "generate" -> generate(image, options.output, true); + case "update-catalog" -> updateCatalog(image, options.catalog, options.output, true); + case "build" -> build(image, options.output); + case "smoke" -> smoke(image); + default -> throw new IllegalArgumentException("Unknown command: " + options.command); + } + } + } + + public static Metadata loadMetadata(Path path) { + try { + Metadata metadata = YAML.readValue(path.toFile(), Metadata.class); + validate(metadata); + return metadata; + } catch (IOException e) { + throw new IllegalStateException("Could not read AMI image metadata: " + path, e); + } + } + + public static String plan(ImageSpec image) { + validateImage(image); + return image.id + " -> " + image.docker.image + " from " + image.canonical.rootfsUrl(); + } + + public static Provenance resolve(ImageSpec image, Path outputRoot, boolean write) { + validateImage(image); + Path context = contextDir(outputRoot, image); + try { + Files.createDirectories(context); + Path manifest = download(image.canonical.manifestUrl(), context.resolve(image.canonical.manifest)); + Provenance provenance = new Provenance(); + provenance.imageId = image.id; + provenance.catalogImageId = image.catalogImageId; + provenance.dockerImage = image.docker.image; + provenance.family = image.family; + provenance.version = image.version; + provenance.architecture = image.architecture; + provenance.aws = image.aws; + provenance.rootfsUrl = image.canonical.rootfsUrl(); + provenance.rootfsSha256 = image.canonical.rootfsSha256; + provenance.manifestUrl = image.canonical.manifestUrl(); + provenance.manifestSha256 = sha256(manifest); + provenance.generatedAt = Instant.now().toString(); + if (write) { + YAML.writerWithDefaultPrettyPrinter().writeValue(context.resolve("provenance.yaml").toFile(), provenance); + } + return provenance; + } catch (IOException e) { + throw new IllegalStateException("Could not resolve AMI image metadata for " + image.id, e); + } + } + + public static Path generate(ImageSpec image, Path outputRoot, boolean write) { + Provenance provenance = resolve(image, outputRoot, write); + Path context = contextDir(outputRoot, image); + try { + Path rootfs = download(image.canonical.rootfsUrl(), context.resolve(image.canonical.rootfs)); + String actual = sha256(rootfs); + if (!image.canonical.rootfsSha256.equalsIgnoreCase(actual)) { + throw new IllegalStateException("Rootfs checksum mismatch for " + image.id + + ": expected " + image.canonical.rootfsSha256 + " but got " + actual); + } + if (write) { + Files.writeString(context.resolve("Dockerfile"), dockerfile(image), StandardCharsets.UTF_8); + Files.writeString(context.resolve("README.md"), readme(image), StandardCharsets.UTF_8); + YAML.writerWithDefaultPrettyPrinter().writeValue(context.resolve("provenance.yaml").toFile(), provenance); + } + return context; + } catch (IOException e) { + throw new IllegalStateException("Could not generate AMI image context for " + image.id, e); + } + } + + public static void updateCatalog(ImageSpec image, Path catalogPath, Path outputRoot, boolean write) { + validateImage(image); + try { + Catalog catalog = YAML.readValue(catalogPath.toFile(), Catalog.class); + CatalogImage staged = catalog.images.stream() + .filter(entry -> image.catalogImageId.equals(entry.imageId)) + .findFirst() + .orElseGet(() -> { + CatalogImage entry = new CatalogImage(); + catalog.images.add(entry); + return entry; + }); + staged.imageId = image.catalogImageId; + staged.aliases = image.catalogAliases == null ? List.of() : List.copyOf(image.catalogAliases); + staged.dockerImage = image.docker.image; + staged.name = image.aws.name; + staged.description = "Canonical, Ubuntu, " + image.version + " LTS cloud image"; + staged.ownerId = image.aws.ownerId; + staged.imageOwnerAlias = "canonical"; + staged.architecture = awsArchitecture(image.architecture); + staged.creationDate = image.aws.creationDate; + staged.rootDeviceType = image.aws.rootDeviceType; + staged.virtualizationType = image.aws.virtualizationType; + staged.guestRuntime = image.guest.runtime; + staged.cloudInit = image.guest.cloudInit; + staged.provenance = contextDir(outputRoot, image).resolve("provenance.yaml").toString(); + if (write) { + YAML.writerWithDefaultPrettyPrinter().writeValue(catalogPath.toFile(), catalog); + } + } catch (IOException e) { + throw new IllegalStateException("Could not update EC2 image catalog: " + catalogPath, e); + } + } + + public static void build(ImageSpec image, Path outputRoot) { + Path context = generate(image, outputRoot, true); + run(List.of("docker", "build", "--platform", platform(image.architecture), "-t", image.docker.image, context.toString())); + } + + public static void smoke(ImageSpec image) { + List args = new ArrayList<>(); + args.addAll(List.of("docker", "run", "--rm", "--entrypoint", "/usr/bin/dpkg-query", image.docker.image, "-W")); + args.addAll(image.guest.smokePackages == null ? List.of() : image.guest.smokePackages); + run(args); + } + + static String dockerfile(ImageSpec image) { + return """ + FROM scratch + LABEL org.opencontainers.image.source="%s" + LABEL io.floci.ami.catalog-image-id="%s" + LABEL io.floci.ami.architecture="%s" + ADD %s / + ENV container=docker + STOPSIGNAL SIGRTMIN+3 + CMD ["/sbin/init"] + """.formatted(image.canonical.rootfsUrl(), image.catalogImageId, image.architecture, image.canonical.rootfs); + } + + static String readme(ImageSpec image) { + return """ + # %s + + Rebuild with: + + ```text + ./mvnw -q -DskipTests compile exec:java -Dexec.mainClass=%s -Dexec.args="generate --image-id %s" + ./mvnw -q -DskipTests compile exec:java -Dexec.mainClass=%s -Dexec.args="build --image-id %s" + ./mvnw -q -DskipTests compile exec:java -Dexec.mainClass=%s -Dexec.args="smoke --image-id %s" + ``` + """.formatted(image.id, AmiImageTool.class.getName(), image.id, + AmiImageTool.class.getName(), image.id, AmiImageTool.class.getName(), image.id); + } + + static Path contextDir(Path outputRoot, ImageSpec image) { + return outputRoot.resolve(image.id); + } + + private static ImageSpec findImage(Metadata metadata, String id) { + return metadata.images.stream() + .filter(image -> id.equals(image.id)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Unknown AMI image id in metadata: " + id)); + } + + private static void validate(Metadata metadata) { + required(metadata.releaseId, "releaseId"); + if (metadata.images == null || metadata.images.isEmpty()) { + throw new IllegalArgumentException("metadata must declare at least one image"); + } + metadata.images.forEach(AmiImageTool::validateImage); + } + + private static void validateImage(ImageSpec image) { + required(image.id, "id"); + required(image.catalogImageId, "catalogImageId"); + required(image.family, "family"); + required(image.version, "version"); + required(image.architecture, "architecture"); + Objects.requireNonNull(image.aws, "aws"); + Objects.requireNonNull(image.canonical, "canonical"); + Objects.requireNonNull(image.docker, "docker"); + Objects.requireNonNull(image.guest, "guest"); + required(image.aws.region, "aws.region"); + required(image.aws.ownerId, "aws.ownerId"); + required(image.aws.imageId, "aws.imageId"); + required(image.aws.name, "aws.name"); + required(image.aws.creationDate, "aws.creationDate"); + required(image.aws.virtualizationType, "aws.virtualizationType"); + required(image.aws.rootDeviceType, "aws.rootDeviceType"); + required(image.canonical.baseUrl, "canonical.baseUrl"); + required(image.canonical.rootfs, "canonical.rootfs"); + required(image.canonical.rootfsSha256, "canonical.rootfsSha256"); + required(image.canonical.manifest, "canonical.manifest"); + required(image.docker.image, "docker.image"); + required(image.guest.runtime, "guest.runtime"); + if (image.canonical.rootfs.contains(":") || isDockerLibraryUbuntu2404(image.docker.image)) { + throw new IllegalArgumentException("AMI guest images must not use Docker-library ubuntu:24.04 as source"); + } + } + + private static boolean isDockerLibraryUbuntu2404(String image) { + return switch (image) { + case "ubuntu:24.04", + "library/ubuntu:24.04", + "docker.io/ubuntu:24.04", + "docker.io/library/ubuntu:24.04", + "public.ecr.aws/docker/library/ubuntu:24.04" -> true; + default -> false; + }; + } + + private static String awsArchitecture(String architecture) { + return "amd64".equals(architecture) ? "x86_64" : architecture; + } + + private static String platform(String architecture) { + return switch (architecture) { + case "arm64" -> "linux/arm64"; + case "amd64", "x86_64" -> "linux/amd64"; + default -> throw new IllegalArgumentException("Unsupported Docker platform architecture: " + architecture); + }; + } + + private static void required(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Missing required AMI image metadata field: " + field); + } + } + + private static Path download(String uri, Path target) throws IOException { + Files.createDirectories(target.getParent()); + if (Files.exists(target)) { + return target; + } + URI source = URI.create(uri); + if ("file".equals(source.getScheme())) { + Files.copy(Path.of(source), target); + return target; + } + HttpRequest request = HttpRequest.newBuilder(source).GET().build(); + try { + HttpResponse response = HTTP.send(request, HttpResponse.BodyHandlers.ofFile(target)); + if (response.statusCode() / 100 != 2) { + throw new IOException("GET " + uri + " returned HTTP " + response.statusCode()); + } + return target; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Interrupted downloading " + uri, e); + } + } + + private static String sha256(Path path) throws IOException { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + try (InputStream input = Files.newInputStream(path)) { + input.transferTo(new java.io.OutputStream() { + @Override + public void write(int b) { + digest.update((byte) b); + } + + @Override + public void write(byte[] b, int off, int len) { + digest.update(b, off, len); + } + }); + } + return HexFormat.of().formatHex(digest.digest()); + } catch (java.security.NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is unavailable", e); + } + } + + private static void run(List command) { + try { + Process process = new ProcessBuilder(command).inheritIO().start(); + int exit = process.waitFor(); + if (exit != 0) { + throw new IllegalStateException("Command failed with exit " + exit + ": " + String.join(" ", command)); + } + } catch (IOException e) { + throw new IllegalStateException("Could not run command: " + String.join(" ", command), e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted running command: " + String.join(" ", command), e); + } + } + + private record Options(String command, Path metadata, Path output, Path catalog, String imageId) { + static Options parse(String[] args) { + if (args.length == 0) { + throw new IllegalArgumentException("usage: AmiImageTool [--image-id id] [--metadata file]"); + } + String command = args[0]; + Path metadata = DEFAULT_METADATA; + Path output = DEFAULT_OUTPUT; + Path catalog = Path.of("src/main/resources/ec2/image-catalog.yaml"); + String imageId = null; + for (int i = 1; i < args.length; i++) { + switch (args[i]) { + case "--metadata" -> metadata = Path.of(args[++i]); + case "--output" -> output = Path.of(args[++i]); + case "--catalog" -> catalog = Path.of(args[++i]); + case "--image-id" -> imageId = args[++i]; + case "--write", "--write-lock" -> { } + case "--context", "--tag" -> i++; + default -> throw new IllegalArgumentException("Unknown argument: " + args[i]); + } + } + return new Options(command, metadata, output, catalog, imageId); + } + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Metadata { + public String releaseId; + public List images = List.of(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class ImageSpec { + public String id; + public String catalogImageId; + public List catalogAliases = List.of(); + public String family; + public String version; + public String architecture; + public Aws aws; + public Canonical canonical; + public Docker docker; + public Guest guest; + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Aws { + public String region; + public String ownerId; + public String imageId; + public String name; + public String creationDate; + public String virtualizationType; + public String rootDeviceType; + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Canonical { + public String baseUrl; + public String rootfs; + public String rootfsSha256; + public String manifest; + + String rootfsUrl() { + return joinUrl(baseUrl, rootfs); + } + + String manifestUrl() { + return joinUrl(baseUrl, manifest); + } + + private static String joinUrl(String base, String leaf) { + return base.endsWith("/") ? base + leaf : base + "/" + leaf; + } + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Docker { + public String image; + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Guest { + public String runtime; + public boolean cloudInit; + public List smokePackages = List.of(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Catalog { + public String defaultDockerImage; + public List images = new ArrayList<>(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class CatalogImage { + public String imageId; + public List aliases = List.of(); + public String dockerImage; + public String name; + public String description; + public String ownerId; + public String imageOwnerAlias; + public String architecture; + public String rootDeviceType; + public String virtualizationType; + public String creationDate; + public String guestRuntime; + public Boolean cloudInit; + public String provenance; + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Provenance { + public String imageId; + public String catalogImageId; + public String dockerImage; + public String family; + public String version; + public String architecture; + public Aws aws; + public String rootfsUrl; + public String rootfsSha256; + public String manifestUrl; + public String manifestSha256; + public String generatedAt; + } +} diff --git a/src/main/resources/ec2/image-catalog.yaml b/src/main/resources/ec2/image-catalog.yaml index 82b887c702..8e2789aa46 100644 --- a/src/main/resources/ec2/image-catalog.yaml +++ b/src/main/resources/ec2/image-catalog.yaml @@ -59,6 +59,22 @@ images: architecture: x86_64 creationDate: "2026-05-15T00:00:00.000Z" + - imageId: ami-ubuntu2404-cloud-arm64 + aliases: + - ami-ubuntu2404-cloud + dockerImage: floci/ami-ubuntu:24.04-arm64 + name: ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-arm64-server-20260515 + description: Canonical, Ubuntu, 24.04 LTS cloud image + ownerId: "099720109477" + imageOwnerAlias: canonical + architecture: arm64 + rootDeviceType: ebs + virtualizationType: hvm + creationDate: "2026-05-15T00:00:00.000Z" + guestRuntime: systemd + cloudInit: true + provenance: target/ami-images/ubuntu-24.04-arm64/provenance.yaml + - imageId: ami-debian12 dockerImage: public.ecr.aws/docker/library/debian:12 name: debian-12-amd64-20230411 diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java index d3fa41feff..d25d39133e 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java @@ -87,6 +87,17 @@ class ContainerBuilderTest { assertEquals(List.of(), spec.dnsServers()); } + @Test + void withCgroupnsModeRecordsDockerNamespaceMode() { + TestFixture fixture = new TestFixture(); + + ContainerSpec spec = fixture.builder.newContainer("alpine") + .withCgroupnsMode("host") + .build(); + + assertEquals("host", spec.cgroupnsMode()); + } + private static class TestFixture { final EmulatorConfig config = mock(EmulatorConfig.class); final EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java index ebe8fa658d..a17ec2d16f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java @@ -245,6 +245,29 @@ class Ec2ContainerManagerTest { "http://floci:9169")); } + @Test + void launchSystemdGuestUsesInitInsteadOfTail() throws Exception { + Ec2ContainerManager.containerBridgeIpAttempts = 1; + Ec2ContainerManager.containerBridgeIpPollMillis = 1; + LaunchHarness harness = launchHarness(); + InspectContainerCmd inspect = mock(InspectContainerCmd.class); + InspectContainerResponse withIp = inspectResponse("172.18.0.11"); + when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect); + when(inspect.exec()).thenReturn(withIp); + harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0)); + Instance instance = instance("i-systemd"); + + harness.manager.launch(instance, + new ResolvedAmiImage("floci/ami-ubuntu:24.04-arm64", ResolvedAmiImage.SYSTEMD_RUNTIME, true), + null, + "us-west-2"); + + awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2)); + verify(harness.builder).withCmd(List.of("/sbin/init")); + verify(harness.builder).withCgroupnsMode("host"); + verify(harness.builder).withBind("/sys/fs/cgroup", "/sys/fs/cgroup"); + } + @Test void preferredMetadataSourceIpUsesConfiguredNetworkBeforeBridge() { ContainerNetwork bridge = new ContainerNetwork(); @@ -380,7 +403,7 @@ class Ec2ContainerManagerTest { portAllocator, config, metadataServer); - return new LaunchHarness(manager, dockerClient, metadataServer, logStreamer); + return new LaunchHarness(manager, dockerClient, metadataServer, logStreamer, builder); } private static Instance instance(String instanceId) { @@ -414,7 +437,8 @@ class Ec2ContainerManagerTest { private record LaunchHarness(Ec2ContainerManager manager, DockerClient dockerClient, Ec2MetadataServer metadataServer, - ContainerLogStreamer logStreamer) { + ContainerLogStreamer logStreamer, + ContainerBuilder.Builder builder) { void stubSuccessfulExecs(CountDownLatch userDataStarted, CountDownLatch finishUserData) throws Exception { AtomicReference currentCommand = new AtomicReference<>(); ExecCreateCmd execCreate = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF)); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ImageCatalogTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ImageCatalogTest.java index 219aff741c..03cd2f9c93 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ImageCatalogTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ImageCatalogTest.java @@ -35,6 +35,7 @@ class Ec2ImageCatalogTest { "ami-ubuntu2204", "ami-ubuntu2404-arm64", "ami-ubuntu2404-amd64", + "ami-ubuntu2404-cloud-arm64", "ami-debian12", "ami-alpine", "ami-0abcdef1234567893"), imageIds); @@ -43,6 +44,7 @@ class Ec2ImageCatalogTest { assertTrue(imageCatalog.findByIdOrAlias("ami-amazonlinux2023").isPresent()); assertTrue(imageCatalog.findByIdOrAlias("ami-ubuntu2004").isPresent()); assertTrue(imageCatalog.findByIdOrAlias("ami-ubuntu2404").isPresent()); + assertTrue(imageCatalog.findByIdOrAlias("ami-ubuntu2404-cloud").isPresent()); } @Test @@ -56,6 +58,16 @@ class Ec2ImageCatalogTest { amiImageResolver.resolve(alias))); } + @Test + void resolverExposesCloudImageGuestRuntimeMetadata() { + ResolvedAmiImage image = amiImageResolver.resolveImage("ami-ubuntu2404-cloud"); + + assertEquals("floci/ami-ubuntu:24.04-arm64", image.dockerImage()); + assertEquals(ResolvedAmiImage.SYSTEMD_RUNTIME, image.guestRuntime()); + assertTrue(image.cloudInit()); + assertTrue(image.systemd()); + } + @Test void unknownImageUsesCatalogDefault() { assertFalse(imageCatalog.findByIdOrAlias("ami-unknown").isPresent()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java index d2ddc86c76..0fd6fa1b60 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java @@ -223,9 +223,10 @@ class Ec2IntegrationTest { .then() .statusCode(200) .contentType("application/xml") - .body("DescribeImagesResponse.imagesSet.item.size()", equalTo(1)) - .body("DescribeImagesResponse.imagesSet.item.imageId", equalTo("ami-ubuntu2404-arm64")) - .body("DescribeImagesResponse.imagesSet.item.architecture", equalTo("arm64")); + .body("DescribeImagesResponse.imagesSet.item.size()", equalTo(2)) + .body("DescribeImagesResponse.imagesSet.item.imageId", + containsInAnyOrder("ami-ubuntu2404-arm64", "ami-ubuntu2404-cloud-arm64")) + .body("DescribeImagesResponse.imagesSet.item.architecture", everyItem(equalTo("arm64"))); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index 4b178551f7..f00d3e8856 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -77,6 +77,22 @@ class Ec2ServiceTest { assertEquals("source", version.getInstanceTags().getFirst().getValue()); } + @Test + void describeImagesAdvertisesCloudGuestWithoutChangingUbuntuDefault() { + Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog(); + AmiImageResolver amiImageResolver = new AmiImageResolver(imageCatalog); + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + amiImageResolver, imageCatalog, new InMemoryStorageFactory()); + + assertTrue(service.describeImages("us-east-1", List.of(), List.of()).stream() + .anyMatch(image -> "ami-ubuntu2404-cloud-arm64".equals(image.getImageId()))); + assertEquals("public.ecr.aws/docker/library/ubuntu:24.04", amiImageResolver.resolve("ami-ubuntu2404")); + + ResolvedAmiImage resolved = amiImageResolver.resolveImage("ami-ubuntu2404-cloud"); + assertEquals("floci/ami-ubuntu:24.04-arm64", resolved.dockerImage()); + assertTrue(resolved.systemd()); + } + private static EmulatorConfig mockConfig(boolean ec2Mock) { EmulatorConfig config = mock(EmulatorConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); diff --git a/src/test/java/io/github/hectorvent/floci/tools/ami/AmiImageToolTest.java b/src/test/java/io/github/hectorvent/floci/tools/ami/AmiImageToolTest.java new file mode 100644 index 0000000000..2544e45ee9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/tools/ami/AmiImageToolTest.java @@ -0,0 +1,162 @@ +package io.github.hectorvent.floci.tools.ami; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.HexFormat; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AmiImageToolTest { + @TempDir + Path tempDir; + + @Test + void metadataDrivesGenerationAndCatalogUpdate() throws Exception { + Path rootfs = tempDir.resolve("ubuntu-root.tar.xz"); + Path manifest = tempDir.resolve("ubuntu.manifest"); + Files.writeString(rootfs, "rootfs", StandardCharsets.UTF_8); + Files.writeString(manifest, "systemd\t1\ncloud-init\t1\n", StandardCharsets.UTF_8); + Path metadata = tempDir.resolve("image-build-metadata.yaml"); + Files.writeString(metadata, """ + releaseId: test-release + images: + - id: ubuntu-24.04-arm64 + catalogImageId: ami-ubuntu2404-cloud-arm64 + catalogAliases: [ami-ubuntu2404-cloud] + family: ubuntu + version: "24.04" + architecture: arm64 + aws: + region: us-east-1 + ownerId: "099720109477" + imageId: ami-source + name: ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-arm64-server-20260515 + creationDate: "2026-05-15T00:00:00.000Z" + virtualizationType: hvm + rootDeviceType: ebs + canonical: + baseUrl: %s + rootfs: %s + rootfsSha256: %s + manifest: %s + docker: + image: floci/ami-ubuntu:24.04-arm64 + guest: + runtime: systemd + cloudInit: true + smokePackages: [systemd, cloud-init] + """.formatted(tempDir.toUri(), rootfs.getFileName(), sha256(rootfs), manifest.getFileName())); + + AmiImageTool.Metadata loaded = AmiImageTool.loadMetadata(metadata); + AmiImageTool.ImageSpec image = loaded.images.getFirst(); + Path context = AmiImageTool.generate(image, tempDir.resolve("out"), true); + + assertTrue(Files.readString(context.resolve("Dockerfile")).contains("FROM scratch")); + assertTrue(Files.readString(context.resolve("Dockerfile")).contains("io.floci.ami.catalog-image-id")); + assertTrue(Files.readString(context.resolve("Dockerfile")).contains("ADD ubuntu-root.tar.xz /")); + assertTrue(Files.readString(context.resolve("provenance.yaml")).contains("manifestSha256")); + + Path catalog = tempDir.resolve("image-catalog.yaml"); + Files.writeString(catalog, """ + defaultDockerImage: public.ecr.aws/amazonlinux/amazonlinux:2023 + images: + - imageId: ami-existing + dockerImage: public.ecr.aws/docker/library/ubuntu:24.04 + name: existing + description: existing + architecture: arm64 + creationDate: "2026-01-01T00:00:00.000Z" + """); + Path output = tempDir.resolve("custom-output"); + AmiImageTool.updateCatalog(image, catalog, output, true); + String catalogText = Files.readString(catalog); + assertTrue(catalogText.contains("ami-existing")); + assertTrue(catalogText.contains("ami-ubuntu2404-cloud-arm64")); + assertTrue(catalogText.contains("guestRuntime: \"systemd\"")); + assertTrue(catalogText.contains("cloudInit: true")); + assertTrue(catalogText.contains("custom-output/ubuntu-24.04-arm64/provenance.yaml")); + } + + @Test + void metadataRejectsDockerLibraryUbuntuAsSource() throws Exception { + Path badRootfsMetadata = tempDir.resolve("bad-rootfs.yaml"); + Files.writeString(badRootfsMetadata, """ + releaseId: bad + images: + - id: bad + catalogImageId: ami-bad + family: ubuntu + version: "24.04" + architecture: arm64 + aws: + region: us-east-1 + ownerId: "099720109477" + imageId: ami-bad-source + name: bad + creationDate: "2026-05-15T00:00:00.000Z" + virtualizationType: hvm + rootDeviceType: ebs + canonical: + baseUrl: https://example.com + rootfs: ubuntu:24.04 + rootfsSha256: abc + manifest: manifest + docker: { image: floci/ami-ubuntu:24.04-arm64 } + guest: { runtime: systemd, cloudInit: true } + """); + + assertThrows(IllegalArgumentException.class, () -> AmiImageTool.loadMetadata(badRootfsMetadata)); + + Path badDockerMetadata = tempDir.resolve("bad-docker.yaml"); + Files.writeString(badDockerMetadata, """ + releaseId: bad + images: + - id: bad + catalogImageId: ami-bad + family: ubuntu + version: "24.04" + architecture: arm64 + aws: + region: us-east-1 + ownerId: "099720109477" + imageId: ami-bad-source + name: bad + creationDate: "2026-05-15T00:00:00.000Z" + virtualizationType: hvm + rootDeviceType: ebs + canonical: + baseUrl: https://example.com + rootfs: ubuntu-root.tar.xz + rootfsSha256: abc + manifest: manifest + docker: { image: public.ecr.aws/docker/library/ubuntu:24.04 } + guest: { runtime: systemd, cloudInit: true } + """); + + assertThrows(IllegalArgumentException.class, () -> AmiImageTool.loadMetadata(badDockerMetadata)); + } + + @Test + void toolTreeDoesNotContainShellScripts() throws Exception { + Path tools = Path.of("src/main/java/io/github/hectorvent/floci/tools/ami"); + if (Files.isDirectory(tools)) { + try (var stream = Files.walk(tools)) { + assertFalse(stream.anyMatch(path -> path.getFileName().toString().endsWith(".sh"))); + } + } + } + + private static String sha256(Path path) throws Exception { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + digest.update(Files.readAllBytes(path)); + return HexFormat.of().formatHex(digest.digest()); + } +}