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
@@ -86,6 +86,8 @@ Only the accelerator is substituted. An instance type also implies vCPU and memo
|
||||
|
||||
Endpoint containers are CPU-only for now; the `gpu` settings above apply to training jobs.
|
||||
|
||||
Floci stops endpoint containers when it shuts down. With persistent storage, each endpoint that was `InService` or still `Creating` goes back to `Creating` when Floci starts again. Its container is started afresh from its endpoint config and model, `ModelDataUrl` included, and the endpoint reports `InService` once `/ping` answers. If the container can't be started, the endpoint reports `Failed` with the reason, for instance when its model was deleted. A container a crash left running is replaced, a `Failed` endpoint stays as it is, and one a crash left `Deleting` is deleted with its container. Endpoint containers are named after the endpoint's account, Region and name, so endpoints of the same name in two accounts or Regions don't share one.
|
||||
|
||||
## Examples
|
||||
|
||||
```python
|
||||
|
||||
@@ -107,6 +107,15 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes {@code key} in {@code accountId}; the counterpart of {@link #getInAccount}. */
|
||||
public static <V> void deleteInAccount(StorageBackend<String, V> store, String accountId, String key) {
|
||||
if (accountId != null && store instanceof AccountAwareStorageBackend<V> aware) {
|
||||
aware.deleteForAccount(accountId, key);
|
||||
} else {
|
||||
store.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void put(String key, V value) {
|
||||
String account = prefix();
|
||||
|
||||
@@ -43,6 +43,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.quarkus.runtime.Quarkus;
|
||||
@@ -102,6 +103,7 @@ public class EmulatorLifecycle {
|
||||
private final NeptuneProxyManager neptuneProxyManager;
|
||||
private final RabbitMqManager rabbitMqManager;
|
||||
private final FlinkContainerManager flinkContainerManager;
|
||||
private final SageMakerService sageMakerService;
|
||||
private final RdsService rdsService;
|
||||
private final TimestreamInfluxDbService timestreamInfluxDbService;
|
||||
private final ElbV2Service elbV2Service;
|
||||
@@ -149,6 +151,7 @@ public class EmulatorLifecycle {
|
||||
NeptuneProxyManager neptuneProxyManager,
|
||||
RabbitMqManager rabbitMqManager,
|
||||
FlinkContainerManager flinkContainerManager,
|
||||
SageMakerService sageMakerService,
|
||||
RdsService rdsService,
|
||||
TimestreamInfluxDbService timestreamInfluxDbService,
|
||||
ElbV2Service elbV2Service,
|
||||
@@ -193,6 +196,7 @@ public class EmulatorLifecycle {
|
||||
this.neptuneProxyManager = neptuneProxyManager;
|
||||
this.rabbitMqManager = rabbitMqManager;
|
||||
this.flinkContainerManager = flinkContainerManager;
|
||||
this.sageMakerService = sageMakerService;
|
||||
this.rdsService = rdsService;
|
||||
this.timestreamInfluxDbService = timestreamInfluxDbService;
|
||||
this.elbV2Service = elbV2Service;
|
||||
@@ -294,6 +298,14 @@ public class EmulatorLifecycle {
|
||||
return null;
|
||||
});
|
||||
}
|
||||
if (config.services().sagemaker().enabled()) {
|
||||
// Restores every endpoint it can and throws the ones it could not, which must not stop Floci starting.
|
||||
try {
|
||||
sageMakerService.restorePersistedRuntime();
|
||||
} catch (RuntimeException e) {
|
||||
LOG.error("Failed to restore persisted SageMaker endpoints at startup", e);
|
||||
}
|
||||
}
|
||||
if (config.services().elbv2().enabled()) {
|
||||
elbV2Service.restorePersistedRuntime();
|
||||
}
|
||||
|
||||
@@ -57,6 +57,7 @@ public class SageMakerEndpointManager implements ContainerTeardown, Resettable {
|
||||
private final S3Service s3Service;
|
||||
// Replaced by afterReset() after a state reset, whose container teardown shuts this pool down.
|
||||
private volatile ExecutorService executor = Executors.newCachedThreadPool();
|
||||
// Keyed by account, Region and name, which together identify an endpoint.
|
||||
private final ConcurrentHashMap<String, String> containers = new ConcurrentHashMap<>();
|
||||
private final HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
|
||||
|
||||
@@ -87,7 +88,7 @@ public class SageMakerEndpointManager implements ContainerTeardown, Resettable {
|
||||
if (image == null) {
|
||||
throw new IllegalArgumentException("PrimaryContainer.Image is required");
|
||||
}
|
||||
String name = ContainerStorageHelper.dockerName(config, "sagemaker-endpoint-" + endpoint.endpointName);
|
||||
String name = containerName(config, endpoint.accountId, endpoint.region, endpoint.endpointName);
|
||||
lifecycleManager.removeIfExists(name);
|
||||
ContainerBuilder.Builder builder = containerBuilder.newContainer(image)
|
||||
.withName(name)
|
||||
@@ -111,7 +112,7 @@ public class SageMakerEndpointManager implements ContainerTeardown, Resettable {
|
||||
endpoint.containerId = containerId;
|
||||
endpoint.invokeHost = ep.host();
|
||||
endpoint.invokePort = ep.port();
|
||||
containers.put(endpoint.endpointName, containerId);
|
||||
containers.put(identity(endpoint), containerId);
|
||||
waitForPing(endpoint.invokeHost, endpoint.invokePort);
|
||||
endpoint.endpointStatus = "InService";
|
||||
endpoint.failureReason = null;
|
||||
@@ -139,19 +140,40 @@ public class SageMakerEndpointManager implements ContainerTeardown, Resettable {
|
||||
}
|
||||
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);
|
||||
String containerId = endpoint.containerId != null ? endpoint.containerId : containers.remove(identity(endpoint));
|
||||
if (containerId != null) {
|
||||
lifecycleManager.stopAndRemove(containerId, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops and removes the endpoint's container: the one its record names, else the one a start of this process
|
||||
* brought up, else any container of the endpoint's name, which a crash can leave behind with no record of it.
|
||||
*/
|
||||
public void stopEndpoint(EndpointResource endpoint) {
|
||||
String containerId = endpoint.containerId != null ? endpoint.containerId : containers.remove(endpoint.endpointName);
|
||||
String tracked = containers.remove(identity(endpoint));
|
||||
String containerId = endpoint.containerId != null ? endpoint.containerId : tracked;
|
||||
if (containerId != null) {
|
||||
lifecycleManager.stopAndRemove(containerId, null);
|
||||
} else {
|
||||
lifecycleManager.removeIfExists(containerName(config, endpoint.accountId, endpoint.region,
|
||||
endpoint.endpointName));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The endpoint's container name. An endpoint is identified by its account, Region and name, so endpoints of the
|
||||
* same name in two accounts or Regions get containers of their own.
|
||||
*/
|
||||
static String containerName(EmulatorConfig config, String accountId, String region, String endpointName) {
|
||||
return ContainerStorageHelper.dockerName(config,
|
||||
"sagemaker-endpoint-" + accountId + "-" + region + "-" + endpointName);
|
||||
}
|
||||
|
||||
private static String identity(EndpointResource endpoint) {
|
||||
return endpoint.accountId + "/" + endpoint.region + "/" + endpoint.endpointName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void stopManagedContainers() {
|
||||
containers.forEach((name, id) -> lifecycleManager.stopAndRemove(id, null));
|
||||
|
||||
@@ -80,9 +80,11 @@ public class SageMakerRuntimeController {
|
||||
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());
|
||||
// A refused connection, as to an endpoint whose container is gone, carries no message.
|
||||
String message = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName();
|
||||
LOG.warnv("SageMaker endpoint invocation failed for {0}: {1}", endpointName, message);
|
||||
return Response.status(424).type(MediaType.APPLICATION_JSON)
|
||||
.entity(Map.of("__type", "ModelError", "message", e.getMessage())).build();
|
||||
.entity(Map.of("__type", "ModelError", "message", message)).build();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ import io.floci.aws.core.common.Base64Url;
|
||||
import io.floci.aws.core.common.EpochSeconds;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.SmithyValidationErrors;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend.AccountEntry;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.sagemaker.model.SageMakerEntities.EndpointConfigResource;
|
||||
@@ -35,6 +37,7 @@ import java.util.Optional;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static io.floci.aws.core.storage.AccountAwareStorageBackend.deleteInAccount;
|
||||
import static io.floci.aws.core.storage.AccountAwareStorageBackend.getInAccount;
|
||||
import static io.floci.aws.core.storage.AccountAwareStorageBackend.putInAccount;
|
||||
|
||||
@@ -266,7 +269,7 @@ public class SageMakerService {
|
||||
ep.tags = tagsFromList(request.path("Tags"));
|
||||
ep.generation = 1;
|
||||
endpointStore.put(regionKey(region, name), ep);
|
||||
endpointManager.startEndpointAsync(ep, this);
|
||||
endpointManager.startEndpointAsync(startRun(ep), this);
|
||||
ObjectNode out = mapper.createObjectNode();
|
||||
out.put("EndpointArn", ep.endpointArn);
|
||||
return out;
|
||||
@@ -287,7 +290,7 @@ public class SageMakerService {
|
||||
ep.lastModifiedTime = nowMillis();
|
||||
ep.generation++;
|
||||
endpointStore.put(regionKey(region, name), ep);
|
||||
endpointManager.startEndpointAsync(ep, this);
|
||||
endpointManager.startEndpointAsync(startRun(ep), this);
|
||||
ObjectNode out = mapper.createObjectNode();
|
||||
out.put("EndpointArn", ep.endpointArn);
|
||||
return out;
|
||||
@@ -509,19 +512,113 @@ public class SageMakerService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Brings the persisted endpoints back after Floci restarts. Shutdown stops their containers
|
||||
* ({@link SageMakerEndpointManager#stopManagedContainers}), so an endpoint stored {@code InService}, or still
|
||||
* {@code Creating}, has nothing behind it. Each goes back to {@code Creating} and is started again from its
|
||||
* endpoint config and model, as {@code CreateEndpoint} starts one, which replaces a container a crash left
|
||||
* running: it reports {@code InService} once the container answers {@code /ping}, or {@code Failed} with the
|
||||
* reason. A {@code Failed} endpoint is left as it is, and one a crash left {@code Deleting} is deleted with its
|
||||
* container. Every endpoint is tried, and the ones that could not be restored are thrown together at the end.
|
||||
*/
|
||||
synchronized boolean finalizeEndpointStart(EndpointResource ep) {
|
||||
String key = regionKey(ep.region, ep.endpointName);
|
||||
EndpointResource current = getInAccount(endpointStore, ep.accountId, key).orElse(null);
|
||||
if (current == null || current.generation != ep.generation) {
|
||||
public synchronized void restorePersistedRuntime() {
|
||||
if (endpointStore instanceof AccountAwareStorageBackend<EndpointResource> aware) {
|
||||
// Records from before stores were account-scoped belong to the default account; move them there, so the
|
||||
// restore writes and deletes the records the store reads.
|
||||
aware.migrateLegacyEntries(regionResolver.getDefaultAccountId(), key -> true,
|
||||
ep -> regionKey(ep.region, ep.endpointName), ep -> true);
|
||||
}
|
||||
RuntimeException failure = null;
|
||||
for (AccountEntry<EndpointResource> entry : persistedEndpoints()) {
|
||||
EndpointResource ep = entry.value();
|
||||
try {
|
||||
restoreEndpoint(entry.accountId(), entry.key(), ep);
|
||||
} catch (RuntimeException e) {
|
||||
RuntimeException restoreFailure = new IllegalStateException("Could not restore SageMaker endpoint "
|
||||
+ ep.endpointName + " of account " + entry.accountId(), e);
|
||||
if (failure == null) {
|
||||
failure = restoreFailure;
|
||||
} else {
|
||||
failure.addSuppressed(restoreFailure);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private void restoreEndpoint(String accountId, String key, EndpointResource ep) {
|
||||
ep.accountId = accountId;
|
||||
if ("Failed".equals(ep.endpointStatus)) {
|
||||
return;
|
||||
}
|
||||
if ("Deleting".equals(ep.endpointStatus)) {
|
||||
endpointManager.stopEndpoint(ep);
|
||||
deleteInAccount(endpointStore, accountId, key);
|
||||
return;
|
||||
}
|
||||
ep.endpointStatus = "Creating";
|
||||
ep.failureReason = null;
|
||||
ep.containerId = null;
|
||||
ep.invokeHost = null;
|
||||
ep.invokePort = 0;
|
||||
ep.generation++;
|
||||
putInAccount(endpointStore, accountId, key, ep);
|
||||
endpointManager.startEndpointAsync(startRun(ep), this);
|
||||
}
|
||||
|
||||
private List<AccountEntry<EndpointResource>> persistedEndpoints() {
|
||||
if (endpointStore instanceof AccountAwareStorageBackend<EndpointResource> aware) {
|
||||
return aware.scanAllAccountEntries(key -> true);
|
||||
}
|
||||
return endpointStore.scan(key -> true).stream()
|
||||
.map(ep -> new AccountEntry<>(ep.accountId, regionKey(ep.region, ep.endpointName), ep))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* The endpoint a start worker runs with: a copy, so a later update or delete, which changes the stored record,
|
||||
* cannot change the generation the worker's result is checked against.
|
||||
*/
|
||||
private static EndpointResource startRun(EndpointResource ep) {
|
||||
EndpointResource run = new EndpointResource();
|
||||
run.endpointName = ep.endpointName;
|
||||
run.endpointArn = ep.endpointArn;
|
||||
run.endpointConfigName = ep.endpointConfigName;
|
||||
run.endpointStatus = ep.endpointStatus;
|
||||
run.failureReason = ep.failureReason;
|
||||
run.creationTime = ep.creationTime;
|
||||
run.lastModifiedTime = ep.lastModifiedTime;
|
||||
run.region = ep.region;
|
||||
run.accountId = ep.accountId;
|
||||
run.containerId = ep.containerId;
|
||||
run.invokeHost = ep.invokeHost;
|
||||
run.invokePort = ep.invokePort;
|
||||
run.generation = ep.generation;
|
||||
run.tags = new LinkedHashMap<>(ep.tags);
|
||||
return run;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists the result of an endpoint start (success or failure) unless a delete or a
|
||||
* newer start has superseded it since {@code run} 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. Only the start's
|
||||
* own fields are written onto the stored endpoint, so tags added meanwhile are kept.
|
||||
*/
|
||||
synchronized boolean finalizeEndpointStart(EndpointResource run) {
|
||||
String key = regionKey(run.region, run.endpointName);
|
||||
EndpointResource current = getInAccount(endpointStore, run.accountId, key).orElse(null);
|
||||
if (current == null || current.generation != run.generation) {
|
||||
return false;
|
||||
}
|
||||
ep.lastModifiedTime = nowMillis();
|
||||
putInAccount(endpointStore, ep.accountId, key, ep);
|
||||
current.endpointStatus = run.endpointStatus;
|
||||
current.failureReason = run.failureReason;
|
||||
current.containerId = run.containerId;
|
||||
current.invokeHost = run.invokeHost;
|
||||
current.invokePort = run.invokePort;
|
||||
current.lastModifiedTime = nowMillis();
|
||||
putInAccount(endpointStore, run.accountId, key, current);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -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