feat(aps): implement AMP rule groups namespaces (#3330)

* feat(aps): implement AMP rule groups namespaces

Closes #3329

* fix(aps): validate rule groups namespace names and tag ARN scope
This commit is contained in:
Matan Baruch authored and GitHub committed 2026-09-09 22:22:26 -05:00
1 parent b377134fcb
commit 6eca8540a8
8 files changed
+712 -28

No files matched your search

@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.aps.model.PrometheusWorkspace;
import io.github.hectorvent.floci.services.aps.model.RuleGroupsNamespace;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.inject.Inject;
@@ -12,6 +13,7 @@ import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
@@ -26,8 +28,9 @@ import java.util.Map;
/**
* Amazon Managed Service for Prometheus (Smithy restJson1, SigV4 scope {@code aps}) — the
* workspace lifecycle only: create/describe/list/delete plus alias update. Tagging goes through
* the shared {@code /tags/{resourceArn}} dispatcher, which routes {@code arn:aws:aps:...} to
* workspace lifecycle (create/describe/list/delete plus alias update) and rule groups namespaces
* (create/describe/list/put/delete). Tagging goes through the shared
* {@code /tags/{resourceArn}} dispatcher, which routes {@code arn:aws:aps:...} to
* {@link ApsService}'s TagHandler implementation.
*
* <p>The literal {@code /workspaces} path segment takes JAX-RS precedence over S3's
@@ -122,6 +125,100 @@ public class ApsController {
return Response.status(204).build();
}
@POST
@Path("/workspaces/{workspaceId}/rulegroupsnamespaces")
public Response createRuleGroupsNamespace(@Context HttpHeaders headers,
@PathParam("workspaceId") String workspaceId,
Map<String, Object> request) {
Map<String, Object> body = request != null ? request : Map.of();
RuleGroupsNamespace namespace = service.createRuleGroupsNamespace(
regionResolver.resolveRegion(headers), workspaceId,
asString(body.get("name"), "name"), asString(body.get("data"), "data"),
asStringMap(body.get("tags"), "tags"));
return Response.status(202).entity(toNamespaceMutationResponse(namespace)).build();
}
@GET
@Path("/workspaces/{workspaceId}/rulegroupsnamespaces")
public Response listRuleGroupsNamespaces(@Context HttpHeaders headers,
@PathParam("workspaceId") String workspaceId,
@QueryParam("name") String name,
@QueryParam("maxResults") String maxResultsParam,
@QueryParam("nextToken") String nextToken) {
PaginatedResult<RuleGroupsNamespace> result = service.listRuleGroupsNamespaces(
regionResolver.resolveRegion(headers), workspaceId, name,
Pagination.parseMaxResults(maxResultsParam, "ValidationException"), nextToken);
Map<String, Object> response = new HashMap<>();
response.put("ruleGroupsNamespaces", result.items().stream().map(this::toNamespaceSummary).toList());
if (result.nextToken() != null) {
response.put("nextToken", result.nextToken());
}
return Response.ok(response).build();
}
@GET
@Path("/workspaces/{workspaceId}/rulegroupsnamespaces/{name}")
public Response describeRuleGroupsNamespace(@Context HttpHeaders headers,
@PathParam("workspaceId") String workspaceId,
@PathParam("name") String name) {
RuleGroupsNamespace namespace = service.describeRuleGroupsNamespace(
regionResolver.resolveRegion(headers), workspaceId, name);
ObjectNode response = objectMapper.createObjectNode();
ObjectNode description = toNamespaceSummary(namespace);
description.put("data", namespace.getEncodedData());
response.set("ruleGroupsNamespace", description);
return Response.ok(response).build();
}
@PUT
@Path("/workspaces/{workspaceId}/rulegroupsnamespaces/{name}")
public Response putRuleGroupsNamespace(@Context HttpHeaders headers,
@PathParam("workspaceId") String workspaceId,
@PathParam("name") String name,
Map<String, Object> request) {
Map<String, Object> body = request != null ? request : Map.of();
RuleGroupsNamespace namespace = service.putRuleGroupsNamespace(
regionResolver.resolveRegion(headers), workspaceId, name,
asString(body.get("data"), "data"));
return Response.status(202).entity(toNamespaceMutationResponse(namespace)).build();
}
@DELETE
@Path("/workspaces/{workspaceId}/rulegroupsnamespaces/{name}")
public Response deleteRuleGroupsNamespace(@Context HttpHeaders headers,
@PathParam("workspaceId") String workspaceId,
@PathParam("name") String name) {
service.deleteRuleGroupsNamespace(regionResolver.resolveRegion(headers), workspaceId, name);
return Response.status(202).build();
}
private ObjectNode toNamespaceMutationResponse(RuleGroupsNamespace namespace) {
ObjectNode node = objectMapper.createObjectNode();
node.put("name", namespace.getName());
node.put("arn", namespace.getArn());
node.set("status", namespaceStatusNode(namespace));
node.set("tags", objectMapper.valueToTree(namespace.getTags()));
return node;
}
private ObjectNode toNamespaceSummary(RuleGroupsNamespace namespace) {
ObjectNode node = objectMapper.createObjectNode();
node.put("arn", namespace.getArn());
node.put("name", namespace.getName());
node.set("status", namespaceStatusNode(namespace));
node.set("tags", objectMapper.valueToTree(namespace.getTags()));
node.put("createdAt", namespace.getCreatedAt().toEpochMilli() / 1000.0);
node.put("modifiedAt", namespace.getModifiedAt().toEpochMilli() / 1000.0);
return node;
}
private ObjectNode namespaceStatusNode(RuleGroupsNamespace namespace) {
ObjectNode status = objectMapper.createObjectNode();
status.put("statusCode", namespace.getStatus());
return status;
}
private ObjectNode toWorkspaceDescription(PrometheusWorkspace workspace) {
ObjectNode node = toWorkspaceSummary(workspace);
node.put("prometheusEndpoint", workspace.getPrometheusEndpoint());
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.TagHandler;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.aps.model.PrometheusWorkspace;
import io.github.hectorvent.floci.services.aps.model.RuleGroupsNamespace;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -18,6 +19,7 @@ import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
@ApplicationScoped
public class ApsService implements TagHandler {
@@ -26,14 +28,19 @@ public class ApsService implements TagHandler {
// AMP's ListWorkspacesRequest declares maxResults with a default of 100 and a maximum of 1000.
private static final int DEFAULT_PAGE = 100;
private static final int MAX_PAGE = 1000;
private static final int MAX_NAMESPACE_NAME_LENGTH = 128;
private static final Pattern NAMESPACE_NAME = Pattern.compile(".*[0-9A-Za-z][-.0-9A-Z_a-z]*.*");
private final StorageBackend<String, PrometheusWorkspace> storage;
private final StorageBackend<String, RuleGroupsNamespace> namespaceStorage;
private final RegionResolver regionResolver;
@Inject
public ApsService(StorageFactory storageFactory, RegionResolver regionResolver) {
this.storage = storageFactory.create("aps", "aps-workspaces.json",
new TypeReference<Map<String, PrometheusWorkspace>>() {});
this.namespaceStorage = storageFactory.create("aps", "aps-rule-groups-namespaces.json",
new TypeReference<Map<String, RuleGroupsNamespace>>() {});
this.regionResolver = regionResolver;
}
@@ -85,6 +92,10 @@ public class ApsService implements TagHandler {
public void deleteWorkspace(String region, String workspaceId) {
describeWorkspace(region, workspaceId);
String namespacePrefix = namespaceKeyPrefix(region, workspaceId);
for (RuleGroupsNamespace namespace : namespaceStorage.scan(k -> k.startsWith(namespacePrefix))) {
namespaceStorage.delete(namespaceKey(region, workspaceId, namespace.getName()));
}
storage.delete(key(region, workspaceId));
LOG.infov("Deleted AMP workspace: {0} in {1}", workspaceId, region);
}
@@ -95,6 +106,71 @@ public class ApsService implements TagHandler {
storage.put(key(region, workspaceId), workspace);
}
public RuleGroupsNamespace createRuleGroupsNamespace(String region, String workspaceId, String name,
String encodedData, Map<String, String> tags) {
describeWorkspace(region, workspaceId);
requireNamespaceName(name);
requireNamespaceData(encodedData);
if (namespaceStorage.get(namespaceKey(region, workspaceId, name)).isPresent()) {
throw new AwsException("ConflictException",
"Rule groups namespace already exists: " + name, 409);
}
RuleGroupsNamespace namespace = new RuleGroupsNamespace();
namespace.setName(name);
namespace.setWorkspaceId(workspaceId);
namespace.setArn(regionResolver.buildArn("aps", region,
"rulegroupsnamespace/" + workspaceId + "/" + name));
namespace.setStatus("ACTIVE");
namespace.setEncodedData(encodedData);
Instant now = Instant.now();
namespace.setCreatedAt(now);
namespace.setModifiedAt(now);
if (tags != null) {
namespace.getTags().putAll(tags);
}
namespaceStorage.put(namespaceKey(region, workspaceId, name), namespace);
LOG.infov("Created AMP rule groups namespace: {0} in workspace {1}", name, workspaceId);
return namespace;
}
public RuleGroupsNamespace describeRuleGroupsNamespace(String region, String workspaceId, String name) {
describeWorkspace(region, workspaceId);
return namespaceStorage.get(namespaceKey(region, workspaceId, name))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Rule groups namespace not found: " + name, 404));
}
public PaginatedResult<RuleGroupsNamespace> listRuleGroupsNamespaces(String region, String workspaceId,
String namePrefix, Integer maxResults,
String nextToken) {
describeWorkspace(region, workspaceId);
String prefix = namespaceKeyPrefix(region, workspaceId);
List<RuleGroupsNamespace> all = namespaceStorage.scan(k -> k.startsWith(prefix)).stream()
.filter(n -> namePrefix == null || namePrefix.isEmpty()
|| (n.getName() != null && n.getName().startsWith(namePrefix)))
.toList();
return Pagination.paginate(all, RuleGroupsNamespace::getName, maxResults, nextToken,
DEFAULT_PAGE, MAX_PAGE, "ValidationException");
}
public RuleGroupsNamespace putRuleGroupsNamespace(String region, String workspaceId, String name,
String encodedData) {
requireNamespaceData(encodedData);
RuleGroupsNamespace namespace = describeRuleGroupsNamespace(region, workspaceId, name);
namespace.setEncodedData(encodedData);
namespace.setModifiedAt(Instant.now());
namespaceStorage.put(namespaceKey(region, workspaceId, name), namespace);
return namespace;
}
public void deleteRuleGroupsNamespace(String region, String workspaceId, String name) {
describeRuleGroupsNamespace(region, workspaceId, name);
namespaceStorage.delete(namespaceKey(region, workspaceId, name));
LOG.infov("Deleted AMP rule groups namespace: {0} in workspace {1}", name, workspaceId);
}
// ── TagHandler: the shared /tags/{resourceArn} dispatcher routes aps ARNs here ──
@Override
@@ -115,7 +191,7 @@ public class ApsService implements TagHandler {
@Override
public Map<String, String> listTags(String region, String arn) {
return Map.copyOf(workspaceByArn(region, arn).getTags());
return Map.copyOf(taggableByArn(region, arn).tags());
}
@Override
@@ -128,32 +204,52 @@ public class ApsService implements TagHandler {
"Tag keys must not begin with aws:. Offending key: " + tagKey, 400);
}
}
PrometheusWorkspace workspace = workspaceByArn(region, arn);
workspace.getTags().putAll(tags);
storage.put(key(region, workspace.getWorkspaceId()), workspace);
Taggable taggable = taggableByArn(region, arn);
taggable.tags().putAll(tags);
taggable.persist().run();
}
@Override
public void untagResource(String region, String arn, List<String> tagKeys) {
PrometheusWorkspace workspace = workspaceByArn(region, arn);
tagKeys.forEach(workspace.getTags()::remove);
storage.put(key(region, workspace.getWorkspaceId()), workspace);
Taggable taggable = taggableByArn(region, arn);
tagKeys.forEach(taggable.tags()::remove);
taggable.persist().run();
}
private PrometheusWorkspace workspaceByArn(String region, String arn) {
// arn:aws:aps:<region>:<account>:workspace/<workspaceId>
String resource;
private record Taggable(Map<String, String> tags, Runnable persist) {
}
private Taggable taggableByArn(String region, String arn) {
AwsArnUtils.Arn parsed;
try {
resource = AwsArnUtils.parse(arn).resource();
parsed = AwsArnUtils.parse(arn);
} catch (IllegalArgumentException e) {
throw new AwsException("ValidationException", "Invalid resource ARN: " + arn, 400);
}
String prefix = "workspace/";
if (!resource.startsWith(prefix) || resource.length() == prefix.length()) {
if (!"aps".equals(parsed.service()) || !region.equals(parsed.region())
|| !regionResolver.getAccountId().equals(parsed.accountId())) {
throw new AwsException("ValidationException",
"Tags are only supported on AMP workspaces: " + arn, 400);
"The resource ARN does not belong to this AMP account and region: " + arn, 400);
}
return describeWorkspace(region, resource.substring(prefix.length()));
String resource = parsed.resource();
String workspacePrefix = "workspace/";
if (resource.startsWith(workspacePrefix) && resource.length() > workspacePrefix.length()) {
PrometheusWorkspace workspace =
describeWorkspace(region, resource.substring(workspacePrefix.length()));
return new Taggable(workspace.getTags(),
() -> storage.put(key(region, workspace.getWorkspaceId()), workspace));
}
String namespacePrefix = "rulegroupsnamespace/";
if (resource.startsWith(namespacePrefix)) {
String[] parts = resource.substring(namespacePrefix.length()).split("/", 2);
if (parts.length == 2 && !parts[0].isEmpty() && !parts[1].isEmpty()) {
RuleGroupsNamespace namespace = describeRuleGroupsNamespace(region, parts[0], parts[1]);
return new Taggable(namespace.getTags(),
() -> namespaceStorage.put(namespaceKey(region, parts[0], parts[1]), namespace));
}
}
throw new AwsException("ValidationException",
"Tags are only supported on AMP workspaces and rule groups namespaces: " + arn, 400);
}
// AMP is regional ("You can have one or more workspaces in each Region in your account"), so
@@ -166,6 +262,30 @@ public class ApsService implements TagHandler {
return region + "::";
}
private static String namespaceKey(String region, String workspaceId, String name) {
return namespaceKeyPrefix(region, workspaceId) + name;
}
private static String namespaceKeyPrefix(String region, String workspaceId) {
return keyPrefix(region) + workspaceId + "::";
}
private static void requireNamespaceName(String name) {
if (name == null || name.isEmpty() || name.length() > MAX_NAMESPACE_NAME_LENGTH
|| !NAMESPACE_NAME.matcher(name).matches() || name.indexOf('/') >= 0) {
throw new AwsException("ValidationException",
"name must be 1 to " + MAX_NAMESPACE_NAME_LENGTH
+ " characters matching " + NAMESPACE_NAME.pattern()
+ " and must not contain '/'.", 400);
}
}
private static void requireNamespaceData(String encodedData) {
if (encodedData == null || encodedData.isEmpty()) {
throw new AwsException("ValidationException", "data must not be empty.", 400);
}
}
// AMP strips leading/trailing blanks from every alias it accepts, including the list filter.
private static String stripAlias(String alias) {
return alias == null ? null : alias.strip();
@@ -0,0 +1,51 @@
package io.github.hectorvent.floci.services.aps.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class RuleGroupsNamespace {
private String name;
private String workspaceId;
private String arn;
private String status;
private String encodedData;
private Instant createdAt;
private Instant modifiedAt;
private Map<String, String> tags = new ConcurrentHashMap<>();
public RuleGroupsNamespace() {
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getWorkspaceId() { return workspaceId; }
public void setWorkspaceId(String workspaceId) { this.workspaceId = workspaceId; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getEncodedData() { return encodedData; }
public void setEncodedData(String encodedData) { this.encodedData = encodedData; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
public Instant getModifiedAt() { return modifiedAt; }
public void setModifiedAt(Instant modifiedAt) { this.modifiedAt = modifiedAt; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) {
this.tags = tags != null ? new ConcurrentHashMap<>(tags) : new ConcurrentHashMap<>();
}
}