-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathresource_workload_scaling_policy.go
More file actions
1644 lines (1444 loc) · 55.2 KB
/
resource_workload_scaling_policy.go
File metadata and controls
1644 lines (1444 loc) · 55.2 KB
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 castai
import (
"context"
"errors"
"fmt"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/samber/lo"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/castai/terraform-provider-castai/castai/sdk"
)
const (
createTimeout = 120 * time.Second
)
const (
minResourceMultiplierValue = 1.0
minApplyThresholdValue = 0.01
maxApplyThresholdValue = 2.5
defaultApplyThresholdPercentage = 0.1
defaultConfidenceThreshold = 0.9
minNumeratorValue = 0.0
maxExponentValue = 1.
minExponentValue = 0.
defaultApplyType = "IMMEDIATE"
)
const (
FieldLimitStrategy = "limit"
FieldLimitStrategyType = "type"
FieldLimitStrategyMultiplier = "multiplier"
FieldConfidence = "confidence"
FieldRolloutBehavior = "rollout_behavior"
FieldRolloutBehaviorType = "type"
FieldRolloutBehaviorNoDisruptionType = "NO_DISRUPTION"
FieldRolloutBehaviorPreferOneByOneType = "prefer_one_by_one"
FieldPredictiveScaling = "predictive_scaling"
FieldMemoryEvent = "memory_event"
FieldApplyType = "apply_type"
FieldConfidenceThreshold = "threshold"
DeprecatedFieldApplyThreshold = "apply_threshold"
FieldApplyThresholdStrategy = "apply_threshold_strategy"
FieldApplyThresholdStrategyType = "type"
FieldApplyThresholdStrategyPercentage = "percentage"
FieldApplyThresholdStrategyNumerator = "numerator"
FieldApplyThresholdStrategyDenominator = "denominator"
FieldApplyThresholdStrategyExponent = "exponent"
FieldApplyThresholdStrategyPercentageType = "PERCENTAGE"
FieldApplyThresholdStrategyDefaultAdaptiveType = "DEFAULT_ADAPTIVE"
FieldApplyThresholdStrategyCustomAdaptiveType = "CUSTOM_ADAPTIVE"
FieldAssignmentRules = "assignment_rules"
)
const (
K8sLabelInOperator = "In"
K8sLabelNotInOperator = "NotIn"
K8sLabelExistsOperator = "Exists"
K8sLabelDoesNotExistOperator = "DoesNotExist"
K8sLabelContainsOperator = "Contains"
K8sLabelRegexOperator = "Regex"
)
var (
k8sNameRegex = regexp.MustCompile("^[a-z0-9A-Z][a-z0-9A-Z._-]{0,61}[a-z0-9A-Z]$")
)
func resourceWorkloadScalingPolicy() *schema.Resource {
return &schema.Resource{
CreateContext: resourceWorkloadScalingPolicyCreate,
ReadContext: resourceWorkloadScalingPolicyRead,
UpdateContext: resourceWorkloadScalingPolicyUpdate,
DeleteContext: resourceWorkloadScalingPolicyDelete,
CustomizeDiff: resourceWorkloadScalingPolicyDiff,
Importer: &schema.ResourceImporter{
StateContext: workloadScalingPolicyImporter,
},
Description: "Manage workload scaling policy. Scaling policy [reference](https://docs.cast.ai/docs/woop-scaling-policies)",
Schema: map[string]*schema.Schema{
FieldClusterID: {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "CAST AI cluster id",
ValidateDiagFunc: validation.ToDiagFunc(validation.IsUUID),
},
FieldAssignmentRules: {
Type: schema.TypeList,
Optional: true,
Description: "Allows defining conditions for automatically assigning workloads to this scaling policy.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"rules": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"namespace": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Allows assigning a scaling policy based on the workload's namespace.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"names": {
Type: schema.TypeList,
Optional: true,
Description: "Defines matching by namespace names.",
Elem: &schema.Schema{Type: schema.TypeString},
},
// TODO(WOOP-714): enable label expressions
//"labels_expressions": k8sLabelExpressionsSchema(),
},
},
},
"workload": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Allows assigning a scaling policy based on the workload's metadata.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"gvk": {
Type: schema.TypeList,
Optional: true,
Description: `Group, version, and kind for Kubernetes resources. Format: kind[.version][.group].
It can be either:
- only kind, e.g. "Deployment"
- group and kind: e.g."Deployment.apps"
- group, version and kind: e.g."Deployment.v1.apps"`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"labels_expressions": k8sLabelExpressionsSchema(),
},
},
},
},
},
},
},
},
},
"name": {
Type: schema.TypeString,
Required: true,
Description: "Scaling policy name",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringMatch(k8sNameRegex, "name must adhere to the format guidelines of Kubernetes labels/annotations")),
},
FieldApplyType: {
Type: schema.TypeString,
Required: true,
Description: `Recommendation apply type.
- IMMEDIATE - pods are restarted immediately when new recommendation is generated.
- DEFERRED - pods are not restarted and recommendation values are applied during natural restarts only (new deployment, etc.)`,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"IMMEDIATE", "DEFERRED"}, false)),
},
"management_option": {
Type: schema.TypeString,
Required: true,
Description: `Defines possible options for workload management.
- READ_ONLY - workload watched (metrics collected), but no actions performed by CAST AI.
- MANAGED - workload watched (metrics collected), CAST AI may perform actions on the workload.`,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"READ_ONLY", "MANAGED"}, false)),
},
"cpu": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
Elem: workloadScalingPolicyResourceSchema("cpu", "QUANTILE", 0, 0.01),
},
"memory": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
Elem: workloadScalingPolicyResourceSchema("memory", "MAX", 0.1, 10),
},
"startup": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"period_seconds": {
Type: schema.TypeInt,
Optional: true,
Description: "Defines the duration (in seconds) during which elevated resource usage is expected at startup.\nWhen set, recommendations will be adjusted to disregard resource spikes within this period.\nIf not specified, the workload will receive standard recommendations without startup considerations.",
ValidateDiagFunc: validation.ToDiagFunc(validation.IntBetween(120, 3600)),
},
},
},
},
FieldConfidence: {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Defines the confidence settings for applying recommendations.",
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return suppressConfidenceThresholdDefaultValueDiff(FieldConfidence, old, new, d)
},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
FieldConfidenceThreshold: {
Type: schema.TypeFloat,
Optional: true,
Default: 0.9,
Description: "Defines the confidence threshold for applying recommendations. The smaller number indicates that we require fewer metrics data points to apply recommendations - changing this value can cause applying less precise recommendations. Do not change the default unless you want to optimize with fewer data points (e.g., short-lived workloads).",
ValidateDiagFunc: validation.ToDiagFunc(validation.FloatBetween(0, 1)),
},
},
},
},
"downscaling": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
FieldApplyType: {
Type: schema.TypeString,
Optional: true,
Description: `Defines the apply type to be used when downscaling.
- IMMEDIATE - pods are restarted immediately when new recommendation is generated.
- DEFERRED - pods are not restarted and recommendation values are applied during natural restarts only (new deployment, etc.)`,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"IMMEDIATE", "DEFERRED"}, false)),
},
},
},
},
FieldMemoryEvent: {
Type: schema.TypeList,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return suppressMemoryEventApplyTypeDefaultValueDiff(old, new, d)
},
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
FieldApplyType: {
Type: schema.TypeString,
Optional: true,
Description: `Defines the apply type to be used when applying recommendation for memory related event.
- IMMEDIATE - pods are restarted immediately when new recommendation is generated.
- DEFERRED - pods are not restarted and recommendation values are applied during natural restarts only (new deployment, etc.)`,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"IMMEDIATE", "DEFERRED"}, false)),
},
},
},
},
"anti_affinity": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"consider_anti_affinity": {
Type: schema.TypeBool,
Optional: true,
Description: `Defines if anti-affinity should be considered when scaling the workload.
If enabled, requiring host ports, or having anti-affinity on hostname will force all recommendations to be deferred.`,
},
},
},
},
FieldPredictiveScaling: {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
FieldCPU: getPredictiveScalingResourceSchema(),
},
},
},
FieldRolloutBehavior: {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `Defines the rollout behavior used when applying recommendations. Prerequisites:
- Applicable to Deployment resources that support running as multi-replica.
- Deployment is running with single replica (replica count = 1).
- Deployment's rollout strategy allows for downtime.
- Recommendation apply type is "immediate".
- Cluster has workload-autoscaler component version v0.35.3 or higher.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
FieldRolloutBehaviorType: {
Type: schema.TypeString,
Optional: true,
Description: `Defines the rollout type to be used when applying recommendations.
- NO_DISRUPTION - pods are restarted without causing service disruption.`,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{FieldRolloutBehaviorNoDisruptionType}, false)),
},
FieldRolloutBehaviorPreferOneByOneType: {
Type: schema.TypeBool,
Optional: true,
Description: `Defines if pods should be restarted one by one to avoid service disruption.`,
},
},
},
},
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(createTimeout),
Read: schema.DefaultTimeout(15 * time.Second),
Update: schema.DefaultTimeout(15 * time.Second),
Delete: schema.DefaultTimeout(15 * time.Second),
},
}
}
func getPredictiveScalingResourceSchema() *schema.Schema {
return &schema.Schema{
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Defines predictive scaling resource configuration.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
FieldEnabled: {
Type: schema.TypeBool,
Required: true,
Description: "Defines if predictive scaling is enabled for resource.",
},
},
},
}
}
func k8sLabelExpressionsSchema() *schema.Schema {
return &schema.Schema{
Type: schema.TypeList,
Optional: true,
Description: "Defines matching by label selector requirements.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
Description: "The label key to match. Required for all operators except `Regex` and `Contains`. If not specified, it will search through all labels.",
},
"operator": {
Type: schema.TypeString,
Required: true,
Description: "The operator to use for matching the label.",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{
K8sLabelInOperator, K8sLabelNotInOperator, K8sLabelExistsOperator, K8sLabelDoesNotExistOperator,
K8sLabelRegexOperator, K8sLabelContainsOperator,
}, false)),
},
"values": {
Type: schema.TypeList,
Optional: true,
Description: "A list of values to match against the label key. It is required for `In`, `NotIn`, `Regex`, and `Contains` operators.",
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
}
}
func workloadScalingPolicyResourceSchema(resource, function string, overhead, minRecommended float64) *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
"function": {
Type: schema.TypeString,
Optional: true,
Description: "The function used to calculate the resource recommendation. Supported values: `QUANTILE`, `MAX`",
Default: function,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"QUANTILE", "MAX"}, false)),
},
"args": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The arguments for the function - i.e. for `QUANTILE` this should be a [0, 1] float. " +
"`MAX` doesn't accept any args",
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"overhead": {
Type: schema.TypeFloat,
Optional: true,
Description: "Overhead for the recommendation, e.g. `0.1` will result in 10% higher recommendation",
Default: overhead,
ValidateDiagFunc: validation.ToDiagFunc(validation.FloatBetween(0, 1)),
},
DeprecatedFieldApplyThreshold: {
Type: schema.TypeFloat,
Optional: true,
Description: "The threshold of when to apply the recommendation. Recommendation will be applied when " +
"diff of current requests and new recommendation is greater than set value",
ValidateDiagFunc: validation.ToDiagFunc(validation.FloatBetween(minApplyThresholdValue, maxApplyThresholdValue)),
Deprecated: "Use apply_threshold_strategy instead",
},
FieldApplyThresholdStrategy: {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Resource apply threshold strategy settings. " +
"The default strategy is `PERCENTAGE` with percentage value set to 0.1.",
Elem: workloadScalingPolicyResourceApplyThresholdStrategySchema(),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return suppressThresholdStrategyDefaultValueDiff(resource, old, new, d)
},
ConflictsWith: []string{fmt.Sprintf("%s.0.%s", resource, DeprecatedFieldApplyThreshold)},
},
"look_back_period_seconds": {
Type: schema.TypeInt,
Optional: true,
Description: "The look back period in seconds for the recommendation.",
ValidateDiagFunc: validation.ToDiagFunc(validation.IntBetween(3*60*60, 7*24*60*60)),
},
"min": {
Type: schema.TypeFloat,
Default: minRecommended,
Optional: true,
Description: "Min values for the recommendation, applies to every container. For memory - this is in MiB, for CPU - this is in cores.",
ValidateDiagFunc: validation.ToDiagFunc(validation.FloatAtLeast(minRecommended)),
},
"max": {
Type: schema.TypeFloat,
Optional: true,
Description: "Max values for the recommendation, applies to every container. For memory - this is in MiB, for CPU - this is in cores.",
},
FieldLimitStrategy: {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Resource limit settings",
Elem: workloadScalingPolicyResourceLimitSchema(),
},
"management_option": {
Type: schema.TypeString,
Optional: true,
Description: "Disables management for a single resource when set to `READ_ONLY`. " +
"The resource will use its original workload template requests and limits. " +
"Supported value: `READ_ONLY`. Minimum required workload-autoscaler version: `v0.23.1`.",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"READ_ONLY"}, false)),
},
},
}
}
func workloadScalingPolicyResourceLimitSchema() *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
FieldLimitStrategyType: {
Type: schema.TypeString,
Required: true,
Description: fmt.Sprintf(`Defines limit strategy type.
- %s - removes the resource limit even if it was specified in the workload spec.
- %s - keep existing resource limits. While limits provide stability predictability, they may restrict workloads that need to temporarily burst beyond their allocation.
- %s - used to calculate the resource limit. The final value is determined by multiplying the resource request by the specified factor.`, sdk.NOLIMIT, sdk.KEEPLIMITS, sdk.MULTIPLIER),
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{string(sdk.MULTIPLIER), string(sdk.KEEPLIMITS), string(sdk.NOLIMIT)}, false)),
},
FieldLimitStrategyMultiplier: {
Type: schema.TypeFloat,
Optional: true,
Description: "Multiplier used to calculate the resource limit. It must be defined for the MULTIPLIER strategy.",
ValidateDiagFunc: validation.ToDiagFunc(validation.FloatAtLeast(minResourceMultiplierValue)),
},
},
}
}
func workloadScalingPolicyResourceApplyThresholdStrategySchema() *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
FieldApplyThresholdStrategyType: {
Type: schema.TypeString,
Required: true,
Description: fmt.Sprintf(`Defines apply theshold strategy type.
- %s - recommendation will be applied when diff of current requests and new recommendation is greater than set value
- %s - will pick larger threshold percentage for small workloads and smaller percentage for large workloads.
- %s - works in same way as %s, but it allows to tweak parameters of adaptive threshold formula: percentage = numerator/(currentRequest + denominator)^exponent. This strategy is for advance use cases, we recommend to use %s strategy.
`, FieldApplyThresholdStrategyPercentageType, FieldApplyThresholdStrategyDefaultAdaptiveType, FieldApplyThresholdStrategyCustomAdaptiveType, FieldApplyThresholdStrategyDefaultAdaptiveType, FieldApplyThresholdStrategyDefaultAdaptiveType),
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{FieldApplyThresholdStrategyPercentageType, FieldApplyThresholdStrategyDefaultAdaptiveType, FieldApplyThresholdStrategyCustomAdaptiveType}, false)),
},
FieldApplyThresholdStrategyPercentage: {
Type: schema.TypeFloat,
Optional: true,
Description: fmt.Sprintf("Percentage of a how much difference should there be between the current pod requests and the new recommendation. "+
"It must be defined for the %s strategy.", FieldApplyThresholdStrategyPercentageType),
ValidateDiagFunc: validation.ToDiagFunc(validation.FloatBetween(minApplyThresholdValue, maxApplyThresholdValue)),
},
FieldApplyThresholdStrategyNumerator: {
Type: schema.TypeFloat,
Optional: true,
Description: fmt.Sprintf("The %s affects vertical stretch of function used in adaptive threshold - smaller number will create smaller threshold."+
"It must be defined for the %s strategy.", FieldApplyThresholdStrategyNumerator, FieldApplyThresholdStrategyCustomAdaptiveType),
ValidateDiagFunc: validation.ToDiagFunc(validation.FloatAtLeast(minNumeratorValue)),
},
FieldApplyThresholdStrategyDenominator: {
// Terraform SDK cannot distinguish between unset and 0 value, that's why it has to be string.
Type: schema.TypeString,
Optional: true,
Description: fmt.Sprintf("If %s is close or equal to 0, the threshold will be much bigger for small values."+
"For example when numerator, exponent is 1 and denominator is 0 the threshold for 0.5 req. CPU will be 200%%."+
"It must be defined for the %s strategy.", FieldApplyThresholdStrategyDenominator, FieldApplyThresholdStrategyCustomAdaptiveType),
ValidateDiagFunc: validateConvertableToNonNegativeFloat(),
},
FieldApplyThresholdStrategyExponent: {
Type: schema.TypeFloat,
Optional: true,
Description: fmt.Sprintf(`The %s changes how fast the curve is going down. The smaller value will cause that we won’t pick extremely small number for big resources, for example:
- if numerator is 0, denominator is 1, and exponent is 1, for 50 CPU we will pick 2%% threshold
- if numerator is 0, denominator is 1, and exponent is 0.8, for 50 CPU we will pick 4.3%% threshold
It must be defined for the %s strategy.`, FieldApplyThresholdStrategyExponent, FieldApplyThresholdStrategyCustomAdaptiveType),
ValidateDiagFunc: validation.ToDiagFunc(validation.FloatBetween(minExponentValue, maxExponentValue)),
},
},
}
}
func validateConvertableToNonNegativeFloat() schema.SchemaValidateDiagFunc {
return validation.ToDiagFunc(func(value any, key string) ([]string, []error) {
v, ok := value.(string)
if !ok {
return nil, []error{fmt.Errorf("expected type of %q to be string", key)}
}
if v == "" {
return nil, nil
}
number, err := strconv.ParseFloat(v, 64)
if err != nil {
return nil, []error{fmt.Errorf("failed to parse %q: %w", key, err)}
}
if number < 0 {
return nil, []error{fmt.Errorf("expected %q to be non-negative, got %g", key, number)}
}
return nil, nil
})
}
func resourceWorkloadScalingPolicyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
client := meta.(*ProviderConfig).api
clusterID := d.Get(FieldClusterID).(string)
req := sdk.WorkloadOptimizationAPICreateWorkloadScalingPolicyJSONRequestBody{
Name: d.Get("name").(string),
ApplyType: sdk.WorkloadoptimizationV1ApplyType(d.Get(FieldApplyType).(string)),
RecommendationPolicies: sdk.WorkloadoptimizationV1RecommendationPolicies{
ManagementOption: sdk.WorkloadoptimizationV1ManagementOption(d.Get("management_option").(string)),
},
}
if v, ok := d.GetOk("cpu"); ok {
cpu, err := toWorkloadScalingPolicies("cpu", v.([]any)[0].(map[string]any))
if err != nil {
return diag.FromErr(err)
}
req.RecommendationPolicies.Cpu = cpu
}
if v, ok := d.GetOk("memory"); ok {
memory, err := toWorkloadScalingPolicies("memory", v.([]any)[0].(map[string]any))
if err != nil {
return diag.FromErr(err)
}
req.RecommendationPolicies.Memory = memory
}
req.RecommendationPolicies.Confidence = toConfidence(toSection(d, FieldConfidence))
req.RecommendationPolicies.Startup = toStartup(toSection(d, "startup"))
req.RecommendationPolicies.Downscaling = toDownscaling(toSection(d, "downscaling"))
req.RecommendationPolicies.MemoryEvent = toMemoryEvent(toSection(d, "memory_event"))
req.RecommendationPolicies.AntiAffinity = toAntiAffinity(toSection(d, "anti_affinity"))
req.RecommendationPolicies.PredictiveScaling = toPredictiveScaling(toSection(d, FieldPredictiveScaling))
req.RecommendationPolicies.RolloutBehavior = toRolloutBehavior(toSection(d, FieldRolloutBehavior))
ar, err := toAssignmentRules(toSection(d, FieldAssignmentRules))
if err != nil {
return diag.FromErr(err)
}
req.AssignmentRules = ar
b := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
var lastErr error
if err := backoff.RetryNotify(func() error {
create, createErr := client.WorkloadOptimizationAPICreateWorkloadScalingPolicyWithResponse(ctx, clusterID, req)
if createErr != nil {
return createErr
}
switch create.StatusCode() {
case http.StatusOK:
d.SetId(create.JSON200.Id)
return checkIfRetryable(fetchScalingPolicy(ctx, d, meta))
case http.StatusConflict:
policy, err := getWorkloadScalingPolicyByName(ctx, client, clusterID, req.Name)
if err != nil {
return err
}
if policy.IsDefault {
d.SetId(policy.Id)
return checkIfRetryable(updateScalingPolicy(ctx, d, meta))
}
return backoff.Permanent(fmt.Errorf("scaling policy with name %q already exists", req.Name))
default:
return checkIfRetryable(create, createErr)
}
}, b, func(err error, _ time.Duration) {
if !isInterrupt(err) {
tflog.Warn(ctx, "Error creating workload scaling policy", map[string]any{
"error": err,
})
lastErr = err
}
}); err != nil {
if isInterrupt(err) {
return diag.FromErr(lastErr)
}
return diag.FromErr(err)
}
return nil
}
func isInterrupt(err error) bool {
return errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)
}
func checkIfRetryable(response sdk.Response, err error) error {
if err != nil {
return err
}
if response == nil || response.StatusCode() == http.StatusOK {
return nil
}
e := fmt.Errorf("expected status code 200, received: status=%d body=%s", response.StatusCode(), string(response.GetBody()))
if response.StatusCode() == http.StatusBadRequest ||
response.StatusCode() == http.StatusUnauthorized ||
response.StatusCode() == http.StatusForbidden {
return backoff.Permanent(e)
}
return e
}
func resourceWorkloadScalingPolicyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
resp, err := fetchScalingPolicy(ctx, d, meta)
if err = sdk.CheckOKResponse(resp, err); err != nil {
return diag.FromErr(err)
}
return nil
}
func fetchScalingPolicy(ctx context.Context, d *schema.ResourceData, meta any) (sdk.Response, error) {
client := meta.(*ProviderConfig).api
clusterID := d.Get(FieldClusterID).(string)
resp, err := client.WorkloadOptimizationAPIGetWorkloadScalingPolicyWithResponse(ctx, clusterID, d.Id())
if err != nil {
return resp, err
}
if !d.IsNewResource() && resp.StatusCode() == http.StatusNotFound {
tflog.Warn(ctx, "Scaling policy not found, removing from state", map[string]any{"id": d.Id()})
d.SetId("")
return nil, nil
}
if resp.StatusCode() != http.StatusOK {
return resp, nil
}
sp := resp.JSON200
if err := d.Set("name", sp.Name); err != nil {
return nil, fmt.Errorf("setting name: %w", err)
}
if err := d.Set(FieldApplyType, sp.ApplyType); err != nil {
return nil, fmt.Errorf("setting apply type: %w", err)
}
if err := d.Set("management_option", sp.RecommendationPolicies.ManagementOption); err != nil {
return nil, fmt.Errorf("setting management option: %w", err)
}
if err := d.Set("cpu", toWorkloadScalingPoliciesMap(getResourceFrom(d, "cpu"), sp.RecommendationPolicies.Cpu)); err != nil {
return nil, fmt.Errorf("setting cpu: %w", err)
}
if err := d.Set("memory", toWorkloadScalingPoliciesMap(getResourceFrom(d, "memory"), sp.RecommendationPolicies.Memory)); err != nil {
return nil, fmt.Errorf("setting memory: %w", err)
}
if err := d.Set("startup", toStartupMap(sp.RecommendationPolicies.Startup)); err != nil {
return nil, fmt.Errorf("setting startup: %w", err)
}
if err := d.Set(FieldConfidence, toConfidenceMap(sp.RecommendationPolicies.Confidence)); err != nil {
return nil, fmt.Errorf("setting confidence: %w", err)
}
if err := d.Set("downscaling", toDownscalingMap(sp.RecommendationPolicies.Downscaling)); err != nil {
return nil, fmt.Errorf("setting downscaling: %w", err)
}
if err := d.Set("memory_event", toMemoryEventMap(sp.RecommendationPolicies.MemoryEvent)); err != nil {
return nil, fmt.Errorf("setting memory event: %w", err)
}
if err := d.Set("anti_affinity", toAntiAffinityMap(sp.RecommendationPolicies.AntiAffinity)); err != nil {
return nil, fmt.Errorf("setting anti-affinity: %w", err)
}
if err := d.Set(FieldPredictiveScaling, toPredictiveScalingMap(sp.RecommendationPolicies.PredictiveScaling)); err != nil {
return nil, fmt.Errorf("setting predictive scaling: %w", err)
}
if err := d.Set(FieldRolloutBehavior, toRolloutBehaviorMap(sp.RecommendationPolicies.RolloutBehavior)); err != nil {
return nil, fmt.Errorf("setting rollout behavior: %w", err)
}
if err := d.Set(FieldAssignmentRules, toAssignmentRulesMap(getResourceFrom(d, FieldAssignmentRules), sp.AssignmentRules)); err != nil {
return nil, fmt.Errorf("setting assignment rules: %w", err)
}
return nil, nil
}
func getResourceFrom(d *schema.ResourceData, resource string) map[string]any {
if v, ok := d.GetOk(resource); ok {
return v.([]any)[0].(map[string]any)
}
return map[string]any{}
}
func resourceWorkloadScalingPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
resp, err := updateScalingPolicy(ctx, d, meta)
if err = sdk.CheckOKResponse(resp, err); err != nil {
return diag.FromErr(err)
}
return nil
}
func updateScalingPolicy(ctx context.Context, d *schema.ResourceData, meta any) (sdk.Response, error) {
if !d.HasChanges(
"name",
FieldApplyType,
"management_option",
"cpu",
"memory",
"startup",
"downscaling",
"memory_event",
"anti_affinity",
FieldConfidence,
FieldAssignmentRules,
FieldPredictiveScaling,
FieldRolloutBehavior,
) {
tflog.Info(ctx, "scaling policy up to date")
return nil, nil
}
client := meta.(*ProviderConfig).api
clusterID := d.Get(FieldClusterID).(string)
cpu, err := toWorkloadScalingPolicies("cpu", d.Get("cpu").([]any)[0].(map[string]any))
if err != nil {
return nil, err
}
memory, err := toWorkloadScalingPolicies("memory", d.Get("memory").([]any)[0].(map[string]any))
if err != nil {
return nil, err
}
ar, err := toAssignmentRules(toSection(d, FieldAssignmentRules))
if err != nil {
return nil, err
}
req := sdk.WorkloadOptimizationAPIUpdateWorkloadScalingPolicyJSONRequestBody{
Name: d.Get("name").(string),
ApplyType: sdk.WorkloadoptimizationV1ApplyType(d.Get(FieldApplyType).(string)),
AssignmentRules: ar,
RecommendationPolicies: sdk.WorkloadoptimizationV1RecommendationPolicies{
ManagementOption: sdk.WorkloadoptimizationV1ManagementOption(d.Get("management_option").(string)),
Cpu: cpu,
Memory: memory,
Startup: toStartup(toSection(d, "startup")),
Downscaling: toDownscaling(toSection(d, "downscaling")),
MemoryEvent: toMemoryEvent(toSection(d, "memory_event")),
AntiAffinity: toAntiAffinity(toSection(d, "anti_affinity")),
Confidence: toConfidence(toSection(d, FieldConfidence)),
PredictiveScaling: toPredictiveScaling(toSection(d, FieldPredictiveScaling)),
RolloutBehavior: toRolloutBehavior(toSection(d, FieldRolloutBehavior)),
},
}
resp, err := client.WorkloadOptimizationAPIUpdateWorkloadScalingPolicyWithResponse(ctx, clusterID, d.Id(), req)
if err != nil {
return resp, err
}
if resp.StatusCode() != http.StatusOK {
return resp, err
}
return fetchScalingPolicy(ctx, d, meta)
}
func resourceWorkloadScalingPolicyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
client := meta.(*ProviderConfig).api
clusterID := d.Get(FieldClusterID).(string)
resp, err := client.WorkloadOptimizationAPIGetWorkloadScalingPolicyWithResponse(ctx, clusterID, d.Id())
if err != nil {
return diag.FromErr(err)
}
if resp.StatusCode() == http.StatusNotFound {
tflog.Debug(ctx, "Scaling policy not found, skipping delete", map[string]any{"id": d.Id()})
return nil
}
if err := sdk.StatusOk(resp); err != nil {
return diag.FromErr(err)
}
if resp.JSON200.IsReadonly || resp.JSON200.IsDefault {
tflog.Warn(ctx, "Default/readonly scaling policy can't be deleted, removing from state", map[string]any{
"id": d.Id(),
})
return nil
}
delResp, err := client.WorkloadOptimizationAPIDeleteWorkloadScalingPolicyWithResponse(ctx, clusterID, d.Id())
if err != nil {
return diag.FromErr(err)
}
if err := sdk.StatusOk(delResp); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceWorkloadScalingPolicyDiff(_ context.Context, d *schema.ResourceDiff, _ any) error {
// Since tf doesn't support cross field validation, doing it here.
_, err := toWorkloadScalingPolicies("cpu", d.Get("cpu").([]any)[0].(map[string]any))
if err != nil {
return err
}
_, err = toWorkloadScalingPolicies("memory", d.Get("memory").([]any)[0].(map[string]any))
if err != nil {
return err
}
return nil
}
func workloadScalingPolicyImporter(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) {
clusterID, nameOrID, found := strings.Cut(d.Id(), "/")
if !found {
return nil, fmt.Errorf("expected import id with format: <cluster_id>/<scaling_policy name or id>, got: %q", d.Id())
}
if err := d.Set(FieldClusterID, clusterID); err != nil {
return nil, fmt.Errorf("setting cluster ID: %w", err)
}
// Return if scaling policy ID provided.
if _, err := uuid.Parse(nameOrID); err == nil {
d.SetId(nameOrID)
return []*schema.ResourceData{d}, nil
}
// Find scaling policy ID by name.
client := meta.(*ProviderConfig).api
policy, err := getWorkloadScalingPolicyByName(ctx, client, clusterID, nameOrID)
if err != nil {
return nil, err
}
d.SetId(policy.Id)
return []*schema.ResourceData{d}, nil
}
func toWorkloadScalingPolicies(resource string, obj map[string]any) (sdk.WorkloadoptimizationV1ResourcePolicies, error) {
var err error
out := sdk.WorkloadoptimizationV1ResourcePolicies{}
if v, ok := obj["function"].(string); ok {
out.Function = sdk.WorkloadoptimizationV1ResourcePoliciesFunction(v)
}
if v, ok := obj["args"].([]any); ok && len(v) > 0 {
out.Args = toStringList(v)
}
if out.Function == "QUANTILE" && len(out.Args) == 0 {
return out, fmt.Errorf("field %q: QUANTILE function requires args to be provided", resource)
}
if out.Function == "MAX" && len(out.Args) > 0 {
return out, fmt.Errorf("field %q: MAX function doesn't accept any args", resource)
}
if v, ok := obj["overhead"].(float64); ok {
out.Overhead = v
}
if v, ok := obj["look_back_period_seconds"].(int); ok && v > 0 {
out.LookBackPeriodSeconds = lo.ToPtr(int32(v))
}
if v, ok := obj["min"].(float64); ok {
out.Min = lo.ToPtr(v)
}
if v, ok := obj["max"].(float64); ok && v > 0 {
out.Max = lo.ToPtr(v)
}
if v, ok := obj[FieldLimitStrategy].([]any); ok && len(v) > 0 {
out.Limit, err = toWorkloadResourceLimit(v[0].(map[string]any))
if err != nil {
return out, fmt.Errorf("field %q: field %q: %w", resource, FieldLimitStrategy, err)
}
}
if v, ok := obj["management_option"].(string); ok && v != "" {
out.ManagementOption = lo.ToPtr(sdk.WorkloadoptimizationV1ManagementOption(v))
}
out.ApplyThresholdStrategy, err = resolveApplyThresholdStrategy(obj)
if err != nil {
return out, fmt.Errorf("field %q: %w", resource, err)
}
return out, err
}
func resolveApplyThresholdStrategy(obj map[string]any) (*sdk.WorkloadoptimizationV1ApplyThresholdStrategy, error) {
if v, ok := obj[DeprecatedFieldApplyThreshold].(float64); ok && v > 0 {
return toWorkloadResourcePercentageThresholdStrategy(v), nil
}
if v, ok := obj[FieldApplyThresholdStrategy].([]any); ok && len(v) > 0 {
out, err := toWorkloadResourceApplyThresholdStrategy(v[0].(map[string]any))
if err != nil {
return nil, fmt.Errorf("field %q: %w", FieldApplyThresholdStrategy, err)
}
return out, nil
}
return toWorkloadResourcePercentageThresholdStrategy(defaultApplyThresholdPercentage), nil
}
func toWorkloadResourceApplyThresholdStrategy(obj map[string]any) (*sdk.WorkloadoptimizationV1ApplyThresholdStrategy, error) {
if len(obj) == 0 {
return nil, nil
}
var out *sdk.WorkloadoptimizationV1ApplyThresholdStrategy
strategy, _ := obj[FieldApplyThresholdStrategyType].(string)
switch strategy {
case FieldApplyThresholdStrategyPercentageType:
percentage, err := mustGetValue[float64](obj, FieldApplyThresholdStrategyPercentage)
if err != nil {
return nil, err
}
out = toWorkloadResourcePercentageThresholdStrategy(*percentage)
case FieldApplyThresholdStrategyDefaultAdaptiveType:
out = toWorkloadResourceDefaultAdaptiveThresholdStrategy()
case FieldApplyThresholdStrategyCustomAdaptiveType:
var err error
numerator, err := mustGetValue[float64](obj, FieldApplyThresholdStrategyNumerator)
if err != nil {
return nil, err
}
denominatorStr, err := mustGetValue[string](obj, FieldApplyThresholdStrategyDenominator)
if err != nil {
return nil, err
}
denominator, err := strconv.ParseFloat(*denominatorStr, 64)
if err != nil {
return nil, fmt.Errorf("invalid denominator value: %w", err)
}
exponent, err := mustGetValue[float64](obj, FieldApplyThresholdStrategyExponent)
if err != nil {
return nil, err
}
out = toWorkloadResourceCustomAdaptiveThresholdStrategy(*numerator, denominator, *exponent)
default:
return nil, fmt.Errorf(
"field %q: unknown apply threshold strategy type: %q", FieldApplyThresholdStrategyType, strategy)
}
return out, nil
}
func mustGetValue[T comparable](obj map[string]any, key string) (*T, error) {
var zeroValue T
if v, ok := obj[key].(T); ok && v != zeroValue {
return &v, nil
}
return nil, fmt.Errorf("field %q: value must be set", key)
}