-
Notifications
You must be signed in to change notification settings - Fork 4k
/
step-scaling-policy.ts
216 lines (189 loc) · 7.47 KB
/
step-scaling-policy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { findAlarmThresholds, normalizeIntervals } from '@aws-cdk/aws-autoscaling-common';
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as cdk from '@aws-cdk/core';
import { IAutoScalingGroup } from './auto-scaling-group';
import { AdjustmentType, MetricAggregationType, StepScalingAction } from './step-scaling-action';
export interface BasicStepScalingPolicyProps {
/**
* Metric to scale on.
*/
readonly metric: cloudwatch.IMetric;
/**
* The intervals for scaling.
*
* Maps a range of metric values to a particular scaling behavior.
*/
readonly scalingSteps: ScalingInterval[];
/**
* How the adjustment numbers inside 'intervals' are interpreted.
*
* @default ChangeInCapacity
*/
readonly adjustmentType?: AdjustmentType;
/**
* Grace period after scaling activity.
*
* @default Default cooldown period on your AutoScalingGroup
*/
readonly cooldown?: cdk.Duration;
/**
* Estimated time until a newly launched instance can send metrics to CloudWatch.
*
* @default Same as the cooldown
*/
readonly estimatedInstanceWarmup?: cdk.Duration;
/**
* Minimum absolute number to adjust capacity with as result of percentage scaling.
*
* Only when using AdjustmentType = PercentChangeInCapacity, this number controls
* the minimum absolute effect size.
*
* @default No minimum scaling effect
*/
readonly minAdjustmentMagnitude?: number;
}
export interface StepScalingPolicyProps extends BasicStepScalingPolicyProps {
/**
* The auto scaling group
*/
readonly autoScalingGroup: IAutoScalingGroup;
}
/**
* Define a acaling strategy which scales depending on absolute values of some metric.
*
* You can specify the scaling behavior for various values of the metric.
*
* Implemented using one or more CloudWatch alarms and Step Scaling Policies.
*/
export class StepScalingPolicy extends cdk.Construct {
public readonly lowerAlarm?: cloudwatch.Alarm;
public readonly lowerAction?: StepScalingAction;
public readonly upperAlarm?: cloudwatch.Alarm;
public readonly upperAction?: StepScalingAction;
constructor(scope: cdk.Construct, id: string, props: StepScalingPolicyProps) {
super(scope, id);
if (props.scalingSteps.length < 2) {
throw new Error('You must supply at least 2 intervals for autoscaling');
}
const adjustmentType = props.adjustmentType || AdjustmentType.CHANGE_IN_CAPACITY;
const changesAreAbsolute = adjustmentType === AdjustmentType.EXACT_CAPACITY;
const intervals = normalizeIntervals(props.scalingSteps, changesAreAbsolute);
const alarms = findAlarmThresholds(intervals);
if (alarms.lowerAlarmIntervalIndex !== undefined) {
const threshold = intervals[alarms.lowerAlarmIntervalIndex].upper;
this.lowerAction = new StepScalingAction(this, 'LowerPolicy', {
adjustmentType: props.adjustmentType,
cooldown: props.cooldown,
metricAggregationType: aggregationTypeFromMetric(props.metric),
minAdjustmentMagnitude: props.minAdjustmentMagnitude,
autoScalingGroup: props.autoScalingGroup,
});
for (let i = alarms.lowerAlarmIntervalIndex; i >= 0; i--) {
this.lowerAction.addAdjustment({
adjustment: intervals[i].change!,
lowerBound: i !== 0 ? intervals[i].lower - threshold : undefined, // Extend last interval to -infinity
upperBound: intervals[i].upper - threshold,
});
}
this.lowerAlarm = new cloudwatch.Alarm(this, 'LowerAlarm', {
// Recommended by AutoScaling
metric: props.metric,
alarmDescription: 'Lower threshold scaling alarm',
comparisonOperator: cloudwatch.ComparisonOperator.LESS_THAN_OR_EQUAL_TO_THRESHOLD,
evaluationPeriods: 1,
threshold,
});
this.lowerAlarm.addAlarmAction(new StepScalingAlarmAction(this.lowerAction));
}
if (alarms.upperAlarmIntervalIndex !== undefined) {
const threshold = intervals[alarms.upperAlarmIntervalIndex].lower;
this.upperAction = new StepScalingAction(this, 'UpperPolicy', {
adjustmentType: props.adjustmentType,
cooldown: props.cooldown,
metricAggregationType: aggregationTypeFromMetric(props.metric),
minAdjustmentMagnitude: props.minAdjustmentMagnitude,
autoScalingGroup: props.autoScalingGroup,
});
for (let i = alarms.upperAlarmIntervalIndex; i < intervals.length; i++) {
this.upperAction.addAdjustment({
adjustment: intervals[i].change!,
lowerBound: intervals[i].lower - threshold,
upperBound: i !== intervals.length - 1 ? intervals[i].upper - threshold : undefined, // Extend last interval to +infinity
});
}
this.upperAlarm = new cloudwatch.Alarm(this, 'UpperAlarm', {
// Recommended by AutoScaling
metric: props.metric,
alarmDescription: 'Upper threshold scaling alarm',
comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
evaluationPeriods: 1,
threshold,
});
this.upperAlarm.addAlarmAction(new StepScalingAlarmAction(this.upperAction));
}
}
}
function aggregationTypeFromMetric(metric: cloudwatch.IMetric): MetricAggregationType | undefined {
const statistic = metric.toMetricConfig().metricStat?.statistic;
if (statistic === undefined) { return undefined; } // Math expression, don't know aggregation, leave default
switch (statistic) {
case 'Average':
return MetricAggregationType.AVERAGE;
case 'Minimum':
return MetricAggregationType.MINIMUM;
case 'Maximum':
return MetricAggregationType.MAXIMUM;
default:
throw new Error(`Cannot only scale on 'Minimum', 'Maximum', 'Average' metrics, got ${statistic}`);
}
}
/**
* A range of metric values in which to apply a certain scaling operation
*/
export interface ScalingInterval {
/**
* The lower bound of the interval.
*
* The scaling adjustment will be applied if the metric is higher than this value.
*
* @default Threshold automatically derived from neighbouring intervals
*/
readonly lower?: number;
/**
* The upper bound of the interval.
*
* The scaling adjustment will be applied if the metric is lower than this value.
*
* @default Threshold automatically derived from neighbouring intervals
*/
readonly upper?: number;
/**
* The capacity adjustment to apply in this interval
*
* The number is interpreted differently based on AdjustmentType:
*
* - ChangeInCapacity: add the adjustment to the current capacity.
* The number can be positive or negative.
* - PercentChangeInCapacity: add or remove the given percentage of the current
* capacity to itself. The number can be in the range [-100..100].
* - ExactCapacity: set the capacity to this number. The number must
* be positive.
*/
readonly change: number;
}
/**
* Use a StepScalingAction as an Alarm Action
*
* This class is here and not in aws-cloudwatch-actions because this library
* needs to use the class, and otherwise we'd have a circular dependency:
*
* aws-autoscaling -> aws-cloudwatch-actions (for using the Action)
* aws-cloudwatch-actions -> aws-autoscaling (for the definition of IStepScalingAction)
*/
class StepScalingAlarmAction implements cloudwatch.IAlarmAction {
constructor(private readonly stepScalingAction: StepScalingAction) {
}
public bind(_scope: cdk.Construct, _alarm: cloudwatch.IAlarm): cloudwatch.AlarmActionConfig {
return { alarmActionArn: this.stepScalingAction.scalingPolicyArn };
}
}