diff --git a/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java index 901efb6091..abc87b6f3e 100644 --- a/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java +++ b/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java @@ -72,6 +72,27 @@ public class AccountAwareStorageBackend implements StorageBackend return new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, defaultAccountId); } + /** + * Reads {@code key} in {@code accountId}, for a caller outside any request (an async worker) + * that knows the account owning the resource. A store that is not account-aware, or a null + * {@code accountId}, falls back to {@link StorageBackend#get}. + */ + public static Optional getInAccount(StorageBackend store, String accountId, String key) { + if (accountId != null && store instanceof AccountAwareStorageBackend aware) { + return aware.getForAccount(accountId, key); + } + return store.get(key); + } + + /** Writes {@code value} in {@code accountId}; the counterpart of {@link #getInAccount}. */ + public static void putInAccount(StorageBackend store, String accountId, String key, V value) { + if (accountId != null && store instanceof AccountAwareStorageBackend aware) { + aware.putForAccount(accountId, key, value); + } else { + store.put(key, value); + } + } + @Override public void put(String key, V value) { String account = prefix(); diff --git a/src/main/java/io/floci/aws/services/iot/IotService.java b/src/main/java/io/floci/aws/services/iot/IotService.java index 19dacab817..8ed9552fec 100644 --- a/src/main/java/io/floci/aws/services/iot/IotService.java +++ b/src/main/java/io/floci/aws/services/iot/IotService.java @@ -79,6 +79,8 @@ import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Pattern; +import static io.floci.aws.core.storage.AccountAwareStorageBackend.getInAccount; + @ApplicationScoped public class IotService { @@ -539,7 +541,7 @@ public class IotService { } CertificateLocation known = certificateLocations.get(certificateId); if (known != null) { - Optional current = getForAccount(certificateStore, known.accountId(), known.key()); + Optional current = getInAccount(certificateStore, known.accountId(), known.key()); if (current.isPresent()) { return Optional.of(new RegisteredDevice(known.accountId(), regionOfCertificateKey(known.key()), current.get())); } @@ -551,7 +553,7 @@ public class IotService { if (location == null) { return Optional.empty(); } - return getForAccount(certificateStore, location.accountId(), location.key()) + return getInAccount(certificateStore, location.accountId(), location.key()) .map(certificate -> new RegisteredDevice(location.accountId(), regionOfCertificateKey(location.key()), certificate)); } @@ -631,10 +633,10 @@ public class IotService { String prefix = "policy-attachment:" + region + ":"; return keysForAccount(policyAttachmentStore, accountId).stream() .filter(key -> key.startsWith(prefix)) - .filter(key -> getForAccount(policyAttachmentStore, accountId, key).orElse(Set.of()).contains(certificateArn)) + .filter(key -> getInAccount(policyAttachmentStore, accountId, key).orElse(Set.of()).contains(certificateArn)) .map(key -> key.substring(prefix.length())) .sorted() - .map(policyName -> getForAccount(policyStore, accountId, policyKey(region, policyName))) + .map(policyName -> getInAccount(policyStore, accountId, policyKey(region, policyName))) .flatMap(Optional::stream) .map(IotPolicy::getPolicyDocument) .filter(Objects::nonNull) @@ -648,9 +650,9 @@ public class IotService { */ private Map connectionVariables(RegisteredDevice device, String clientId, String sourceIp, String domainName) { Map variables = basicConnectionVariables(clientId, sourceIp, domainName); - Optional thing = getForAccount(thingStore, device.accountId(), thingKey(device.region(), clientId)); + Optional thing = getInAccount(thingStore, device.accountId(), thingKey(device.region(), clientId)); boolean attached = thing.isPresent() - && getForAccount(thingPrincipalStore, device.accountId(), thingPrincipalKey(device.region(), clientId)) + && getInAccount(thingPrincipalStore, device.accountId(), thingPrincipalKey(device.region(), clientId)) .orElse(Set.of()).contains(device.certificate().getCertificateArn()); variables.put("iot:Connection.Thing.IsAttached", Boolean.toString(attached)); if (attached) { @@ -686,10 +688,6 @@ public class IotService { .toList(); } - private static Optional getForAccount(StorageBackend store, String accountId, String key) { - return store instanceof AccountAwareStorageBackend aware ? aware.getForAccount(accountId, key) : store.get(key); - } - private static Set keysForAccount(StorageBackend store, String accountId) { return store instanceof AccountAwareStorageBackend aware ? aware.keysForAccount(accountId) : store.keys(); } diff --git a/src/main/java/io/floci/aws/services/kinesis/KinesisService.java b/src/main/java/io/floci/aws/services/kinesis/KinesisService.java index 49882da9b7..17f61713c7 100644 --- a/src/main/java/io/floci/aws/services/kinesis/KinesisService.java +++ b/src/main/java/io/floci/aws/services/kinesis/KinesisService.java @@ -40,6 +40,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Pattern; +import static io.floci.aws.core.storage.AccountAwareStorageBackend.putInAccount; + @ApplicationScoped public class KinesisService implements ResourceProvider { private static final Logger LOG = Logger.getLogger(KinesisService.class); @@ -1030,19 +1032,11 @@ public class KinesisService implements ResourceProvider { putRecordAppendHook.run(); KinesisRecord record = new KinesisRecord(data, partitionKey, sequenceNumber, clock.instant()); shard.addRecord(record); - persistStream(accountId, key, current); + putInAccount(store, accountId, key, current); return new PutRecordResult(sequenceNumber, shard.getShardId()); } } - private void persistStream(String accountId, String key, KinesisStream stream) { - if (accountId != null && store instanceof AccountAwareStorageBackend aware) { - aware.putForAccount(accountId, key, stream); - } else { - store.put(key, stream); - } - } - public String getShardIterator(String streamName, String shardId, String type, String sequenceNumber, String region) { return getShardIterator(streamName, shardId, type, sequenceNumber, null, region); } diff --git a/src/main/java/io/floci/aws/services/sagemaker/SageMakerService.java b/src/main/java/io/floci/aws/services/sagemaker/SageMakerService.java index 275c526465..3d910ad470 100644 --- a/src/main/java/io/floci/aws/services/sagemaker/SageMakerService.java +++ b/src/main/java/io/floci/aws/services/sagemaker/SageMakerService.java @@ -33,6 +33,9 @@ import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Function; +import static io.floci.aws.core.storage.AccountAwareStorageBackend.getInAccount; +import static io.floci.aws.core.storage.AccountAwareStorageBackend.putInAccount; + @ApplicationScoped public class SageMakerService { private static final Logger LOG = Logger.getLogger(SageMakerService.class); @@ -486,10 +489,11 @@ public class SageMakerService { } public ModelResource modelForEndpoint(EndpointResource ep) { - EndpointConfigResource cfg = endpointConfig(ep.region, ep.endpointConfigName) + EndpointConfigResource cfg = getInAccount(endpointConfigStore, ep.accountId, regionKey(ep.region, ep.endpointConfigName)) .orElseThrow(() -> validation("Could not find endpoint configuration \"" + ep.endpointConfigName + "\".")); String modelName = String.valueOf(cfg.productionVariants.get(0).get("ModelName")); - return model(ep.region, modelName).orElseThrow(() -> validation("Could not find model \"" + modelName + "\".")); + return getInAccount(modelStore, ep.accountId, regionKey(ep.region, modelName)) + .orElseThrow(() -> validation("Could not find model \"" + modelName + "\".")); } /** @@ -499,12 +503,13 @@ public class SageMakerService { * of publishing it, because the endpoint it belongs to is gone or has moved on. */ synchronized boolean finalizeEndpointStart(EndpointResource ep) { - EndpointResource current = endpointStore.get(regionKey(ep.region, ep.endpointName)).orElse(null); + String key = regionKey(ep.region, ep.endpointName); + EndpointResource current = getInAccount(endpointStore, ep.accountId, key).orElse(null); if (current == null || current.generation != ep.generation) { return false; } ep.lastModifiedTime = nowMillis(); - endpointStore.put(regionKey(ep.region, ep.endpointName), ep); + putInAccount(endpointStore, ep.accountId, key, ep); return true; } @@ -516,14 +521,14 @@ public class SageMakerService { */ public synchronized boolean updateTrainingJob(TrainingJobResource job) { String key = regionKey(job.region, job.trainingJobName); - TrainingJobResource current = trainingJobStore.get(key).orElse(null); + TrainingJobResource current = getInAccount(trainingJobStore, job.accountId, key).orElse(null); if (current == null || !Objects.equals(current.trainingJobArn, job.trainingJobArn) || current.creationTime != job.creationTime) { LOG.debugv("SageMaker training job {0} is no longer the stored job; discarding its run update", job.trainingJobName); return false; } - trainingJobStore.put(key, job); + putInAccount(trainingJobStore, job.accountId, key, job); return true; } diff --git a/src/test/java/io/floci/aws/core/storage/AccountAwareStorageBackendTest.java b/src/test/java/io/floci/aws/core/storage/AccountAwareStorageBackendTest.java index 3af9fdb408..881acdfa2d 100644 --- a/src/test/java/io/floci/aws/core/storage/AccountAwareStorageBackendTest.java +++ b/src/test/java/io/floci/aws/core/storage/AccountAwareStorageBackendTest.java @@ -33,6 +33,49 @@ import static org.mockito.Mockito.when; class AccountAwareStorageBackendTest { + @Test + void getInAccountReadsTheNamedAccountOutsideAnyRequest() { + InMemoryStorage raw = new InMemoryStorage<>(); + AccountAwareStorageBackend storage = new AccountAwareStorageBackend<>(raw, null, "000000000000"); + raw.put("000000000000/resource", "default"); + raw.put("111111111111/resource", "owned"); + + assertEquals(Optional.of("owned"), AccountAwareStorageBackend.getInAccount(storage, "111111111111", "resource")); + assertEquals(Optional.empty(), AccountAwareStorageBackend.getInAccount(storage, "222222222222", "resource")); + } + + @Test + void putInAccountWritesTheNamedAccountOutsideAnyRequest() { + InMemoryStorage raw = new InMemoryStorage<>(); + AccountAwareStorageBackend storage = new AccountAwareStorageBackend<>(raw, null, "000000000000"); + + AccountAwareStorageBackend.putInAccount(storage, "111111111111", "resource", "owned"); + + assertEquals(Optional.of("owned"), raw.get("111111111111/resource")); + assertEquals(Optional.empty(), raw.get("000000000000/resource")); + } + + @Test + void inAccountHelpersUseTheAmbientAccountWithoutAnAccountId() { + InMemoryStorage raw = new InMemoryStorage<>(); + AccountAwareStorageBackend storage = new AccountAwareStorageBackend<>(raw, null, "000000000000"); + + AccountAwareStorageBackend.putInAccount(storage, null, "resource", "ambient"); + + assertEquals(Optional.of("ambient"), raw.get("000000000000/resource")); + assertEquals(Optional.of("ambient"), AccountAwareStorageBackend.getInAccount(storage, null, "resource")); + } + + @Test + void inAccountHelpersUseAPlainStoreAsIs() { + InMemoryStorage plain = new InMemoryStorage<>(); + + AccountAwareStorageBackend.putInAccount(plain, "111111111111", "resource", "value"); + + assertEquals(Set.of("resource"), plain.keys()); + assertEquals(Optional.of("value"), AccountAwareStorageBackend.getInAccount(plain, "111111111111", "resource")); + } + @Test void accountIdReturnsDefaultOutsideRequestScope() { AccountAwareStorageBackend storage = diff --git a/src/test/java/io/floci/aws/services/sagemaker/SageMakerServiceTest.java b/src/test/java/io/floci/aws/services/sagemaker/SageMakerServiceTest.java index 0bcc7a9eb4..15dee16c67 100644 --- a/src/test/java/io/floci/aws/services/sagemaker/SageMakerServiceTest.java +++ b/src/test/java/io/floci/aws/services/sagemaker/SageMakerServiceTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.services.sagemaker.model.SageMakerEntities.EndpointConfigResource; import io.floci.aws.services.sagemaker.model.SageMakerEntities.EndpointResource; @@ -12,7 +13,9 @@ import io.floci.aws.services.sagemaker.model.SageMakerEntities.TrainingJobResour import org.junit.jupiter.api.Test; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -21,6 +24,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; class SageMakerServiceTest { + private static final String DEFAULT_ACCOUNT = "000000000000"; + private static final String OTHER_ACCOUNT = "111111111111"; + private final ObjectMapper mapper = new ObjectMapper(); @Test @@ -323,6 +329,112 @@ class SageMakerServiceTest { assertEquals("InProgress", describeStatus(service, "reset-job")); } + @Test + void endpointWorkerStartsTheModelOfTheEndpointsOwnAccount() { + WorkerFixture fixture = workerFixture(); + assertEquals("image-of-account-111", + fixture.service().modelForEndpoint(endpoint("Creating")).primaryContainer.get("Image")); + } + + @Test + void endpointWorkerFindsAConfigThatOnlyItsOwnAccountHas() { + WorkerFixture fixture = workerFixture(); + EndpointResource endpoint = endpoint("Creating"); + endpoint.endpointConfigName = "solo-cfg"; + assertEquals("image-of-account-111", + fixture.service().modelForEndpoint(endpoint).primaryContainer.get("Image")); + } + + @Test + void endpointWorkerSavesItsOutcomeInTheEndpointsOwnAccount() { + WorkerFixture fixture = workerFixture(); + assertTrue(fixture.service().finalizeEndpointStart(endpoint("InService"))); + assertEquals("InService", + fixture.endpoints().getForAccount(OTHER_ACCOUNT, "us-east-1::demo-ep").orElseThrow().endpointStatus); + } + + @Test + void trainingWorkerSavesItsOutcomeInTheJobsOwnAccount() { + WorkerFixture fixture = workerFixture(); + assertTrue(fixture.service().updateTrainingJob(trainingJob("Completed"))); + assertEquals("Completed", + fixture.jobs().getForAccount(OTHER_ACCOUNT, "us-east-1::demo-job").orElseThrow().trainingJobStatus); + } + + private record WorkerFixture(SageMakerService service, + AccountAwareStorageBackend endpoints, + AccountAwareStorageBackend jobs) { + } + + /** + * #8373: the endpoint and training workers call back on their own threads, outside any request, + * where an account-aware store reads the default account. Stores with no request context stand + * in for that thread. Account 111 owns the resources; the default account holds a same-named + * endpoint config and model with a different image, and nothing named {@code solo-cfg}. + */ + private WorkerFixture workerFixture() { + AccountAwareStorageBackend models = + new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, DEFAULT_ACCOUNT); + AccountAwareStorageBackend configs = + new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, DEFAULT_ACCOUNT); + AccountAwareStorageBackend endpoints = + new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, DEFAULT_ACCOUNT); + AccountAwareStorageBackend jobs = + new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, DEFAULT_ACCOUNT); + SageMakerService service = new SageMakerService(models, configs, endpoints, jobs, + new RegionResolver("us-east-1", DEFAULT_ACCOUNT), mapper, + mock(SageMakerEndpointManager.class), mock(SageMakerTrainingRunner.class)); + + models.putForAccount(DEFAULT_ACCOUNT, "us-east-1::demo", model("demo", "image-of-default-account")); + configs.putForAccount(DEFAULT_ACCOUNT, "us-east-1::demo-cfg", endpointConfig("demo-cfg", "demo")); + models.putForAccount(OTHER_ACCOUNT, "us-east-1::demo", model("demo", "image-of-account-111")); + configs.putForAccount(OTHER_ACCOUNT, "us-east-1::demo-cfg", endpointConfig("demo-cfg", "demo")); + models.putForAccount(OTHER_ACCOUNT, "us-east-1::solo", model("solo", "image-of-account-111")); + configs.putForAccount(OTHER_ACCOUNT, "us-east-1::solo-cfg", endpointConfig("solo-cfg", "solo")); + endpoints.putForAccount(OTHER_ACCOUNT, "us-east-1::demo-ep", endpoint("Creating")); + jobs.putForAccount(OTHER_ACCOUNT, "us-east-1::demo-job", trainingJob("InProgress")); + return new WorkerFixture(service, endpoints, jobs); + } + + private static ModelResource model(String name, String image) { + ModelResource model = new ModelResource(); + model.modelName = name; + model.region = "us-east-1"; + model.primaryContainer.put("Image", image); + return model; + } + + private static EndpointConfigResource endpointConfig(String name, String modelName) { + EndpointConfigResource config = new EndpointConfigResource(); + config.endpointConfigName = name; + config.region = "us-east-1"; + config.productionVariants.add(new HashMap<>(Map.of("VariantName", "v", "ModelName", modelName))); + return config; + } + + /** A fresh object each call, so a check of the stored record proves a write rather than a shared reference. */ + private static EndpointResource endpoint(String status) { + EndpointResource endpoint = new EndpointResource(); + endpoint.endpointName = "demo-ep"; + endpoint.endpointConfigName = "demo-cfg"; + endpoint.endpointStatus = status; + endpoint.region = "us-east-1"; + endpoint.accountId = OTHER_ACCOUNT; + endpoint.generation = 1; + return endpoint; + } + + private static TrainingJobResource trainingJob(String status) { + TrainingJobResource job = new TrainingJobResource(); + job.trainingJobName = "demo-job"; + job.trainingJobArn = "arn:aws:sagemaker:us-east-1:" + OTHER_ACCOUNT + ":training-job/demo-job"; + job.trainingJobStatus = status; + job.creationTime = 1000L; + job.region = "us-east-1"; + job.accountId = OTHER_ACCOUNT; + return job; + } + private String describeStatus(SageMakerService service, String name) throws Exception { return service.describeTrainingJob(mapper.readTree("{\"TrainingJobName\":\"" + name + "\"}"), "us-east-1") .path("TrainingJobStatus").asText();