feat(eks): implement cluster addon management (#4038)

* feat(eks): implement cluster addon management

* fix(eks): address addon management review comments

* fix(eks): handle uncataloged k8s versions and association validation ordering
This commit is contained in:
Simone Primarosa authored and GitHub committed 2026-09-21 14:18:07 -04:00
1 parent 49d28fb685
commit 6a3380d13a
22 files changed
+2357 -6

No files matched your search

@@ -0,0 +1,188 @@
package io.github.hectorvent.floci.services.eks;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.eks.model.AddonInfo;
import io.github.hectorvent.floci.services.eks.model.AddonVersionInfo;
import io.github.hectorvent.floci.services.eks.model.Compatibility;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@ApplicationScoped
public class EksAddonCatalog {
private static final Logger LOG = Logger.getLogger(EksAddonCatalog.class);
private static final String CATALOG_RESOURCE_NAME = "eks/addon-versions.json";
private static final ObjectMapper MAPPER = new ObjectMapper();
private volatile List<AddonInfo> addons;
public EksAddonCatalog() {
// Loaded lazily on first access.
}
public EksAddonCatalog(List<AddonInfo> addons) {
this.addons = addons != null ? List.copyOf(addons) : List.of();
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
record CatalogWrapper(List<AddonInfo> addons) {}
private List<AddonInfo> getAddons() {
if (addons == null) {
synchronized (this) {
if (addons == null) {
addons = loadCatalog();
}
}
}
return addons;
}
private List<AddonInfo> loadCatalog() {
try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(CATALOG_RESOURCE_NAME)) {
if (is == null) {
LOG.warnv("EKS addon versions catalog resource not found: {0}", CATALOG_RESOURCE_NAME);
return List.of();
}
CatalogWrapper wrapper = MAPPER.readValue(is, CatalogWrapper.class);
return wrapper.addons() != null ? List.copyOf(wrapper.addons()) : List.of();
} catch (IOException e) {
LOG.errorv(e, "Failed to load EKS addon versions catalog from {0}", CATALOG_RESOURCE_NAME);
return List.of();
}
}
public List<AddonInfo> allAddons() {
return getAddons();
}
public Optional<AddonInfo> findAddon(String addonName) {
if (addonName == null || addonName.isBlank()) {
return Optional.empty();
}
String normalized = addonName.trim();
return getAddons().stream()
.filter(a -> a.addonName().equalsIgnoreCase(normalized))
.findFirst();
}
public boolean isKnownAddon(String addonName) {
return findAddon(addonName).isPresent();
}
public boolean isClusterVersionInCatalog(String kubernetesVersion) {
if (kubernetesVersion == null || kubernetesVersion.isBlank()) {
return false;
}
String k8s = normalizeK8sVersion(kubernetesVersion);
return getAddons().stream()
.flatMap(a -> a.addonVersions().stream())
.filter(v -> v.compatibilities() != null)
.flatMap(v -> v.compatibilities().stream())
.anyMatch(c -> k8s.equals(c.clusterVersion()));
}
public boolean isVersionSupported(String addonName, String addonVersion) {
return isVersionSupported(addonName, addonVersion, null);
}
public boolean isVersionSupported(String addonName, String addonVersion, String kubernetesVersion) {
if (addonName == null || addonName.isBlank() || addonVersion == null || addonVersion.isBlank()) {
return false;
}
String k8s = kubernetesVersion != null && isClusterVersionInCatalog(kubernetesVersion)
? normalizeK8sVersion(kubernetesVersion) : null;
return findAddon(addonName)
.map(AddonInfo::addonVersions)
.orElse(List.of())
.stream()
.filter(v -> v.addonVersion().equalsIgnoreCase(addonVersion.trim()))
.anyMatch(v -> k8s == null || isCompatible(v, k8s, false));
}
public Optional<String> resolveDefaultVersion(String addonName, String kubernetesVersion) {
List<AddonVersionInfo> versions = findAddon(addonName)
.map(AddonInfo::addonVersions)
.orElse(List.of());
if (versions.isEmpty()) {
return Optional.empty();
}
String k8s = kubernetesVersion != null && !kubernetesVersion.isBlank()
? normalizeK8sVersion(kubernetesVersion) : null;
if (k8s != null) {
Optional<String> def = versions.stream()
.filter(v -> isCompatible(v, k8s, true))
.map(AddonVersionInfo::addonVersion)
.findFirst();
if (def.isPresent()) {
return def;
}
Optional<String> any = versions.stream()
.filter(v -> isCompatible(v, k8s, false))
.map(AddonVersionInfo::addonVersion)
.findFirst();
if (any.isPresent()) {
return any;
}
}
return versions.stream()
.filter(v -> isCompatible(v, null, true))
.map(AddonVersionInfo::addonVersion)
.findFirst()
.or(() -> Optional.of(versions.getFirst().addonVersion()));
}
public List<AddonInfo> describeVersions(String addonName, String kubernetesVersion,
List<String> publishers, List<String> types, List<String> owners) {
String k8s = kubernetesVersion != null && !kubernetesVersion.isBlank()
? normalizeK8sVersion(kubernetesVersion) : null;
return getAddons().stream()
.filter(a -> addonName == null || addonName.isBlank() || a.addonName().equalsIgnoreCase(addonName.trim()))
.filter(a -> publishers == null || publishers.isEmpty() || publishers.contains(a.publisher()))
.filter(a -> types == null || types.isEmpty() || types.contains(a.type()))
.filter(a -> owners == null || owners.isEmpty() || owners.contains(a.owner()))
.map(a -> k8s == null ? a : filterByK8s(a, k8s))
.filter(Objects::nonNull)
.toList();
}
private static AddonInfo filterByK8s(AddonInfo addon, String k8s) {
List<AddonVersionInfo> filtered = addon.addonVersions().stream()
.filter(v -> isCompatible(v, k8s, false))
.toList();
return filtered.isEmpty() ? null
: new AddonInfo(addon.addonName(), addon.type(), filtered, addon.publisher(), addon.owner());
}
private static boolean isCompatible(AddonVersionInfo versionInfo, String k8s, boolean defaultOnly) {
if (versionInfo.compatibilities() == null) {
return false;
}
return versionInfo.compatibilities().stream().anyMatch(c ->
(!defaultOnly || Boolean.TRUE.equals(c.defaultVersion()))
&& (k8s == null || k8s.equals(c.clusterVersion())));
}
private static String normalizeK8sVersion(String version) {
if (version == null) {
return "";
}
String v = version.trim();
if (v.startsWith("v")) {
v = v.substring(1);
}
String[] parts = v.split("\\.");
return parts.length >= 2 ? parts[0] + "." + parts[1] : v;
}
}
@@ -0,0 +1,528 @@
package io.github.hectorvent.floci.services.eks;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.eks.model.Addon;
import io.github.hectorvent.floci.services.eks.model.AddonHealth;
import io.github.hectorvent.floci.services.eks.model.AddonInfo;
import io.github.hectorvent.floci.services.eks.model.AddonPodIdentityAssociation;
import io.github.hectorvent.floci.services.eks.model.Cluster;
import io.github.hectorvent.floci.services.eks.model.ClusterStatus;
import io.github.hectorvent.floci.services.eks.model.CreateAddonRequest;
import io.github.hectorvent.floci.services.eks.model.CreatePodIdentityAssociationRequest;
import io.github.hectorvent.floci.services.eks.model.PodIdentityAssociation;
import io.github.hectorvent.floci.services.eks.model.Update;
import io.github.hectorvent.floci.services.eks.model.UpdateAddonRequest;
import io.github.hectorvent.floci.services.eks.model.UpdateParam;
import io.github.hectorvent.floci.services.iam.IamService;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
@ApplicationScoped
public class EksAddonService {
private static final Logger LOG = Logger.getLogger(EksAddonService.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final int DEFAULT_PAGE_SIZE = 100;
private static final int MAX_PAGE_SIZE = 100;
private final StorageBackend<String, StoredAddon> storage;
private final StorageBackend<String, StoredUpdate> updatesStorage;
private final EksAddonCatalog catalog;
private final IamService iam;
private final EksPodIdentityAssociationService podIdentityAssociations;
@Inject
public EksAddonService(StorageFactory storageFactory, EksAddonCatalog catalog,
IamService iam, EksPodIdentityAssociationService podIdentityAssociations) {
this(storageFactory.create("eks", "eks-addons.json",
new TypeReference<Map<String, StoredAddon>>() {}),
storageFactory.create("eks", "eks-updates.json",
new TypeReference<Map<String, StoredUpdate>>() {}),
catalog, iam, podIdentityAssociations);
}
EksAddonService(StorageBackend<String, StoredAddon> storage,
StorageBackend<String, StoredUpdate> updatesStorage,
EksAddonCatalog catalog,
IamService iam,
EksPodIdentityAssociationService podIdentityAssociations) {
this.storage = storage;
this.updatesStorage = updatesStorage;
this.catalog = catalog;
this.iam = iam;
this.podIdentityAssociations = podIdentityAssociations;
}
@RegisterForReflection
public record StoredAddon(Addon addon, String clientRequestToken) {}
@RegisterForReflection
public record StoredUpdate(Update update, String addonName) {}
@RegisterForReflection
public record AddonNamesPage(List<String> addons, String nextToken) {}
@RegisterForReflection
public record AddonVersionsPage(List<AddonInfo> addons, String nextToken) {}
public synchronized Addon create(Cluster cluster, CreateAddonRequest request) {
requireActiveCluster(cluster);
if (request == null || request.addonName() == null || request.addonName().isBlank()) {
throw new AwsException("InvalidParameterException", "addonName is required", 400);
}
String addonName = request.addonName().trim();
if (!catalog.isKnownAddon(addonName)) {
throw new AwsException("InvalidParameterException",
"Addon name '" + addonName + "' is not valid", 400);
}
String storageKey = prefix(cluster) + addonName.toLowerCase(Locale.ROOT);
Optional<StoredAddon> existing = storage.get(storageKey);
if (existing.isPresent()) {
StoredAddon stored = existing.get();
if (request.clientRequestToken() != null && !request.clientRequestToken().isBlank()
&& request.clientRequestToken().equals(stored.clientRequestToken())) {
if (parametersMatch(stored.addon(), request)) {
return stored.addon();
}
throw new AwsException("InvalidParameterException",
"clientRequestToken was already used with different parameters", 400);
}
throw new AwsException("ResourceInUseException", "Addon already exists: " + addonName, 409);
}
String version = (request.addonVersion() != null && !request.addonVersion().isBlank())
? request.addonVersion().trim()
: catalog.resolveDefaultVersion(addonName, cluster.getVersion()).orElse(null);
if (version == null || !catalog.isVersionSupported(addonName, version, cluster.getVersion())) {
throw new AwsException("InvalidParameterException",
"Addon version specified is not supported", 400);
}
if (request.serviceAccountRoleArn() != null && !request.serviceAccountRoleArn().isBlank()) {
validateRoleArn(cluster, request.serviceAccountRoleArn(), "serviceAccountRoleArn");
}
if (request.resolveConflicts() != null && !request.resolveConflicts().isBlank()) {
validateResolveConflicts(request.resolveConflicts());
}
Map<String, String> tags = request.tags() != null ? request.tags() : Map.of();
validateTags(tags);
List<String> associationArns = createOrLinkPodIdentityAssociations(cluster, addonName, request.podIdentityAssociations());
double now = Instant.now().toEpochMilli() / 1000.0;
String addonArn = generateAddonArn(cluster, addonName);
Optional<AddonInfo> addonInfo = catalog.findAddon(addonName);
String owner = addonInfo.map(AddonInfo::owner).orElse("aws");
String publisher = addonInfo.map(AddonInfo::publisher).orElse("eks");
Addon addon = new Addon(
addonArn,
addonName,
version,
cluster.getName(),
"ACTIVE",
new AddonHealth(List.of()),
now,
now,
request.serviceAccountRoleArn(),
request.configurationValues(),
Map.copyOf(tags),
List.copyOf(associationArns),
owner,
publisher
);
storage.put(storageKey, new StoredAddon(addon, request.clientRequestToken()));
LOG.infov("Created EKS addon {0} on cluster {1} with version {2}", addonName, cluster.getName(), version);
return addon;
}
public Addon describe(Cluster cluster, String addonName) {
requireActiveCluster(cluster);
if (addonName == null || addonName.isBlank()) {
throw new AwsException("InvalidParameterException", "addonName is required", 400);
}
String storageKey = prefix(cluster) + addonName.trim().toLowerCase(Locale.ROOT);
StoredAddon stored = storage.get(storageKey)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No addon: " + addonName + " found for cluster: " + cluster.getName(), 404));
return stored.addon();
}
public AddonNamesPage list(Cluster cluster, Integer maxResults, String nextToken) {
requireActiveCluster(cluster);
String p = prefix(cluster);
List<String> addonNames = storage.scan(key -> key.startsWith(p)).stream()
.map(stored -> stored.addon().addonName())
.sorted()
.toList();
PaginatedResult<String> result = Pagination.paginate(
addonNames,
Function.identity(),
maxResults,
nextToken,
DEFAULT_PAGE_SIZE,
MAX_PAGE_SIZE,
"InvalidParameterException"
);
return new AddonNamesPage(result.items(), result.nextToken());
}
public synchronized Update update(Cluster cluster, String addonName, UpdateAddonRequest request) {
requireActiveCluster(cluster);
if (addonName == null || addonName.isBlank()) {
throw new AwsException("InvalidParameterException", "addonName is required", 400);
}
String storageKey = prefix(cluster) + addonName.trim().toLowerCase(Locale.ROOT);
StoredAddon stored = storage.get(storageKey)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No addon: " + addonName + " found for cluster: " + cluster.getName(), 404));
Addon current = stored.addon();
String newVersion = current.addonVersion();
List<UpdateParam> params = new ArrayList<>();
if (request != null) {
if (request.addonVersion() != null && !request.addonVersion().isBlank()) {
String requestedVersion = request.addonVersion().trim();
if (!catalog.isVersionSupported(addonName, requestedVersion, cluster.getVersion())) {
throw new AwsException("InvalidParameterException",
"Addon version specified is not supported", 400);
}
newVersion = requestedVersion;
params.add(new UpdateParam("Version", newVersion));
}
if (request.serviceAccountRoleArn() != null) {
if (!request.serviceAccountRoleArn().isBlank()) {
validateRoleArn(cluster, request.serviceAccountRoleArn(), "serviceAccountRoleArn");
}
params.add(new UpdateParam("ServiceAccountRoleArn", request.serviceAccountRoleArn()));
}
if (request.resolveConflicts() != null && !request.resolveConflicts().isBlank()) {
validateResolveConflicts(request.resolveConflicts());
params.add(new UpdateParam("ResolveConflicts", request.resolveConflicts()));
}
if (request.configurationValues() != null) {
params.add(new UpdateParam("ConfigurationValues", request.configurationValues()));
}
}
String updatedRoleArn = request != null && request.serviceAccountRoleArn() != null
? (request.serviceAccountRoleArn().isBlank() ? null : request.serviceAccountRoleArn())
: current.serviceAccountRoleArn();
String updatedConfig = request != null && request.configurationValues() != null
? request.configurationValues()
: current.configurationValues();
List<String> updatedAssociations = current.podIdentityAssociations();
if (request != null && request.podIdentityAssociations() != null) {
validatePodIdentityAssociations(cluster, request.podIdentityAssociations());
if (podIdentityAssociations != null && current.podIdentityAssociations() != null) {
for (String arn : current.podIdentityAssociations()) {
deleteAssociationSilently(cluster, arn);
}
}
updatedAssociations = createOrLinkPodIdentityAssociations(cluster, addonName, request.podIdentityAssociations());
params.add(new UpdateParam("PodIdentityAssociations", serializeAssociations(request.podIdentityAssociations())));
}
double now = Instant.now().toEpochMilli() / 1000.0;
Addon updatedAddon = new Addon(
current.addonArn(),
current.addonName(),
newVersion,
current.clusterName(),
"ACTIVE",
current.health(),
current.createdAt(),
now,
updatedRoleArn,
updatedConfig,
current.tags(),
updatedAssociations,
current.owner(),
current.publisher()
);
String token = request != null && request.clientRequestToken() != null
? request.clientRequestToken() : stored.clientRequestToken();
storage.put(storageKey, new StoredAddon(updatedAddon, token));
LOG.infov("Updated EKS addon {0} on cluster {1}", addonName, cluster.getName());
Update update = new Update(
UUID.randomUUID().toString(),
"Successful",
"AddonUpdate",
params,
now,
List.of()
);
updatesStorage.put(prefix(cluster) + update.id(), new StoredUpdate(update, addonName));
return update;
}
public synchronized Addon delete(Cluster cluster, String addonName, boolean preserve) {
requireActiveCluster(cluster);
if (addonName == null || addonName.isBlank()) {
throw new AwsException("InvalidParameterException", "addonName is required", 400);
}
String storageKey = prefix(cluster) + addonName.trim().toLowerCase(Locale.ROOT);
StoredAddon stored = storage.get(storageKey)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No addon: " + addonName + " found for cluster: " + cluster.getName(), 404));
storage.delete(storageKey);
if (preserve) {
LOG.infov("Deleted EKS addon {0} on cluster {1} (preserve=true)", addonName, cluster.getName());
} else {
if (podIdentityAssociations != null && stored.addon().podIdentityAssociations() != null) {
for (String arn : stored.addon().podIdentityAssociations()) {
deleteAssociationSilently(cluster, arn);
}
}
LOG.infov("Deleted EKS addon {0} on cluster {1} (preserve=false)", addonName, cluster.getName());
}
Addon current = stored.addon();
return new Addon(
current.addonArn(),
current.addonName(),
current.addonVersion(),
current.clusterName(),
"DELETING",
current.health(),
current.createdAt(),
Instant.now().toEpochMilli() / 1000.0,
current.serviceAccountRoleArn(),
current.configurationValues(),
current.tags(),
current.podIdentityAssociations(),
current.owner(),
current.publisher()
);
}
public synchronized void deleteClusterAddons(Cluster cluster) {
if (cluster != null) {
String p = prefix(cluster);
storage.keys().stream().filter(k -> k.startsWith(p)).toList().forEach(storage::delete);
updatesStorage.keys().stream().filter(k -> k.startsWith(p)).toList().forEach(updatesStorage::delete);
LOG.infov("Purged all addons and updates for cluster {0}", cluster.getName());
}
}
public Update describeUpdate(Cluster cluster, String updateId, String addonName) {
requireActiveCluster(cluster);
if (updateId == null || updateId.isBlank()) {
throw new AwsException("InvalidParameterException", "updateId is required", 400);
}
StoredUpdate stored = updatesStorage.get(prefix(cluster) + updateId)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No update: " + updateId + " found for cluster: " + cluster.getName(), 404));
if (addonName != null && !addonName.isBlank()
&& stored.addonName() != null && !stored.addonName().equalsIgnoreCase(addonName.trim())) {
throw new AwsException("ResourceNotFoundException",
"No update: " + updateId + " found for addon: " + addonName, 404);
}
return stored.update();
}
public AddonVersionsPage describeAddonVersions(String addonName, String kubernetesVersion,
Integer maxResults, String nextToken,
List<String> publishers, List<String> types, List<String> owners) {
List<AddonInfo> filtered = catalog.describeVersions(addonName, kubernetesVersion, publishers, types, owners);
PaginatedResult<AddonInfo> result = Pagination.paginate(
filtered,
AddonInfo::addonName,
maxResults,
nextToken,
DEFAULT_PAGE_SIZE,
MAX_PAGE_SIZE,
"InvalidParameterException"
);
return new AddonVersionsPage(result.items(), result.nextToken());
}
private void validatePodIdentityAssociations(Cluster cluster, List<AddonPodIdentityAssociation> associations) {
if (associations == null || associations.isEmpty()) {
return;
}
for (AddonPodIdentityAssociation assoc : associations) {
if (assoc.roleArn() == null || assoc.roleArn().isBlank()
|| assoc.serviceAccount() == null || assoc.serviceAccount().isBlank()) {
throw new AwsException("InvalidParameterException",
"roleArn and serviceAccount are required for podIdentityAssociations", 400);
}
validateRoleArn(cluster, assoc.roleArn(), "roleArn");
}
}
private static String serializeAssociations(List<AddonPodIdentityAssociation> associations) {
if (associations == null) {
return "[]";
}
try {
return MAPPER.writeValueAsString(associations);
} catch (JsonProcessingException e) {
return "[]";
}
}
private List<String> createOrLinkPodIdentityAssociations(Cluster cluster,
String addonName,
List<AddonPodIdentityAssociation> associations) {
if (associations == null || associations.isEmpty()) {
return List.of();
}
validatePodIdentityAssociations(cluster, associations);
List<String> arns = new ArrayList<>();
String namespace = resolveAddonNamespace(addonName);
for (AddonPodIdentityAssociation assoc : associations) {
if (podIdentityAssociations != null) {
CreatePodIdentityAssociationRequest req = new CreatePodIdentityAssociationRequest(
cluster.getName(),
namespace,
assoc.serviceAccount(),
assoc.roleArn(),
null,
Map.of(),
null,
null,
null
);
PodIdentityAssociation created = podIdentityAssociations.create(cluster, req);
arns.add(created.associationArn());
} else {
String[] clusterArn = cluster.getArn().split(":", 6);
String assocId = "a-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17);
String arn = "arn:" + clusterArn[1] + ":eks:" + clusterArn[3] + ":"
+ clusterArn[4] + ":podidentityassociation/" + cluster.getName() + "/" + assocId;
arns.add(arn);
}
}
return arns;
}
private void deleteAssociationSilently(Cluster cluster, String associationArn) {
if (associationArn == null || associationArn.isBlank() || podIdentityAssociations == null) {
return;
}
String associationId = associationArn.substring(associationArn.lastIndexOf('/') + 1);
try {
podIdentityAssociations.delete(cluster, associationId);
} catch (AwsException e) {
LOG.debugf("Ignored error deleting pod identity association %s: %s", associationId, e.getMessage());
}
}
private static String resolveAddonNamespace(String addonName) {
return "kube-system";
}
private static String prefix(Cluster cluster) {
return cluster.getArn() + "/" + Objects.toString(cluster.getCreatedAt()) + "/";
}
private static String generateAddonArn(Cluster cluster, String addonName) {
String[] clusterArn = cluster.getArn().split(":", 6);
return "arn:" + clusterArn[1] + ":eks:" + clusterArn[3] + ":"
+ clusterArn[4] + ":addon/" + cluster.getName() + "/" + addonName + "/" + UUID.randomUUID();
}
private static void requireActiveCluster(Cluster cluster) {
if (cluster == null) {
throw new AwsException("ResourceNotFoundException", "Cluster not found", 404);
}
if (cluster.getStatus() != ClusterStatus.ACTIVE) {
throw new AwsException("InvalidRequestException",
"Cluster must be ACTIVE, but was " + cluster.getStatus(), 400);
}
}
private void validateRoleArn(Cluster cluster, String roleArn, String fieldName) {
if (roleArn == null || roleArn.isBlank()) {
throw new AwsException("InvalidParameterException", fieldName + " is required", 400);
}
String[] arn = roleArn.split(":", 6);
String[] clusterArn = cluster.getArn().split(":", 6);
if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(clusterArn[1])
|| !"iam".equals(arn[2]) || !arn[3].isEmpty() || !arn[4].matches("[0-9]{12}")
|| !arn[5].startsWith("role/") || arn[5].startsWith("role/aws-service-role/")
|| roleArn.endsWith("/")) {
throw new AwsException("InvalidParameterException", fieldName + " must identify an IAM role", 400);
}
if (iam != null) {
String roleName = roleArn.substring(roleArn.lastIndexOf('/') + 1);
iam.findRole(arn[4], roleName)
.filter(role -> roleArn.equals(role.getArn()))
.orElseThrow(() -> new AwsException("InvalidParameterException", "Role not found: " + roleArn, 400));
}
}
private static void validateResolveConflicts(String resolveConflicts) {
String upper = resolveConflicts.toUpperCase(Locale.ROOT);
if (!"OVERWRITE".equals(upper) && !"NONE".equals(upper) && !"PRESERVE".equals(upper)) {
throw new AwsException("InvalidParameterException",
"Unsupported resolveConflicts value: " + resolveConflicts, 400);
}
}
private static void validateTags(Map<String, String> tags) {
if (tags == null) {
return;
}
if (tags.size() > 50) {
throw new AwsException("InvalidParameterException", "Too many tags: maximum is 50", 400);
}
for (Map.Entry<String, String> entry : tags.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key == null || key.isBlank() || key.length() > 128) {
throw new AwsException("InvalidParameterException", "Invalid tag key: " + key, 400);
}
if (value == null || value.length() > 256) {
throw new AwsException("InvalidParameterException", "Invalid tag value: " + value, 400);
}
}
}
private static boolean parametersMatch(Addon existing, CreateAddonRequest request) {
Map<String, String> existingTags = existing.tags() != null ? existing.tags() : Map.of();
Map<String, String> requestTags = request.tags() != null ? request.tags() : Map.of();
return Objects.equals(existing.serviceAccountRoleArn(), request.serviceAccountRoleArn())
&& Objects.equals(existing.configurationValues(), request.configurationValues())
&& (request.addonVersion() == null || request.addonVersion().isBlank()
|| Objects.equals(existing.addonVersion(), request.addonVersion()))
&& Objects.equals(existingTags, requestTags);
}
}
@@ -1,8 +1,10 @@
package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.services.eks.model.Addon;
import io.github.hectorvent.floci.services.eks.model.Cluster;
import io.github.hectorvent.floci.services.eks.model.CreateAccessEntryRequest;
import io.github.hectorvent.floci.services.eks.model.CreateAddonRequest;
import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;
import io.github.hectorvent.floci.services.eks.model.CreateFargateProfileRequest;
import io.github.hectorvent.floci.services.eks.model.CreateNodeGroupRequest;
@@ -10,6 +12,8 @@ import io.github.hectorvent.floci.services.eks.model.CreatePodIdentityAssociatio
import io.github.hectorvent.floci.services.eks.model.FargateProfile;
import io.github.hectorvent.floci.services.eks.model.Nodegroup;
import io.github.hectorvent.floci.services.eks.model.PodIdentityAssociation;
import io.github.hectorvent.floci.services.eks.model.Update;
import io.github.hectorvent.floci.services.eks.model.UpdateAddonRequest;
import io.github.hectorvent.floci.services.eks.model.UpdatePodIdentityAssociationRequest;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
@@ -41,13 +45,16 @@ public class EksController {
private final EksService eksService;
private final EksAccessEntryService accessEntries;
private final EksPodIdentityAssociationService podIdentityAssociations;
private final EksAddonService addons;
@Inject
public EksController(EksService eksService, EksAccessEntryService accessEntries,
EksPodIdentityAssociationService podIdentityAssociations) {
EksPodIdentityAssociationService podIdentityAssociations,
EksAddonService addons) {
this.eksService = eksService;
this.accessEntries = accessEntries;
this.podIdentityAssociations = podIdentityAssociations;
this.addons = addons;
}
@POST
@@ -175,11 +182,88 @@ public class EksController {
return Response.ok(Map.of()).build();
}
@POST
@Path("/clusters/{name}/addons")
public Response createAddon(@PathParam("name") String name, CreateAddonRequest request) {
Cluster cluster = eksService.describeCluster(name);
Addon addon = addons.create(cluster, request);
return Response.ok(Map.of("addon", addon)).build();
}
@GET
@Path("/clusters/{name}/addons")
public Response listAddons(@PathParam("name") String name) {
eksService.describeCluster(name);
return Response.ok(Map.of("addons", List.of())).build();
public Response listAddons(@PathParam("name") String name,
@QueryParam("maxResults") String maxResults,
@QueryParam("nextToken") String nextToken) {
Cluster cluster = eksService.describeCluster(name);
EksAddonService.AddonNamesPage page = addons.list(cluster,
Pagination.parseMaxResults(maxResults, "InvalidParameterException"), nextToken);
return Response.ok(page.nextToken() == null
? Map.of("addons", page.addons())
: Map.of("addons", page.addons(), "nextToken", page.nextToken())).build();
}
@GET
@Path("/clusters/{name}/addons/{addonName}")
public Response describeAddon(@PathParam("name") String name,
@PathParam("addonName") String addonName) {
Cluster cluster = eksService.describeCluster(name);
Addon addon = addons.describe(cluster, addonName);
return Response.ok(Map.of("addon", addon)).build();
}
@POST
@Path("/clusters/{name}/addons/{addonName}/update")
public Response updateAddon(@PathParam("name") String name,
@PathParam("addonName") String addonName,
UpdateAddonRequest request) {
Cluster cluster = eksService.describeCluster(name);
Update update = addons.update(cluster, addonName, request);
return Response.ok(Map.of("update", update)).build();
}
@GET
@Path("/clusters/{name}/updates/{updateId}")
public Response describeUpdate(@PathParam("name") String name,
@PathParam("updateId") String updateId,
@QueryParam("addonName") String addonName,
@QueryParam("nodegroupName") String nodegroupName) {
Cluster cluster = eksService.describeCluster(name);
Update update = addons.describeUpdate(cluster, updateId, addonName);
return Response.ok(Map.of("update", update)).build();
}
@DELETE
@Path("/clusters/{name}/addons/{addonName}")
public Response deleteAddon(@PathParam("name") String name,
@PathParam("addonName") String addonName,
@QueryParam("preserve") Boolean preserve) {
Cluster cluster = eksService.describeCluster(name);
Addon addon = addons.delete(cluster, addonName, Boolean.TRUE.equals(preserve));
return Response.ok(Map.of("addon", addon)).build();
}
@GET
@Path("/addons/supported-versions")
public Response describeAddonVersions(@QueryParam("addonName") String addonName,
@QueryParam("kubernetesVersion") String kubernetesVersion,
@QueryParam("maxResults") String maxResults,
@QueryParam("nextToken") String nextToken,
@QueryParam("publishers") List<String> publishers,
@QueryParam("types") List<String> types,
@QueryParam("owners") List<String> owners) {
EksAddonService.AddonVersionsPage page = addons.describeAddonVersions(
addonName,
kubernetesVersion,
Pagination.parseMaxResults(maxResults, "InvalidParameterException"),
nextToken,
publishers,
types,
owners
);
return Response.ok(page.nextToken() == null
? Map.of("addons", page.addons())
: Map.of("addons", page.addons(), "nextToken", page.nextToken())).build();
}
@GET
@@ -93,13 +93,15 @@ public class EksService implements TagHandler, ResourceProvider {
private final EksOidcService oidcService;
private final EksAccessEntryService accessEntries;
private final EksPodIdentityAssociationService podIdentityAssociations;
private final EksAddonService addons;
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
@Inject
public EksService(StorageFactory storageFactory, EmulatorConfig config,
RegionResolver regionResolver, EksClusterManager clusterManager, Ec2Service ec2Service,
EksOidcService oidcService, EksAccessEntryService accessEntries,
EksPodIdentityAssociationService podIdentityAssociations) {
EksPodIdentityAssociationService podIdentityAssociations,
EksAddonService addons) {
this.storage = storageFactory.create("eks", "eks-clusters.json",
new TypeReference<Map<String, Cluster>>() {
});
@@ -116,13 +118,22 @@ public class EksService implements TagHandler, ResourceProvider {
this.oidcService = oidcService;
this.accessEntries = accessEntries;
this.podIdentityAssociations = podIdentityAssociations;
this.addons = addons;
}
public EksService(StorageFactory storageFactory, EmulatorConfig config,
RegionResolver regionResolver, EksClusterManager clusterManager, Ec2Service ec2Service,
EksOidcService oidcService, EksAccessEntryService accessEntries,
EksPodIdentityAssociationService podIdentityAssociations) {
this(storageFactory, config, regionResolver, clusterManager, ec2Service,
oidcService, accessEntries, podIdentityAssociations, null);
}
public EksService(StorageFactory storageFactory, EmulatorConfig config,
RegionResolver regionResolver, EksClusterManager clusterManager, Ec2Service ec2Service,
EksOidcService oidcService, EksAccessEntryService accessEntries) {
this(storageFactory, config, regionResolver, clusterManager, ec2Service,
oidcService, accessEntries, null);
oidcService, accessEntries, null, null);
}
@PostConstruct
@@ -564,6 +575,9 @@ public class EksService implements TagHandler, ResourceProvider {
if (podIdentityAssociations != null) {
podIdentityAssociations.deleteClusterAssociations(cluster);
}
if (addons != null) {
addons.deleteClusterAddons(cluster);
}
storage.delete(name);
oidcService.deleteKey(name);
return cluster;
@@ -0,0 +1,28 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Addon(
String addonArn,
String addonName,
String addonVersion,
String clusterName,
String status,
AddonHealth health,
double createdAt,
double modifiedAt,
String serviceAccountRoleArn,
String configurationValues,
Map<String, String> tags,
List<String> podIdentityAssociations,
String owner,
String publisher
) {}
@@ -0,0 +1,14 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record AddonHealth(
List<AddonIssue> issues
) {}
@@ -0,0 +1,18 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record AddonInfo(
String addonName,
String type,
List<AddonVersionInfo> addonVersions,
String publisher,
String owner
) {}
@@ -0,0 +1,16 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record AddonIssue(
String code,
String message,
List<String> resourceIds
) {}
@@ -0,0 +1,13 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record AddonPodIdentityAssociation(
String roleArn,
String serviceAccount
) {}
@@ -0,0 +1,18 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record AddonVersionInfo(
String addonVersion,
List<String> architecture,
List<Compatibility> compatibilities,
Boolean requiresConfiguration,
Boolean requiresIamPermissions
) {}
@@ -0,0 +1,16 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Compatibility(
String clusterVersion,
List<String> platformVersions,
Boolean defaultVersion
) {}
@@ -0,0 +1,20 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public record CreateAddonRequest(
String addonName,
String addonVersion,
String serviceAccountRoleArn,
String resolveConflicts,
String clientRequestToken,
String configurationValues,
Map<String, String> tags,
List<AddonPodIdentityAssociation> podIdentityAssociations
) {}
@@ -0,0 +1,14 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public record ErrorDetail(
String errorCode,
String errorMessage,
List<String> resourceIds
) {}
@@ -0,0 +1,19 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Update(
String id,
String status,
String type,
List<UpdateParam> params,
double createdAt,
List<ErrorDetail> errors
) {}
@@ -0,0 +1,17 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public record UpdateAddonRequest(
String addonVersion,
String serviceAccountRoleArn,
String resolveConflicts,
String clientRequestToken,
String configurationValues,
List<AddonPodIdentityAssociation> podIdentityAssociations
) {}
@@ -0,0 +1,11 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public record UpdateParam(
String type,
String value
) {}