-
Notifications
You must be signed in to change notification settings - Fork 13
/
scaler.py
1620 lines (1484 loc) · 62.3 KB
/
scaler.py
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
import collections
import datetime
import logging
import re
import time
from typing import Any
from typing import FrozenSet
from typing import List
from typing import Optional
from typing import Pattern
from typing import Tuple
import pykube
import requests
from pykube import CronJob
from pykube import CustomResourceDefinition
from pykube import DaemonSet
from pykube import Deployment
from pykube import HorizontalPodAutoscaler
from pykube import HTTPClient
from pykube import Job
from pykube import Namespace
from pykube import StatefulSet
from pykube.exceptions import HTTPError
from pykube.objects import APIObject
from pykube.objects import NamespacedAPIObject
from pykube.objects import PodDisruptionBudget
from kube_downscaler import helper
from kube_downscaler.helper import matches_time_spec
from kube_downscaler.resources.constraint import KubeDownscalerJobsConstraint
from kube_downscaler.resources.constrainttemplate import ConstraintTemplate
from kube_downscaler.resources.keda import ScaledObject
from kube_downscaler.resources.policy import KubeDownscalerJobsPolicy
from kube_downscaler.resources.rollout import ArgoRollout
from kube_downscaler.resources.stack import Stack
ORIGINAL_REPLICAS_ANNOTATION = "downscaler/original-replicas"
FORCE_UPTIME_ANNOTATION = "downscaler/force-uptime"
FORCE_DOWNTIME_ANNOTATION = "downscaler/force-downtime"
UPSCALE_PERIOD_ANNOTATION = "downscaler/upscale-period"
DOWNSCALE_PERIOD_ANNOTATION = "downscaler/downscale-period"
EXCLUDE_ANNOTATION = "downscaler/exclude"
EXCLUDE_UNTIL_ANNOTATION = "downscaler/exclude-until"
UPTIME_ANNOTATION = "downscaler/uptime"
DOWNTIME_ANNOTATION = "downscaler/downtime"
DOWNTIME_REPLICAS_ANNOTATION = "downscaler/downtime-replicas"
GRACE_PERIOD_ANNOTATION = "downscaler/grace-period"
# GoLang 32-bit signed integer max value + 1. The value was choosen because 2147483647 is the max allowed
# for Deployment/StatefulSet.spec.template.replicas. This value is used to allow
# ScaledObject to support "downscaler/downtime-replcas" annotation
KUBERNETES_MAX_ALLOWED_REPLICAS = 2147483647
RESOURCE_CLASSES = [
Deployment,
StatefulSet,
Stack,
CronJob,
HorizontalPodAutoscaler,
ArgoRollout,
ScaledObject,
DaemonSet,
PodDisruptionBudget,
Job,
]
TIMESTAMP_FORMATS = [
"%Y-%m-%dT%H:%M:%SZ",
"%Y-%m-%dT%H:%M",
"%Y-%m-%d %H:%M",
"%Y-%m-%d",
]
ADMISSION_CONTROLLERS = ["gatekeeper", "kyverno"]
logger = logging.getLogger(__name__)
def parse_time(timestamp: str) -> datetime.datetime:
for fmt in TIMESTAMP_FORMATS:
try:
dt = datetime.datetime.strptime(timestamp, fmt)
except ValueError:
pass
else:
return dt.replace(tzinfo=datetime.timezone.utc)
raise ValueError(
f"time data '{timestamp}' does not match any format ({', '.join(TIMESTAMP_FORMATS)})"
)
# If the argument --upscale-target-only is present, resources from namespaces not in target won't be processed.
# Otherwise all resources from all namespaces will be processed for scaling if the have original_replicas annotation
def define_scope(exclude, original_replicas, upscale_target_only):
if upscale_target_only:
exclude_condition = exclude
else:
exclude_condition = exclude and not original_replicas
return exclude_condition
def is_grace_period_annotation_integer(value):
try:
int(value) # Attempt to convert the string to an integer
return True
except ValueError:
return False
def within_grace_period(
resource,
grace_period: int,
now: datetime.datetime,
deployment_time_annotation: Optional[str] = None,
):
update_time = parse_time(resource.metadata["creationTimestamp"])
grace_period_annotation = resource.annotations.get(GRACE_PERIOD_ANNOTATION, None)
if grace_period_annotation is not None and is_grace_period_annotation_integer(
grace_period_annotation
):
grace_period_annotation_integer = int(grace_period_annotation)
if grace_period_annotation_integer > 0:
if grace_period_annotation_integer <= grace_period:
logger.debug(
f"Grace period annotation found for {resource.kind} {resource.name} in namespace {resource.namespace}. "
f"Since the grace period specified in the annotation is shorter than the global grace period, "
f"the downscaler will use the annotation's grace period for this resource."
)
grace_period = grace_period_annotation_integer
else:
logger.debug(
f"Grace period annotation found for {resource.kind} {resource.name} in namespace {resource.namespace}. "
f"The global grace period is shorter, so the downscaler will use the global grace period for this resource."
)
else:
logger.debug(
f"Grace period annotation found for {resource.kind} {resource.name} in namespace {resource.namespace} "
f"but cannot be a negative integer"
)
if deployment_time_annotation:
annotations = resource.metadata.get("annotations", {})
deployment_time = annotations.get(deployment_time_annotation)
if deployment_time:
try:
update_time = max(update_time, parse_time(deployment_time))
except ValueError as e:
logger.warning(
f"Invalid {deployment_time_annotation} in {resource.namespace}/{resource.name}: {e}"
)
delta = now - update_time
return delta.total_seconds() <= grace_period
def within_grace_period_namespace(
resource: APIObject,
grace_period: int,
now: datetime.datetime,
deployment_time_annotation: Optional[str] = None,
):
update_time = parse_time(resource.metadata["creationTimestamp"])
grace_period_annotation = resource.annotations.get(GRACE_PERIOD_ANNOTATION, None)
if grace_period_annotation is not None and is_grace_period_annotation_integer(
grace_period_annotation
):
grace_period_annotation_integer = int(grace_period_annotation)
if grace_period_annotation_integer > 0:
if grace_period_annotation_integer <= grace_period:
logger.debug(
f"Grace period annotation found for namespace {resource.name}. "
f"Since the grace period specified in the annotation is shorter than the global grace period, "
f"the downscaler will use the annotation's grace period for this resource."
)
grace_period = grace_period_annotation_integer
else:
logger.debug(
f"Grace period annotation found for namespace {resource.name}. "
f"The global grace period is shorter, so the downscaler will use the global grace period for this resource."
)
else:
logger.debug(
f"Grace period annotation found for namespace {resource.name} "
f"but cannot be a negative integer"
)
if deployment_time_annotation:
annotations = resource.metadata.get("annotations", {})
deployment_time = annotations.get(deployment_time_annotation)
if deployment_time:
try:
update_time = max(update_time, parse_time(deployment_time))
except ValueError as e:
logger.warning(
f"Invalid {deployment_time_annotation} in {resource.kind}/{resource.name}: {e}"
)
delta = now - update_time
return delta.total_seconds() <= grace_period
def pods_force_uptime(api, namespace: FrozenSet[str]):
"""Return True if there are any running pods which require the deployments to be scaled back up."""
pods = get_pod_resources(api, namespace)
for pod in pods:
if pod.obj.get("status", {}).get("phase") in ("Succeeded", "Failed"):
continue
if pod.annotations.get(FORCE_UPTIME_ANNOTATION, "").lower() == "true":
logger.info(f"Forced uptime because of {pod.namespace}/{pod.name}")
return True
return False
def get_pod_resources(api, namespaces: FrozenSet[str]):
if len(namespaces) >= 1:
pods = []
for namespace in namespaces:
try:
pods_query_result = pykube.Pod.objects(api).filter(namespace=namespace)
pods += pods_query_result
except requests.HTTPError as e:
if e.response.status_code == 404:
logger.debug(f"No pods found in namespace {namespace} (404)")
if e.response.status_code == 403:
logger.warning(
f"KubeDownscaler is not authorized to access the Namespace {namespace} (403). Please check your RBAC settings if you are using constrained mode. "
f"Ensure that a Role with proper access to the necessary resources and a RoleBinding have been deployed to this Namespace."
f"The RoleBinding should be linked to the KubeDownscaler Service Account."
)
else:
raise e
else:
try:
pods = pykube.Pod.objects(api).filter(namespace=pykube.all)
except requests.HTTPError as e:
if e.response.status_code == 403:
logger.warning(
"KubeDownscaler is not authorized to perform a cluster wide query to retrieve Pods (403)"
)
else:
raise e
return pods
def create_excluded_namespaces_regex(namespaces: FrozenSet[str]):
# Ensure the input is a FrozenSet of strings
if not isinstance(namespaces, FrozenSet):
raise TypeError("namespaces must be of type FrozenSet[str]")
if not all(isinstance(ns, str) for ns in namespaces):
raise TypeError("All elements of namespaces must be strings")
# Escape special regex characters in each namespace name
escaped_namespaces = [re.escape(ns) for ns in namespaces]
# Combine the escaped names into a single alternation pattern
combined_pattern = "|".join(escaped_namespaces)
# Create a regex pattern that matches any string not exactly one of the namespaces
excluded_pattern = f"^(?!{combined_pattern}$).+"
logging.info(
"--namespace arg is not empty the --exclude-namespaces argument was modified to the following regex pattern: "
+ excluded_pattern
)
# Compile and return the regex pattern
return [re.compile(excluded_pattern)]
def get_resources(kind, api, namespaces: FrozenSet[str], excluded_namespaces):
if len(namespaces) >= 1:
resources = []
excluded_namespaces = create_excluded_namespaces_regex(namespaces)
for namespace in namespaces:
try:
resources_inside_namespace = kind.objects(api, namespace=namespace)
resources += resources_inside_namespace
except requests.HTTPError as e:
if e.response.status_code == 404:
logger.debug(
f"No {kind.endpoint} found in namespace {namespace} (404)"
)
if e.response.status_code == 403:
logger.warning(
f"KubeDownscaler is not authorized to access the Namespace {namespace} (403). Please check your RBAC settings if you are using constrained mode. "
f"Ensure that a Role with proper access to the necessary resources and a RoleBinding have been deployed to this Namespace."
f"The RoleBinding should be linked to the KubeDownscaler Service Account."
)
else:
raise e
else:
try:
resources = kind.objects(api, namespace=pykube.all)
except requests.HTTPError as e:
if e.response.status_code == 403:
logger.warning(
f"KubeDownscaler is not authorized to perform a cluster wide query to retrieve {kind.endpoint} (403)"
)
else:
raise e
return resources, excluded_namespaces
def get_resource(kind, api, namespace, resource_name: str):
try:
resource = (
kind.objects(api)
.filter(namespace=namespace)
.get_or_none(name=resource_name)
)
if resource is None:
logger.debug(f"{kind.endpoint} {namespace}/{resource_name} not found")
except requests.HTTPError as e:
resource = None
if e.response.status_code == 404:
logger.debug(
f"{kind} {resource_name} not found in namespace {namespace} (404)"
)
if e.response.status_code == 403:
logger.warning(
f"KubeDownscaler is not authorized to to retrieve {kind} {namespace}/{resource_name} (403)"
)
else:
raise e
return resource
def scale_jobs_without_admission_controller(
plural, admission_controller, constrainted_downscaler
):
return (plural == "jobs" and admission_controller == "") or constrainted_downscaler
def is_stack_deployment(resource: NamespacedAPIObject) -> bool:
if resource.kind == Deployment.kind and resource.version == Deployment.version:
for owner_ref in resource.metadata.get("ownerReferences", []):
if (
owner_ref["apiVersion"] == Stack.version
and owner_ref["kind"] == Stack.kind
):
return True
return False
def ignore_if_labels_dont_match(
resource: NamespacedAPIObject, labels: FrozenSet[Pattern]
) -> bool:
# For backwards compatibility, if there is no label filter, we don't ignore anything
if not any(label.pattern for label in labels):
return False
# Ignore resources whose labels do not match the set of input labels
resource_labels = [f"{key}={value}" for key, value in resource.labels.items()]
ignore = True
for label_pattern in labels:
if not ignore:
break
ignore = not any(
[
label_pattern.fullmatch(resource_label)
for resource_label in resource_labels
]
)
return ignore
def ignore_resource(resource: NamespacedAPIObject, now: datetime.datetime) -> bool:
# Ignore deployments managed by stacks, we will downscale the stack instead
if is_stack_deployment(resource):
return True
# any value different from "false" will ignore the resource (to be on the safe side)
if resource.annotations.get(EXCLUDE_ANNOTATION, "false").lower() != "false":
return True
exclude_until = resource.annotations.get(EXCLUDE_UNTIL_ANNOTATION)
if exclude_until:
try:
until_ts = parse_time(exclude_until)
except ValueError as e:
logger.warning(
f"Invalid annotation value for '{EXCLUDE_UNTIL_ANNOTATION}' on {resource.namespace}/{resource.name}: {e}"
)
# we will ignore the invalid timestamp and treat the resource as not excluded
return False
if now < until_ts:
return True
return False
def get_replicas(
resource: NamespacedAPIObject, original_replicas: Optional[int], uptime: str
) -> int:
if resource.kind in ["CronJob", "Job"]:
suspended = resource.obj["spec"]["suspend"]
replicas = 0 if suspended else 1
state = "suspended" if suspended else "not suspended"
original_state = "suspended" if original_replicas == 0 else "not suspended"
logger.debug(
f"{resource.kind} {resource.namespace}/{resource.name} is {state} (original: {original_state}, uptime: {uptime})"
)
elif resource.kind == "PodDisruptionBudget":
if "minAvailable" in resource.obj["spec"]:
replicas = resource.obj["spec"]["minAvailable"]
logger.debug(
f"{resource.kind} {resource.namespace}/{resource.name} has {replicas} minAvailable (original: {original_replicas}, uptime: {uptime})"
)
elif "maxUnavailable" in resource.obj["spec"]:
replicas = resource.obj["spec"]["maxUnavailable"]
logger.debug(
f"{resource.kind} {resource.namespace}/{resource.name} has {replicas} maxUnavailable (original: {original_replicas}, uptime: {uptime})"
)
else:
replicas = 0
logger.debug(
f"{resource.kind} {resource.namespace}/{resource.name} has neither minAvailable nor maxUnavailable (original: {original_replicas}, uptime: {uptime})"
)
elif resource.kind == "HorizontalPodAutoscaler":
replicas = resource.obj["spec"]["minReplicas"]
logger.debug(
f"{resource.kind} {resource.namespace}/{resource.name} has {replicas} minReplicas (original: {original_replicas}, uptime: {uptime})"
)
elif resource.kind == "DaemonSet":
if "nodeSelector" in resource.obj["spec"]["template"]["spec"]:
kube_downscaler_node_selector_dict = resource.obj["spec"]["template"][
"spec"
]["nodeSelector"]
else:
kube_downscaler_node_selector_dict = None
if kube_downscaler_node_selector_dict is None:
suspended = False
else:
if "kube-downscaler-non-existent" in kube_downscaler_node_selector_dict:
suspended = True
else:
suspended = False
replicas = 0 if suspended else 1
state = "suspended" if suspended else "not suspended"
original_state = "suspended" if original_replicas == 0 else "not suspended"
logger.debug(
f"{resource.kind} {resource.namespace}/{resource.name} is {state} (original: {original_state}, uptime: {uptime})"
)
elif resource.kind == "ScaledObject":
replicas = resource.replicas
if replicas == KUBERNETES_MAX_ALLOWED_REPLICAS + 1:
logger.debug(
f"{resource.kind} {resource.namespace}/{resource.name} is not suspended (uptime: {uptime})"
)
else:
logger.debug(
f"{resource.kind} {resource.namespace}/{resource.name} is suspended (uptime: {uptime})"
)
else:
replicas = resource.replicas
logger.debug(
f"{resource.kind} {resource.namespace}/{resource.name} has {replicas} replicas (original: {original_replicas}, uptime: {uptime})"
)
return replicas
def scale_up_jobs(
api,
resource: NamespacedAPIObject,
uptime,
downtime,
admission_controller: str,
dry_run: bool,
enable_events: bool,
) -> APIObject:
policy: APIObject = None
operation = "no_scale"
event_message = "Scaling up jobs"
if admission_controller == "gatekeeper":
policy = KubeDownscalerJobsConstraint.objects(api).get_or_none(
name=resource.name
)
if policy is not None:
operation = "scale_up"
logger.info(
f"Unsuspending jobs for {resource.kind}/{resource.name} (uptime: {uptime}, downtime: {downtime})"
)
else:
operation = "no_scale"
if admission_controller == "kyverno":
policy_name = "kube-downscaler-jobs-policy"
policy = (
KubeDownscalerJobsPolicy.objects(api)
.filter(namespace=resource.name)
.get_or_none(name=policy_name)
)
if policy is not None:
operation = "scale_up"
logger.info(
f"Unsuspending jobs for {resource.kind}/{resource.name} (uptime: {uptime}, downtime: {downtime})"
)
else:
operation = "no_scale"
if enable_events:
helper.add_event(
resource,
event_message,
"ScaleUp",
"Normal",
dry_run,
)
return policy, operation
def scale_down_jobs(
api,
resource: NamespacedAPIObject,
uptime,
downtime,
admission_controller: str,
excluded_jobs: List[str],
matching_labels: FrozenSet[Pattern],
dry_run: bool,
enable_events: bool,
) -> Tuple[Optional[Any], str]:
policy: APIObject = None
operation = "no_scale"
obj = None
event_message = "Scaling down jobs"
if admission_controller == "gatekeeper":
policy = KubeDownscalerJobsConstraint.objects(api).get_or_none(
name=resource.name
)
if policy is None:
obj = KubeDownscalerJobsConstraint.create_job_constraint(resource.name)
operation = "scale_down"
logger.info(
f"Suspending jobs for {resource.kind}/{resource.name} (uptime: {uptime}, downtime: {downtime})"
)
else:
obj = policy
operation = "no_scale"
if admission_controller == "kyverno":
# if the matching_labels FrozenSet has an empty string as the first element, we create a different kyverno policy
first_element = next(iter(matching_labels), "")
if first_element == "":
has_matching_labels_arg = False
else:
has_matching_labels_arg = True
policy_name = "kube-downscaler-jobs-policy"
policy = (
KubeDownscalerJobsPolicy.objects(api)
.filter(namespace=resource.name)
.get_or_none(name=policy_name)
)
if policy is None:
if has_matching_labels_arg:
obj = KubeDownscalerJobsPolicy.create_job_policy_with_matching_labels(
resource.name, matching_labels
)
else:
obj = KubeDownscalerJobsPolicy.create_job_policy(resource.name)
if len(excluded_jobs) > 0:
obj = KubeDownscalerJobsPolicy.append_excluded_jobs_condition(
obj, excluded_jobs, has_matching_labels_arg
)
operation = "scale_down"
logger.info(
f"Suspending jobs for {resource.kind}/{resource.name} (uptime: {uptime}, downtime: {downtime})"
)
else:
if has_matching_labels_arg and policy.type == "with-matching-labels":
obj = policy
operation = "no_scale"
logging.debug(
"No need to update kyverno policy, correctly found a policy with matching label"
)
elif has_matching_labels_arg and policy.type != "with-matching-labels":
operation = "kyverno_update"
obj = KubeDownscalerJobsPolicy.create_job_policy_with_matching_labels(
resource.name, matching_labels
)
if len(excluded_jobs) > 0:
obj = KubeDownscalerJobsPolicy.append_excluded_jobs_condition(
obj, excluded_jobs, has_matching_labels_arg
)
logging.debug(
"Update needed for kyverno policy, found a policy without matching label but need a policy with matching label"
)
elif (
not has_matching_labels_arg and policy.type == "without-matching-labels"
):
obj = policy
operation = "no_scale"
logging.debug(
"No need to update kyverno policy, correctly found a policy without matching label"
)
elif (
not has_matching_labels_arg and policy.type != "without-matching-labels"
):
operation = "kyverno_update"
obj = KubeDownscalerJobsPolicy.create_job_policy(resource.name)
if len(excluded_jobs) > 0:
obj = KubeDownscalerJobsPolicy.append_excluded_jobs_condition(
obj, excluded_jobs, has_matching_labels_arg
)
logging.debug(
"Update needed for kyverno policy, found a policy with matching label but need a policy without matching label"
)
else:
obj = policy
operation = "no_scale"
logging.debug(
"No Update Needed For Policy, all conditions were not met"
)
if enable_events:
helper.add_event(
resource,
event_message,
"ScaleDown",
"Normal",
dry_run,
)
return obj, operation
def scale_up(
resource: NamespacedAPIObject,
replicas: int,
original_replicas: int,
uptime,
downtime,
dry_run: bool,
enable_events: bool,
):
event_message = "Scaling up replicas"
if resource.kind == "DaemonSet":
resource.obj["spec"]["template"]["spec"]["nodeSelector"][
"kube-downscaler-non-existent"
] = None
logger.info(
f"Unsuspending {resource.kind} {resource.namespace}/{resource.name} (uptime: {uptime}, downtime: {downtime})"
)
event_message = "Unsuspending DaemonSet"
elif resource.kind in ["CronJob", "Job"]:
resource.obj["spec"]["suspend"] = False
logger.info(
f"Unsuspending {resource.kind} {resource.namespace}/{resource.name} (uptime: {uptime}, downtime: {downtime})"
)
event_message = f"Unsuspending {resource.kind}"
elif resource.kind == "PodDisruptionBudget":
if "minAvailable" in resource.obj["spec"]:
resource.obj["spec"]["minAvailable"] = original_replicas
logger.info(
f"Scaling up {resource.kind} {resource.namespace}/{resource.name} from {replicas} to {original_replicas} minAvailable (uptime: {uptime}, downtime: {downtime})"
)
elif "maxUnavailable" in resource.obj["spec"]:
resource.obj["spec"]["maxUnavailable"] = original_replicas
logger.info(
f"Scaling up {resource.kind} {resource.namespace}/{resource.name} from {replicas} to {original_replicas} maxUnavailable (uptime: {uptime}, downtime: {downtime})"
)
elif resource.kind == "HorizontalPodAutoscaler":
resource.obj["spec"]["minReplicas"] = original_replicas
logger.info(
f"Scaling up {resource.kind} {resource.namespace}/{resource.name} from {replicas} to {original_replicas} minReplicas (uptime: {uptime}, downtime: {downtime})"
)
elif resource.kind == "Rollout":
resource.obj["spec"]["replicas"] = original_replicas
logger.info(
f"Scaling up {resource.kind} {resource.namespace}/{resource.name} from {replicas} to {original_replicas} replicas (uptime: {uptime}, downtime: {downtime})"
)
elif resource.kind == "ScaledObject":
if ScaledObject.last_keda_pause_annotation_if_present in resource.annotations:
if (
resource.annotations[ScaledObject.last_keda_pause_annotation_if_present]
is not None
):
paused_replicas = resource.annotations[
ScaledObject.last_keda_pause_annotation_if_present
]
resource.annotations[ScaledObject.keda_pause_annotation] = (
paused_replicas
)
resource.annotations[
ScaledObject.last_keda_pause_annotation_if_present
] = None
else:
resource.annotations[ScaledObject.keda_pause_annotation] = None
logger.info(
f"Unpausing {resource.kind} {resource.namespace}/{resource.name} (uptime: {uptime}, downtime: {downtime})"
)
else:
resource.replicas = original_replicas
logger.info(
f"Scaling up {resource.kind} {resource.namespace}/{resource.name} from {replicas} to {original_replicas} replicas (uptime: {uptime}, downtime: {downtime})"
)
if enable_events:
helper.add_event(
resource,
event_message,
"ScaleUp",
"Normal",
dry_run,
)
resource.annotations[ORIGINAL_REPLICAS_ANNOTATION] = None
def scale_down(
resource: NamespacedAPIObject,
replicas: int,
target_replicas: int,
uptime,
downtime,
dry_run: bool,
enable_events: bool,
):
event_message = "Scaling down replicas"
if resource.kind == "DaemonSet":
if "nodeSelector" not in resource.obj["spec"]["template"]["spec"]:
resource.obj["spec"]["template"]["spec"]["nodeSelector"] = {}
resource.obj["spec"]["template"]["spec"]["nodeSelector"][
"kube-downscaler-non-existent"
] = "true"
logger.info(
f"Suspending {resource.kind} {resource.namespace}/{resource.name} (uptime: {uptime}, downtime: {downtime})"
)
event_message = "Suspending DaemonSet"
elif resource.kind in ["CronJob", "Job"]:
resource.obj["spec"]["suspend"] = True
logger.info(
f"Suspending {resource.kind} {resource.namespace}/{resource.name} (uptime: {uptime}, downtime: {downtime})"
)
event_message = f"Suspending {resource.kind}"
elif resource.kind == "PodDisruptionBudget":
if "minAvailable" in resource.obj["spec"]:
resource.obj["spec"]["minAvailable"] = target_replicas
logger.info(
f"Scaling down {resource.kind} {resource.namespace}/{resource.name} from {replicas} to {target_replicas} minAvailable (uptime: {uptime}, downtime: {downtime})"
)
elif "maxUnavailable" in resource.obj["spec"]:
resource.obj["spec"]["maxUnavailable"] = target_replicas
logger.info(
f"Scaling down {resource.kind} {resource.namespace}/{resource.name} from {replicas} to {target_replicas} maxUnavailable (uptime: {uptime}, downtime: {downtime})"
)
elif resource.kind == "HorizontalPodAutoscaler":
resource.obj["spec"]["minReplicas"] = target_replicas
logger.info(
f"Scaling down {resource.kind} {resource.namespace}/{resource.name} from {replicas} to {target_replicas} minReplicas (uptime: {uptime}, downtime: {downtime})"
)
elif resource.kind == "Rollout":
resource.obj["spec"]["replicas"] = target_replicas
logger.info(
f"Scaling down {resource.kind} {resource.namespace}/{resource.name} from {replicas} to {target_replicas} replicas (uptime: {uptime}, downtime: {downtime})"
)
elif resource.kind == "ScaledObject":
if ScaledObject.keda_pause_annotation in resource.annotations:
if resource.annotations[ScaledObject.keda_pause_annotation] is not None:
paused_replicas = resource.annotations[
ScaledObject.keda_pause_annotation
]
resource.annotations[
ScaledObject.last_keda_pause_annotation_if_present
] = paused_replicas
resource.annotations[ScaledObject.keda_pause_annotation] = str(target_replicas)
logger.info(
f"Pausing {resource.kind} {resource.namespace}/{resource.name} (uptime: {uptime}, downtime: {downtime})"
)
event_message = "Pausing KEDA ScaledObject"
else:
resource.replicas = target_replicas
logger.info(
f"Scaling down {resource.kind} {resource.namespace}/{resource.name} from {replicas} to {target_replicas} replicas (uptime: {uptime}, downtime: {downtime})"
)
if enable_events:
helper.add_event(
resource,
event_message,
"ScaleDown",
"Normal",
dry_run,
)
resource.annotations[ORIGINAL_REPLICAS_ANNOTATION] = str(replicas)
def get_annotation_value_as_int(
resource: NamespacedAPIObject, annotation_name: str
) -> Optional[int]:
value = resource.annotations.get(annotation_name)
if value is None:
return None
try:
return int(value)
except ValueError as e:
raise ValueError(
f"Could not read annotation '{annotation_name}' as integer: {e}"
)
def autoscale_jobs_for_namespace(
api,
resource: NamespacedAPIObject, # resource here is a namespace object
upscale_period: str,
downscale_period: str,
default_uptime: str,
default_downtime: str,
forced_uptime: bool,
forced_downtime: bool,
matching_labels: FrozenSet[Pattern],
dry_run: bool,
now: datetime.datetime,
grace_period: int,
excluded_jobs: List[str],
admission_controller: str,
deployment_time_annotation: Optional[str] = None,
namespace_excluded: bool = False,
enable_events: bool = False,
):
try:
exclude = namespace_excluded
if exclude:
logger.debug(
f"{resource.kind} {resource.name} was excluded from downscaling jobs"
)
else:
ignore = False
is_uptime = True
upscale_period = resource.annotations.get(
UPSCALE_PERIOD_ANNOTATION, upscale_period
)
downscale_period = resource.annotations.get(
DOWNSCALE_PERIOD_ANNOTATION, downscale_period
)
if forced_uptime or exclude:
uptime = "forced"
downtime = "ignored"
is_uptime = True
elif forced_downtime and not exclude:
uptime = "ignored"
downtime = "forced"
is_uptime = False
elif upscale_period != "never" or downscale_period != "never":
uptime = upscale_period
downtime = downscale_period
if matches_time_spec(now, uptime) and matches_time_spec(now, downtime):
logger.debug("Upscale and downscale periods overlap, do nothing")
ignore = True
elif matches_time_spec(now, uptime):
is_uptime = True
elif matches_time_spec(now, downtime):
is_uptime = False
else:
ignore = True
logger.debug(
f"Periods checked: upscale={upscale_period}, downscale={downscale_period}, ignore={ignore}, is_uptime={is_uptime}"
)
else:
uptime = resource.annotations.get(UPTIME_ANNOTATION, default_uptime)
downtime = resource.annotations.get(
DOWNTIME_ANNOTATION, default_downtime
)
is_uptime = matches_time_spec(now, uptime) and not matches_time_spec(
now, downtime
)
update_needed = False
if not ignore and is_uptime:
policy, operation = scale_up_jobs(
api,
resource,
uptime,
downtime,
admission_controller,
dry_run=dry_run,
enable_events=enable_events,
)
update_needed = True
elif not ignore and not is_uptime:
if within_grace_period_namespace(
resource, grace_period, now, deployment_time_annotation
):
logger.info(
f"{resource.kind}/{resource.name} within grace period ({grace_period}s), not scaling down jobs (yet)"
)
else:
policy, operation = scale_down_jobs(
api,
resource,
uptime,
downtime,
admission_controller,
excluded_jobs,
matching_labels,
dry_run=dry_run,
enable_events=enable_events,
)
update_needed = True
if update_needed:
if dry_run:
logger.info(
f"**DRY-RUN**: would update {policy.kind}/{policy.name} for jobs scaling inside {resource.kind}/{resource.name}"
)
else:
if (
operation == "scale_down"
and admission_controller == "gatekeeper"
):
logger.debug("Creating KubeDownscalerJobsConstraint")
KubeDownscalerJobsConstraint(api, policy).create()
elif (
operation == "scale_down" and admission_controller == "kyverno"
):
logger.debug("Creating KubeDownscalerJobsPolicy")
KubeDownscalerJobsPolicy(api, policy).create()
elif operation == "scale_up":
policy.delete()
elif operation == "kyverno_update":
KubeDownscalerJobsPolicy(api, policy).update()
logger.debug("Kyverno Policy Correctly Updated")
elif operation == "no_scale":
pass
else:
logging.error(
f"there was an error scaling scaling inside {resource.kind}/{resource.name}"
)
except Exception as e:
logger.exception(f"Failed to process {resource.kind} {resource.name}: {e}")
def autoscale_resource(
resource: NamespacedAPIObject,
upscale_period: str,
downscale_period: str,
default_uptime: str,
default_downtime: str,
forced_uptime: bool,
forced_downtime: bool,
upscale_target_only: bool,
max_retries_on_conflict: int,
api: HTTPClient,
kind: NamespacedAPIObject,
dry_run: bool,
now: datetime.datetime,
grace_period: int = 0,
downtime_replicas: int = 0,
namespace_excluded=False,
deployment_time_annotation: Optional[str] = None,
enable_events: bool = False,
matching_labels: FrozenSet[Pattern] = frozenset(),
):
try:
exclude = (
namespace_excluded
or ignore_if_labels_dont_match(resource, matching_labels)
or ignore_resource(resource, now)
)
original_replicas = get_annotation_value_as_int(
resource, ORIGINAL_REPLICAS_ANNOTATION
)
downtime_replicas_from_annotation = get_annotation_value_as_int(
resource, DOWNTIME_REPLICAS_ANNOTATION
)
if downtime_replicas_from_annotation is not None:
downtime_replicas = downtime_replicas_from_annotation
exclude_condition = define_scope(
exclude, original_replicas, upscale_target_only
)
if exclude_condition:
logger.debug(
f"{resource.kind} {resource.namespace}/{resource.name} was excluded"
)
else:
ignore = False
is_uptime = True
upscale_period = resource.annotations.get(
UPSCALE_PERIOD_ANNOTATION, upscale_period
)
downscale_period = resource.annotations.get(
DOWNSCALE_PERIOD_ANNOTATION, downscale_period
)
if forced_uptime or (exclude and original_replicas):