feat(sagemaker): add SageMaker emulation with Docker-backed training (#1949)

Implement the SageMaker control plane over the AWS JSON 1.1 protocol
(X-Amz-Target: SageMaker.*) plus the runtime invocation path:

- Models, endpoint configs, endpoints, training jobs, and tags with
  AWS-shaped validation errors (ValidationException / ResourceInUse)
- CreateTrainingJob runs the training image as a real Docker container
  using the /opt/ml contract: hyperparameters, resourceconfig and
  inputdataconfig under /opt/ml/input/config, S3 channel data under
  /opt/ml/input/data/<channel>, and /opt/ml/model uploaded back to S3
  as model.tar.gz under the configured S3OutputPath
- CreateEndpoint hosts the model image as a long-lived container with
  the serve command, /ping health checks, and ModelDataUrl artifacts
  extracted into /opt/ml/model
- POST /endpoints/{name}/invocations proxies to the container and maps
  model 5xx responses to ModelError (HTTP 424) like SageMaker Runtime
- Training container logs stream to CloudWatch Logs under
  /aws/sagemaker/TrainingJobs
- Storage wired through StorageFactory with memory/persistent modes,
  config in EmulatorConfig and both application.yml files
- Unit, integration, and Docker-gated integration tests plus a boto3
  compatibility test; service and docs registered in the catalog
This commit is contained in:
Marcus Bergo authored and GitHub committed 2026-09-15 22:31:05 -05:00
1 parent e5f9baa12d
commit e2aefa654b
20 files changed
+2110 -1

No files matched your search

@@ -336,6 +336,7 @@ public interface EmulatorConfig {
LakeFormationStorageConfig lakeformation();
EfsStorageConfig efs();
SageMakerStorageConfig sagemaker();
}
interface ApsStorageConfig {
@@ -611,6 +612,7 @@ public interface EmulatorConfig {
@WithDefault("5000")
long flushIntervalMs();
}
interface EfsStorageConfig {
Optional<String> mode();
@@ -618,6 +620,13 @@ public interface EmulatorConfig {
long flushIntervalMs();
}
interface SageMakerStorageConfig {
Optional<String> mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface CodeDeployStorageConfig {
Optional<String> mode();
@@ -727,6 +736,7 @@ public interface EmulatorConfig {
CloudFrontServiceConfig cloudfront();
AppSyncServiceConfig appsync();
BatchServiceConfig batch();
SageMakerServiceConfig sagemaker();
LightsailServiceConfig lightsail();
UiServiceConfig ui();
S3VectorsServiceConfig s3vectors();
@@ -1104,6 +1114,13 @@ public interface EmulatorConfig {
Optional<String> dockerNetwork();
}
interface SageMakerServiceConfig {
@WithDefault("true")
boolean enabled();
Optional<String> dockerNetwork();
}
interface CodeDeployServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -57,6 +57,7 @@ import io.github.hectorvent.floci.services.route53resolver.Route53ResolverJsonHa
import io.github.hectorvent.floci.services.networkfirewall.NetworkFirewallJsonHandler;
import io.github.hectorvent.floci.services.servicecatalog.ServiceCatalogJsonHandler;
import io.github.hectorvent.floci.services.servicequotas.ServiceQuotasJsonHandler;
import io.github.hectorvent.floci.services.sagemaker.SageMakerJsonHandler;
import io.github.hectorvent.floci.services.ssm.Ec2MessagesJsonHandler;
import io.github.hectorvent.floci.services.ssm.SsmJsonHandler;
import jakarta.inject.Inject;
@@ -139,6 +140,7 @@ public class AwsJson11Controller {
private final ServiceQuotasJsonHandler serviceQuotasJsonHandler;
private final MarketplaceEntitlementController marketplaceEntitlementController;
private final MarketplaceMeteringController marketplaceMeteringController;
private final SageMakerJsonHandler sageMakerJsonHandler;
@Inject
public AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -192,7 +194,8 @@ public class AwsJson11Controller {
BudgetsJsonHandler budgetsJsonHandler,
ServiceQuotasJsonHandler serviceQuotasJsonHandler,
MarketplaceEntitlementController marketplaceEntitlementController,
MarketplaceMeteringController marketplaceMeteringController) {
MarketplaceMeteringController marketplaceMeteringController,
SageMakerJsonHandler sageMakerJsonHandler) {
this.objectMapper = objectMapper;
this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
this.catalog = catalog;
@@ -251,6 +254,7 @@ public class AwsJson11Controller {
this.serviceQuotasJsonHandler = serviceQuotasJsonHandler;
this.marketplaceEntitlementController = marketplaceEntitlementController;
this.marketplaceMeteringController = marketplaceMeteringController;
this.sageMakerJsonHandler = sageMakerJsonHandler;
}
@POST
@@ -362,6 +366,7 @@ public class AwsJson11Controller {
}
yield marketplaceMeteringController.handle(action, request, region);
}
case "sagemaker" -> sageMakerJsonHandler.handle(action, request, region);
default -> null;
};
// catalog.matchTarget is protocol-agnostic: a JSON 1.0 target
@@ -60,6 +60,7 @@ import io.github.hectorvent.floci.services.marketplace.MarketplaceCatalogControl
import io.github.hectorvent.floci.services.marketplace.MarketplaceDeploymentController;
import io.github.hectorvent.floci.services.marketplace.MarketplaceDiscoveryController;
import io.github.hectorvent.floci.services.marketplace.MarketplaceReportingController;
import io.github.hectorvent.floci.services.sagemaker.SageMakerRuntimeController;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -402,6 +403,12 @@ public class ResolvedServiceCatalog {
config.storage().services().batch().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("batch"), Set.of(), Set.of(BatchController.class)),
descriptor("sagemaker", "sagemaker", config.services().sagemaker().enabled(), true,
"sagemaker", storageMode(config.storage().services().sagemaker().mode(), config.storage().mode()),
config.storage().services().sagemaker().flushIntervalMs(), null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON, ServiceProtocol.REST_JSON),
Set.of("SageMaker."), Set.of("sagemaker", "runtime.sagemaker"), Set.of(),
Set.of(SageMakerRuntimeController.class)),
descriptor("codedeploy", "codedeploy", config.services().codedeploy().enabled(), true,
"codedeploy", storageMode(config.storage().services().codedeploy().mode(), config.storage().mode()),
config.storage().services().codedeploy().flushIntervalMs(), null, ServiceProtocol.JSON,
@@ -0,0 +1,19 @@
package io.github.hectorvent.floci.services.sagemaker;
record S3Uri(String bucket, String key) {
static S3Uri parse(String uri) {
if (uri == null || !uri.startsWith("s3://")) {
throw new IllegalArgumentException("Expected s3:// URI");
}
String rest = uri.substring(5);
int slash = rest.indexOf('/');
String bucket = slash < 0 ? rest : rest.substring(0, slash);
if (bucket.isBlank()) {
throw new IllegalArgumentException("Expected s3://<bucket>/<key>, got: " + uri);
}
if (slash < 0) {
return new S3Uri(bucket, "");
}
return new S3Uri(bucket, rest.substring(slash + 1));
}
}
@@ -0,0 +1,268 @@
package io.github.hectorvent.floci.services.sagemaker;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.services.sagemaker.model.SageMakerEntities.EndpointResource;
import io.github.hectorvent.floci.services.sagemaker.model.SageMakerEntities.ModelResource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.ConnectException;
import java.net.URI;
import java.net.http.HttpTimeoutException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ApplicationScoped
public class SageMakerEndpointManager implements ContainerTeardown {
private static final Logger LOG = Logger.getLogger(SageMakerEndpointManager.class);
private static final int PORT = 8080;
private static final int DEFAULT_FILE_MODE = 0644;
private static final int PING_LOG_FREQUENCY = 15;
private static final Duration PING_TIMEOUT = Duration.ofSeconds(120);
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final EmulatorConfig config;
private final ContainerDetector containerDetector;
private final S3Service s3Service;
private final ExecutorService executor = Executors.newCachedThreadPool();
private final ConcurrentHashMap<String, String> containers = new ConcurrentHashMap<>();
private final HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
@Inject
public SageMakerEndpointManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
EmulatorConfig config, ContainerDetector containerDetector, S3Service s3Service) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.config = config;
this.containerDetector = containerDetector;
this.s3Service = s3Service;
}
public void startEndpointAsync(EndpointResource endpoint, SageMakerService service) {
executor.submit(() -> startEndpoint(endpoint, service));
}
private void startEndpoint(EndpointResource endpoint, SageMakerService service) {
String containerId = null;
try {
ModelResource model = service.modelForEndpoint(endpoint);
Map<String, Object> c = model.primaryContainer;
String image = string(c.get("Image"));
if (image == null) {
throw new IllegalArgumentException("PrimaryContainer.Image is required");
}
String name = ContainerStorageHelper.dockerName(config, "floci-sagemaker-endpoint-" + endpoint.endpointName);
lifecycleManager.removeIfExists(name);
ContainerBuilder.Builder builder = containerBuilder.newContainer(image)
.withName(name)
.withEnv(environment(endpoint.region, map(c.get("Environment"))))
.withDockerNetwork(config.services().sagemaker().dockerNetwork())
.withHostDockerInternalOnLinux()
.withEmbeddedDns()
.withPortBinding(PORT, 0)
.withLogRotation();
applyEntrypoint(builder, c, "serve");
ContainerSpec spec = builder.build();
containerId = lifecycleManager.create(spec);
String modelDataUrl = string(c.get("ModelDataUrl"));
if (modelDataUrl != null && !modelDataUrl.isBlank()) {
copyModelData(containerId, modelDataUrl);
}
ContainerInfo info = lifecycleManager.startCreated(containerId, spec);
EndpointInfo ep = info.getEndpoint(PORT);
endpoint.containerId = containerId;
endpoint.invokeHost = ep.host();
endpoint.invokePort = ep.port();
containers.put(endpoint.endpointName, containerId);
waitForPing(endpoint.invokeHost, endpoint.invokePort);
endpoint.endpointStatus = "InService";
endpoint.failureReason = null;
finishStart(endpoint, service);
} catch (Exception e) {
LOG.warnv("SageMaker endpoint {0} failed: {1}", endpoint.endpointName, e.getMessage());
if (containerId != null) {
lifecycleManager.stopAndRemove(containerId, null);
}
endpoint.endpointStatus = "Failed";
endpoint.failureReason = e.getMessage();
finishStart(endpoint, service);
}
}
/**
* Publishes a start attempt's outcome unless a delete or a newer update has superseded it
* while Docker was still working: {@link SageMakerService#finalizeEndpointStart} refuses the
* write in that case, and the container this attempt just brought up (if any) is torn down
* instead of being left running as an orphan nothing points to any more.
*/
private void finishStart(EndpointResource endpoint, SageMakerService service) {
if (service.finalizeEndpointStart(endpoint)) {
return;
}
LOG.infov("SageMaker endpoint {0} start superseded by a delete or newer update; discarding result",
endpoint.endpointName);
String containerId = endpoint.containerId != null ? endpoint.containerId : containers.remove(endpoint.endpointName);
if (containerId != null) {
lifecycleManager.stopAndRemove(containerId, null);
}
}
public void stopEndpoint(EndpointResource endpoint) {
String containerId = endpoint.containerId != null ? endpoint.containerId : containers.remove(endpoint.endpointName);
if (containerId != null) {
lifecycleManager.stopAndRemove(containerId, null);
}
}
@Override
public void stopManagedContainers() {
containers.forEach((name, id) -> lifecycleManager.stopAndRemove(id, null));
containers.clear();
executor.shutdownNow();
}
private List<String> environment(String region, Map<String, String> modelEnv) {
List<String> env = new ArrayList<>();
env.add("SAGEMAKER_BIND_TO_PORT=8080");
env.add("SAGEMAKER_REGION=" + region);
env.add("AWS_REGION=" + region);
env.add("AWS_DEFAULT_REGION=" + region);
env.add("AWS_ACCESS_KEY_ID=test");
env.add("AWS_SECRET_ACCESS_KEY=test");
env.add("AWS_SESSION_TOKEN=test");
String endpoint = "http://" + resolveEndpointHostname() + ":" + config.port();
env.add("AWS_ENDPOINT_URL=" + endpoint);
env.add("FLOCI_ENDPOINT=" + endpoint);
modelEnv.forEach((k, v) -> env.add(k + "=" + (v == null ? "" : v)));
return env;
}
private String resolveEndpointHostname() {
return containerDetector.isRunningInContainer() ? config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX) : "host.docker.internal";
}
static void applyEntrypoint(ContainerBuilder.Builder builder, Map<String, Object> container, String defaultCommand) {
Object entrypoint = container.get("ContainerEntrypoint");
Object arguments = container.get("ContainerArguments");
if (entrypoint instanceof List<?> list && !list.isEmpty()) {
builder.withEntrypoint(list.stream().map(String::valueOf).toList());
if (arguments instanceof List<?> args) {
builder.withCmd(args.stream().map(String::valueOf).toList());
}
} else if (arguments instanceof List<?> args && !args.isEmpty()) {
builder.withCmd(args.stream().map(String::valueOf).toList());
} else {
builder.withCmd(List.of(defaultCommand));
}
}
private void copyModelData(String containerId, String s3Uri) throws Exception {
S3Uri uri = S3Uri.parse(s3Uri);
S3Object object = s3Service.getObject(uri.bucket(), uri.key());
byte[] tarData = tarModelData(object.getData(), uri.key());
lifecycleManager.getDockerClient().copyArchiveToContainerCmd(containerId)
.withRemotePath("/")
.withTarInputStream(new ByteArrayInputStream(tarData))
.exec();
}
private byte[] tarModelData(byte[] data, String key) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(out)) {
if (key.endsWith(".tar.gz") || key.endsWith(".tgz")) {
try (TarArchiveInputStream in = new TarArchiveInputStream(new GzipCompressorInputStream(new ByteArrayInputStream(data)))) {
TarArchiveEntry e;
while ((e = in.getNextEntry()) != null) {
if (!in.canReadEntryData(e) || e.isDirectory()) continue;
String entryName = e.getName();
Path normalized = Path.of(entryName).normalize();
if (normalized.isAbsolute() || normalized.startsWith("..")) continue;
addFile(tar, "opt/ml/model/" + normalized.toString(), in.readAllBytes());
}
}
} else {
addFile(tar, "opt/ml/model/" + key.substring(key.lastIndexOf('/') + 1), data);
}
}
return out.toByteArray();
}
static void addFile(TarArchiveOutputStream tar, String path, byte[] data) throws Exception {
TarArchiveEntry entry = new TarArchiveEntry(path);
entry.setSize(data.length);
entry.setMode(DEFAULT_FILE_MODE);
tar.putArchiveEntry(entry);
tar.write(data);
tar.closeArchiveEntry();
}
private void waitForPing(String host, int port) throws Exception {
long deadline = System.currentTimeMillis() + PING_TIMEOUT.toMillis();
URI uri = URI.create("http://" + host + ":" + port + "/ping");
int failures = 0;
while (System.currentTimeMillis() < deadline) {
try {
HttpRequest req = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(2)).GET().build();
if (httpClient.send(req, HttpResponse.BodyHandlers.discarding()).statusCode() == 200) {
return;
}
failures++;
} catch (ConnectException | HttpTimeoutException e) {
failures++;
if (failures % PING_LOG_FREQUENCY == 0) {
LOG.warnv("Still waiting for SageMaker endpoint ping after {0} failures: {1}", failures, e.getMessage());
} else {
LOG.debugv("Waiting for SageMaker endpoint ping: {0}", e.getMessage());
}
} catch (Exception e) {
failures++;
LOG.warnv("Waiting for SageMaker endpoint ping failed: {0}", e.getMessage());
}
Thread.sleep(1000);
}
throw new IllegalStateException("Container did not pass /ping health check");
}
@SuppressWarnings("unchecked")
static Map<String, String> map(Object value) {
if (value instanceof Map<?, ?> in) {
LinkedHashMap<String, String> out = new LinkedHashMap<>();
in.forEach((k, v) -> out.put(String.valueOf(k), v == null ? "" : String.valueOf(v)));
return out;
}
return Map.of();
}
static String string(Object value) {
return value == null ? null : String.valueOf(value);
}
}
@@ -0,0 +1,43 @@
package io.github.hectorvent.floci.services.sagemaker;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
@ApplicationScoped
public class SageMakerJsonHandler {
private final SageMakerService service;
@Inject
public SageMakerJsonHandler(SageMakerService service) {
this.service = service;
}
public Response handle(String action, JsonNode request, String region) {
Object entity = switch (action) {
case "CreateModel" -> service.createModel(request, region);
case "DescribeModel" -> service.describeModel(request, region);
case "DeleteModel" -> service.deleteModel(request, region);
case "ListModels" -> service.listModels(request, region);
case "CreateEndpointConfig" -> service.createEndpointConfig(request, region);
case "DescribeEndpointConfig" -> service.describeEndpointConfig(request, region);
case "DeleteEndpointConfig" -> service.deleteEndpointConfig(request, region);
case "ListEndpointConfigs" -> service.listEndpointConfigs(request, region);
case "CreateEndpoint" -> service.createEndpoint(request, region);
case "DescribeEndpoint" -> service.describeEndpoint(request, region);
case "DeleteEndpoint" -> service.deleteEndpoint(request, region);
case "ListEndpoints" -> service.listEndpoints(request, region);
case "UpdateEndpoint" -> service.updateEndpoint(request, region);
case "CreateTrainingJob" -> service.createTrainingJob(request, region);
case "DescribeTrainingJob" -> service.describeTrainingJob(request, region);
case "ListTrainingJobs" -> service.listTrainingJobs(request, region);
case "StopTrainingJob" -> service.stopTrainingJob(request, region);
case "AddTags" -> service.addTags(request);
case "ListTags" -> service.listTags(request);
case "DeleteTags" -> service.deleteTags(request);
default -> throw SageMakerService.validation("Action " + action + " is not supported");
};
return Response.ok(entity).build();
}
}
@@ -0,0 +1,93 @@
package io.github.hectorvent.floci.services.sagemaker;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.sagemaker.model.SageMakerEntities.EndpointResource;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
@Path("/endpoints")
public class SageMakerRuntimeController {
private static final Logger LOG = Logger.getLogger(SageMakerRuntimeController.class);
private final SageMakerService service;
private final RegionResolver regionResolver;
private final HttpClient httpClient;
@Inject
public SageMakerRuntimeController(SageMakerService service, RegionResolver regionResolver) {
this.service = service;
this.regionResolver = regionResolver;
this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
}
@POST
@Path("/{endpointName}/invocations")
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.WILDCARD)
public Response invoke(@PathParam("endpointName") String endpointName,
@HeaderParam("Content-Type") String contentType,
@HeaderParam("Accept") String accept,
@Context HttpHeaders headers,
byte[] body) {
String region = regionResolver.resolveRegion(headers);
EndpointResource ep = service.endpoint(region, endpointName).orElse(null);
if (ep == null) {
return validation("Endpoint " + endpointName + " of account " + regionResolver.getAccountId() + " not found.");
}
if (!"InService".equals(ep.endpointStatus) || ep.invokeHost == null) {
return validation("Endpoint " + endpointName + " is not InService.");
}
try {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create("http://" + ep.invokeHost + ":" + ep.invokePort + "/invocations"))
.timeout(Duration.ofSeconds(60))
.POST(HttpRequest.BodyPublishers.ofByteArray(body == null ? new byte[0] : body));
if (contentType != null) {
builder.header("Content-Type", contentType);
}
if (accept != null) {
builder.header("Accept", accept);
}
HttpResponse<byte[]> response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray());
// SageMaker Runtime maps model-container 5xx responses to ModelError (HTTP 424).
if (response.statusCode() >= 500) {
String originalMessage = new String(response.body(), StandardCharsets.UTF_8);
return Response.status(424).type(MediaType.APPLICATION_JSON).entity(Map.of(
"__type", "ModelError",
"Message", "Received server error (" + response.statusCode() + ") from primary with message \"" + originalMessage + "\"",
"OriginalStatusCode", response.statusCode(),
"OriginalMessage", originalMessage
)).build();
}
Response.ResponseBuilder out = Response.status(response.statusCode()).entity(response.body());
response.headers().firstValue("Content-Type").ifPresent(out::type);
return out.build();
} catch (Exception e) {
LOG.warnv("SageMaker endpoint invocation failed for {0}: {1}", endpointName, e.getMessage());
return Response.status(424).type(MediaType.APPLICATION_JSON)
.entity(Map.of("__type", "ModelError", "message", e.getMessage())).build();
}
}
private Response validation(String message) {
return Response.status(400).type(MediaType.APPLICATION_JSON)
.entity(Map.of("__type", "ValidationError", "message", message)).build();
}
}
@@ -0,0 +1,631 @@
package io.github.hectorvent.floci.services.sagemaker;
import com.fasterxml.jackson.core.type.TypeReference;
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.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.sagemaker.model.SageMakerEntities.EndpointConfigResource;
import io.github.hectorvent.floci.services.sagemaker.model.SageMakerEntities.EndpointResource;
import io.github.hectorvent.floci.services.sagemaker.model.SageMakerEntities.ModelResource;
import io.github.hectorvent.floci.services.sagemaker.model.SageMakerEntities.TrainingJobResource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Function;
@ApplicationScoped
public class SageMakerService {
static final int DEFAULT_LIMIT = 100;
static final int MAX_RESULTS_CEILING = 100;
private static final ObjectMapper STATIC_MAPPER = new ObjectMapper();
private final StorageBackend<String, ModelResource> modelStore;
private final StorageBackend<String, EndpointConfigResource> endpointConfigStore;
private final StorageBackend<String, EndpointResource> endpointStore;
private final StorageBackend<String, TrainingJobResource> trainingJobStore;
private final RegionResolver regionResolver;
private final ObjectMapper mapper;
private final SageMakerEndpointManager endpointManager;
private final SageMakerTrainingRunner trainingRunner;
private final Clock clock;
@Inject
public SageMakerService(StorageFactory storageFactory, RegionResolver regionResolver, ObjectMapper mapper,
SageMakerEndpointManager endpointManager, SageMakerTrainingRunner trainingRunner) {
this(storageFactory.create("sagemaker", "sagemaker-models.json", new TypeReference<Map<String, ModelResource>>() {}),
storageFactory.create("sagemaker", "sagemaker-endpoint-configs.json", new TypeReference<Map<String, EndpointConfigResource>>() {}),
storageFactory.create("sagemaker", "sagemaker-endpoints.json", new TypeReference<Map<String, EndpointResource>>() {}),
storageFactory.create("sagemaker", "sagemaker-training-jobs.json", new TypeReference<Map<String, TrainingJobResource>>() {}),
regionResolver, mapper, endpointManager, trainingRunner, Clock.systemUTC());
}
SageMakerService(StorageBackend<String, ModelResource> modelStore,
StorageBackend<String, EndpointConfigResource> endpointConfigStore,
StorageBackend<String, EndpointResource> endpointStore,
StorageBackend<String, TrainingJobResource> trainingJobStore,
RegionResolver regionResolver,
ObjectMapper mapper,
SageMakerEndpointManager endpointManager,
SageMakerTrainingRunner trainingRunner) {
this(modelStore, endpointConfigStore, endpointStore, trainingJobStore, regionResolver, mapper, endpointManager,
trainingRunner, Clock.systemUTC());
}
SageMakerService(StorageBackend<String, ModelResource> modelStore,
StorageBackend<String, EndpointConfigResource> endpointConfigStore,
StorageBackend<String, EndpointResource> endpointStore,
StorageBackend<String, TrainingJobResource> trainingJobStore,
RegionResolver regionResolver,
ObjectMapper mapper,
SageMakerEndpointManager endpointManager,
SageMakerTrainingRunner trainingRunner,
Clock clock) {
this.modelStore = modelStore;
this.endpointConfigStore = endpointConfigStore;
this.endpointStore = endpointStore;
this.trainingJobStore = trainingJobStore;
this.regionResolver = regionResolver;
this.mapper = mapper;
this.endpointManager = endpointManager;
this.trainingRunner = trainingRunner;
this.clock = clock;
}
public synchronized ObjectNode createModel(JsonNode request, String region) {
String name = required(request, "ModelName");
if (model(region, name).isPresent()) {
throw new AwsException("ValidationException", "Cannot create already existing model \"" + name + "\".", 400);
}
JsonNode primary = request.path("PrimaryContainer");
JsonNode containers = request.path("Containers");
boolean hasContainers = containers.isArray() && !containers.isEmpty() && containers.get(0).isObject();
if (!primary.isObject() && !hasContainers) {
throw validation("PrimaryContainer or Containers is required");
}
ModelResource model = new ModelResource();
model.modelName = name;
model.modelArn = arn(region, "model/" + name);
model.executionRoleArn = text(request, "ExecutionRoleArn");
model.creationTime = nowMillis();
model.region = region;
model.accountId = regionResolver.getAccountId();
model.primaryContainer = primary.isObject() ? map(primary) : map(containers.get(0));
model.containers = listMap(containers);
model.tags = tagsFromList(request.path("Tags"));
modelStore.put(regionKey(region, name), model);
ObjectNode out = mapper.createObjectNode();
out.put("ModelArn", model.modelArn);
return out;
}
public ObjectNode describeModel(JsonNode request, String region) {
String name = required(request, "ModelName");
ModelResource m = model(region, name).orElseThrow(() -> validation("Could not find model \"" + name + "\"."));
ObjectNode out = mapper.createObjectNode();
out.put("ModelName", m.modelName);
out.put("ModelArn", m.modelArn);
out.set("PrimaryContainer", mapper.valueToTree(m.primaryContainer));
if (!m.containers.isEmpty()) {
out.set("Containers", mapper.valueToTree(m.containers));
}
if (m.executionRoleArn != null) {
out.put("ExecutionRoleArn", m.executionRoleArn);
}
out.put("CreationTime", epoch(m.creationTime));
return out;
}
public synchronized ObjectNode deleteModel(JsonNode request, String region) {
String name = required(request, "ModelName");
model(region, name).orElseThrow(() -> validation("Could not find model \"" + name + "\"."));
modelStore.delete(regionKey(region, name));
return mapper.createObjectNode();
}
public ObjectNode listModels(JsonNode request, String region) {
List<ModelResource> models = modelStore.scan(k -> k.startsWith(region + "::")).stream()
.sorted(Comparator.comparing(m -> m.modelName)).toList();
String nameContains = text(request, "NameContains");
if (nameContains != null && !nameContains.isBlank()) {
models = models.stream().filter(m -> m.modelName.contains(nameContains)).toList();
}
return paginate(models, request, m -> m.modelName, (m, n) -> {
n.put("ModelName", m.modelName);
n.put("ModelArn", m.modelArn);
n.put("CreationTime", epoch(m.creationTime));
}, "Models");
}
public synchronized ObjectNode createEndpointConfig(JsonNode request, String region) {
String name = required(request, "EndpointConfigName");
if (endpointConfig(region, name).isPresent()) {
throw new AwsException("ValidationException", "Cannot create already existing endpoint configuration \"" + name + "\".", 400);
}
List<Map<String, Object>> variants = listMap(request.path("ProductionVariants"));
if (variants.isEmpty()) {
throw validation("ProductionVariants is required");
}
for (Map<String, Object> v : variants) {
String modelName = SageMakerEndpointManager.string(v.get("ModelName"));
if (modelName == null || modelName.isBlank()) {
throw validation("ProductionVariants.ModelName is required");
}
if (model(region, modelName).isEmpty()) {
throw validation("Could not find model \"" + modelName + "\".");
}
}
EndpointConfigResource cfg = new EndpointConfigResource();
cfg.endpointConfigName = name;
cfg.endpointConfigArn = arn(region, "endpoint-config/" + name);
cfg.productionVariants = variants;
cfg.creationTime = nowMillis();
cfg.region = region;
cfg.accountId = regionResolver.getAccountId();
cfg.tags = tagsFromList(request.path("Tags"));
endpointConfigStore.put(regionKey(region, name), cfg);
ObjectNode out = mapper.createObjectNode();
out.put("EndpointConfigArn", cfg.endpointConfigArn);
return out;
}
public ObjectNode describeEndpointConfig(JsonNode request, String region) {
String name = required(request, "EndpointConfigName");
EndpointConfigResource cfg = endpointConfig(region, name)
.orElseThrow(() -> validation("Could not find endpoint configuration \"" + name + "\"."));
ObjectNode out = mapper.createObjectNode();
out.put("EndpointConfigName", cfg.endpointConfigName);
out.put("EndpointConfigArn", cfg.endpointConfigArn);
out.set("ProductionVariants", mapper.valueToTree(cfg.productionVariants));
out.put("CreationTime", epoch(cfg.creationTime));
return out;
}
public synchronized ObjectNode deleteEndpointConfig(JsonNode request, String region) {
String name = required(request, "EndpointConfigName");
endpointConfig(region, name).orElseThrow(() -> validation("Could not find endpoint configuration \"" + name + "\"."));
endpointConfigStore.delete(regionKey(region, name));
return mapper.createObjectNode();
}
public ObjectNode listEndpointConfigs(JsonNode request, String region) {
List<EndpointConfigResource> configs = endpointConfigStore.scan(k -> k.startsWith(region + "::")).stream()
.sorted(Comparator.comparing(c -> c.endpointConfigName)).toList();
return paginate(configs, request, c -> c.endpointConfigName, (c, n) -> {
n.put("EndpointConfigName", c.endpointConfigName);
n.put("EndpointConfigArn", c.endpointConfigArn);
n.put("CreationTime", epoch(c.creationTime));
}, "EndpointConfigs");
}
public synchronized ObjectNode createEndpoint(JsonNode request, String region) {
String name = required(request, "EndpointName");
if (endpoint(region, name).isPresent()) {
throw new AwsException("ValidationException", "Cannot create already existing endpoint \"" + name + "\".", 400);
}
String cfgName = required(request, "EndpointConfigName");
endpointConfig(region, cfgName).orElseThrow(() -> validation("Could not find endpoint configuration \"" + cfgName + "\"."));
EndpointResource ep = new EndpointResource();
ep.endpointName = name;
ep.endpointArn = arn(region, "endpoint/" + name);
ep.endpointConfigName = cfgName;
ep.endpointStatus = "Creating";
ep.creationTime = nowMillis();
ep.lastModifiedTime = ep.creationTime;
ep.region = region;
ep.accountId = regionResolver.getAccountId();
ep.tags = tagsFromList(request.path("Tags"));
ep.generation = 1;
endpointStore.put(regionKey(region, name), ep);
endpointManager.startEndpointAsync(ep, this);
ObjectNode out = mapper.createObjectNode();
out.put("EndpointArn", ep.endpointArn);
return out;
}
public synchronized ObjectNode updateEndpoint(JsonNode request, String region) {
String name = required(request, "EndpointName");
EndpointResource ep = endpoint(region, name).orElseThrow(() -> validation("Could not find endpoint \"" + name + "\"."));
String cfgName = required(request, "EndpointConfigName");
endpointConfig(region, cfgName).orElseThrow(() -> validation("Could not find endpoint configuration \"" + cfgName + "\"."));
if (ep.containerId != null) {
endpointManager.stopEndpoint(ep);
}
ep.endpointConfigName = cfgName;
ep.endpointStatus = "Creating";
ep.failureReason = null;
ep.containerId = null;
ep.lastModifiedTime = nowMillis();
ep.generation++;
endpointStore.put(regionKey(region, name), ep);
endpointManager.startEndpointAsync(ep, this);
ObjectNode out = mapper.createObjectNode();
out.put("EndpointArn", ep.endpointArn);
return out;
}
public ObjectNode describeEndpoint(JsonNode request, String region) {
String name = required(request, "EndpointName");
EndpointResource ep = endpoint(region, name).orElseThrow(() -> validation("Could not find endpoint \"" + name + "\"."));
ObjectNode out = mapper.createObjectNode();
out.put("EndpointName", ep.endpointName);
out.put("EndpointArn", ep.endpointArn);
out.put("EndpointConfigName", ep.endpointConfigName);
out.put("EndpointStatus", ep.endpointStatus);
if (ep.failureReason != null) {
out.put("FailureReason", ep.failureReason);
}
out.put("CreationTime", epoch(ep.creationTime));
out.put("LastModifiedTime", epoch(ep.lastModifiedTime));
return out;
}
public synchronized ObjectNode deleteEndpoint(JsonNode request, String region) {
String name = required(request, "EndpointName");
EndpointResource ep = endpoint(region, name).orElseThrow(() -> validation("Could not find endpoint \"" + name + "\"."));
ep.endpointStatus = "Deleting";
// Bump the generation before removing the record: a start worker still in flight for
// this endpoint checks the generation against what is (no longer) in the store and will
// no-op instead of resurrecting the record it raced with this delete.
ep.generation++;
endpointStore.put(regionKey(region, name), ep);
endpointManager.stopEndpoint(ep);
endpointStore.delete(regionKey(region, name));
return mapper.createObjectNode();
}
public ObjectNode listEndpoints(JsonNode request, String region) {
List<EndpointResource> endpoints = endpointStore.scan(k -> k.startsWith(region + "::")).stream()
.sorted(Comparator.comparing(e -> e.endpointName)).toList();
return paginate(endpoints, request, e -> e.endpointName, (e, n) -> {
n.put("EndpointName", e.endpointName);
n.put("EndpointArn", e.endpointArn);
n.put("EndpointStatus", e.endpointStatus);
n.put("CreationTime", epoch(e.creationTime));
n.put("LastModifiedTime", epoch(e.lastModifiedTime));
}, "Endpoints");
}
public synchronized ObjectNode createTrainingJob(JsonNode request, String region) {
String name = required(request, "TrainingJobName");
if (trainingJob(region, name).isPresent()) {
throw new AwsException("ResourceInUse", "Training job already exists: " + name, 400);
}
if (!request.path("AlgorithmSpecification").isObject() || text(request.path("AlgorithmSpecification"), "TrainingImage") == null) {
throw validation("AlgorithmSpecification.TrainingImage is required");
}
if (!request.path("OutputDataConfig").isObject() || text(request.path("OutputDataConfig"), "S3OutputPath") == null) {
throw validation("OutputDataConfig.S3OutputPath is required");
}
validateS3Uri(text(request.path("OutputDataConfig"), "S3OutputPath"), "OutputDataConfig.S3OutputPath");
for (JsonNode channel : request.path("InputDataConfig")) {
JsonNode s3DataSource = channel.path("DataSource").path("S3DataSource");
if (s3DataSource.isObject()) {
validateS3Uri(text(s3DataSource, "S3Uri"), "InputDataConfig[].DataSource.S3DataSource.S3Uri");
}
}
TrainingJobResource job = new TrainingJobResource();
job.trainingJobName = name;
job.trainingJobArn = arn(region, "training-job/" + name);
job.trainingJobStatus = "InProgress";
job.secondaryStatus = "Starting";
job.creationTime = nowMillis();
job.region = region;
job.accountId = regionResolver.getAccountId();
job.algorithmSpecification = map(request.path("AlgorithmSpecification"));
job.inputDataConfig = listMap(request.path("InputDataConfig"));
job.outputDataConfig = map(request.path("OutputDataConfig"));
job.resourceConfig = map(request.path("ResourceConfig"));
job.stoppingCondition = map(request.path("StoppingCondition"));
job.hyperParameters = stringMap(request.path("HyperParameters"));
job.tags = tagsFromList(request.path("Tags"));
trainingJobStore.put(regionKey(region, name), job);
trainingRunner.runAsync(job, this);
ObjectNode out = mapper.createObjectNode();
out.put("TrainingJobArn", job.trainingJobArn);
return out;
}
public ObjectNode describeTrainingJob(JsonNode request, String region) {
String name = required(request, "TrainingJobName");
TrainingJobResource job = trainingJob(region, name).orElseThrow(() -> validation("Could not find training job \"" + name + "\"."));
ObjectNode out = mapper.valueToTree(Map.of(
"TrainingJobName", job.trainingJobName,
"TrainingJobArn", job.trainingJobArn,
"TrainingJobStatus", job.trainingJobStatus,
"SecondaryStatus", job.secondaryStatus == null ? "" : job.secondaryStatus,
"AlgorithmSpecification", job.algorithmSpecification,
"InputDataConfig", job.inputDataConfig,
"OutputDataConfig", job.outputDataConfig,
"ResourceConfig", job.resourceConfig,
"StoppingCondition", job.stoppingCondition,
"CreationTime", epoch(job.creationTime)
));
if (job.trainingStartTime > 0) {
out.put("TrainingStartTime", epoch(job.trainingStartTime));
}
if (job.trainingEndTime > 0) {
out.put("TrainingEndTime", epoch(job.trainingEndTime));
}
if (job.failureReason != null) {
out.put("FailureReason", job.failureReason);
}
if (job.modelArtifactsS3ModelArtifacts != null) {
ObjectNode ma = mapper.createObjectNode();
ma.put("S3ModelArtifacts", job.modelArtifactsS3ModelArtifacts);
out.set("ModelArtifacts", ma);
}
return out;
}
public ObjectNode listTrainingJobs(JsonNode request, String region) {
List<TrainingJobResource> jobs = trainingJobStore.scan(k -> k.startsWith(region + "::")).stream()
.sorted(Comparator.comparing(j -> j.trainingJobName)).toList();
String nameContains = text(request, "NameContains");
if (nameContains != null && !nameContains.isBlank()) {
jobs = jobs.stream().filter(j -> j.trainingJobName.contains(nameContains)).toList();
}
String statusEquals = text(request, "StatusEquals");
if (statusEquals != null && !statusEquals.isBlank()) {
jobs = jobs.stream().filter(j -> statusEquals.equals(j.trainingJobStatus)).toList();
}
return paginate(jobs, request, j -> j.trainingJobName, (j, n) -> {
n.put("TrainingJobName", j.trainingJobName);
n.put("TrainingJobArn", j.trainingJobArn);
n.put("TrainingJobStatus", j.trainingJobStatus);
n.put("CreationTime", epoch(j.creationTime));
}, "TrainingJobSummaries");
}
public synchronized ObjectNode stopTrainingJob(JsonNode request, String region) {
String name = required(request, "TrainingJobName");
TrainingJobResource job = trainingJob(region, name).orElseThrow(() -> validation("Could not find training job \"" + name + "\"."));
// AWS only transitions InProgress/Stopping jobs; a job already in a terminal state is
// left as-is rather than relabeled "Stopped" out from under its real outcome.
if ("InProgress".equals(job.trainingJobStatus) || "Stopping".equals(job.trainingJobStatus)) {
trainingRunner.stop(job);
job.trainingJobStatus = "Stopped";
job.secondaryStatus = "Stopped";
job.trainingEndTime = nowMillis();
trainingJobStore.put(regionKey(region, name), job);
}
return mapper.createObjectNode();
}
public synchronized ObjectNode addTags(JsonNode request) {
String arn = required(request, "ResourceArn");
Map<String, String> tags = tagsFromList(request.path("Tags"));
resourceTags(arn).putAll(tags);
persistByArn(arn);
ObjectNode out = mapper.createObjectNode();
out.set("Tags", tagsArray(resourceTags(arn)));
return out;
}
public ObjectNode listTags(JsonNode request) {
String arn = required(request, "ResourceArn");
ObjectNode out = mapper.createObjectNode();
out.set("Tags", tagsArray(resourceTags(arn)));
return out;
}
public synchronized ObjectNode deleteTags(JsonNode request) {
String arn = required(request, "ResourceArn");
Map<String, String> tags = resourceTags(arn);
request.path("TagKeys").forEach(k -> tags.remove(k.asText()));
persistByArn(arn);
return mapper.createObjectNode();
}
Optional<ModelResource> model(String region, String name) {
return modelStore.get(regionKey(region, name));
}
Optional<EndpointConfigResource> endpointConfig(String region, String name) {
return endpointConfigStore.get(regionKey(region, name));
}
public Optional<EndpointResource> endpoint(String region, String name) {
return endpointStore.get(regionKey(region, name));
}
Optional<TrainingJobResource> trainingJob(String region, String name) {
return trainingJobStore.get(regionKey(region, name));
}
public ModelResource modelForEndpoint(EndpointResource ep) {
EndpointConfigResource cfg = endpointConfig(ep.region, ep.endpointConfigName)
.orElseThrow(() -> validation("Could not find endpoint configuration \"" + ep.endpointConfigName + "\"."));
String modelName = String.valueOf(cfg.productionVariants.get(0).get("ModelName"));
return model(ep.region, modelName).orElseThrow(() -> validation("Could not find model \"" + modelName + "\"."));
}
/**
* Persists the result of an endpoint start (success or failure) unless a delete or a
* newer start has superseded it since {@code ep} was handed to {@link SageMakerEndpointManager}.
* Returns {@code false} when the caller should tear down whatever it just started instead
* of publishing it, because the endpoint it belongs to is gone or has moved on.
*/
synchronized boolean finalizeEndpointStart(EndpointResource ep) {
EndpointResource current = endpointStore.get(regionKey(ep.region, ep.endpointName)).orElse(null);
if (current == null || current.generation != ep.generation) {
return false;
}
ep.lastModifiedTime = nowMillis();
endpointStore.put(regionKey(ep.region, ep.endpointName), ep);
return true;
}
public synchronized void updateTrainingJob(TrainingJobResource job) {
trainingJobStore.put(regionKey(job.region, job.trainingJobName), job);
}
private Map<String, String> resourceTags(String arn) {
String region = arnRegion(arn);
String name = arn.substring(arn.lastIndexOf('/') + 1);
if (arn.contains(":model/")) return model(region, name).orElseThrow(() -> validation("Could not find model \"" + name + "\".")).tags;
if (arn.contains(":endpoint-config/")) return endpointConfig(region, name).orElseThrow(() -> validation("Could not find endpoint configuration \"" + name + "\".")).tags;
if (arn.contains(":endpoint/")) return endpoint(region, name).orElseThrow(() -> validation("Could not find endpoint \"" + name + "\".")).tags;
if (arn.contains(":training-job/")) return trainingJob(region, name).orElseThrow(() -> validation("Could not find training job \"" + name + "\".")).tags;
throw validation("ResourceArn is invalid");
}
private void persistByArn(String arn) {
String region = arnRegion(arn);
String name = arn.substring(arn.lastIndexOf('/') + 1);
if (arn.contains(":model/")) model(region, name).ifPresent(v -> modelStore.put(regionKey(region, name), v));
else if (arn.contains(":endpoint-config/")) endpointConfig(region, name).ifPresent(v -> endpointConfigStore.put(regionKey(region, name), v));
else if (arn.contains(":endpoint/")) endpoint(region, name).ifPresent(v -> endpointStore.put(regionKey(region, name), v));
else if (arn.contains(":training-job/")) trainingJob(region, name).ifPresent(v -> trainingJobStore.put(regionKey(region, name), v));
}
/** ARN shape: {@code arn:aws:sagemaker:<region>:<account>:<type>/<name>}. */
private static String arnRegion(String arn) {
String[] parts = arn.split(":", 6);
if (parts.length < 4 || parts[3].isBlank()) {
throw validation("ResourceArn is invalid");
}
return parts[3];
}
private static String regionKey(String region, String name) {
return region + "::" + name;
}
private String arn(String region, String resource) {
return "arn:aws:sagemaker:" + region + ":" + regionResolver.getAccountId() + ":" + resource;
}
private long nowMillis() {
return clock.millis();
}
static double epoch(long millis) {
return millis / 1000.0;
}
static AwsException validation(String message) {
return new AwsException("ValidationException", message, 400);
}
static void validateS3Uri(String uri, String field) {
try {
S3Uri.parse(uri);
} catch (IllegalArgumentException e) {
throw validation(field + ": " + e.getMessage());
}
}
static String required(JsonNode node, String field) {
String value = text(node, field);
if (value == null || value.isBlank()) {
throw validation(field + " is required");
}
return value;
}
static String text(JsonNode node, String field) {
JsonNode v = node.path(field);
return v.isMissingNode() || v.isNull() ? null : v.asText();
}
static Map<String, Object> map(JsonNode node) {
if (!node.isObject()) {
return new LinkedHashMap<>();
}
return STATIC_MAPPER.convertValue(node, new TypeReference<LinkedHashMap<String, Object>>() {});
}
static Map<String, String> stringMap(JsonNode node) {
Map<String, String> out = new LinkedHashMap<>();
if (node.isObject()) {
node.fields().forEachRemaining(e -> out.put(e.getKey(), e.getValue().asText()));
}
return out;
}
static List<Map<String, Object>> listMap(JsonNode node) {
List<Map<String, Object>> out = new ArrayList<>();
if (node.isArray()) {
node.forEach(n -> out.add(map(n)));
}
return out;
}
static Map<String, String> tagsFromList(JsonNode node) {
Map<String, String> out = new LinkedHashMap<>();
if (node.isArray()) {
node.forEach(t -> {
String key = text(t, "Key");
if (key != null && !key.isBlank()) {
out.put(key, text(t, "Value"));
}
});
}
return out;
}
private ArrayNode tagsArray(Map<String, String> tags) {
ArrayNode arr = mapper.createArrayNode();
tags.forEach((k, v) -> {
ObjectNode n = mapper.createObjectNode();
n.put("Key", k);
n.put("Value", v);
arr.add(n);
});
return arr;
}
/**
* Applies AWS's {@code MaxResults}/{@code NextToken} contract to an already-filtered,
* name-sorted list: {@code MaxResults} (1-100, default {@value #DEFAULT_LIMIT}) caps the
* page, and an opaque {@code NextToken} (the last name returned) resumes strictly after it,
* matching the sort the caller applied.
*/
private <T> ObjectNode paginate(List<T> sorted, JsonNode request, Function<T, String> nameOf,
BiConsumer<T, ObjectNode> render, String itemsField) {
int max = maxResults(request);
String nextToken = text(request, "NextToken");
List<T> remaining = sorted;
if (nextToken != null && !nextToken.isBlank()) {
remaining = remaining.stream().dropWhile(v -> nameOf.apply(v).compareTo(nextToken) <= 0).toList();
}
List<T> page = remaining.stream().limit(max).toList();
ArrayNode arr = mapper.createArrayNode();
page.forEach(v -> {
ObjectNode n = mapper.createObjectNode();
render.accept(v, n);
arr.add(n);
});
ObjectNode out = mapper.createObjectNode();
out.set(itemsField, arr);
if (page.size() == max && remaining.size() > max) {
out.put("NextToken", nameOf.apply(page.get(page.size() - 1)));
}
return out;
}
private static int maxResults(JsonNode request) {
JsonNode node = request.path("MaxResults");
if (node.isMissingNode() || node.isNull()) {
return DEFAULT_LIMIT;
}
int max = node.asInt();
if (max < 1 || max > MAX_RESULTS_CEILING) {
throw validation("MaxResults must be between 1 and " + MAX_RESULTS_CEILING + ".");
}
return max;
}
}
@@ -0,0 +1,362 @@
package io.github.hectorvent.floci.services.sagemaker;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.command.LogContainerResultCallback;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.services.sagemaker.model.SageMakerEntities.TrainingJobResource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ApplicationScoped
public class SageMakerTrainingRunner implements ContainerTeardown {
private static final Logger LOG = Logger.getLogger(SageMakerTrainingRunner.class);
private static final String LOG_GROUP = "/aws/sagemaker/TrainingJobs";
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerLogStreamer logStreamer;
private final EmulatorConfig config;
private final ContainerDetector containerDetector;
private final S3Service s3Service;
private final ObjectMapper mapper;
private final ExecutorService executor = Executors.newCachedThreadPool();
private final ConcurrentHashMap<String, String> containers = new ConcurrentHashMap<>();
// Names a stop that stop() has already committed to the store as "Stopped": run()'s exit-code
// handling checks this before persisting, since a stop races the removal of the very container
// waitForExit() is polling, and the container disappearing (NotFoundException, exit code 1)
// must not be relabeled a training failure.
private final Set<String> stopRequested = ConcurrentHashMap.newKeySet();
@Inject
public SageMakerTrainingRunner(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
ContainerLogStreamer logStreamer, EmulatorConfig config,
ContainerDetector containerDetector, S3Service s3Service, ObjectMapper mapper) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
this.config = config;
this.containerDetector = containerDetector;
this.s3Service = s3Service;
this.mapper = mapper;
}
public void runAsync(TrainingJobResource job, SageMakerService service) {
executor.submit(() -> run(job, service));
}
private void run(TrainingJobResource job, SageMakerService service) {
String containerId = null;
Closeable logs = null;
try {
String image = SageMakerEndpointManager.string(job.algorithmSpecification.get("TrainingImage"));
String name = ContainerStorageHelper.dockerName(config, "floci-sagemaker-training-" + job.trainingJobName);
lifecycleManager.removeIfExists(name);
ContainerBuilder.Builder builder = containerBuilder.newContainer(image)
.withName(name)
.withEnv(environment(job))
.withDockerNetwork(config.services().sagemaker().dockerNetwork())
.withHostDockerInternalOnLinux()
.withEmbeddedDns()
.withLogRotation();
SageMakerEndpointManager.applyEntrypoint(builder, job.algorithmSpecification, "train");
ContainerSpec spec = builder.build();
containerId = lifecycleManager.create(spec);
containers.put(job.trainingJobName, containerId);
job.containerId = containerId;
copyTrainingInput(containerId, job);
lifecycleManager.startCreated(containerId, spec);
job.trainingStartTime = System.currentTimeMillis();
job.secondaryStatus = "Training";
service.updateTrainingJob(job);
logs = logStreamer.attach(containerId, LOG_GROUP, job.trainingJobName + "/algo-1", job.region,
"sagemaker:" + job.trainingJobName);
Integer exit = waitForExit(containerId, timeout(job));
if (stopRequested.remove(job.trainingJobName)) {
// stop() already persisted Stopped and is tearing the container down itself;
// whatever exit code we just observed (or failed to) is a side effect of that,
// not a real outcome to report.
containers.remove(job.trainingJobName);
return;
}
if (exit == null) {
lifecycleManager.stopAndRemove(containerId, logs);
job.trainingJobStatus = "Failed";
job.secondaryStatus = "Failed";
job.failureReason = "Training job exceeded StoppingCondition.MaxRuntimeInSeconds";
} else if (exit == 0) {
job.modelArtifactsS3ModelArtifacts = uploadModelArtifacts(containerId, job);
lifecycleManager.stopAndRemove(containerId, logs);
job.trainingJobStatus = "Completed";
job.secondaryStatus = "Completed";
} else {
job.failureReason = readFailure(containerId, exit);
lifecycleManager.stopAndRemove(containerId, logs);
job.trainingJobStatus = "Failed";
job.secondaryStatus = "Failed";
}
containers.remove(job.trainingJobName);
job.trainingEndTime = System.currentTimeMillis();
service.updateTrainingJob(job);
} catch (Exception e) {
if (stopRequested.remove(job.trainingJobName)) {
containers.remove(job.trainingJobName);
return;
}
LOG.warnv("SageMaker training job {0} failed: {1}", job.trainingJobName, e.getMessage());
if (containerId != null) {
lifecycleManager.stopAndRemove(containerId, logs);
}
containers.remove(job.trainingJobName);
job.trainingJobStatus = "Failed";
job.secondaryStatus = "Failed";
job.failureReason = e.getMessage();
job.trainingEndTime = System.currentTimeMillis();
service.updateTrainingJob(job);
}
}
public void stop(TrainingJobResource job) {
stopRequested.add(job.trainingJobName);
String id = job.containerId != null ? job.containerId : containers.remove(job.trainingJobName);
if (id != null) {
lifecycleManager.stopAndRemove(id, null);
}
}
@Override
public void stopManagedContainers() {
containers.forEach((name, id) -> lifecycleManager.stopAndRemove(id, null));
containers.clear();
executor.shutdownNow();
}
private List<String> environment(TrainingJobResource job) {
List<String> env = new ArrayList<>();
env.add("TRAINING_JOB_NAME=" + job.trainingJobName);
env.add("TRAINING_JOB_ARN=" + job.trainingJobArn);
env.add("SAGEMAKER_REGION=" + job.region);
env.add("AWS_REGION=" + job.region);
env.add("AWS_DEFAULT_REGION=" + job.region);
env.add("AWS_ACCESS_KEY_ID=test");
env.add("AWS_SECRET_ACCESS_KEY=test");
env.add("AWS_SESSION_TOKEN=test");
String endpoint = "http://" + resolveEndpointHostname() + ":" + config.port();
env.add("AWS_ENDPOINT_URL=" + endpoint);
env.add("FLOCI_ENDPOINT=" + endpoint);
return env;
}
private String resolveEndpointHostname() {
return containerDetector.isRunningInContainer() ? config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX) : "host.docker.internal";
}
private void copyTrainingInput(String containerId, TrainingJobResource job) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(out)) {
SageMakerEndpointManager.addFile(tar, "opt/ml/input/config/hyperparameters.json",
mapper.writeValueAsBytes(job.hyperParameters));
SageMakerEndpointManager.addFile(tar, "opt/ml/input/config/resourceconfig.json",
"{\"current_host\":\"algo-1\",\"hosts\":[\"algo-1\"]}".getBytes(StandardCharsets.UTF_8));
SageMakerEndpointManager.addFile(tar, "opt/ml/input/config/inputdataconfig.json",
mapper.writeValueAsBytes(inputDataConfig(job.inputDataConfig)));
for (Map<String, Object> channel : job.inputDataConfig) {
copyChannelObjects(tar, channel);
}
}
lifecycleManager.getDockerClient().copyArchiveToContainerCmd(containerId)
.withRemotePath("/")
.withTarInputStream(new ByteArrayInputStream(out.toByteArray()))
.exec();
}
private Map<String, Object> inputDataConfig(List<Map<String, Object>> channels) {
Map<String, Object> out = new LinkedHashMap<>();
for (Map<String, Object> c : channels) {
Map<String, Object> value = new LinkedHashMap<>();
value.put("ContentType", c.getOrDefault("ContentType", "application/octet-stream"));
value.put("TrainingInputMode", c.getOrDefault("TrainingInputMode", "File"));
out.put(String.valueOf(c.get("ChannelName")), value);
}
return out;
}
@SuppressWarnings("unchecked")
private void copyChannelObjects(TarArchiveOutputStream tar, Map<String, Object> channel) throws Exception {
String channelName = String.valueOf(channel.get("ChannelName"));
Object dataSource = channel.get("DataSource");
if (!(dataSource instanceof Map<?, ?> ds)) {
return;
}
Object s3 = ds.get("S3DataSource");
if (!(s3 instanceof Map<?, ?> s3ds)) {
return;
}
String s3Uri = String.valueOf(s3ds.get("S3Uri"));
S3Uri uri = S3Uri.parse(s3Uri);
List<S3Object> objects = uri.key().isBlank()
? s3Service.listObjects(uri.bucket(), "", null, 1000)
: s3Service.listObjects(uri.bucket(), uri.key(), null, 1000);
for (S3Object object : objects) {
S3Object full = s3Service.getObject(uri.bucket(), object.getKey());
String relative = relativeToPrefix(uri.key(), object.getKey());
String safeRelative = safeRelativePath(relative);
if (safeRelative != null && !safeRelative.isBlank()) {
SageMakerEndpointManager.addFile(tar, "opt/ml/input/data/" + channelName + "/" + safeRelative, full.getData());
}
}
}
/**
* The part of an object key below the channel's S3 prefix, preserving any subdirectory
* structure instead of flattening every object to its basename (which loses structure and
* collides same-named objects in different "folders" under the prefix).
*/
private static String relativeToPrefix(String prefix, String key) {
if (prefix.isBlank()) {
return key;
}
String folder = prefix.endsWith("/") ? prefix : prefix + "/";
if (key.startsWith(folder)) {
return key.substring(folder.length());
}
// The prefix matched key without a folder boundary (e.g. prefix "input" matching
// "input.csv" itself, or a same-named sibling key equal to the prefix): fall back to
// the basename rather than a key that still carries the shared prefix.
return key.equals(prefix) || key.startsWith(prefix)
? key.substring(key.lastIndexOf('/') + 1)
: key;
}
/** Rejects an absolute path or one that escapes the channel directory via "..". */
private static String safeRelativePath(String relative) {
Path normalized = Path.of(relative).normalize();
if (normalized.isAbsolute() || normalized.startsWith("..") || normalized.toString().equals("..")) {
return null;
}
return normalized.toString();
}
private Integer waitForExit(String containerId, Duration timeout) throws InterruptedException {
long deadline = timeout.isZero() ? Long.MAX_VALUE : System.currentTimeMillis() + timeout.toMillis();
while (System.currentTimeMillis() < deadline) {
Integer exit = getExitCodeIfStopped(containerId);
if (exit != null) {
return exit;
}
Thread.sleep(500);
}
return null;
}
private Integer getExitCodeIfStopped(String containerId) {
try {
InspectContainerResponse inspect = lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec();
if (Boolean.TRUE.equals(inspect.getState().getRunning())) {
return null;
}
Long exit = inspect.getState().getExitCodeLong();
return exit == null ? 0 : exit.intValue();
} catch (NotFoundException e) {
return 1;
}
}
private Duration timeout(TrainingJobResource job) {
Object value = job.stoppingCondition.get("MaxRuntimeInSeconds");
if (value instanceof Number n) {
return Duration.ofSeconds(n.longValue());
}
return Duration.ZERO;
}
private String uploadModelArtifacts(String containerId, TrainingJobResource job) throws Exception {
byte[] data = modelTarGz(containerId);
S3Uri out = S3Uri.parse(String.valueOf(job.outputDataConfig.get("S3OutputPath")));
String prefix = out.key().isBlank() ? "" : (out.key().endsWith("/") ? out.key() : out.key() + "/");
String key = prefix + job.trainingJobName + "/output/model.tar.gz";
s3Service.putObject(out.bucket(), key, data, "application/x-tar", Map.of());
return "s3://" + out.bucket() + "/" + key;
}
private byte[] modelTarGz(String containerId) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (GzipCompressorOutputStream gz = new GzipCompressorOutputStream(out);
TarArchiveOutputStream tarOut = new TarArchiveOutputStream(gz);
InputStream dockerTar = lifecycleManager.getDockerClient().copyArchiveFromContainerCmd(containerId, "/opt/ml/model").exec();
TarArchiveInputStream tarIn = new TarArchiveInputStream(dockerTar)) {
TarArchiveEntry e;
String prefix = null;
while ((e = tarIn.getNextEntry()) != null) {
if (!tarIn.canReadEntryData(e) || e.isDirectory()) continue;
String name = e.getName();
if (prefix == null) {
int slash = name.indexOf('/');
prefix = slash >= 0 ? name.substring(0, slash + 1) : "";
}
if (!prefix.isBlank() && name.startsWith(prefix)) {
name = name.substring(prefix.length());
}
if (!name.isBlank()) {
SageMakerEndpointManager.addFile(tarOut, name, tarIn.readAllBytes());
}
}
}
return out.toByteArray();
}
private String readFailure(String containerId, int exitCode) {
StringBuilder sb = new StringBuilder();
try {
lifecycleManager.getDockerClient().logContainerCmd(containerId)
.withStdErr(true).withTail(20)
.exec(new LogContainerResultCallback() {
@Override
public void onNext(Frame item) {
sb.append(new String(item.getPayload(), StandardCharsets.UTF_8));
}
}).awaitCompletion(Duration.ofSeconds(2).toMillis(), java.util.concurrent.TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
LOG.warnv("Interrupted while reading SageMaker training failure log for container {0}: {1}", containerId, e.getMessage());
Thread.currentThread().interrupt();
return "Container exited with code " + exitCode;
} catch (Exception e) {
LOG.warnv("Could not read SageMaker training failure log for container {0}: {1}", containerId, e.getMessage());
}
String detail = sb.toString().trim();
return detail.isBlank() ? "Container exited with code " + exitCode : detail;
}
}
@@ -0,0 +1,88 @@
package io.github.hectorvent.floci.services.sagemaker.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@RegisterForReflection
public final class SageMakerEntities {
private SageMakerEntities() {
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ModelResource {
public String modelName;
public String modelArn;
public Map<String, Object> primaryContainer = new LinkedHashMap<>();
public List<Map<String, Object>> containers = new ArrayList<>();
public String executionRoleArn;
public long creationTime;
public String region;
public String accountId;
public Map<String, String> tags = new LinkedHashMap<>();
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class EndpointConfigResource {
public String endpointConfigName;
public String endpointConfigArn;
public List<Map<String, Object>> productionVariants = new ArrayList<>();
public long creationTime;
public String region;
public String accountId;
public Map<String, String> tags = new LinkedHashMap<>();
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class EndpointResource {
public String endpointName;
public String endpointArn;
public String endpointConfigName;
public String endpointStatus;
public String failureReason;
public long creationTime;
public long lastModifiedTime;
public String region;
public String accountId;
public String containerId;
public String invokeHost;
public int invokePort;
// Bumped every time a start (create or update) is kicked off; a start worker only
// persists its result while it is still the current one for this endpoint, so a
// superseding update or a delete does not get overwritten by a stale worker finishing
// late.
public long generation;
public Map<String, String> tags = new LinkedHashMap<>();
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class TrainingJobResource {
public String trainingJobName;
public String trainingJobArn;
public String trainingJobStatus;
public String secondaryStatus;
public String failureReason;
public long creationTime;
public long trainingStartTime;
public long trainingEndTime;
public String region;
public String accountId;
public Map<String, Object> algorithmSpecification = new LinkedHashMap<>();
public List<Map<String, Object>> inputDataConfig = new ArrayList<>();
public Map<String, Object> outputDataConfig = new LinkedHashMap<>();
public Map<String, Object> resourceConfig = new LinkedHashMap<>();
public Map<String, Object> stoppingCondition = new LinkedHashMap<>();
public Map<String, String> hyperParameters = new LinkedHashMap<>();
public String modelArtifactsS3ModelArtifacts;
public String containerId;
public Map<String, String> tags = new LinkedHashMap<>();
}
}