-
Notifications
You must be signed in to change notification settings - Fork 1
/
vpa_operator.py
205 lines (183 loc) · 8.24 KB
/
vpa_operator.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
import kopf
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes import config
import logging
from functools import reduce
logger = logging.getLogger(__name__)
config.load_incluster_config()
VPA_CONFIGS = {}
def get_all_configs():
configs = {}
api = kubernetes.client.CustomObjectsApi()
try:
autovpas = api.list_cluster_custom_object(
group="autoscaling.k8s.io",
version="v1",
plural="autovpaconfigs"
)
configs = {}
for item in autovpas["items"]:
namespace = item["metadata"]["namespace"]
excluded_deployments = deep_get(item, ["spec","excludedDeployments"], [])
resource_policy = deep_get(item, ["spec","resourcePolicy"], False)
if resource_policy:
resource_policy["containerName"] = "*"
resource_policy = { "containerPolicies": [ resource_policy ] }
update_policy = deep_get(item, ["spec","updatePolicy"], {"updateMode":"Off"})
configs[namespace] = {
"excluded_deployments": excluded_deployments,
"resource_policy": resource_policy,
"update_policy": update_policy
}
except ApiException as e:
if e.status == 404:
logger.info("No VPAConfig CRs found")
else:
logger.error(f"Failed to fetch VPAConfig CRs: {e}")
return configs
def update_vpa_configs():
global VPA_CONFIGS
VPA_CONFIGS = get_all_configs()
def filter_resources(namespace, annotations, name, **_):
return namespace in VPA_CONFIGS and name not in VPA_CONFIGS[namespace]["excluded_deployments"] and str2bool(annotations.get("autovpa.autoscaling.k8s.io/enabled", "true"))
def filter_resources_only_namespace(namespace, **_):
return namespace in VPA_CONFIGS
def create_vpa_for_deployment(name, namespace):
api_instance = kubernetes.client.CustomObjectsApi()
config = VPA_CONFIGS[namespace]
vpa_body = {
"apiVersion": "autoscaling.k8s.io/v1",
"kind": "VerticalPodAutoscaler",
"metadata": {
"name": name,
"namespace": namespace,
"annotations": {
"autovpa.autoscaling.k8s.io/deployment": name
}
},
"spec": {
"targetRef": {
"apiVersion": "apps/v1",
"kind": "Deployment",
"name": name
},
"updatePolicy": config["update_policy"],
"resourcePolicy": config["resource_policy"]
}
}
try:
api_instance.create_namespaced_custom_object(
group="autoscaling.k8s.io",
version="v1",
namespace=namespace,
plural="verticalpodautoscalers",
body=vpa_body
)
logger.info(f"VPA created for deployment {name} in namespace {namespace}")
except ApiException as e:
if e.status != 409: # Ignore conflict errors if the VPA already exists
logger.error(f"Failed to create VPA for deployment {name} in namespace {namespace}: {e} \n Request: {vpa_body}")
def delete_vpa_for_deployment(name, namespace):
api_instance = kubernetes.client.CustomObjectsApi()
#check the vpa annotation
try:
api_response = api_instance.get_namespaced_custom_object(
group="autoscaling.k8s.io",
version="v1",
namespace=namespace,
plural="verticalpodautoscalers",
name=name,
)
if deep_get(api_response, ["metadata","annotations","autovpa.autoscaling.k8s.io/deployment"], "") == name:
api_instance.delete_namespaced_custom_object(
group="autoscaling.k8s.io",
version="v1",
namespace=namespace,
plural="verticalpodautoscalers",
name=name,
)
logger.info(f"VPA deleted for deployment {name} in namespace {namespace}")
except ApiException as e:
if e.status != 404:
logger.error(f"Failed to delete VPA for deployment {name} in namespace {namespace}: {e}")
def update_vpa(namespace, new_config):
api_instance = kubernetes.client.CustomObjectsApi()
try:
vpas = api_instance.list_namespaced_custom_object(
group="autoscaling.k8s.io",
version="v1",
namespace=namespace,
plural="verticalpodautoscalers"
)
for vpa in vpas["items"]:
vpa_name = vpa["metadata"]["name"]
vpa["spec"]["updatePolicy"] = new_config["update_policy"]
vpa["spec"]["resourcePolicy"] = new_config["resource_policy"]
api_instance.patch_namespaced_custom_object(
group="autoscaling.k8s.io",
version="v1",
namespace=namespace,
plural="verticalpodautoscalers",
name=vpa_name,
body=vpa
)
logger.info(f"VPA {vpa_name} in namespace {namespace} updated with new configuration")
except ApiException as e:
logger.error(f"Failed to update VPAs in namespace {namespace} with new configuration: {e} \n Request: {vpa}")
@kopf.on.startup()
def configure(settings: kopf.OperatorSettings, **_):
settings.posting.enabled = False
#settings.persistence.finalizer = 'autovpa.autoscaling.k8s.io/finalizer'
update_vpa_configs()
@kopf.on.create('deployments', when=filter_resources)
def create_vpa(body, meta, spec, name, namespace, **_):
create_vpa_for_deployment(name, namespace)
@kopf.on.delete('deployments', when=filter_resources)
def delete_vpa(body, meta, spec, name, namespace, **_):
delete_vpa_for_deployment(name, namespace)
@kopf.on.update('deployments', when=filter_resources_only_namespace)
def update_deployment(body, meta, spec, name, namespace, annotations, **_):
vpa_enabled = str2bool(annotations.get("autovpa.autoscaling.k8s.io/enabled", "true"))
excluded_deployments = VPA_CONFIGS[namespace]["excluded_deployments"]
if namespace in VPA_CONFIGS and name not in excluded_deployments and vpa_enabled:
create_vpa_for_deployment(name, namespace)
else:
delete_vpa_for_deployment(name, namespace)
@kopf.on.create('autovpaconfigs', group='autoscaling.k8s.io')
@kopf.on.update('autovpaconfigs', group='autoscaling.k8s.io')
def handle_vpaconfig_change(spec, name, namespace, **_):
old_config = VPA_CONFIGS.get(namespace, {})
update_vpa_configs()
new_config = VPA_CONFIGS[namespace]
if old_config != new_config:
update_vpa(namespace, new_config)
if namespace in VPA_CONFIGS:
excluded_deployments = VPA_CONFIGS[namespace]["excluded_deployments"]
api_instance = kubernetes.client.AppsV1Api()
deployments = api_instance.list_namespaced_deployment(namespace=namespace)
for deployment in deployments.items:
dep_name = deployment.metadata.name
dep_annotations = deployment.metadata.annotations or {}
vpa_enabled = str2bool(dep_annotations.get("autovpa.autoscaling.k8s.io/enabled", "true"))
if dep_name in excluded_deployments or not vpa_enabled:
delete_vpa_for_deployment(dep_name, namespace)
elif dep_name not in excluded_deployments and vpa_enabled:
create_vpa_for_deployment(dep_name, namespace)
@kopf.on.delete('autovpaconfigs', group='autoscaling.k8s.io')
def handle_vpaconfig_delete(spec, name, namespace, **_):
if namespace in VPA_CONFIGS:
excluded_deployments = VPA_CONFIGS[namespace]["excluded_deployments"]
api_instance = kubernetes.client.AppsV1Api()
deployments = api_instance.list_namespaced_deployment(namespace=namespace)
for deployment in deployments.items:
dep_name = deployment.metadata.name
dep_annotations = deployment.metadata.annotations or {}
vpa_enabled = str2bool(dep_annotations.get("autovpa.autoscaling.k8s.io/enabled", "true"))
if dep_name not in excluded_deployments and vpa_enabled:
delete_vpa_for_deployment(dep_name, namespace)
update_vpa_configs()
def deep_get(dictionary, keys, default=None):
return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys, dictionary)
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")