Light, fluffy, and always free - The AWS Local Emulator alternative
fix(elb): keep Classic load balancer health checks per account (#6666)
Jackson Price9fd057818142
diff --git a/docs/services/elb-classic.md b/docs/services/elb-classic.mdindex 1ab999301b..038e252328 100644--- a/docs/services/elb-classic.md+++ b/docs/services/elb-classic.md@@ -64,8 +64,8 @@ opened and no traffic is forwarded. Only the control plane and health checking a## Behavior Notes-- Load balancer state is persisted through Floci storage and health checking is restarted on- startup.+- Load balancer state is persisted through Floci storage, and on startup health checking is+ restarted for the load balancers of every account.- A new load balancer gets AWS's default health check (`TCP:80`, interval 30, timeout 5,unhealthy 2, healthy 10) and AWS's default attributes (cross-zone off, access log off,connection draining off with a 300 second timeout, 60 second idle timeout).@@ -75,6 +75,8 @@ opened and no traffic is forwarded. Only the control plane and health checking athe same port.- Between registration and the first successful check an instance reports `OutOfService` withreason code `ELB`, as it does on AWS.+- Health is tracked per account, so two accounts can each have a load balancer with the same name+ without either one changing the instance health the other reports.- An Auto Scaling group that names Classic load balancers in `LoadBalancerNames` has its instancesregistered and deregistered automatically, so a Terraform `min_elb_capacity` wait can besatisfied.diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthChecker.java b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthChecker.javaindex 2daec43fa8..1379be67dd 100644--- a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthChecker.java+++ b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthChecker.java@@ -17,6 +17,7 @@ import java.net.InetSocketAddress;import java.net.Socket;import java.net.URL;import java.util.Collection;+import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;@@ -60,10 +61,13 @@ public class ElbClassicHealthChecker implements Resettable {private final EmulatorConfig config;private final Ec2Service ec2Service;- // "region|lbName" → instanceId → state+ // "account|region|lbName" → instanceId → stateprivate final Map<String, Map<String, InstanceState>> states = new ConcurrentHashMap<>();- // "region|lbName" → Vert.x timer id- private final Map<String, Long> timers = new ConcurrentHashMap<>();+ // "account|region|lbName" → the periodic check armed for it+ private final Map<String, ArmedCheck> timers = new ConcurrentHashMap<>();++ /** A periodic check: its Vert.x timer and the tick that timer runs. */+ private record ArmedCheck(long id, Runnable tick) {}@Injectpublic ElbClassicHealthChecker(Vertx vertx, EmulatorConfig config, Ec2Service ec2Service) {@@ -72,12 +76,16 @@ public class ElbClassicHealthChecker implements Resettable {this.ec2Service = ec2Service;}- public static String key(String region, String loadBalancerName) {- return region + "|" + loadBalancerName;+ /**+ * A Classic name is unique only within one account and region, so two accounts can each have+ * a load balancer called {@code web}; without the account they would share one state and timer.+ */+ private static String key(ClassicLoadBalancer lb) {+ return lb.getAccountId() + "|" + lb.getRegion() + "|" + lb.getLoadBalancerName();}public void startMonitoring(ClassicLoadBalancer lb) {- String k = key(lb.getRegion(), lb.getLoadBalancerName());+ String k = key(lb);states.computeIfAbsent(k, x -> new ConcurrentHashMap<>());if (mock() || vertx == null) {return;@@ -85,26 +93,33 @@ public class ElbClassicHealthChecker implements Resettable {stopTimer(k);int interval = lb.getHealthCheck() != null && lb.getHealthCheck().getInterval() != null? lb.getHealthCheck().getInterval() : 30;- timers.put(k, vertx.setPeriodic(interval * 1000L, id -> probeAll(lb)));+ Runnable tick = () -> probeAll(lb);+ timers.put(k, new ArmedCheck(vertx.setPeriodic(interval * 1000L, id -> tick.run()), tick));+ }++ /**+ * Runs one tick of every armed periodic check now, probing what each timer would probe, so+ * tests need not wait out a check interval. The timers themselves keep their schedule.+ */+ void runArmedChecks() {+ List.copyOf(timers.values()).forEach(timer -> timer.tick().run());}- public void stopMonitoring(String region, String loadBalancerName) {- String k = key(region, loadBalancerName);+ public void stopMonitoring(ClassicLoadBalancer lb) {+ String k = key(lb);stopTimer(k);states.remove(k);}/** Re-arms the periodic timer after {@code ConfigureHealthCheck} changed the interval. */public void healthCheckChanged(ClassicLoadBalancer lb) {- if (states.containsKey(key(lb.getRegion(), lb.getLoadBalancerName()))) {+ if (states.containsKey(key(lb))) {startMonitoring(lb);}}public void registerInstances(ClassicLoadBalancer lb, Collection<String> instanceIds) {- Map<String, InstanceState> lbStates =- states.computeIfAbsent(key(lb.getRegion(), lb.getLoadBalancerName()),- k -> new ConcurrentHashMap<>());+ Map<String, InstanceState> lbStates = states.computeIfAbsent(key(lb), k -> new ConcurrentHashMap<>());for (String id : instanceIds) {lbStates.putIfAbsent(id, new InstanceState());}@@ -113,8 +128,8 @@ public class ElbClassicHealthChecker implements Resettable {}}- public void deregisterInstances(String region, String loadBalancerName, Collection<String> instanceIds) {- Map<String, InstanceState> lbStates = states.get(key(region, loadBalancerName));+ public void deregisterInstances(ClassicLoadBalancer lb, Collection<String> instanceIds) {+ Map<String, InstanceState> lbStates = states.get(key(lb));if (lbStates != null) {instanceIds.forEach(lbStates::remove);}@@ -127,11 +142,11 @@ public class ElbClassicHealthChecker implements Resettable {* live Classic load balancer reports between {@code RegisterInstancesWithLoadBalancer} and the* first successful check.*/- public InstanceHealth getHealth(String region, String loadBalancerName, String instanceId) {+ public InstanceHealth getHealth(ClassicLoadBalancer lb, String instanceId) {if (mock()) {return InstanceHealth.inService();}- Map<String, InstanceState> lbStates = states.get(key(region, loadBalancerName));+ Map<String, InstanceState> lbStates = states.get(key(lb));InstanceState s = lbStates != null ? lbStates.get(instanceId) : null;if (s == null || s.health == null) {return InstanceHealth.registering();@@ -142,7 +157,7 @@ public class ElbClassicHealthChecker implements Resettable {@Overridepublic void clear() {if (vertx != null) {- timers.values().forEach(vertx::cancelTimer);+ timers.values().forEach(timer -> vertx.cancelTimer(timer.id()));}timers.clear();states.clear();@@ -153,14 +168,14 @@ public class ElbClassicHealthChecker implements Resettable {}private void stopTimer(String k) {- Long timerId = timers.remove(k);- if (timerId != null && vertx != null) {- vertx.cancelTimer(timerId);+ ArmedCheck timer = timers.remove(k);+ if (timer != null && vertx != null) {+ vertx.cancelTimer(timer.id());}}private void probeAll(ClassicLoadBalancer lb) {- Map<String, InstanceState> lbStates = states.get(key(lb.getRegion(), lb.getLoadBalancerName()));+ Map<String, InstanceState> lbStates = states.get(key(lb));if (lbStates == null || lbStates.isEmpty()) {return;}diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.javaindex e569dc5604..dbfdf7b969 100644--- a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java+++ b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsRegionFacts;import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;import io.github.hectorvent.floci.core.storage.StorageBackedMap;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.acm.AcmService;@@ -57,14 +58,16 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {private final Ec2Service ec2Service;private final ElbClassicHealthChecker healthChecker;- private final StorageFactory storageFactory;private final EmulatorConfig config;private final RegionResolver regionResolver;private final IamService iamService;private final CertificateReferenceResolver certificates;- // region → load balancer name → record- private Map<String, Map<String, ClassicLoadBalancer>> loadBalancers = new ConcurrentHashMap<>();+ // region → load balancer name → record, in the calling account+ private final Map<String, Map<String, ClassicLoadBalancer>> loadBalancers;+ // The store behind loadBalancers, for the startup passes that must reach every account; null+ // without a StorageFactory, when loadBalancers is a plain in-memory map+ private final AccountAwareStorageBackend<Map<String, ClassicLoadBalancer>> loadBalancerStore;/** Serializes listener writes against each other; see {@link #createLoadBalancerListeners}. */private final Object listenerLock = new Object();@@ -94,51 +97,90 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {AcmService acmService) {this.ec2Service = ec2Service;this.healthChecker = healthChecker;- this.storageFactory = storageFactory;this.config = config;this.regionResolver = regionResolver;this.iamService = iamService;this.certificates = new CertificateReferenceResolver(iamService, acmService);+ this.loadBalancerStore = storageFactory != null+ ? storageFactory.create("elb", "elb-load-balancers.json",+ new TypeReference<Map<String, Map<String, ClassicLoadBalancer>>>() {})+ : null;+ this.loadBalancers = loadBalancerStore != null+ ? new StorageBackedMap<>(loadBalancerStore)+ : new ConcurrentHashMap<>();}@PostConstructvoid initializeStorage() {- if (storageFactory == null) {+ if (loadBalancerStore == null) {return;}- this.loadBalancers = new StorageBackedMap<>(storageFactory.create("elb", "elb-load-balancers.json",- new TypeReference<Map<String, Map<String, ClassicLoadBalancer>>>() {}));- for (Map.Entry<String, Map<String, ClassicLoadBalancer>> entry- : new ArrayList<>(loadBalancers.entrySet())) {- if (!(entry.getValue() instanceof ConcurrentHashMap)) {- loadBalancers.put(entry.getKey(), new ConcurrentHashMap<>(entry.getValue()));+ // Region maps read back from disk are plain maps; the name check in createLoadBalancer and+ // the certificate scan rely on concurrent ones, in every account.+ for (StoredRegion stored : storedRegions()) {+ if (!(stored.regionLbs() instanceof ConcurrentHashMap)) {+ storeRegion(stored.accountId(), stored.region(), new ConcurrentHashMap<>(stored.regionLbs()));}}}/**- * Restarts health checking for load balancers restored from disk. Called from- * {@code EmulatorLifecycle} once the bean is constructed, like {@code ElbV2Service} does —- * nothing reachable from {@link #initializeStorage()} may touch an injected collaborator.+ * Restarts health checking for the load balancers of every account restored from disk.+ * Called from {@code EmulatorLifecycle} once the bean is constructed, because nothing+ * reachable from {@link #initializeStorage()} may touch an injected collaborator.*/public void restorePersistedRuntime() {- // A balancer stored before the zone was looked up per region still carries the one fixed- // zone every balancer used to report; take the region's zone again and store it back.- for (String region : List.copyOf(loadBalancers.keySet())) {- Map<String, ClassicLoadBalancer> regionLbs = loadBalancers.get(region);- if (regionLbs == null) {- continue;- }- for (ClassicLoadBalancer lb : regionLbs.values()) {- lb.setCanonicalHostedZoneNameId(AwsRegionFacts.classicElbHostedZoneId(region).orElse(null));- }- loadBalancers.put(region, regionLbs);- }- for (Map<String, ClassicLoadBalancer> regionLbs : loadBalancers.values()) {- for (ClassicLoadBalancer lb : regionLbs.values()) {+ for (StoredRegion stored : storedRegions()) {+ for (ClassicLoadBalancer lb : stored.regionLbs().values()) {+ // A balancer stored before balancers recorded their account belongs to the account+ // it is stored under, which its health state and instance lookups go by.+ if (lb.getAccountId() == null) {+ lb.setAccountId(stored.accountId());+ }+ // A balancer stored before the zone was looked up per region still carries the one+ // fixed zone every balancer used to report; take the region's zone again.+ lb.setCanonicalHostedZoneNameId(+ AwsRegionFacts.classicElbHostedZoneId(stored.region()).orElse(null));healthChecker.startMonitoring(lb);healthChecker.registerInstances(lb, lb.getInstanceIds());}+ // Stores back the account and zone set above.+ storeRegion(stored.accountId(), stored.region(), stored.regionLbs());+ }+ }++ /** One account's load balancers in one region, as stored. */+ private record StoredRegion(String accountId, String region, Map<String, ClassicLoadBalancer> regionLbs) {}++ /**+ * Every stored region map with the account that owns it, taken from its raw key,+ * {@code <account>/<region>}. {@code loadBalancers} shows only the account of the current+ * request, or the default one outside a request, and the service can first be created inside+ * any account's request. The account-aware scans recognize only 12-digit account prefixes, but+ * the default account id is configurable and AssumeRole takes the account from the role ARN.+ * A region never contains a slash, so the account is everything before the last one; every+ * key here has an account, since this store is younger than account-aware storage.+ */+ private List<StoredRegion> storedRegions() {+ List<StoredRegion> regions = new ArrayList<>();+ if (loadBalancerStore == null) {+ loadBalancers.forEach((region, regionLbs) -> regions.add(new StoredRegion(null, region, regionLbs)));+ return regions;+ }+ loadBalancerStore.scanAllAccountsWithRawKeys().forEach((rawKey, regionLbs) -> {+ int slash = rawKey.lastIndexOf('/');+ if (slash > 0) {+ regions.add(new StoredRegion(rawKey.substring(0, slash), rawKey.substring(slash + 1), regionLbs));+ }+ });+ return regions;+ }++ private void storeRegion(String accountId, String region, Map<String, ClassicLoadBalancer> regionLbs) {+ if (loadBalancerStore != null) {+ loadBalancerStore.putForAccount(accountId, region, regionLbs);+ } else {+ loadBalancers.put(region, regionLbs);}}@@ -264,8 +306,9 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {if (regionLbs == null) {return;}- if (regionLbs.remove(name) != null) {- healthChecker.stopMonitoring(region, name);+ ClassicLoadBalancer removed = regionLbs.remove(name);+ if (removed != null) {+ healthChecker.stopMonitoring(removed);loadBalancers.put(region, regionLbs);}}@@ -360,7 +403,7 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {ClassicLoadBalancer lb = requireLoadBalancer(region, name);lb.getInstanceIds().removeAll(instanceIds);persist(region);- healthChecker.deregisterInstances(region, name, instanceIds);+ healthChecker.deregisterInstances(lb, instanceIds);return List.copyOf(lb.getInstanceIds());}@@ -377,7 +420,7 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {throw new AwsException("InvalidInstance","Could not find EC2 instance " + id + ".", 400);}- result.put(id, healthChecker.getHealth(region, name, id));+ result.put(id, healthChecker.getHealth(lb, id));}return result;}diff --git a/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicAccountIsolationTest.java b/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicAccountIsolationTest.javanew file mode 100644index 0000000000..533383814a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicAccountIsolationTest.java@@ -0,0 +1,165 @@+package io.github.hectorvent.floci.services.elb;++import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.RequestContext;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.ec2.Ec2Service;+import io.github.hectorvent.floci.services.elb.model.ClassicHealthCheck;+import io.github.hectorvent.floci.services.elb.model.ClassicListener;+import io.github.hectorvent.floci.services.elb.model.ClassicLoadBalancer;+import io.vertx.core.Vertx;+import io.vertx.core.http.HttpServer;+import jakarta.enterprise.inject.Instance;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.time.Duration;+import java.util.List;+import java.util.Map;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicInteger;++import static org.awaitility.Awaitility.await;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * Classic load balancer names are unique within one account and region, so two accounts can each+ * run a balancer called {@code web}. These tests run the real health checker against a backend on+ * loopback and check that one account's balancer never changes the health the other one reports.+ */+class ElbClassicAccountIsolationTest {++ private static final String REGION = "us-west-2";+ private static final String FIRST = "111111111111";+ private static final String SECOND = "222222222222";+ private static final String INSTANCE = "i-0123456789abcdef0";++ private final Vertx vertx = Vertx.vertx();+ private final RequestContext context = new RequestContext();+ private final AtomicInteger backendStatus = new AtomicInteger(200);+ private HttpServer backend;+ private ElbClassicHealthChecker healthChecker;+ private ElbClassicService service;++ @BeforeEach+ @SuppressWarnings("unchecked")+ void setUp() throws Exception {+ backend = vertx.createHttpServer()+ .requestHandler(request -> request.response().setStatusCode(backendStatus.get()).end())+ .listen(0, "127.0.0.1")+ .toCompletionStage()+ .toCompletableFuture()+ .get(5, TimeUnit.SECONDS);++ Instance<RequestContext> contexts = mock(Instance.class);+ when(contexts.get()).thenReturn(context);+ RegionResolver resolver = mock(RegionResolver.class);+ when(resolver.getAccountId()).thenAnswer(ignored -> context.getAccountId());+ StorageFactory factory = mock(StorageFactory.class);+ when(factory.create(eq("elb"), anyString(), any())).thenAnswer(ignored ->+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), contexts, FIRST));++ // The registered instance answers on loopback. The EC2 model's Instance is qualified+ // because this file also imports CDI's Instance for the request context.+ io.github.hectorvent.floci.services.ec2.model.Instance instance =+ new io.github.hectorvent.floci.services.ec2.model.Instance();+ instance.setContainerBridgeIp("127.0.0.1");+ Ec2Service ec2Service = mock(Ec2Service.class);+ when(ec2Service.findInstanceById(anyString(), eq(INSTANCE))).thenReturn(instance);++ // Without an EmulatorConfig the checker is not in mock mode, so it really probes.+ healthChecker = new ElbClassicHealthChecker(vertx, null, ec2Service);+ context.setAccountId(FIRST);+ service = new ElbClassicService(ec2Service, healthChecker, factory, null, resolver);+ service.initializeStorage();+ }++ @AfterEach+ void tearDown() {+ vertx.close().toCompletionStage().toCompletableFuture().join();+ }++ @Test+ void deletingAnotherAccountsBalancerOfTheSameNameLeavesMyInstanceInService() {+ context.setAccountId(FIRST);+ createWeb();+ registerHealthyInstance();++ context.setAccountId(SECOND);+ createWeb();+ service.deleteLoadBalancer(REGION, "web");++ context.setAccountId(FIRST);+ assertEquals("InService", health().state());+ }++ @Test+ void anotherAccountsBalancerOfTheSameNameDoesNotStopMyHealthChecks() {+ context.setAccountId(FIRST);+ createWeb();+ registerHealthyInstance();++ context.setAccountId(SECOND);+ createWeb();+ backendStatus.set(503);++ // The instance now fails, which only the first account's own periodic check can notice.+ healthChecker.runArmedChecks();+ context.setAccountId(FIRST);+ await().pollInSameThread().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {+ ElbClassicHealthChecker.InstanceHealth health = health();+ assertEquals("OutOfService", health.state());+ assertEquals("Instance", health.reasonCode());+ });++ // And it recovers, which the other account's default TCP:80 check could not report.+ backendStatus.set(200);+ healthChecker.runArmedChecks();+ await().pollInSameThread().atMost(Duration.ofSeconds(5))+ .until(() -> "InService".equals(health().state()));+ }++ private void createWeb() {+ ClassicListener listener = new ClassicListener();+ listener.setProtocol("HTTP");+ listener.setLoadBalancerPort(80);+ listener.setInstanceProtocol("HTTP");+ listener.setInstancePort(8080);+ service.createLoadBalancer(REGION, "web", List.of(listener), List.of(REGION + "a"),+ List.of(), List.of(), null, Map.of());+ }++ /**+ * Gives the stored balancer a check that one probe settles and re-arms the checker, as+ * ConfigureHealthCheck does but with a timeout and thresholds below the minimums that action+ * enforces. The interval is the longest the API allows, so the periodic timer never fires+ * during a test: the probe that registration schedules settles the instance here, and the+ * tests run later rounds themselves through {@link ElbClassicHealthChecker#runArmedChecks()}.+ */+ private void registerHealthyInstance() {+ ClassicHealthCheck check = new ClassicHealthCheck();+ check.setTarget("HTTP:" + backend.actualPort() + "/");+ check.setInterval(300);+ check.setTimeout(1);+ check.setHealthyThreshold(1);+ check.setUnhealthyThreshold(1);+ ClassicLoadBalancer lb = service.requireLoadBalancer(REGION, "web");+ lb.setHealthCheck(check);+ healthChecker.healthCheckChanged(lb);+ service.registerInstances(REGION, "web", List.of(INSTANCE));+ await().pollInSameThread().atMost(Duration.ofSeconds(5))+ .until(() -> "InService".equals(health().state()));+ }++ private ElbClassicHealthChecker.InstanceHealth health() {+ return service.describeInstanceHealth(REGION, "web", List.of(INSTANCE)).get(INSTANCE);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicServiceTest.javaindex e2b70258a5..de9453bf0b 100644--- a/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicServiceTest.java@@ -2,20 +2,29 @@ package io.github.hectorvent.floci.services.elb;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.AwsRegionFacts;+import io.github.hectorvent.floci.core.common.RequestContext;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.ec2.Ec2Service;import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;import io.github.hectorvent.floci.services.ec2.model.Subnet;import io.github.hectorvent.floci.services.elb.model.ClassicHealthCheck;import io.github.hectorvent.floci.services.elb.model.ClassicListener;import io.github.hectorvent.floci.services.elb.model.ClassicLoadBalancer;+import jakarta.enterprise.inject.Instance;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import java.util.ArrayList;+import java.util.LinkedHashMap;import java.util.List;import java.util.Map;+import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;@@ -25,13 +34,19 @@ import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertInstanceOf;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.anyList;import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doReturn;import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;@@ -39,6 +54,8 @@ import static org.mockito.Mockito.when;class ElbClassicServiceTest {private static final String REGION = "us-west-2";+ private static final String DEFAULT_ACCOUNT = "000000000000";+ private static final String OTHER_ACCOUNT = "222222222222";@MockEc2Service ec2Service;@@ -311,11 +328,11 @@ class ElbClassicServiceTest {@Testvoid registerAndDeregisterInstancesAreIdempotent() {- create("my-elb");+ ClassicLoadBalancer lb = create("my-elb");service.registerInstances(REGION, "my-elb", List.of("i-1"));assertEquals(List.of("i-1"), service.registerInstances(REGION, "my-elb", List.of("i-1")));assertEquals(List.of(), service.deregisterInstances(REGION, "my-elb", List.of("i-1")));- verify(healthChecker).deregisterInstances(REGION, "my-elb", List.of("i-1"));+ verify(healthChecker).deregisterInstances(lb, List.of("i-1"));}@Test@@ -379,4 +396,118 @@ class ElbClassicServiceTest {assertEquals(AwsRegionFacts.classicElbHostedZoneId(REGION).orElseThrow(),service.describeLoadBalancers(REGION, List.of("stored-elb")).getFirst().getCanonicalHostedZoneNameId());}++ /**+ * Startup runs outside any request, where the storage-backed map sees only the default+ * account. Every other account's balancers have to come back too, as their own account's.+ */+ @Test+ void restoreBringsBackTheBalancersOfEveryAccount() {+ AccountAwareStorageBackend<Map<String, ClassicLoadBalancer>> storage =+ AccountAwareStorageBackend.inMemory(DEFAULT_ACCOUNT);+ StorageFactory factory = mock(StorageFactory.class);+ doReturn(storage).when(factory).create(eq("elb"), eq("elb-load-balancers.json"), any());+ ClassicLoadBalancer own = storedBalancer("web", List.of("i-own"));+ ClassicLoadBalancer foreign = storedBalancer("web", List.of("i-foreign"));+ // Read back from disk, a region map is whatever map the JSON reader built.+ storage.putForAccount(DEFAULT_ACCOUNT, REGION, new LinkedHashMap<>(Map.of("web", own)));+ storage.putForAccount(OTHER_ACCOUNT, REGION, new LinkedHashMap<>(Map.of("web", foreign)));++ service = new ElbClassicService(ec2Service, healthChecker, factory, null);+ service.initializeStorage();+ service.restorePersistedRuntime();++ verify(healthChecker).startMonitoring(own);+ verify(healthChecker).registerInstances(own, List.of("i-own"));+ verify(healthChecker).startMonitoring(foreign);+ verify(healthChecker).registerInstances(foreign, List.of("i-foreign"));+ String zone = AwsRegionFacts.classicElbHostedZoneId(REGION).orElseThrow();+ assertEquals(zone, own.getCanonicalHostedZoneNameId());+ assertEquals(zone, foreign.getCanonicalHostedZoneNameId());+ // A record stored before balancers carried their account takes it from where it is stored.+ assertEquals(DEFAULT_ACCOUNT, own.getAccountId());+ assertEquals(OTHER_ACCOUNT, foreign.getAccountId());+ assertInstanceOf(ConcurrentHashMap.class, storage.getForAccount(DEFAULT_ACCOUNT, REGION).orElseThrow());+ assertInstanceOf(ConcurrentHashMap.class, storage.getForAccount(OTHER_ACCOUNT, REGION).orElseThrow());+ }++ /**+ * The default account id is configurable and need not be 12 digits, while a scan of every+ * account recognizes only 12-digit prefixes. The default account's balancers must still keep+ * their keys and zone, and be restored once.+ */+ @Test+ void restoreKeepsTheKeysOfADefaultAccountWhoseIdIsNotTwelveDigits() {+ AccountAwareStorageBackend<Map<String, ClassicLoadBalancer>> storage =+ AccountAwareStorageBackend.inMemory("local");+ StorageFactory factory = mock(StorageFactory.class);+ doReturn(storage).when(factory).create(eq("elb"), eq("elb-load-balancers.json"), any());+ ClassicLoadBalancer own = storedBalancer("web", List.of("i-own"));+ ClassicLoadBalancer foreign = storedBalancer("web", List.of("i-foreign"));+ storage.putForAccount("local", REGION, new LinkedHashMap<>(Map.of("web", own)));+ storage.putForAccount(OTHER_ACCOUNT, REGION, new LinkedHashMap<>(Map.of("web", foreign)));++ service = new ElbClassicService(ec2Service, healthChecker, factory, null);+ service.initializeStorage();+ service.restorePersistedRuntime();++ assertEquals(Set.of(REGION), storage.keysForAccount("local"));+ assertEquals(Set.of(REGION), storage.keysForAccount(OTHER_ACCOUNT));+ verify(healthChecker, times(1)).startMonitoring(own);+ verify(healthChecker, times(1)).startMonitoring(foreign);+ assertEquals(AwsRegionFacts.classicElbHostedZoneId(REGION).orElseThrow(), own.getCanonicalHostedZoneNameId());+ assertEquals("local", own.getAccountId());+ assertInstanceOf(ConcurrentHashMap.class, storage.getForAccount("local", REGION).orElseThrow());+ }++ /**+ * The service is created on its first use, which can come inside another account's request, and+ * an account id need not be 12 digits: the default one is configurable, and AssumeRole takes the+ * account from the role ARN. Every region map still has to come back under its own key.+ */+ @Test+ void restoreReadsEachRegionMapUnderTheAccountOfItsKey() {+ RequestContext request = new RequestContext();+ request.setAccountId(OTHER_ACCOUNT);+ @SuppressWarnings("unchecked")+ Instance<RequestContext> requests = mock(Instance.class);+ // Lenient: the restore should not consult the request at all, but anything that does sees+ // another account's.+ lenient().when(requests.get()).thenReturn(request);+ AccountAwareStorageBackend<Map<String, ClassicLoadBalancer>> storage =+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), requests, "local");+ StorageFactory factory = mock(StorageFactory.class);+ doReturn(storage).when(factory).create(eq("elb"), eq("elb-load-balancers.json"), any());+ Map<String, ClassicLoadBalancer> byAccount = new LinkedHashMap<>();+ for (String account : List.of("local", OTHER_ACCOUNT, "dev")) {+ ClassicLoadBalancer lb = storedBalancer("web", List.of("i-" + account));+ byAccount.put(account, lb);+ storage.putForAccount(account, REGION, new LinkedHashMap<>(Map.of("web", lb)));+ }++ service = new ElbClassicService(ec2Service, healthChecker, factory, null);+ service.initializeStorage();+ service.restorePersistedRuntime();++ String zone = AwsRegionFacts.classicElbHostedZoneId(REGION).orElseThrow();+ for (Map.Entry<String, ClassicLoadBalancer> entry : byAccount.entrySet()) {+ String account = entry.getKey();+ ClassicLoadBalancer lb = entry.getValue();+ assertEquals(Set.of(REGION), storage.keysForAccount(account), account);+ assertInstanceOf(ConcurrentHashMap.class, storage.getForAccount(account, REGION).orElseThrow(), account);+ assertSame(lb, storage.getForAccount(account, REGION).orElseThrow().get("web"), account);+ verify(healthChecker, times(1)).startMonitoring(lb);+ assertEquals(zone, lb.getCanonicalHostedZoneNameId(), account);+ assertEquals(account, lb.getAccountId());+ }+ }++ private static ClassicLoadBalancer storedBalancer(String name, List<String> instanceIds) {+ ClassicLoadBalancer lb = new ClassicLoadBalancer();+ lb.setLoadBalancerName(name);+ lb.setRegion(REGION);+ lb.setCanonicalHostedZoneNameId("Z35SXDOTRQ7X7K");+ lb.setInstanceIds(new ArrayList<>(instanceIds));+ return lb;+ }}