feat: ecr (#337)

This commit is contained in:
Conor Heine authored and GitHub committed 2026-04-11 09:59:05 -05:00
1 parent 68311a5b47
commit a0ed51e9d1
54 files changed
+3654 -186

No files matched your search

@@ -214,6 +214,7 @@ public interface EmulatorConfig {
EcsServiceConfig ecs();
AppConfigServiceConfig appconfig();
AppConfigDataServiceConfig appconfigdata();
EcrServiceConfig ecr();
}
interface SsmServiceConfig {
@@ -414,6 +415,38 @@ public interface EmulatorConfig {
int defaultCpuUnits();
}
interface EcrServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("registry:2")
String registryImage();
@WithDefault("floci-ecr-registry")
String registryContainerName();
@WithDefault("5000")
int registryBasePort();
@WithDefault("5099")
int registryMaxPort();
@WithDefault("./data/ecr")
String dataPath();
@WithDefault("false")
boolean tlsEnabled();
@WithDefault("true")
boolean keepRunningOnShutdown();
/** URI style for repositoryUri responses: "hostname" (default, *.dkr.ecr.<region>.localhost) or "path". */
@WithDefault("hostname")
String uriStyle();
Optional<String> dockerNetwork();
}
interface LambdaServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.acm.AcmJsonHandler;
import io.github.hectorvent.floci.services.ecr.EcrJsonHandler;
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2JsonHandler;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsHandler;
@@ -43,6 +44,7 @@ public class AwsJson11Controller {
private static final String COGNITO_TARGET_PREFIX = "AWSCognitoIdentityProviderService.";
private static final String ACM_TARGET_PREFIX = "CertificateManager.";
private static final String ECS_TARGET_PREFIX = "AmazonEC2ContainerServiceV20141113.";
private static final String ECR_TARGET_PREFIX = "AmazonEC2ContainerRegistry_V20150921.";
private final ObjectMapper objectMapper;
private final RegionResolver regionResolver;
@@ -56,6 +58,7 @@ public class AwsJson11Controller {
private final CognitoJsonHandler cognitoJsonHandler;
private final AcmJsonHandler acmJsonHandler;
private final EcsJsonHandler ecsJsonHandler;
private final EcrJsonHandler ecrJsonHandler;
@Inject
public AwsJson11Controller(ObjectMapper objectMapper, RegionResolver regionResolver,
@@ -65,7 +68,8 @@ public class AwsJson11Controller {
KinesisJsonHandler kinesisJsonHandler,
ApiGatewayV2JsonHandler apigwV2JsonHandler,
KmsJsonHandler kmsJsonHandler, CognitoJsonHandler cognitoJsonHandler,
AcmJsonHandler acmJsonHandler, EcsJsonHandler ecsJsonHandler) {
AcmJsonHandler acmJsonHandler, EcsJsonHandler ecsJsonHandler,
EcrJsonHandler ecrJsonHandler) {
this.objectMapper = objectMapper;
this.regionResolver = regionResolver;
this.ssmJsonHandler = ssmJsonHandler;
@@ -78,6 +82,7 @@ public class AwsJson11Controller {
this.cognitoJsonHandler = cognitoJsonHandler;
this.acmJsonHandler = acmJsonHandler;
this.ecsJsonHandler = ecsJsonHandler;
this.ecrJsonHandler = ecrJsonHandler;
}
@POST
@@ -125,6 +130,9 @@ public class AwsJson11Controller {
} else if (target.startsWith(ECS_TARGET_PREFIX)) {
prefix = ECS_TARGET_PREFIX;
serviceName = "ECS";
} else if (target.startsWith(ECR_TARGET_PREFIX)) {
prefix = ECR_TARGET_PREFIX;
serviceName = "ECR";
} else {
return JsonErrorResponseUtils.createUnknownOperationErrorResponse(target);
}
@@ -147,6 +155,7 @@ public class AwsJson11Controller {
case "Cognito" -> cognitoJsonHandler.handle(action, request, region);
case "ACM" -> acmJsonHandler.handle(action, request, region);
case "ECS" -> ecsJsonHandler.handle(action, request, region);
case "ECR" -> ecrJsonHandler.handle(action, request, region);
default -> null;
};
} catch (AwsException e) {
@@ -55,6 +55,7 @@ public class ServiceRegistry {
case "ecs" -> config.services().ecs().enabled();
case "appconfig" -> config.services().appconfig().enabled();
case "appconfigdata" -> config.services().appconfigdata().enabled();
case "ecr" -> config.services().ecr().enabled();
default -> true;
};
}
@@ -87,6 +88,9 @@ public class ServiceRegistry {
if (config.services().opensearch().enabled()) enabled.add("es");
if (config.services().appconfig().enabled()) enabled.add("appconfig");
if (config.services().appconfigdata().enabled()) enabled.add("appconfigdata");
if (config.services().ec2().enabled()) enabled.add("ec2");
if (config.services().ecs().enabled()) enabled.add("ecs");
if (config.services().ecr().enabled()) enabled.add("ecr");
return enabled;
}
@@ -123,6 +127,7 @@ public class ServiceRegistry {
services.put("ecs", status(config.services().ecs().enabled()));
services.put("appconfig", status(config.services().appconfig().enabled()));
services.put("appconfigdata", status(config.services().appconfigdata().enabled()));
services.put("ecr", status(config.services().ecr().enabled()));
return services;
}
@@ -9,6 +9,8 @@ import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;
import io.github.hectorvent.floci.services.ecr.EcrService;
import io.github.hectorvent.floci.services.ecr.model.Repository;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
@@ -54,6 +56,7 @@ public class CloudFormationResourceProvisioner {
private final EventBridgeService eventBridgeService;
private final ApiGatewayService apiGatewayService;
private final ApiGatewayV2Service apiGatewayV2Service;
private final EcrService ecrService;
@Inject
public CloudFormationResourceProvisioner(S3Service s3Service, SqsService sqsService,
@@ -63,7 +66,8 @@ public class CloudFormationResourceProvisioner {
SecretsManagerService secretsManagerService,
EventBridgeService eventBridgeService,
ApiGatewayService apiGatewayService,
ApiGatewayV2Service apiGatewayV2Service) {
ApiGatewayV2Service apiGatewayV2Service,
EcrService ecrService) {
this.s3Service = s3Service;
this.sqsService = sqsService;
this.snsService = snsService;
@@ -76,6 +80,7 @@ public class CloudFormationResourceProvisioner {
this.eventBridgeService = eventBridgeService;
this.apiGatewayService = apiGatewayService;
this.apiGatewayV2Service = apiGatewayV2Service;
this.ecrService = ecrService;
}
/**
@@ -160,6 +165,8 @@ public class CloudFormationResourceProvisioner {
case "AWS::Events::Rule" -> deleteEventBridgeRuleSafe(physicalId, region);
case "AWS::ApiGateway::RestApi" -> apiGatewayService.deleteRestApi(region, physicalId);
case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId);
case "AWS::ECR::Repository" ->
ecrService.deleteRepository(physicalId, null, true, "us-east-1");
default -> LOG.debugv("Skipping delete of unsupported resource type: {0}", resourceType);
}
} catch (Exception e) {
@@ -313,14 +320,52 @@ public class CloudFormationResourceProvisioner {
if (funcName == null || funcName.isBlank()) {
funcName = generatePhysicalName(stackName, r.getLogicalId(), 64, false);
}
String packageType = resolveOrDefault(props, "PackageType", engine, "Zip");
Map<String, Object> req = new HashMap<>();
req.put("FunctionName", funcName);
req.put("Runtime", resolveOrDefault(props, "Runtime", engine, "nodejs18.x"));
req.put("Handler", resolveOrDefault(props, "Handler", engine, "index.handler"));
req.put("PackageType", packageType);
req.put("Role", resolveOrDefault(props, "Role", engine, "arn:aws:iam::" + accountId + ":role/default"));
req.put("Code", resolveLambdaCode(props, engine));
var func = lambdaService.createFunction(region, req);
if ("Zip".equals(packageType)) {
req.put("Runtime", resolveOrDefault(props, "Runtime", engine, "nodejs18.x"));
req.put("Handler", resolveOrDefault(props, "Handler", engine, "index.handler"));
} else {
// Image-packaged functions: forward Runtime/Handler only if explicitly set
String runtime = resolveOptional(props, "Runtime", engine);
if (runtime != null) req.put("Runtime", runtime);
String handler = resolveOptional(props, "Handler", engine);
if (handler != null) req.put("Handler", handler);
}
// Forward optional configuration fields when present
String timeout = resolveOptional(props, "Timeout", engine);
if (timeout != null) {
try { req.put("Timeout", Integer.parseInt(timeout)); } catch (NumberFormatException ignored) {}
}
String memorySize = resolveOptional(props, "MemorySize", engine);
if (memorySize != null) {
try { req.put("MemorySize", Integer.parseInt(memorySize)); } catch (NumberFormatException ignored) {}
}
String description = resolveOptional(props, "Description", engine);
if (description != null) {
req.put("Description", description);
}
io.github.hectorvent.floci.services.lambda.model.LambdaFunction func;
try {
func = lambdaService.createFunction(region, req);
} catch (AwsException e) {
// CDK redeploys re-run CFN provisioning against the same Floci instance.
// If the function already exists, adopt it (CFN provisioning must be idempotent).
if ("ResourceConflictException".equals(e.getErrorCode())
|| (e.getMessage() != null && e.getMessage().contains("Function already exist"))) {
func = lambdaService.getFunction(region, funcName);
} else {
throw e;
}
}
r.setPhysicalId(funcName);
r.getAttributes().put("Arn", func.getFunctionArn());
}
@@ -695,8 +740,59 @@ public class CloudFormationResourceProvisioner {
if (repoName == null || repoName.isBlank()) {
repoName = generatePhysicalName(stackName, r.getLogicalId(), 256, true);
}
// CDK bootstrap requires lower-case repository names; CFN-generated suffixes can include
// upper-case characters. Normalize to satisfy the AWS ECR repository name pattern.
repoName = repoName.toLowerCase();
String mutability = resolveOptional(props, "ImageTagMutability", engine);
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
Repository repo;
try {
repo = ecrService.createRepository(repoName, null, mutability, null, null, null, tags, "us-east-1");
} catch (AwsException e) {
if ("RepositoryAlreadyExistsException".equals(e.getErrorCode())) {
repo = ecrService.describeRepositories(List.of(repoName), null, "us-east-1").get(0);
} else {
throw e;
}
}
// Lifecycle policy can be inlined as `LifecyclePolicy.LifecyclePolicyText`
if (props != null && props.has("LifecyclePolicy")) {
JsonNode lp = engine.resolveNode(props.get("LifecyclePolicy"));
String policyText = lp.path("LifecyclePolicyText").asText(null);
if (policyText != null && !policyText.isEmpty()) {
ecrService.putLifecyclePolicy(repoName, null, policyText, "us-east-1");
}
}
if (props != null && props.has("RepositoryPolicyText")) {
JsonNode pol = engine.resolveNode(props.get("RepositoryPolicyText"));
String policyText = pol.isTextual() ? pol.asText() : pol.toString();
if (policyText != null && !policyText.isEmpty()) {
ecrService.setRepositoryPolicy(repoName, null, policyText, "us-east-1");
}
}
r.setPhysicalId(repoName);
r.getAttributes().put("Arn", "arn:aws:ecr:us-east-1:000000000000:repository/" + repoName);
r.getAttributes().put("Arn", repo.getRepositoryArn());
r.getAttributes().put("RepositoryUri", repo.getRepositoryUri());
}
private Map<String, String> parseCfnTags(JsonNode tagsNode, CloudFormationTemplateEngine engine) {
Map<String, String> out = new HashMap<>();
if (tagsNode == null || tagsNode.isNull() || !tagsNode.isArray()) {
return out;
}
for (JsonNode entry : tagsNode) {
JsonNode resolved = engine.resolveNode(entry);
String key = resolved.path("Key").asText(null);
String value = resolved.path("Value").asText("");
if (key != null) {
out.put(key, value);
}
}
return out;
}
private void provisionRoute53HostedZone(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) {
@@ -0,0 +1,455 @@
package io.github.hectorvent.floci.services.ecr;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.services.ecr.model.AuthorizationData;
import io.github.hectorvent.floci.services.ecr.model.Image;
import io.github.hectorvent.floci.services.ecr.model.ImageDetail;
import io.github.hectorvent.floci.services.ecr.model.ImageFailure;
import io.github.hectorvent.floci.services.ecr.model.ImageIdentifier;
import io.github.hectorvent.floci.services.ecr.model.Repository;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* AWS JSON 1.1 dispatcher for the {@code AmazonEC2ContainerRegistry_V20150921}
* target prefix.
*/
@ApplicationScoped
public class EcrJsonHandler {
private final EcrService service;
private final ObjectMapper objectMapper;
@Inject
public EcrJsonHandler(EcrService service, ObjectMapper objectMapper) {
this.service = service;
this.objectMapper = objectMapper;
}
public Response handle(String action, JsonNode request, String region) {
return switch (action) {
case "CreateRepository" -> handleCreateRepository(request, region);
case "DescribeRepositories" -> handleDescribeRepositories(request, region);
case "DeleteRepository" -> handleDeleteRepository(request, region);
case "GetAuthorizationToken" -> handleGetAuthorizationToken(request);
case "ListImages" -> handleListImages(request, region);
case "DescribeImages" -> handleDescribeImages(request, region);
case "BatchGetImage" -> handleBatchGetImage(request, region);
case "BatchDeleteImage" -> handleBatchDeleteImage(request, region);
case "PutImageTagMutability" -> handlePutImageTagMutability(request, region);
case "TagResource" -> handleTagResource(request, region);
case "UntagResource" -> handleUntagResource(request, region);
case "ListTagsForResource" -> handleListTagsForResource(request, region);
case "PutLifecyclePolicy" -> handlePutLifecyclePolicy(request, region);
case "GetLifecyclePolicy" -> handleGetLifecyclePolicy(request, region);
case "DeleteLifecyclePolicy" -> handleDeleteLifecyclePolicy(request, region);
case "SetRepositoryPolicy" -> handleSetRepositoryPolicy(request, region);
case "GetRepositoryPolicy" -> handleGetRepositoryPolicy(request, region);
case "DeleteRepositoryPolicy" -> handleDeleteRepositoryPolicy(request, region);
default -> Response.status(400)
.entity(new AwsErrorResponse("UnsupportedOperation",
"Operation " + action + " is not supported."))
.build();
};
}
private Response handleCreateRepository(JsonNode request, String region) {
String repositoryName = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
String tagMutability = request.path("imageTagMutability").asText(null);
Boolean scanOnPush = request.path("imageScanningConfiguration").has("scanOnPush")
? request.path("imageScanningConfiguration").path("scanOnPush").asBoolean()
: null;
String encType = request.path("encryptionConfiguration").path("encryptionType").asText(null);
String kmsKey = request.path("encryptionConfiguration").path("kmsKey").asText(null);
Map<String, String> tags = parseTags(request.path("tags"));
Repository repo = service.createRepository(repositoryName, registryId, tagMutability,
scanOnPush, encType, kmsKey, tags, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("repository", buildRepository(repo));
return Response.ok(response).build();
}
private Response handleDescribeRepositories(JsonNode request, String region) {
List<String> names = parseStringList(request.path("repositoryNames"));
String registryId = request.path("registryId").asText(null);
List<Repository> repos = service.describeRepositories(names, registryId, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = objectMapper.createArrayNode();
for (Repository r : repos) {
arr.add(buildRepository(r));
}
response.set("repositories", arr);
return Response.ok(response).build();
}
private Response handleDeleteRepository(JsonNode request, String region) {
String repositoryName = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
boolean force = request.path("force").asBoolean(false);
Repository repo = service.deleteRepository(repositoryName, registryId, force, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("repository", buildRepository(repo));
return Response.ok(response).build();
}
private Response handleGetAuthorizationToken(JsonNode request) {
AuthorizationData data = service.getAuthorizationToken();
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = objectMapper.createArrayNode();
ObjectNode entry = objectMapper.createObjectNode();
entry.put("authorizationToken", data.getAuthorizationToken());
entry.put("expiresAt", data.getExpiresAt().getEpochSecond());
entry.put("proxyEndpoint", data.getProxyEndpoint());
arr.add(entry);
response.set("authorizationData", arr);
return Response.ok(response).build();
}
// ============================================================
// Image inspection / batch operations
// ============================================================
private Response handleListImages(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
List<ImageIdentifier> ids = service.listImages(repo, registryId, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = objectMapper.createArrayNode();
for (ImageIdentifier id : ids) {
arr.add(buildImageIdentifier(id));
}
response.set("imageIds", arr);
return Response.ok(response).build();
}
private Response handleDescribeImages(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
List<ImageIdentifier> requested = parseImageIds(request.path("imageIds"));
EcrService.DescribeImagesResult result = service.describeImages(repo, requested, registryId, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode details = objectMapper.createArrayNode();
for (ImageDetail d : result.imageDetails()) {
details.add(buildImageDetail(d));
}
response.set("imageDetails", details);
ArrayNode failures = objectMapper.createArrayNode();
for (ImageFailure f : result.failures()) {
failures.add(buildImageFailure(f));
}
response.set("failures", failures);
return Response.ok(response).build();
}
private Response handleBatchGetImage(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
List<ImageIdentifier> ids = parseImageIds(request.path("imageIds"));
List<String> accepted = parseStringList(request.path("acceptedMediaTypes"));
EcrService.BatchGetImageResult result = service.batchGetImage(repo, ids, accepted, registryId, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode imgs = objectMapper.createArrayNode();
for (Image img : result.images()) {
ObjectNode n = objectMapper.createObjectNode();
n.put("registryId", img.getRegistryId());
n.put("repositoryName", img.getRepositoryName());
n.set("imageId", buildImageIdentifier(img.getImageId()));
if (img.getImageManifest() != null) {
n.put("imageManifest", img.getImageManifest());
}
if (img.getImageManifestMediaType() != null) {
n.put("imageManifestMediaType", img.getImageManifestMediaType());
}
imgs.add(n);
}
response.set("images", imgs);
ArrayNode failures = objectMapper.createArrayNode();
for (ImageFailure f : result.failures()) {
failures.add(buildImageFailure(f));
}
response.set("failures", failures);
return Response.ok(response).build();
}
private Response handleBatchDeleteImage(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
List<ImageIdentifier> ids = parseImageIds(request.path("imageIds"));
EcrService.BatchDeleteImageResult result = service.batchDeleteImage(repo, ids, registryId, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = objectMapper.createArrayNode();
for (ImageIdentifier id : result.imageIds()) {
arr.add(buildImageIdentifier(id));
}
response.set("imageIds", arr);
ArrayNode failures = objectMapper.createArrayNode();
for (ImageFailure f : result.failures()) {
failures.add(buildImageFailure(f));
}
response.set("failures", failures);
return Response.ok(response).build();
}
// ============================================================
// Tag mutability + resource tags
// ============================================================
private Response handlePutImageTagMutability(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
String mutability = request.path("imageTagMutability").asText(null);
Repository updated = service.putImageTagMutability(repo, registryId, mutability, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("registryId", updated.getRegistryId());
response.put("repositoryName", updated.getRepositoryName());
response.put("imageTagMutability", updated.getImageTagMutability());
return Response.ok(response).build();
}
private Response handleTagResource(JsonNode request, String region) {
String resourceArn = request.path("resourceArn").asText(null);
String repoName = repoNameFromArn(resourceArn);
Map<String, String> tags = parseTags(request.path("tags"));
service.tagResource(repoName, accountFromArn(resourceArn), tags, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleUntagResource(JsonNode request, String region) {
String resourceArn = request.path("resourceArn").asText(null);
String repoName = repoNameFromArn(resourceArn);
List<String> keys = parseStringList(request.path("tagKeys"));
service.untagResource(repoName, accountFromArn(resourceArn), keys, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleListTagsForResource(JsonNode request, String region) {
String resourceArn = request.path("resourceArn").asText(null);
String repoName = repoNameFromArn(resourceArn);
Map<String, String> tags = service.listTagsForResource(repoName, accountFromArn(resourceArn), region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = objectMapper.createArrayNode();
for (Map.Entry<String, String> e : tags.entrySet()) {
ObjectNode entry = objectMapper.createObjectNode();
entry.put("Key", e.getKey());
entry.put("Value", e.getValue());
arr.add(entry);
}
response.set("tags", arr);
return Response.ok(response).build();
}
// ============================================================
// Lifecycle + repository policies
// ============================================================
private Response handlePutLifecyclePolicy(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
String text = request.path("lifecyclePolicyText").asText(null);
Repository updated = service.putLifecyclePolicy(repo, registryId, text, region);
return lifecycleResponse(updated);
}
private Response handleGetLifecyclePolicy(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
Repository r = service.getLifecyclePolicy(repo, registryId, region);
return lifecycleResponse(r);
}
private Response handleDeleteLifecyclePolicy(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
Repository r = service.deleteLifecyclePolicy(repo, registryId, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("registryId", r.getRegistryId());
response.put("repositoryName", r.getRepositoryName());
return Response.ok(response).build();
}
private Response lifecycleResponse(Repository r) {
ObjectNode response = objectMapper.createObjectNode();
response.put("registryId", r.getRegistryId());
response.put("repositoryName", r.getRepositoryName());
if (r.getLifecyclePolicyText() != null) {
response.put("lifecyclePolicyText", r.getLifecyclePolicyText());
}
return Response.ok(response).build();
}
private Response handleSetRepositoryPolicy(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
String text = request.path("policyText").asText(null);
Repository updated = service.setRepositoryPolicy(repo, registryId, text, region);
return repoPolicyResponse(updated);
}
private Response handleGetRepositoryPolicy(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
Repository r = service.getRepositoryPolicy(repo, registryId, region);
return repoPolicyResponse(r);
}
private Response handleDeleteRepositoryPolicy(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
Repository r = service.deleteRepositoryPolicy(repo, registryId, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("registryId", r.getRegistryId());
response.put("repositoryName", r.getRepositoryName());
return Response.ok(response).build();
}
private Response repoPolicyResponse(Repository r) {
ObjectNode response = objectMapper.createObjectNode();
response.put("registryId", r.getRegistryId());
response.put("repositoryName", r.getRepositoryName());
if (r.getRepositoryPolicyText() != null) {
response.put("policyText", r.getRepositoryPolicyText());
}
return Response.ok(response).build();
}
// ============================================================
// Builders / parsers
// ============================================================
private ObjectNode buildImageIdentifier(ImageIdentifier id) {
ObjectNode n = objectMapper.createObjectNode();
if (id.getImageTag() != null) n.put("imageTag", id.getImageTag());
if (id.getImageDigest() != null) n.put("imageDigest", id.getImageDigest());
return n;
}
private ObjectNode buildImageDetail(ImageDetail d) {
ObjectNode n = objectMapper.createObjectNode();
n.put("registryId", d.getRegistryId());
n.put("repositoryName", d.getRepositoryName());
if (d.getImageDigest() != null) n.put("imageDigest", d.getImageDigest());
ArrayNode tags = objectMapper.createArrayNode();
for (String t : d.getImageTags()) tags.add(t);
n.set("imageTags", tags);
n.put("imageSizeInBytes", d.getImageSizeInBytes());
if (d.getImagePushedAt() != null) {
n.put("imagePushedAt", d.getImagePushedAt().getEpochSecond());
}
if (d.getImageManifestMediaType() != null) {
n.put("imageManifestMediaType", d.getImageManifestMediaType());
}
if (d.getArtifactMediaType() != null) {
n.put("artifactMediaType", d.getArtifactMediaType());
}
return n;
}
private ObjectNode buildImageFailure(ImageFailure f) {
ObjectNode n = objectMapper.createObjectNode();
if (f.getImageId() != null) n.set("imageId", buildImageIdentifier(f.getImageId()));
if (f.getFailureCode() != null) n.put("failureCode", f.getFailureCode());
if (f.getFailureReason() != null) n.put("failureReason", f.getFailureReason());
return n;
}
private static List<ImageIdentifier> parseImageIds(JsonNode node) {
List<ImageIdentifier> out = new ArrayList<>();
if (node == null || node.isMissingNode() || node.isNull() || !node.isArray()) {
return out;
}
node.forEach(e -> out.add(new ImageIdentifier(
e.path("imageTag").asText(null),
e.path("imageDigest").asText(null))));
return out;
}
private static String repoNameFromArn(String arn) {
if (arn == null) return null;
int idx = arn.indexOf(":repository/");
return idx < 0 ? null : arn.substring(idx + ":repository/".length());
}
private static String accountFromArn(String arn) {
if (arn == null) return null;
// arn:aws:ecr:<region>:<account>:repository/<name>
String[] parts = arn.split(":");
return parts.length >= 5 ? parts[4] : null;
}
private ObjectNode buildRepository(Repository repo) {
ObjectNode n = objectMapper.createObjectNode();
n.put("repositoryArn", repo.getRepositoryArn());
n.put("registryId", repo.getRegistryId());
n.put("repositoryName", repo.getRepositoryName());
n.put("repositoryUri", repo.getRepositoryUri());
if (repo.getCreatedAt() != null) {
n.put("createdAt", repo.getCreatedAt().getEpochSecond());
}
n.put("imageTagMutability", repo.getImageTagMutability());
ObjectNode scanCfg = objectMapper.createObjectNode();
scanCfg.put("scanOnPush", repo.isScanOnPush());
n.set("imageScanningConfiguration", scanCfg);
ObjectNode enc = objectMapper.createObjectNode();
enc.put("encryptionType", repo.getEncryptionType());
if (repo.getKmsKey() != null) {
enc.put("kmsKey", repo.getKmsKey());
}
n.set("encryptionConfiguration", enc);
return n;
}
private static List<String> parseStringList(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull() || !node.isArray()) {
return new ArrayList<>();
}
List<String> out = new ArrayList<>();
node.forEach(n -> out.add(n.asText()));
return out;
}
private static Map<String, String> parseTags(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull() || !node.isArray()) {
return new HashMap<>();
}
Map<String, String> tags = new HashMap<>();
Iterator<JsonNode> it = node.elements();
while (it.hasNext()) {
JsonNode entry = it.next();
String key = entry.path("Key").asText(null);
String value = entry.path("Value").asText("");
if (key != null) {
tags.put(key, value);
}
}
return tags;
}
}
@@ -0,0 +1,545 @@
package io.github.hectorvent.floci.services.ecr;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ecr.model.AuthorizationData;
import io.github.hectorvent.floci.services.ecr.model.ImageDetail;
import io.github.hectorvent.floci.services.ecr.model.ImageFailure;
import io.github.hectorvent.floci.services.ecr.model.ImageIdentifier;
import io.github.hectorvent.floci.services.ecr.model.ImageMetadata;
import io.github.hectorvent.floci.services.ecr.model.Image;
import io.github.hectorvent.floci.services.ecr.model.Repository;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.ecr.registry.RegistryHttpClient;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
@ApplicationScoped
public class EcrService {
private static final Logger LOG = Logger.getLogger(EcrService.class);
private static final Pattern REPO_NAME = Pattern.compile(
"(?:[a-z0-9]+(?:[._-][a-z0-9]+)*/)*[a-z0-9]+(?:[._-][a-z0-9]+)*");
private static final int MAX_REPO_NAME_LENGTH = 256;
private final StorageBackend<String, Repository> repoStore;
private final StorageBackend<String, ImageMetadata> imageMetaStore;
private final EcrRegistryManager registryManager;
private final EmulatorConfig config;
@Inject
public EcrService(StorageFactory factory,
EcrRegistryManager registryManager,
EmulatorConfig config) {
this(factory.create("ecr", "repositories.json",
new TypeReference<Map<String, Repository>>() {}),
factory.create("ecr", "image-metadata.json",
new TypeReference<Map<String, ImageMetadata>>() {}),
registryManager, config);
}
EcrService(StorageBackend<String, Repository> repoStore,
StorageBackend<String, ImageMetadata> imageMetaStore,
EcrRegistryManager registryManager,
EmulatorConfig config) {
this.repoStore = repoStore;
this.imageMetaStore = imageMetaStore;
this.registryManager = registryManager;
this.config = config;
this.registryManager.setReconcileHook(this::reconcileFromCatalog);
}
/**
* Recreates {@link Repository} metadata entries for any internal-namespaced
* repos found in the registry catalog that are missing from local storage.
* Internal names are of the form {@code <account>/<region>/<repoName>}.
*/
void reconcileFromCatalog(List<String> catalog) {
if (catalog == null || catalog.isEmpty()) {
return;
}
int recreated = 0;
for (String internal : catalog) {
String[] parts = internal.split("/", 3);
if (parts.length < 3) {
continue;
}
String account = parts[0];
String region = parts[1];
String repoName = parts[2];
String key = key(region, account, repoName);
if (repoStore.get(key).isPresent()) {
continue;
}
Repository repo = new Repository();
repo.setRepositoryName(repoName);
repo.setRegistryId(account);
repo.setRepositoryArn("arn:aws:ecr:" + region + ":" + account + ":repository/" + repoName);
repo.setRepositoryUri(registryManager.getRepositoryUri(account, region, repoName));
repo.setCreatedAt(Instant.now());
repoStore.put(key, repo);
recreated++;
}
if (recreated > 0) {
LOG.infov("Reconciled {0} ECR repository metadata entries from registry catalog", recreated);
}
}
// ============================================================
// CreateRepository
// ============================================================
public Repository createRepository(String repositoryName,
String registryId,
String imageTagMutability,
Boolean scanOnPush,
String encryptionType,
String kmsKey,
Map<String, String> tags,
String region) {
validateRepoName(repositoryName);
registryManager.ensureStarted();
String account = effectiveAccount(registryId);
String key = key(region, account, repositoryName);
if (repoStore.get(key).isPresent()) {
throw new AwsException("RepositoryAlreadyExistsException",
"The repository with name '" + repositoryName + "' already exists in the registry with id '"
+ account + "'", 400);
}
Repository repo = new Repository();
repo.setRepositoryName(repositoryName);
repo.setRegistryId(account);
repo.setRepositoryArn("arn:aws:ecr:" + region + ":" + account + ":repository/" + repositoryName);
repo.setRepositoryUri(registryManager.getRepositoryUri(account, region, repositoryName));
repo.setCreatedAt(Instant.now());
if (imageTagMutability != null && !imageTagMutability.isBlank()) {
repo.setImageTagMutability(imageTagMutability);
}
if (scanOnPush != null) {
repo.setScanOnPush(scanOnPush);
}
if (encryptionType != null && !encryptionType.isBlank()) {
repo.setEncryptionType(encryptionType);
}
repo.setKmsKey(kmsKey);
if (tags != null) {
repo.getTags().putAll(tags);
}
repoStore.put(key, repo);
LOG.infov("Created ECR repository {0}/{1}/{2}", region, account, repositoryName);
return repo;
}
// ============================================================
// DescribeRepositories
// ============================================================
public List<Repository> describeRepositories(List<String> repositoryNames,
String registryId,
String region) {
String account = effectiveAccount(registryId);
String prefix = region + "::" + account + "::";
if (repositoryNames == null || repositoryNames.isEmpty()) {
return repoStore.scan(k -> k.startsWith(prefix));
}
List<Repository> out = new ArrayList<>();
for (String name : repositoryNames) {
String key = key(region, account, name);
Repository repo = repoStore.get(key).orElseThrow(() -> notFound(name, account));
out.add(repo);
}
return out;
}
// ============================================================
// DeleteRepository
// ============================================================
public Repository deleteRepository(String repositoryName,
String registryId,
boolean force,
String region) {
String account = effectiveAccount(registryId);
String key = key(region, account, repositoryName);
Repository repo = repoStore.get(key).orElseThrow(() -> notFound(repositoryName, account));
// Check whether the registry has any tagged images for this repo. If
// ensureStarted() can't talk to docker (no daemon), assume the repo is
// empty — this allows control-plane unit tests to delete without docker.
List<String> tags = listTagsBestEffort(account, region, repositoryName);
if (!tags.isEmpty() && !force) {
throw new AwsException("RepositoryNotEmptyException",
"The repository with name '" + repositoryName
+ "' in registry with id '" + account + "' cannot be deleted because it still contains images",
400);
}
if (force && !tags.isEmpty()) {
// Phase 5 will issue real DELETE /v2/<name>/manifests/<digest> calls.
LOG.infov("Force-deleting ECR repository {0} containing {1} tag(s) (manifest deletion deferred)",
repositoryName, tags.size());
}
repoStore.delete(key);
// Drop cached image metadata for this repo.
String metaPrefix = key + "::";
for (ImageMetadata meta : imageMetaStore.scan(k -> k.startsWith(metaPrefix))) {
imageMetaStore.delete(metaPrefix + meta.getDigest());
}
LOG.infov("Deleted ECR repository {0}/{1}/{2}", region, account, repositoryName);
return repo;
}
// ============================================================
// GetAuthorizationToken
// ============================================================
public AuthorizationData getAuthorizationToken() {
registryManager.ensureStarted();
String token = Base64.getEncoder()
.encodeToString("AWS:floci".getBytes(StandardCharsets.UTF_8));
Instant expires = Instant.now().plusSeconds(12 * 60 * 60);
String proxy = registryManager.getProxyEndpoint();
return new AuthorizationData(token, expires, proxy);
}
// ============================================================
// ListImages / DescribeImages / BatchGetImage / BatchDeleteImage
// ============================================================
public List<ImageIdentifier> listImages(String repositoryName, String registryId, String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
registryManager.ensureStarted();
String internal = registryManager.internalRepoName(repo.getRegistryId(), region, repositoryName);
try {
RegistryHttpClient http = registryManager.httpClient();
List<String> tags = http.listTags(internal);
List<ImageIdentifier> out = new ArrayList<>();
for (String tag : tags) {
String digest = http.headManifestDigest(internal, tag, null);
out.add(new ImageIdentifier(tag, digest));
}
return out;
} catch (Exception e) {
LOG.warnv("ListImages registry query failed for {0}: {1}", repositoryName, e.getMessage());
return List.of();
}
}
public DescribeImagesResult describeImages(String repositoryName,
List<ImageIdentifier> requested,
String registryId,
String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
registryManager.ensureStarted();
String internal = registryManager.internalRepoName(repo.getRegistryId(), region, repositoryName);
RegistryHttpClient http = registryManager.httpClient();
List<String> refs = new ArrayList<>();
if (requested == null || requested.isEmpty()) {
try {
refs.addAll(http.listTags(internal));
} catch (Exception e) {
LOG.warnv("DescribeImages tag enumeration failed for {0}: {1}", repositoryName, e.getMessage());
}
} else {
for (ImageIdentifier id : requested) {
if (id.getImageTag() != null) refs.add(id.getImageTag());
else if (id.getImageDigest() != null) refs.add(id.getImageDigest());
}
}
boolean explicitRequest = requested != null && !requested.isEmpty();
List<ImageDetail> details = new ArrayList<>();
List<ImageFailure> failures = new ArrayList<>();
for (String ref : refs) {
try {
RegistryHttpClient.ManifestResult m = http.getManifest(internal, ref, null);
if (m == null) {
failures.add(new ImageFailure(
new ImageIdentifier(ref.startsWith("sha256:") ? null : ref,
ref.startsWith("sha256:") ? ref : null),
"ImageNotFound", "Image not found"));
continue;
}
ImageDetail d = new ImageDetail();
d.setRegistryId(repo.getRegistryId());
d.setRepositoryName(repositoryName);
d.setImageDigest(m.digest());
if (!ref.startsWith("sha256:")) {
d.setImageTags(new ArrayList<>(List.of(ref)));
}
d.setImageSizeInBytes(RegistryHttpClient.sizeFromManifest(m.body()));
d.setImageManifestMediaType(m.mediaType());
d.setArtifactMediaType(RegistryHttpClient.artifactMediaTypeFromManifest(m.body()));
String metaKey = imageMetaKey(region, repo.getRegistryId(), repositoryName, m.digest());
ImageMetadata meta = imageMetaStore.get(metaKey).orElseGet(() -> {
ImageMetadata fresh = new ImageMetadata(m.digest(), Instant.now());
imageMetaStore.put(metaKey, fresh);
return fresh;
});
d.setImagePushedAt(meta.getPushedAt());
details.add(d);
} catch (Exception e) {
LOG.warnv("DescribeImages registry call failed for {0}/{1}: {2}", repositoryName, ref, e.getMessage());
failures.add(new ImageFailure(
new ImageIdentifier(ref.startsWith("sha256:") ? null : ref,
ref.startsWith("sha256:") ? ref : null),
"ImageNotFound", "Image not found"));
}
}
// Real AWS throws ImageNotFoundException when explicit imageIds were passed
// and NONE of them resolved to an actual image. cdk-assets relies on this
// exception to decide whether an asset needs to be published.
if (explicitRequest && details.isEmpty()) {
throw new AwsException("ImageNotFoundException",
"The image with imageId(s) " + requested + " does not exist within the repository with name '"
+ repositoryName + "' in the registry with id '" + repo.getRegistryId() + "'", 400);
}
return new DescribeImagesResult(details, failures);
}
public BatchGetImageResult batchGetImage(String repositoryName,
List<ImageIdentifier> imageIds,
List<String> acceptedMediaTypes,
String registryId,
String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
registryManager.ensureStarted();
String internal = registryManager.internalRepoName(repo.getRegistryId(), region, repositoryName);
RegistryHttpClient http = registryManager.httpClient();
List<Image> images = new ArrayList<>();
List<ImageFailure> failures = new ArrayList<>();
if (imageIds == null) imageIds = List.of();
for (ImageIdentifier id : imageIds) {
String ref = id.getImageTag() != null ? id.getImageTag() : id.getImageDigest();
if (ref == null) {
failures.add(new ImageFailure(id, "MissingDigestAndTag", "Both imageTag and imageDigest are missing"));
continue;
}
try {
RegistryHttpClient.ManifestResult m = http.getManifest(internal, ref, acceptedMediaTypes);
if (m == null) {
failures.add(new ImageFailure(id, "ImageNotFound", "Image not found"));
continue;
}
Image img = new Image();
img.setRegistryId(repo.getRegistryId());
img.setRepositoryName(repositoryName);
img.setImageId(new ImageIdentifier(
id.getImageTag(),
m.digest() != null ? m.digest() : id.getImageDigest()));
img.setImageManifest(m.body());
img.setImageManifestMediaType(m.mediaType());
images.add(img);
} catch (Exception e) {
failures.add(new ImageFailure(id, "ImageNotFound", e.getMessage()));
}
}
return new BatchGetImageResult(images, failures);
}
public BatchDeleteImageResult batchDeleteImage(String repositoryName,
List<ImageIdentifier> imageIds,
String registryId,
String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
registryManager.ensureStarted();
String internal = registryManager.internalRepoName(repo.getRegistryId(), region, repositoryName);
RegistryHttpClient http = registryManager.httpClient();
List<ImageIdentifier> deleted = new ArrayList<>();
List<ImageFailure> failures = new ArrayList<>();
if (imageIds == null) imageIds = List.of();
for (ImageIdentifier id : imageIds) {
try {
String digest = id.getImageDigest();
if (digest == null && id.getImageTag() != null) {
digest = http.headManifestDigest(internal, id.getImageTag(), null);
}
if (digest == null) {
failures.add(new ImageFailure(id, "ImageNotFound", "Image not found"));
continue;
}
boolean ok = http.deleteManifest(internal, digest);
if (!ok) {
failures.add(new ImageFailure(id, "ImageNotFound", "Image not found"));
continue;
}
deleted.add(new ImageIdentifier(id.getImageTag(), digest));
imageMetaStore.delete(imageMetaKey(region, repo.getRegistryId(), repositoryName, digest));
} catch (Exception e) {
failures.add(new ImageFailure(id, "ImageNotFound", e.getMessage()));
}
}
return new BatchDeleteImageResult(deleted, failures);
}
// ============================================================
// Tag mutability + resource tags + policies (metadata round-trip)
// ============================================================
public Repository putImageTagMutability(String repositoryName, String registryId,
String mutability, String region) {
if (mutability == null
|| (!"MUTABLE".equals(mutability) && !"IMMUTABLE".equals(mutability))) {
throw new AwsException("InvalidParameterException",
"imageTagMutability must be MUTABLE or IMMUTABLE", 400);
}
Repository repo = requireRepo(repositoryName, registryId, region);
repo.setImageTagMutability(mutability);
repoStore.put(key(region, repo.getRegistryId(), repositoryName), repo);
return repo;
}
public void tagResource(String repoName, String registryId, Map<String, String> tags, String region) {
Repository repo = requireRepo(repoName, registryId, region);
if (tags != null) {
repo.getTags().putAll(tags);
}
repoStore.put(key(region, repo.getRegistryId(), repoName), repo);
}
public void untagResource(String repoName, String registryId, List<String> tagKeys, String region) {
Repository repo = requireRepo(repoName, registryId, region);
if (tagKeys != null) {
for (String k : tagKeys) {
repo.getTags().remove(k);
}
}
repoStore.put(key(region, repo.getRegistryId(), repoName), repo);
}
public Map<String, String> listTagsForResource(String repoName, String registryId, String region) {
Repository repo = requireRepo(repoName, registryId, region);
return repo.getTags();
}
public Repository putLifecyclePolicy(String repoName, String registryId, String policyText, String region) {
Repository repo = requireRepo(repoName, registryId, region);
repo.setLifecyclePolicyText(policyText);
repoStore.put(key(region, repo.getRegistryId(), repoName), repo);
return repo;
}
public Repository getLifecyclePolicy(String repoName, String registryId, String region) {
Repository repo = requireRepo(repoName, registryId, region);
if (repo.getLifecyclePolicyText() == null) {
throw new AwsException("LifecyclePolicyNotFoundException",
"No lifecycle policy associated with repository " + repoName, 400);
}
return repo;
}
public Repository deleteLifecyclePolicy(String repoName, String registryId, String region) {
Repository repo = getLifecyclePolicy(repoName, registryId, region);
repo.setLifecyclePolicyText(null);
repoStore.put(key(region, repo.getRegistryId(), repoName), repo);
return repo;
}
public Repository setRepositoryPolicy(String repoName, String registryId, String policyText, String region) {
Repository repo = requireRepo(repoName, registryId, region);
repo.setRepositoryPolicyText(policyText);
repoStore.put(key(region, repo.getRegistryId(), repoName), repo);
return repo;
}
public Repository getRepositoryPolicy(String repoName, String registryId, String region) {
Repository repo = requireRepo(repoName, registryId, region);
if (repo.getRepositoryPolicyText() == null) {
throw new AwsException("RepositoryPolicyNotFoundException",
"Repository policy does not exist for the repository with name '" + repoName + "'", 400);
}
return repo;
}
public Repository deleteRepositoryPolicy(String repoName, String registryId, String region) {
Repository repo = getRepositoryPolicy(repoName, registryId, region);
repo.setRepositoryPolicyText(null);
repoStore.put(key(region, repo.getRegistryId(), repoName), repo);
return repo;
}
// ============================================================
// Result records
// ============================================================
public record DescribeImagesResult(List<ImageDetail> imageDetails, List<ImageFailure> failures) {}
public record BatchGetImageResult(List<Image> images, List<ImageFailure> failures) {}
public record BatchDeleteImageResult(List<ImageIdentifier> imageIds, List<ImageFailure> failures) {}
// ============================================================
// Helpers
// ============================================================
private Repository requireRepo(String name, String registryId, String region) {
String account = effectiveAccount(registryId);
return repoStore.get(key(region, account, name)).orElseThrow(() -> notFound(name, account));
}
private static String imageMetaKey(String region, String account, String repoName, String digest) {
return key(region, account, repoName) + "::" + digest;
}
private List<String> listTagsBestEffort(String account, String region, String repoName) {
try {
return registryManager.httpClient()
.listTags(registryManager.internalRepoName(account, region, repoName));
} catch (Exception e) {
LOG.debugv("Could not list tags for {0} (registry not available): {1}", repoName, e.getMessage());
return List.of();
}
}
private static String key(String region, String account, String repoName) {
return region + "::" + account + "::" + repoName;
}
private String effectiveAccount(String registryId) {
if (registryId != null && !registryId.isBlank()) {
return registryId;
}
return config.defaultAccountId();
}
private static void validateRepoName(String name) {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidParameterException",
"Repository name must not be empty", 400);
}
if (name.length() > MAX_REPO_NAME_LENGTH) {
throw new AwsException("InvalidParameterException",
"Repository name exceeds " + MAX_REPO_NAME_LENGTH + " characters", 400);
}
if (!REPO_NAME.matcher(name).matches()) {
throw new AwsException("InvalidParameterException",
"Repository name '" + name + "' does not match the required pattern", 400);
}
}
private static AwsException notFound(String name, String account) {
return new AwsException("RepositoryNotFoundException",
"The repository with name '" + name + "' does not exist in the registry with id '"
+ account + "'", 400);
}
}
@@ -0,0 +1,34 @@
package io.github.hectorvent.floci.services.ecr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/**
* Short-lived credential bundle returned by GetAuthorizationToken.
*
* @see <a href="https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_AuthorizationData.html">AWS ECR AuthorizationData</a>
*/
@RegisterForReflection
public class AuthorizationData {
private String authorizationToken;
private Instant expiresAt;
private String proxyEndpoint;
public AuthorizationData() {}
public AuthorizationData(String authorizationToken, Instant expiresAt, String proxyEndpoint) {
this.authorizationToken = authorizationToken;
this.expiresAt = expiresAt;
this.proxyEndpoint = proxyEndpoint;
}
public String getAuthorizationToken() { return authorizationToken; }
public void setAuthorizationToken(String authorizationToken) { this.authorizationToken = authorizationToken; }
public Instant getExpiresAt() { return expiresAt; }
public void setExpiresAt(Instant expiresAt) { this.expiresAt = expiresAt; }
public String getProxyEndpoint() { return proxyEndpoint; }
public void setProxyEndpoint(String proxyEndpoint) { this.proxyEndpoint = proxyEndpoint; }
}
@@ -0,0 +1,34 @@
package io.github.hectorvent.floci.services.ecr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* An image manifest returned by BatchGetImage.
*
* @see <a href="https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_Image.html">AWS ECR Image</a>
*/
@RegisterForReflection
public class Image {
private String registryId;
private String repositoryName;
private ImageIdentifier imageId;
private String imageManifest;
private String imageManifestMediaType;
public Image() {}
public String getRegistryId() { return registryId; }
public void setRegistryId(String registryId) { this.registryId = registryId; }
public String getRepositoryName() { return repositoryName; }
public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; }
public ImageIdentifier getImageId() { return imageId; }
public void setImageId(ImageIdentifier imageId) { this.imageId = imageId; }
public String getImageManifest() { return imageManifest; }
public void setImageManifest(String imageManifest) { this.imageManifest = imageManifest; }
public String getImageManifestMediaType() { return imageManifestMediaType; }
public void setImageManifestMediaType(String imageManifestMediaType) { this.imageManifestMediaType = imageManifestMediaType; }
}
@@ -0,0 +1,50 @@
package io.github.hectorvent.floci.services.ecr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
* Detailed image metadata returned by DescribeImages.
*
* @see <a href="https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_ImageDetail.html">AWS ECR ImageDetail</a>
*/
@RegisterForReflection
public class ImageDetail {
private String registryId;
private String repositoryName;
private String imageDigest;
private List<String> imageTags = new ArrayList<>();
private long imageSizeInBytes;
private Instant imagePushedAt;
private String imageManifestMediaType;
private String artifactMediaType;
public ImageDetail() {}
public String getRegistryId() { return registryId; }
public void setRegistryId(String registryId) { this.registryId = registryId; }
public String getRepositoryName() { return repositoryName; }
public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; }
public String getImageDigest() { return imageDigest; }
public void setImageDigest(String imageDigest) { this.imageDigest = imageDigest; }
public List<String> getImageTags() { return imageTags; }
public void setImageTags(List<String> imageTags) { this.imageTags = imageTags == null ? new ArrayList<>() : imageTags; }
public long getImageSizeInBytes() { return imageSizeInBytes; }
public void setImageSizeInBytes(long imageSizeInBytes) { this.imageSizeInBytes = imageSizeInBytes; }
public Instant getImagePushedAt() { return imagePushedAt; }
public void setImagePushedAt(Instant imagePushedAt) { this.imagePushedAt = imagePushedAt; }
public String getImageManifestMediaType() { return imageManifestMediaType; }
public void setImageManifestMediaType(String imageManifestMediaType) { this.imageManifestMediaType = imageManifestMediaType; }
public String getArtifactMediaType() { return artifactMediaType; }
public void setArtifactMediaType(String artifactMediaType) { this.artifactMediaType = artifactMediaType; }
}
@@ -0,0 +1,32 @@
package io.github.hectorvent.floci.services.ecr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* Per-item failure entry for batch image operations.
*
* @see <a href="https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_ImageFailure.html">AWS ECR ImageFailure</a>
*/
@RegisterForReflection
public class ImageFailure {
private ImageIdentifier imageId;
private String failureCode;
private String failureReason;
public ImageFailure() {}
public ImageFailure(ImageIdentifier imageId, String failureCode, String failureReason) {
this.imageId = imageId;
this.failureCode = failureCode;
this.failureReason = failureReason;
}
public ImageIdentifier getImageId() { return imageId; }
public void setImageId(ImageIdentifier imageId) { this.imageId = imageId; }
public String getFailureCode() { return failureCode; }
public void setFailureCode(String failureCode) { this.failureCode = failureCode; }
public String getFailureReason() { return failureReason; }
public void setFailureReason(String failureReason) { this.failureReason = failureReason; }
}
@@ -0,0 +1,27 @@
package io.github.hectorvent.floci.services.ecr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* Reference to an image by tag, digest, or both.
*
* @see <a href="https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_ImageIdentifier.html">AWS ECR ImageIdentifier</a>
*/
@RegisterForReflection
public class ImageIdentifier {
private String imageTag;
private String imageDigest;
public ImageIdentifier() {}
public ImageIdentifier(String imageTag, String imageDigest) {
this.imageTag = imageTag;
this.imageDigest = imageDigest;
}
public String getImageTag() { return imageTag; }
public void setImageTag(String imageTag) { this.imageTag = imageTag; }
public String getImageDigest() { return imageDigest; }
public void setImageDigest(String imageDigest) { this.imageDigest = imageDigest; }
}
@@ -0,0 +1,28 @@
package io.github.hectorvent.floci.services.ecr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/**
* Internal storage record caching the push timestamp for a digest, since the
* Docker Registry HTTP API does not expose push timestamps.
*/
@RegisterForReflection
public class ImageMetadata {
private String digest;
private Instant pushedAt;
public ImageMetadata() {}
public ImageMetadata(String digest, Instant pushedAt) {
this.digest = digest;
this.pushedAt = pushedAt;
}
public String getDigest() { return digest; }
public void setDigest(String digest) { this.digest = digest; }
public Instant getPushedAt() { return pushedAt; }
public void setPushedAt(Instant pushedAt) { this.pushedAt = pushedAt; }
}
@@ -0,0 +1,66 @@
package io.github.hectorvent.floci.services.ecr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
/**
* Mutable ECR repository entity for Jackson serialization/deserialization.
*
* @see <a href="https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_Repository.html">AWS ECR Repository</a>
*/
@RegisterForReflection
public class Repository {
private String repositoryArn;
private String registryId;
private String repositoryName;
private String repositoryUri;
private Instant createdAt;
private String imageTagMutability = "MUTABLE";
private boolean scanOnPush;
private String encryptionType = "AES256";
private String kmsKey;
private String lifecyclePolicyText;
private String repositoryPolicyText;
private Map<String, String> tags = new HashMap<>();
public Repository() {}
public String getRepositoryArn() { return repositoryArn; }
public void setRepositoryArn(String repositoryArn) { this.repositoryArn = repositoryArn; }
public String getRegistryId() { return registryId; }
public void setRegistryId(String registryId) { this.registryId = registryId; }
public String getRepositoryName() { return repositoryName; }
public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; }
public String getRepositoryUri() { return repositoryUri; }
public void setRepositoryUri(String repositoryUri) { this.repositoryUri = repositoryUri; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
public String getImageTagMutability() { return imageTagMutability; }
public void setImageTagMutability(String imageTagMutability) { this.imageTagMutability = imageTagMutability; }
public boolean isScanOnPush() { return scanOnPush; }
public void setScanOnPush(boolean scanOnPush) { this.scanOnPush = scanOnPush; }
public String getEncryptionType() { return encryptionType; }
public void setEncryptionType(String encryptionType) { this.encryptionType = encryptionType; }
public String getKmsKey() { return kmsKey; }
public void setKmsKey(String kmsKey) { this.kmsKey = kmsKey; }
public String getLifecyclePolicyText() { return lifecyclePolicyText; }
public void setLifecyclePolicyText(String lifecyclePolicyText) { this.lifecyclePolicyText = lifecyclePolicyText; }
public String getRepositoryPolicyText() { return repositoryPolicyText; }
public void setRepositoryPolicyText(String repositoryPolicyText) { this.repositoryPolicyText = repositoryPolicyText; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags == null ? new HashMap<>() : tags; }
}
@@ -0,0 +1,61 @@
package io.github.hectorvent.floci.services.ecr.registry;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.util.Map;
/**
* Admin endpoint that triggers garbage collection on the backing {@code registry:2}
* container to reclaim disk space after {@code BatchDeleteImage} calls.
*/
@ApplicationScoped
@Path("_floci/ecr/gc")
@Produces(MediaType.APPLICATION_JSON)
public class EcrGcController {
private static final Logger LOG = Logger.getLogger(EcrGcController.class);
private static final int GC_TIMEOUT_SECONDS = 120;
private final EcrRegistryManager registryManager;
@Inject
public EcrGcController(EcrRegistryManager registryManager) {
this.registryManager = registryManager;
}
@POST
public Response runGc() {
if (!registryManager.isStarted()) {
return Response.status(400)
.entity(Map.of(
"status", "error",
"output", "ECR registry is not started",
"durationMs", 0))
.build();
}
try {
EcrRegistryManager.GcResult result = registryManager.runGarbageCollect(GC_TIMEOUT_SECONDS);
return Response.ok(Map.of(
"status", "ok",
"output", result.output(),
"durationMs", result.durationMs()))
.build();
} catch (Exception e) {
LOG.warnv("ECR GC failed: {0}", e.getMessage());
return Response.status(500)
.entity(Map.of(
"status", "error",
"output", e.getMessage() != null ? e.getMessage() : "",
"durationMs", 0))
.build();
}
}
}
@@ -0,0 +1,342 @@
package io.github.hectorvent.floci.services.ecr.registry;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.InspectExecResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Ports;
import com.github.dockerjava.api.model.Volume;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.ServerSocket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Manages the lifecycle of the shared {@code registry:2} container that backs
* Floci's emulated ECR. There is one container per Floci instance, started
* lazily on first use and reused across restarts.
*
* <p>Methods that compute URIs ({@link #getRepositoryUri}, {@link #getProxyEndpoint})
* do not require Docker — they read the configured port and account/region from
* {@link EmulatorConfig}. Only {@link #ensureStarted()} talks to the daemon.
*/
@ApplicationScoped
public class EcrRegistryManager {
private static final Logger LOG = Logger.getLogger(EcrRegistryManager.class);
private static final int CONTAINER_INTERNAL_PORT = 5000;
private final DockerClient dockerClient;
private final EmulatorConfig config;
private final ImageCacheService imageCacheService;
private volatile boolean started;
private volatile boolean reconciled;
private volatile int hostPort;
private volatile String containerId;
private volatile java.util.function.Consumer<List<String>> reconcileHook;
@Inject
public EcrRegistryManager(DockerClient dockerClient,
EmulatorConfig config,
ImageCacheService imageCacheService) {
this.dockerClient = dockerClient;
this.config = config;
this.imageCacheService = imageCacheService;
this.hostPort = config.services().ecr().registryBasePort();
}
/** Returns the docker-pullable repository URI for the given account/region/name. */
public String getRepositoryUri(String accountId, String region, String repoName) {
int port = effectivePort();
String style = config.services().ecr().uriStyle();
if ("path".equalsIgnoreCase(style)) {
return "localhost:" + port + "/" + accountId + "/" + region + "/" + repoName;
}
return accountId + ".dkr.ecr." + region + ".localhost:" + port + "/" + repoName;
}
/** Returns the proxy endpoint a docker daemon should log into for any ECR repo. */
public String getProxyEndpoint() {
String scheme = config.services().ecr().tlsEnabled() ? "https" : "http";
return scheme + "://localhost:" + effectivePort();
}
/** Returns the effective registry port. Stable across calls once {@link #ensureStarted} runs. */
public int effectivePort() {
return hostPort;
}
/** Internal namespace prefix used to isolate cross-account/region repos within the shared registry. */
public String internalRepoName(String accountId, String region, String repoName) {
return accountId + "/" + region + "/" + repoName;
}
/** Returns a {@link RegistryHttpClient} bound to the current registry endpoint. */
public RegistryHttpClient httpClient() {
return new RegistryHttpClient("http://localhost:" + effectivePort());
}
/**
* Registers a callback invoked once on first {@link #ensureStarted()} with the
* list of repository names known to the backing registry. EcrService uses this
* to recreate metadata entries for blobs whose metadata is missing (FR-013).
*/
public void setReconcileHook(java.util.function.Consumer<List<String>> hook) {
this.reconcileHook = hook;
}
/**
* Lazily starts (or reuses) the {@code registry:2} container. Idempotent and
* thread-safe. Throws if Docker is unreachable.
*/
public synchronized void ensureStarted() {
if (started) {
return;
}
String name = config.services().ecr().registryContainerName();
Container existing = findExistingContainer(name);
if (existing != null) {
adoptExisting(existing);
runReconcileOnce();
return;
}
int chosenPort = allocatePort();
ensureDataDir();
String image = config.services().ecr().registryImage();
// Pull the registry image on demand. CI runners and fresh dev machines
// will not have it cached locally; without this we'd see
// "Status 404: No such image: registry:2" from createContainerCmd.
imageCacheService.ensureImageExists(image);
ExposedPort exposed = ExposedPort.tcp(CONTAINER_INTERNAL_PORT);
Ports portBindings = new Ports();
portBindings.bind(exposed, Ports.Binding.bindPort(chosenPort));
String dataPath = Paths.get(config.services().ecr().dataPath(), "registry").toAbsolutePath().toString();
HostConfig hostConfig = HostConfig.newHostConfig()
.withPortBindings(portBindings)
.withBinds(new Bind(dataPath, new Volume("/var/lib/registry")));
config.services().ecr().dockerNetwork()
.or(() -> config.services().dockerNetwork())
.filter(n -> !n.isBlank())
.ifPresent(hostConfig::withNetworkMode);
try {
CreateContainerResponse created = dockerClient.createContainerCmd(image)
.withName(name)
.withEnv(
"REGISTRY_STORAGE_DELETE_ENABLED=true",
"REGISTRY_HTTP_ADDR=0.0.0.0:" + CONTAINER_INTERNAL_PORT)
.withExposedPorts(exposed)
.withHostConfig(hostConfig)
.exec();
this.containerId = created.getId();
dockerClient.startContainerCmd(containerId).exec();
this.hostPort = chosenPort;
this.started = true;
LOG.infov("Started ECR backing registry {0} on host port {1}", name, chosenPort);
} catch (Exception e) {
throw new RuntimeException("Failed to start ECR backing registry container: " + e.getMessage(), e);
}
runReconcileOnce();
}
private void runReconcileOnce() {
if (reconciled || reconcileHook == null) {
return;
}
try {
// Give the registry a moment to be ready on first start
for (int i = 0; i < 10; i++) {
if (httpClient().ping()) break;
try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return; }
}
List<String> repos = httpClient().catalog();
reconcileHook.accept(repos);
reconciled = true;
} catch (Exception e) {
LOG.warnv("ECR reconcile-on-startup failed: {0}", e.getMessage());
}
}
/** Value object returned by {@link #runGarbageCollect}. */
public record GcResult(String output, long durationMs) {}
/**
* Runs {@code registry garbage-collect} inside the running registry container
* to reclaim disk space after image deletions. Synchronized to prevent concurrent
* ECR operations during the GC window.
*
* @param timeoutSeconds max time to wait for the exec to complete
* @return captured stdout+stderr output from the GC run
* @throws IllegalStateException if the registry is not started
* @throws RuntimeException if the exec fails, exits non-zero, or times out
*/
public synchronized GcResult runGarbageCollect(int timeoutSeconds) {
if (!started || containerId == null) {
throw new IllegalStateException("ECR registry is not started");
}
long startMs = System.currentTimeMillis();
StringBuilder output = new StringBuilder();
ExecCreateCmdResponse exec = dockerClient
.execCreateCmd(containerId)
.withCmd("registry", "garbage-collect", "/etc/docker/registry/config.yml")
.withAttachStdout(true)
.withAttachStderr(true)
.exec();
try {
boolean completed = dockerClient.execStartCmd(exec.getId())
.exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
output.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
}
})
.awaitCompletion(timeoutSeconds, TimeUnit.SECONDS);
if (!completed) {
throw new RuntimeException("garbage-collect timed out after " + timeoutSeconds + "s");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("garbage-collect interrupted", e);
}
InspectExecResponse inspect = dockerClient.inspectExecCmd(exec.getId()).exec();
long durationMs = System.currentTimeMillis() - startMs;
Long exitCode = inspect.getExitCodeLong();
if (exitCode == null) {
throw new RuntimeException("garbage-collect did not exit (still running after await)");
}
if (exitCode != 0) {
LOG.warnv("ECR GC exited with code {0}: {1}", exitCode, output);
throw new RuntimeException("garbage-collect exited with code " + exitCode + ": " + output);
}
LOG.infov("ECR GC completed in {0}ms", durationMs);
return new GcResult(output.toString(), durationMs);
}
/** Stops the container if {@code keepRunningOnShutdown=false}. Called from EmulatorLifecycle hooks. */
public void shutdown() {
if (!started || containerId == null) {
return;
}
if (config.services().ecr().keepRunningOnShutdown()) {
LOG.infov("Leaving ECR backing registry container {0} running for next start-up", containerId);
return;
}
try {
dockerClient.stopContainerCmd(containerId).withTimeout(5).exec();
} catch (Exception e) {
LOG.warnv("Error stopping ECR registry container: {0}", e.getMessage());
}
try {
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
} catch (Exception e) {
LOG.warnv("Error removing ECR registry container: {0}", e.getMessage());
}
}
private Container findExistingContainer(String name) {
try {
List<Container> all = dockerClient.listContainersCmd().withShowAll(true).exec();
for (Container c : all) {
String[] names = c.getNames();
if (names == null) continue;
for (String n : names) {
if (n.equals("/" + name) || n.equals(name)) {
return c;
}
}
}
} catch (Exception e) {
LOG.debugv("Could not list containers while searching for {0}: {1}", name, e.getMessage());
}
return null;
}
private void adoptExisting(Container existing) {
this.containerId = existing.getId();
try {
InspectContainerResponse inspect = dockerClient.inspectContainerCmd(containerId).exec();
boolean running = Boolean.TRUE.equals(inspect.getState().getRunning());
if (!running) {
dockerClient.startContainerCmd(containerId).exec();
}
var bindings = inspect.getNetworkSettings().getPorts().getBindings();
var binding = bindings.get(ExposedPort.tcp(CONTAINER_INTERNAL_PORT));
if (binding != null && binding.length > 0) {
this.hostPort = Integer.parseInt(binding[0].getHostPortSpec());
}
this.started = true;
LOG.infov("Adopted existing ECR registry container {0} on host port {1}",
containerId, hostPort);
} catch (NotFoundException nf) {
this.containerId = null;
} catch (Exception e) {
LOG.warnv("Failed to adopt existing ECR registry container: {0}", e.getMessage());
}
}
private int allocatePort() {
int base = config.services().ecr().registryBasePort();
int max = config.services().ecr().registryMaxPort();
for (int p = base; p <= max; p++) {
if (isPortFree(p)) {
return p;
}
}
throw new RuntimeException("No free port available in range "
+ base + "-" + max + " for ECR registry");
}
private boolean isPortFree(int port) {
try (ServerSocket s = new ServerSocket(port)) {
s.setReuseAddress(true);
return true;
} catch (IOException e) {
return false;
}
}
private void ensureDataDir() {
try {
Path dir = Paths.get(config.services().ecr().dataPath(), "registry");
Files.createDirectories(dir);
} catch (IOException e) {
LOG.warnv("Could not create ECR data directory: {0}", e.getMessage());
}
}
// Test seam
boolean isStarted() {
return started;
}
}
@@ -0,0 +1,216 @@
package io.github.hectorvent.floci.services.ecr.registry;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Thin wrapper around the Docker Registry HTTP API v2 (the protocol implemented
* by {@code registry:2}). Used by {@link EcrRegistryManager} to enumerate tags,
* fetch manifests, and delete images on behalf of the ECR control plane.
*/
public class RegistryHttpClient {
private static final Logger LOG = Logger.getLogger(RegistryHttpClient.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private final String baseUrl;
private final HttpClient http;
public RegistryHttpClient(String baseUrl) {
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
this.http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
}
/** Returns true if the registry responds to {@code GET /v2/}. */
public boolean ping() {
try {
HttpResponse<Void> resp = http.send(
HttpRequest.newBuilder(URI.create(baseUrl + "/v2/"))
.timeout(Duration.ofSeconds(5))
.GET()
.build(),
HttpResponse.BodyHandlers.discarding());
return resp.statusCode() < 500;
} catch (Exception e) {
return false;
}
}
/** Lists all repository names known to the backing registry. */
public List<String> catalog() throws IOException, InterruptedException {
HttpResponse<String> resp = http.send(
HttpRequest.newBuilder(URI.create(baseUrl + "/v2/_catalog"))
.timeout(Duration.ofSeconds(10))
.GET()
.build(),
HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() != 200) {
LOG.warnv("Registry catalog returned {0}: {1}", resp.statusCode(), resp.body());
return Collections.emptyList();
}
JsonNode root = MAPPER.readTree(resp.body());
JsonNode repos = root.get("repositories");
if (repos == null || !repos.isArray()) {
return Collections.emptyList();
}
List<String> out = new ArrayList<>();
repos.forEach(n -> out.add(n.asText()));
return out;
}
/** Lists tags for a repository. Returns an empty list if the repo is not yet known to the registry. */
public List<String> listTags(String name) throws IOException, InterruptedException {
HttpResponse<String> resp = http.send(
HttpRequest.newBuilder(URI.create(baseUrl + "/v2/" + name + "/tags/list"))
.timeout(Duration.ofSeconds(10))
.GET()
.build(),
HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() == 404) {
return Collections.emptyList();
}
if (resp.statusCode() != 200) {
LOG.warnv("Registry tags/list returned {0}: {1}", resp.statusCode(), resp.body());
return Collections.emptyList();
}
JsonNode root = MAPPER.readTree(resp.body());
JsonNode tags = root.get("tags");
if (tags == null || tags.isNull() || !tags.isArray()) {
return Collections.emptyList();
}
List<String> out = new ArrayList<>();
tags.forEach(n -> out.add(n.asText()));
return out;
}
/**
* HEAD a manifest by tag or digest, returning the {@code Docker-Content-Digest}
* header value (the canonical manifest digest), or {@code null} if not found.
*/
public String headManifestDigest(String name, String reference, List<String> acceptedMediaTypes)
throws IOException, InterruptedException {
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(baseUrl + "/v2/" + name + "/manifests/" + reference))
.timeout(Duration.ofSeconds(10))
.method("HEAD", HttpRequest.BodyPublishers.noBody());
applyAccept(b, acceptedMediaTypes);
HttpResponse<Void> resp = http.send(b.build(), HttpResponse.BodyHandlers.discarding());
if (resp.statusCode() == 404) {
return null;
}
if (resp.statusCode() >= 400) {
LOG.warnv("Registry HEAD manifest {0}/{1} returned {2}", name, reference, resp.statusCode());
return null;
}
return resp.headers().firstValue("Docker-Content-Digest").orElse(null);
}
/** Result of {@link #getManifest}: digest, body, and content media type. */
public record ManifestResult(String digest, String body, String mediaType) {}
/** GET a manifest by tag or digest, honoring the caller's {@code Accept} list. */
public ManifestResult getManifest(String name, String reference, List<String> acceptedMediaTypes)
throws IOException, InterruptedException {
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(baseUrl + "/v2/" + name + "/manifests/" + reference))
.timeout(Duration.ofSeconds(10))
.GET();
applyAccept(b, acceptedMediaTypes);
HttpResponse<String> resp = http.send(b.build(), HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() == 404) {
return null;
}
if (resp.statusCode() >= 400) {
LOG.warnv("Registry GET manifest {0}/{1} returned {2}: {3}", name, reference, resp.statusCode(), resp.body());
return null;
}
String digest = resp.headers().firstValue("Docker-Content-Digest").orElse(null);
String mediaType = resp.headers().firstValue("Content-Type").orElse(null);
return new ManifestResult(digest, resp.body(), mediaType);
}
/** DELETE a manifest by digest. Returns true on 202/200, false on 404. */
public boolean deleteManifest(String name, String digest) throws IOException, InterruptedException {
HttpResponse<Void> resp = http.send(
HttpRequest.newBuilder(URI.create(baseUrl + "/v2/" + name + "/manifests/" + digest))
.timeout(Duration.ofSeconds(10))
.DELETE()
.build(),
HttpResponse.BodyHandlers.discarding());
if (resp.statusCode() == 404) {
return false;
}
if (resp.statusCode() >= 400) {
LOG.warnv("Registry DELETE manifest {0}/{1} returned {2}", name, digest, resp.statusCode());
return false;
}
return true;
}
/**
* Sums {@code config.size} + each {@code layers[].size} from a manifest body.
* Returns 0 if the body is not a recognised image manifest.
*/
public static long sizeFromManifest(String manifestBody) {
if (manifestBody == null || manifestBody.isBlank()) {
return 0L;
}
try {
JsonNode root = MAPPER.readTree(manifestBody);
long total = root.path("config").path("size").asLong(0L);
JsonNode layers = root.get("layers");
if (layers != null && layers.isArray()) {
for (JsonNode layer : layers) {
total += layer.path("size").asLong(0L);
}
}
return total;
} catch (Exception e) {
return 0L;
}
}
/** Returns the {@code config.mediaType} from a manifest body, or {@code null}. */
public static String artifactMediaTypeFromManifest(String manifestBody) {
if (manifestBody == null || manifestBody.isBlank()) {
return null;
}
try {
JsonNode root = MAPPER.readTree(manifestBody);
String mt = root.path("config").path("mediaType").asText(null);
return (mt == null || mt.isEmpty()) ? null : mt;
} catch (Exception e) {
return null;
}
}
private static void applyAccept(HttpRequest.Builder b, List<String> acceptedMediaTypes) {
if (acceptedMediaTypes == null || acceptedMediaTypes.isEmpty()) {
// Default to the union of OCI and Docker v2 schema 2 manifest types so the
// registry serves whichever format the manifest is stored as.
b.header("Accept", "application/vnd.oci.image.manifest.v1+json,"
+ "application/vnd.oci.image.index.v1+json,"
+ "application/vnd.docker.distribution.manifest.v2+json,"
+ "application/vnd.docker.distribution.manifest.list.v2+json");
return;
}
for (String mt : acceptedMediaTypes) {
b.header("Accept", mt);
}
}
public String baseUrl() {
return baseUrl;
}
}
@@ -83,9 +83,15 @@ public class LambdaController {
ObjectNode root = objectMapper.createObjectNode();
root.set("Configuration", objectMapper.valueToTree(buildFunctionConfiguration(fn)));
ObjectNode code = root.putObject("Code");
code.put("Location", "https://awslambda-" + region + "-tasks.s3." + region
+ ".amazonaws.com/" + fn.getFunctionName());
code.put("RepositoryType", "S3");
if ("Image".equals(fn.getPackageType()) && fn.getImageUri() != null) {
code.put("RepositoryType", "ECR");
code.put("ImageUri", fn.getImageUri());
code.put("ResolvedImageUri", fn.getImageUri());
} else {
code.put("Location", "https://awslambda-" + region + "-tasks.s3." + region
+ ".amazonaws.com/" + fn.getFunctionName());
code.put("RepositoryType", "S3");
}
return Response.ok(root).build();
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.lambda.launcher;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.lambda.model.ContainerState;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
@@ -56,6 +57,11 @@ public class ContainerLauncher {
private final DockerHostResolver dockerHostResolver;
private final EmulatorConfig config;
private final CloudWatchLogsService cloudWatchLogsService;
private final EcrRegistryManager ecrRegistryManager;
/** Matches an AWS-shaped ECR image URI: {@code <account>.dkr.ecr.<region>.amazonaws.com/<repo>[:tag]}. */
private static final java.util.regex.Pattern AWS_ECR_URI =
java.util.regex.Pattern.compile("^([0-9]{12})\\.dkr\\.ecr\\.([a-z0-9-]+)\\.amazonaws\\.com/(.+)$");
@Inject
public ContainerLauncher(DockerClient dockerClient,
@@ -64,7 +70,8 @@ public class ContainerLauncher {
RuntimeApiServerFactory runtimeApiServerFactory,
DockerHostResolver dockerHostResolver,
EmulatorConfig config,
CloudWatchLogsService cloudWatchLogsService) {
CloudWatchLogsService cloudWatchLogsService,
EcrRegistryManager ecrRegistryManager) {
this.dockerClient = dockerClient;
this.imageCacheService = imageCacheService;
this.imageResolver = imageResolver;
@@ -72,6 +79,26 @@ public class ContainerLauncher {
this.dockerHostResolver = dockerHostResolver;
this.config = config;
this.cloudWatchLogsService = cloudWatchLogsService;
this.ecrRegistryManager = ecrRegistryManager;
}
/**
* Rewrites real-AWS-shaped ECR image URIs to point at Floci's loopback registry.
* Stored ImageUri is preserved (so describe-function returns the original);
* the rewrite is only applied immediately before the docker pull.
*/
private String rewriteForEmulatedRegistry(String image) {
if (image == null) return null;
java.util.regex.Matcher m = AWS_ECR_URI.matcher(image);
if (!m.matches()) return image;
String account = m.group(1);
String region = m.group(2);
String repoAndTag = m.group(3);
ecrRegistryManager.ensureStarted();
int port = ecrRegistryManager.effectivePort();
String rewritten = account + ".dkr.ecr." + region + ".localhost:" + port + "/" + repoAndTag;
LOG.infov("Rewriting ECR image URI {0} -> {1}", image, rewritten);
return rewritten;
}
public ContainerHandle launch(LambdaFunction fn) {
@@ -98,6 +125,10 @@ public class ContainerLauncher {
? fn.getImageUri()
: imageResolver.resolve(fn.getRuntime());
// If this is an AWS-shaped ECR URI, rewrite it to Floci's loopback registry
// so docker pull lands on the emulated backing store rather than real AWS.
image = rewriteForEmulatedRegistry(image);
// Ensure image is available locally
imageCacheService.ensureImageExists(image);
@@ -112,7 +143,9 @@ public class ContainerLauncher {
env.add("AWS_LAMBDA_FUNCTION_MEMORY_SIZE=" + fn.getMemorySize());
env.add("AWS_LAMBDA_FUNCTION_TIMEOUT=" + fn.getTimeout());
env.add("AWS_LAMBDA_FUNCTION_VERSION=$LATEST");
env.add("_HANDLER=" + fn.getHandler());
if (fn.getHandler() != null && !fn.getHandler().isBlank()) {
env.add("_HANDLER=" + fn.getHandler());
}
env.add("AWS_DEFAULT_REGION=us-east-1");
env.add("AWS_REGION=us-east-1");
if (fn.getEnvironment() != null) {
@@ -124,6 +157,17 @@ public class ContainerLauncher {
HostConfig hostConfig = HostConfig.newHostConfig()
.withMemory(fn.getMemorySize() * 1024 * 1024L);
// On native Linux Docker, host.docker.internal is NOT auto-injected into
// containers (unlike Docker Desktop on Mac/Windows). Add an extra-host
// mapping that resolves to the host gateway, so the in-container Lambda
// RIC can reach Floci's Runtime API server via the same hostname on every
// platform. Harmless on Docker Desktop (it just duplicates an existing
// entry). The "host-gateway" magic value is translated by Docker to the
// bridge gateway IP at container-create time.
if (dockerHostResolver.isLinuxHost()) {
hostConfig.withExtraHosts("host.docker.internal:host-gateway");
}
// Attach to a specific Docker network if configured
config.services().lambda().dockerNetwork()
.or(() -> config.services().dockerNetwork())
@@ -8,6 +8,7 @@ import org.jboss.logging.Logger;
import java.net.InetAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Detects the hostname that Lambda containers should use to reach the Floci host.
@@ -24,6 +25,7 @@ public class DockerHostResolver {
private static final String LINUX_DOCKER_BRIDGE = "172.17.0.1";
private final EmulatorConfig config;
private final AtomicBoolean ufwHintLogged = new AtomicBoolean(false);
@Inject
public DockerHostResolver(EmulatorConfig config) {
@@ -53,15 +55,30 @@ public class DockerHostResolver {
}
}
// On Docker Desktop (macOS/Windows/Linux Desktop), host.docker.internal works.
// On native Linux Docker, it doesn't exist - fall back to bridge IP.
if (isHostDockerInternalResolvable()) {
LOG.debugv("Using host.docker.internal for container-to-host communication");
return HOST_DOCKER_INTERNAL;
// Floci is running natively on the host. Always return host.docker.internal:
// - On macOS/Windows (Docker Desktop), the alias is auto-injected into every
// container's /etc/hosts and routes through the Docker VM to the host.
// - On native Linux Docker, the alias is NOT auto-injected, so ContainerLauncher
// must add `host.docker.internal:host-gateway` to each Lambda container's
// extra-hosts at create time. ContainerLauncher does that on Linux only.
// Either way, the in-container Lambda RIC can resolve "host.docker.internal" to
// the host gateway and reach Floci's Runtime API server.
LOG.debugv("Floci on host ({0}) — Lambda containers will use host.docker.internal",
System.getProperty("os.name"));
if (isLinuxHost() && ufwHintLogged.compareAndSet(false, true)) {
LOG.info("Lambda containers will reach Floci via host.docker.internal "
+ "(translated to the docker bridge gateway). On Linux hosts running UFW "
+ "with the default 'INPUT DROP' policy, this path is blocked and Lambda "
+ "invocations will time out with Function.TimedOut. If you see that, run: "
+ "'sudo ufw allow in on docker0' (see README \u2192 'Lambda on native Linux Docker').");
}
return HOST_DOCKER_INTERNAL;
}
LOG.infov("host.docker.internal not resolvable (native Linux Docker?) — using bridge IP: {0}", LINUX_DOCKER_BRIDGE);
return LINUX_DOCKER_BRIDGE;
/** True when the Floci JVM is running natively on a Linux host (not on Docker Desktop). */
public boolean isLinuxHost() {
String os = System.getProperty("os.name", "").toLowerCase();
return os.contains("linux") || os.contains("nix") || os.contains("nux");
}
private boolean isRunningInContainer() {
@@ -77,12 +94,4 @@ public class DockerHostResolver {
}
}
private boolean isHostDockerInternalResolvable() {
try {
InetAddress.getByName(HOST_DOCKER_INTERNAL);
return true;
} catch (Exception e) {
return false;
}
}
}