fix(elb): keep Classic load balancer health checks per account (#6666)

* fix(elb): keep Classic health checks apart between accounts

The Classic health checker kept its instance states and its probe timer
under the region and the load balancer name. A Classic name is unique
only within one account, so when two accounts each had a load balancer
called web they shared one entry. Creating the second web replaced the
first one's periodic check with its own, and deleting it removed the
first account's instance states too: those instances then reported
OutOfService with reason ELB ("Instance registration is still in
progress") and were no longer checked.

The key now includes the load balancer's account, and the checker's
methods take the load balancer itself instead of a region and a name,
so the account always comes with it.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(elb): restore every account's Classic load balancers at startup

Startup runs outside any request, where the storage-backed map of
Classic load balancers sees only the default account. Restoring through
it restarted health checks for the default account's load balancers
alone: after a restart, the instances registered with another account's
load balancers reported OutOfService with reason ELB and were never
checked. Those accounts' region maps also stayed the plain maps read
from disk, although the name check in CreateLoadBalancer and the
certificate scan rely on concurrent ones, and a load balancer stored
with the old fixed hosted zone kept it unless the default account owned
it.

Startup now walks the stored region maps of every account: it makes
them concurrent, gives each load balancer its region's hosted zone, and
starts its health checks. A load balancer stored before load balancers
recorded their account takes the account it is stored under, so its
health state and instance lookups belong to that account.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(elb): restore the default account's Classic load balancers by their own keys

The every-account restore read the default account from a scan of the
whole store as well, and that scan recognizes only 12-digit account
prefixes. The default account id is configurable, through
FLOCI_DEFAULT_ACCOUNT_ID, and need not be 12 digits. With one such as
local, every restart read the key local/us-west-2 as a region of that
name: the default account's load balancers lost their hosted zone, their
region maps stayed plain maps, and each restart wrote nested copies of
the store that a delete never reached.

The region maps that the storage-backed map shows, which at startup are
the default account's, are read through it again, as they were before
the every-account restore, and written back under their own keys. The
scan now supplies only the other accounts' maps. The javadoc no longer
compares this restore with ELBv2's, which still covers the default
account only.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(elb): run the Classic account isolation checks every second

The account isolation tests set their health check through
ConfigureHealthCheck, whose 5-second minimum interval made the two tests
take about 20 seconds. They now set a check every second on the stored
load balancer and re-arm the checker directly, and take about 4
seconds. Both still fail on the commit before the per-account key.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(elb): restore each Classic region map under the account in its key

The startup restore read the default account through the storage-backed
map, which shows the account of the current request, and every other
account from a scan that recognizes only 12-digit account prefixes.
Neither holds in general. The service is created on its first use, and
that use can come inside another account's request: an IAM
DeleteServerCertificate reaches it even while Classic ELB is disabled
and its lifecycle restore never runs. Account ids need not be 12 digits
either: FLOCI_DEFAULT_ACCOUNT_ID is free-form, and AssumeRole takes the
account from the role ARN. In those cases the restore again nested
copies of a region map and cleared its hosted zone, or left another
account's load balancers unrestored.

Startup now reads every region map by its raw stored key and takes the
account and the region from it. A region never contains a slash, so the
account is everything before the last one.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(elb): check which load balancer each restored account holds

The restore test for region maps read by their stored keys checked each
account's keys, map type, hosted zone and health checks, but not which
load balancer its map held. A restore that wrote every map back under
the account of the current request still passed, with one account left
holding another account's load balancer. The test now checks that each
account's stored map holds that account's own load balancer, and that
write-back fails it.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(elb): run the Classic isolation checks without waiting on timers

The account isolation tests waited on the real one-second health check
timer, so the class took about 5.6 seconds, 3 of them in the second
case. The checker now keeps the load balancer each periodic check
probes next to its timer, and a package-private runArmedChecks() runs
one tick of every armed check at once. The tests set an interval no
timer reaches during a test, settle each check in one probe, and run
the rounds themselves. The class now takes about 1.8 seconds, most of
it the first case's setup, and the timers keep their schedule.

Running what the armed timers would run, rather than probing one load
balancer directly, keeps the second case meaningful: it is about
another account's balancer taking over the periodic check. With the
account left out of the health checker's key, both cases still fail.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(elb): make the second Classic isolation case independent of rounds

The case where another account creates a load balancer of the same name
caught a health checker keyed without the account only because it ran
exactly one round: the other account's default TCP:80 check needs two
failures, so a second round would have let it report OutOfService as
well. The case now also checks that the instance recovers once its
backend answers 200 again, which only the first account's own check can
report.

The helper that registers the instance no longer runs a round of its
own. The probe that registration schedules already settles a check with
thresholds of one, and a second probe could still be running when the
case moved on. Each periodic check now stores the tick its timer runs,
and runArmedChecks runs that same tick, so the two cannot drift apart.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* refactor(elb): create the Classic load balancer store in the constructor

The Classic service created its load balancer store and the map over it
in initializeStorage, so neither field could be final, as AGENTS.md asks
of service fields. Both are now created in the constructor, as
CloudFormationService creates its stores, and are final; without a
StorageFactory the map is a plain in-memory map, as before.
initializeStorage keeps the conversion of region maps read from disk, so
the startup order is unchanged: the store is created and loaded during
the bean's construction either way, and nothing in that step calls
another bean. The StorageFactory field, read only there, is removed.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-26 17:23:04 -04:00
1 parent f3f8b42200
commit 9fd0578181
5 files changed
+414 -58

No files matched your search

+4 -2
View File
@@ -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 a
the same port.
- Between registration and the first successful check an instance reports `OutOfService` with
reason 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 instances
registered and deregistered automatically, so a Terraform `min_elb_capacity` wait can be
satisfied.
@@ -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 → state
private 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) {}
@Inject
public 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));
}
public void stopMonitoring(String region, String loadBalancerName) {
String k = key(region, loadBalancerName);
/**
* 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(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 {
@Override
public 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;
}
@@ -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<>();
}
@PostConstruct
void 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;
}
@@ -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);
}
}
@@ -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";
@Mock
Ec2Service ec2Service;
@@ -311,11 +328,11 @@ class ElbClassicServiceTest {
@Test
void 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;
}
}