mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eks): mirror the cluster's and default account's AWS ECR hosts to Floci (#9297)
A chart written for EKS names its own account's images by the AWS registry host, <account>.dkr.ecr.<region>.amazonaws.com. The registries.yaml Floci gives a k3s node mirrored only Floci's localhost forms, so containerd sent those pulls to AWS, where they fail. The generated registries.yaml now also mirrors the cluster's and the default account's registry hosts as AWS names them, across the regions of the cluster's partition, under that partition's DNS suffix (amazonaws.com.cn in the China regions). containerd still tries AWS last, so an image Floci does not hold is looked for there. Other accounts' registries, such as the ones EKS add-on images come from, and public registries are not mirrored. Floci's registry endpoint serves a mirror request whose ns names an account's AWS registry host from that account's repositories in that region, when the region belongs to the suffix's partition. A request sent with an AWS registry host as its Host is not routed there. A node now records the digest of the registries.yaml it was started with in a label. When Floci starts, a surviving node whose label does not match the registries.yaml Floci gives it now, such as one started before these entries existed, is replaced on its data volume, as one with another capacity is, so existing clusters get the new mirrors too. It is kept while the registry is unavailable or the mirror is off. EksVpcPodNetworkNightlyIntegrationTest, which #9288 added, now skips without -Dnightly.checks.enabled=true, as every other nightly check does, so a local test run with Docker no longer starts its k3s node. Closes #5711
This commit is contained in:
1 parent
422c78866d
commit
9c21d7c64c
12 files changed
+624
-238
No files matched your search
@@ -116,6 +116,39 @@ class EcrRegistryDataPlaneTest {
|
||||
assertEquals("/v2/123456789012/eu-west-1/team/app/tags/list", requestNoPort.backendUri());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMirrorRequestForAnAccountsAwsRegistryHostIsServedFromThatAccountsRepository() {
|
||||
EcrRegistryDataPlane.RegistryRequest request = EcrRegistryDataPlane.requestFor("172.17.0.1:4566",
|
||||
"/v2/team/app/manifests/v1", "ns=111122223333.dkr.ecr.eu-west-1.amazonaws.com", "hostname").orElseThrow();
|
||||
|
||||
assertEquals("111122223333", request.accountId());
|
||||
assertEquals("eu-west-1", request.region());
|
||||
assertEquals("team/app", request.repositoryName());
|
||||
assertEquals("111122223333/eu-west-1/team/app", request.storageRepositoryName());
|
||||
assertEquals("v1", request.tag());
|
||||
assertEquals("/v2/111122223333/eu-west-1/team/app/manifests/v1", request.backendUri());
|
||||
|
||||
EcrRegistryDataPlane.RegistryRequest china = EcrRegistryDataPlane.requestFor("172.17.0.1:4566",
|
||||
"/v2/app/blobs/sha256:abc", "ns=111122223333.dkr.ecr.cn-north-1.amazonaws.com.cn", "hostname").orElseThrow();
|
||||
assertEquals("cn-north-1", china.region());
|
||||
assertEquals("/v2/111122223333/cn-north-1/app/blobs/sha256:abc", china.backendUri());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAwsRegistryHostIsServedOnlyAsAMirrorRequestsNamespaceInItsRegionsPartition() {
|
||||
// A region under another partition's suffix names no registry.
|
||||
assertFalse(EcrRegistryDataPlane.requestFor("172.17.0.1:4566", "/v2/app/manifests/v1",
|
||||
"ns=111122223333.dkr.ecr.cn-north-1.amazonaws.com", "hostname").isPresent());
|
||||
assertFalse(EcrRegistryDataPlane.requestFor("172.17.0.1:4566", "/v2/app/manifests/v1",
|
||||
"ns=111122223333.dkr.ecr.us-east-1.amazonaws.com.cn", "hostname").isPresent());
|
||||
// Another registry's namespace, such as a public registry's, is not Floci's.
|
||||
assertFalse(EcrRegistryDataPlane.requestFor("172.17.0.1:4566", "/v2/library/nginx/manifests/1",
|
||||
"ns=docker.io", "hostname").isPresent());
|
||||
// A request sent to the AWS host itself is not a mirror request.
|
||||
assertFalse(EcrRegistryDataPlane.requestFor("111122223333.dkr.ecr.us-east-1.amazonaws.com",
|
||||
"/v2/app/manifests/v1", null, "hostname").isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedAccountOrNonEcrHostIsRejected() {
|
||||
// Less than 12 digits
|
||||
|
||||
@@ -259,11 +259,13 @@ class EksClusterManagerTest {
|
||||
for (String region : AwsRegions.advertised("aws")) {
|
||||
assertTrue(yaml.contains("\"000000000000.dkr.ecr." + region + ".localhost:4566\":"),
|
||||
"should mirror the " + region + " hostname");
|
||||
assertTrue(yaml.contains("\"000000000000.dkr.ecr." + region + ".amazonaws.com\":"),
|
||||
"should mirror the account's " + region + " registry host as AWS names it");
|
||||
}
|
||||
assertTrue(yaml.contains("\"localhost:4566\":"), "should mirror the path-style form");
|
||||
assertFalse(yaml.contains("\"*\""), "must not catch-all public registries");
|
||||
long endpoints = yaml.lines().filter(l -> l.contains("- \"http://floci:4566\"")).count();
|
||||
assertEquals(AwsRegions.advertised("aws").size() + 1, endpoints,
|
||||
assertEquals(2L * AwsRegions.advertised("aws").size() + 1, endpoints,
|
||||
"every mirror should point at Floci's in-network data plane");
|
||||
}
|
||||
|
||||
@@ -286,16 +288,17 @@ class EksClusterManagerTest {
|
||||
for (String region : AwsRegions.advertised("aws")) {
|
||||
assertTrue(yaml.contains("\"111122223333.dkr.ecr." + region + ".localhost:4577\":"));
|
||||
assertTrue(yaml.contains("\"111122223333.dkr.ecr." + region + ".localhost.floci.io:4577\":"));
|
||||
assertTrue(yaml.contains("\"111122223333.dkr.ecr." + region + ".amazonaws.com\":"));
|
||||
}
|
||||
assertTrue(yaml.contains("\"localhost:4577\":"));
|
||||
assertTrue(yaml.contains("\"localhost.floci.io:4577\":"));
|
||||
assertFalse(yaml.contains("*"), "mirrors must not intercept unrelated registries");
|
||||
assertFalse(yaml.contains("amazonaws.com"));
|
||||
assertFalse(yaml.contains("amazonaws.com:"), "the AWS registry host carries no port");
|
||||
assertFalse(yaml.contains("docker.io"));
|
||||
assertFalse(yaml.contains("ghcr.io"));
|
||||
assertFalse(yaml.contains("https://"), "internal pulls still use the HTTP data plane");
|
||||
long endpoints = yaml.lines().filter(line -> line.contains("- \"" + endpoint + "\"")).count();
|
||||
assertEquals(2L * (AwsRegions.advertised("aws").size() + 1), endpoints);
|
||||
assertEquals(3L * AwsRegions.advertised("aws").size() + 2, endpoints);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -316,11 +319,12 @@ class EksClusterManagerTest {
|
||||
|
||||
for (String region : AwsRegions.advertised("aws-cn")) {
|
||||
assertTrue(yaml.contains("\"000000000000.dkr.ecr." + region + ".localhost:4566\":"), region);
|
||||
assertTrue(yaml.contains("\"000000000000.dkr.ecr." + region + ".amazonaws.com.cn\":"), region);
|
||||
}
|
||||
assertTrue(yaml.contains("\"000000000000.dkr.ecr.cn-north-1.localhost:4566\":"));
|
||||
assertFalse(yaml.contains(".us-east-1."));
|
||||
assertFalse(yaml.contains("amazonaws"), "repository URIs are Floci's localhost hosts in every partition");
|
||||
assertEquals(AwsRegions.advertised("aws-cn").size() + 1,
|
||||
assertFalse(yaml.contains(".amazonaws.com\""), "the China regions' registry hosts are under amazonaws.com.cn");
|
||||
assertEquals(2L * AwsRegions.advertised("aws-cn").size() + 1,
|
||||
yaml.lines().filter(line -> line.contains("- \"http://floci:4566\"")).count());
|
||||
}
|
||||
|
||||
@@ -330,14 +334,21 @@ class EksClusterManagerTest {
|
||||
EksClusterManager.mirrorAccounts("111122223333", "000000000000"),
|
||||
List.of("eu-central-1"), 4566, "http://floci:4566", false);
|
||||
|
||||
// Only these two accounts: another account's registry, such as the ones EKS add-on images come from, stays AWS's.
|
||||
assertEquals("""
|
||||
mirrors:
|
||||
"111122223333.dkr.ecr.eu-central-1.localhost:4566":
|
||||
endpoint:
|
||||
- "http://floci:4566"
|
||||
"111122223333.dkr.ecr.eu-central-1.amazonaws.com":
|
||||
endpoint:
|
||||
- "http://floci:4566"
|
||||
"000000000000.dkr.ecr.eu-central-1.localhost:4566":
|
||||
endpoint:
|
||||
- "http://floci:4566"
|
||||
"000000000000.dkr.ecr.eu-central-1.amazonaws.com":
|
||||
endpoint:
|
||||
- "http://floci:4566"
|
||||
"localhost:4566":
|
||||
endpoint:
|
||||
- "http://floci:4566"
|
||||
@@ -345,7 +356,7 @@ class EksClusterManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void registriesYamlKeepsTheExistingOutputWhenTlsUrisAreDisabled() {
|
||||
void registriesYamlHasNoTlsAliasesWhenTlsUrisAreDisabled() {
|
||||
String yaml = EksClusterManager.buildRegistriesYaml(
|
||||
"111122223333", List.of("eu-central-1"), 4566, "http://floci:4566", false);
|
||||
|
||||
@@ -354,6 +365,9 @@ class EksClusterManagerTest {
|
||||
"111122223333.dkr.ecr.eu-central-1.localhost:4566":
|
||||
endpoint:
|
||||
- "http://floci:4566"
|
||||
"111122223333.dkr.ecr.eu-central-1.amazonaws.com":
|
||||
endpoint:
|
||||
- "http://floci:4566"
|
||||
"localhost:4566":
|
||||
endpoint:
|
||||
- "http://floci:4566"
|
||||
@@ -647,6 +661,7 @@ class EksClusterManagerTest {
|
||||
private ContainerBuilder containerBuilder;
|
||||
private ContainerBuilder.Builder builder;
|
||||
private ContainerDetector containerDetector;
|
||||
private EcrRegistryManager registryManager;
|
||||
private EksClusterManager manager;
|
||||
|
||||
@BeforeEach
|
||||
@@ -677,9 +692,10 @@ class EksClusterManagerTest {
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
|
||||
containerDetector = Mockito.mock(ContainerDetector.class);
|
||||
registryManager = Mockito.mock(EcrRegistryManager.class);
|
||||
manager = EksClusterManagers.create(containerBuilder, lifecycleManager,
|
||||
containerDetector, portAllocator,
|
||||
Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class),
|
||||
Mockito.mock(DockerHostResolver.class), registryManager,
|
||||
config, Mockito.mock(RegionResolver.class));
|
||||
}
|
||||
|
||||
@@ -876,6 +892,60 @@ class EksClusterManagerTest {
|
||||
verify(containerBuilder.newContainer("rancher/k3s:v1.30.0-k3s1")).withEntrypoint(EksClusterManager.RSHARE_ENTRYPOINT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacesASurvivorStartedWithAnotherRegistryMirrorAndLabelsItsReplacement(@TempDir Path dataPath) {
|
||||
Cluster cluster = mirroredCluster(dataPath);
|
||||
String older = EksClusterManager.buildRegistriesYaml("000000000000", List.of("us-east-1"), 4566,
|
||||
"http://floci:4566");
|
||||
restoreSurvivorWithMirror(EksClusterManager.registryMirrorLabel(older));
|
||||
stubFreshStart("cid-new", 6440);
|
||||
|
||||
manager.restoreCluster(cluster);
|
||||
|
||||
assertEquals("cid-new", cluster.getContainerId());
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, String>> labels = ArgumentCaptor.forClass(Map.class);
|
||||
verify(builder).withLabels(labels.capture());
|
||||
assertEquals(EksClusterManager.registryMirrorLabel(manager.registriesYaml(cluster)),
|
||||
labels.getValue().get("io.floci.eks.registry-mirror"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsASurvivorStartedWithTheRegistryMirrorFlociGivesItNow(@TempDir Path dataPath) {
|
||||
Cluster cluster = mirroredCluster(dataPath);
|
||||
restoreSurvivorWithMirror(EksClusterManager.registryMirrorLabel(manager.registriesYaml(cluster)));
|
||||
|
||||
manager.restoreCluster(cluster);
|
||||
|
||||
assertEquals("cid-old", cluster.getContainerId());
|
||||
verify(lifecycleManager, never()).create(any());
|
||||
}
|
||||
|
||||
/** The cluster, with the registry mirror on and ECR enabled. */
|
||||
private Cluster mirroredCluster(Path dataPath) {
|
||||
EmulatorConfig.EcrServiceConfig ecr = Mockito.mock(EmulatorConfig.EcrServiceConfig.class);
|
||||
when(config.services().ecr()).thenReturn(ecr);
|
||||
when(ecr.enabled()).thenReturn(true);
|
||||
when(config.services().eks().ecrRegistryMirror()).thenReturn(true);
|
||||
when(config.services().eks().dataPath()).thenReturn(dataPath.toString());
|
||||
when(config.port()).thenReturn(4566);
|
||||
when(registryManager.advertisedPort()).thenReturn(4566);
|
||||
Cluster cluster = cluster();
|
||||
cluster.setAccountId("000000000000");
|
||||
cluster.setArn("arn:aws:eks:us-east-1:000000000000:cluster/demo");
|
||||
cluster.setDockerName("floci-eks-demo");
|
||||
return cluster;
|
||||
}
|
||||
|
||||
private void restoreSurvivorWithMirror(String mirrorLabel) {
|
||||
when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.of(containerFromJson(
|
||||
"{\"Id\":\"cid-old\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\","
|
||||
+ "\"io.floci.eks.shared-mounts\":\"true\",\"io.floci.eks.registry-mirror\":\""
|
||||
+ mirrorLabel + "\"}}")));
|
||||
when(lifecycleManager.adopt(eq("cid-old"), eq(List.of(6443)), any()))
|
||||
.thenReturn(new ContainerInfo("cid-old", Map.of(), Map.of(6443, 6440)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void recreatesASurvivorWhoseCertificateLacksTheEndpointHost() {
|
||||
when(config.services().eks().endpointHost()).thenReturn(Optional.of("aws.example.test"));
|
||||
@@ -1717,10 +1787,14 @@ class EksClusterManagerTest {
|
||||
return cluster;
|
||||
}
|
||||
|
||||
/** Injects the mirror a node created now gets, as a launch does. */
|
||||
private void inject(Cluster cluster) {
|
||||
manager.injectEcrRegistryMirror("container-1", cluster, manager.startingRegistriesYaml(cluster));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDefaultCommercialClusterKeepsTheDeploymentWideMirror() throws Exception {
|
||||
manager.injectEcrRegistryMirror("container-1",
|
||||
clusterWithArn("arn:aws:eks:us-east-1:000000000000:cluster/demo"));
|
||||
inject(clusterWithArn("arn:aws:eks:us-east-1:000000000000:cluster/demo"));
|
||||
|
||||
assertEquals(EksClusterManager.buildRegistriesYaml("000000000000", AwsRegions.advertised("aws"),
|
||||
4566, "http://floci:4566"), Files.readString(tempDir.resolve("registries/000000000000/us-east-1/demo/registries.yaml")));
|
||||
@@ -1728,8 +1802,7 @@ class EksClusterManagerTest {
|
||||
|
||||
@Test
|
||||
void aChinaClusterInACommercialDeploymentMirrorsItsOwnPartitionsRegions() throws Exception {
|
||||
manager.injectEcrRegistryMirror("container-1",
|
||||
clusterWithArn("arn:aws-cn:eks:cn-north-1:000000000000:cluster/demo"));
|
||||
inject(clusterWithArn("arn:aws-cn:eks:cn-north-1:000000000000:cluster/demo"));
|
||||
|
||||
String yaml = Files.readString(tempDir.resolve("registries/000000000000/cn-north-1/demo/registries.yaml"));
|
||||
assertTrue(yaml.contains("\"000000000000.dkr.ecr.cn-north-1.localhost:4566\":"));
|
||||
@@ -1742,7 +1815,7 @@ class EksClusterManagerTest {
|
||||
Cluster cluster = clusterWithArn("arn:aws:eks:eu-west-1:111122223333:cluster/demo");
|
||||
cluster.setAccountId("111122223333");
|
||||
|
||||
manager.injectEcrRegistryMirror("container-1", cluster);
|
||||
inject(cluster);
|
||||
|
||||
String yaml = Files.readString(tempDir.resolve("registries/111122223333/eu-west-1/demo/registries.yaml"));
|
||||
assertTrue(yaml.contains("\"111122223333.dkr.ecr.eu-west-1.localhost:4566\":"));
|
||||
@@ -1751,7 +1824,7 @@ class EksClusterManagerTest {
|
||||
|
||||
@Test
|
||||
void injectsTheMirrorIntoTheContainer() throws Exception {
|
||||
manager.injectEcrRegistryMirror("container-1", demoCluster());
|
||||
inject(demoCluster());
|
||||
|
||||
verify(registryManager).ensureStarted();
|
||||
verify(copyCmd).withRemotePath("/etc");
|
||||
@@ -1767,7 +1840,7 @@ class EksClusterManagerTest {
|
||||
// k3s still reaches Floci on its own port inside the Docker network.
|
||||
when(registryManager.advertisedPort()).thenReturn(54321);
|
||||
|
||||
manager.injectEcrRegistryMirror("container-1", demoCluster());
|
||||
inject(demoCluster());
|
||||
|
||||
String yaml = Files.readString(manager.localClusterFile(demoCluster(), "registries", "registries.yaml"));
|
||||
assertTrue(yaml.contains("\"000000000000.dkr.ecr.us-east-1.localhost:54321\":"));
|
||||
@@ -1784,7 +1857,7 @@ class EksClusterManagerTest {
|
||||
when(tls.enabled()).thenReturn(true);
|
||||
when(ecr.tlsUri()).thenReturn(true);
|
||||
|
||||
manager.injectEcrRegistryMirror("container-1", demoCluster());
|
||||
inject(demoCluster());
|
||||
|
||||
String yaml = Files.readString(manager.localClusterFile(demoCluster(), "registries", "registries.yaml"));
|
||||
assertTrue(yaml.contains("\"000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566\":"));
|
||||
@@ -1800,7 +1873,7 @@ class EksClusterManagerTest {
|
||||
when(config.tls()).thenReturn(tls);
|
||||
when(ecr.tlsUri()).thenReturn(true);
|
||||
|
||||
manager.injectEcrRegistryMirror("container-1", demoCluster());
|
||||
inject(demoCluster());
|
||||
|
||||
String yaml = Files.readString(manager.localClusterFile(demoCluster(), "registries", "registries.yaml"));
|
||||
assertFalse(yaml.contains("localhost.floci.io"));
|
||||
@@ -1812,7 +1885,7 @@ class EksClusterManagerTest {
|
||||
void skipsWhenTheKnobIsOff() {
|
||||
when(eks.ecrRegistryMirror()).thenReturn(false);
|
||||
|
||||
manager.injectEcrRegistryMirror("container-1", demoCluster());
|
||||
inject(demoCluster());
|
||||
|
||||
verifyNoInteractions(registryManager);
|
||||
verify(lifecycleManager, never()).getDockerClient();
|
||||
@@ -1822,7 +1895,7 @@ class EksClusterManagerTest {
|
||||
void skipsWhenEcrIsDisabled() {
|
||||
when(ecr.enabled()).thenReturn(false);
|
||||
|
||||
manager.injectEcrRegistryMirror("container-1", demoCluster());
|
||||
inject(demoCluster());
|
||||
|
||||
verifyNoInteractions(registryManager);
|
||||
verify(lifecycleManager, never()).getDockerClient();
|
||||
@@ -1832,7 +1905,7 @@ class EksClusterManagerTest {
|
||||
void registryStartupFailureSkipsTheMirrorWithoutAborting() {
|
||||
Mockito.doThrow(new RuntimeException("no docker")).when(registryManager).ensureStarted();
|
||||
|
||||
manager.injectEcrRegistryMirror("container-1", demoCluster());
|
||||
inject(demoCluster());
|
||||
|
||||
verify(lifecycleManager, never()).getDockerClient();
|
||||
}
|
||||
@@ -1841,10 +1914,37 @@ class EksClusterManagerTest {
|
||||
void copyFailureDoesNotAbortClusterCreation() {
|
||||
when(copyCmd.exec()).thenThrow(new RuntimeException("copy failed"));
|
||||
|
||||
manager.injectEcrRegistryMirror("container-1", demoCluster());
|
||||
inject(demoCluster());
|
||||
|
||||
verify(copyCmd).exec();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSurvivorIsReplacedWhenItRunsAnotherMirrorThanFlociGivesItNow() {
|
||||
Cluster cluster = demoCluster();
|
||||
String current = manager.registriesYaml(cluster);
|
||||
|
||||
// Started with the mirror Floci gives it now: kept.
|
||||
assertFalse(manager.registryMirrorChanged(cluster,
|
||||
Map.of("io.floci.eks.registry-mirror", EksClusterManager.registryMirrorLabel(current))));
|
||||
// Started with one written before the mirror set grew: replaced.
|
||||
String older = EksClusterManager.buildRegistriesYaml("000000000000", List.of("us-east-1"), 4566,
|
||||
"http://floci:4566");
|
||||
assertTrue(manager.registryMirrorChanged(cluster,
|
||||
Map.of("io.floci.eks.registry-mirror", EksClusterManager.registryMirrorLabel(older))));
|
||||
// Started before the label, or without a mirror: replaced, to get it.
|
||||
assertTrue(manager.registryMirrorChanged(cluster, Map.of()));
|
||||
assertTrue(manager.registryMirrorChanged(cluster, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSurvivorIsKeptWhenItsReplacementWouldGetNoMirrorEither() {
|
||||
Mockito.doThrow(new RuntimeException("no docker")).when(registryManager).ensureStarted();
|
||||
assertFalse(manager.registryMirrorChanged(demoCluster(), Map.of()), "the registry is unavailable");
|
||||
|
||||
when(eks.ecrRegistryMirror()).thenReturn(false);
|
||||
assertFalse(manager.registryMirrorChanged(demoCluster(), Map.of()), "the mirror is off");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.EcrRequests;
|
||||
import io.floci.aws.testing.EcrTestImages;
|
||||
import io.floci.aws.testing.EksTestNode;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* The registry mirror Floci gives a k3s node, run for real: in a cluster of an account other than the default one, a pod
|
||||
* pulls an image by its own account's registry host as AWS names it, and another pod by the default account's, both
|
||||
* images pushed to Floci ECR, as a chart written for EKS names them. Nothing but Floci holds either image, so each pod
|
||||
* runs only if containerd took the mirror and Floci served the mirror request from that account's repository.
|
||||
*
|
||||
* <p>A nightly check: it starts a k3s cluster. Its own profile has Floci listen on the port it advertises, which is the
|
||||
* one the generated mirror sends the node to.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(EksEcrMirrorNightlyIntegrationTest.Profile.class)
|
||||
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
|
||||
// Bounded waits: the k3s image's pull and the API server, two minutes, then two pods; the Nightly checks job's timeout
|
||||
// counts the 10.
|
||||
@Timeout(value = 10, unit = TimeUnit.MINUTES)
|
||||
class EksEcrMirrorNightlyIntegrationTest {
|
||||
|
||||
/** EKS runs its clusters for real, and Floci listens on the port its registry mirror names. */
|
||||
public static final class Profile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.services.eks.mock", "false",
|
||||
"quarkus.http.test-port", String.valueOf(PORT),
|
||||
"floci.port", String.valueOf(PORT),
|
||||
"floci.base-url", "http://localhost:" + PORT);
|
||||
}
|
||||
}
|
||||
|
||||
private static final int PORT = 4593;
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String CLUSTER_ACCOUNT = "111122223333";
|
||||
private static final String DEFAULT_ACCOUNT = "000000000000";
|
||||
private static final Duration API_SERVER_TIMEOUT = Duration.ofSeconds(120);
|
||||
private static final Duration POD_TIMEOUT = Duration.ofSeconds(90);
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
EksClusterManager eksClusterManager;
|
||||
|
||||
private Cluster cluster;
|
||||
private final List<List<String>> repositories = new ArrayList<>();
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
Assumptions.assumeTrue(DockerAvailability.answers(dockerClient),
|
||||
"Docker daemon must be available for the EKS registry mirror check");
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (cluster != null) {
|
||||
eksClusterManager.stopCluster(cluster);
|
||||
}
|
||||
for (List<String> repository : repositories) {
|
||||
EcrRequests.ecr(repository.get(0), REGION, "DeleteRepository",
|
||||
"{\"repositoryName\":\"" + repository.get(1) + "\",\"force\":true}");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void podsPullTheirAccountsAndTheDefaultAccountsImagesByTheAwsRegistryHost() throws IOException {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String ownImage = pushImage(CLUSTER_ACCOUNT, "mirror-own-" + suffix);
|
||||
String defaultImage = pushImage(DEFAULT_ACCOUNT, "mirror-default-" + suffix);
|
||||
|
||||
cluster = EksTestNode.cluster(CLUSTER_ACCOUNT, "ecr-mirror-" + suffix);
|
||||
EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, API_SERVER_TIMEOUT);
|
||||
|
||||
runPod(node, "own-account", ownImage);
|
||||
runPod(node, "default-account", defaultImage);
|
||||
}
|
||||
|
||||
/** Creates {@code repo} in {@code account} and pushes the image to it; returns its reference by the AWS host. */
|
||||
private String pushImage(String account, String repo) throws IOException {
|
||||
EcrRequests.ecr(account, REGION, "CreateRepository", "{\"repositoryName\":\"" + repo + "\"}");
|
||||
repositories.add(List.of(account, repo));
|
||||
EcrTestImages.pushSleepImage(dockerClient, account + ".dkr.ecr." + REGION + ".localhost:" + PORT, repo, "v1");
|
||||
return account + ".dkr.ecr." + REGION + ".amazonaws.com/" + repo + ":v1";
|
||||
}
|
||||
|
||||
private static void runPod(EksTestNode node, String name, String image) {
|
||||
node.apply("""
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: %s
|
||||
spec:
|
||||
containers:
|
||||
- name: workload
|
||||
image: %s
|
||||
command: ["/bin/sleep", "3600"]
|
||||
""".formatted(name, image));
|
||||
node.awaitPodRunning(name, POD_TIMEOUT);
|
||||
}
|
||||
}
|
||||
+5
-171
@@ -3,7 +3,6 @@ package io.floci.aws.services.eks;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import io.floci.aws.core.common.Digests;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.core.common.docker.DockerHostResolver;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
@@ -12,6 +11,8 @@ import io.floci.aws.services.ec2.model.LaunchTemplateData;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.services.eks.model.ClusterStatus;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.EcrRequests;
|
||||
import io.floci.aws.testing.EcrTestImages;
|
||||
import io.floci.aws.testing.EksTestNode;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RdsMockProfile;
|
||||
@@ -19,8 +20,6 @@ import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.eclipse.microprofile.config.inject.ConfigProperty;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
@@ -30,8 +29,6 @@ import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
@@ -40,7 +37,6 @@ import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
@@ -114,10 +110,10 @@ class EksRegistryHostsDockerIntegrationTest {
|
||||
|
||||
// ECR answers a push to a repository nobody created with NAME_UNKNOWN, so the account creates it first.
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
ecrAsImageAccount("CreateRepository", "{\"repositoryName\":\"" + repo + "\"}");
|
||||
cleanup.register(() -> ecrAsImageAccount("DeleteRepository",
|
||||
EcrRequests.ecr(IMAGE_ACCOUNT, "us-east-1", "CreateRepository", "{\"repositoryName\":\"" + repo + "\"}");
|
||||
cleanup.register(() -> EcrRequests.ecr(IMAGE_ACCOUNT, "us-east-1", "DeleteRepository",
|
||||
"{\"repositoryName\":\"" + repo + "\",\"force\":true}"));
|
||||
pushMinimalImage(host, repo);
|
||||
EcrTestImages.pushSleepImage(dockerClient, host, repo, "v1");
|
||||
|
||||
given().contentType(JSON)
|
||||
.body("{\"name\":\"" + clusterName + "\",\"roleArn\":"
|
||||
@@ -287,168 +283,6 @@ class EksRegistryHostsDockerIntegrationTest {
|
||||
return out.toString(StandardCharsets.UTF_8) + problem;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pushes a minimal, genuinely pullable image via raw OCI Distribution calls against Floci's
|
||||
* ECR data plane. The image contains a tiny static executable at {@code /bin/sleep} so kubelet
|
||||
* can both unpack and run it to reach {@code Running}.
|
||||
*/
|
||||
private void pushMinimalImage(String host, String repo) throws Exception {
|
||||
String arch = "amd64";
|
||||
boolean isArm64 = false;
|
||||
try {
|
||||
String dockerArch = dockerClient.infoCmd().exec().getArchitecture();
|
||||
if (dockerArch != null && (dockerArch.contains("aarch64") || dockerArch.contains("arm64"))) {
|
||||
arch = "arm64";
|
||||
isArm64 = true;
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// default to amd64
|
||||
}
|
||||
|
||||
byte[] elfBytes = buildPauseElf(isArm64);
|
||||
byte[] tarBytes;
|
||||
try (ByteArrayOutputStream tarOut = new ByteArrayOutputStream();
|
||||
TarArchiveOutputStream tar = new TarArchiveOutputStream(tarOut)) {
|
||||
TarArchiveEntry entry = new TarArchiveEntry("bin/sleep");
|
||||
entry.setMode(0755);
|
||||
entry.setSize(elfBytes.length);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(elfBytes);
|
||||
tar.closeArchiveEntry();
|
||||
tar.finish();
|
||||
tarBytes = tarOut.toByteArray();
|
||||
}
|
||||
ByteArrayOutputStream gzOut = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(gzOut)) {
|
||||
gzip.write(tarBytes);
|
||||
}
|
||||
byte[] layerBytes = gzOut.toByteArray();
|
||||
String diffId = "sha256:" + Digests.sha256Hex(tarBytes);
|
||||
String layerDigest = "sha256:" + Digests.sha256Hex(layerBytes);
|
||||
|
||||
byte[] configBytes = ("{\"architecture\":\"" + arch + "\",\"os\":\"linux\",\"config\":{},"
|
||||
+ "\"rootfs\":{\"type\":\"layers\",\"diff_ids\":[\"" + diffId + "\"]}}")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
String configDigest = "sha256:" + Digests.sha256Hex(configBytes);
|
||||
|
||||
uploadBlob(host, repo, layerDigest, layerBytes);
|
||||
uploadBlob(host, repo, configDigest, configBytes);
|
||||
|
||||
String manifestJson = """
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
|
||||
"config": {
|
||||
"mediaType": "application/vnd.docker.container.image.v1+json",
|
||||
"size": %d,
|
||||
"digest": "%s"
|
||||
},
|
||||
"layers": [
|
||||
{
|
||||
"mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
|
||||
"size": %d,
|
||||
"digest": "%s"
|
||||
}
|
||||
]
|
||||
}
|
||||
""".formatted(configBytes.length, configDigest, layerBytes.length, layerDigest);
|
||||
|
||||
given().header("Host", host)
|
||||
.contentType("application/vnd.docker.distribution.manifest.v2+json")
|
||||
.body(manifestJson)
|
||||
.when().put("/v2/" + repo + "/manifests/v1")
|
||||
.then().statusCode(201);
|
||||
}
|
||||
|
||||
private static byte[] buildPauseElf(boolean isArm64) {
|
||||
byte[] code;
|
||||
short machine;
|
||||
if (isArm64) {
|
||||
// aarch64: sys_ppoll(NULL, 0, NULL, NULL, 0) (syscall 73) sleeps indefinitely at 0% CPU
|
||||
code = new byte[]{
|
||||
0x00, 0x00, (byte) 0x80, (byte) 0xd2, // mov x0, #0
|
||||
0x01, 0x00, (byte) 0x80, (byte) 0xd2, // mov x1, #0
|
||||
0x02, 0x00, (byte) 0x80, (byte) 0xd2, // mov x2, #0
|
||||
0x03, 0x00, (byte) 0x80, (byte) 0xd2, // mov x3, #0
|
||||
0x04, 0x00, (byte) 0x80, (byte) 0xd2, // mov x4, #0
|
||||
0x28, 0x09, (byte) 0x80, (byte) 0xd2, // mov x8, #73
|
||||
0x01, 0x00, 0x00, (byte) 0xd4, // svc #0
|
||||
(byte) 0xf9, (byte) 0xff, (byte) 0xff, 0x17 // b -7
|
||||
};
|
||||
machine = (short) 0xB7;
|
||||
} else {
|
||||
// x86_64: sys_pause() (syscall 34) sleeps indefinitely at 0% CPU
|
||||
code = new byte[]{
|
||||
(byte) 0xb8, 0x22, 0x00, 0x00, 0x00, // mov eax, 34
|
||||
0x0f, 0x05, // syscall
|
||||
(byte) 0xeb, (byte) 0xf7 // jmp -9
|
||||
};
|
||||
machine = (short) 0x3E;
|
||||
}
|
||||
long baseAddr = 0x400000L;
|
||||
long entryPoint = baseAddr + 0x78L;
|
||||
int fileSize = 0x78 + code.length;
|
||||
|
||||
ByteBuffer buf = ByteBuffer.allocate(fileSize).order(ByteOrder.LITTLE_ENDIAN);
|
||||
// ELF header (64 bytes)
|
||||
buf.put(new byte[]{0x7F, 'E', 'L', 'F', 2, 1, 1, 0});
|
||||
buf.put(new byte[8]); // padding
|
||||
buf.putShort((short) 2); // ET_EXEC
|
||||
buf.putShort(machine);
|
||||
buf.putInt(1); // EV_CURRENT
|
||||
buf.putLong(entryPoint);
|
||||
buf.putLong(64L); // e_phoff
|
||||
buf.putLong(0L); // e_shoff
|
||||
buf.putInt(0); // e_flags
|
||||
buf.putShort((short) 64); // e_ehsize
|
||||
buf.putShort((short) 56); // e_phentsize
|
||||
buf.putShort((short) 1); // e_phnum
|
||||
buf.putShort((short) 0); // e_shentsize
|
||||
buf.putShort((short) 0); // e_shnum
|
||||
buf.putShort((short) 0); // e_shstrndx
|
||||
|
||||
// Program header (56 bytes)
|
||||
buf.putInt(1); // PT_LOAD
|
||||
buf.putInt(7); // PF_R | PF_W | PF_X
|
||||
buf.putLong(0L); // p_offset
|
||||
buf.putLong(baseAddr); // p_vaddr
|
||||
buf.putLong(baseAddr); // p_paddr
|
||||
buf.putLong(fileSize); // p_filesz
|
||||
buf.putLong(fileSize); // p_memsz
|
||||
buf.putLong(0x1000L); // p_align
|
||||
|
||||
// Code
|
||||
buf.put(code);
|
||||
return buf.array();
|
||||
}
|
||||
|
||||
private static void ecrAsImageAccount(String action, String body) {
|
||||
given().header("X-Amz-Target", "AmazonEC2ContainerRegistry_V20150921." + action)
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + IMAGE_ACCOUNT
|
||||
+ "/20260923/us-east-1/ecr/aws4_request")
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private void uploadBlob(String host, String repo, String digest, byte[] content) {
|
||||
String location = given().header("Host", host)
|
||||
.when().post("/v2/" + repo + "/blobs/uploads/")
|
||||
.then().statusCode(202)
|
||||
.extract().header("Location");
|
||||
assertNotNull(location);
|
||||
String separator = location.contains("?") ? "&" : "?";
|
||||
given().header("Host", host)
|
||||
// The Location header already carries a percent-encoded _state token; RestAssured's
|
||||
// default encoding would double-encode it and corrupt the token.
|
||||
.urlEncodingEnabled(false)
|
||||
.contentType("application/octet-stream")
|
||||
.body(content)
|
||||
.when().put(location + separator + "digest=" + digest)
|
||||
.then().statusCode(201);
|
||||
}
|
||||
|
||||
private void waitUntilReady(Cluster cluster) {
|
||||
await("cluster ACTIVE").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(1))
|
||||
.until(() -> {
|
||||
|
||||
@@ -15,6 +15,7 @@ import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
@@ -40,8 +41,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
* arguments, on a network standing in for Floci's and a second standing in for the VPC's: its pods take addresses from
|
||||
* both of its prefixes, and those answer another container on the VPC network and, on Linux, this JVM, the way Floci's
|
||||
* health checks and load balancers dial a {@code TargetType ip} target. It pulls k3s and busybox and runs fourteen pods,
|
||||
* so it runs nightly rather than in the pull request shards.
|
||||
* so it runs with the nightly checks ({@code -Dnightly.checks.enabled=true}) rather than in the pull request shards.
|
||||
*/
|
||||
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
|
||||
class EksVpcPodNetworkNightlyIntegrationTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EksVpcPodNetworkNightlyIntegrationTest.class);
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
/** ECR JSON requests signed for an account in a region, which must succeed. */
|
||||
public final class EcrRequests {
|
||||
|
||||
private EcrRequests() {
|
||||
}
|
||||
|
||||
public static void ecr(String account, String region, String action, String body) {
|
||||
given().header("X-Amz-Target", "AmazonEC2ContainerRegistry_V20150921." + action)
|
||||
.header("Authorization", EnforcementFixtures.auth(account, region, "ecr"))
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.core.common.Digests;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
/**
|
||||
* A minimal image that a k3s node can pull from Floci ECR and run: one layer holding a tiny static executable at
|
||||
* {@code /bin/sleep} that sleeps without end at no CPU, built for the Docker daemon's architecture, pushed through the
|
||||
* registry API as {@code docker push} would.
|
||||
*/
|
||||
public final class EcrTestImages {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EcrTestImages.class);
|
||||
|
||||
private EcrTestImages() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Pushes the image to {@code repo} as {@code tag}, sending {@code host}, one of Floci's repository hosts, as the
|
||||
* {@code Host} header. The repository must exist: ECR refuses a push to one nobody created.
|
||||
*/
|
||||
public static void pushSleepImage(DockerClient dockerClient, String host, String repo, String tag)
|
||||
throws IOException {
|
||||
boolean arm64 = isArm64(dockerClient);
|
||||
byte[] executable = sleepExecutable(arm64);
|
||||
byte[] tarBytes;
|
||||
try (ByteArrayOutputStream tarOut = new ByteArrayOutputStream();
|
||||
TarArchiveOutputStream tar = new TarArchiveOutputStream(tarOut)) {
|
||||
TarArchiveEntry entry = new TarArchiveEntry("bin/sleep");
|
||||
entry.setMode(0755);
|
||||
entry.setSize(executable.length);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(executable);
|
||||
tar.closeArchiveEntry();
|
||||
tar.finish();
|
||||
tarBytes = tarOut.toByteArray();
|
||||
}
|
||||
ByteArrayOutputStream gzOut = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(gzOut)) {
|
||||
gzip.write(tarBytes);
|
||||
}
|
||||
byte[] layerBytes = gzOut.toByteArray();
|
||||
String diffId = "sha256:" + Digests.sha256Hex(tarBytes);
|
||||
String layerDigest = "sha256:" + Digests.sha256Hex(layerBytes);
|
||||
|
||||
byte[] configBytes = ("{\"architecture\":\"" + (arm64 ? "arm64" : "amd64") + "\",\"os\":\"linux\",\"config\":{},"
|
||||
+ "\"rootfs\":{\"type\":\"layers\",\"diff_ids\":[\"" + diffId + "\"]}}")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
String configDigest = "sha256:" + Digests.sha256Hex(configBytes);
|
||||
|
||||
uploadBlob(host, repo, layerDigest, layerBytes);
|
||||
uploadBlob(host, repo, configDigest, configBytes);
|
||||
|
||||
String manifestJson = """
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
|
||||
"config": {
|
||||
"mediaType": "application/vnd.docker.container.image.v1+json",
|
||||
"size": %d,
|
||||
"digest": "%s"
|
||||
},
|
||||
"layers": [
|
||||
{
|
||||
"mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
|
||||
"size": %d,
|
||||
"digest": "%s"
|
||||
}
|
||||
]
|
||||
}
|
||||
""".formatted(configBytes.length, configDigest, layerBytes.length, layerDigest);
|
||||
|
||||
given().header("Host", host)
|
||||
.contentType("application/vnd.docker.distribution.manifest.v2+json")
|
||||
.body(manifestJson)
|
||||
.when().put("/v2/" + repo + "/manifests/" + tag)
|
||||
.then().statusCode(201);
|
||||
}
|
||||
|
||||
private static boolean isArm64(DockerClient dockerClient) {
|
||||
try {
|
||||
String architecture = dockerClient.infoCmd().exec().getArchitecture();
|
||||
return architecture != null && (architecture.contains("aarch64") || architecture.contains("arm64"));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Could not read the Docker daemon's architecture, so the image is built for amd64: {0}",
|
||||
e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] sleepExecutable(boolean arm64) {
|
||||
byte[] code;
|
||||
short machine;
|
||||
if (arm64) {
|
||||
// aarch64: sys_ppoll(NULL, 0, NULL, NULL, 0) (syscall 73) sleeps indefinitely at 0% CPU
|
||||
code = new byte[]{
|
||||
0x00, 0x00, (byte) 0x80, (byte) 0xd2, // mov x0, #0
|
||||
0x01, 0x00, (byte) 0x80, (byte) 0xd2, // mov x1, #0
|
||||
0x02, 0x00, (byte) 0x80, (byte) 0xd2, // mov x2, #0
|
||||
0x03, 0x00, (byte) 0x80, (byte) 0xd2, // mov x3, #0
|
||||
0x04, 0x00, (byte) 0x80, (byte) 0xd2, // mov x4, #0
|
||||
0x28, 0x09, (byte) 0x80, (byte) 0xd2, // mov x8, #73
|
||||
0x01, 0x00, 0x00, (byte) 0xd4, // svc #0
|
||||
(byte) 0xf9, (byte) 0xff, (byte) 0xff, 0x17 // b -7
|
||||
};
|
||||
machine = (short) 0xB7;
|
||||
} else {
|
||||
// x86_64: sys_pause() (syscall 34) sleeps indefinitely at 0% CPU
|
||||
code = new byte[]{
|
||||
(byte) 0xb8, 0x22, 0x00, 0x00, 0x00, // mov eax, 34
|
||||
0x0f, 0x05, // syscall
|
||||
(byte) 0xeb, (byte) 0xf7 // jmp -9
|
||||
};
|
||||
machine = (short) 0x3E;
|
||||
}
|
||||
long baseAddr = 0x400000L;
|
||||
long entryPoint = baseAddr + 0x78L;
|
||||
int fileSize = 0x78 + code.length;
|
||||
|
||||
ByteBuffer buf = ByteBuffer.allocate(fileSize).order(ByteOrder.LITTLE_ENDIAN);
|
||||
// ELF header (64 bytes)
|
||||
buf.put(new byte[]{0x7F, 'E', 'L', 'F', 2, 1, 1, 0});
|
||||
buf.put(new byte[8]); // padding
|
||||
buf.putShort((short) 2); // ET_EXEC
|
||||
buf.putShort(machine);
|
||||
buf.putInt(1); // EV_CURRENT
|
||||
buf.putLong(entryPoint);
|
||||
buf.putLong(64L); // e_phoff
|
||||
buf.putLong(0L); // e_shoff
|
||||
buf.putInt(0); // e_flags
|
||||
buf.putShort((short) 64); // e_ehsize
|
||||
buf.putShort((short) 56); // e_phentsize
|
||||
buf.putShort((short) 1); // e_phnum
|
||||
buf.putShort((short) 0); // e_shentsize
|
||||
buf.putShort((short) 0); // e_shnum
|
||||
buf.putShort((short) 0); // e_shstrndx
|
||||
|
||||
// Program header (56 bytes)
|
||||
buf.putInt(1); // PT_LOAD
|
||||
buf.putInt(7); // PF_R | PF_W | PF_X
|
||||
buf.putLong(0L); // p_offset
|
||||
buf.putLong(baseAddr); // p_vaddr
|
||||
buf.putLong(baseAddr); // p_paddr
|
||||
buf.putLong(fileSize); // p_filesz
|
||||
buf.putLong(fileSize); // p_memsz
|
||||
buf.putLong(0x1000L); // p_align
|
||||
|
||||
// Code
|
||||
buf.put(code);
|
||||
return buf.array();
|
||||
}
|
||||
|
||||
private static void uploadBlob(String host, String repo, String digest, byte[] content) {
|
||||
String location = given().header("Host", host)
|
||||
.when().post("/v2/" + repo + "/blobs/uploads/")
|
||||
.then().statusCode(202)
|
||||
.extract().header("Location");
|
||||
assertNotNull(location);
|
||||
String separator = location.contains("?") ? "&" : "?";
|
||||
given().header("Host", host)
|
||||
// The Location header already carries a percent-encoded _state token; RestAssured's
|
||||
// default encoding would double-encode it and corrupt the token.
|
||||
.urlEncodingEnabled(false)
|
||||
.contentType("application/octet-stream")
|
||||
.body(content)
|
||||
.when().put(location + separator + "digest=" + digest)
|
||||
.then().statusCode(201);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user