mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(sagemaker): start endpoint containers again when Floci restarts (#9367)
Floci's shutdown stops every endpoint container, and nothing started them again, so after a restart with persistent storage an endpoint still reported InService while InvokeEndpoint failed with ModelError. At startup, each endpoint that was InService or still Creating goes back to Creating and is started again from its endpoint config and model, as CreateEndpoint starts one, in the account it is stored under. It reports InService once its container answers /ping, or Failed with the reason. A Failed endpoint is left as it is, and one a crash left Deleting is deleted. Part of #5664.
This commit is contained in:
1 parent
464aaaf734
commit
2bcde72f1e
12 files changed
+622
-30
No files matched your search
@@ -78,6 +78,22 @@ class AccountAwareStorageBackendTest {
|
||||
assertEquals(Optional.empty(), raw.get("000000000000/resource"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteInAccountDeletesOnlyTheNamedAccountsEntry() {
|
||||
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
|
||||
AccountAwareStorageBackend<String> storage = new AccountAwareStorageBackend<>(raw, null, "000000000000");
|
||||
raw.put("000000000000/resource", "default");
|
||||
raw.put("111111111111/resource", "owned");
|
||||
|
||||
AccountAwareStorageBackend.deleteInAccount(storage, "111111111111", "resource");
|
||||
|
||||
assertEquals(Set.of("000000000000/resource"), raw.keys());
|
||||
InMemoryStorage<String, String> plain = new InMemoryStorage<>();
|
||||
plain.put("resource", "value");
|
||||
AccountAwareStorageBackend.deleteInAccount(plain, "111111111111", "resource");
|
||||
assertTrue(plain.keys().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inAccountHelpersUseTheAmbientAccountWithoutAnAccountId() {
|
||||
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
|
||||
|
||||
@@ -42,6 +42,7 @@ import io.floci.aws.services.rds.RdsService;
|
||||
import io.floci.aws.services.rds.container.RdsContainerManager;
|
||||
import io.floci.aws.services.rds.proxy.RdsProxyManager;
|
||||
import io.floci.aws.services.redshift.RedshiftDynamoDbZeroEtlConsumer;
|
||||
import io.floci.aws.services.sagemaker.SageMakerService;
|
||||
import io.floci.aws.services.stepfunctions.StepFunctionsService;
|
||||
import io.floci.aws.services.timestreaminfluxdb.TimestreamInfluxDbService;
|
||||
import io.floci.aws.testutil.LogCapture;
|
||||
@@ -121,6 +122,8 @@ class EmulatorLifecycleTest {
|
||||
@Mock private ElbV2Service elbV2Service;
|
||||
@Mock private ElbClassicService elbClassicService;
|
||||
@Mock private EcsService ecsService;
|
||||
@Mock private SageMakerService sageMakerService;
|
||||
@Mock private EmulatorConfig.SageMakerServiceConfig sageMakerServiceConfig;
|
||||
@Mock private EksService eksService;
|
||||
@Mock private CodeArtifactService codeArtifactService;
|
||||
@Mock private CloudWatchMetricsService cloudWatchMetricsService;
|
||||
@@ -168,6 +171,8 @@ class EmulatorLifecycleTest {
|
||||
Mockito.lenient().when(eksServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(servicesConfig.codeartifact()).thenReturn(codeArtifactServiceConfig);
|
||||
Mockito.lenient().when(codeArtifactServiceConfig.enabled()).thenReturn(true);
|
||||
Mockito.lenient().when(servicesConfig.sagemaker()).thenReturn(sageMakerServiceConfig);
|
||||
Mockito.lenient().when(sageMakerServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(servicesConfig.timestreamInfluxdb()).thenReturn(timestreamInfluxDbServiceConfig);
|
||||
Mockito.lenient().when(timestreamInfluxDbServiceConfig.enabled()).thenReturn(true);
|
||||
Mockito.lenient().when(servicesConfig.iam()).thenReturn(iamServiceConfig);
|
||||
@@ -183,7 +188,7 @@ class EmulatorLifecycleTest {
|
||||
elastiCacheProxyManager, rdsContainerManager, rdsProxyManager,
|
||||
memoryDbContainerManager, memoryDbProxyManager, memoryDbService,
|
||||
docDbContainerManager, neptuneContainerManager, neptuneProxyManager,
|
||||
rabbitMqManager, flinkContainerManager, rdsService, timestreamInfluxDbService,
|
||||
rabbitMqManager, flinkContainerManager, sageMakerService, rdsService, timestreamInfluxDbService,
|
||||
elbV2Service, elbClassicService, ecsService,
|
||||
initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller,
|
||||
pipesService, ec2MetadataServer, ecsTaskRoleCredentialsServer, ecrRegistryManager, flociUiManager, initLifecycleState,
|
||||
@@ -482,6 +487,47 @@ class EmulatorLifecycleTest {
|
||||
inOrder.verify(elastiCacheMemcachedService).restorePersistedRuntime();
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoresPersistedSageMakerEndpointsAfterStorageLoad() {
|
||||
stubStorageConfig();
|
||||
when(sageMakerServiceConfig.enabled()).thenReturn(true);
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
|
||||
InOrder inOrder = Mockito.inOrder(storageFactory, sageMakerService);
|
||||
inOrder.verify(storageFactory).loadAll();
|
||||
inOrder.verify(sageMakerService).restorePersistedRuntime();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedSageMakerRestoreDoesNotStopTheOtherRestores() {
|
||||
stubStorageConfig();
|
||||
when(sageMakerServiceConfig.enabled()).thenReturn(true);
|
||||
when(elbv2ServiceConfig.enabled()).thenReturn(true);
|
||||
doThrow(new IllegalStateException("Could not restore SageMaker endpoint demo of account 000000000000"))
|
||||
.when(sageMakerService).restorePersistedRuntime();
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
|
||||
verify(elbV2Service).restorePersistedRuntime();
|
||||
verify(initLifecycleState).markReadyCompleted();
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesSageMakerEndpointsUntouchedWhenSageMakerIsDisabled() {
|
||||
stubStorageConfig();
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
|
||||
verify(sageMakerService, never()).restorePersistedRuntime();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not restore ElastiCache persisted runtime when elasticache is disabled")
|
||||
void shouldNotRestoreElastiCachePersistedRuntimeWhenDisabled() {
|
||||
|
||||
@@ -2,8 +2,10 @@ package io.floci.aws.services.sagemaker;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import com.github.dockerjava.api.model.Event;
|
||||
import com.github.dockerjava.api.model.EventType;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.floci.aws.testing.TestImages;
|
||||
@@ -42,6 +44,8 @@ class SageMakerDockerIntegrationTest {
|
||||
|
||||
@Inject DockerClient dockerClient;
|
||||
@Inject S3Service s3Service;
|
||||
@Inject SageMakerService sageMakerService;
|
||||
@Inject EmulatorConfig config;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
@@ -85,13 +89,49 @@ class SageMakerDockerIntegrationTest {
|
||||
|
||||
@Test
|
||||
void endpointHostsRealContainerAndRuntimeProxiesInvocations() throws Exception {
|
||||
String endpoint = createUppercasingEndpoint("sm-ep");
|
||||
waitForEndpoint(endpoint, "InService");
|
||||
invoke(endpoint).then().statusCode(200).body(equalTo("MODEL:HELLO"));
|
||||
post("SageMaker.DeleteEndpoint", "{\"EndpointName\":\"%s\"}".formatted(endpoint)).then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* #5664: Floci's shutdown removes every endpoint container, and the stored endpoint still says InService. The
|
||||
* startup restore starts it again from its model, model data included, so InvokeEndpoint answers again. Removing
|
||||
* the container stands in for the shutdown, and the restore is what startup calls.
|
||||
*/
|
||||
@Test
|
||||
void anEndpointWhoseContainerIsGoneServesAgainOnceRestored() throws Exception {
|
||||
String endpoint = createUppercasingEndpoint("sm-restore");
|
||||
waitForEndpoint(endpoint, "InService");
|
||||
try {
|
||||
for (Container container : dockerClient.listContainersCmd().withShowAll(true)
|
||||
.withNameFilter(List.of(containerName(endpoint))).exec()) {
|
||||
dockerClient.removeContainerCmd(container.getId()).withForce(true).exec();
|
||||
}
|
||||
invoke(endpoint).then().statusCode(424).body("__type", equalTo("ModelError"));
|
||||
|
||||
sageMakerService.restorePersistedRuntime();
|
||||
|
||||
waitForEndpoint(endpoint, "InService");
|
||||
invoke(endpoint).then().statusCode(200).body(equalTo("MODEL:HELLO"));
|
||||
} finally {
|
||||
post("SageMaker.DeleteEndpoint", "{\"EndpointName\":\"%s\"}".formatted(endpoint));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an endpoint whose model answers an invocation with its model data, {@code MODEL:}, followed by the
|
||||
* request body upper-cased, and returns its name. The model data is copied in from S3 as the endpoint starts.
|
||||
*/
|
||||
private String createUppercasingEndpoint(String prefix) {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String bucket = "sm-ep-" + suffix;
|
||||
String bucket = prefix + "-" + suffix;
|
||||
s3Service.createBucket(bucket, "us-east-1");
|
||||
s3Service.putObject(bucket, "prefix.txt", "MODEL:".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
|
||||
String model = "sm-ep-model-" + suffix;
|
||||
String cfg = "sm-ep-cfg-" + suffix;
|
||||
String endpoint = "sm-endpoint-" + suffix;
|
||||
String model = prefix + "-model-" + suffix;
|
||||
String cfg = prefix + "-cfg-" + suffix;
|
||||
String endpoint = prefix + "-endpoint-" + suffix;
|
||||
String script = "trap 'exit 0' TERM; cat > /server.py <<'PY'\nfrom http.server import BaseHTTPRequestHandler,HTTPServer\nfrom pathlib import Path\nmodel=Path('/opt/ml/model/prefix.txt').read_bytes()\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(model+b.upper())\nHTTPServer(('0.0.0.0',8080),H).serve_forever()\nPY\npython /server.py & wait $!";
|
||||
post("SageMaker.CreateModel", """
|
||||
{"ModelName":"%s","PrimaryContainer":{"Image":"%s","ModelDataUrl":"s3://%s/prefix.txt","ContainerEntrypoint":["/bin/sh","-c"],"ContainerArguments":[%s]}}
|
||||
@@ -101,12 +141,18 @@ class SageMakerDockerIntegrationTest {
|
||||
""".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")
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
/** The container of an endpoint of the default account in us-east-1, named as production names it. */
|
||||
private String containerName(String endpoint) {
|
||||
return SageMakerEndpointManager.containerName(config, "000000000000", "us-east-1", endpoint);
|
||||
}
|
||||
|
||||
private Response invoke(String endpoint) {
|
||||
return 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("MODEL:HELLO"));
|
||||
post("SageMaker.DeleteEndpoint", "{\"EndpointName\":\"%s\"}".formatted(endpoint)).then().statusCode(200);
|
||||
.when().post("/endpoints/%s/invocations".formatted(endpoint));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -162,7 +208,7 @@ class SageMakerDockerIntegrationTest {
|
||||
// rather than polling for the container means a container that is created and discarded
|
||||
// between two polls is still seen: events are queued and replayed from the watch's start.
|
||||
try (ContainerDestroyWatch discarded =
|
||||
new ContainerDestroyWatch(dockerClient, "floci-aws-sagemaker-endpoint-" + endpoint)) {
|
||||
new ContainerDestroyWatch(dockerClient, containerName(endpoint))) {
|
||||
post("SageMaker.CreateEndpoint", "{\"EndpointName\":\"%s\",\"EndpointConfigName\":\"%s\"}".formatted(endpoint, cfg))
|
||||
.then().statusCode(200);
|
||||
post("SageMaker.DeleteEndpoint", "{\"EndpointName\":\"%s\"}".formatted(endpoint)).then().statusCode(200);
|
||||
|
||||
@@ -1,26 +1,40 @@
|
||||
package io.floci.aws.services.sagemaker;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.sagemaker.model.SageMakerEntities.EndpointResource;
|
||||
import io.floci.aws.services.sagemaker.model.SageMakerEntities.ModelResource;
|
||||
import io.floci.aws.testing.ParallelLocks;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.parallel.ResourceAccessMode;
|
||||
import org.junit.jupiter.api.parallel.ResourceLock;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -29,6 +43,8 @@ import static org.mockito.Mockito.when;
|
||||
* {@code clear()}, and {@code afterReset()} last, even when the wipe or a {@code clear()}
|
||||
* failed. Shutdown runs only the teardown.
|
||||
*/
|
||||
// One test serves /ping on a port it holds for the test's length.
|
||||
@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ)
|
||||
class SageMakerEndpointManagerTest {
|
||||
|
||||
@Test
|
||||
@@ -83,8 +99,9 @@ class SageMakerEndpointManagerTest {
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.create(any())).thenThrow(new IllegalStateException("stop after the spec"));
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
SageMakerEndpointManager manager = new SageMakerEndpointManager(containerBuilder, lifecycleManager,
|
||||
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), mock(ContainerDetector.class), mock(S3Service.class));
|
||||
config, mock(ContainerDetector.class), mock(S3Service.class));
|
||||
SageMakerService service = mock(SageMakerService.class);
|
||||
EndpointResource endpoint = new EndpointResource();
|
||||
endpoint.endpointName = "labelled";
|
||||
@@ -104,9 +121,96 @@ class SageMakerEndpointManagerTest {
|
||||
assertTrue(published.await(5, TimeUnit.SECONDS));
|
||||
verify(specBuilder).withLabels(argThat(labels -> "sagemaker".equals(labels.get("io.floci.service"))
|
||||
&& "labelled".equals(labels.get("io.floci.resource-id"))));
|
||||
String name = SageMakerEndpointManager.containerName(config, "000000000000", "us-east-1", "labelled");
|
||||
verify(lifecycleManager).removeIfExists(name);
|
||||
verify(specBuilder).withName(name);
|
||||
manager.stopManagedContainers();
|
||||
}
|
||||
|
||||
/** #5664: endpoints of one name in two accounts or Regions get containers of their own. */
|
||||
@Test
|
||||
void sameNamedEndpointsOfOtherAccountsOrRegionsGetContainersOfTheirOwn() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
|
||||
Set<String> names = Set.of(
|
||||
SageMakerEndpointManager.containerName(config, "111111111111", "us-east-1", "ep"),
|
||||
SageMakerEndpointManager.containerName(config, "222222222222", "us-east-1", "ep"),
|
||||
SageMakerEndpointManager.containerName(config, "111111111111", "eu-west-1", "ep"));
|
||||
|
||||
assertEquals(3, names.size());
|
||||
}
|
||||
|
||||
/** Two endpoints of one name in two accounts are tracked apart: stopping one leaves the other's container. */
|
||||
@Test
|
||||
void stoppingOneOfTwoSameNamedEndpointsLeavesTheOthersContainer() throws Exception {
|
||||
HttpServer ping = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
|
||||
ping.createContext("/ping", exchange -> {
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
exchange.close();
|
||||
});
|
||||
ping.start();
|
||||
try {
|
||||
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.create(any())).thenReturn("container-of-111", "container-of-222");
|
||||
when(lifecycleManager.startCreated(anyString(), any())).thenAnswer(invocation -> new ContainerInfo(
|
||||
invocation.getArgument(0), Map.of(8080, new EndpointInfo("127.0.0.1", ping.getAddress().getPort()))));
|
||||
SageMakerEndpointManager manager = new SageMakerEndpointManager(containerBuilder, lifecycleManager,
|
||||
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), mock(ContainerDetector.class), mock(S3Service.class));
|
||||
SageMakerService service = mock(SageMakerService.class);
|
||||
ModelResource model = new ModelResource();
|
||||
model.primaryContainer.put("Image", "example/serve:1");
|
||||
when(service.modelForEndpoint(any())).thenReturn(model);
|
||||
for (String account : List.of("111111111111", "222222222222")) {
|
||||
CountDownLatch published = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
published.countDown();
|
||||
return true;
|
||||
}).when(service).finalizeEndpointStart(any());
|
||||
manager.startEndpointAsync(sharedNameEndpoint(account), service);
|
||||
assertTrue(published.await(5, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
manager.stopEndpoint(sharedNameEndpoint("111111111111"));
|
||||
|
||||
verify(lifecycleManager).stopAndRemove("container-of-111", null);
|
||||
verify(lifecycleManager, never()).stopAndRemove(eq("container-of-222"), any());
|
||||
manager.stopManagedContainers();
|
||||
} finally {
|
||||
ping.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
/** The stored record of an endpoint named "shared" while it starts, before a container is recorded on it. */
|
||||
private static EndpointResource sharedNameEndpoint(String accountId) {
|
||||
EndpointResource endpoint = new EndpointResource();
|
||||
endpoint.endpointName = "shared";
|
||||
endpoint.region = "us-east-1";
|
||||
endpoint.accountId = accountId;
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
/** A crash can leave a container no record names; stopping the endpoint removes it by the endpoint's name. */
|
||||
@Test
|
||||
void stoppingAnEndpointNoContainerIsRecordedForRemovesItsContainerByName() {
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
SageMakerEndpointManager manager = new SageMakerEndpointManager(mock(ContainerBuilder.class),
|
||||
lifecycleManager, config, mock(ContainerDetector.class), mock(S3Service.class));
|
||||
EndpointResource endpoint = new EndpointResource();
|
||||
endpoint.endpointName = "leftover";
|
||||
endpoint.region = "us-east-1";
|
||||
endpoint.accountId = "111111111111";
|
||||
|
||||
manager.stopEndpoint(endpoint);
|
||||
|
||||
verify(lifecycleManager).removeIfExists(
|
||||
SageMakerEndpointManager.containerName(config, "111111111111", "us-east-1", "leftover"));
|
||||
verify(lifecycleManager, never()).stopAndRemove(any(), any());
|
||||
}
|
||||
|
||||
private static SageMakerEndpointManager manager() {
|
||||
return new SageMakerEndpointManager(mock(ContainerBuilder.class), mock(ContainerLifecycleManager.class),
|
||||
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), mock(ContainerDetector.class), mock(S3Service.class));
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package io.floci.aws.services.sagemaker;
|
||||
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.services.sagemaker.model.SageMakerEntities.EndpointResource;
|
||||
import io.floci.aws.testing.ParallelLocks;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.parallel.ResourceLock;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
// Takes a free port and releases it before dialing it, so it holds the ports lock exclusively.
|
||||
@ResourceLock(ParallelLocks.PORTS)
|
||||
class SageMakerRuntimeControllerTest {
|
||||
|
||||
/**
|
||||
* #5664: an endpoint whose container is gone refuses the connection, with an exception that carries no message.
|
||||
* The invocation answers ModelError rather than failing on the missing message.
|
||||
*/
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void anEndpointWhoseContainerRefusesTheConnectionAnswersModelError() throws IOException {
|
||||
SageMakerService service = mock(SageMakerService.class);
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.resolveRegion(any())).thenReturn("us-east-1");
|
||||
EndpointResource endpoint = new EndpointResource();
|
||||
endpoint.endpointName = "gone";
|
||||
endpoint.endpointStatus = "InService";
|
||||
endpoint.invokeHost = "127.0.0.1";
|
||||
endpoint.invokePort = closedPort();
|
||||
when(service.endpoint("us-east-1", "gone")).thenReturn(Optional.of(endpoint));
|
||||
|
||||
Response response = new SageMakerRuntimeController(service, regionResolver).invoke("gone", "text/plain", null,
|
||||
mock(HttpHeaders.class), "hello".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
assertEquals(424, response.getStatus());
|
||||
Map<String, Object> body = (Map<String, Object>) response.getEntity();
|
||||
assertEquals("ModelError", body.get("__type"));
|
||||
assertNotNull(body.get("message"));
|
||||
}
|
||||
|
||||
private static int closedPort() throws IOException {
|
||||
try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
|
||||
return socket.getLocalPort();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,17 +11,30 @@ import io.floci.aws.services.sagemaker.model.SageMakerEntities.EndpointResource;
|
||||
import io.floci.aws.services.sagemaker.model.SageMakerEntities.ModelResource;
|
||||
import io.floci.aws.services.sagemaker.model.SageMakerEntities.TrainingJobResource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class SageMakerServiceTest {
|
||||
private static final String DEFAULT_ACCOUNT = "000000000000";
|
||||
@@ -361,6 +374,170 @@ class SageMakerServiceTest {
|
||||
fixture.jobs().getForAccount(OTHER_ACCOUNT, "us-east-1::demo-job").orElseThrow().trainingJobStatus);
|
||||
}
|
||||
|
||||
/**
|
||||
* #5664: shutdown stops every endpoint's container, so after a restart an endpoint that was running or still
|
||||
* starting goes back to Creating and starts again, written in its own account; a failed one stays as it is, and
|
||||
* one a crash left deleting is deleted.
|
||||
*/
|
||||
@Test
|
||||
void restoringStartsEveryRunningOrStartingEndpointAgainInItsOwnAccount() {
|
||||
InMemoryStorage<String, EndpointResource> raw = spy(new InMemoryStorage<String, EndpointResource>());
|
||||
AccountAwareStorageBackend<EndpointResource> endpoints =
|
||||
new AccountAwareStorageBackend<>(raw, null, DEFAULT_ACCOUNT);
|
||||
SageMakerEndpointManager manager = mock(SageMakerEndpointManager.class);
|
||||
SageMakerService service = restoringService(endpoints, manager);
|
||||
EndpointResource running = endpoint("InService", "running");
|
||||
running.containerId = "stopped-on-shutdown";
|
||||
running.invokeHost = "172.17.0.9";
|
||||
running.invokePort = 32768;
|
||||
running.generation = 3;
|
||||
// A record saved before endpoints carried their account: the account it is stored under owns it.
|
||||
running.accountId = null;
|
||||
EndpointResource starting = endpoint("Creating", "starting");
|
||||
starting.accountId = DEFAULT_ACCOUNT;
|
||||
EndpointResource failed = endpoint("Failed", "failed");
|
||||
failed.failureReason = "Container did not pass /ping health check";
|
||||
endpoints.putForAccount(OTHER_ACCOUNT, "us-east-1::running", running);
|
||||
endpoints.putForAccount(DEFAULT_ACCOUNT, "us-east-1::starting", starting);
|
||||
endpoints.putForAccount(OTHER_ACCOUNT, "us-east-1::failed", failed);
|
||||
endpoints.putForAccount(OTHER_ACCOUNT, "us-east-1::deleting", endpoint("Deleting", "deleting"));
|
||||
clearInvocations(raw);
|
||||
|
||||
service.restorePersistedRuntime();
|
||||
|
||||
EndpointResource restored = endpoints.getForAccount(OTHER_ACCOUNT, "us-east-1::running").orElseThrow();
|
||||
assertEquals("Creating", restored.endpointStatus);
|
||||
assertNull(restored.containerId);
|
||||
assertNull(restored.invokeHost);
|
||||
assertEquals(0, restored.invokePort);
|
||||
assertEquals(4, restored.generation);
|
||||
verify(raw).put(OTHER_ACCOUNT + "/us-east-1::running", restored);
|
||||
assertEquals("Creating",
|
||||
endpoints.getForAccount(DEFAULT_ACCOUNT, "us-east-1::starting").orElseThrow().endpointStatus);
|
||||
verify(raw).put(eq(DEFAULT_ACCOUNT + "/us-east-1::starting"), any());
|
||||
EndpointResource stillFailed = endpoints.getForAccount(OTHER_ACCOUNT, "us-east-1::failed").orElseThrow();
|
||||
assertEquals("Failed", stillFailed.endpointStatus);
|
||||
assertEquals("Container did not pass /ping health check", stillFailed.failureReason);
|
||||
assertTrue(endpoints.getForAccount(OTHER_ACCOUNT, "us-east-1::deleting").isEmpty());
|
||||
|
||||
ArgumentCaptor<EndpointResource> started = ArgumentCaptor.forClass(EndpointResource.class);
|
||||
verify(manager, times(2)).startEndpointAsync(started.capture(), eq(service));
|
||||
assertEquals(Map.of("running", OTHER_ACCOUNT, "starting", DEFAULT_ACCOUNT), started.getAllValues().stream()
|
||||
.collect(Collectors.toMap(endpoint -> endpoint.endpointName, endpoint -> endpoint.accountId)));
|
||||
verify(manager).stopEndpoint(argThat(endpoint -> "deleting".equals(endpoint.endpointName)));
|
||||
}
|
||||
|
||||
/** One endpoint that cannot be restored leaves the others to restore, and its failure is thrown at the end. */
|
||||
@Test
|
||||
void anEndpointThatCannotBeRestoredLeavesTheOthersToRestore() {
|
||||
AccountAwareStorageBackend<EndpointResource> endpoints =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, DEFAULT_ACCOUNT);
|
||||
SageMakerEndpointManager manager = mock(SageMakerEndpointManager.class);
|
||||
SageMakerService service = restoringService(endpoints, manager);
|
||||
endpoints.putForAccount(OTHER_ACCOUNT, "us-east-1::first", endpoint("InService", "first"));
|
||||
endpoints.putForAccount(OTHER_ACCOUNT, "us-east-1::second", endpoint("InService", "second"));
|
||||
IllegalStateException cause = new IllegalStateException("worker pool shut down");
|
||||
doThrow(cause).when(manager)
|
||||
.startEndpointAsync(argThat(endpoint -> "first".equals(endpoint.endpointName)), any());
|
||||
|
||||
IllegalStateException thrown = assertThrows(IllegalStateException.class, service::restorePersistedRuntime);
|
||||
|
||||
assertEquals("Could not restore SageMaker endpoint first of account " + OTHER_ACCOUNT, thrown.getMessage());
|
||||
assertSame(cause, thrown.getCause());
|
||||
verify(manager).startEndpointAsync(argThat(endpoint -> "second".equals(endpoint.endpointName)), eq(service));
|
||||
}
|
||||
|
||||
/**
|
||||
* A start worker runs with a copy of the endpoint, so an UpdateEndpoint while a restored endpoint is starting
|
||||
* supersedes the restore's start: its result is discarded, not published over the update.
|
||||
*/
|
||||
@Test
|
||||
void anUpdateSupersedesTheStartOfARestoredEndpoint() throws Exception {
|
||||
AccountAwareStorageBackend<EndpointResource> endpoints =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, DEFAULT_ACCOUNT);
|
||||
InMemoryStorage<String, EndpointConfigResource> configs = new InMemoryStorage<>();
|
||||
configs.put("us-east-1::demo-cfg", endpointConfig("demo-cfg", "demo"));
|
||||
SageMakerEndpointManager manager = mock(SageMakerEndpointManager.class);
|
||||
SageMakerService service = new SageMakerService(new InMemoryStorage<String, ModelResource>(), configs,
|
||||
endpoints, new InMemoryStorage<String, TrainingJobResource>(),
|
||||
new RegionResolver("us-east-1", DEFAULT_ACCOUNT), mapper, manager, mock(SageMakerTrainingRunner.class));
|
||||
EndpointResource stored = endpoint("InService");
|
||||
stored.accountId = DEFAULT_ACCOUNT;
|
||||
endpoints.putForAccount(DEFAULT_ACCOUNT, "us-east-1::demo-ep", stored);
|
||||
service.restorePersistedRuntime();
|
||||
ArgumentCaptor<EndpointResource> restoreRun = ArgumentCaptor.forClass(EndpointResource.class);
|
||||
verify(manager).startEndpointAsync(restoreRun.capture(), eq(service));
|
||||
|
||||
service.updateEndpoint(mapper.readTree("""
|
||||
{"EndpointName":"demo-ep","EndpointConfigName":"demo-cfg"}"""), "us-east-1");
|
||||
restoreRun.getValue().endpointStatus = "InService";
|
||||
restoreRun.getValue().invokeHost = "172.17.0.9";
|
||||
|
||||
assertFalse(service.finalizeEndpointStart(restoreRun.getValue()));
|
||||
EndpointResource current = endpoints.getForAccount(DEFAULT_ACCOUNT, "us-east-1::demo-ep").orElseThrow();
|
||||
assertEquals("Creating", current.endpointStatus);
|
||||
assertNull(current.invokeHost);
|
||||
}
|
||||
|
||||
/** A start publishes its own fields onto the stored endpoint, keeping what was written to it meanwhile. */
|
||||
@Test
|
||||
void aStartsResultKeepsTagsAddedWhileItRan() {
|
||||
WorkerFixture fixture = workerFixture();
|
||||
fixture.endpoints().getForAccount(OTHER_ACCOUNT, "us-east-1::demo-ep").orElseThrow().tags.put("team", "ml");
|
||||
EndpointResource run = endpoint("InService");
|
||||
run.invokeHost = "172.17.0.9";
|
||||
run.invokePort = 32768;
|
||||
|
||||
assertTrue(fixture.service().finalizeEndpointStart(run));
|
||||
|
||||
EndpointResource current = fixture.endpoints().getForAccount(OTHER_ACCOUNT, "us-east-1::demo-ep").orElseThrow();
|
||||
assertEquals("InService", current.endpointStatus);
|
||||
assertEquals("172.17.0.9", current.invokeHost);
|
||||
assertEquals(32768, current.invokePort);
|
||||
assertEquals(Map.of("team", "ml"), current.tags);
|
||||
}
|
||||
|
||||
/**
|
||||
* A record from before stores were account-scoped is moved into the default account, not copied there: a second
|
||||
* restart restores it once, and a deleting one is gone for good.
|
||||
*/
|
||||
@Test
|
||||
void aRecordFromBeforeAccountScopedStoresIsMovedNotCopied() {
|
||||
InMemoryStorage<String, EndpointResource> raw = new InMemoryStorage<>();
|
||||
AccountAwareStorageBackend<EndpointResource> endpoints =
|
||||
new AccountAwareStorageBackend<>(raw, null, DEFAULT_ACCOUNT);
|
||||
SageMakerEndpointManager manager = mock(SageMakerEndpointManager.class);
|
||||
SageMakerService service = restoringService(endpoints, manager);
|
||||
EndpointResource legacy = endpoint("InService", "legacy");
|
||||
legacy.accountId = null;
|
||||
raw.put("us-east-1::legacy", legacy);
|
||||
EndpointResource gone = endpoint("Deleting", "gone");
|
||||
gone.accountId = null;
|
||||
raw.put("us-east-1::gone", gone);
|
||||
|
||||
service.restorePersistedRuntime();
|
||||
service.restorePersistedRuntime();
|
||||
|
||||
assertEquals(Set.of(DEFAULT_ACCOUNT + "/us-east-1::legacy"), raw.keys());
|
||||
verify(manager, times(2)).startEndpointAsync(argThat(endpoint -> "legacy".equals(endpoint.endpointName)),
|
||||
eq(service));
|
||||
assertEquals(3, endpoints.getForAccount(DEFAULT_ACCOUNT, "us-east-1::legacy").orElseThrow().generation);
|
||||
}
|
||||
|
||||
private SageMakerService restoringService(AccountAwareStorageBackend<EndpointResource> endpoints,
|
||||
SageMakerEndpointManager manager) {
|
||||
return new SageMakerService(new InMemoryStorage<String, ModelResource>(),
|
||||
new InMemoryStorage<String, EndpointConfigResource>(), endpoints,
|
||||
new InMemoryStorage<String, TrainingJobResource>(), new RegionResolver("us-east-1", DEFAULT_ACCOUNT),
|
||||
mapper, manager, mock(SageMakerTrainingRunner.class));
|
||||
}
|
||||
|
||||
private static EndpointResource endpoint(String status, String name) {
|
||||
EndpointResource endpoint = endpoint(status);
|
||||
endpoint.endpointName = name;
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
private record WorkerFixture(SageMakerService service,
|
||||
AccountAwareStorageBackend<EndpointResource> endpoints,
|
||||
AccountAwareStorageBackend<TrainingJobResource> jobs) {
|
||||
|
||||
Reference in new issue
Block a user