Debian Codegraph @

ansible_collections/kubernetes/core/plugins/module_utils/apply.py

raw symbols SCIP
1 # Copyright [2017] [Red Hat, Inc.]
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15
16 from __future__ import absolute_import, division, print_function
17
18 __metaclass__ = type
19
20 import json
21 from collections import OrderedDict
22
23 from ansible.module_utils.common.dict_transformations import dict_merge
24 from ansible_collections.kubernetes.core.plugins.module_utils.exceptions import (
25 ApplyException,
26 )
27 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
28 gather_versions,
29 )
30 from ansible_collections.kubernetes.core.plugins.module_utils.version import (
31 LooseVersion,
32 )
33
34 try:
35 from kubernetes.dynamic.exceptions import NotFoundError
36 except ImportError:
37 pass
38
39
40 LAST_APPLIED_CONFIG_ANNOTATION = "kubectl.kubernetes.io/last-applied-configuration"
41
42 POD_SPEC_SUFFIXES = {
43 "containers": "name",
44 "initContainers": "name",
45 "ephemeralContainers": "name",
46 "volumes": "name",
47 "imagePullSecrets": "name",
48 "containers.volumeMounts": "mountPath",
49 "containers.volumeDevices": "devicePath",
50 "containers.env": "name",
51 "containers.ports": "containerPort",
52 "initContainers.volumeMounts": "mountPath",
53 "initContainers.volumeDevices": "devicePath",
54 "initContainers.env": "name",
55 "initContainers.ports": "containerPort",
56 "ephemeralContainers.volumeMounts": "mountPath",
57 "ephemeralContainers.volumeDevices": "devicePath",
58 "ephemeralContainers.env": "name",
59 "ephemeralContainers.ports": "containerPort",
60 }
61
62 POD_SPEC_PREFIXES = [
63 "Pod.spec",
64 "Deployment.spec.template.spec",
65 "DaemonSet.spec.template.spec",
66 "StatefulSet.spec.template.spec",
67 "Job.spec.template.spec",
68 "Cronjob.spec.jobTemplate.spec.template.spec",
69 ]
70
71 # patch merge keys taken from generated.proto files under
72 # staging/src/k8s.io/api in kubernetes/kubernetes
73 STRATEGIC_MERGE_PATCH_KEYS = {
74 "Service.spec.ports": "port",
75 "ServiceAccount.secrets": "name",
76 "ValidatingWebhookConfiguration.webhooks": "name",
77 "MutatingWebhookConfiguration.webhooks": "name",
78 }
79
80 STRATEGIC_MERGE_PATCH_KEYS.update(
81 {
82 "%s.%s" % (prefix, key): value
83 for prefix in POD_SPEC_PREFIXES
84 for key, value in POD_SPEC_SUFFIXES.items()
85 }
86 )
87
88
89 def annotate(desired):
90 return dict(
91 metadata=dict(
92 annotations={
93 LAST_APPLIED_CONFIG_ANNOTATION: json.dumps(
94 desired, separators=(",", ":"), indent=None, sort_keys=True
95 )
96 }
97 )
98 )
99
100
101 def apply_patch(actual, desired):
102 last_applied = (
103 actual["metadata"].get("annotations", {}).get(LAST_APPLIED_CONFIG_ANNOTATION)
104 )
105
106 if last_applied:
107 # ensure that last_applied doesn't come back as a dict of unicode key/value pairs
108 # json.loads can be used if we stop supporting python 2
109 last_applied = json.loads(last_applied)
110 patch = merge(
111 dict_merge(last_applied, annotate(last_applied)),
112 dict_merge(desired, annotate(desired)),
113 actual,
114 )
115 if patch:
116 return actual, patch
117 else:
118 return actual, actual
119 else:
120 return actual, dict_merge(desired, annotate(desired))
121
122
123 def apply_object(resource, definition, server_side=False):
124 try:
125 actual = resource.get(
126 name=definition["metadata"]["name"],
127 namespace=definition["metadata"].get("namespace"),
128 )
129 if server_side:
130 return actual, None
131 except NotFoundError:
132 return None, dict_merge(definition, annotate(definition))
133 return apply_patch(actual.to_dict(), definition)
134
135
136 def k8s_apply(resource, definition, **kwargs):
137 existing, desired = apply_object(resource, definition)
138 server_side = kwargs.get("server_side", False)
139 if server_side:
140 versions = gather_versions()
141 body = definition
142 if LooseVersion(versions["kubernetes"]) < LooseVersion("25.0.0"):
143 body = json.dumps(definition).encode()
144 # server_side_apply is forces content_type to 'application/apply-patch+yaml'
145 return resource.server_side_apply(
146 body=body,
147 name=definition["metadata"]["name"],
148 namespace=definition["metadata"].get("namespace"),
149 force_conflicts=kwargs.get("force_conflicts"),
150 field_manager=kwargs.get("field_manager"),
151 dry_run=kwargs.get("dry_run"),
152 serialize=kwargs.get("serialize"),
153 )
154 if not existing:
155 return resource.create(
156 body=desired, namespace=definition["metadata"].get("namespace"), **kwargs
157 )
158 if existing == desired:
159 return resource.get(
160 name=definition["metadata"]["name"],
161 namespace=definition["metadata"].get("namespace"),
162 **kwargs
163 )
164 return resource.patch(
165 body=desired,
166 name=definition["metadata"]["name"],
167 namespace=definition["metadata"].get("namespace"),
168 content_type="application/merge-patch+json",
169 **kwargs
170 )
171
172
173 # The patch is the difference from actual to desired without deletions, plus deletions
174 # from last_applied to desired. To find it, we compute deletions, which are the deletions from
175 # last_applied to desired, and delta, which is the difference from actual to desired without
176 # deletions, and then apply delta to deletions as a patch, which should be strictly additive.
177 def merge(last_applied, desired, actual, position=None):
178 deletions = get_deletions(last_applied, desired)
179 delta = get_delta(last_applied, actual, desired, position or desired["kind"])
180 return dict_merge(deletions, delta)
181
182
183 def list_to_dict(lst, key, position):
184 result = OrderedDict()
185 for item in lst:
186 try:
187 result[item[key]] = item
188 except KeyError:
189 raise ApplyException(
190 "Expected key '%s' not found in position %s" % (key, position)
191 )
192 return result
193
194
195 # list_merge applies a strategic merge to a set of lists if the patchMergeKey is known
196 # each item in the list is compared based on the patchMergeKey - if two values with the
197 # same patchMergeKey differ, we take the keys that are in last applied, compare the
198 # actual and desired for those keys, and update if any differ
199 def list_merge(last_applied, actual, desired, position):
200 result = list()
201 if position in STRATEGIC_MERGE_PATCH_KEYS and last_applied:
202 patch_merge_key = STRATEGIC_MERGE_PATCH_KEYS[position]
203 last_applied_dict = list_to_dict(last_applied, patch_merge_key, position)
204 actual_dict = list_to_dict(actual, patch_merge_key, position)
205 desired_dict = list_to_dict(desired, patch_merge_key, position)
206 for key in desired_dict:
207 if key not in actual_dict or key not in last_applied_dict:
208 result.append(desired_dict[key])
209 else:
210 patch = merge(
211 last_applied_dict[key],
212 desired_dict[key],
213 actual_dict[key],
214 position,
215 )
216 result.append(dict_merge(actual_dict[key], patch))
217 for key in actual_dict:
218 if key not in desired_dict and key not in last_applied_dict:
219 result.append(actual_dict[key])
220 return result
221 else:
222 return desired
223
224
225 def recursive_list_diff(list1, list2, position=None):
226 result = (list(), list())
227 if position in STRATEGIC_MERGE_PATCH_KEYS:
228 patch_merge_key = STRATEGIC_MERGE_PATCH_KEYS[position]
229 dict1 = list_to_dict(list1, patch_merge_key, position)
230 dict2 = list_to_dict(list2, patch_merge_key, position)
231 dict1_keys = set(dict1.keys())
232 dict2_keys = set(dict2.keys())
233 for key in dict1_keys - dict2_keys:
234 result[0].append(dict1[key])
235 for key in dict2_keys - dict1_keys:
236 result[1].append(dict2[key])
237 for key in dict1_keys & dict2_keys:
238 diff = recursive_diff(dict1[key], dict2[key], position)
239 if diff:
240 # reinsert patch merge key to relate changes in other keys to
241 # a specific list element
242 diff[0].update({patch_merge_key: dict1[key][patch_merge_key]})
243 diff[1].update({patch_merge_key: dict2[key][patch_merge_key]})
244 result[0].append(diff[0])
245 result[1].append(diff[1])
246 if result[0] or result[1]:
247 return result
248 elif list1 != list2:
249 return (list1, list2)
250 return None
251
252
253 def recursive_diff(dict1, dict2, position=None):
254 if not position:
255 if "kind" in dict1 and dict1.get("kind") == dict2.get("kind"):
256 position = dict1["kind"]
257 left = dict((k, v) for (k, v) in dict1.items() if k not in dict2)
258 right = dict((k, v) for (k, v) in dict2.items() if k not in dict1)
259 for k in set(dict1.keys()) & set(dict2.keys()):
260 if position:
261 this_position = "%s.%s" % (position, k)
262 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
263 result = recursive_diff(dict1[k], dict2[k], this_position)
264 if result:
265 left[k] = result[0]
266 right[k] = result[1]
267 elif isinstance(dict1[k], list) and isinstance(dict2[k], list):
268 result = recursive_list_diff(dict1[k], dict2[k], this_position)
269 if result:
270 left[k] = result[0]
271 right[k] = result[1]
272 elif dict1[k] != dict2[k]:
273 left[k] = dict1[k]
274 right[k] = dict2[k]
275 if left or right:
276 return left, right
277 else:
278 return None
279
280
281 def get_deletions(last_applied, desired):
282 patch = {}
283 for k, last_applied_value in last_applied.items():
284 desired_value = desired.get(k)
285 if isinstance(last_applied_value, dict) and isinstance(desired_value, dict):
286 p = get_deletions(last_applied_value, desired_value)
287 if p:
288 patch[k] = p
289 elif last_applied_value != desired_value:
290 patch[k] = desired_value
291 return patch
292
293
294 def get_delta(last_applied, actual, desired, position=None):
295 patch = {}
296
297 for k, desired_value in desired.items():
298 if position:
299 this_position = "%s.%s" % (position, k)
300 actual_value = actual.get(k)
301 if actual_value is None:
302 patch[k] = desired_value
303 elif isinstance(desired_value, dict):
304 p = get_delta(
305 last_applied.get(k, {}), actual_value, desired_value, this_position
306 )
307 if p:
308 patch[k] = p
309 elif isinstance(desired_value, list):
310 p = list_merge(
311 last_applied.get(k, []), actual_value, desired_value, this_position
312 )
313 if p:
314 patch[k] = [item for item in p if item is not None]
315 elif actual_value != desired_value:
316 patch[k] = desired_value
317 return patch