-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
spotinst.go
1162 lines (985 loc) · 33.9 KB
/
spotinst.go
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
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package awsmodel
import (
"fmt"
"strconv"
"strings"
corev1 "k8s.io/api/core/v1"
"k8s.io/klog/v2"
"k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/featureflag"
"k8s.io/kops/pkg/model"
"k8s.io/kops/pkg/model/defaults"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/awstasks"
"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
"k8s.io/kops/upup/pkg/fi/cloudup/spotinsttasks"
)
const (
// SpotInstanceGroupLabelHybrid is the metadata label used on the instance group
// to specify that the Spotinst provider should be used to upon creation.
SpotInstanceGroupLabelHybrid = "spotinst.io/hybrid"
SpotInstanceGroupLabelManaged = "spotinst.io/managed" // for backward compatibility
// SpotInstanceGroupLabelSpotPercentage is the metadata label used on the
// instance group to specify the percentage of Spot instances that
// should spin up from the target capacity.
SpotInstanceGroupLabelSpotPercentage = "spotinst.io/spot-percentage"
// SpotInstanceGroupLabelOrientation is the metadata label used on the
// instance group to specify which orientation should be used.
SpotInstanceGroupLabelOrientation = "spotinst.io/orientation"
// SpotInstanceGroupLabelUtilizeReservedInstances is the metadata label used
// on the instance group to specify whether reserved instances should be
// utilized.
SpotInstanceGroupLabelUtilizeReservedInstances = "spotinst.io/utilize-reserved-instances"
// SpotInstanceGroupLabelUtilizeCommitments is the metadata label used
// on the instance group to specify whether commitments should be utilized.
SpotInstanceGroupLabelUtilizeCommitments = "spotinst.io/utilize-commitments"
// SpotInstanceGroupLabelFallbackToOnDemand is the metadata label used on the
// instance group to specify whether fallback to on-demand instances should
// be enabled.
SpotInstanceGroupLabelFallbackToOnDemand = "spotinst.io/fallback-to-ondemand"
// SpotInstanceGroupLabelDrainingTimeout is the metadata label used on the
// instance group to specify a period of time, in seconds, after a node
// is marked for termination during which on running pods remains active.
SpotInstanceGroupLabelDrainingTimeout = "spotinst.io/draining-timeout"
// SpotInstanceGroupLabelGracePeriod is the metadata label used on the
// instance group to specify a period of time, in seconds, that Ocean
// should wait before applying instance health checks.
SpotInstanceGroupLabelGracePeriod = "spotinst.io/grace-period"
// SpotInstanceGroupLabelHealthCheckType is the metadata label used on the
// instance group to specify the type of the health check that should be used.
SpotInstanceGroupLabelHealthCheckType = "spotinst.io/health-check-type"
// SpotInstanceGroupLabelOceanDefaultLaunchSpec is the metadata label used on the
// instance group to specify whether to use the SpotInstanceGroup's spec as the default
// Launch Spec for the Ocean cluster.
SpotInstanceGroupLabelOceanDefaultLaunchSpec = "spotinst.io/ocean-default-launchspec"
// SpotInstanceGroupLabelOceanInstanceTypes[White|Black]list are the metadata labels
// used on the instance group to specify whether to whitelist or blacklist
// specific instance types.
SpotInstanceGroupLabelOceanInstanceTypesWhitelist = "spotinst.io/ocean-instance-types-whitelist"
SpotInstanceGroupLabelOceanInstanceTypesBlacklist = "spotinst.io/ocean-instance-types-blacklist"
SpotInstanceGroupLabelOceanInstanceTypes = "spotinst.io/ocean-instance-types" // launchspec
// SpotInstanceGroupLabelAutoScalerDisabled is the metadata label used on the
// instance group to specify whether the auto scaler should be enabled.
SpotInstanceGroupLabelAutoScalerDisabled = "spotinst.io/autoscaler-disabled"
// SpotInstanceGroupLabelAutoScalerDefaultNodeLabels is the metadata label used on the
// instance group to specify whether default node labels should be set for
// the auto scaler.
SpotInstanceGroupLabelAutoScalerDefaultNodeLabels = "spotinst.io/autoscaler-default-node-labels"
// SpotInstanceGroupLabelAutoScalerAuto* are the metadata labels used on the
// instance group to specify whether headroom resources should be
// automatically configured and optimized.
SpotInstanceGroupLabelAutoScalerAutoConfig = "spotinst.io/autoscaler-auto-config"
SpotInstanceGroupLabelAutoScalerAutoHeadroomPercentage = "spotinst.io/autoscaler-auto-headroom-percentage"
// SpotInstanceGroupLabelAutoScalerHeadroom* are the metadata labels used on the
// instance group to specify the headroom configuration used by the auto scaler.
SpotInstanceGroupLabelAutoScalerHeadroomCPUPerUnit = "spotinst.io/autoscaler-headroom-cpu-per-unit"
SpotInstanceGroupLabelAutoScalerHeadroomGPUPerUnit = "spotinst.io/autoscaler-headroom-gpu-per-unit"
SpotInstanceGroupLabelAutoScalerHeadroomMemPerUnit = "spotinst.io/autoscaler-headroom-mem-per-unit"
SpotInstanceGroupLabelAutoScalerHeadroomNumOfUnits = "spotinst.io/autoscaler-headroom-num-of-units"
// SpotInstanceGroupLabelAutoScalerCooldown is the metadata label used on the
// instance group to specify the cooldown period (in seconds) for scaling actions.
SpotInstanceGroupLabelAutoScalerCooldown = "spotinst.io/autoscaler-cooldown"
// SpotInstanceGroupLabelAutoScalerScaleDown* are the metadata labels used on the
// instance group to specify the scale down configuration used by the auto scaler.
SpotInstanceGroupLabelAutoScalerScaleDownMaxPercentage = "spotinst.io/autoscaler-scale-down-max-percentage"
SpotInstanceGroupLabelAutoScalerScaleDownEvaluationPeriods = "spotinst.io/autoscaler-scale-down-evaluation-periods"
// SpotInstanceGroupLabelAutoScalerResourceLimits* are the metadata labels used on the
// instance group to specify the resource limits configuration used by the auto scaler.
SpotInstanceGroupLabelAutoScalerResourceLimitsMaxVCPU = "spotinst.io/autoscaler-resource-limits-max-vcpu"
SpotInstanceGroupLabelAutoScalerResourceLimitsMaxMemory = "spotinst.io/autoscaler-resource-limits-max-memory"
// InstanceGroupLabelRestrictScaleDown is the metadata label used on the
// instance group to specify whether the scale-down activities should be restricted.
SpotInstanceGroupLabelRestrictScaleDown = "spotinst.io/restrict-scale-down"
// SpotClusterLabelSpreadNodesBy is the cloud label used on the
// cluster spec to specify how Ocean will spread the nodes across markets by this value
SpotClusterLabelSpreadNodesBy = "spotinst.io/strategy-cluster-spread-nodes-by"
// SpotClusterLabelStrategyClusterOrientationAvailabilityVsCost is the metadata label used on the
// instance group to specify how to optimize towards continuity and/or cost-effective infrastructure
SpotClusterLabelStrategyClusterOrientationAvailabilityVsCost = "spotinst.io/strategy-cluster-orientation-availability-vs-cost"
)
// SpotInstanceGroupModelBuilder configures SpotInstanceGroup objects
type SpotInstanceGroupModelBuilder struct {
*AWSModelContext
BootstrapScriptBuilder *model.BootstrapScriptBuilder
Lifecycle fi.Lifecycle
SecurityLifecycle fi.Lifecycle
}
var _ fi.CloudupModelBuilder = &SpotInstanceGroupModelBuilder{}
func (b *SpotInstanceGroupModelBuilder) Build(c *fi.CloudupModelBuilderContext) error {
var nodeSpotInstanceGroups []*kops.InstanceGroup
var err error
for _, ig := range b.InstanceGroups {
name := b.AutoscalingGroupName(ig)
if featureflag.SpotinstHybrid.Enabled() {
if !HybridInstanceGroup(ig) {
klog.V(2).Infof("Skipping instance group: %q", name)
continue
}
}
klog.V(2).Infof("Building instance group: %q", name)
switch ig.Spec.Role {
// Create both Master and Bastion instance groups as Elastigroups.
case kops.InstanceGroupRoleControlPlane, kops.InstanceGroupRoleBastion:
err = b.buildElastigroup(c, ig)
// Create Node instance groups as Elastigroups or a single Ocean with
// multiple LaunchSpecs.
case kops.InstanceGroupRoleNode:
if featureflag.SpotinstOcean.Enabled() {
nodeSpotInstanceGroups = append(nodeSpotInstanceGroups, ig)
} else {
err = b.buildElastigroup(c, ig)
}
default:
err = fmt.Errorf("spotinst: unexpected instance group role: %s", ig.Spec.Role)
}
if err != nil {
return fmt.Errorf("spotinst: error building elastigroup: %v", err)
}
}
if len(nodeSpotInstanceGroups) > 0 {
if err = b.buildOcean(c, nodeSpotInstanceGroups...); err != nil {
return fmt.Errorf("spotinst: error building ocean: %v", err)
}
}
return nil
}
func (b *SpotInstanceGroupModelBuilder) buildElastigroup(c *fi.CloudupModelBuilderContext, ig *kops.InstanceGroup) (err error) {
klog.V(4).Infof("Building instance group as Elastigroup: %q", b.AutoscalingGroupName(ig))
group := &spotinsttasks.Elastigroup{
Lifecycle: b.Lifecycle,
Name: fi.PtrTo(b.AutoscalingGroupName(ig)),
Region: fi.PtrTo(b.Region),
ImageID: fi.PtrTo(ig.Spec.Image),
OnDemandInstanceType: fi.PtrTo(strings.Split(ig.Spec.MachineType, ",")[0]),
SpotInstanceTypes: strings.Split(ig.Spec.MachineType, ","),
}
// Cloud config.
if aws := b.Cluster.Spec.CloudProvider.AWS; aws != nil {
group.Product = aws.SpotinstProduct
group.Orientation = aws.SpotinstOrientation
}
// Strategy.
for k, v := range ig.ObjectMeta.Labels {
switch k {
case SpotInstanceGroupLabelSpotPercentage:
group.SpotPercentage, err = parseFloat(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelOrientation:
group.Orientation = fi.PtrTo(v)
case SpotInstanceGroupLabelUtilizeReservedInstances:
group.UtilizeReservedInstances, err = parseBool(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelUtilizeCommitments:
group.UtilizeCommitments, err = parseBool(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelFallbackToOnDemand:
group.FallbackToOnDemand, err = parseBool(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelDrainingTimeout:
group.DrainingTimeout, err = parseInt(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelHealthCheckType:
group.HealthCheckType = fi.PtrTo(strings.ToUpper(v))
}
}
// Spot percentage.
if group.SpotPercentage == nil {
group.SpotPercentage = defaultSpotPercentage(ig)
}
// Instance profile.
group.IAMInstanceProfile, err = b.LinkToIAMInstanceProfile(ig)
if err != nil {
return fmt.Errorf("error building iam instance profile: %v", err)
}
// Root volume.
group.RootVolumeOpts, err = b.buildRootVolumeOpts(ig)
if err != nil {
return fmt.Errorf("error building root volume options: %v", err)
}
// Tenancy.
if ig.Spec.Tenancy != "" {
group.Tenancy = fi.PtrTo(ig.Spec.Tenancy)
}
// Security groups.
group.SecurityGroups, err = b.buildSecurityGroups(c, ig)
if err != nil {
return fmt.Errorf("error building security groups: %v", err)
}
// SSH key.
group.SSHKey, err = b.LinkToSSHKey()
if err != nil {
return fmt.Errorf("error building ssh key: %v", err)
}
// Load balancers.
group.LoadBalancers, group.TargetGroups, err = b.buildLoadBalancers(c, ig)
if err != nil {
return fmt.Errorf("error building load balancers: %v", err)
}
// User data.
group.UserData, err = b.BootstrapScriptBuilder.ResourceNodeUp(c, ig)
if err != nil {
return fmt.Errorf("error building user data: %v", err)
}
// Public IP.
group.AssociatePublicIPAddress, err = b.buildPublicIPOpts(ig)
if err != nil {
return fmt.Errorf("error building public ip options: %v", err)
}
// Subnets.
group.Subnets, err = b.buildSubnets(ig)
if err != nil {
return fmt.Errorf("error building subnets: %v", err)
}
// Capacity.
group.MinSize, group.MaxSize = b.buildCapacity(ig)
// Monitoring.
group.Monitoring = ig.Spec.DetailedInstanceMonitoring
// Tags.
group.Tags, err = b.buildTags(ig)
if err != nil {
return fmt.Errorf("error building cloud tags: %v", err)
}
// Auto Scaler.
group.AutoScalerOpts, err = b.buildAutoScalerOpts(b.ClusterName(), ig)
if err != nil {
return fmt.Errorf("error building auto scaler options: %v", err)
}
if group.AutoScalerOpts != nil { // remove unsupported options
group.AutoScalerOpts.Taints = nil
}
// Instance Metadata Options
group.InstanceMetadataOptions = b.buildInstanceMetadataOptions(ig)
klog.V(4).Infof("Adding task: Elastigroup/%s", fi.ValueOf(group.Name))
c.AddTask(group)
return nil
}
func (b *SpotInstanceGroupModelBuilder) buildOcean(c *fi.CloudupModelBuilderContext, igs ...*kops.InstanceGroup) (err error) {
klog.V(4).Infof("Building instance group as Ocean: %q", "nodes."+b.ClusterName())
ocean := &spotinsttasks.Ocean{
Lifecycle: b.Lifecycle,
Name: fi.PtrTo("nodes." + b.ClusterName()),
}
if featureflag.SpotinstOceanTemplate.Enabled() {
ocean.UseAsTemplateOnly = fi.PtrTo(true)
}
if len(igs) == 0 {
return nil
}
var ig *kops.InstanceGroup
for _, g := range igs {
for k, v := range g.ObjectMeta.Labels {
if k == SpotInstanceGroupLabelOceanDefaultLaunchSpec {
defaultLaunchSpec, err := parseBool(v)
if err != nil {
continue
}
if fi.ValueOf(defaultLaunchSpec) {
if ig != nil {
return fmt.Errorf("unable to detect default launch spec: "+
"multiple instance groups labeled with `%s: \"true\"`",
SpotInstanceGroupLabelOceanDefaultLaunchSpec)
}
ig = g.DeepCopy()
break
}
}
}
}
if ig == nil {
ig = igs[0].DeepCopy()
}
klog.V(4).Infof("Detected default launch spec: %q", b.AutoscalingGroupName(ig))
for k, v := range b.Cluster.Labels {
switch k {
case SpotClusterLabelSpreadNodesBy:
ocean.SpreadNodesBy = fi.PtrTo(v)
case SpotClusterLabelStrategyClusterOrientationAvailabilityVsCost:
ocean.AvailabilityVsCost = fi.PtrTo(string(spotinsttasks.NormalizeClusterOrientation(&v)))
}
}
// Image.
ocean.ImageID = fi.PtrTo(ig.Spec.Image)
// Strategy and instance types.
for k, v := range ig.ObjectMeta.Labels {
switch k {
case SpotInstanceGroupLabelUtilizeReservedInstances:
ocean.UtilizeReservedInstances, err = parseBool(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelUtilizeCommitments:
ocean.UtilizeCommitments, err = parseBool(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelFallbackToOnDemand:
ocean.FallbackToOnDemand, err = parseBool(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelGracePeriod:
ocean.GracePeriod, err = parseInt(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelDrainingTimeout:
ocean.DrainingTimeout, err = parseInt(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelOceanInstanceTypesWhitelist:
ocean.InstanceTypesWhitelist, err = parseStringSlice(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelOceanInstanceTypesBlacklist:
ocean.InstanceTypesBlacklist, err = parseStringSlice(v)
if err != nil {
return err
}
}
}
// Monitoring.
ocean.Monitoring = ig.Spec.DetailedInstanceMonitoring
// Security groups.
ocean.SecurityGroups, err = b.buildSecurityGroups(c, ig)
if err != nil {
return fmt.Errorf("error building security groups: %v", err)
}
// SSH key.
ocean.SSHKey, err = b.LinkToSSHKey()
if err != nil {
return fmt.Errorf("error building ssh key: %v", err)
}
// Subnets.
ocean.Subnets, err = b.buildSubnets(ig)
if err != nil {
return fmt.Errorf("error building subnets: %v", err)
}
// Auto Scaler.
ocean.AutoScalerOpts, err = b.buildAutoScalerOpts(b.ClusterName(), ig)
if err != nil {
return fmt.Errorf("error building auto scaler options: %v", err)
}
if ocean.AutoScalerOpts != nil { // remove unsupported options
ocean.AutoScalerOpts.Labels = nil
ocean.AutoScalerOpts.Taints = nil
ocean.AutoScalerOpts.Headroom = nil
}
// Instance Metadata Options
ocean.InstanceMetadataOptions = b.buildInstanceMetadataOptions(ig)
if !fi.ValueOf(ocean.UseAsTemplateOnly) {
// Capacity.
ocean.MinSize = fi.PtrTo(int64(0))
ocean.MaxSize = fi.PtrTo(int64(0))
// User data.
ocean.UserData, err = b.BootstrapScriptBuilder.ResourceNodeUp(c, ig)
if err != nil {
return fmt.Errorf("error building user data: %v", err)
}
// Instance profile.
ocean.IAMInstanceProfile, err = b.LinkToIAMInstanceProfile(ig)
if err != nil {
return fmt.Errorf("error building iam instance profile: %v", err)
}
// Root volume.
rootVolumeOpts, err := b.buildRootVolumeOpts(ig)
if err != nil {
return fmt.Errorf("error building root volume options: %v", err)
}
if rootVolumeOpts != nil {
ocean.RootVolumeOpts = rootVolumeOpts
ocean.RootVolumeOpts.Type = nil // not supported in Ocean
}
// Public IP.
ocean.AssociatePublicIPAddress, err = b.buildPublicIPOpts(ig)
if err != nil {
return fmt.Errorf("error building public ip options: %v", err)
}
// Tags.
ocean.Tags, err = b.buildTags(ig)
if err != nil {
return fmt.Errorf("error building cloud tags: %v", err)
}
}
// Create a Launch Spec for each instance group.
for _, g := range igs {
if err := b.buildLaunchSpec(c, g, ig, ocean); err != nil {
return fmt.Errorf("error building launch spec: %v", err)
}
}
klog.V(4).Infof("Adding task: Ocean/%s", fi.ValueOf(ocean.Name))
c.AddTask(ocean)
return nil
}
func (b *SpotInstanceGroupModelBuilder) buildLaunchSpec(c *fi.CloudupModelBuilderContext,
ig, igOcean *kops.InstanceGroup, ocean *spotinsttasks.Ocean) (err error) {
klog.V(4).Infof("Building instance group as LaunchSpec: %q", b.AutoscalingGroupName(ig))
launchSpec := &spotinsttasks.LaunchSpec{
Name: fi.PtrTo(b.AutoscalingGroupName(ig)),
Lifecycle: b.Lifecycle,
ImageID: fi.PtrTo(ig.Spec.Image),
Ocean: ocean, // link to Ocean
}
// Instance types and strategy.
for k, v := range ig.ObjectMeta.Labels {
switch k {
case SpotInstanceGroupLabelOceanInstanceTypesWhitelist, SpotInstanceGroupLabelOceanInstanceTypes:
launchSpec.InstanceTypes, err = parseStringSlice(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelSpotPercentage:
launchSpec.SpotPercentage, err = parseInt(v)
if err != nil {
return err
}
case SpotInstanceGroupLabelRestrictScaleDown:
launchSpec.RestrictScaleDown, err = parseBool(v)
if err != nil {
return err
}
}
}
policy := ig.Spec.MixedInstancesPolicy
if len(launchSpec.InstanceTypes) == 0 && policy != nil && len(policy.Instances) > 0 {
launchSpec.InstanceTypes = policy.Instances
}
// Capacity.
minSize, maxSize := b.buildCapacity(ig)
if !fi.ValueOf(ocean.UseAsTemplateOnly) {
ocean.MinSize = fi.PtrTo(fi.ValueOf(ocean.MinSize) + fi.ValueOf(minSize))
ocean.MaxSize = fi.PtrTo(fi.ValueOf(ocean.MaxSize) + fi.ValueOf(maxSize))
}
launchSpec.MinSize = minSize
launchSpec.MaxSize = maxSize
// User data.
if ig.Name == igOcean.Name && !featureflag.SpotinstOceanTemplate.Enabled() {
launchSpec.UserData = ocean.UserData
} else {
launchSpec.UserData, err = b.BootstrapScriptBuilder.ResourceNodeUp(c, ig)
if err != nil {
return fmt.Errorf("error building user data: %v", err)
}
}
// Instance profile.
launchSpec.IAMInstanceProfile, err = b.LinkToIAMInstanceProfile(ig)
if err != nil {
return fmt.Errorf("error building iam instance profile: %v", err)
}
// Root volume.
rootVolumeOpts, err := b.buildRootVolumeOpts(ig)
if err != nil {
return fmt.Errorf("error building root volume options: %v", err)
}
if rootVolumeOpts != nil { // remove unsupported options
launchSpec.RootVolumeOpts = rootVolumeOpts
launchSpec.RootVolumeOpts.Optimization = nil
}
// Public IP.
launchSpec.AssociatePublicIPAddress, err = b.buildPublicIPOpts(ig)
if err != nil {
return fmt.Errorf("error building public ip options: %v", err)
}
// Security groups.
launchSpec.SecurityGroups, err = b.buildSecurityGroups(c, ig)
if err != nil {
return fmt.Errorf("error building security groups: %v", err)
}
// Subnets.
launchSpec.Subnets, err = b.buildSubnets(ig)
if err != nil {
return fmt.Errorf("error building subnets: %v", err)
}
// Tags.
launchSpec.Tags, err = b.buildTags(ig)
if err != nil {
return fmt.Errorf("error building cloud tags: %v", err)
}
// Auto Scaler.
autoScalerOpts, err := b.buildAutoScalerOpts(b.ClusterName(), ig)
if err != nil {
return fmt.Errorf("error building auto scaler options: %v", err)
}
if autoScalerOpts != nil { // remove unsupported options
autoScalerOpts.Enabled = nil
autoScalerOpts.AutoConfig = nil
autoScalerOpts.AutoHeadroomPercentage = nil
autoScalerOpts.ClusterID = nil
autoScalerOpts.Cooldown = nil
autoScalerOpts.Down = nil
if autoScalerOpts.Labels != nil || autoScalerOpts.Taints != nil || autoScalerOpts.Headroom != nil {
launchSpec.AutoScalerOpts = autoScalerOpts
}
}
// Instance Metadata Options
launchSpec.InstanceMetadataOptions = b.buildInstanceMetadataOptions(ig)
klog.V(4).Infof("Adding task: LaunchSpec/%s", fi.ValueOf(launchSpec.Name))
c.AddTask(launchSpec)
return nil
}
func (b *SpotInstanceGroupModelBuilder) buildSecurityGroups(c *fi.CloudupModelBuilderContext,
ig *kops.InstanceGroup) ([]*awstasks.SecurityGroup, error) {
securityGroups := []*awstasks.SecurityGroup{
b.LinkToSecurityGroup(ig.Spec.Role),
}
for _, id := range ig.Spec.AdditionalSecurityGroups {
sg := &awstasks.SecurityGroup{
Lifecycle: b.SecurityLifecycle,
ID: fi.PtrTo(id),
Name: fi.PtrTo(id),
Shared: fi.PtrTo(true),
}
c.EnsureTask(sg)
securityGroups = append(securityGroups, sg)
}
return securityGroups, nil
}
func (b *SpotInstanceGroupModelBuilder) buildSubnets(ig *kops.InstanceGroup) ([]*awstasks.Subnet, error) {
subnets, err := b.GatherSubnets(ig)
if err != nil {
return nil, err
}
if len(subnets) == 0 {
return nil, fmt.Errorf("could not determine any subnets for SpotInstanceGroup %q; subnets was %s", ig.ObjectMeta.Name, ig.Spec.Subnets)
}
out := make([]*awstasks.Subnet, len(subnets))
for i, subnet := range subnets {
out[i] = b.LinkToSubnet(subnet)
}
return out, nil
}
func (b *SpotInstanceGroupModelBuilder) buildPublicIPOpts(ig *kops.InstanceGroup) (*bool, error) {
subnetMap := make(map[string]*kops.ClusterSubnetSpec)
for i := range b.Cluster.Spec.Networking.Subnets {
subnet := &b.Cluster.Spec.Networking.Subnets[i]
subnetMap[subnet.Name] = subnet
}
var subnetType kops.SubnetType
for _, subnetName := range ig.Spec.Subnets {
subnet := subnetMap[subnetName]
if subnet == nil {
return nil, fmt.Errorf("SpotInstanceGroup %q uses subnet %q that does not exist", ig.ObjectMeta.Name, subnetName)
}
if subnetType != "" && subnetType != subnet.Type {
return nil, fmt.Errorf("SpotInstanceGroup %q cannot be in subnets of different Type", ig.ObjectMeta.Name)
}
subnetType = subnet.Type
}
var associatePublicIP bool
switch subnetType {
case kops.SubnetTypePublic, kops.SubnetTypeUtility:
associatePublicIP = true
if ig.Spec.AssociatePublicIP != nil {
associatePublicIP = *ig.Spec.AssociatePublicIP
}
case kops.SubnetTypeDualStack, kops.SubnetTypePrivate:
associatePublicIP = false
if ig.Spec.AssociatePublicIP != nil {
if *ig.Spec.AssociatePublicIP {
klog.Warningf("Ignoring AssociatePublicIPAddress=true for private SpotInstanceGroup %q", ig.ObjectMeta.Name)
}
}
default:
return nil, fmt.Errorf("unknown subnet type %q", subnetType)
}
return fi.PtrTo(associatePublicIP), nil
}
func (b *SpotInstanceGroupModelBuilder) buildRootVolumeOpts(ig *kops.InstanceGroup) (*spotinsttasks.RootVolumeOpts, error) {
opts := new(spotinsttasks.RootVolumeOpts)
var size int32
var typ string
var iops int32
var throughput int32
if ig.Spec.RootVolume != nil {
// Optimization.
{
if fi.ValueOf(ig.Spec.RootVolume.Optimization) {
opts.Optimization = ig.Spec.RootVolume.Optimization
}
}
// Encryption.
{
if fi.ValueOf(ig.Spec.RootVolume.Encryption) {
opts.Encryption = ig.Spec.RootVolume.Encryption
}
}
size = fi.ValueOf(ig.Spec.RootVolume.Size)
typ = fi.ValueOf(ig.Spec.RootVolume.Type)
iops = fi.ValueOf(ig.Spec.RootVolume.IOPS)
throughput = fi.ValueOf(ig.Spec.RootVolume.Throughput)
}
if size == 0 {
var err error
size, err = defaults.DefaultInstanceGroupVolumeSize(ig.Spec.Role)
if err != nil {
return nil, err
}
}
opts.Size = fi.PtrTo(int64(size))
if typ == "" {
typ = "gp2"
}
opts.Type = fi.PtrTo(typ)
if iops > 0 {
opts.IOPS = fi.PtrTo(int64(iops))
}
if throughput > 0 {
opts.Throughput = fi.PtrTo(int64(throughput))
}
return opts, nil
}
func (b *SpotInstanceGroupModelBuilder) buildCapacity(ig *kops.InstanceGroup) (*int64, *int64) {
minSize := int32(1)
if ig.Spec.MinSize != nil {
minSize = fi.ValueOf(ig.Spec.MinSize)
} else if ig.Spec.Role == kops.InstanceGroupRoleNode {
minSize = 2
}
maxSize := int32(1)
if ig.Spec.MaxSize != nil {
maxSize = *ig.Spec.MaxSize
} else if ig.Spec.Role == kops.InstanceGroupRoleNode {
maxSize = 2
}
return fi.PtrTo(int64(minSize)), fi.PtrTo(int64(maxSize))
}
func (b *SpotInstanceGroupModelBuilder) buildLoadBalancers(c *fi.CloudupModelBuilderContext,
ig *kops.InstanceGroup) ([]*awstasks.ClassicLoadBalancer, []*awstasks.TargetGroup, error) {
var loadBalancers []*awstasks.ClassicLoadBalancer
var targetGroups []*awstasks.TargetGroup
if b.UseLoadBalancerForAPI() && ig.HasAPIServer() {
if b.UseNetworkLoadBalancer() {
targetGroups = append(targetGroups, b.LinkToTargetGroup("tcp"))
if b.Cluster.Spec.API.LoadBalancer.SSLCertificate != "" {
targetGroups = append(targetGroups, b.LinkToTargetGroup("tls"))
}
} else {
loadBalancers = append(loadBalancers, b.LinkToCLB("api"))
}
}
if ig.Spec.Role == kops.InstanceGroupRoleBastion {
loadBalancers = append(loadBalancers, b.LinkToCLB("bastion"))
}
for _, extLB := range ig.Spec.ExternalLoadBalancers {
if extLB.LoadBalancerName != nil {
lb := &awstasks.ClassicLoadBalancer{
Name: extLB.LoadBalancerName,
LoadBalancerName: extLB.LoadBalancerName,
Shared: fi.PtrTo(true),
}
loadBalancers = append(loadBalancers, lb)
c.EnsureTask(lb)
}
if extLB.TargetGroupARN != nil {
targetGroupName, err := awsup.GetTargetGroupNameFromARN(fi.ValueOf(extLB.TargetGroupARN))
if err != nil {
return nil, nil, err
}
tg := &awstasks.TargetGroup{
Name: fi.PtrTo(ig.Name + "-" + targetGroupName),
ARN: extLB.TargetGroupARN,
Shared: fi.PtrTo(true),
}
targetGroups = append(targetGroups, tg)
c.AddTask(tg)
}
}
return loadBalancers, targetGroups, nil
}
func (b *SpotInstanceGroupModelBuilder) buildTags(ig *kops.InstanceGroup) (map[string]string, error) {
tags, err := b.CloudTagsForInstanceGroup(ig)
if err != nil {
return nil, err
}
return tags, nil
}
func (b *SpotInstanceGroupModelBuilder) buildAutoScalerOpts(clusterID string, ig *kops.InstanceGroup) (*spotinsttasks.AutoScalerOpts, error) {
opts := &spotinsttasks.AutoScalerOpts{
ClusterID: fi.PtrTo(clusterID),
}
switch ig.Spec.Role {
case kops.InstanceGroupRoleControlPlane:
return opts, nil
case kops.InstanceGroupRoleBastion:
return nil, nil
}
// Enable the auto scaler for Node instance groups.
opts.Enabled = fi.PtrTo(true)
opts.AutoConfig = fi.PtrTo(true)
// Parse instance group labels.
var defaultNodeLabels bool
for k, v := range ig.ObjectMeta.Labels {
switch k {
case SpotInstanceGroupLabelAutoScalerDisabled:
{
v, err := parseBool(v)
if err != nil {
return nil, err
}
opts.Enabled = fi.PtrTo(!fi.ValueOf(v))
}
case SpotInstanceGroupLabelAutoScalerDefaultNodeLabels:
{
v, err := parseBool(v)
if err != nil {
return nil, err
}
defaultNodeLabels = fi.ValueOf(v)
}
case SpotInstanceGroupLabelAutoScalerCooldown:
{
v, err := parseInt(v)
if err != nil {
return nil, err
}
opts.Cooldown = fi.PtrTo(int(fi.ValueOf(v)))
}
case SpotInstanceGroupLabelAutoScalerAutoConfig:
{
v, err := parseBool(v)
if err != nil {
return nil, err
}
opts.AutoConfig = v
}
case SpotInstanceGroupLabelAutoScalerAutoHeadroomPercentage:
{
v, err := parseInt(v)
if err != nil {
return nil, err
}
opts.AutoHeadroomPercentage = fi.PtrTo(int(fi.ValueOf(v)))
}
case SpotInstanceGroupLabelAutoScalerHeadroomCPUPerUnit:
{
v, err := parseInt(v)
if err != nil {
return nil, err
}
if opts.Headroom == nil {
opts.Headroom = new(spotinsttasks.AutoScalerHeadroomOpts)
}
opts.Headroom.CPUPerUnit = fi.PtrTo(int(fi.ValueOf(v)))
}
case SpotInstanceGroupLabelAutoScalerHeadroomGPUPerUnit:
{
v, err := parseInt(v)
if err != nil {
return nil, err
}
if opts.Headroom == nil {
opts.Headroom = new(spotinsttasks.AutoScalerHeadroomOpts)
}
opts.Headroom.GPUPerUnit = fi.PtrTo(int(fi.ValueOf(v)))
}
case SpotInstanceGroupLabelAutoScalerHeadroomMemPerUnit:
{
v, err := parseInt(v)
if err != nil {
return nil, err
}
if opts.Headroom == nil {
opts.Headroom = new(spotinsttasks.AutoScalerHeadroomOpts)
}
opts.Headroom.MemPerUnit = fi.PtrTo(int(fi.ValueOf(v)))
}
case SpotInstanceGroupLabelAutoScalerHeadroomNumOfUnits:
{
v, err := parseInt(v)
if err != nil {
return nil, err
}
if opts.Headroom == nil {
opts.Headroom = new(spotinsttasks.AutoScalerHeadroomOpts)
}
opts.Headroom.NumOfUnits = fi.PtrTo(int(fi.ValueOf(v)))
}
case SpotInstanceGroupLabelAutoScalerScaleDownMaxPercentage:
{
v, err := parseFloat(v)
if err != nil {
return nil, err
}
if opts.Down == nil {
opts.Down = new(spotinsttasks.AutoScalerDownOpts)
}
opts.Down.MaxPercentage = v
}
case SpotInstanceGroupLabelAutoScalerScaleDownEvaluationPeriods:
{
v, err := parseInt(v)
if err != nil {
return nil, err
}
if opts.Down == nil {
opts.Down = new(spotinsttasks.AutoScalerDownOpts)
}
opts.Down.EvaluationPeriods = fi.PtrTo(int(fi.ValueOf(v)))
}
case SpotInstanceGroupLabelAutoScalerResourceLimitsMaxVCPU:
{
v, err := parseInt(v)