mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
e5f9baa12d
commit
e2aefa654b
20 files changed
+2110
-1
No files matched your search
+182
@@ -0,0 +1,182 @@
|
||||
package io.github.hectorvent.floci.services.sagemaker;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
@QuarkusTest
|
||||
class SageMakerDockerIntegrationTest {
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/sagemaker/aws4_request";
|
||||
|
||||
@Inject DockerClient dockerClient;
|
||||
@Inject S3Service s3Service;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for SageMaker Docker tests");
|
||||
}
|
||||
|
||||
@Test
|
||||
void trainingJobRunsRealContainerAndUploadsModelArtifacts() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String bucket = "sm-train-" + suffix;
|
||||
s3Service.createBucket(bucket, "us-east-1");
|
||||
s3Service.putObject(bucket, "input/data.txt", "hello".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
|
||||
String job = "sm-train-" + suffix;
|
||||
post("SageMaker.CreateTrainingJob", """
|
||||
{
|
||||
"TrainingJobName":"%s",
|
||||
"AlgorithmSpecification":{
|
||||
"TrainingImage":"public.ecr.aws/docker/library/busybox:stable",
|
||||
"ContainerEntrypoint":["/bin/sh","-c"],
|
||||
"ContainerArguments":["mkdir -p /opt/ml/model && cp /opt/ml/input/data/train/data.txt /opt/ml/model/model.txt"]
|
||||
},
|
||||
"InputDataConfig":[{"ChannelName":"train","DataSource":{"S3DataSource":{"S3Uri":"s3://%s/input"}},"ContentType":"text/plain","TrainingInputMode":"File"}],
|
||||
"OutputDataConfig":{"S3OutputPath":"s3://%s/output"},
|
||||
"ResourceConfig":{"InstanceType":"ml.m5.large","InstanceCount":1,"VolumeSizeInGB":1},
|
||||
"StoppingCondition":{"MaxRuntimeInSeconds":60}
|
||||
}
|
||||
""".formatted(job, bucket, bucket)).then().statusCode(200).body("TrainingJobArn", notNullValue());
|
||||
|
||||
waitForTraining(job, "Completed");
|
||||
String artifact = post("SageMaker.DescribeTrainingJob", "{\"TrainingJobName\":\"%s\"}".formatted(job))
|
||||
.then().statusCode(200).body("TrainingJobStatus", equalTo("Completed"))
|
||||
.extract().path("ModelArtifacts.S3ModelArtifacts");
|
||||
S3Uri uri = S3Uri.parse(artifact);
|
||||
assertNotNull(s3Service.getObject(uri.bucket(), uri.key()).getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointHostsRealContainerAndRuntimeProxiesInvocations() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String model = "sm-ep-model-" + suffix;
|
||||
String cfg = "sm-ep-cfg-" + suffix;
|
||||
String endpoint = "sm-endpoint-" + suffix;
|
||||
String script = "cat > /server.py <<'PY'\nfrom http.server import BaseHTTPRequestHandler,HTTPServer\nclass H(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200 if self.path == '/ping' else 404); self.end_headers()\n def do_POST(self):\n n=int(self.headers.get('content-length','0')); b=self.rfile.read(n); self.send_response(200); self.send_header('Content-Type','text/plain'); self.end_headers(); self.wfile.write(b.upper())\nHTTPServer(('0.0.0.0',8080),H).serve_forever()\nPY\npython /server.py";
|
||||
post("SageMaker.CreateModel", """
|
||||
{"ModelName":"%s","PrimaryContainer":{"Image":"public.ecr.aws/docker/library/python:3-alpine","ContainerEntrypoint":["/bin/sh","-c"],"ContainerArguments":[%s]}}
|
||||
""".formatted(model, json(script))).then().statusCode(200);
|
||||
post("SageMaker.CreateEndpointConfig", """
|
||||
{"EndpointConfigName":"%s","ProductionVariants":[{"VariantName":"AllTraffic","ModelName":"%s","InitialInstanceCount":1,"InstanceType":"ml.t2.medium","InitialVariantWeight":1.0}]}
|
||||
""".formatted(cfg, model)).then().statusCode(200);
|
||||
post("SageMaker.CreateEndpoint", "{\"EndpointName\":\"%s\",\"EndpointConfigName\":\"%s\"}".formatted(endpoint, cfg))
|
||||
.then().statusCode(200);
|
||||
waitForEndpoint(endpoint, "InService");
|
||||
given().header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/runtime.sagemaker/aws4_request")
|
||||
.contentType("text/plain").body("hello")
|
||||
.when().post("/endpoints/%s/invocations".formatted(endpoint))
|
||||
.then().statusCode(200).body(equalTo("HELLO"));
|
||||
post("SageMaker.DeleteEndpoint", "{\"EndpointName\":\"%s\"}".formatted(endpoint)).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppingATrainingJobDoesNotGetRelabeledFailed() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String bucket = "sm-stop-" + suffix;
|
||||
s3Service.createBucket(bucket, "us-east-1");
|
||||
String job = "sm-stop-" + suffix;
|
||||
post("SageMaker.CreateTrainingJob", """
|
||||
{
|
||||
"TrainingJobName":"%s",
|
||||
"AlgorithmSpecification":{
|
||||
"TrainingImage":"public.ecr.aws/docker/library/busybox:stable",
|
||||
"ContainerEntrypoint":["/bin/sh","-c"],
|
||||
"ContainerArguments":["sleep 60"]
|
||||
},
|
||||
"OutputDataConfig":{"S3OutputPath":"s3://%s/output"},
|
||||
"ResourceConfig":{"InstanceType":"ml.m5.large","InstanceCount":1,"VolumeSizeInGB":1},
|
||||
"StoppingCondition":{"MaxRuntimeInSeconds":300}
|
||||
}
|
||||
""".formatted(job, bucket)).then().statusCode(200);
|
||||
// Give the container time to actually be created and start running "sleep 60" so the
|
||||
// stop races a real running container rather than one still being staged.
|
||||
Thread.sleep(3000);
|
||||
post("SageMaker.StopTrainingJob", "{\"TrainingJobName\":\"%s\"}".formatted(job)).then().statusCode(200);
|
||||
post("SageMaker.DescribeTrainingJob", "{\"TrainingJobName\":\"%s\"}".formatted(job))
|
||||
.then().statusCode(200).body("TrainingJobStatus", equalTo("Stopped"));
|
||||
// The runner's exit-code handling races the container disappearing after the stop;
|
||||
// give it a beat and confirm it did not relabel the stop a failure once it observes that.
|
||||
Thread.sleep(3000);
|
||||
post("SageMaker.DescribeTrainingJob", "{\"TrainingJobName\":\"%s\"}".formatted(job))
|
||||
.then().statusCode(200).body("TrainingJobStatus", equalTo("Stopped"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAnEndpointDuringStartupDoesNotResurrectIt() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String model = "sm-del-model-" + suffix;
|
||||
String cfg = "sm-del-cfg-" + suffix;
|
||||
String endpoint = "sm-del-endpoint-" + suffix;
|
||||
// Sleeps before serving so the /ping health check keeps CreateEndpoint's async start
|
||||
// in flight well past DeleteEndpoint returning.
|
||||
String script = "sleep 5 && cat > /server.py <<'PY'\nfrom http.server import BaseHTTPRequestHandler,HTTPServer\nclass H(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200); self.end_headers()\nHTTPServer(('0.0.0.0',8080),H).serve_forever()\nPY\npython /server.py";
|
||||
post("SageMaker.CreateModel", """
|
||||
{"ModelName":"%s","PrimaryContainer":{"Image":"public.ecr.aws/docker/library/python:3-alpine","ContainerEntrypoint":["/bin/sh","-c"],"ContainerArguments":[%s]}}
|
||||
""".formatted(model, json(script))).then().statusCode(200);
|
||||
post("SageMaker.CreateEndpointConfig", """
|
||||
{"EndpointConfigName":"%s","ProductionVariants":[{"VariantName":"AllTraffic","ModelName":"%s","InitialInstanceCount":1,"InstanceType":"ml.t2.medium","InitialVariantWeight":1.0}]}
|
||||
""".formatted(cfg, model)).then().statusCode(200);
|
||||
post("SageMaker.CreateEndpoint", "{\"EndpointName\":\"%s\",\"EndpointConfigName\":\"%s\"}".formatted(endpoint, cfg))
|
||||
.then().statusCode(200);
|
||||
post("SageMaker.DeleteEndpoint", "{\"EndpointName\":\"%s\"}".formatted(endpoint)).then().statusCode(200);
|
||||
// Let the superseded start worker finish (it should discard its result, not persist it).
|
||||
Thread.sleep(10000);
|
||||
post("SageMaker.DescribeEndpoint", "{\"EndpointName\":\"%s\"}".formatted(endpoint)).then().statusCode(400);
|
||||
}
|
||||
|
||||
private void waitForTraining(String job, String status) throws Exception {
|
||||
long deadline = System.currentTimeMillis() + Duration.ofSeconds(120).toMillis();
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
String current = post("SageMaker.DescribeTrainingJob", "{\"TrainingJobName\":\"%s\"}".formatted(job)).then().statusCode(200).extract().path("TrainingJobStatus");
|
||||
if (status.equals(current)) return;
|
||||
if ("Failed".equals(current)) throw new AssertionError("Training failed");
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
throw new AssertionError("Timed out waiting for training job");
|
||||
}
|
||||
|
||||
private void waitForEndpoint(String endpoint, String status) throws Exception {
|
||||
long deadline = System.currentTimeMillis() + Duration.ofSeconds(150).toMillis();
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
String current = post("SageMaker.DescribeEndpoint", "{\"EndpointName\":\"%s\"}".formatted(endpoint)).then().statusCode(200).extract().path("EndpointStatus");
|
||||
if (status.equals(current)) return;
|
||||
if ("Failed".equals(current)) throw new AssertionError("Endpoint failed");
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
throw new AssertionError("Timed out waiting for endpoint");
|
||||
}
|
||||
|
||||
private io.restassured.response.Response post(String target, String body) {
|
||||
return given().header("Authorization", AUTH).header("X-Amz-Target", target)
|
||||
.contentType("application/x-amz-json-1.1").body(body).when().post("/");
|
||||
}
|
||||
|
||||
private boolean isDockerAvailable() {
|
||||
try { dockerClient.pingCmd().exec(); return true; } catch (Exception e) { return false; }
|
||||
}
|
||||
|
||||
private String json(String value) {
|
||||
return "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n") + "\"";
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package io.github.hectorvent.floci.services.sagemaker;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
|
||||
@QuarkusTest
|
||||
class SageMakerIntegrationTest {
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/sagemaker/aws4_request";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonControlPlaneModelEndpointConfigAndTags() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String model = "sm-model-" + suffix;
|
||||
String arn = post("SageMaker.CreateModel", """
|
||||
{"ModelName":"%s","PrimaryContainer":{"Image":"busybox:stable"},"Tags":[{"Key":"env","Value":"test"}]}
|
||||
""".formatted(model))
|
||||
.then().statusCode(200).body("ModelArn", notNullValue()).extract().path("ModelArn");
|
||||
|
||||
post("SageMaker.DescribeModel", "{\"ModelName\":\"%s\"}".formatted(model))
|
||||
.then().statusCode(200).body("ModelName", equalTo(model)).body("PrimaryContainer.Image", equalTo("busybox:stable"));
|
||||
|
||||
String cfg = "sm-cfg-" + suffix;
|
||||
post("SageMaker.CreateEndpointConfig", """
|
||||
{"EndpointConfigName":"%s","ProductionVariants":[{"VariantName":"AllTraffic","ModelName":"%s","InitialInstanceCount":1,"InstanceType":"ml.t2.medium","InitialVariantWeight":1.0}]}
|
||||
""".formatted(cfg, model))
|
||||
.then().statusCode(200).body("EndpointConfigArn", notNullValue());
|
||||
post("SageMaker.ListEndpointConfigs", "{}").then().statusCode(200)
|
||||
.body("EndpointConfigs.find { it.EndpointConfigName == '%s' }.EndpointConfigName".formatted(cfg), equalTo(cfg));
|
||||
|
||||
post("SageMaker.AddTags", "{\"ResourceArn\":\"%s\",\"Tags\":[{\"Key\":\"owner\",\"Value\":\"sdk\"}]}".formatted(arn))
|
||||
.then().statusCode(200).body("Tags", hasSize(2));
|
||||
post("SageMaker.DeleteTags", "{\"ResourceArn\":\"%s\",\"TagKeys\":[\"env\"]}".formatted(arn))
|
||||
.then().statusCode(200);
|
||||
post("SageMaker.ListTags", "{\"ResourceArn\":\"%s\"}".formatted(arn))
|
||||
.then().statusCode(200).body("Tags", hasSize(1)).body("Tags[0].Key", equalTo("owner"));
|
||||
|
||||
post("SageMaker.DeleteEndpointConfig", "{\"EndpointConfigName\":\"%s\"}".formatted(cfg)).then().statusCode(200);
|
||||
post("SageMaker.DeleteModel", "{\"ModelName\":\"%s\"}".formatted(model)).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void trainingJobValidationErrorsUseAwsJsonErrorShape() {
|
||||
post("SageMaker.CreateTrainingJob", "{\"TrainingJobName\":\"bad\"}")
|
||||
.then().statusCode(400).body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
private io.restassured.response.Response post(String target, String body) {
|
||||
return given().header("Authorization", AUTH)
|
||||
.header("X-Amz-Target", target)
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body)
|
||||
.when().post("/");
|
||||
}
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
package io.github.hectorvent.floci.services.sagemaker;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
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 org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
class SageMakerServiceTest {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void modelCrudAndDuplicateValidation() throws Exception {
|
||||
SageMakerService service = service();
|
||||
service.createModel(mapper.readTree("""
|
||||
{"ModelName":"m1","PrimaryContainer":{"Image":"busybox:stable"},"ExecutionRoleArn":"arn:aws:iam::000000000000:role/r"}
|
||||
"""), "us-east-1");
|
||||
assertEquals("m1", service.describeModel(mapper.readTree("{\"ModelName\":\"m1\"}"), "us-east-1").path("ModelName").asText());
|
||||
AwsException duplicate = assertThrows(AwsException.class, () -> service.createModel(mapper.readTree("""
|
||||
{"ModelName":"m1","PrimaryContainer":{"Image":"busybox:stable"}}
|
||||
"""), "us-east-1"));
|
||||
assertEquals("ValidationException", duplicate.getErrorCode());
|
||||
service.deleteModel(mapper.readTree("{\"ModelName\":\"m1\"}"), "us-east-1");
|
||||
AwsException missing = assertThrows(AwsException.class,
|
||||
() -> service.describeModel(mapper.readTree("{\"ModelName\":\"m1\"}"), "us-east-1"));
|
||||
assertEquals("ValidationException", missing.getErrorCode());
|
||||
AwsException deleteMissing = assertThrows(AwsException.class,
|
||||
() -> service.deleteModel(mapper.readTree("{\"ModelName\":\"m1\"}"), "us-east-1"));
|
||||
assertEquals("ValidationException", deleteMissing.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modelIsScopedByRegion() throws Exception {
|
||||
SageMakerService service = service();
|
||||
service.createModel(mapper.readTree("""
|
||||
{"ModelName":"m1","PrimaryContainer":{"Image":"busybox:stable"}}
|
||||
"""), "us-east-1");
|
||||
AwsException missingInOtherRegion = assertThrows(AwsException.class,
|
||||
() -> service.describeModel(mapper.readTree("{\"ModelName\":\"m1\"}"), "us-west-2"));
|
||||
assertEquals("ValidationException", missingInOtherRegion.getErrorCode());
|
||||
// Same name, different region: not a collision, since the ARNs are regional.
|
||||
service.createModel(mapper.readTree("""
|
||||
{"ModelName":"m1","PrimaryContainer":{"Image":"busybox:stable"}}
|
||||
"""), "us-west-2");
|
||||
assertEquals(1, service.listModels(mapper.readTree("{}"), "us-east-1").path("Models").size());
|
||||
assertEquals(1, service.listModels(mapper.readTree("{}"), "us-west-2").path("Models").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createModelRejectsEmptyContainers() throws Exception {
|
||||
SageMakerService service = service();
|
||||
AwsException empty = assertThrows(AwsException.class, () -> service.createModel(mapper.readTree("""
|
||||
{"ModelName":"m1","Containers":[]}
|
||||
"""), "us-east-1"));
|
||||
assertEquals("ValidationException", empty.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listModelsValidatesMaxResultsAndPaginates() throws Exception {
|
||||
SageMakerService service = service();
|
||||
for (String name : List.of("a", "b", "c")) {
|
||||
service.createModel(mapper.readTree(
|
||||
"{\"ModelName\":\"" + name + "\",\"PrimaryContainer\":{\"Image\":\"busybox:stable\"}}"), "us-east-1");
|
||||
}
|
||||
AwsException badMax = assertThrows(AwsException.class,
|
||||
() -> service.listModels(mapper.readTree("{\"MaxResults\":0}"), "us-east-1"));
|
||||
assertEquals("ValidationException", badMax.getErrorCode());
|
||||
|
||||
JsonNode firstPage = service.listModels(mapper.readTree("{\"MaxResults\":2}"), "us-east-1");
|
||||
assertEquals(2, firstPage.path("Models").size());
|
||||
assertEquals("a", firstPage.path("Models").get(0).path("ModelName").asText());
|
||||
String nextToken = firstPage.path("NextToken").asText();
|
||||
assertEquals("b", nextToken);
|
||||
|
||||
JsonNode secondPage = service.listModels(
|
||||
mapper.readTree("{\"MaxResults\":2,\"NextToken\":\"" + nextToken + "\"}"), "us-east-1");
|
||||
assertEquals(1, secondPage.path("Models").size());
|
||||
assertEquals("c", secondPage.path("Models").get(0).path("ModelName").asText());
|
||||
assertTrue(secondPage.path("NextToken").isMissingNode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteEndpointConfigRequiresExistingConfig() throws Exception {
|
||||
SageMakerService service = service();
|
||||
AwsException missing = assertThrows(AwsException.class,
|
||||
() -> service.deleteEndpointConfig(mapper.readTree("{\"EndpointConfigName\":\"missing\"}"), "us-east-1"));
|
||||
assertEquals("ValidationException", missing.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointConfigRequiresExistingModel() throws Exception {
|
||||
SageMakerService service = service();
|
||||
AwsException missing = assertThrows(AwsException.class, () -> service.createEndpointConfig(mapper.readTree("""
|
||||
{"EndpointConfigName":"cfg","ProductionVariants":[{"VariantName":"AllTraffic","ModelName":"missing","InitialInstanceCount":1,"InstanceType":"ml.t2.medium"}]}
|
||||
"""), "us-east-1"));
|
||||
assertEquals("ValidationException", missing.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsRoundTrip() throws Exception {
|
||||
SageMakerService service = service();
|
||||
String arn = service.createModel(mapper.readTree("""
|
||||
{"ModelName":"tagged","PrimaryContainer":{"Image":"busybox:stable"},"Tags":[{"Key":"a","Value":"b"}]}
|
||||
"""), "us-east-1").path("ModelArn").asText();
|
||||
service.addTags(mapper.readTree("{\"ResourceArn\":\"" + arn + "\",\"Tags\":[{\"Key\":\"c\",\"Value\":\"d\"}]}"));
|
||||
assertEquals(2, service.listTags(mapper.readTree("{\"ResourceArn\":\"" + arn + "\"}")).path("Tags").size());
|
||||
service.deleteTags(mapper.readTree("{\"ResourceArn\":\"" + arn + "\",\"TagKeys\":[\"a\"]}"));
|
||||
assertEquals("c", service.listTags(mapper.readTree("{\"ResourceArn\":\"" + arn + "\"}")).path("Tags").get(0).path("Key").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsWithoutAKeyAreSkippedInsteadOfStoredWithANullKey() throws Exception {
|
||||
SageMakerService service = service();
|
||||
String arn = service.createModel(mapper.readTree("""
|
||||
{"ModelName":"m1","PrimaryContainer":{"Image":"busybox:stable"},"Tags":[{"Value":"orphan"},{"Key":"a","Value":"b"}]}
|
||||
"""), "us-east-1").path("ModelArn").asText();
|
||||
JsonNode tags = service.listTags(mapper.readTree("{\"ResourceArn\":\"" + arn + "\"}")).path("Tags");
|
||||
assertEquals(1, tags.size());
|
||||
assertEquals("a", tags.get(0).path("Key").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void trainingJobListingFiltersByNameAndStatus() throws Exception {
|
||||
SageMakerService service = service();
|
||||
for (String name : List.of("job-a", "job-b", "other")) {
|
||||
service.createTrainingJob(mapper.readTree("""
|
||||
{"TrainingJobName":"%s",
|
||||
"AlgorithmSpecification":{"TrainingImage":"busybox:stable"},
|
||||
"OutputDataConfig":{"S3OutputPath":"s3://bucket/out"}}
|
||||
""".formatted(name)), "us-east-1");
|
||||
}
|
||||
JsonNode filtered = service.listTrainingJobs(mapper.readTree("{\"NameContains\":\"job-\"}"), "us-east-1");
|
||||
assertEquals(2, filtered.path("TrainingJobSummaries").size());
|
||||
|
||||
JsonNode byStatus = service.listTrainingJobs(mapper.readTree("{\"StatusEquals\":\"Completed\"}"), "us-east-1");
|
||||
assertEquals(0, byStatus.path("TrainingJobSummaries").size());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void s3UriParsingCoversPrefixesAndValidation() {
|
||||
S3Uri object = S3Uri.parse("s3://bucket/path/to/object");
|
||||
assertEquals("bucket", object.bucket());
|
||||
assertEquals("path/to/object", object.key());
|
||||
S3Uri bucketOnly = S3Uri.parse("s3://bucket");
|
||||
assertEquals("bucket", bucketOnly.bucket());
|
||||
assertEquals("", bucketOnly.key());
|
||||
assertThrows(IllegalArgumentException.class, () -> S3Uri.parse("http://bucket/key"));
|
||||
}
|
||||
|
||||
private SageMakerService service() {
|
||||
return new SageMakerService(new InMemoryStorage<String, ModelResource>(),
|
||||
new InMemoryStorage<String, EndpointConfigResource>(),
|
||||
new InMemoryStorage<String, EndpointResource>(),
|
||||
new InMemoryStorage<String, TrainingJobResource>(),
|
||||
new RegionResolver("us-east-1", "000000000000"), mapper,
|
||||
mock(SageMakerEndpointManager.class), mock(SageMakerTrainingRunner.class));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user