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:
Matheus Oliveira authored and GitHub committed 2026-08-29 14:23:13 -04:00
1 parent cf6fede453
commit 2a7c94b04d
20 files changed
+1720 -10

No files matched your search

+73 -7
View File
@@ -22,6 +22,7 @@ Auto Scaling groups over the Query protocol under the `autoscaling` signing name
| `PutScalingPolicy` | Creates or updates a scaling policy and its CloudWatch alarms |
| `DescribeScalingPolicies` | Lists scaling policies in a namespace, optionally filtered |
| `DeleteScalingPolicy` | Deletes a scaling policy and its CloudWatch alarms |
| `DescribeScalingActivities` | Lists recorded capacity-change events for a scalable target |
| `ListTagsForResource` | Returns the tags on a scalable target |
| `TagResource` | Adds or overwrites tags on a scalable target |
| `UntagResource` | Removes tags from a scalable target |
@@ -64,6 +65,56 @@ TargetTracking-<resourceId>-AlarmLow-<uuid>
They are visible through `DescribeAlarms` and are deleted when the policy is deleted or
its scalable target is deregistered.
For `ecs` targets, the alarm is created with the same `ClusterName`/`ServiceName`
dimensions real AWS attaches to the metric, so a metric you push with
`cloudwatch:PutMetricData` using those dimensions is what the control loop below
evaluates against.
## Control loop (ECS only)
A background evaluator (ticking every ~10s) evaluates every CloudWatch alarm with
metric-math configuration — the two alarms above, and any hand-created alarm behind a
`StepScaling` policy, since AWS does not auto-create alarms for those — against the
metric data pushed via `PutMetricData`, transitioning `StateValue` the same way real
CloudWatch does, over the last `EvaluationPeriods` **complete** periods (the still-forming
current period is never counted, matching real CloudWatch). While an alarm is in `ALARM`,
its policy fires on every tick, not only the first transition — a scale-out blocked by
cooldown on one tick is retried on a later one instead of being dropped. For
`ScalableDimension=ecs:service:DesiredCount`, Floci calls the ECS `UpdateService` action
to actually change `desiredCount`, respecting `MinCapacity`/`MaxCapacity` and
`SuspendedState`.
- `TargetTrackingScaling` computes the new capacity as
`ceil(current * metricValue / TargetValue)`. `DisableScaleIn` suppresses the scale-in
direction only; the alarm still transitions.
- `StepScaling` resolves the matching `StepAdjustment` by comparing
`metricValue - Threshold` against each step's interval bounds, then applies
`AdjustmentType` (`ChangeInCapacity`, `PercentChangeInCapacity` with
`MinAdjustmentMagnitude`, or `ExactCapacity`).
- **Cooldown** (`ScaleInCooldown`/`ScaleOutCooldown` for target tracking, `Cooldown` for
step scaling) defaults to AWS's documented 300s ECS default when unset, not `0`. Per
AWS's own cooldown semantics, a scale-out blocked by cooldown still proceeds immediately
if the newly computed capacity is *larger* than what the last scale-out already applied
— cooldown exists to stop flapping on small repeated moves, not to cap a sustained
breach's climb toward `MaxCapacity`. Scale-in has no such carve-out and is simply
blocked for the full cooldown window, same as AWS.
- When `TreatMissingData=breaching` reaches `ALARM` with no populated datapoint actually
breaching (only missing periods pushed it there), the policy still fires: target
tracking nudges capacity by one unit in the alarm's own direction (the only substitute
that's guaranteed not to reverse direction), and step scaling resolves the step at
`delta=0` (right at the alarm's own threshold).
- `TreatMissingData=ignore` keeps the alarm's current state rather than transitioning it,
but if that current state is already `ALARM`, a deferred action still retries — "ignore"
only means "don't let this gap change my state," not "stop trying to act."
- Every capacity change is recorded and visible through `DescribeScalingActivities`.
- No metric data pushed for the alarm's window means `INSUFFICIENT_DATA` and no action —
Floci does not synthesize ECS CPU/memory metrics itself, so an operator (or a compat
test) has to push them to exercise the loop, the same way a real CloudWatch agent
would against real AWS.
- Scalable dimensions other than `ecs:service:DesiredCount` (MSK broker storage,
DynamoDB capacity, Lambda provisioned concurrency, ...) remain stored but inert, as
described below.
## Service-linked roles
When `RoleARN` is omitted, Floci synthesizes and returns a service-linked role ARN in the
@@ -75,19 +126,34 @@ arn:aws:iam::<account>:role/aws-service-role/<namespace>.application-autoscaling
## Limitations
- **Scaling policies are stored but inert.** Nothing evaluates them, no alarm ever fires,
and no capacity is ever adjusted — an ECS service's desired count will not change, and
MSK broker storage will not grow. This matches the existing behavior of EC2 Auto
Scaling's `PutScalingPolicy` in Floci. The control plane is faithful; the control loop
is not emulated.
- **Only `ecs:service:DesiredCount` is driven by the control loop above.** Every other
scalable dimension (MSK broker storage, DynamoDB capacity, Lambda provisioned
concurrency, EC2 Spot Fleet, ...) is stored and described faithfully, but nothing
evaluates its policies or adjusts its capacity. This matches the existing behavior of
EC2 Auto Scaling's `PutScalingPolicy` in Floci for those dimensions. The control plane
is faithful for all dimensions; the control loop is only emulated for ECS.
- `PutScheduledAction`, `DescribeScheduledActions`, and `DeleteScheduledAction` are not
implemented.
- `DescribeScalingActivities` is not implemented; there are no scaling activities to
report because policies never fire.
- `PredictiveScalingPolicyConfiguration` is accepted only insofar as `PolicyType` is
validated; the configuration block is not stored.
- Pagination is not implemented — `DescribeScalableTargets` and `DescribeScalingPolicies`
return all matching results and never emit a `NextToken`.
- **Missing-data evaluation uses a fixed window, not AWS's sliding one.** Real CloudWatch
queries a wider "evaluation range" than `Period × EvaluationPeriods` and, whenever enough
*real* datapoints exist within that wider range, evaluates using those and ignores
`TreatMissingData` entirely — falling back to it only when genuinely too few real
datapoints exist even with the extra lookback. Real CloudWatch also has "premature
transition" avoidance logic that can delay a move into `ALARM` when trailing data is
missing. Floci's evaluator queries exactly `EvaluationPeriods` period-aligned buckets and
applies `TreatMissingData` as soon as any of them is empty — correct for the common case
(continuous metric reporting) but less faithful once data has partial, intermittent gaps.
- **Scale-out cooldown rarely blocks a repeated scale-out in practice.** Its "proceed if
larger than the last applied capacity" carve-out (see above) is almost always satisfied
when nothing external has changed capacity, because both capacity formulas grow
monotonically with `current` — this matches AWS's documented intent for scale-out to add
capacity "as fast as it can," so cooldown's practical effect for this control loop is
mostly to gate scale-*in*, and to eventually halt scale-out once `MaxCapacity` is
reached (via the ordinary no-op-when-unchanged check, not the cooldown check itself).
## Terraform
@@ -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());
@@ -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();
}
}
@@ -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);
}
@@ -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) {}
}
@@ -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));
}
}
@@ -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; }
}
@@ -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; }
}
@@ -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);
}
@@ -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;
};
}
}
@@ -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"));
@@ -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));
@@ -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; }
}
@@ -0,0 +1,146 @@
package io.github.hectorvent.floci.services.applicationautoscaling;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
/**
* End-to-end coverage for the control loop that closes floci-io/floci#2565: a
* TargetTrackingScaling policy's CloudWatch alarm actually gets evaluated, and a breach
* changes the ECS service's {@code desiredCount} via {@code UpdateService}.
*
* <p>The alarm's period is fixed at 60s with 3 evaluation periods for the high alarm
* (matching real AWS's target-tracking defaults), and the evaluator's lookback window is
* period-aligned. Datapoints are pushed with explicit historical {@code Timestamp}s spanning
* six consecutive periods rather than exactly three, so whichever period boundary the
* evaluator's tick lands on, its 3-period aligned window is still fully covered — without a
* 3-minute real wait for fresh data to accrue.</p>
*
* <p>Because the pushed metric never responds to the resulting capacity change (unlike a real
* AWS metric), and AWS's own documented cooldown semantics let a scale-out that computes to a
* <em>larger</em> capacity than the last one proceed immediately, the service converges across
* several ticks — 2 desiredCount to 4, 4 to 8, 8 to 10 (clamped at {@code MaxCapacity}) — rather
* than settling after a single action. It stops there because the next recompute
* ({@code ceil(10 * 90 / 50) = 18}, clamped back to 10) no longer differs from the current
* capacity.</p>
*/
@QuarkusTest
class ApplicationAutoScalingEcsControlLoopIntegrationTest {
private static final String ECS_TARGET = "AmazonEC2ContainerServiceV20141113.";
private static final String AAS_TARGET = "AnyScaleFrontendService.";
private static final String CW_TARGET = "GraniteServiceVersion20100801.";
private static final String CT = "application/x-amz-json-1.1";
private static final String CLOUDWATCH_JSON_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String CLUSTER = "aas-loop-cluster";
private static final String SERVICE = "aas-loop-svc";
private static final String RESOURCE_ID = "service/" + CLUSTER + "/" + SERVICE;
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static Response call(String target, String action, String body) {
return call(target, action, body, CT);
}
private static Response call(String target, String action, String body, String contentType) {
RequestSpecification spec = given().contentType(contentType).header("X-Amz-Target", target + action);
if (body != null) {
spec = spec.body(body);
}
return spec.when().post("/").then().statusCode(200).extract().response();
}
@Test
void breachingMetricAdjustsEcsDesiredCount() {
call(ECS_TARGET, "CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}");
call(ECS_TARGET, "RegisterTaskDefinition", "{\"family\":\"aas-loop-td\","
+ "\"containerDefinitions\":[{\"name\":\"web\",\"image\":\"nginx\",\"memory\":128}]}");
call(ECS_TARGET, "CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"" + SERVICE + "\","
+ "\"taskDefinition\":\"aas-loop-td\",\"desiredCount\":2}");
call(AAS_TARGET, "RegisterScalableTarget", """
{
"ServiceNamespace": "ecs",
"ResourceId": "%s",
"ScalableDimension": "ecs:service:DesiredCount",
"MinCapacity": 1,
"MaxCapacity": 10
}
""".formatted(RESOURCE_ID));
call(AAS_TARGET, "PutScalingPolicy", """
{
"PolicyName": "aas-loop-cpu",
"PolicyType": "TargetTrackingScaling",
"ServiceNamespace": "ecs",
"ResourceId": "%s",
"ScalableDimension": "ecs:service:DesiredCount",
"TargetTrackingScalingPolicyConfiguration": {
"TargetValue": 50.0,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ECSServiceAverageCPUUtilization"
},
"ScaleOutCooldown": 300
}
}
""".formatted(RESOURCE_ID));
long now = Instant.now().getEpochSecond();
StringBuilder metricData = new StringBuilder("[");
for (int i = 5; i >= 0; i--) {
if (i != 5) {
metricData.append(",");
}
metricData.append("""
{
"MetricName": "ECSServiceAverageCPUUtilization",
"Value": 90.0,
"Unit": "Percent",
"Timestamp": %d,
"Dimensions": [
{"Name": "ClusterName", "Value": "%s"},
{"Name": "ServiceName", "Value": "%s"}
]
}
""".formatted(now - (60L * i), CLUSTER, SERVICE));
}
metricData.append("]");
call(CW_TARGET, "PutMetricData",
"{\"Namespace\":\"AWS/ECS\",\"MetricData\":" + metricData + "}", CLOUDWATCH_JSON_CONTENT_TYPE);
int maxCapacity = 10;
await().atMost(Duration.ofSeconds(60)).untilAsserted(() ->
call(ECS_TARGET, "DescribeServices",
"{\"cluster\":\"" + CLUSTER + "\",\"services\":[\"" + SERVICE + "\"]}")
.then().body("services[0].desiredCount", equalTo(maxCapacity)));
await().during(Duration.ofSeconds(15)).atMost(Duration.ofSeconds(20)).untilAsserted(() ->
call(ECS_TARGET, "DescribeServices",
"{\"cluster\":\"" + CLUSTER + "\",\"services\":[\"" + SERVICE + "\"]}")
.then().body("services[0].desiredCount", equalTo(maxCapacity)));
call(AAS_TARGET, "DescribeScalingActivities", """
{ "ServiceNamespace": "ecs", "ResourceId": "%s" }
""".formatted(RESOURCE_ID))
.then()
.body("ScalingActivities", hasSize(greaterThan(0)))
.body("ScalingActivities[0].StatusCode", equalTo("Successful"))
.body("ScalingActivities[0].ResourceId", equalTo(RESOURCE_ID));
}
}
@@ -57,7 +57,8 @@ class ApplicationAutoScalingServiceTest {
}).when(cloudWatch).deleteAlarms(any(), anyString());
service = new ApplicationAutoScalingService(
new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver, cloudWatch);
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
regionResolver, cloudWatch);
}
private ScalableTarget register() {
@@ -0,0 +1,62 @@
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 org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class EcsCapacityAdjusterTest {
private static final String REGION = "us-east-1";
private static final String RESOURCE_ID = "service/my-cluster/my-service";
private final EcsService ecsService = mock(EcsService.class);
private final EcsCapacityAdjuster adjuster = new EcsCapacityAdjuster(ecsService);
@Test
void supportsOnlyEcsDesiredCountDimension() {
assertTrue(adjuster.supports("ecs:service:DesiredCount"));
assertEquals(false, adjuster.supports("dynamodb:table:ReadCapacityUnits"));
}
@Test
void readsCurrentDesiredCountFromParsedClusterAndService() {
EcsServiceModel svc = new EcsServiceModel();
svc.setDesiredCount(4);
when(ecsService.describeServices("my-cluster", List.of("my-service"), REGION))
.thenReturn(List.of(svc));
assertEquals(4, adjuster.getCurrentCapacity(RESOURCE_ID, REGION));
}
@Test
void writesDesiredCountViaUpdateServiceLeavingOtherFieldsUntouched() {
adjuster.setCapacity(RESOURCE_ID, 7, REGION);
verify(ecsService).updateService("my-cluster", "my-service", null, 7, null, REGION);
}
@Test
void rejectsResourceIdNotShapedLikeAnEcsService() {
AwsException e = assertThrows(AwsException.class,
() -> adjuster.setCapacity("not-a-valid-id", 1, REGION));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void throwsWhenServiceNotFound() {
when(ecsService.describeServices("my-cluster", List.of("my-service"), REGION))
.thenReturn(List.of());
assertThrows(AwsException.class, () -> adjuster.getCurrentCapacity(RESOURCE_ID, REGION));
}
}
@@ -0,0 +1,352 @@
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.model.MetricAlarm;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ScalingPolicyAlarmActionHandlerTest {
private static final String REGION = "us-east-1";
private static final String RESOURCE_ID = "service/my-cluster/my-service";
private static final String POLICY_ARN =
"arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:x:resource/ecs/y:policyName/z";
private final ApplicationAutoScalingService service = mock(ApplicationAutoScalingService.class);
private final CapacityAdjuster adjuster = mock(CapacityAdjuster.class);
@SuppressWarnings("unchecked")
private final Instance<CapacityAdjuster> adjusters = mock(Instance.class);
private ScalingPolicyAlarmActionHandler handler;
@BeforeEach
void setUp() {
when(adjusters.iterator()).thenAnswer(inv -> List.of(adjuster).iterator());
when(adjuster.supports("ecs:service:DesiredCount")).thenReturn(true);
handler = new ScalingPolicyAlarmActionHandler(service, adjusters);
}
private static ScalingPolicy targetTrackingPolicy(double targetValue, Boolean disableScaleIn) {
ScalingPolicy policy = new ScalingPolicy();
policy.setPolicyName("cpu-target-tracking");
policy.setPolicyArn(POLICY_ARN);
policy.setPolicyType("TargetTrackingScaling");
policy.setServiceNamespace("ecs");
policy.setResourceId(RESOURCE_ID);
policy.setScalableDimension("ecs:service:DesiredCount");
TargetTrackingConfiguration config = new TargetTrackingConfiguration();
config.setTargetValue(targetValue);
config.setDisableScaleIn(disableScaleIn);
policy.setTargetTrackingConfiguration(config);
return policy;
}
private static ScalableTarget target(int min, int max) {
ScalableTarget target = new ScalableTarget();
target.setServiceNamespace("ecs");
target.setResourceId(RESOURCE_ID);
target.setScalableDimension("ecs:service:DesiredCount");
target.setMinCapacity(min);
target.setMaxCapacity(max);
return target;
}
private static MetricAlarm alarm(String comparisonOperator, double threshold) {
MetricAlarm alarm = new MetricAlarm();
alarm.setAlarmName("TargetTracking-svc-AlarmHigh-abc");
alarm.setComparisonOperator(comparisonOperator);
alarm.setThreshold(threshold);
return alarm;
}
private void stub(ScalingPolicy policy, ScalableTarget target, int currentCapacity) {
when(service.findPolicyByArn(POLICY_ARN, REGION)).thenReturn(Optional.of(policy));
when(service.findTarget(REGION, "ecs", RESOURCE_ID, "ecs:service:DesiredCount"))
.thenReturn(Optional.of(target));
when(adjuster.getCurrentCapacity(RESOURCE_ID, REGION)).thenReturn(currentCapacity);
}
@Test
void scalesOutProportionallyToTargetRatio() {
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
stub(policy, target(1, 10), 4);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 7, REGION);
assertTrue(policy.getLastScaleOutTime() > 0);
verify(service).savePolicy(policy, REGION);
verify(service).recordScalingActivity(eq(policy), anyString(), anyString(), eq(REGION));
}
@Test
void clampsToMaxCapacity() {
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
stub(policy, target(1, 5), 4);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 5, REGION);
}
@Test
void disableScaleInSuppressesScaleInAction() {
ScalingPolicy policy = targetTrackingPolicy(50.0, true);
stub(policy, target(1, 10), 4);
handler.handle(POLICY_ARN, alarm("LessThanThreshold", 50.0), 10.0, REGION);
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
}
@Test
void disableScaleInChecksTheComputedResultNotTheAlarmDirection() {
ScalingPolicy policy = targetTrackingPolicy(50.0, true);
stub(policy, target(1, 20), 10);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 30.0), 40.0, REGION);
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
}
@Test
void disableScaleInSuppressesADecreaseCausedByMaxCapacityClamp() {
ScalingPolicy policy = targetTrackingPolicy(50.0, true);
stub(policy, target(1, 10), 15);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
}
@Test
void suspendedScaleOutDirectionSkipsAction() {
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
ScalableTarget target = target(1, 10);
target.getSuspendedState().setDynamicScalingOutSuspended(true);
stub(policy, target, 4);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
}
@Test
void cooldownSuppressesRepeatedScaleIn() {
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
policy.getTargetTrackingConfiguration().setScaleInCooldown(300);
policy.setLastScaleInTime(System.currentTimeMillis() / 1000.0);
stub(policy, target(1, 10), 8);
handler.handle(POLICY_ARN, alarm("LessThanThreshold", 50.0), 20.0, REGION);
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
}
@Test
void interveningScaleInDoesNotCorruptTheScaleOutCooldownReference() {
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
policy.getTargetTrackingConfiguration().setScaleOutCooldown(300);
policy.setLastScaleOutCapacity(10);
policy.setLastAppliedCapacity(6);
policy.setLastScaleOutTime(System.currentTimeMillis() / 1000.0);
stub(policy, target(1, 20), 6);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 60.0, REGION);
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
}
@Test
void continuesScalingOutAcrossCallsAsCapacityConvergesTowardTheCeiling() {
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
stub(policy, target(1, 10), 4);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 7, REGION);
when(adjuster.getCurrentCapacity(RESOURCE_ID, REGION)).thenReturn(7);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 10, REGION);
when(adjuster.getCurrentCapacity(RESOURCE_ID, REGION)).thenReturn(10);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster, times(2)).setCapacity(anyString(), anyInt(), anyString());
}
@Test
void firesAgainWhenTheMetricValueChanges() {
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
stub(policy, target(1, 20), 4);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 7, REGION);
when(adjuster.getCurrentCapacity(RESOURCE_ID, REGION)).thenReturn(7);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 95.0, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 14, REGION);
}
@Test
void deferredScaleInStillFiresLaterOnceCooldownClears() {
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
policy.getTargetTrackingConfiguration().setScaleInCooldown(300);
policy.setLastScaleInTime(System.currentTimeMillis() / 1000.0);
stub(policy, target(1, 10), 8);
handler.handle(POLICY_ARN, alarm("LessThanThreshold", 50.0), 20.0, REGION);
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
policy.setLastScaleInTime(0);
handler.handle(POLICY_ARN, alarm("LessThanThreshold", 50.0), 20.0, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 4, REGION);
}
@Test
void noAdjusterRegisteredForDimensionIsNoOp() {
when(adjuster.supports("ecs:service:DesiredCount")).thenReturn(false);
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
stub(policy, target(1, 10), 4);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
}
@Test
void stepScalingExactCapacityAppliesMatchingStepDirectly() {
ScalingPolicy policy = new ScalingPolicy();
policy.setPolicyName("step-policy");
policy.setPolicyArn(POLICY_ARN);
policy.setPolicyType("StepScaling");
policy.setServiceNamespace("ecs");
policy.setResourceId(RESOURCE_ID);
policy.setScalableDimension("ecs:service:DesiredCount");
StepScalingConfiguration config = new StepScalingConfiguration();
config.setAdjustmentType("ExactCapacity");
StepAdjustment step = new StepAdjustment();
step.setMetricIntervalLowerBound(0.0);
step.setScalingAdjustment(9);
config.setStepAdjustments(List.of(step));
policy.setStepScalingConfiguration(config);
stub(policy, target(1, 10), 4);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 9, REGION);
}
@Test
void suspensionChecksTheComputedDirectionNotTheAlarmDirection() {
ScalingPolicy policy = new ScalingPolicy();
policy.setPolicyName("step-policy");
policy.setPolicyArn(POLICY_ARN);
policy.setPolicyType("StepScaling");
policy.setServiceNamespace("ecs");
policy.setResourceId(RESOURCE_ID);
policy.setScalableDimension("ecs:service:DesiredCount");
StepScalingConfiguration config = new StepScalingConfiguration();
config.setAdjustmentType("ChangeInCapacity");
StepAdjustment step = new StepAdjustment();
step.setMetricIntervalLowerBound(0.0);
step.setScalingAdjustment(-2);
config.setStepAdjustments(List.of(step));
policy.setStepScalingConfiguration(config);
ScalableTarget target = target(1, 10);
target.getSuspendedState().setDynamicScalingInSuspended(true);
stub(policy, target, 4);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
}
@Test
void nanMetricValueNudgesCapacityByOneInTheAlarmsDirection() {
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
stub(policy, target(1, 10), 4);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), Double.NaN, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 5, REGION);
}
@Test
void nanMetricValueForStepScalingResolvesTheZeroDeltaStep() {
ScalingPolicy policy = new ScalingPolicy();
policy.setPolicyName("step-policy");
policy.setPolicyArn(POLICY_ARN);
policy.setPolicyType("StepScaling");
policy.setServiceNamespace("ecs");
policy.setResourceId(RESOURCE_ID);
policy.setScalableDimension("ecs:service:DesiredCount");
StepScalingConfiguration config = new StepScalingConfiguration();
config.setAdjustmentType("ChangeInCapacity");
StepAdjustment step = new StepAdjustment();
step.setMetricIntervalLowerBound(0.0);
step.setScalingAdjustment(3);
config.setStepAdjustments(List.of(step));
policy.setStepScalingConfiguration(config);
stub(policy, target(1, 10), 4);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), Double.NaN, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 7, REGION);
}
@Test
void reconciliationContinuesWhenCapacityDriftsHigherExternally() {
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
stub(policy, target(1, 30), 4);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 7, REGION);
when(adjuster.getCurrentCapacity(RESOURCE_ID, REGION)).thenReturn(9);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 15, REGION);
}
@Test
void reconciliationBypassesCooldownWhenCapacityDriftsLowerExternally() {
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
policy.getTargetTrackingConfiguration().setScaleOutCooldown(300);
policy.setLastAppliedCapacity(10);
policy.setLastScaleOutTime(System.currentTimeMillis() / 1000.0);
stub(policy, target(1, 20), 3);
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster).setCapacity(RESOURCE_ID, 5, REGION);
}
@Test
void unknownPolicyArnIsNoOp() {
when(service.findPolicyByArn(POLICY_ARN, REGION)).thenReturn(Optional.empty());
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
}
}
@@ -0,0 +1,249 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class AlarmEvaluatorTest {
private static final String REGION = "us-east-1";
private static final String POLICY_ARN =
"arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:x:resource/ecs/y:policyName/z";
private final CloudWatchMetricsService metricsService = mock(CloudWatchMetricsService.class);
@SuppressWarnings("unchecked")
private final Instance<AlarmActionHandler> handlers = mock(Instance.class);
private final AlarmActionHandler handler = mock(AlarmActionHandler.class);
private final AlarmEvaluator evaluator = new AlarmEvaluator(metricsService, handlers);
private static MetricAlarm alarm() {
MetricAlarm alarm = new MetricAlarm();
alarm.setAlarmName("TargetTracking-svc-AlarmHigh-abc");
alarm.setRegion(REGION);
alarm.setNamespace("AWS/ECS");
alarm.setMetricName("CPUUtilization");
alarm.setStatistic("Average");
alarm.setPeriod(60);
alarm.setEvaluationPeriods(3);
alarm.setThreshold(50.0);
alarm.setComparisonOperator("GreaterThanThreshold");
alarm.setActionsEnabled(true);
alarm.setAlarmActions(List.of(POLICY_ARN));
return alarm;
}
private static List<CloudWatchMetricsService.Datapoint> datapoints(double... values) {
List<CloudWatchMetricsService.Datapoint> points = new ArrayList<>();
Instant now = Instant.now();
for (int i = 0; i < values.length; i++) {
points.add(new CloudWatchMetricsService.Datapoint(
now.minusSeconds(60L * (values.length - i)),
1, values[i], values[i], values[i], values[i], "Percent"));
}
return points;
}
private void stubMetrics(List<CloudWatchMetricsService.Datapoint> points) {
when(metricsService.getMetricStatistics(
any(), any(), any(), any(), any(), anyInt(), any(), any(), anyString()))
.thenReturn(points);
}
@Test
void transitionsToAlarmAndDispatchesWhenThresholdBreachedForAllPeriods() {
stubMetrics(datapoints(80, 85, 90));
when(handlers.iterator()).thenAnswer(inv -> List.of(handler).iterator());
when(handler.supports(POLICY_ARN)).thenReturn(true);
MetricAlarm alarm = alarm();
evaluator.evaluate(alarm);
verify(metricsService).setAlarmState(
eq(alarm.getAlarmName()), eq("ALARM"), anyString(), any(), eq(REGION));
verify(handler).handle(eq(POLICY_ARN), eq(alarm), eq(90.0), eq(REGION));
}
@Test
void redispatchesOnEveryTickWhileStillInAlarm() {
stubMetrics(datapoints(80, 85, 90));
when(handlers.iterator()).thenAnswer(inv -> List.of(handler).iterator());
when(handler.supports(POLICY_ARN)).thenReturn(true);
MetricAlarm alarm = alarm();
alarm.setStateValue("ALARM");
evaluator.evaluate(alarm);
verify(handler).handle(eq(POLICY_ARN), eq(alarm), eq(90.0), eq(REGION));
}
@Test
void insufficientDataWhenFewerDatapointsThanEvaluationPeriods() {
stubMetrics(datapoints(80));
MetricAlarm alarm = alarm();
alarm.setStateValue("OK");
evaluator.evaluate(alarm);
verify(metricsService).setAlarmState(
eq(alarm.getAlarmName()), eq("INSUFFICIENT_DATA"), anyString(), any(), eq(REGION));
}
@Test
void transitionsBackToOkWhenNoLongerBreaching() {
stubMetrics(datapoints(10, 15, 20));
MetricAlarm alarm = alarm();
alarm.setStateValue("ALARM");
evaluator.evaluate(alarm);
verify(metricsService).setAlarmState(
eq(alarm.getAlarmName()), eq("OK"), anyString(), any(), eq(REGION));
verify(handler, never()).handle(anyString(), any(), anyDouble(), anyString());
}
@Test
void skipsAlarmsMissingEvaluableConfig() {
MetricAlarm alarm = new MetricAlarm();
alarm.setAlarmName("hand-created-no-metric-config");
alarm.setRegion(REGION);
evaluator.evaluate(alarm);
verify(metricsService, never()).getMetricStatistics(
any(), any(), any(), any(), any(), anyInt(), any(), any(), anyString());
}
@Test
void evaluateAllSurvivesAllAlarmsThrowing() {
when(metricsService.allAlarms()).thenThrow(new RuntimeException("storage hiccup"));
assertDoesNotThrow(evaluator::evaluateAll);
}
@Test
void actionsDisabledSuppressesDispatchEvenOnBreach() {
stubMetrics(datapoints(80, 85, 90));
MetricAlarm alarm = alarm();
alarm.setActionsEnabled(false);
evaluator.evaluate(alarm);
verify(handler, never()).handle(anyString(), any(), anyDouble(), anyString());
}
@Test
void dispatchesTheMostRecentBreachingValueEvenWhenTheLatestDatapointDoesNot() {
stubMetrics(datapoints(90, 85, 20));
when(handlers.iterator()).thenAnswer(inv -> List.of(handler).iterator());
when(handler.supports(POLICY_ARN)).thenReturn(true);
MetricAlarm alarm = alarm();
alarm.setDatapointsToAlarm(2);
evaluator.evaluate(alarm);
verify(handler).handle(eq(POLICY_ARN), eq(alarm), eq(85.0), eq(REGION));
}
@Test
void treatMissingDataBreachingCountsGapsAsBreaching() {
stubMetrics(datapoints(80));
when(handlers.iterator()).thenAnswer(inv -> List.<AlarmActionHandler>of().iterator());
MetricAlarm alarm = alarm();
alarm.setStateValue("OK");
alarm.setTreatMissingData("breaching");
evaluator.evaluate(alarm);
verify(metricsService).setAlarmState(
eq(alarm.getAlarmName()), eq("ALARM"), anyString(), any(), eq(REGION));
}
@Test
void missingDataAlarmWithNoRealBreachingDatapointDispatchesNaN() {
stubMetrics(datapoints(20));
when(handlers.iterator()).thenAnswer(inv -> List.of(handler).iterator());
when(handler.supports(POLICY_ARN)).thenReturn(true);
MetricAlarm alarm = alarm();
alarm.setStateValue("OK");
alarm.setTreatMissingData("breaching");
alarm.setDatapointsToAlarm(2);
evaluator.evaluate(alarm);
verify(metricsService).setAlarmState(
eq(alarm.getAlarmName()), eq("ALARM"), anyString(), any(), eq(REGION));
verify(handler).handle(eq(POLICY_ARN), eq(alarm), eq(Double.NaN), eq(REGION));
}
@Test
void treatMissingDataNotBreachingDoesNotCountGapsTowardAlarm() {
stubMetrics(datapoints(80));
MetricAlarm alarm = alarm();
alarm.setStateValue("ALARM");
alarm.setTreatMissingData("notBreaching");
evaluator.evaluate(alarm);
verify(metricsService).setAlarmState(
eq(alarm.getAlarmName()), eq("OK"), anyString(), any(), eq(REGION));
}
@Test
void queriesAPeriodAlignedWindowRegardlessOfWhenTheTickFires() {
stubMetrics(datapoints(80, 85, 90));
when(handlers.iterator()).thenAnswer(inv -> List.<AlarmActionHandler>of().iterator());
evaluator.evaluate(alarm());
ArgumentCaptor<Instant> startCaptor = ArgumentCaptor.forClass(Instant.class);
verify(metricsService).getMetricStatistics(
any(), any(), any(), startCaptor.capture(), any(), anyInt(), any(), any(), anyString());
assertEquals(0, startCaptor.getValue().getEpochSecond() % 60);
}
@Test
void treatMissingDataIgnoreLeavesStateUntouched() {
stubMetrics(datapoints(80));
MetricAlarm alarm = alarm();
alarm.setStateValue("OK");
alarm.setTreatMissingData("ignore");
evaluator.evaluate(alarm);
verify(metricsService, never()).setAlarmState(
anyString(), anyString(), anyString(), any(), anyString());
}
@Test
void treatMissingDataIgnoreStillRetriesDispatchWhileAlreadyInAlarm() {
stubMetrics(datapoints(80));
when(handlers.iterator()).thenAnswer(inv -> List.of(handler).iterator());
when(handler.supports(POLICY_ARN)).thenReturn(true);
MetricAlarm alarm = alarm();
alarm.setStateValue("ALARM");
alarm.setTreatMissingData("ignore");
evaluator.evaluate(alarm);
verify(metricsService, never()).setAlarmState(
anyString(), anyString(), anyString(), any(), anyString());
verify(handler).handle(eq(POLICY_ARN), eq(alarm), eq(80.0), eq(REGION));
}
}
@@ -0,0 +1,57 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* The JSON 1.0 handler defaults {@code ActionsEnabled} to {@code true} when omitted, matching
* AWS's documented default for {@code PutMetricAlarm}. This handler must do the same over the
* Query protocol — a mismatch here would silently disable {@link AlarmEvaluator} dispatch for
* any hand-created alarm (e.g. behind a StepScaling policy) that doesn't explicitly pass the
* parameter, since {@code Boolean.parseBoolean(null)} defaults to {@code false}.
*/
class CloudWatchMetricsQueryHandlerTest {
private static final String REGION = "us-east-1";
private final CloudWatchMetricsService metricsService = mock(CloudWatchMetricsService.class);
private final CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(metricsService);
@Test
void putMetricAlarmDefaultsActionsEnabledToTrueWhenOmitted() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("AlarmName", "TestAlarm");
params.putSingle("MetricName", "M");
params.putSingle("Namespace", "NS");
handler.handle("PutMetricAlarm", params, REGION);
ArgumentCaptor<MetricAlarm> captor = ArgumentCaptor.forClass(MetricAlarm.class);
verify(metricsService).putMetricAlarm(captor.capture(), anyString());
assertTrue(captor.getValue().isActionsEnabled());
}
@Test
void putMetricAlarmRespectsExplicitActionsEnabledFalse() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("AlarmName", "TestAlarm");
params.putSingle("MetricName", "M");
params.putSingle("Namespace", "NS");
params.putSingle("ActionsEnabled", "false");
handler.handle("PutMetricAlarm", params, REGION);
ArgumentCaptor<MetricAlarm> captor = ArgumentCaptor.forClass(MetricAlarm.class);
verify(metricsService).putMetricAlarm(captor.capture(), anyString());
assertFalse(captor.getValue().isActionsEnabled());
}
}
+1
View File
@@ -168,6 +168,7 @@ services:
deferred_handlers:
- { path: src/main/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminJsonHandler.java } # single-op Identity Center stub, no standalone doc page yet
- { path: src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java } # non-tabular doc (grouped/inline)
- { path: src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ScalingPolicyAlarmActionHandler.java } # not a JSON/Query action dispatcher — its `case "X" ->` arms are the StepScaling AdjustmentType switch, not AWS actions
- { path: src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java } # non-tabular doc (grouped/inline)
- { path: src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsJsonHandler.java } # no standalone action table yet
- { path: src/main/java/io/github/hectorvent/floci/services/ce/CostExplorerJsonHandler.java } # no standalone action table yet