mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(applicationautoscaling): evaluate target-tracking and step-scaling policies against ECS (#2692)
Adds a generic CloudWatch alarm evaluator plus an ECS CapacityAdjuster, so a firing policy calls UpdateService to change desiredCount instead of sitting inert. Adds DescribeScalingActivities to observe the result. Closes #2565 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
1 parent
cf6fede453
commit
2a7c94b04d
20 files changed
+1720
-10
No files matched your search
+32
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.Alarm;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.PredefinedMetricSpecification;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalableTarget;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingActivity;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingPolicy;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.StepAdjustment;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.StepScalingConfiguration;
|
||||
@@ -54,6 +55,7 @@ public class ApplicationAutoScalingJsonHandler {
|
||||
case "PutScalingPolicy" -> handlePutScalingPolicy(request, region);
|
||||
case "DescribeScalingPolicies" -> handleDescribeScalingPolicies(request, region);
|
||||
case "DeleteScalingPolicy" -> handleDeleteScalingPolicy(request, region);
|
||||
case "DescribeScalingActivities" -> handleDescribeScalingActivities(request, region);
|
||||
case "ListTagsForResource" -> handleListTagsForResource(request, region);
|
||||
case "TagResource" -> handleTagResource(request, region);
|
||||
case "UntagResource" -> handleUntagResource(request, region);
|
||||
@@ -149,6 +151,19 @@ public class ApplicationAutoScalingJsonHandler {
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeScalingActivities(JsonNode request, String region) {
|
||||
List<ScalingActivity> found = service.describeScalingActivities(
|
||||
text(request, "ServiceNamespace"),
|
||||
text(request, "ResourceId"),
|
||||
text(request, "ScalableDimension"),
|
||||
region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode array = response.putArray("ScalingActivities");
|
||||
found.forEach(a -> array.add(scalingActivityJson(a)));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- tagging
|
||||
|
||||
private Response handleListTagsForResource(JsonNode request, String region) {
|
||||
@@ -278,6 +293,23 @@ public class ApplicationAutoScalingJsonHandler {
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode scalingActivityJson(ScalingActivity a) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("ActivityId", a.getActivityId());
|
||||
node.put("ServiceNamespace", a.getServiceNamespace());
|
||||
node.put("ResourceId", a.getResourceId());
|
||||
node.put("ScalableDimension", a.getScalableDimension());
|
||||
node.put("Description", a.getDescription());
|
||||
node.put("Cause", a.getCause());
|
||||
node.put("StartTime", a.getStartTime());
|
||||
node.put("EndTime", a.getEndTime());
|
||||
node.put("StatusCode", a.getStatusCode());
|
||||
if (a.getStatusMessage() != null) {
|
||||
node.put("StatusMessage", a.getStatusMessage());
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode alarmJson(Alarm alarm) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("AlarmName", alarm.getAlarmName());
|
||||
|
||||
+71
@@ -7,11 +7,13 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.Alarm;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalableTarget;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingActivity;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingPolicy;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.StepScalingConfiguration;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.SuspendedState;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.TargetTrackingConfiguration;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -78,6 +80,7 @@ public class ApplicationAutoScalingService {
|
||||
|
||||
private final StorageBackend<String, ScalableTarget> targets;
|
||||
private final StorageBackend<String, ScalingPolicy> policies;
|
||||
private final StorageBackend<String, ScalingActivity> activities;
|
||||
private final RegionResolver regionResolver;
|
||||
private final CloudWatchMetricsService cloudWatchMetricsService;
|
||||
|
||||
@@ -89,16 +92,20 @@ public class ApplicationAutoScalingService {
|
||||
new TypeReference<Map<String, ScalableTarget>>() {}),
|
||||
factory.create("applicationautoscaling", "application-autoscaling-policies.json",
|
||||
new TypeReference<Map<String, ScalingPolicy>>() {}),
|
||||
factory.create("applicationautoscaling", "application-autoscaling-activities.json",
|
||||
new TypeReference<Map<String, ScalingActivity>>() {}),
|
||||
regionResolver,
|
||||
cloudWatchMetricsService);
|
||||
}
|
||||
|
||||
ApplicationAutoScalingService(StorageBackend<String, ScalableTarget> targets,
|
||||
StorageBackend<String, ScalingPolicy> policies,
|
||||
StorageBackend<String, ScalingActivity> activities,
|
||||
RegionResolver regionResolver,
|
||||
CloudWatchMetricsService cloudWatchMetricsService) {
|
||||
this.targets = targets;
|
||||
this.policies = policies;
|
||||
this.activities = activities;
|
||||
this.regionResolver = regionResolver;
|
||||
this.cloudWatchMetricsService = cloudWatchMetricsService;
|
||||
}
|
||||
@@ -348,11 +355,13 @@ public class ApplicationAutoScalingService {
|
||||
String alarmName = "TargetTracking-" + policy.getResourceId() + "-" + suffix + "-"
|
||||
+ UUID.randomUUID();
|
||||
MetricAlarm alarm = new MetricAlarm();
|
||||
alarm.setActionsEnabled(true);
|
||||
alarm.setAlarmName(alarmName);
|
||||
alarm.setAlarmDescription("DO NOT EDIT OR DELETE. For TargetTrackingScaling policy "
|
||||
+ policy.getPolicyArn() + ".");
|
||||
alarm.setNamespace(cloudWatchNamespace(policy.getServiceNamespace()));
|
||||
alarm.setMetricName(predefinedMetricType(policy));
|
||||
alarm.setDimensions(resolveDimensions(policy));
|
||||
alarm.setStatistic("Average");
|
||||
alarm.setPeriod(60);
|
||||
alarm.setEvaluationPeriods("AlarmHigh".equals(suffix) ? 3 : 15);
|
||||
@@ -379,6 +388,22 @@ public class ApplicationAutoScalingService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The alarm needs the same dimensions AWS attaches to the real metric, or the evaluator
|
||||
* will never find data an operator pushes in the real ECS shape. Real AWS keys ECS
|
||||
* service metrics by {@code ClusterName} + {@code ServiceName}; other namespaces are left
|
||||
* without dimensions, matching their existing "stored but inert" behavior.
|
||||
*/
|
||||
private static List<Dimension> resolveDimensions(ScalingPolicy policy) {
|
||||
if ("ecs".equals(policy.getServiceNamespace()) && policy.getResourceId() != null) {
|
||||
String[] parts = policy.getResourceId().split("/");
|
||||
if (parts.length == 3 && "service".equals(parts[0])) {
|
||||
return List.of(new Dimension("ClusterName", parts[1]), new Dimension("ServiceName", parts[2]));
|
||||
}
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private static String cloudWatchNamespace(String serviceNamespace) {
|
||||
return switch (serviceNamespace) {
|
||||
case "ecs" -> "AWS/ECS";
|
||||
@@ -490,4 +515,50 @@ public class ApplicationAutoScalingService {
|
||||
String scalableDimension) {
|
||||
return targets.get(targetKey(region, serviceNamespace, resourceId, scalableDimension));
|
||||
}
|
||||
|
||||
/** Looked up by {@link ScalingPolicyAlarmActionHandler} when an alarm's AlarmActions
|
||||
* references a scaling-policy ARN. */
|
||||
Optional<ScalingPolicy> findPolicyByArn(String policyArn, String region) {
|
||||
String prefix = region + "::";
|
||||
return policies.scan(k -> k.startsWith(prefix)).stream()
|
||||
.filter(p -> policyArn.equals(p.getPolicyArn()))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
/** Persists a policy after the control loop stamps a cooldown timestamp on it. */
|
||||
void savePolicy(ScalingPolicy policy, String region) {
|
||||
policies.put(policyKey(region, policy.getServiceNamespace(), policy.getResourceId(),
|
||||
policy.getScalableDimension(), policy.getPolicyName()), policy);
|
||||
}
|
||||
|
||||
/** Records that the control loop changed capacity, mirroring what AWS reports through
|
||||
* DescribeScalingActivities. */
|
||||
void recordScalingActivity(ScalingPolicy policy, String description, String cause, String region) {
|
||||
ScalingActivity activity = new ScalingActivity();
|
||||
activity.setActivityId(UUID.randomUUID().toString());
|
||||
activity.setServiceNamespace(policy.getServiceNamespace());
|
||||
activity.setResourceId(policy.getResourceId());
|
||||
activity.setScalableDimension(policy.getScalableDimension());
|
||||
activity.setDescription(description);
|
||||
activity.setCause(cause);
|
||||
double now = nowEpochSeconds();
|
||||
activity.setStartTime(now);
|
||||
activity.setEndTime(now);
|
||||
activity.setStatusCode("Successful");
|
||||
String key = region + "::" + policy.getServiceNamespace() + "::" + policy.getScalableDimension()
|
||||
+ "::" + policy.getResourceId() + "::" + activity.getActivityId();
|
||||
activities.put(key, activity);
|
||||
LOG.infov("Scaling activity for policy {0}: {1}", policy.getPolicyName(), description);
|
||||
}
|
||||
|
||||
public List<ScalingActivity> describeScalingActivities(String serviceNamespace, String resourceId,
|
||||
String scalableDimension, String region) {
|
||||
requireNamespace(serviceNamespace);
|
||||
String prefix = region + "::" + serviceNamespace + "::";
|
||||
return activities.scan(k -> k.startsWith(prefix)).stream()
|
||||
.filter(a -> resourceId == null || resourceId.equals(a.getResourceId()))
|
||||
.filter(a -> scalableDimension == null || scalableDimension.equals(a.getScalableDimension()))
|
||||
.sorted(Comparator.comparingDouble(ScalingActivity::getStartTime).reversed())
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package io.github.hectorvent.floci.services.applicationautoscaling;
|
||||
|
||||
/**
|
||||
* Reads and writes the actual capacity behind one {@code ScalableDimension}.
|
||||
*
|
||||
* <p>{@link ScalingPolicyAlarmActionHandler} discovers every CDI bean implementing this
|
||||
* interface and delegates to the one whose {@link #supports(String)} matches a scalable
|
||||
* target's dimension. A dimension with no adjuster stays exactly as inert as it is today —
|
||||
* this is the seam a future DynamoDB/Lambda/etc. adjuster plugs into without touching the
|
||||
* alarm-evaluation or scaling-math code.</p>
|
||||
*/
|
||||
public interface CapacityAdjuster {
|
||||
|
||||
boolean supports(String scalableDimension);
|
||||
|
||||
int getCurrentCapacity(String resourceId, String region);
|
||||
|
||||
void setCapacity(String resourceId, int capacity, String region);
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package io.github.hectorvent.floci.services.applicationautoscaling;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.ecs.EcsService;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* {@link CapacityAdjuster} for {@code ecs:service:DesiredCount} — the only scalable
|
||||
* dimension this control loop drives today.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EcsCapacityAdjuster implements CapacityAdjuster {
|
||||
|
||||
private final EcsService ecsService;
|
||||
|
||||
@Inject
|
||||
public EcsCapacityAdjuster(EcsService ecsService) {
|
||||
this.ecsService = ecsService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(String scalableDimension) {
|
||||
return "ecs:service:DesiredCount".equals(scalableDimension);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCurrentCapacity(String resourceId, String region) {
|
||||
return resolveService(resourceId, region).getDesiredCount();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCapacity(String resourceId, int capacity, String region) {
|
||||
ClusterAndService ref = parse(resourceId);
|
||||
ecsService.updateService(ref.cluster(), ref.service(), null, capacity, null, region);
|
||||
}
|
||||
|
||||
private EcsServiceModel resolveService(String resourceId, String region) {
|
||||
ClusterAndService ref = parse(resourceId);
|
||||
List<EcsServiceModel> found = ecsService.describeServices(ref.cluster(), List.of(ref.service()), region);
|
||||
if (found.isEmpty()) {
|
||||
throw new AwsException("ObjectNotFoundException",
|
||||
"No ECS service found for resource ID: " + resourceId, 400);
|
||||
}
|
||||
return found.get(0);
|
||||
}
|
||||
|
||||
/** Application Auto Scaling's ECS {@code resourceId} is {@code service/<cluster>/<service>}. */
|
||||
private static ClusterAndService parse(String resourceId) {
|
||||
String[] parts = resourceId == null ? new String[0] : resourceId.split("/");
|
||||
if (parts.length != 3 || !"service".equals(parts[0])) {
|
||||
throw new AwsException("ValidationException", "Invalid ECS resource ID: " + resourceId, 400);
|
||||
}
|
||||
return new ClusterAndService(parts[1], parts[2]);
|
||||
}
|
||||
|
||||
private record ClusterAndService(String cluster, String service) {}
|
||||
}
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
package io.github.hectorvent.floci.services.applicationautoscaling;
|
||||
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalableTarget;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingPolicy;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.StepAdjustment;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.StepScalingConfiguration;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.TargetTrackingConfiguration;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.AlarmActionHandler;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Any;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Invokes a target-tracking or step-scaling policy when the CloudWatch alarm behind it fires.
|
||||
*
|
||||
* <p>The alarm's {@code comparisonOperator} (rather than Floci's own {@code AlarmHigh}/{@code
|
||||
* AlarmLow} naming, which only its own synthesized alarms carry) selects the
|
||||
* TargetTrackingScaling formula's fallback direction when no real datapoint is available. Every
|
||||
* other decision (suspension, cooldown, and {@code DisableScaleIn}) keys off the actual computed
|
||||
* capacity delta instead: a StepScaling alarm's matched step, or clamping to {@code
|
||||
* MaxCapacity}/{@code MinCapacity}, can both move capacity opposite to the alarm's own comparison
|
||||
* direction, so checking any of those against the alarm's labeled direction rather than the
|
||||
* resulting adjustment would let a suspended or disabled direction through.</p>
|
||||
*
|
||||
* <p>Cooldown gating follows AWS's documented target-tracking cooldown semantics (see
|
||||
* "Define cooldown periods" in the Application Auto Scaling user guide), which this handler
|
||||
* applies to StepScaling too: a scale-out is blocked while its cooldown is active <em>unless
|
||||
* the newly computed capacity is larger than what the last scale-out already applied</em>, in
|
||||
* which case it proceeds immediately — cooldown exists to stop flapping on small repeated
|
||||
* moves, not to cap a scalable target's climb toward {@code MaxCapacity} while a breach
|
||||
* persists. Scale-in has no such carve-out (AWS documents none): it is simply blocked for the
|
||||
* full cooldown window. {@code ScalingPolicy.lastScaleOutCapacity} is what "larger than"
|
||||
* compares against — a dedicated field, separate from {@code lastAppliedCapacity} (which a
|
||||
* scale-in also updates), so an intervening scale-in can't corrupt the scale-out high-water
|
||||
* mark and let a later scale-out through cooldown just because it beats the scale-in's lower
|
||||
* capacity rather than the original scale-out's. Independently, if current capacity no longer
|
||||
* matches {@code lastAppliedCapacity} at all (an operator, or another mechanism, changed it
|
||||
* since either kind of action), the carve-out is treated as satisfied unconditionally: the
|
||||
* situation has changed underneath the policy, so the "avoid flapping on our own repeated
|
||||
* moves" rationale no longer applies, and a persistent breach must not stay stuck below where
|
||||
* it belongs for a full cooldown window just because of an unrelated capacity change. Cooldown
|
||||
* defaults to 300s when unset, matching
|
||||
* AWS's documented default for ECS services (the only scalable dimension this handler drives
|
||||
* today) rather than inventing a different value.</p>
|
||||
*
|
||||
* <p>{@link AlarmEvaluator} dispatches on every tick a breach persists, not only the first
|
||||
* transition into {@code ALARM}, so a cooldown-deferred action gets retried on a later tick
|
||||
* instead of being dropped.</p>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ScalingPolicyAlarmActionHandler implements AlarmActionHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ScalingPolicyAlarmActionHandler.class);
|
||||
|
||||
/**
|
||||
* AWS's documented per-service default when a cooldown isn't explicitly configured. ECS is
|
||||
* the only scalable dimension this handler drives today, so its default (also shared by
|
||||
* most other scalable-target types) is the one that applies here.
|
||||
*/
|
||||
private static final int DEFAULT_COOLDOWN_SECONDS = 300;
|
||||
|
||||
private final ApplicationAutoScalingService service;
|
||||
private final Instance<CapacityAdjuster> adjusters;
|
||||
|
||||
@Inject
|
||||
public ScalingPolicyAlarmActionHandler(ApplicationAutoScalingService service,
|
||||
@Any Instance<CapacityAdjuster> adjusters) {
|
||||
this.service = service;
|
||||
this.adjusters = adjusters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(String actionArn) {
|
||||
return actionArn != null && actionArn.contains(":autoscaling:") && actionArn.contains(":scalingPolicy:");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(String actionArn, MetricAlarm alarm, double metricValue, String region) {
|
||||
ScalingPolicy policy = service.findPolicyByArn(actionArn, region).orElse(null);
|
||||
if (policy == null) {
|
||||
LOG.debugv("No scaling policy found for alarm action {0}", actionArn);
|
||||
return;
|
||||
}
|
||||
ScalableTarget target = service.findTarget(region, policy.getServiceNamespace(),
|
||||
policy.getResourceId(), policy.getScalableDimension()).orElse(null);
|
||||
if (target == null) {
|
||||
LOG.debugv("No scalable target for policy {0}", policy.getPolicyName());
|
||||
return;
|
||||
}
|
||||
|
||||
CapacityAdjuster adjuster = findAdjuster(target.getScalableDimension());
|
||||
if (adjuster == null) {
|
||||
LOG.debugv("No capacity adjuster registered for dimension {0}; policy {1} stays inert",
|
||||
target.getScalableDimension(), policy.getPolicyName());
|
||||
return;
|
||||
}
|
||||
|
||||
boolean scaleOut = isScaleOutAlarm(alarm);
|
||||
int current = adjuster.getCurrentCapacity(target.getResourceId(), region);
|
||||
Integer computed = "StepScaling".equals(policy.getPolicyType())
|
||||
? computeStepScaling(policy, current, metricValue, alarm.getThreshold())
|
||||
: computeTargetTracking(policy, current, metricValue, scaleOut);
|
||||
if (computed == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
int newCapacity = clamp(computed, target.getMinCapacity(), target.getMaxCapacity());
|
||||
if (newCapacity == current) {
|
||||
return;
|
||||
}
|
||||
if (newCapacity < current && isScaleInDisabled(policy)) {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean isScaleOutAction = newCapacity > current;
|
||||
if (isScaleOutAction) {
|
||||
if (target.getSuspendedState().isDynamicScalingOutSuspended()) {
|
||||
return;
|
||||
}
|
||||
Integer lastApplied = policy.getLastAppliedCapacity();
|
||||
boolean driftedSinceLastAction = lastApplied != null && lastApplied != current;
|
||||
Integer lastScaleOut = policy.getLastScaleOutCapacity();
|
||||
boolean largerThanLastScaleOut = lastScaleOut == null || driftedSinceLastAction || newCapacity > lastScaleOut;
|
||||
if (!largerThanLastScaleOut && withinCooldown(policy, true)) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (target.getSuspendedState().isDynamicScalingInSuspended()) {
|
||||
return;
|
||||
}
|
||||
if (withinCooldown(policy, false)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
adjuster.setCapacity(target.getResourceId(), newCapacity, region);
|
||||
stampCooldown(policy, isScaleOutAction);
|
||||
policy.setLastAppliedCapacity(newCapacity);
|
||||
if (isScaleOutAction) {
|
||||
policy.setLastScaleOutCapacity(newCapacity);
|
||||
}
|
||||
service.savePolicy(policy, region);
|
||||
service.recordScalingActivity(policy,
|
||||
"Setting desired capacity to " + newCapacity,
|
||||
"monitor alarm " + alarm.getAlarmName() + " in state ALARM triggered policy "
|
||||
+ policy.getPolicyName(),
|
||||
region);
|
||||
LOG.infov("Policy {0} adjusted {1}: {2} -> {3}",
|
||||
policy.getPolicyName(), target.getResourceId(), current, newCapacity);
|
||||
}
|
||||
|
||||
private CapacityAdjuster findAdjuster(String scalableDimension) {
|
||||
for (CapacityAdjuster adjuster : adjusters) {
|
||||
if (adjuster.supports(scalableDimension)) {
|
||||
return adjuster;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isScaleOutAlarm(MetricAlarm alarm) {
|
||||
String op = alarm.getComparisonOperator();
|
||||
return op != null && op.startsWith("GreaterThan");
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors the class-level note on suspension/cooldown: {@code DisableScaleIn} is checked
|
||||
* against the final, post-clamp capacity in {@link #handle}, not against the raw ratio
|
||||
* computed here. Clamping to {@code MaxCapacity} can turn a formula result that looked like
|
||||
* a scale-out (computed above {@code current}) into an actual decrease once capped — if this
|
||||
* method suppressed based on its own unclamped output, that clamp-induced decrease would
|
||||
* slip past the {@code DisableScaleIn} guard entirely.
|
||||
*/
|
||||
private static Integer computeTargetTracking(ScalingPolicy policy, int current, double metricValue,
|
||||
boolean scaleOut) {
|
||||
TargetTrackingConfiguration config = policy.getTargetTrackingConfiguration();
|
||||
if (config == null || config.getTargetValue() == null || config.getTargetValue() == 0) {
|
||||
return null;
|
||||
}
|
||||
return Double.isNaN(metricValue)
|
||||
? (scaleOut ? current + 1 : current - 1)
|
||||
: (int) Math.ceil(current * metricValue / config.getTargetValue());
|
||||
}
|
||||
|
||||
private static boolean isScaleInDisabled(ScalingPolicy policy) {
|
||||
TargetTrackingConfiguration config = policy.getTargetTrackingConfiguration();
|
||||
return config != null && Boolean.TRUE.equals(config.getDisableScaleIn());
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS resolves step adjustments by comparing {@code metricValue - threshold} against each
|
||||
* step's interval bounds, which are relative to the alarm's threshold, not absolute. With
|
||||
* no real datapoint to compare ({@code metricValue} is {@code NaN}, see {@link
|
||||
* #computeTargetTracking}), a delta of exactly zero — sitting right at the threshold the
|
||||
* alarm itself defines — is the step scaling equivalent of that same "assume the boundary,
|
||||
* nothing more" fallback.
|
||||
*/
|
||||
private static Integer computeStepScaling(ScalingPolicy policy, int current, double metricValue,
|
||||
double threshold) {
|
||||
StepScalingConfiguration config = policy.getStepScalingConfiguration();
|
||||
if (config == null || config.getStepAdjustments().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
double delta = Double.isNaN(metricValue) ? 0 : metricValue - threshold;
|
||||
StepAdjustment matched = null;
|
||||
for (StepAdjustment step : config.getStepAdjustments()) {
|
||||
double lower = step.getMetricIntervalLowerBound() != null
|
||||
? step.getMetricIntervalLowerBound() : Double.NEGATIVE_INFINITY;
|
||||
double upper = step.getMetricIntervalUpperBound() != null
|
||||
? step.getMetricIntervalUpperBound() : Double.POSITIVE_INFINITY;
|
||||
if (delta >= lower && delta < upper) {
|
||||
matched = step;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matched == null || matched.getScalingAdjustment() == null) {
|
||||
return null;
|
||||
}
|
||||
int adjustment = matched.getScalingAdjustment();
|
||||
String adjustmentType = config.getAdjustmentType() != null ? config.getAdjustmentType() : "ChangeInCapacity";
|
||||
return switch (adjustmentType) {
|
||||
case "ExactCapacity" -> adjustment;
|
||||
case "PercentChangeInCapacity" -> {
|
||||
int magnitude = (int) Math.round(current * adjustment / 100.0);
|
||||
if (config.getMinAdjustmentMagnitude() != null
|
||||
&& Math.abs(magnitude) < config.getMinAdjustmentMagnitude()) {
|
||||
magnitude = adjustment >= 0
|
||||
? config.getMinAdjustmentMagnitude() : -config.getMinAdjustmentMagnitude();
|
||||
}
|
||||
yield current + magnitude;
|
||||
}
|
||||
default -> current + adjustment;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean withinCooldown(ScalingPolicy policy, boolean scaleOut) {
|
||||
int cooldownSeconds = cooldownSeconds(policy, scaleOut);
|
||||
double last = scaleOut ? policy.getLastScaleOutTime() : policy.getLastScaleInTime();
|
||||
return last > 0 && (Instant.now().getEpochSecond() - last) < cooldownSeconds;
|
||||
}
|
||||
|
||||
private static int cooldownSeconds(ScalingPolicy policy, boolean scaleOut) {
|
||||
if ("StepScaling".equals(policy.getPolicyType())) {
|
||||
StepScalingConfiguration config = policy.getStepScalingConfiguration();
|
||||
return config != null && config.getCooldown() != null ? config.getCooldown() : DEFAULT_COOLDOWN_SECONDS;
|
||||
}
|
||||
TargetTrackingConfiguration config = policy.getTargetTrackingConfiguration();
|
||||
if (config == null) {
|
||||
return DEFAULT_COOLDOWN_SECONDS;
|
||||
}
|
||||
Integer cooldown = scaleOut ? config.getScaleOutCooldown() : config.getScaleInCooldown();
|
||||
return cooldown != null ? cooldown : DEFAULT_COOLDOWN_SECONDS;
|
||||
}
|
||||
|
||||
private static void stampCooldown(ScalingPolicy policy, boolean scaleOut) {
|
||||
double now = Instant.now().getEpochSecond();
|
||||
if (scaleOut) {
|
||||
policy.setLastScaleOutTime(now);
|
||||
} else {
|
||||
policy.setLastScaleInTime(now);
|
||||
}
|
||||
}
|
||||
|
||||
private static int clamp(int value, Integer min, Integer max) {
|
||||
int lo = min != null ? min : Integer.MIN_VALUE;
|
||||
int hi = max != null ? max : Integer.MAX_VALUE;
|
||||
return Math.max(lo, Math.min(hi, value));
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package io.github.hectorvent.floci.services.applicationautoscaling.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* One recorded scaling action, returned by {@code DescribeScalingActivities}.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_ScalingActivity.html">ScalingActivity</a>
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public class ScalingActivity {
|
||||
|
||||
private String activityId;
|
||||
private String serviceNamespace;
|
||||
private String resourceId;
|
||||
private String scalableDimension;
|
||||
private String description;
|
||||
private String cause;
|
||||
private double startTime;
|
||||
private double endTime;
|
||||
private String statusCode;
|
||||
private String statusMessage;
|
||||
|
||||
public String getActivityId() { return activityId; }
|
||||
public void setActivityId(String v) { this.activityId = v; }
|
||||
|
||||
public String getServiceNamespace() { return serviceNamespace; }
|
||||
public void setServiceNamespace(String v) { this.serviceNamespace = v; }
|
||||
|
||||
public String getResourceId() { return resourceId; }
|
||||
public void setResourceId(String v) { this.resourceId = v; }
|
||||
|
||||
public String getScalableDimension() { return scalableDimension; }
|
||||
public void setScalableDimension(String v) { this.scalableDimension = v; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String v) { this.description = v; }
|
||||
|
||||
public String getCause() { return cause; }
|
||||
public void setCause(String v) { this.cause = v; }
|
||||
|
||||
public double getStartTime() { return startTime; }
|
||||
public void setStartTime(double v) { this.startTime = v; }
|
||||
|
||||
public double getEndTime() { return endTime; }
|
||||
public void setEndTime(double v) { this.endTime = v; }
|
||||
|
||||
public String getStatusCode() { return statusCode; }
|
||||
public void setStatusCode(String v) { this.statusCode = v; }
|
||||
|
||||
public String getStatusMessage() { return statusMessage; }
|
||||
public void setStatusMessage(String v) { this.statusMessage = v; }
|
||||
}
|
||||
+31
@@ -26,6 +26,10 @@ public class ScalingPolicy {
|
||||
private List<Alarm> alarms = new ArrayList<>();
|
||||
private TargetTrackingConfiguration targetTrackingConfiguration;
|
||||
private StepScalingConfiguration stepScalingConfiguration;
|
||||
private double lastScaleOutTime;
|
||||
private double lastScaleInTime;
|
||||
private Integer lastAppliedCapacity;
|
||||
private Integer lastScaleOutCapacity;
|
||||
|
||||
public String getPolicyArn() { return policyArn; }
|
||||
public void setPolicyArn(String v) { this.policyArn = v; }
|
||||
@@ -56,4 +60,31 @@ public class ScalingPolicy {
|
||||
|
||||
public StepScalingConfiguration getStepScalingConfiguration() { return stepScalingConfiguration; }
|
||||
public void setStepScalingConfiguration(StepScalingConfiguration v) { this.stepScalingConfiguration = v; }
|
||||
|
||||
/** Epoch seconds of this policy's last scale-out action; 0 if it has never scaled out.
|
||||
* Used to enforce {@code ScaleOutCooldown} / {@code Cooldown}. */
|
||||
public double getLastScaleOutTime() { return lastScaleOutTime; }
|
||||
public void setLastScaleOutTime(double v) { this.lastScaleOutTime = v; }
|
||||
|
||||
/** Epoch seconds of this policy's last scale-in action; 0 if it has never scaled in.
|
||||
* Used to enforce {@code ScaleInCooldown} / {@code Cooldown}. */
|
||||
public double getLastScaleInTime() { return lastScaleInTime; }
|
||||
public void setLastScaleInTime(double v) { this.lastScaleInTime = v; }
|
||||
|
||||
/** The capacity this policy's last successful action (scale-out <em>or</em> scale-in) set;
|
||||
* {@code null} if it has never acted. Detects external interference: if the target's actual
|
||||
* current capacity no longer matches this, something other than this policy's own last
|
||||
* action changed it, and the scale-out cooldown carve-out below is treated as satisfied
|
||||
* unconditionally so a persistent breach isn't stuck stranded below where it belongs. */
|
||||
public Integer getLastAppliedCapacity() { return lastAppliedCapacity; }
|
||||
public void setLastAppliedCapacity(Integer v) { this.lastAppliedCapacity = v; }
|
||||
|
||||
/** The capacity this policy's last successful <em>scale-out</em> action set; {@code null}
|
||||
* if it has never scaled out. Deliberately separate from {@link #getLastAppliedCapacity},
|
||||
* which a scale-in also updates — comparing against that shared field instead of this one
|
||||
* would let an intervening scale-in corrupt the scale-out cooldown carve-out's high-water
|
||||
* mark. Per AWS's documented target-tracking cooldown semantics, a scale-out during cooldown
|
||||
* is only allowed through when it would set a capacity <em>larger</em> than this. */
|
||||
public Integer getLastScaleOutCapacity() { return lastScaleOutCapacity; }
|
||||
public void setLastScaleOutCapacity(Integer v) { this.lastScaleOutCapacity = v; }
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
|
||||
/**
|
||||
* Reacts to a CloudWatch alarm entering the {@code ALARM} state, the way a real AWS action
|
||||
* target (a scaling policy, an SNS topic, ...) would when listed in an alarm's
|
||||
* {@code AlarmActions}.
|
||||
*
|
||||
* <p>{@link AlarmEvaluator} discovers every CDI bean implementing this interface and
|
||||
* dispatches to the first one whose {@link #supports(String)} matches. An action ARN with no
|
||||
* matching handler is a no-op, the same as it is today for every action type.</p>
|
||||
*/
|
||||
public interface AlarmActionHandler {
|
||||
|
||||
boolean supports(String actionArn);
|
||||
|
||||
void handle(String actionArn, MetricAlarm alarm, double metricValue, String region);
|
||||
}
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.enterprise.inject.Any;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Evaluates every CloudWatch alarm that carries metric-math configuration
|
||||
* (namespace/metricName/period/evaluationPeriods/comparisonOperator), transitions its
|
||||
* {@code StateValue} the way real CloudWatch would, and while it is in {@code ALARM}
|
||||
* dispatches {@code AlarmActions} through {@link AlarmActionHandler} on every tick — not
|
||||
* just the first transition into that state, so an action deferred by a handler (e.g. a
|
||||
* scaling policy still in cooldown) is retried on a later tick rather than dropped for as
|
||||
* long as the breach continues.
|
||||
*
|
||||
* <p>Generic on purpose: this class has no notion of Application Auto Scaling or ECS. An
|
||||
* alarm created by hand (e.g. for a {@code StepScaling} policy, which AWS does not
|
||||
* auto-create alarms for) is evaluated identically to one Floci synthesized itself.</p>
|
||||
*
|
||||
* <p>The value handed to {@link AlarmActionHandler#handle} is always the most recent
|
||||
* <em>breaching</em> datapoint, not simply the most recent one chronologically — the two can
|
||||
* differ once {@code TreatMissingData} lets missing periods themselves cause an {@code ALARM}
|
||||
* transition, and dispatching a non-breaching real reading in that case would push a handler's
|
||||
* math in the wrong direction. When {@code TreatMissingData=breaching} reaches {@code ALARM}
|
||||
* with no populated datapoint breaching at all, {@code NaN} is dispatched instead: this class
|
||||
* has no notion of what a sound substitute value would be for any given handler's math, so
|
||||
* that decision is left to the handler, which does know its own policy's semantics.</p>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class AlarmEvaluator {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AlarmEvaluator.class);
|
||||
|
||||
private final CloudWatchMetricsService metricsService;
|
||||
private final Instance<AlarmActionHandler> handlers;
|
||||
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(
|
||||
r -> new Thread(r, "alarm-evaluator"));
|
||||
|
||||
@Inject
|
||||
AlarmEvaluator(CloudWatchMetricsService metricsService, @Any Instance<AlarmActionHandler> handlers) {
|
||||
this.metricsService = metricsService;
|
||||
this.handlers = handlers;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void start() {
|
||||
scheduler.scheduleAtFixedRate(this::evaluateAll, 5, 10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void stop() {
|
||||
scheduler.shutdownNow();
|
||||
}
|
||||
|
||||
void onStart(@Observes StartupEvent event) {
|
||||
LOG.debug("Alarm evaluator initialized");
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole body, not just the per-alarm loop, is guarded: {@link
|
||||
* ScheduledExecutorService#scheduleAtFixedRate} silently stops all future executions
|
||||
* forever if the submitted task throws, so a transient failure fetching the alarm list
|
||||
* itself (not just evaluating one alarm) must not be allowed to kill every future tick.
|
||||
*/
|
||||
void evaluateAll() {
|
||||
try {
|
||||
for (MetricAlarm alarm : metricsService.allAlarms()) {
|
||||
try {
|
||||
evaluate(alarm);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Alarm evaluation failed for {0}: {1}", alarm.getAlarmName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Alarm evaluation tick failed: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates the last {@code evaluationPeriods} <em>complete</em> periods, not counting
|
||||
* whichever period is still accumulating right now — matching real CloudWatch, which
|
||||
* evaluates elapsed periods only. Counting the in-progress period would make it look
|
||||
* "missing" on nearly every tick even under perfectly healthy, continuous reporting,
|
||||
* since data for it typically hasn't arrived yet.
|
||||
*/
|
||||
void evaluate(MetricAlarm alarm) {
|
||||
if (!isEvaluable(alarm)) {
|
||||
return;
|
||||
}
|
||||
String region = alarm.getRegion();
|
||||
int period = alarm.getPeriod();
|
||||
int evaluationPeriods = alarm.getEvaluationPeriods();
|
||||
long nowBucket = (Instant.now().getEpochSecond() / period) * period;
|
||||
long lastCompleteBucket = nowBucket - period;
|
||||
long oldestBucket = lastCompleteBucket - (long) period * (evaluationPeriods - 1);
|
||||
Instant start = Instant.ofEpochSecond(oldestBucket);
|
||||
Instant end = Instant.ofEpochSecond(lastCompleteBucket + period - 1);
|
||||
|
||||
List<CloudWatchMetricsService.Datapoint> recent = metricsService.getMetricStatistics(
|
||||
alarm.getNamespace(), alarm.getMetricName(), alarm.getDimensions(),
|
||||
start, end, period, List.of(alarm.getStatistic()), alarm.getUnit(), region);
|
||||
int missing = evaluationPeriods - recent.size();
|
||||
|
||||
int breaching = 0;
|
||||
double latestValue = Double.NaN;
|
||||
for (CloudWatchMetricsService.Datapoint dp : recent) {
|
||||
double value = CloudWatchMetricsService.resolveStatValue(dp, alarm.getStatistic());
|
||||
if (breaches(value, alarm.getComparisonOperator(), alarm.getThreshold())) {
|
||||
breaching++;
|
||||
latestValue = value;
|
||||
}
|
||||
}
|
||||
|
||||
String newState;
|
||||
String reason;
|
||||
if (missing > 0) {
|
||||
String treatMissingData = alarm.getTreatMissingData();
|
||||
if ("ignore".equalsIgnoreCase(treatMissingData)) {
|
||||
newState = alarm.getStateValue();
|
||||
reason = alarm.getStateReason();
|
||||
} else if ("breaching".equalsIgnoreCase(treatMissingData)) {
|
||||
newState = evaluateBreachCount(breaching + missing, alarm, evaluationPeriods);
|
||||
reason = "Threshold Crossed (missing datapoints treated as breaching): "
|
||||
+ (breaching + missing) + " datapoint(s) breaching the threshold.";
|
||||
} else if ("notBreaching".equalsIgnoreCase(treatMissingData)) {
|
||||
newState = evaluateBreachCount(breaching, alarm, evaluationPeriods);
|
||||
reason = "Threshold evaluated with missing datapoints treated as not breaching: "
|
||||
+ breaching + " datapoint(s) breaching the threshold.";
|
||||
} else {
|
||||
newState = "INSUFFICIENT_DATA";
|
||||
reason = "Insufficient Data: " + recent.size() + " of " + evaluationPeriods + " datapoints available";
|
||||
}
|
||||
} else {
|
||||
newState = evaluateBreachCount(breaching, alarm, evaluationPeriods);
|
||||
reason = ("ALARM".equals(newState) ? "Threshold Crossed: " : "Threshold Not Crossed: ")
|
||||
+ breaching + " datapoint(s) breaching the threshold.";
|
||||
}
|
||||
|
||||
if (!newState.equals(alarm.getStateValue())) {
|
||||
metricsService.setAlarmState(alarm.getAlarmName(), newState, reason, null, region);
|
||||
}
|
||||
|
||||
if ("ALARM".equals(newState) && alarm.isActionsEnabled()) {
|
||||
dispatch(alarm, latestValue, region);
|
||||
}
|
||||
}
|
||||
|
||||
private static String evaluateBreachCount(int breaching, MetricAlarm alarm, int evaluationPeriods) {
|
||||
int datapointsToAlarm = alarm.getDatapointsToAlarm() > 0 ? alarm.getDatapointsToAlarm() : evaluationPeriods;
|
||||
return breaching >= datapointsToAlarm ? "ALARM" : "OK";
|
||||
}
|
||||
|
||||
private void dispatch(MetricAlarm alarm, double metricValue, String region) {
|
||||
for (String actionArn : alarm.getAlarmActions()) {
|
||||
for (AlarmActionHandler handler : handlers) {
|
||||
if (handler.supports(actionArn)) {
|
||||
try {
|
||||
handler.handle(actionArn, alarm, metricValue, region);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Alarm action {0} failed for {1}: {2}",
|
||||
actionArn, alarm.getAlarmName(), e.getMessage());
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isEvaluable(MetricAlarm alarm) {
|
||||
return alarm.getRegion() != null
|
||||
&& alarm.getNamespace() != null && !alarm.getNamespace().isBlank()
|
||||
&& alarm.getMetricName() != null && !alarm.getMetricName().isBlank()
|
||||
&& alarm.getPeriod() > 0
|
||||
&& alarm.getEvaluationPeriods() > 0
|
||||
&& alarm.getComparisonOperator() != null;
|
||||
}
|
||||
|
||||
private static boolean breaches(double value, String comparisonOperator, double threshold) {
|
||||
return switch (comparisonOperator) {
|
||||
case "GreaterThanThreshold" -> value > threshold;
|
||||
case "GreaterThanOrEqualToThreshold" -> value >= threshold;
|
||||
case "LessThanThreshold" -> value < threshold;
|
||||
case "LessThanOrEqualToThreshold" -> value <= threshold;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -353,7 +353,8 @@ public class CloudWatchMetricsQueryHandler {
|
||||
MetricAlarm a = new MetricAlarm();
|
||||
a.setAlarmName(params.getFirst("AlarmName"));
|
||||
a.setAlarmDescription(params.getFirst("AlarmDescription"));
|
||||
a.setActionsEnabled(Boolean.parseBoolean(params.getFirst("ActionsEnabled")));
|
||||
String actionsEnabled = params.getFirst("ActionsEnabled");
|
||||
a.setActionsEnabled(actionsEnabled == null || Boolean.parseBoolean(actionsEnabled));
|
||||
a.setMetricName(params.getFirst("MetricName"));
|
||||
a.setNamespace(params.getFirst("Namespace"));
|
||||
a.setStatistic(params.getFirst("Statistic"));
|
||||
|
||||
+10
-1
@@ -221,7 +221,9 @@ public class CloudWatchMetricsService {
|
||||
return results;
|
||||
}
|
||||
|
||||
private double resolveStatValue(Datapoint dp, String stat) {
|
||||
/** Shared with {@link AlarmEvaluator}, which resolves the same statistic against
|
||||
* freshly-fetched datapoints when evaluating an alarm's threshold. */
|
||||
public static double resolveStatValue(Datapoint dp, String stat) {
|
||||
return switch (stat) {
|
||||
case "Average" -> dp.average();
|
||||
case "Sum" -> dp.sum();
|
||||
@@ -239,11 +241,18 @@ public class CloudWatchMetricsService {
|
||||
if (alarm.getAlarmArn() == null) {
|
||||
alarm.setAlarmArn(regionResolver.buildArn("cloudwatch", region, "alarm:" + alarm.getAlarmName()));
|
||||
}
|
||||
alarm.setRegion(region);
|
||||
alarm.setAlarmConfigurationUpdatedTimestamp(Instant.now().getEpochSecond());
|
||||
alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);
|
||||
LOG.infov("PutMetricAlarm: {0} in {1}", alarm.getAlarmName(), region);
|
||||
}
|
||||
|
||||
/** Every stored alarm, across all regions. Used by the background {@link AlarmEvaluator}
|
||||
* tick, which has no per-request region to scope a lookup to. */
|
||||
public List<MetricAlarm> allAlarms() {
|
||||
return alarmStore.scan(k -> true);
|
||||
}
|
||||
|
||||
public List<MetricAlarm> describeAlarms(List<String> alarmNames, String alarmNamePrefix, String region) {
|
||||
String prefix = region + "::";
|
||||
List<MetricAlarm> all = alarmStore.scan(k -> k.startsWith(prefix));
|
||||
|
||||
+6
@@ -37,6 +37,7 @@ public class MetricAlarm {
|
||||
private String treatMissingData = "missing";
|
||||
private String evaluateLowSampleCountPercentile;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
private String region;
|
||||
|
||||
public MetricAlarm() {
|
||||
long now = Instant.now().getEpochSecond();
|
||||
@@ -118,4 +119,9 @@ public class MetricAlarm {
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
|
||||
/** Not part of the AWS shape; set by {@code putMetricAlarm} so a background evaluator
|
||||
* that only holds the alarm object still knows which region's metric data to query. */
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
}
|
||||
Reference in new issue
Block a user