forked from spinnaker/keel
/
ClusterHandler.kt
1070 lines (969 loc) · 39.6 KB
/
ClusterHandler.kt
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.netflix.spinnaker.keel.ec2.resource
import com.fasterxml.jackson.module.kotlin.convertValue
import com.netflix.frigga.ami.AppVersion
import com.netflix.rocket.api.artifact.internal.debian.DebianArtifactParser
import com.netflix.spinnaker.keel.api.Exportable
import com.netflix.spinnaker.keel.api.Moniker
import com.netflix.spinnaker.keel.api.RedBlack
import com.netflix.spinnaker.keel.api.Resource
import com.netflix.spinnaker.keel.api.ResourceDiff
import com.netflix.spinnaker.keel.api.SubnetAwareLocations
import com.netflix.spinnaker.keel.api.SubnetAwareRegionSpec
import com.netflix.spinnaker.keel.api.actuation.Task
import com.netflix.spinnaker.keel.api.actuation.TaskLauncher
import com.netflix.spinnaker.keel.api.artifacts.ArtifactStatus.UNKNOWN
import com.netflix.spinnaker.keel.api.artifacts.DeliveryArtifact
import com.netflix.spinnaker.keel.api.artifacts.VirtualMachineOptions
import com.netflix.spinnaker.keel.api.ec2.CLOUD_PROVIDER
import com.netflix.spinnaker.keel.api.ec2.Capacity
import com.netflix.spinnaker.keel.api.ec2.ClusterDependencies
import com.netflix.spinnaker.keel.api.ec2.ClusterSpec
import com.netflix.spinnaker.keel.api.ec2.ClusterSpec.HealthSpec
import com.netflix.spinnaker.keel.api.ec2.ClusterSpec.ServerGroupSpec
import com.netflix.spinnaker.keel.api.ec2.CustomizedMetricSpecification
import com.netflix.spinnaker.keel.api.ec2.EC2_CLUSTER_V1
import com.netflix.spinnaker.keel.api.ec2.HealthCheckType
import com.netflix.spinnaker.keel.api.ec2.LaunchConfigurationSpec
import com.netflix.spinnaker.keel.api.ec2.Location
import com.netflix.spinnaker.keel.api.ec2.Metric
import com.netflix.spinnaker.keel.api.ec2.MetricDimension
import com.netflix.spinnaker.keel.api.ec2.PredefinedMetricSpecification
import com.netflix.spinnaker.keel.api.ec2.ReferenceArtifactImageProvider
import com.netflix.spinnaker.keel.api.ec2.Scaling
import com.netflix.spinnaker.keel.api.ec2.ScalingProcess
import com.netflix.spinnaker.keel.api.ec2.ServerGroup
import com.netflix.spinnaker.keel.api.ec2.ServerGroup.ActiveServerGroupImage
import com.netflix.spinnaker.keel.api.ec2.ServerGroup.Health
import com.netflix.spinnaker.keel.api.ec2.ServerGroup.LaunchConfiguration
import com.netflix.spinnaker.keel.api.ec2.StepAdjustment
import com.netflix.spinnaker.keel.api.ec2.StepScalingPolicy
import com.netflix.spinnaker.keel.api.ec2.TargetTrackingPolicy
import com.netflix.spinnaker.keel.api.ec2.TerminationPolicy
import com.netflix.spinnaker.keel.api.ec2.byRegion
import com.netflix.spinnaker.keel.api.ec2.resolve
import com.netflix.spinnaker.keel.api.id
import com.netflix.spinnaker.keel.api.plugins.Resolver
import com.netflix.spinnaker.keel.api.plugins.ResourceHandler
import com.netflix.spinnaker.keel.api.serviceAccount
import com.netflix.spinnaker.keel.artifacts.DebianArtifact
import com.netflix.spinnaker.keel.clouddriver.CloudDriverCache
import com.netflix.spinnaker.keel.clouddriver.CloudDriverService
import com.netflix.spinnaker.keel.clouddriver.ResourceNotFound
import com.netflix.spinnaker.keel.clouddriver.model.ActiveServerGroup
import com.netflix.spinnaker.keel.clouddriver.model.CustomizedMetricSpecificationModel
import com.netflix.spinnaker.keel.clouddriver.model.MetricDimensionModel
import com.netflix.spinnaker.keel.clouddriver.model.PredefinedMetricSpecificationModel
import com.netflix.spinnaker.keel.clouddriver.model.ScalingPolicy
import com.netflix.spinnaker.keel.clouddriver.model.StepAdjustmentModel
import com.netflix.spinnaker.keel.clouddriver.model.Tag
import com.netflix.spinnaker.keel.clouddriver.model.subnet
import com.netflix.spinnaker.keel.core.orcaClusterMoniker
import com.netflix.spinnaker.keel.core.parseMoniker
import com.netflix.spinnaker.keel.core.serverGroup
import com.netflix.spinnaker.keel.diff.toIndividualDiffs
import com.netflix.spinnaker.keel.ec2.MissingAppVersionException
import com.netflix.spinnaker.keel.ec2.toEc2Api
import com.netflix.spinnaker.keel.events.ArtifactVersionDeployed
import com.netflix.spinnaker.keel.events.ArtifactVersionDeploying
import com.netflix.spinnaker.keel.exceptions.ExportError
import com.netflix.spinnaker.keel.orca.ClusterExportHelper
import com.netflix.spinnaker.keel.orca.OrcaService
import com.netflix.spinnaker.keel.orca.dependsOn
import com.netflix.spinnaker.keel.orca.restrictedExecutionWindow
import com.netflix.spinnaker.keel.orca.waitStage
import com.netflix.spinnaker.keel.plugin.buildSpecFromDiff
import com.netflix.spinnaker.keel.retrofit.isNotFound
import com.netflix.spinnaker.keel.serialization.configuredObjectMapper
import java.time.Clock
import java.time.Duration
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import org.springframework.context.ApplicationEventPublisher
import retrofit2.HttpException
class ClusterHandler(
private val cloudDriverService: CloudDriverService,
private val cloudDriverCache: CloudDriverCache,
private val orcaService: OrcaService,
private val taskLauncher: TaskLauncher,
private val clock: Clock,
private val publisher: ApplicationEventPublisher,
resolvers: List<Resolver<*>>,
private val clusterExportHelper: ClusterExportHelper
) : ResourceHandler<ClusterSpec, Map<String, ServerGroup>>(resolvers) {
private val debianArtifactParser = DebianArtifactParser()
private val mapper = configuredObjectMapper()
override val supportedKind = EC2_CLUSTER_V1
override suspend fun toResolvedType(resource: Resource<ClusterSpec>): Map<String, ServerGroup> =
with(resource.spec) {
resolve().byRegion()
}
override suspend fun current(resource: Resource<ClusterSpec>): Map<String, ServerGroup> =
cloudDriverService
.getServerGroups(resource)
.byRegion()
override suspend fun upsert(
resource: Resource<ClusterSpec>,
resourceDiff: ResourceDiff<Map<String, ServerGroup>>
): List<Task> =
coroutineScope {
val diffs = resourceDiff
.toIndividualDiffs()
.filter { diff -> diff.hasChanges() }
val deferred: MutableList<Deferred<Task>> = mutableListOf()
val modifyDiffs = diffs.filter { it.isCapacityOrAutoScalingOnly() }
val createDiffs = diffs - modifyDiffs
if (modifyDiffs.isNotEmpty()) {
deferred.addAll(
modifyInPlace(resource, modifyDiffs))
}
val version = diffs.first().desired.launchConfiguration.appVersion
?: throw MissingAppVersionException(resource.id)
if (resource.spec.deployWith.isStaggered && createDiffs.isNotEmpty()) {
val tasks = upsertStaggered(resource, createDiffs, version)
return@coroutineScope tasks + deferred.map { it.await() }
}
deferred.addAll(
upsertUnstaggered(resource, createDiffs, version)
)
if (createDiffs.isNotEmpty()) {
publisher.publishEvent(ArtifactVersionDeploying(
resourceId = resource.id,
artifactVersion = version
))
}
return@coroutineScope deferred.map { it.await() }
}
private suspend fun modifyInPlace(
resource: Resource<ClusterSpec>,
diffs: List<ResourceDiff<ServerGroup>>
): List<Deferred<Task>> =
coroutineScope {
diffs.mapNotNull { diff ->
val (job, what) = when {
diff.isCapacityOnly() -> listOf(diff.resizeServerGroupJob()) to "capacity"
diff.isAutoScalingOnly() -> diff.modifyScalingPolicyJob() to "auto-scaling"
else -> listOf(diff.resizeServerGroupJob()) + diff.modifyScalingPolicyJob(1) to "capacity and auto-scaling"
}
if (job.isEmpty()) {
null
} else {
log.info("Modifying server group in-place using task: {}", job)
async {
taskLauncher.submitJob(
resource = resource,
description = "Modify $what of server group ${diff.desired.moniker} in " +
"${diff.desired.location.account}/${diff.desired.location.region}",
correlationId = "${resource.id}:${diff.desired.location.region}",
stages = job)
}
}
}
}
private suspend fun upsertUnstaggered(
resource: Resource<ClusterSpec>,
diffs: List<ResourceDiff<ServerGroup>>,
version: String,
dependsOn: String? = null
): List<Deferred<Task>> =
coroutineScope {
diffs.mapNotNull { diff ->
val stages: MutableList<Map<String, Any?>> = mutableListOf()
var refId = 0
if (dependsOn != null) {
stages.add(dependsOn(dependsOn))
refId++
}
when {
diff.shouldDeployAndModifyScalingPolicies() -> {
stages.add(diff.createServerGroupJob(refId) + resource.spec.deployWith.toOrcaJobProperties())
refId++
stages.addAll(diff.modifyScalingPolicyJob(refId))
}
else -> stages.add(diff.createServerGroupJob(refId) + resource.spec.deployWith.toOrcaJobProperties())
}
if (stages.isEmpty()) {
null
} else {
log.info("Upsert server group using task: {}", stages)
async {
taskLauncher.submitJob(
resource = resource,
description = "Deploy $version to server group ${diff.desired.moniker} in " +
"${diff.desired.location.account}/${diff.desired.location.region}",
correlationId = "${resource.id}:${diff.desired.location.region}",
stages = stages)
}
}
}
}
private suspend fun upsertStaggered(
resource: Resource<ClusterSpec>,
diffs: List<ResourceDiff<ServerGroup>>,
version: String
): List<Task> =
coroutineScope {
val regionalDiffs = diffs.associateBy { it.desired.location.region }
val tasks: MutableList<Task> = mutableListOf()
var priorExecutionId: String? = null
val staggeredRegions = resource.spec.deployWith.stagger.map {
it.region
}
.toSet()
// If any, these are deployed in-parallel after all regions with a defined stagger
val unstaggeredRegions = regionalDiffs.keys - staggeredRegions
for (stagger in resource.spec.deployWith.stagger) {
if (!regionalDiffs.containsKey(stagger.region)) {
continue
}
val diff = regionalDiffs[stagger.region] as ResourceDiff<ServerGroup>
val stages: MutableList<Map<String, Any?>> = mutableListOf()
var refId = 0
/**
* Given regions staggered as [A, B, C], this makes the execution of the B
* `createServerGroup` task dependent on the A task, and C dependent on B,
* while preserving the unstaggered behavior of an orca task per region.
*/
if (priorExecutionId != null) {
stages.add(dependsOn(priorExecutionId))
refId++
}
val stage = (diff.createServerGroupJob(refId) + resource.spec.deployWith.toOrcaJobProperties())
.toMutableMap()
refId++
/**
* If regions are staggered by time windows, add a `restrictedExecutionWindow`
* to the `createServerGroup` stage.
*/
if (stagger.hours != null) {
val hours = stagger.hours!!.split("-").map { it.toInt() }
stage.putAll(restrictedExecutionWindow(hours[0], hours[1]))
}
stages.add(stage)
if (diff.shouldDeployAndModifyScalingPolicies()) {
stages.addAll(diff.modifyScalingPolicyJob(refId))
}
if (stagger.pauseTime != null) {
stages.add(
waitStage(stagger.pauseTime!!, stages.size))
}
val deferred = async {
taskLauncher.submitJob(
resource = resource,
description = "Deploy $version to server group ${diff.desired.moniker} in " +
"${diff.desired.location.account}/${diff.desired.location.region}",
correlationId = "${resource.id}:${diff.desired.location.region}",
stages = stages
)
}
publisher.publishEvent(ArtifactVersionDeploying(
resourceId = resource.id,
artifactVersion = version
))
val task = deferred.await()
priorExecutionId = task.id
tasks.add(task)
}
/**
* `ClusterSpec.stagger` doesn't have to define a stagger for all of the regions clusters.
* If a cluster deploys into 4 regions [A, B, C, D] but only defines a stagger for [A, B],
* [C, D] will deploy in parallel after the completion of B and any pauseTime it defines.
*/
if (unstaggeredRegions.isNotEmpty()) {
val unstaggeredDiffs = regionalDiffs
.filter { unstaggeredRegions.contains(it.key) }
.map { it.value }
tasks.addAll(
upsertUnstaggered(resource, unstaggeredDiffs, version, priorExecutionId)
.map { it.await() }
)
}
return@coroutineScope tasks
}
override suspend fun export(exportable: Exportable): ClusterSpec {
// Get existing infrastructure
val serverGroups = cloudDriverService.getServerGroups(
account = exportable.account,
moniker = exportable.moniker,
regions = exportable.regions,
serviceAccount = exportable.user
)
.byRegion()
if (serverGroups.isEmpty()) {
throw ResourceNotFound("Could not find cluster: ${exportable.moniker} " +
"in account: ${exportable.account} for export")
}
val zonesByRegion = serverGroups.map { (region, serverGroup) ->
region to cloudDriverCache.availabilityZonesBy(
account = exportable.account,
vpcId = cloudDriverCache.subnetBy(exportable.account, region, serverGroup.location.subnet).vpcId,
purpose = serverGroup.location.subnet,
region = region
)
}
.toMap()
val subnetAwareRegionSpecs = serverGroups.map { (region, serverGroup) ->
SubnetAwareRegionSpec(
name = region,
availabilityZones =
if (!serverGroup.location.availabilityZones.containsAll(zonesByRegion[region]
?: error("Failed resolving availabilityZones for account: ${exportable.account}, region: $region"))) {
serverGroup.location.availabilityZones
} else {
emptySet()
}
)
}
.toSet()
// let's assume that the largest server group is the most important and should be the base
val base = serverGroups.values.maxBy { it.capacity.desired ?: it.capacity.max }
?: throw ExportError("Unable to calculate the server group with the largest capacity from server groups $serverGroups")
// Construct the minimal locations object
val locations = SubnetAwareLocations(
account = exportable.account,
subnet = base.location.subnet,
vpc = base.location.vpc,
regions = subnetAwareRegionSpecs
).withDefaultsOmitted()
val deployStrategy = clusterExportHelper.discoverDeploymentStrategy(
cloudProvider = "aws",
account = exportable.account,
application = exportable.moniker.app,
serverGroupName = base.name
) ?: RedBlack()
val appversion = AppVersion.parseName(base.image?.appVersion).packageName
val spec = ClusterSpec(
moniker = exportable.moniker,
imageProvider = if (appversion != null) {
ReferenceArtifactImageProvider(reference = appversion)
} else {
null
},
locations = locations,
deployWith = deployStrategy.withDefaultsOmitted(),
_defaults = base.exportSpec(exportable.account, exportable.moniker.app),
overrides = mutableMapOf()
)
spec.generateOverrides(
exportable.account,
exportable.moniker.app,
serverGroups
.filter { it.value.location.region != base.location.region }
)
return spec
}
override suspend fun exportArtifact(exportable: Exportable): DeliveryArtifact {
val serverGroups = cloudDriverService.getServerGroups(
account = exportable.account,
moniker = exportable.moniker,
regions = exportable.regions,
serviceAccount = exportable.user
)
.byRegion()
if (serverGroups.isEmpty()) {
throw ResourceNotFound("Could not find cluster: ${exportable.moniker} " +
"in account: ${exportable.account} for export")
}
val base = serverGroups.values.maxBy { it.capacity.desired ?: it.capacity.max }
?: throw ExportError("Unable to determine largest server group: $serverGroups")
if (base.image == null) {
throw ExportError("Server group ${base.name} doesn't have image information - unable to correctly export artifact.")
}
val artifactName = AppVersion.parseName(base.launchConfiguration.appVersion).packageName
val status = debianArtifactParser.parseStatus(base.launchConfiguration.appVersion?.substringAfter("$artifactName-"))
if (status == UNKNOWN) {
throw ExportError("Unable to determine release status from appVersion ${base.launchConfiguration.appVersion}, you'll have to configure this artifact manually.")
}
return DebianArtifact(
name = artifactName,
vmOptions = VirtualMachineOptions(regions = serverGroups.keys, baseOs = guessBaseOsFrom(base.image)),
statuses = setOf(status)
)
}
/**
* This function attempts to use image description to guess what OS the image is.
* If not found, it will throw an error.
*/
fun guessBaseOsFrom(image: ActiveServerGroupImage?): String =
parseBaseOsFrom(image?.description)
?: throw ExportError("Unable to determine the base image from image description: $image")
/**
* Parses the base os from the start of the ancestor name of a description like:
* "name=fiat, arch=x86_64, ancestor_name=bionic-classicbase-x86_64-202005072313-ebs,
* ancestor_id=ami-1111, ancestor_version=nflx-base-5.540.0-h1708.eeeeeee"
*/
private fun parseBaseOsFrom(description: String?): String? {
if (description == null) {
return null
}
val info: List<String> = description.split(",").map { it.trim() }
val ancestor = info.firstOrNull { it.startsWith("ancestor_name") } ?: return null
val ancestorValue = ancestor.split("=")[1]
return ancestorValue.substringBefore("base-x")
}
override suspend fun actuationInProgress(resource: Resource<ClusterSpec>) =
resource
.spec
.locations
.regions
.map { it.name }
.any { region ->
orcaService
.getCorrelatedExecutions("${resource.id}:$region")
.isNotEmpty()
}
private fun ClusterSpec.generateOverrides(account: String, application: String, serverGroups: Map<String, ServerGroup>) =
serverGroups.forEach { (region, serverGroup) ->
val workingSpec = serverGroup.exportSpec(account, application)
val override: ServerGroupSpec? = buildSpecFromDiff(
defaults,
workingSpec,
OVERRIDABLE_SERVER_GROUP_PROPERTIES
)
if (override != null) {
(overrides as MutableMap)[region] = override
}
}
/**
* @return `true` if the only changes in the diff are to capacity.
*/
private fun ResourceDiff<ServerGroup>.isCapacityOnly(): Boolean =
current != null && affectedRootPropertyTypes.all { it == Capacity::class.java }
/**
* @return `true` if the only changes in the diff are to scaling.
*/
private fun ResourceDiff<ServerGroup>.isAutoScalingOnly(): Boolean =
current != null &&
affectedRootPropertyTypes.any { it == Scaling::class.java } &&
affectedRootPropertyTypes.all { it == Capacity::class.java || it == Scaling::class.java } &&
current!!.scaling.suspendedProcesses == desired.scaling.suspendedProcesses &&
current!!.capacity.min == desired.capacity.min &&
current!!.capacity.max == desired.capacity.max
/**
* @return `true` if [current] doesn't exist and desired includes a scaling policy.
*/
private fun ResourceDiff<ServerGroup>.shouldDeployAndModifyScalingPolicies(): Boolean =
(current == null && desired.scaling.hasScalingPolicies()) ||
(current != null && !isCapacityOrAutoScalingOnly() && hasScalingPolicyDiff())
/**
* @return `true` if [current] exists and the diff impacts scaling policies or capacity only.
*/
private fun ResourceDiff<ServerGroup>.isCapacityOrAutoScalingOnly(): Boolean =
current != null &&
affectedRootPropertyTypes.all { it == Capacity::class.java || it == Scaling::class.java } &&
current!!.scaling.suspendedProcesses == desired.scaling.suspendedProcesses
/**
* @return `true` if [current] exists and the diff includes a scaling policy change.
*/
private fun ResourceDiff<ServerGroup>.hasScalingPolicyDiff(): Boolean =
current != null && affectedRootPropertyTypes.contains(Scaling::class.java) &&
(current!!.scaling.targetTrackingPolicies != desired.scaling.targetTrackingPolicies ||
current!!.scaling.stepScalingPolicies != desired.scaling.stepScalingPolicies)
private fun ResourceDiff<ServerGroup>.createServerGroupJob(startingRefId: Int = 0): Map<String, Any?> =
with(desired) {
mutableMapOf(
"application" to moniker.app,
"credentials" to location.account,
"refId" to (startingRefId + 1).toString(),
"requisiteStageRefIds" to when (startingRefId) {
0 -> emptyList()
else -> listOf(startingRefId.toString())
},
"capacity" to mapOf(
"min" to capacity.min,
"max" to capacity.max,
"desired" to capacity.desired
),
"targetHealthyDeployPercentage" to 100, // TODO: any reason to do otherwise?
"cooldown" to health.cooldown.seconds,
"enabledMetrics" to health.enabledMetrics,
"healthCheckType" to health.healthCheckType.name,
"healthCheckGracePeriod" to health.warmup.seconds,
"instanceMonitoring" to launchConfiguration.instanceMonitoring,
"ebsOptimized" to launchConfiguration.ebsOptimized,
"iamRole" to launchConfiguration.iamRole,
"terminationPolicies" to health.terminationPolicies.map(TerminationPolicy::name),
"subnetType" to location.subnet,
"availabilityZones" to mapOf(
location.region to location.availabilityZones
),
"keyPair" to launchConfiguration.keyPair,
"suspendedProcesses" to scaling.suspendedProcesses,
"securityGroups" to securityGroupIds,
"stack" to moniker.stack,
"freeFormDetails" to moniker.detail,
"tags" to tags,
"useAmiBlockDeviceMappings" to false, // TODO: any reason to do otherwise?
"copySourceCustomBlockDeviceMappings" to false, // TODO: any reason to do otherwise?
"virtualizationType" to "hvm", // TODO: any reason to do otherwise?
"moniker" to moniker.orcaClusterMoniker,
"amiName" to launchConfiguration.imageId,
"reason" to "Diff detected at ${clock.instant().iso()}",
"instanceType" to launchConfiguration.instanceType,
"type" to "createServerGroup",
"cloudProvider" to CLOUD_PROVIDER,
"loadBalancers" to dependencies.loadBalancerNames,
"targetGroups" to dependencies.targetGroups,
"account" to location.account
)
}
.also { job ->
current?.apply {
job["source"] = mapOf(
"account" to location.account,
"region" to location.region,
"asgName" to moniker.serverGroup
)
job["copySourceCustomBlockDeviceMappings"] = true
}
}
private fun ResourceDiff<ServerGroup>.resizeServerGroupJob(): Map<String, Any?> {
val current = requireNotNull(current) {
"Current server group must not be null when generating a resize job"
}
return mapOf(
"refId" to "1",
"type" to "resizeServerGroup",
"capacity" to mapOf(
"min" to desired.capacity.min,
"max" to desired.capacity.max,
"desired" to desired.capacity.desired
),
"cloudProvider" to CLOUD_PROVIDER,
"credentials" to desired.location.account,
"moniker" to current.moniker.orcaClusterMoniker,
"region" to current.location.region,
"serverGroupName" to current.name
)
}
/**
* @return list of stages to remove or create scaling policies in-place on the
* current serverGroup.
*
* Scaling policies are treated as immutable by keel once applied. If an existing
* policy is modified, it will be deleted and reapplied via a single task.
*/
private fun ResourceDiff<ServerGroup>.modifyScalingPolicyJob(startingRefId: Int = 0): List<Map<String, Any?>> {
var (refId, stages) = toDeletePolicyJob(startingRefId)
val newTargetPolicies = when (current) {
null -> desired.scaling.targetTrackingPolicies
else -> desired.scaling.targetTrackingPolicies
.subtract(current!!.scaling.targetTrackingPolicies)
}
val newStepPolicies = when (current) {
null -> desired.scaling.stepScalingPolicies
else -> desired.scaling.stepScalingPolicies
.subtract(current!!.scaling.stepScalingPolicies)
}
if (newTargetPolicies.isNotEmpty()) {
val (newRef, jobs) = newTargetPolicies.toCreateJob(refId, current ?: desired)
refId = newRef
stages.addAll(jobs)
}
if (newStepPolicies.isNotEmpty()) {
stages.addAll(newStepPolicies.toCreateJob(refId, current ?: desired))
}
return stages
}
private fun ResourceDiff<ServerGroup>.toDeletePolicyJob(startingRefId: Int):
Pair<Int, MutableList<Map<String, Any?>>> {
var refId = startingRefId
val stages: MutableList<Map<String, Any?>> = mutableListOf()
if (current == null) {
return Pair(refId, stages)
}
val current = current!!
val targetPoliciesToRemove = current.scaling.targetTrackingPolicies.filterNot {
desired.scaling.targetTrackingPolicies.contains(it)
}
val stepPoliciesToRemove = current.scaling.stepScalingPolicies.filterNot {
desired.scaling.stepScalingPolicies.contains(it)
}
val policyNamesToRemove = targetPoliciesToRemove.mapNotNull { it.name } +
stepPoliciesToRemove.mapNotNull { it.name }
.toSet()
stages.addAll(
policyNamesToRemove
.map {
refId++
mapOf(
"refId" to refId.toString(),
"requisiteStageRefIds" to when (refId) {
0, 1 -> listOf()
else -> listOf((refId - 1).toString())
},
"type" to "deleteScalingPolicy",
"policyName" to it,
"cloudProvider" to CLOUD_PROVIDER,
"credentials" to desired.location.account,
"moniker" to current.moniker.orcaClusterMoniker,
"region" to current.location.region
)
}
.toMutableList()
)
return Pair(refId, stages)
}
private fun Set<TargetTrackingPolicy>.toCreateJob(startingRefId: Int, serverGroup: ServerGroup):
Pair<Int, List<Map<String, Any?>>> {
var refId = startingRefId
val stages = map {
refId++
mapOf(
"refId" to refId.toString(),
"requisiteStageRefIds" to when (refId) {
0, 1 -> listOf()
else -> listOf((refId - 1).toString())
},
"type" to "upsertScalingPolicy",
"cloudProvider" to CLOUD_PROVIDER,
"credentials" to serverGroup.location.account,
"moniker" to serverGroup.moniker.orcaClusterMoniker,
"region" to serverGroup.location.region,
"estimatedInstanceWarmup" to it.warmup.seconds,
"targetTrackingConfiguration" to mapOf(
"targetValue" to it.targetValue,
"disableScaleIn" to it.disableScaleIn,
"predefinedMetricSpecification" to when (val metricsSpec = it.predefinedMetricSpec) {
null -> null
else -> with(metricsSpec) {
PredefinedMetricSpecificationModel(
predefinedMetricType = type,
resourceLabel = label
)
}
},
"customizedMetricSpecification" to when (val metricsSpec = it.customMetricSpec) {
null -> null
else -> with(metricsSpec) {
CustomizedMetricSpecificationModel(
metricName = name,
namespace = namespace,
statistic = statistic,
unit = unit,
dimensions = dimensions?.map { d ->
MetricDimensionModel(name = d.name, value = d.value)
}
)
}
}
)
)
}
return Pair(refId, stages)
}
private fun Set<StepScalingPolicy>.toCreateJob(startingRefId: Int, serverGroup: ServerGroup):
List<Map<String, Any?>> {
var refId = startingRefId
return map {
refId++
mapOf(
"refId" to refId.toString(),
"requisiteStageRefIds" to when (refId) {
0, 1 -> listOf()
else -> listOf((refId - 1).toString())
},
"type" to "upsertScalingPolicy",
"cloudProvider" to CLOUD_PROVIDER,
"credentials" to serverGroup.location.account,
"moniker" to serverGroup.moniker.orcaClusterMoniker,
"region" to serverGroup.location.region,
"adjustmentType" to it.adjustmentType,
"alarm" to mapOf(
"region" to serverGroup.location.region,
"actionsEnabled" to it.actionsEnabled,
"comparisonOperator" to it.comparisonOperator,
"dimensions" to it.dimensions,
"evaluationPeriods" to it.evaluationPeriods,
"period" to it.period.seconds,
"threshold" to it.threshold,
"namespace" to it.namespace,
"metricName" to it.metricName,
"statistic" to it.statistic
),
"step" to mapOf(
"estimatedInstanceWarmup" to it.warmup.seconds,
"metricAggregationType" to it.metricAggregationType,
"stepAdjustments" to it.stepAdjustments.map { adjustment ->
StepAdjustmentModel(
metricIntervalLowerBound = adjustment.lowerBound,
metricIntervalUpperBound = adjustment.upperBound,
scalingAdjustment = adjustment.scalingAdjustment
)
}
)
)
}
}
private suspend fun CloudDriverService.getServerGroups(resource: Resource<ClusterSpec>): Iterable<ServerGroup> =
getServerGroups(
account = resource.spec.locations.account,
moniker = resource.spec.moniker,
regions = resource.spec.locations.regions.map { it.name }.toSet(),
serviceAccount = resource.serviceAccount
)
.also { them ->
val allSame: Boolean = them.distinctBy { it.launchConfiguration.appVersion }.size == 1
val healthy: Boolean = them.all { it.instanceCounts?.isHealthy() == true }
if (allSame && healthy) {
// // only publish a successfully deployed event if the server group is healthy
val appVersion = them.first().launchConfiguration.appVersion
if (appVersion != null) {
publisher.publishEvent(ArtifactVersionDeployed(
resourceId = resource.id,
artifactVersion = appVersion
))
}
}
}
private suspend fun CloudDriverService.getServerGroups(
account: String,
moniker: Moniker,
regions: Set<String>,
serviceAccount: String
): Iterable<ServerGroup> =
coroutineScope {
regions.map {
async {
try {
activeServerGroup(
user = serviceAccount,
app = moniker.app,
account = account,
cluster = moniker.toString(),
region = it,
cloudProvider = CLOUD_PROVIDER
)
.toServerGroup()
} catch (e: HttpException) {
if (!e.isNotFound) {
throw e
}
null
}
}
}
.mapNotNull { it.await() }
}
/**
* Transforms CloudDriver response to our server group model.
*/
private fun ActiveServerGroup.toServerGroup() =
ServerGroup(
name = name,
location = Location(
account = accountName,
region = region,
vpc = cloudDriverCache.networkBy(vpcId).name ?: error("VPC with id $vpcId has no name!"),
subnet = subnet(cloudDriverCache),
availabilityZones = zones
),
launchConfiguration = launchConfig.run {
LaunchConfiguration(
imageId = imageId,
appVersion = image.appVersion,
baseImageVersion = image.baseImageVersion,
instanceType = instanceType,
ebsOptimized = ebsOptimized,
iamRole = iamInstanceProfile,
keyPair = keyName,
instanceMonitoring = instanceMonitoring.enabled,
ramdiskId = ramdiskId.orNull()
)
},
buildInfo = buildInfo?.toEc2Api(),
capacity = capacity.let {
when (scalingPolicies.isEmpty()) {
true -> Capacity(it.min, it.max, it.desired)
false -> Capacity(it.min, it.max)
}
},
dependencies = ClusterDependencies(
loadBalancerNames = loadBalancers,
securityGroupNames = securityGroupNames,
targetGroups = targetGroups
),
health = Health(
enabledMetrics = asg.enabledMetrics.map { Metric.valueOf(it) }.toSet(),
cooldown = asg.defaultCooldown.let(Duration::ofSeconds),
warmup = asg.healthCheckGracePeriod.let(Duration::ofSeconds),
healthCheckType = asg.healthCheckType.let { HealthCheckType.valueOf(it) },
terminationPolicies = asg.terminationPolicies.map { TerminationPolicy.valueOf(it) }.toSet()
),
scaling = Scaling(
suspendedProcesses = asg.suspendedProcesses.map { ScalingProcess.valueOf(it.processName) }.toSet(),
targetTrackingPolicies = scalingPolicies.toTargetTrackingPolicies(),
stepScalingPolicies = scalingPolicies.toStepScalingPolicies()
),
tags = asg.tags.associateBy(Tag::key, Tag::value).filterNot { it.key in DEFAULT_TAGS },
image = image.toEc2Api(),
instanceCounts = instanceCounts.toEc2Api()
)
private fun List<MetricDimensionModel>?.toSpec(): Set<MetricDimension> =
when (this) {
null -> emptySet()
else -> this.filter { it.name != "AutoScalingGroupName" }
.map { MetricDimension(it.name, it.value) }
.toSet()
}
private fun CustomizedMetricSpecificationModel?.toSpec() =
when (this) {
null -> null
else -> CustomizedMetricSpecification(
name = metricName,
namespace = namespace,
statistic = statistic,
unit = unit,
dimensions = dimensions.toSpec()
)
}
private fun PredefinedMetricSpecificationModel?.toSpec() =
when (this) {
null -> null
else -> PredefinedMetricSpecification(
type = predefinedMetricType,
label = resourceLabel
)
}
private fun List<StepAdjustmentModel>?.toSteps() =
when (this) {
null -> emptySet()
else -> map {
StepAdjustment(
scalingAdjustment = it.scalingAdjustment,
lowerBound = it.metricIntervalLowerBound,
upperBound = it.metricIntervalUpperBound
)
}
.toSet()
}
private fun List<ScalingPolicy>.toTargetTrackingPolicies(): Set<TargetTrackingPolicy> =
filter { it.targetTrackingConfiguration != null }
.map {
TargetTrackingPolicy(
name = it.policyName,
warmup = Duration.ofSeconds(it.estimatedInstanceWarmup.toLong()),
targetValue = it.targetTrackingConfiguration!!.targetValue,
disableScaleIn = it.targetTrackingConfiguration!!.disableScaleIn,
predefinedMetricSpec = it.targetTrackingConfiguration!!.predefinedMetricSpecification.toSpec(),
customMetricSpec = it.targetTrackingConfiguration!!.customizedMetricSpecification.toSpec()
)
}
.toSet()
private fun List<ScalingPolicy>.toStepScalingPolicies(): Set<StepScalingPolicy> =
filter { it.targetTrackingConfiguration == null && it.adjustmentType != null }
.map {
val alarm = it.alarms.first()
StepScalingPolicy(
name = it.policyName,
adjustmentType = it.adjustmentType!!,
actionsEnabled = alarm.actionsEnabled,
comparisonOperator = alarm.comparisonOperator,
dimensions = alarm.dimensions.toSpec(),
evaluationPeriods = alarm.evaluationPeriods,
period = Duration.ofSeconds(alarm.period.toLong()),
threshold = alarm.threshold,
metricName = alarm.metricName,
namespace = alarm.namespace,
statistic = alarm.statistic,
warmup = Duration.ofSeconds(it.estimatedInstanceWarmup.toLong()),
metricAggregationType = it.metricAggregationType!!,
stepAdjustments = it.stepAdjustments.toSteps()
)
}
.toSet()
private val ServerGroup.moniker: Moniker
get() = parseMoniker(name)
private val ServerGroup.securityGroupIds: Collection<String>
get() = dependencies
.securityGroupNames
// no need to specify these as Orca will auto-assign them, also the application security group
// gets auto-created so may not exist yet
.filter { it !in setOf("nf-infrastructure", "nf-datacenter", moniker.app) }
.map {
cloudDriverCache.securityGroupByName(location.account, location.region, it).id
}
private val ActiveServerGroup.securityGroupNames: Set<String>
get() = securityGroups.map {
cloudDriverCache.securityGroupById(accountName, region, it).name
}
.toSet()
private fun Instant.iso() =
atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_DATE_TIME)
/**
* Translates a ServerGroup object to a ClusterSpec.ServerGroupSpec with default values omitted for export.
*/
private fun ServerGroup.exportSpec(account: String, application: String): ServerGroupSpec {
val defaults = ServerGroupSpec(
capacity = Capacity(1, 1, 1),
dependencies = ClusterDependencies(),
health = Health().toSpecWithoutDefaults(),
scaling = Scaling(),
tags = emptyMap()
)
val thisSpec = ServerGroupSpec(