This repository has been archived by the owner on Jun 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Autoscaler.cs
303 lines (270 loc) · 14.1 KB
/
Autoscaler.cs
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DynamoDbAutoscaler.Configuration;
using DynamoDbAutoscaler.Interfaces;
using DynamoDbAutoscaler.Models;
using DynamoDbAutoscaler.Provisioners;
using Serilog;
using DynamoDbAutoscaler;
namespace DynamoDbAutoscaler
{
public class Autoscaler : IAutoscaler
{
private readonly IDynamoDbTableThroughputClient throughputClient;
private readonly IDynamoDbTableMetricsClient metricsClient;
private readonly IAutoscalingCalculator autoscalingCalculator;
private readonly ICircuitBreaker circuitBreaker;
private readonly ILogger structuredLogger;
public Autoscaler(ILogger logger) : this(
new DynamoDbTableThroughputClient(logger),
new CloudWatchDynamoDbTableMetricsClient(),
new AutoscalingCalculator(logger),
new NullCircuitBreaker(),
logger)
{
}
public Autoscaler(
IDynamoDbTableThroughputClient throughputClient,
IDynamoDbTableMetricsClient metricsClient,
IAutoscalingCalculator autoscalingCalculator,
ICircuitBreaker circuitBreaker,
ILogger structuredLogger)
{
this.throughputClient = throughputClient;
this.metricsClient = metricsClient;
this.autoscalingCalculator = autoscalingCalculator;
this.circuitBreaker = circuitBreaker;
this.structuredLogger = structuredLogger;
}
public async Task EnsureProvisionAsync(
GlobalAutoscalingConfigurationSet configurationSet,
CancellationToken cancellationToken = default(CancellationToken))
{
var isCircuitBreakerTripped = await circuitBreaker.IsTrippedAsync();
var exceptions = new List<Exception>();
foreach (var configuration in configurationSet.TableConfigurations.Concat(configurationSet.GlobalSecondaryIndexConfigurations))
{
try
{
await EnsureProvisionAsync(isCircuitBreakerTripped, configuration, cancellationToken).ConfigureAwait(false);
}
catch (Exception exception)
{
structuredLogger.Error(exception,
"Failed to ensure provisioning {TableName}-{EntityName} R:{Reads} W:{Writes}",
configuration.TableName,
configuration.EntityName,
configuration.Writes,
configuration.Reads);
exceptions.Add(exception);
}
}
if (exceptions.Any())
{
throw exceptions.Count().Equals(1) ? exceptions.First() : new AggregateException(exceptions);
}
}
internal async Task EnsureProvisionAsync(
bool isCircuitBreakerTripped,
AutoscalingConfigurationSet configurationSet,
CancellationToken cancellationToken = default(CancellationToken))
{
if (configurationSet is GlobalSecondaryIndexAutoscalingConfigurationSet)
{
var indexConfiguration = configurationSet as GlobalSecondaryIndexAutoscalingConfigurationSet;
if (indexConfiguration.IndexName.Equals("*"))
{
await EnsureAllGlobalSecondaryIndexProvisionAsync(isCircuitBreakerTripped, indexConfiguration, cancellationToken).ConfigureAwait(false);
}
else
{
await EnsureGlobalSecondaryIndexProvisionAsync(isCircuitBreakerTripped, indexConfiguration, cancellationToken).ConfigureAwait(false);
}
}
else if (configurationSet is TableAutoscalingConfigurationSet)
{
var tableConfiguration = configurationSet as TableAutoscalingConfigurationSet;
await EnsureTableProvisionAsync(isCircuitBreakerTripped, tableConfiguration, cancellationToken).ConfigureAwait(false);
}
}
internal async Task EnsureTableProvisionAsync(
bool isCircuitBreakerTripped,
TableAutoscalingConfigurationSet configuration,
CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
var tableName = configuration.TableName;
var provisioned = await throughputClient.GetTableThroughputLevelAsync(tableName, cancellationToken).ConfigureAwait(false);
var metrics = await metricsClient.GetTableMetricsAsync(tableName, cancellationToken).ConfigureAwait(false);
LogStats(configuration, provisioned, metrics);
var updated = EnsureProvision(isCircuitBreakerTripped, provisioned, metrics, configuration);
var provisioner = new TableProvisioner(tableName, throughputClient, structuredLogger);
await provisioner.ProvisionAsync(configuration, provisioned, updated, cancellationToken).ConfigureAwait(false);
}
internal async Task EnsureAllGlobalSecondaryIndexProvisionAsync(
bool isCircuitBreakerTripped,
GlobalSecondaryIndexAutoscalingConfigurationSet configuration,
CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
var tableName = configuration.TableName;
var indices = await throughputClient.FindAllGlobalSecondaryIndexThroughputLevelsAsync(tableName, cancellationToken).ConfigureAwait(false);
foreach (var index in indices)
{
var indexConfiguration = new GlobalSecondaryIndexAutoscalingConfigurationSet(tableName, index.IndexName, configuration);
await EnsureGlobalSecondaryIndexProvisionAsync(isCircuitBreakerTripped, indexConfiguration, cancellationToken).ConfigureAwait(false);
}
}
internal async Task EnsureGlobalSecondaryIndexProvisionAsync(
bool isCircuitBreakerTripped,
GlobalSecondaryIndexAutoscalingConfigurationSet configuration,
CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
var tableName = configuration.TableName;
var indexName = configuration.IndexName;
var provisioned = await throughputClient.GetGlobalSecondaryIndexThroughputLevelAsync(tableName, indexName, cancellationToken).ConfigureAwait(false);
var metrics = await metricsClient.GetGlobalSecondaryIndexMetricsAsync(tableName, indexName, cancellationToken);
LogStats(configuration, provisioned, metrics);
var updated = EnsureProvision(isCircuitBreakerTripped, provisioned, metrics, configuration);
var provisioner = new GlobalSecondaryIndexProvisioner(tableName, indexName, throughputClient, structuredLogger);
await provisioner.ProvisionAsync(configuration, provisioned, updated, cancellationToken).ConfigureAwait(false);
}
internal DynamoDbTableThroughput EnsureProvision(
bool isCircuitBreakerTripped,
DynamoDbTableThroughput provisioned,
DynamoDbMetrics metrics,
AutoscalingConfigurationSet configuration)
{
var updatedReads = EnsureProvision(isCircuitBreakerTripped, provisioned.ReadThroughput, metrics.ReadsThroughputMetrics, configuration.Reads);
var updatedWrites = EnsureProvision(isCircuitBreakerTripped, provisioned.WriteThroughput, metrics.WritesThroughputMetrics, configuration.Writes);
var updated = new DynamoDbTableThroughput { ReadThroughput = updatedReads, WriteThroughput = updatedWrites };
return updated;
}
internal long EnsureProvision(
bool isCircuitBreakerTripped,
long provisioned,
DynamoDbThroughputMetrics metrics,
AutoscalingConfiguration configuration)
{
var scaleDirection = ComputeScaleDirection(isCircuitBreakerTripped, provisioned, metrics, configuration);
var updated = ComputeUpdatedProvisioned(provisioned, scaleDirection, metrics, configuration);
return updated;
}
internal AutoscaleDirection ComputeScaleDirection(
bool isCircuitBreakerTripped,
long provisioned,
DynamoDbThroughputMetrics metrics,
AutoscalingConfiguration configuration)
{
var upperThreshold = configuration.UpperThreshold.GetValueOrDefault();
var lowerThreshold = configuration.LowerThreshold.GetValueOrDefault();
var throttleThreshold = configuration.ThrottleThreshold.GetValueOrDefault();
return ComputeScaleDirection(
isCircuitBreakerTripped, provisioned, metrics.ConsumedCapacityUnits, upperThreshold, lowerThreshold, throttleThreshold,
metrics.ThrottleEvents, metrics.ConsumptionDirection, metrics.ThrottleDirection);
}
internal long ComputeUpdatedProvisioned(
long provisioned,
AutoscaleDirection autoscaleDirection,
DynamoDbThroughputMetrics metrics,
AutoscalingConfiguration configuration)
{
var increasePercent = configuration.IncreaseWithPercent.GetValueOrDefault();
var decreasePercent = configuration.DecreaseWithPercent.GetValueOrDefault();
var minProvisioned = configuration.MinProvisioned.GetValueOrDefault();
var maxProvisioned = configuration.MaxProvisioned.GetValueOrDefault();
return ComputeUpdatedProvisioned(
autoscaleDirection, provisioned, increasePercent, decreasePercent, minProvisioned, maxProvisioned);
}
internal AutoscaleDirection ComputeScaleDirection(
bool isCircuitBreakerTripped,
long provisionedUnits,
long consumedUnits,
int upperThreshold,
int lowerThreshold,
int throttleThreshold,
long throttleEvents,
double consumptionDirection,
double throttleDirection)
{
var consumed = consumedUnits.ToPercentage(provisionedUnits);
// Todo: Currently ignored
if (throttleDirection > 0)
{
// return ScaleDirection.UltraUp; // Scale up x3
}
// We only will do a scale up or stay operation when the circuit breaker is open
// That way we do not scale down while we are having problems (like a bad deploy)
if (throttleEvents > throttleThreshold && !isCircuitBreakerTripped)
{
return AutoscaleDirection.UltraUp;
}
else if (consumed >= upperThreshold)
{
return AutoscaleDirection.Up;
}
else if (consumptionDirection > 0)
{
return AutoscaleDirection.Stay;
}
else if (consumed <= lowerThreshold && !isCircuitBreakerTripped)
{
return AutoscaleDirection.Down;
}
return AutoscaleDirection.Stay;
}
internal long ComputeUpdatedProvisioned(
AutoscaleDirection autoscaleDirection,
long provisionedUnits,
int increasePercent,
int decreasePercent,
int minProvisioned,
int maxProvisioned)
{
var updatedUnits = ComputeUpdatedProvisioned(autoscaleDirection, provisionedUnits, increasePercent, decreasePercent);
updatedUnits = autoscalingCalculator.EnsureProvisionInRange(updatedUnits, minProvisioned, maxProvisioned);
return updatedUnits;
}
private long ComputeUpdatedProvisioned(
AutoscaleDirection autoscaleDirection,
long provisionedUnits,
int increasePercent,
int decreasePercent)
{
switch (autoscaleDirection)
{
case AutoscaleDirection.UltraUp:
return autoscalingCalculator.CalculateProvisionIncrease(provisionedUnits, increasePercent * 4);
case AutoscaleDirection.ExtraUp:
return autoscalingCalculator.CalculateProvisionIncrease(provisionedUnits, increasePercent * 2);
case AutoscaleDirection.Up:
return autoscalingCalculator.CalculateProvisionIncrease(provisionedUnits, increasePercent);
case AutoscaleDirection.Down:
return autoscalingCalculator.CalculateProvisionDecrease(provisionedUnits, decreasePercent);
default:
return provisionedUnits;
}
}
private void LogStats(AutoscalingConfigurationSet configuration, DynamoDbThroughput throughput, DynamoDbMetrics metrics)
{
var entityName = configuration.EntityName;
var readsProvisioned = throughput.ReadThroughput;
var writesProvisioned = throughput.WriteThroughput;
var readsConsumed = metrics.ConsumedReadCapacityUnits;
var writesConsumed = metrics.ConsumedWriteCapacityUnits;
var readsPercent = readsConsumed.ToPercentage(readsProvisioned);
var writesPercent = writesConsumed.ToPercentage(writesProvisioned);
structuredLogger.Information(
"{EntityName}:reads {ReadsConsumed}/{ReadsProvisioned},{ReadsPercent}%,->{ReadConsumptionDirection},{ReadThrottleEvents}",
entityName, readsConsumed, readsProvisioned, readsPercent, metrics.ReadConsumptionDirection.ToString("F4"), metrics.ReadThrottleEvents);
structuredLogger.Information(
"{EntityName}:writes {WritesConsumed}/{WritesProvisioned},{WritesPercent}%,->{WriteConsumptionDirection},{WriteThrottleEvents}",
entityName, writesConsumed, writesProvisioned, writesPercent, metrics.WriteConsumptionDirection.ToString("F4"), metrics.WriteThrottleEvents);
}
}
}