fix(eks): allow a cluster name in more than one Region of an account (#8140)

Cluster names only have to be unique within a Region of an account, but
EKS stored clusters under the bare name, so creating `demo` in
eu-central-1 failed with ResourceInUseException while a `demo` existed in
eu-west-1. Since #7936 the eu-central-1 caller cannot even see that
cluster.

Clusters, node groups and Fargate profiles are now keyed by
`<region>::<name>`, as OpenSearch domains and Kinesis streams are, and so
are the node-capacity locks and the OIDC signing keys. On startup,
records persisted under the bare name move to the new keys, taking the
Region from each record's ARN. A cluster's signing key moves with it, so
tokens it signed before the upgrade still verify. Access entries, add-ons
and Pod Identity associations were already keyed by the cluster ARN.

A cluster outside the default Region, or one that shares its name with a
cluster in another Region, puts its Region first in its Docker container
and volume names. This is persisted as dockerNameRegion and left out of
API responses, so two Regions' clusters never share a k3s container. A
default-Region cluster, and any cluster created before this change, keeps
its name, so existing containers, volumes and endpoint-mode=network DNS
names stay as they are.

The Pod Identity webhook path now includes the Region. The old path still
works for clusters whose webhook configuration predates the change. The
_floci OIDC routes have no Region of their own and are usually called
unsigned, so they try the request's Region and then the account's only
cluster with that name.

Closes #7966

Follow-up to the Regional cluster names change, from review:

- k3s was given a signing key minted under the bare cluster name while
  EksService created, published and migrated the cluster's key under its
  Regional key, so pod tokens could be signed with a key JWKS did not
  publish. EksClusterManager now asks for the key by the Regional key, at
  start and on reinjection.
- The token-webhook kubeconfig, audit policy, registries.yaml and Pod
  Identity manifest Floci writes per cluster now live under
  <kind>/<account>/<region>/<name>/, the layout of the signing-key files,
  so same-named clusters in two Regions no longer share them.
- The Region-less Pod Identity webhook route resolves the cluster created
  before Regional names, which registered it, rather than preferring the
  request's Region, which could pick a newer same-named default-Region
  cluster.
- OIDC discovery and the key route take an optional region query
  parameter, and the discovery document's jwks_uri names the cluster's
  Region, since a verifier follows it without the discovery context.
- A signing key stored before account-prefixed keys now moves with its
  cluster too, checked by its issuer.
- CreateCluster reserves the Regional key until the cluster is stored, so
  a concurrent create of the same name in the same Region is refused
  instead of overwriting the first.
- Test imports replace fully qualified names, for Checkstyle.

Cluster names are unique only within a Region of an account, and the
token route is usually called unsigned, so with the same name in two
Regions it could only mint for the request's Region. Accept the same
optional ?region= as the discovery and key routes, and document it.

Also correct the accountQualifiedName Javadoc, which still said names
are unique only within an account.
This commit is contained in:
thejrose1984 authored and GitHub committed 2026-11-12 20:10:54 -04:00
1 parent 0383d65acb
commit 55b2fb7bd3
22 files changed
+888 -179

No files matched your search

@@ -733,7 +733,7 @@ public class EksClusterManager
try {
String accountId = resolveClusterAccountId(cluster);
String issuer = resolveClusterIssuer(cluster);
ClusterOidcKey oidcKey = oidcService.ensureKeyForAccount(accountId, cluster.getName(), issuer);
ClusterOidcKey oidcKey = oidcService.ensureKeyForAccount(accountId, oidcKeyName(cluster), issuer);
signingKeyFiles = writeSigningKeyFiles(cluster, oidcKey);
if (signingKeyFiles != null) {
serverArgs.addAll(buildIrsaServerArgs(oidcKey.getIssuer()));
@@ -1404,8 +1404,9 @@ public class EksClusterManager
}
/**
* Account-qualified Docker name for a cluster. Cluster names are unique only within an
* account, so a non-default account's cluster is qualified with its account ID — otherwise
* Account-qualified Docker name for a cluster. Cluster names are unique only within a Region
* of an account, so a non-default account's cluster is qualified with its account ID (and,
* where needed, its Region; see {@link #accountQualifiedClusterName}) — otherwise
* two accounts' same-named clusters would resolve to the same container and data volume,
* letting one account reach (or, via startCluster's stale-container removal, destroy) the
* other's workloads. The default account keeps the historical unqualified name so existing
@@ -1425,10 +1426,19 @@ public class EksClusterManager
return ContainerStorageHelper.resourceName(config, "eks", null, accountQualifiedClusterName(cluster));
}
/**
* The cluster's name qualified by its account and, when {@link Cluster#getDockerNameRegion()}
* is set, by its Region, which leads: {@code [<region>.][<accountId>.]<name>}. Cluster names
* are unique only within a Region of an account, so same-named clusters in two Regions need
* distinct containers and volumes. The forms cannot collide: a name holds no dot, an account
* id is all digits, and a Region never is.
*/
private String accountQualifiedClusterName(Cluster cluster) {
String accountId = cluster.getAccountId();
boolean defaultAccount = accountId == null || accountId.equals(config.defaultAccountId());
return defaultAccount ? cluster.getName() : accountId + "." + cluster.getName();
String qualified = defaultAccount ? cluster.getName() : accountId + "." + cluster.getName();
String region = cluster.getDockerNameRegion();
return region == null || region.isBlank() ? qualified : region + "." + qualified;
}
/**
@@ -1446,6 +1456,11 @@ public class EksClusterManager
*/
private String resolveRestoredDockerName(Cluster cluster) {
String qualified = accountQualifiedName(cluster);
if (cluster.getDockerNameRegion() != null) {
// Region qualification postdates both the account qualifier and the floci-aws- rename,
// so no older name can hold this cluster's resources.
return qualified;
}
// A cluster created after account qualification but before the floci-aws- rename lives
// under the qualified name with the old prefix. Nothing else about it changed, so adopt
@@ -1704,8 +1719,7 @@ public class EksClusterManager
*/
private String writeWebhookKubeconfig(Cluster cluster) {
String clusterName = cluster.getName();
Path localFile = Paths.get(config.services().eks().dataPath(), "webhook", clusterName, WEBHOOK_CONFIG_FILE)
.toAbsolutePath().normalize();
Path localFile = localClusterFile(cluster, "webhook", WEBHOOK_CONFIG_FILE);
try {
Files.createDirectories(localFile.getParent());
Files.writeString(localFile, buildWebhookKubeconfig("http://" + dockerHostResolver.resolve() + ":"
@@ -1746,8 +1760,7 @@ public class EksClusterManager
if (dataPath == null || dataPath.isBlank()) {
return null;
}
Path localFile = Paths.get(dataPath, "audit", clusterName, AUDIT_POLICY_FILE)
.toAbsolutePath().normalize();
Path localFile = localClusterFile(cluster, "audit", AUDIT_POLICY_FILE);
Files.createDirectories(localFile.getParent());
Files.writeString(localFile, buildAuditPolicy());
return localFile.toString();
@@ -2011,6 +2024,24 @@ public class EksClusterManager
return "000000000000";
}
/**
* The key of {@code cluster}'s OIDC signing key in {@link EksOidcService}: the cluster's storage
* key, which carries its Region, as {@link EksService} creates, publishes and migrates it.
*/
private String oidcKeyName(Cluster cluster) {
return EksService.clusterKey(clusterRegion(cluster), cluster.getName());
}
/**
* A file Floci writes for {@code cluster} under {@code <dataPath>/<kind>/<account>/<region>/<name>/},
* the layout of {@link #resolveKeysDir}. Cluster names are unique only within a Region of an
* account, so a shorter path would let same-named clusters overwrite each other's files.
*/
Path localClusterFile(Cluster cluster, String kind, String fileName) {
return Paths.get(config.services().eks().dataPath(), kind, resolveClusterAccountId(cluster),
clusterRegion(cluster), cluster.getName(), fileName).toAbsolutePath().normalize();
}
Path resolveKeysDir(Cluster cluster) {
String accountId = resolveClusterAccountId(cluster);
String region = clusterRegion(cluster);
@@ -2107,7 +2138,7 @@ public class EksClusterManager
try {
String accountId = resolveClusterAccountId(cluster);
String issuer = resolveClusterIssuer(cluster);
ClusterOidcKey oidcKey = oidcService.ensureKeyForAccount(accountId, cluster.getName(), issuer);
ClusterOidcKey oidcKey = oidcService.ensureKeyForAccount(accountId, oidcKeyName(cluster), issuer);
SigningKeyFiles keyFiles = writeSigningKeyFiles(cluster, oidcKey);
if (keyFiles != null) {
copySigningKeysIntoContainer(containerId, keyFiles, cluster.getName());
@@ -2145,8 +2176,7 @@ public class EksClusterManager
boolean tlsUri = config.services().ecr().tlsUri() && config.tls().enabled();
String content = buildRegistriesYaml(mirrorAccounts(resolveClusterAccountId(cluster), config.defaultAccountId()),
mirrorRegions(region), ecrRegistryManager.advertisedPort(), endpoint, tlsUri);
writeLocalCopy(Paths.get(config.services().eks().dataPath(), "registries", clusterName,
"registries.yaml"), content, clusterName);
writeLocalCopy(localClusterFile(cluster, "registries", "registries.yaml"), content, clusterName);
try {
RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, "/etc",
REGISTRIES_TAR_ENTRY, content.getBytes(StandardCharsets.UTF_8), 0644,
@@ -2232,10 +2262,9 @@ public class EksClusterManager
return;
}
String url = "https://" + dockerHostResolver.resolve() + ":" + config.port()
+ podIdentityWebhookPath(clusterName, resolveClusterAccountId(cluster));
+ podIdentityWebhookPath(clusterName, resolveClusterAccountId(cluster), clusterRegion(cluster));
String manifest = buildPodIdentityWebhookConfiguration(url, certificateAuthority.caPem());
writeLocalCopy(Paths.get(config.services().eks().dataPath(), "webhook", clusterName,
POD_IDENTITY_MANIFEST_FILE), manifest, clusterName);
writeLocalCopy(localClusterFile(cluster, "webhook", POD_IDENTITY_MANIFEST_FILE), manifest, clusterName);
try {
byte[] tar = tarSingleFile(POD_IDENTITY_MANIFEST_TAR_ENTRY, manifest);
RetryingTarCopier.copyStreamed(lifecycleManager.getDockerClient(), containerId, K3S_DATA_DIR,
@@ -2253,8 +2282,8 @@ public class EksClusterManager
* token webhook puts its scope there: the API server calls Floci with no AWS credentials, so a
* cluster owned by a non-default account would otherwise never be found.
*/
static String podIdentityWebhookPath(String clusterName, String accountId) {
return "/_floci/eks/clusters/" + clusterName + "/pod-identity-webhook/scope/" + accountId;
static String podIdentityWebhookPath(String clusterName, String accountId, String region) {
return "/_floci/eks/clusters/" + clusterName + "/pod-identity-webhook/scope/" + accountId + "/" + region;
}
/**
@@ -2709,7 +2738,7 @@ public class EksClusterManager
if (nodeGroupStorage == null || cluster == null || cluster.getName() == null) {
return List.of();
}
String prefix = cluster.getName() + "/";
String prefix = EksService.clusterKey(clusterRegion(cluster), cluster.getName()) + "/";
String accountId = resolveClusterAccountId(cluster);
List<Nodegroup> groups;
if (nodeGroupStorage instanceof AccountAwareStorageBackend<Nodegroup> aware) {
@@ -110,10 +110,11 @@ public class EksController {
private Cluster toClusterResponse(Cluster cluster) {
if (cluster == null || (!cluster.isExplicitVersion() && cluster.getNodeInstanceType() == null
&& cluster.getClusterArgs() == null && cluster.getDefaultStorageClass() == null
&& cluster.getJoinedInstanceIds() == null)) {
&& cluster.getJoinedInstanceIds() == null && cluster.getDockerNameRegion() == null)) {
return cluster;
}
Cluster response = cluster.copy();
response.setDockerNameRegion(null);
response.setExplicitVersion(false);
response.setNodeInstanceType(null);
response.setClusterArgs(null);
@@ -72,10 +72,12 @@ public class EksOidcService implements OidcIssuerKeyLookup {
/**
* Generates and stores the cluster's signing keypair if absent, returning the stored material.
* Keyed by cluster name so {@code DeleteCluster} can drop it.
* Keyed by the cluster's storage key ({@link EksService#clusterKey(String, String)}), which
* carries its Region, so {@code DeleteCluster} can drop it and same-named clusters in two
* Regions each keep their own key.
*/
public synchronized ClusterOidcKey ensureKey(String clusterName, String issuer) {
return ensureKey(null, clusterName, issuer);
public synchronized ClusterOidcKey ensureKey(String clusterKey, String issuer) {
return ensureKey(null, clusterKey, issuer);
}
/**
@@ -83,13 +85,13 @@ public class EksOidcService implements OidcIssuerKeyLookup {
* without a request context must pass the owning account from the cluster record, since the
* request-scoped store would otherwise resolve to the default account.
*/
public synchronized ClusterOidcKey ensureKeyForAccount(String accountId, String clusterName,
public synchronized ClusterOidcKey ensureKeyForAccount(String accountId, String clusterKey,
String issuer) {
return ensureKey(accountId, clusterName, issuer);
return ensureKey(accountId, clusterKey, issuer);
}
private ClusterOidcKey ensureKey(String accountId, String clusterName, String issuer) {
Optional<ClusterOidcKey> existing = readKey(accountId, clusterName);
private ClusterOidcKey ensureKey(String accountId, String clusterKey, String issuer) {
Optional<ClusterOidcKey> existing = readKey(accountId, clusterKey);
if (existing.isPresent() && issuer.equals(existing.get().getIssuer())) {
return existing.get();
}
@@ -104,36 +106,68 @@ public class EksOidcService implements OidcIssuerKeyLookup {
UUID.randomUUID().toString(),
Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()),
Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
writeKey(accountId, clusterName, key);
LOG.debugv("Generated IRSA OIDC signing key for EKS cluster {0}", clusterName);
writeKey(accountId, clusterKey, key);
LOG.debugv("Generated IRSA OIDC signing key for EKS cluster {0}", clusterKey);
return key;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Failed to generate EKS OIDC signing keypair for cluster "
+ clusterName + ": RSA unavailable", e);
+ clusterKey + ": RSA unavailable", e);
}
}
private Optional<ClusterOidcKey> readKey(String accountId, String clusterName) {
private Optional<ClusterOidcKey> readKey(String accountId, String clusterKey) {
if (accountId != null && keyStore instanceof AccountAwareStorageBackend<ClusterOidcKey> aware) {
return aware.getForAccount(accountId, clusterName);
return aware.getForAccount(accountId, clusterKey);
}
return keyStore.get(clusterName);
return keyStore.get(clusterKey);
}
private void writeKey(String accountId, String clusterName, ClusterOidcKey key) {
private void writeKey(String accountId, String clusterKey, ClusterOidcKey key) {
if (accountId != null && keyStore instanceof AccountAwareStorageBackend<ClusterOidcKey> aware) {
aware.putForAccount(accountId, clusterName, key);
aware.putForAccount(accountId, clusterKey, key);
return;
}
keyStore.put(clusterName, key);
keyStore.put(clusterKey, key);
}
public void deleteKey(String clusterName) {
keyStore.delete(clusterName);
public void deleteKey(String clusterKey) {
keyStore.delete(clusterKey);
}
public Optional<ClusterOidcKey> findKeyByCluster(String clusterName) {
return keyStore.get(clusterName);
/**
* Moves the signing key of {@code accountId}'s cluster from {@code legacyKey}, the bare cluster
* name keys were stored under before cluster names became Regional, to {@code clusterKey}. Only
* a key minted for {@code issuer} moves, so a same-named cluster's key is never taken over.
* Keeping the key, rather than minting a new one, keeps tokens already issued verifiable. A key
* stored before keys were account-prefixed moves too; the issuer, a random URL minted for one
* cluster, is what proves it belongs to this one.
*/
public synchronized void migrateLegacyKey(String accountId, String legacyKey, String clusterKey,
String issuer) {
if (legacyKey.equals(clusterKey) || issuer == null) {
return;
}
if (accountId != null && keyStore instanceof AccountAwareStorageBackend<ClusterOidcKey> aware) {
aware.getForAccountMigratingLegacyKeys(accountId, clusterKey, List.of(legacyKey),
key -> issuer.equals(key.getIssuer()));
return;
}
Optional<ClusterOidcKey> legacy = readKey(accountId, legacyKey);
if (legacy.isEmpty() || !issuer.equals(legacy.get().getIssuer())) {
return;
}
if (readKey(accountId, clusterKey).isEmpty()) {
writeKey(accountId, clusterKey, legacy.get());
}
if (accountId != null && keyStore instanceof AccountAwareStorageBackend<ClusterOidcKey> aware) {
aware.deleteForAccount(accountId, legacyKey);
} else {
keyStore.delete(legacyKey);
}
}
public Optional<ClusterOidcKey> findKeyByCluster(String clusterKey) {
return keyStore.get(clusterKey);
}
@Override
@@ -162,7 +196,7 @@ public class EksOidcService implements OidcIssuerKeyLookup {
* Mints an RS256-signed service-account token for {@code namespace}/{@code serviceAccount},
* shaped like the projected token a pod would present to STS.
*/
public String mintServiceAccountToken(String clusterName, String issuer, String namespace,
public String mintServiceAccountToken(String clusterKey, String issuer, String namespace,
String serviceAccount, String audience, Integer lifetimeSeconds) {
if (namespace == null || namespace.isBlank()) {
throw new AwsException("InvalidParameterException", "namespace is required", 400);
@@ -173,7 +207,7 @@ public class EksOidcService implements OidcIssuerKeyLookup {
int lifetime = resolveLifetime(lifetimeSeconds);
String aud = audience == null || audience.isBlank() ? STS_AUDIENCE : audience;
ClusterOidcKey key = ensureKey(clusterName, issuer);
ClusterOidcKey key = ensureKey(clusterKey, issuer);
long now = Instant.now().getEpochSecond();
long exp = now + lifetime;
String subject = "system:serviceaccount:" + namespace + ":" + serviceAccount;
@@ -9,6 +9,7 @@ import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@@ -25,6 +26,10 @@ import java.util.Map;
*
* <p>Minting server-side keeps the RSA private key inside Floci. Callers never hold signing
* material, and the claim shape stays authoritative in one place.
*
* <p>Takes the same optional {@code ?region=} as the discovery and key routes: cluster names are
* unique only within a Region of an account, and this route is usually called unsigned, so without
* it the request's Region is used, and then the account's only cluster of that name.
*/
@ApplicationScoped
@Path("_floci/eks/clusters/{name}/oidc-token")
@@ -42,8 +47,9 @@ public class EksOidcTokenController {
}
@POST
public Response mintToken(@PathParam("name") String clusterName, Map<String, Object> request) {
Cluster cluster = eksService.describeCluster(clusterName);
public Response mintToken(@PathParam("name") String clusterName, @QueryParam("region") String region,
Map<String, Object> request) {
Cluster cluster = eksService.findClusterForFlociRoute(clusterName, region);
String issuer = cluster.getIdentity() != null && cluster.getIdentity().getOidc() != null
? cluster.getIdentity().getOidc().getIssuer()
: null;
@@ -59,7 +65,7 @@ public class EksOidcTokenController {
Integer lifetime = integer(body, "expirySeconds");
String token = oidcService.mintServiceAccountToken(
clusterName, issuer, namespace, serviceAccount, audience, lifetime);
eksService.clusterKey(cluster), issuer, namespace, serviceAccount, audience, lifetime);
Map<String, Object> response = new LinkedHashMap<>();
response.put("token", token);
@@ -11,6 +11,7 @@ import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@@ -53,12 +54,14 @@ public class EksOidcWellKnownController {
@GET
@Path(".well-known/openid-configuration")
public Response openIdConfiguration(@PathParam("name") String clusterName) {
String issuer = requireIssuer(clusterName);
public Response openIdConfiguration(@PathParam("name") String clusterName,
@QueryParam("region") String region) {
Cluster cluster = eksService.findClusterForFlociRoute(clusterName, region);
String issuer = requireIssuer(cluster, clusterName);
Map<String, Object> body = new LinkedHashMap<>();
body.put("issuer", issuer);
body.put("jwks_uri", jwksUri(clusterName));
body.put("jwks_uri", jwksUri(clusterName, eksService.clusterRegion(cluster)));
body.put("authorization_endpoint", "urn:kubernetes:programmatic_authorization");
body.put("response_types_supported", List.of("id_token"));
body.put("subject_types_supported", List.of("public"));
@@ -69,9 +72,10 @@ public class EksOidcWellKnownController {
@GET
@Path("keys")
public Response keys(@PathParam("name") String clusterName) {
requireIssuer(clusterName);
ClusterOidcKey key = oidcService.findKeyByCluster(clusterName)
public Response keys(@PathParam("name") String clusterName, @QueryParam("region") String region) {
Cluster cluster = eksService.findClusterForFlociRoute(clusterName, region);
requireIssuer(cluster, clusterName);
ClusterOidcKey key = oidcService.findKeyByCluster(eksService.clusterKey(cluster))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No OIDC signing key for cluster: " + clusterName, 404));
@@ -87,8 +91,7 @@ public class EksOidcWellKnownController {
return Response.ok(Map.of("keys", List.of(jwk))).build();
}
private String requireIssuer(String clusterName) {
Cluster cluster = eksService.describeCluster(clusterName);
private String requireIssuer(Cluster cluster, String clusterName) {
String issuer = cluster.getIdentity() != null && cluster.getIdentity().getOidc() != null
? cluster.getIdentity().getOidc().getIssuer()
: null;
@@ -99,8 +102,13 @@ public class EksOidcWellKnownController {
return issuer;
}
private String jwksUri(String clusterName) {
return config.effectiveBaseUrl() + "/_floci/eks/clusters/" + clusterName + "/oidc/keys";
/**
* The key route of the cluster discovery resolved. It names the cluster's Region, since a verifier
* follows it without the discovery request's context, and cluster names are unique only within a
* Region of an account.
*/
private String jwksUri(String clusterName, String region) {
return config.effectiveBaseUrl() + "/_floci/eks/clusters/" + clusterName + "/oidc/keys?region=" + region;
}
/**
@@ -94,12 +94,22 @@ public class EksPodIdentityWebhook {
* the cluster would only ever be looked up in the default account.
*/
public Map<String, Object> review(String clusterName, String accountId, Map<String, Object> admissionReview) {
return review(clusterName, accountId, null, admissionReview);
}
/**
* As {@link #review(String, String, Map)}, for the cluster in {@code region}: cluster names are
* unique only within a Region. A null Region, from a route registered before the Region was
* part of it, resolves the cluster created before Regional names that registered it.
*/
public Map<String, Object> review(String clusterName, String accountId, String region,
Map<String, Object> admissionReview) {
String apiVersion = admissionReview != null && admissionReview.get("apiVersion") instanceof String version
? version : DEFAULT_API_VERSION;
Map<String, Object> request = admissionReview == null ? null : asMap(admissionReview.get("request"));
String uid = request != null && request.get("uid") instanceof String value ? value : "";
try {
return admissionReview(apiVersion, uid, decide(clusterName, accountId, request));
return admissionReview(apiVersion, uid, decide(clusterName, accountId, region, request));
} catch (RuntimeException e) {
LOG.warnv("EKS pod-identity-webhook: admitting pod unchanged for cluster {0} after an "
+ "internal error: {1}", clusterName, e.toString());
@@ -107,7 +117,7 @@ public class EksPodIdentityWebhook {
}
}
private List<Map<String, Object>> decide(String clusterName, String accountId,
private List<Map<String, Object>> decide(String clusterName, String accountId, String region,
Map<String, Object> request) {
if (request == null) {
return List.of();
@@ -120,7 +130,11 @@ public class EksPodIdentityWebhook {
if (namespace == null) {
return List.of();
}
Optional<Cluster> cluster = eks.findAuthenticationCluster(accountId, clusterName);
// A route without a Region was registered by a cluster created before cluster names became
// Regional, so that cluster answers it, not a same-named one created since.
Optional<Cluster> cluster = region == null
? eks.findPreRegionalCluster(accountId, clusterName)
: eks.findAuthenticationCluster(accountId, region, clusterName);
if (cluster.isEmpty()) {
return List.of();
}
@@ -39,11 +39,24 @@ public class EksPodIdentityWebhookController {
this.webhook = webhook;
}
@POST
@Path("scope/{accountId}/{region}")
public Response review(@PathParam("clusterName") String clusterName,
@PathParam("accountId") String accountId,
@PathParam("region") String region,
Map<String, Object> admissionReview) {
return Response.ok(webhook.review(clusterName, accountId, region, admissionReview)).build();
}
/**
* The route registered by clusters started before the Region was part of the path. Their
* webhook configuration lives in the k3s data volume, so it outlives an upgrade.
*/
@POST
@Path("scope/{accountId}")
public Response review(@PathParam("clusterName") String clusterName,
@PathParam("accountId") String accountId,
Map<String, Object> admissionReview) {
return Response.ok(webhook.review(clusterName, accountId, admissionReview)).build();
return Response.ok(webhook.review(clusterName, accountId, null, admissionReview)).build();
}
}
@@ -74,6 +74,7 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -94,6 +95,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
* qualifier relies on — see EksClusterManager#accountQualifiedName. */
static final String CLUSTER_NAME_REGEX = "[0-9A-Za-z][A-Za-z0-9\\-_]*";
/** Separates the Region from the cluster name in a storage key; see {@link #clusterKey(String, String)}. */
private static final String KEY_SEPARATOR = "::";
private static final String CLUSTER_SG_DESCRIPTION =
"EKS created security group applied to ENI that is attached to EKS Control Plane master nodes, as well as any managed workloads.";
@@ -115,6 +119,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
// Storage hands every caller the same live Cluster, and Cluster keeps identity equality.
private final Set<Cluster> clustersBeingDeleted = ConcurrentHashMap.newKeySet();
private final Set<String> restoringClusters = ConcurrentHashMap.newKeySet();
/** {@code <account>/<cluster key>} of each cluster a CreateCluster call is building. */
private final Set<String> clustersBeingCreated = ConcurrentHashMap.newKeySet();
@Inject
public EksService(StorageFactory storageFactory, EmulatorConfig config,
@@ -169,6 +175,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
@PostConstruct
public void init() {
migrateLegacyKeys();
backfillOidcIdentities();
backfillClusterSecurityGroups();
backfillLogging();
@@ -228,7 +235,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
cluster.setStatus(ClusterStatus.CREATING);
cluster.setPodCidr(EksClusterManager.DEFAULT_POD_CIDR);
if (cluster.getNodeInstanceType() == null) {
firstNodeGroup(cluster.getName(), entry.accountId()).ifPresent(group ->
firstNodeGroup(clusterKey(cluster), entry.accountId()).ifPresent(group ->
cluster.setNodeInstanceType(selectedNodeInstanceType(group)));
}
clusterManager.restoreCluster(cluster);
@@ -268,13 +275,13 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
private boolean isClusterDeleting(String accountId, Cluster cluster) {
return cluster != null && cluster.getName() != null
&& (cluster.getStatus() == ClusterStatus.DELETING
|| clustersBeingDeleted.stream().anyMatch(c -> cluster.getName().equals(c.getName())
|| clustersBeingDeleted.stream().anyMatch(c -> clusterKey(cluster).equals(clusterKey(c))
&& (accountId == null || c.getAccountId() == null || accountId.equals(c.getAccountId()))));
}
private void saveClusterIfNotDeleting(String accountId, String clusterName, Consumer<Cluster> mutator) {
private void saveClusterIfNotDeleting(String accountId, String clusterKey, Consumer<Cluster> mutator) {
synchronized (clustersBeingDeleted) {
Cluster current = findAuthenticationCluster(accountId, clusterName).orElse(null);
Cluster current = findClusterForAccount(accountId, clusterKey).orElse(null);
if (current != null && !isClusterDeleting(accountId, current)) {
if (current.getAccountId() == null) {
current.setAccountId(accountId);
@@ -287,7 +294,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
private void restoreJoinedInstances(String accountId, Cluster cluster) {
if (cluster == null || cluster.getJoinedInstanceIds() == null || ec2Service == null
|| isClusterDeleting(accountId, cluster) || findAuthenticationCluster(accountId, cluster.getName()).isEmpty()) {
|| isClusterDeleting(accountId, cluster) || findClusterForAccount(accountId, clusterKey(cluster)).isEmpty()) {
return;
}
if (cluster.getAccountId() == null) {
@@ -295,7 +302,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
Set<String> prunedInstanceIds = new HashSet<>();
for (Map.Entry<String, String> instEntry : new ArrayList<>(cluster.getJoinedInstanceIds().entrySet())) {
if (isClusterDeleting(accountId, cluster) || findAuthenticationCluster(accountId, cluster.getName()).isEmpty()) {
if (isClusterDeleting(accountId, cluster) || findClusterForAccount(accountId, clusterKey(cluster)).isEmpty()) {
return;
}
String instId = instEntry.getKey();
@@ -316,7 +323,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
});
}
if (!prunedInstanceIds.isEmpty()) {
saveClusterIfNotDeleting(accountId, cluster.getName(), current -> {
saveClusterIfNotDeleting(accountId, clusterKey(cluster), current -> {
if (current.getJoinedInstanceIds() != null) {
prunedInstanceIds.forEach(current.getJoinedInstanceIds()::remove);
}
@@ -330,8 +337,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
}
private Optional<Nodegroup> firstNodeGroup(String clusterName, String accountId) {
String prefix = clusterName + "/";
private Optional<Nodegroup> firstNodeGroup(String clusterKey, String accountId) {
String prefix = clusterKey + "/";
List<Nodegroup> groups;
if (nodeGroupStorage instanceof AccountAwareStorageBackend<Nodegroup> aware) {
groups = aware.scanAllAccountEntries(key -> key.startsWith(prefix)).stream()
@@ -346,8 +353,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
.thenComparing(Nodegroup::getNodegroupName));
}
List<Nodegroup> listNodeGroupsForCluster(String clusterName, String accountId) {
String prefix = clusterName + "/";
List<Nodegroup> listNodeGroupsForCluster(String clusterKey, String accountId) {
String prefix = clusterKey + "/";
if (nodeGroupStorage instanceof AccountAwareStorageBackend<Nodegroup> aware) {
return aware.scanAllAccountEntries(key -> key.startsWith(prefix)).stream()
.filter(entry -> accountId == null || accountId.equals(entry.accountId()))
@@ -376,7 +383,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
if (cluster.getIdentity() != null && cluster.getIdentity().getOidc() != null
&& cluster.getIdentity().getOidc().getIssuer() != null) {
oidcService.ensureKeyForAccount(accountId, cluster.getName(),
oidcService.ensureKeyForAccount(accountId, clusterKey(cluster),
cluster.getIdentity().getOidc().getIssuer());
continue;
}
@@ -384,7 +391,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
String issuer = oidcService.newIssuerUrl(
AwsArnUtils.regionOrDefault(cluster.getArn(), config.defaultRegion()));
cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer)));
oidcService.ensureKeyForAccount(accountId, cluster.getName(), issuer);
oidcService.ensureKeyForAccount(accountId, clusterKey(cluster), issuer);
putClusterForAccount(accountId, cluster);
LOG.infov("Backfilled IRSA OIDC issuer for existing EKS cluster {0} in account {1}",
cluster.getName(), accountId);
@@ -393,22 +400,27 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
void putClusterForAccount(String accountId, Cluster cluster) {
if (storage instanceof AccountAwareStorageBackend<Cluster> aware) {
aware.putForAccount(accountId, cluster.getName(), cluster);
aware.putForAccount(accountId, clusterKey(cluster), cluster);
return;
}
storage.put(cluster.getName(), cluster);
storage.put(clusterKey(cluster), cluster);
}
/**
* Deletes {@code accountId}'s cluster {@code clusterName} found as
* {@link #findAuthenticationCluster(String, String)} finds it: in the request's Region, or the
* account's only cluster of that name.
*/
void deleteClusterForAccount(String accountId, String clusterName) {
synchronized (capacityLock(accountId, clusterName)) {
deleteClusterForAccountHoldingCapacity(accountId, clusterName);
String key = findAuthenticationCluster(accountId, clusterName).map(this::clusterKey)
.orElse(requestClusterKey(clusterName));
synchronized (capacityLock(accountId, key)) {
deleteClusterForAccountHoldingCapacity(accountId, key, clusterName);
}
}
private void deleteClusterForAccountHoldingCapacity(String accountId, String clusterName) {
Cluster cluster = (storage instanceof AccountAwareStorageBackend<Cluster> aware)
? aware.getForAccount(accountId, clusterName).orElse(null)
: storage.get(clusterName).orElse(null);
private void deleteClusterForAccountHoldingCapacity(String accountId, String clusterKey, String clusterName) {
Cluster cluster = findClusterForAccount(accountId, clusterKey).orElse(null);
if (cluster != null) {
if (cluster.getAccountId() == null) {
cluster.setAccountId(accountId);
@@ -419,16 +431,16 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
try {
clearAppliedClusterUserData(cluster, clusterName);
if (cluster == null || cluster.getArn() == null) {
String fallbackArn = AwsArnUtils.Arn.of("eks", config.defaultRegion(), accountId,
String fallbackArn = AwsArnUtils.Arn.of("eks", regionOfKey(clusterKey), accountId,
"cluster/" + clusterName).toString();
appliedClusterUserData.remove(fallbackArn);
}
synchronized (clustersBeingDeleted) {
if (storage instanceof AccountAwareStorageBackend<Cluster> aware) {
aware.deleteForAccount(accountId, clusterName);
aware.deleteForAccount(accountId, clusterKey);
return;
}
storage.delete(clusterName);
storage.delete(clusterKey);
}
} finally {
if (cluster != null) {
@@ -574,6 +586,95 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
return config != null ? config.defaultRegion() : regionResolver.getRegion();
}
/**
* The account-relative key a cluster is stored under, {@code <region>::<name>}. Cluster names are
* unique only within a Region of an account (#7966), so the key carries the Region; node groups
* and Fargate profiles are stored under it followed by {@code /<child name>}. Neither a Region
* nor a cluster name holds a colon or a slash, so keys never run into one another.
*/
static String clusterKey(String region, String clusterName) {
return region + KEY_SEPARATOR + clusterName;
}
/** The key {@code cluster} is stored under, in the Region its ARN names. */
String clusterKey(Cluster cluster) {
return clusterKey(resolveClusterRegion(cluster), cluster.getName());
}
private String requestClusterKey(String clusterName) {
return clusterKey(regionResolver.getRegion(), clusterName);
}
private static String regionOfKey(String clusterKey) {
return clusterKey.substring(0, clusterKey.indexOf(KEY_SEPARATOR));
}
/**
* The Region that qualifies a new cluster's Docker names, or null for the unqualified name. A
* cluster in the default Region keeps the name it always had, so its container, volume and
* {@code endpoint-mode=network} DNS name do not change, unless the request's account already has
* a cluster of that name in another Region: that one may hold the unqualified name.
*/
private String dockerNameRegion(String region, String name) {
if (!region.equals(config.defaultRegion())) {
return region;
}
String suffix = KEY_SEPARATOR + name;
return storage.scan(key -> key.endsWith(suffix)).isEmpty() ? null : region;
}
/**
* Moves records persisted before cluster names became Regional (#7966) from keys built on the
* bare cluster name onto Region-qualified ones. The Region comes from each record's ARN, which
* has always carried it. A cluster's OIDC signing key moves with it, so tokens it signed before
* the upgrade still verify. Docker names are untouched: a migrated cluster has no
* {@link Cluster#getDockerNameRegion()}, so it keeps its containers and volume.
*/
private void migrateLegacyKeys() {
migrateLegacyEntries(storage, this::clusterKey);
migrateLegacyEntries(nodeGroupStorage, group -> group.getClusterName() == null ? null
: nodeGroupKey(clusterKey(AwsArnUtils.regionOrDefault(group.getNodegroupArn(), config.defaultRegion()),
group.getClusterName()), group.getNodegroupName()));
migrateLegacyEntries(fargateProfileStorage, profile -> profile.getClusterName() == null ? null
: fargateProfileKey(clusterKey(AwsArnUtils.regionOrDefault(profile.getFargateProfileArn(),
config.defaultRegion()), profile.getClusterName()), profile.getFargateProfileName()));
for (AccountAwareStorageBackend.AccountEntry<Cluster> entry : allClusterEntries()) {
Cluster cluster = entry.value();
if (cluster.getName() != null && cluster.getIdentity() != null && cluster.getIdentity().getOidc() != null) {
oidcService.migrateLegacyKey(entry.accountId(), cluster.getName(), clusterKey(cluster),
cluster.getIdentity().getOidc().getIssuer());
}
}
}
private <V> void migrateLegacyEntries(StorageBackend<String, V> store, Function<V, String> destinationKey) {
if (!(store instanceof AccountAwareStorageBackend<V> aware)) {
for (String key : new ArrayList<>(store.keys())) {
if (key.contains(KEY_SEPARATOR)) {
continue;
}
store.get(key).ifPresent(value -> {
String destination = destinationKey.apply(value);
if (destination != null && !destination.equals(key)) {
if (store.get(destination).isEmpty()) {
store.put(destination, value);
}
store.delete(key);
}
});
}
return;
}
Set<String> accounts = new LinkedHashSet<>();
for (String rawKey : aware.scanAllAccountsWithRawKeys().keySet()) {
accounts.add(AccountAwareStorageBackend.hasAccountPrefix(rawKey)
? rawKey.substring(0, 12) : config.defaultAccountId());
}
for (String accountId : accounts) {
aware.migrateLegacyEntries(accountId, key -> !key.contains(KEY_SEPARATOR), destinationKey, value -> true);
}
}
private static String randomHex(int len) {
byte[] bytes = new byte[(len + 1) / 2];
ThreadLocalRandom.current().nextBytes(bytes);
@@ -615,11 +716,25 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
+ "satisfy regular expression pattern: ^" + CLUSTER_NAME_REGEX + "$",
400);
}
if (storage.get(name).isPresent()) {
throw new AwsException("ResourceInUseException",
"Cluster already exists: " + name, 409);
// Cluster names are unique only within a Region of an account (#7966). The key stays reserved
// until the cluster is stored, so a concurrent create of the same name is refused, not let
// through to overwrite this one.
String reservation = regionResolver.getAccountId() + "/" + requestClusterKey(name);
if (!clustersBeingCreated.add(reservation)) {
throw new AwsException("ResourceInUseException", "Cluster already exists: " + name, 409);
}
try {
if (storage.get(requestClusterKey(name)).isPresent()) {
throw new AwsException("ResourceInUseException",
"Cluster already exists: " + name, 409);
}
return createReservedCluster(request, name);
} finally {
clustersBeingCreated.remove(reservation);
}
}
private Cluster createReservedCluster(CreateClusterRequest request, String name) {
AccessConfig requestedAccess = request.getAccessConfig();
String authenticationMode = requestedAccess == null || requestedAccess.authenticationMode() == null
? "CONFIG_MAP" : requestedAccess.authenticationMode();
@@ -640,6 +755,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
cluster.setArn(arn);
cluster.setAccountId(accountId);
cluster.setCreatedAt(Instant.now());
cluster.setDockerNameRegion(dockerNameRegion(region, name));
if (request.getVersion() != null && !request.getVersion().isBlank()) {
String requestedVersion = request.getVersion().trim();
@@ -701,7 +817,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
try {
String issuer = oidcService.newIssuerUrl(region);
cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer)));
oidcService.ensureKey(name, issuer);
oidcService.ensureKey(clusterKey(region, name), issuer);
if (config.services().eks().mock()) {
markMetadataOnlyActive(cluster);
@@ -719,7 +835,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
}
storage.put(name, cluster);
storage.put(clusterKey(region, name), cluster);
} catch (RuntimeException e) {
if (clusterSg != null) {
try {
@@ -746,9 +862,72 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
cluster.setEndpoint("https://localhost:" + config.services().eks().apiServerBasePort());
}
/**
* {@code accountId}'s cluster {@code name} in {@code region}, for callers that act outside the
* account's request context, such as the k3s API server calling Floci's webhooks.
*/
public Optional<Cluster> findAuthenticationCluster(String accountId, String region, String name) {
return findClusterForAccount(accountId, clusterKey(region, name));
}
/**
* {@code accountId}'s cluster {@code name} for a caller that does not name its Region: the one in
* the request's Region, or else the account's only cluster of that name. Empty when the name is
* in several Regions and none is the request's, since the caller cannot be told which it meant.
*/
public Optional<Cluster> findAuthenticationCluster(String accountId, String name) {
return storage instanceof AccountAwareStorageBackend<Cluster> aware
? aware.getForAccount(accountId, name) : storage.get(name);
Optional<Cluster> inRequestRegion = findClusterForAccount(accountId, requestClusterKey(name));
if (inRequestRegion.isPresent()) {
return inRequestRegion;
}
String suffix = KEY_SEPARATOR + name;
List<Cluster> named = storage instanceof AccountAwareStorageBackend<Cluster> aware
? aware.scanForAccount(accountId, key -> key.endsWith(suffix))
: storage.scan(key -> key.endsWith(suffix));
return named.size() == 1 ? Optional.of(named.getFirst()) : Optional.empty();
}
/**
* {@code accountId}'s cluster {@code name} that was created before cluster names became Regional,
* for a route such a cluster registered without a Region in it. Names were unique within an
* account then, and a later cluster sharing the name is always Region-qualified in Docker, so at
* most one cluster of the name has no {@link Cluster#getDockerNameRegion()}: the one that
* registered the route. Preferring the request's Region instead could pick a newer same-named
* cluster in the default Region.
*/
public Optional<Cluster> findPreRegionalCluster(String accountId, String name) {
String suffix = KEY_SEPARATOR + name;
List<Cluster> unqualified = (storage instanceof AccountAwareStorageBackend<Cluster> aware
? aware.scanForAccount(accountId, key -> key.endsWith(suffix))
: storage.scan(key -> key.endsWith(suffix))).stream()
.filter(cluster -> cluster.getDockerNameRegion() == null)
.toList();
return unqualified.size() == 1 ? Optional.of(unqualified.getFirst()) : Optional.empty();
}
/**
* The cluster a {@code _floci/eks/clusters/<name>/...} route names. Those routes are often called
* unsigned, so a {@code region} the route carries wins; without one the request's Region is tried
* first and then the account's only cluster of that name, as
* {@link #findAuthenticationCluster(String, String)} does.
*/
public Cluster findClusterForFlociRoute(String name, String region) {
String accountId = regionResolver.getAccountId();
return (region == null || region.isBlank()
? findAuthenticationCluster(accountId, name)
: findAuthenticationCluster(accountId, region, name))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No cluster found for name: " + name, 404));
}
/** The Region of {@code cluster}, from its ARN. */
public String clusterRegion(Cluster cluster) {
return resolveClusterRegion(cluster);
}
private Optional<Cluster> findClusterForAccount(String accountId, String clusterKey) {
return storage instanceof AccountAwareStorageBackend<Cluster> aware && accountId != null
? aware.getForAccount(accountId, clusterKey) : storage.get(clusterKey);
}
/**
@@ -759,7 +938,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
* or the handler would refuse the lookup.
*/
public Optional<String> findResourceArn(String clusterName, String collection, String name) {
Optional<Cluster> cluster = storage.get(clusterName);
Optional<Cluster> cluster = storage.get(requestClusterKey(clusterName));
if (cluster.isEmpty() || collection == null) {
return cluster.map(Cluster::getArn);
}
@@ -782,8 +961,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
}
/** The cluster {@code name} in the request's Region. */
public Cluster describeCluster(String name) {
Cluster cluster = storage.get(name)
Cluster cluster = storage.get(requestClusterKey(name))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No cluster found for name: " + name, 404));
if (cluster.getLogging() == null) {
@@ -799,7 +979,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
try {
Cluster cluster = describeCluster(name);
validateInstanceRegion(cluster, instance);
saveClusterIfNotDeleting(accountId, name, current ->
saveClusterIfNotDeleting(accountId, clusterKey(cluster), current ->
clusterManager.recordJoinedInstanceId(current, instance));
} catch (AwsException e) {
LOG.warnv("Cannot join instance {0} to cluster {1}: {2}",
@@ -820,7 +1000,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
Cluster cluster = describeCluster(clusterName);
validateInstanceRegion(cluster, instance);
clusterManager.joinInstance(cluster, instance);
storage.put(cluster.getName(), cluster);
storage.put(clusterKey(cluster), cluster);
}
void joinInstance(String clusterName, String instanceId) {
@@ -905,8 +1085,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
// A first node group replacing the node holds this lock while the swap runs; deleting
// meanwhile would find no container to stop and have its cluster written back. Read the
// cluster only once the lock is held: a delete that waited may find it gone.
synchronized (capacityLock(regionResolver.getAccountId(), name)) {
Cluster cluster = storage.get(name)
synchronized (capacityLock(regionResolver.getAccountId(), requestClusterKey(name))) {
Cluster cluster = storage.get(requestClusterKey(name))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No cluster found for name: " + name, 404));
if (inRequestRegion) {
@@ -948,9 +1128,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
addons.deleteClusterAddons(cluster);
}
synchronized (clustersBeingDeleted) {
storage.delete(name);
storage.delete(clusterKey(cluster));
clearAppliedClusterUserData(cluster, name);
oidcService.deleteKey(name);
oidcService.deleteKey(clusterKey(cluster));
}
return cluster;
} finally {
@@ -996,7 +1176,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
throw new AwsException("InvalidParameterException", "subnets are required", 400);
}
String storageKey = nodeGroupKey(clusterName, nodegroupName);
String clusterKey = clusterKey(cluster);
String storageKey = nodeGroupKey(clusterKey, nodegroupName);
if (nodeGroupStorage.get(storageKey).isPresent()) {
throw new AwsException("ResourceInUseException",
"Nodegroup already exists: " + nodegroupName, 409);
@@ -1043,8 +1224,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
nodeGroup.setLabels(request.getLabels() != null ? new HashMap<>(request.getLabels()) : null);
nodeGroup.setTags(request.getTags() != null ? new HashMap<>(request.getTags()) : new HashMap<>());
String capacityKey = accountId + "/" + clusterName;
Object capacityLock = capacityLock(accountId, clusterName);
String capacityKey = accountId + "/" + clusterKey;
Object capacityLock = capacityLock(accountId, clusterKey);
boolean hasUserData = launchTemplateData != null && launchTemplateData.getUserData() != null
&& !launchTemplateData.getUserData().isBlank();
Cluster currentCluster;
@@ -1057,7 +1238,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
currentCluster = describeCluster(clusterName);
pendingFirst = pendingFirstNodeGroups.get(capacityKey);
boolean firstGroup = firstNodeGroup(clusterName, accountId).isEmpty() && pendingFirst == null;
boolean firstGroup = firstNodeGroup(clusterKey, accountId).isEmpty() && pendingFirst == null;
if (firstGroup && !config.services().eks().mock() && clusterManager != null) {
applyFirstNodeGroupCapacity(clusterName, nodegroupName, currentCluster, nodeGroup);
if (currentCluster.getContainerId() != null && currentCluster.getStatus() == ClusterStatus.ACTIVE) {
@@ -1067,16 +1248,16 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
} else if (!firstGroup && pendingFirst == null
&& !config.services().eks().mock() && clusterManager != null) {
if (currentCluster.getNodeInstanceType() == null) {
firstNodeGroup(clusterName, accountId).ifPresent(group ->
firstNodeGroup(clusterKey, accountId).ifPresent(group ->
currentCluster.setNodeInstanceType(selectedNodeInstanceType(group)));
storage.put(clusterName, currentCluster);
storage.put(clusterKey, currentCluster);
}
if (!nodeGroup.getInstanceTypes().isEmpty()
&& !nodeGroup.getInstanceTypes().contains(currentCluster.getNodeInstanceType())) {
LOG.warnv("EKS cluster {0} has one shared node; nodegroup {1} cannot change its capacity from {2}",
clusterName, nodegroupName, currentCluster.getNodeInstanceType());
}
firstNodeGroup(clusterName, accountId).ifPresent(first -> {
firstNodeGroup(clusterKey, accountId).ifPresent(first -> {
if (!nodegroupName.equals(first.getNodegroupName())) {
LOG.warnv(
"EKS cluster {0} has one shared node; nodegroup {1} metadata (labels/taints) is not applied to the node (already represented by nodegroup {2})",
@@ -1123,7 +1304,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
if (nodeGroupStorage.get(storageKey)
.filter(saved -> arn.equals(saved.getNodegroupArn())).isPresent()) {
if (nodeGroup.getStatus() == NodegroupStatus.CREATING) {
if (!ownsPendingFirst && firstNodeGroup(clusterName, accountId).isEmpty()
if (!ownsPendingFirst && firstNodeGroup(clusterKey, accountId).isEmpty()
&& !config.services().eks().mock() && clusterManager != null) {
Cluster refreshedCluster = describeCluster(clusterName);
applyFirstNodeGroupCapacity(clusterName, nodegroupName, refreshedCluster, nodeGroup);
@@ -1170,7 +1351,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
clusterName, e.getMessage());
}
}
storage.put(clusterName, currentCluster);
storage.put(clusterKey(currentCluster), currentCluster);
}
private String selectedNodeInstanceType(Nodegroup group) {
@@ -1219,31 +1400,32 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
public Nodegroup describeNodeGroup(String clusterName, String nodegroupName) {
describeCluster(clusterName);
return nodeGroupStorage.get(nodeGroupKey(clusterName, nodegroupName))
return nodeGroupStorage.get(nodeGroupKey(requestClusterKey(clusterName), nodegroupName))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No nodegroup found for name: " + nodegroupName, 404));
}
public List<String> listNodeGroups(String clusterName) {
describeCluster(clusterName);
String prefix = clusterName + "/";
String prefix = requestClusterKey(clusterName) + "/";
return nodeGroupStorage.scan(key -> key.startsWith(prefix)).stream()
.map(Nodegroup::getNodegroupName)
.collect(Collectors.toList());
}
/** Serializes node group capacity changes and cluster deletion; taken before clustersBeingDeleted. */
private Object capacityLock(String accountId, String clusterName) {
return nodeGroupCapacityLocks.computeIfAbsent(accountId + "/" + clusterName, ignored -> new Object());
private Object capacityLock(String accountId, String clusterKey) {
return nodeGroupCapacityLocks.computeIfAbsent(accountId + "/" + clusterKey, ignored -> new Object());
}
public Nodegroup deleteNodeGroup(String clusterName, String nodegroupName) {
Object capacityLock = capacityLock(regionResolver.getAccountId(), clusterName);
String clusterKey = requestClusterKey(clusterName);
Object capacityLock = capacityLock(regionResolver.getAccountId(), clusterKey);
synchronized (capacityLock) {
Nodegroup nodeGroup = describeNodeGroup(clusterName, nodegroupName);
nodeGroup.setStatus(NodegroupStatus.DELETING);
nodeGroup.setModifiedAt(Instant.now());
nodeGroupStorage.delete(nodeGroupKey(clusterName, nodegroupName));
nodeGroupStorage.delete(nodeGroupKey(clusterKey, nodegroupName));
return nodeGroup;
}
}
@@ -1259,7 +1441,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
throw new AwsException("InvalidParameterException", "podExecutionRoleArn is required", 400);
}
String storageKey = fargateProfileKey(clusterName, fargateProfileName);
String storageKey = fargateProfileKey(clusterKey(cluster), fargateProfileName);
if (fargateProfileStorage.get(storageKey).isPresent()) {
throw new AwsException("ResourceInUseException",
"Fargate profile already exists: " + fargateProfileName, 409);
@@ -1290,14 +1472,14 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
public FargateProfile describeFargateProfile(String clusterName, String fargateProfileName) {
describeCluster(clusterName);
return fargateProfileStorage.get(fargateProfileKey(clusterName, fargateProfileName))
return fargateProfileStorage.get(fargateProfileKey(requestClusterKey(clusterName), fargateProfileName))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No fargate profile found for name: " + fargateProfileName, 404));
}
public List<String> listFargateProfiles(String clusterName) {
describeCluster(clusterName);
String prefix = clusterName + "/";
String prefix = requestClusterKey(clusterName) + "/";
return fargateProfileStorage.scan(key -> key.startsWith(prefix)).stream()
.map(FargateProfile::getFargateProfileName)
.collect(Collectors.toList());
@@ -1306,7 +1488,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
public FargateProfile deleteFargateProfile(String clusterName, String fargateProfileName) {
FargateProfile profile = describeFargateProfile(clusterName, fargateProfileName);
profile.setStatus(FargateProfileStatus.DELETING);
fargateProfileStorage.delete(fargateProfileKey(clusterName, fargateProfileName));
fargateProfileStorage.delete(fargateProfileKey(requestClusterKey(clusterName), fargateProfileName));
return profile;
}
@@ -1378,6 +1560,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
String clusterName = parts[1];
String childName = child ? parts[2] : "";
// The ARN names the Region its cluster is in, and cluster names are unique only within one.
String clusterKey = clusterKey(AwsArnUtils.parse(resourceArn).region(), clusterName);
UnaryOperator<Map<String, String>> change = current -> {
Map<String, String> next = edit.apply(current);
if (!next.equals(current)) {
@@ -1386,28 +1570,28 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
return next;
};
Optional<Map<String, String>> tags = switch (parts[0]) {
case "cluster" -> storage.get(clusterName).map(cluster -> applyTags(cluster.getTags(), change, next -> {
case "cluster" -> storage.get(clusterKey).map(cluster -> applyTags(cluster.getTags(), change, next -> {
cluster.setTags(new HashMap<>(next));
storage.put(clusterName, cluster);
storage.put(clusterKey, cluster);
}));
case "nodegroup" -> nodeGroupStorage.get(nodeGroupKey(clusterName, childName))
case "nodegroup" -> nodeGroupStorage.get(nodeGroupKey(clusterKey, childName))
.filter(nodegroup -> resourceArn.equals(nodegroup.getNodegroupArn()))
.map(nodegroup -> applyTags(nodegroup.getTags(), change, next -> {
nodegroup.setTags(new HashMap<>(next));
nodeGroupStorage.put(nodeGroupKey(clusterName, childName), nodegroup);
nodeGroupStorage.put(nodeGroupKey(clusterKey, childName), nodegroup);
}));
case "fargateprofile" -> fargateProfileStorage.get(fargateProfileKey(clusterName, childName))
case "fargateprofile" -> fargateProfileStorage.get(fargateProfileKey(clusterKey, childName))
.filter(profile -> resourceArn.equals(profile.getFargateProfileArn()))
.map(profile -> applyTags(profile.getTags(), change, next -> {
profile.setTags(new HashMap<>(next));
fargateProfileStorage.put(fargateProfileKey(clusterName, childName), profile);
fargateProfileStorage.put(fargateProfileKey(clusterKey, childName), profile);
}));
case "addon" -> addons == null ? Optional.empty() : storage.get(clusterName)
case "addon" -> addons == null ? Optional.empty() : storage.get(clusterKey)
.flatMap(cluster -> addons.retag(cluster, childName, resourceArn, change));
case "podidentityassociation" -> podIdentityAssociations == null ? Optional.empty()
: storage.get(clusterName)
: storage.get(clusterKey)
.flatMap(cluster -> podIdentityAssociations.retag(cluster, childName, resourceArn, change));
case "access-entry" -> accessEntries == null ? Optional.empty() : storage.get(clusterName)
case "access-entry" -> accessEntries == null ? Optional.empty() : storage.get(clusterKey)
.flatMap(cluster -> accessEntries.retag(cluster, resourceArn, change));
default -> Optional.empty();
};
@@ -1642,12 +1826,12 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
return List.of(new EncryptionConfig(List.of("secrets"), new Provider(config.getProvider().getKeyArn())));
}
private String nodeGroupKey(String clusterName, String nodegroupName) {
return clusterName + "/" + nodegroupName;
private static String nodeGroupKey(String clusterKey, String nodegroupName) {
return clusterKey + "/" + nodegroupName;
}
private String fargateProfileKey(String clusterName, String fargateProfileName) {
return clusterName + "/" + fargateProfileName;
private static String fargateProfileKey(String clusterKey, String fargateProfileName) {
return clusterKey + "/" + fargateProfileName;
}
private NodegroupScalingConfig defaultScalingConfig() {
@@ -1816,7 +2000,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
if (cluster == null || cluster.getName() == null || isClusterDeleting(accountId, cluster)) {
return;
}
String key = (accountId != null ? accountId : "default") + "/" + cluster.getName();
String key = (accountId != null ? accountId : "default") + "/" + clusterKey(cluster);
if (!restoringClusters.add(key)) {
return;
}
@@ -1853,9 +2037,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
private void putCluster(Cluster cluster) {
if (cluster.getAccountId() != null && storage instanceof AccountAwareStorageBackend<Cluster> aware) {
aware.putForAccount(cluster.getAccountId(), cluster.getName(), cluster);
aware.putForAccount(cluster.getAccountId(), clusterKey(cluster), cluster);
} else {
storage.put(cluster.getName(), cluster);
storage.put(clusterKey(cluster), cluster);
}
}
@@ -57,7 +57,7 @@ class EksWorkerAuthentication {
|| !region.equals(token.region()) || identity.roleArn() == null || identity.roleId() == null) {
return Optional.empty();
}
Optional<Cluster> cluster = eks.findAuthenticationCluster(account, name)
Optional<Cluster> cluster = eks.findAuthenticationCluster(account, region, name)
.filter(value -> value.getArn() != null && value.getArn().equals(
AwsArnUtils.Arn.of("eks", region, account, "cluster/" + name).toString()))
.filter(value -> createdAt.equals(String.valueOf(value.getCreatedAt())));
@@ -128,6 +128,18 @@ public class Cluster {
@JsonInclude(JsonInclude.Include.NON_NULL)
private Boolean defaultStorageClass;
/**
* The Region that qualifies this cluster's Docker container and volume names, or null for a
* name without one. Cluster names are unique only within a Region, so a cluster outside the
* default Region, or one sharing its name with a cluster in another Region, is qualified.
* Persisted because a restore re-derives the Docker name from the record, and a cluster
* created before Region qualification must keep its unqualified name. Internal metadata
* omitted from AWS API responses.
*/
@JsonProperty("dockerNameRegion")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String dockerNameRegion;
// Internal persisted map of joined EC2 instance IDs to their region.
@JsonProperty("joinedInstanceIds")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@@ -224,6 +236,9 @@ public class Cluster {
public String getDockerName() { return dockerName; }
public void setDockerName(String dockerName) { this.dockerName = dockerName; }
public String getDockerNameRegion() { return dockerNameRegion; }
public void setDockerNameRegion(String dockerNameRegion) { this.dockerNameRegion = dockerNameRegion; }
public String getPodCidr() { return podCidr; }
public void setPodCidr(String podCidr) { this.podCidr = podCidr; }
@@ -261,6 +276,7 @@ public class Cluster {
c.finalizePending = this.finalizePending;
c.explicitVersion = this.explicitVersion;
c.dockerName = this.dockerName;
c.dockerNameRegion = this.dockerNameRegion;
c.nodeInstanceType = this.nodeInstanceType;
c.clusterArgs = this.clusterArgs != null ? new ArrayList<>(this.clusterArgs) : null;
c.defaultStorageClass = this.defaultStorageClass;