-
Notifications
You must be signed in to change notification settings - Fork 84
/
openshift_resource.py
416 lines (352 loc) · 14.5 KB
/
openshift_resource.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
import copy
import hashlib
import json
import semver
import datetime
import re
from threading import Lock
class ResourceKeyExistsError(Exception):
pass
class ConstructResourceError(Exception):
def __init__(self, msg):
super(ConstructResourceError, self).__init__(
"error constructing openshift resource: " + str(msg)
)
class OpenshiftResource(object):
def __init__(self, body, integration, integration_version,
error_details='', caller_name=None):
self.body = body
self.integration = integration
self.integration_version = integration_version
self.error_details = error_details
self.caller_name = caller_name
self.verify_valid_k8s_object()
def __eq__(self, other):
return self.obj_intersect_equal(self.body, other.body)
def obj_intersect_equal(self, obj1, obj2):
if obj1.__class__ != obj2.__class__:
return False
if isinstance(obj1, dict):
for obj1_k, obj1_v in obj1.items():
obj2_v = obj2.get(obj1_k, None)
if obj2_v is None:
if obj1_v not in [None, '']:
return False
if self.ignorable_field(obj1_k):
pass
elif self.ignorable_key_value_pair(obj1_k, obj1_v):
pass
elif obj1_k == 'cpu':
equal = self.cpu_equal(obj1_v, obj2_v)
if not equal:
return False
elif obj1_k == 'apiVersion':
valid = self.api_version_mutation(obj1_v, obj2_v)
if not valid:
return False
elif obj1_k == 'imagePullSecrets':
# remove default pull secrets added by k8s
obj2_v_clean = [s for s in obj2_v
if '-dockercfg-' not in s['name']]
if not self.obj_intersect_equal(obj1_v, obj2_v_clean):
return False
elif not self.obj_intersect_equal(obj1_v, obj2_v):
return False
elif isinstance(obj1, list):
if len(obj1) != len(obj2):
return False
for i in range(len(obj1)):
if not self.obj_intersect_equal(obj1[i], obj2[i]):
return False
elif obj1 != obj2:
return False
return True
@staticmethod
def ignorable_field(val):
ignorable_fields = [
'kubectl.kubernetes.io/last-applied-configuration',
'creationTimestamp',
'resourceVersion',
'generation',
'selfLink',
'uid',
'status',
'fieldRef'
]
if val in ignorable_fields:
return True
return False
@staticmethod
def ignorable_key_value_pair(key, val):
ignorable_key_value_pair = {
'annotations': None,
'divisor': '0'
}
if key in ignorable_key_value_pair and \
ignorable_key_value_pair[key] == val:
return True
return False
@staticmethod
def cpu_equal(val1, val2):
# normalize both to string
try:
val1 = f"{int(float(val1) * 1000)}m"
except Exception:
pass
try:
val2 = f"{int(float(val2) * 1000)}m"
except Exception:
pass
return val1 == val2
@staticmethod
def api_version_mutation(val1, val2):
# required temporarily, pending response on
# https://redhat.service-now.com/surl.do?n=INC1224482
if val1 == 'apps/v1' and val2 == 'extensions/v1beta1':
return True
if val1 == 'extensions/v1beta1' and val2 == 'apps/v1':
return True
if val1 == 'networking.k8s.io/v1' and val2 == 'extensions/v1beta1':
return True
return val1 == val2
@property
def name(self):
return self.body['metadata']['name']
@property
def kind(self):
return self.body['kind']
@property
def caller(self):
try:
return self.caller_name or \
self.body['metadata']['annotations']['qontract.caller_name']
except KeyError:
return None
def verify_valid_k8s_object(self):
try:
self.name
self.kind
except (KeyError, TypeError) as e:
msg = "resource invalid data ({}). details: {}".format(
e.__class__.__name__, self.error_details)
raise ConstructResourceError(msg)
r = '[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*'
if self.kind not in \
['Role', 'RoleBinding', 'ClusterRole', 'ClusterRoleBinding'] \
and not re.search(r'^{}$'.format(r), self.name):
msg = f"The {self.kind} \"{self.name}\" is invalid: " + \
f"metadata.name: Invalid value: \"{self.name}\": " + \
f"a DNS-1123 subdomain must consist of lower case " + \
f"alphanumeric characters, '-' or '.', and must start " + \
f"and end with an alphanumeric character (e.g. " + \
f"'example.com', regex used for validation is '{r}')"
raise ConstructResourceError(msg)
def has_qontract_annotations(self):
try:
annotations = self.body['metadata']['annotations']
assert annotations['qontract.integration'] == self.integration
integration_version = annotations['qontract.integration_version']
assert semver.parse(integration_version)['major'] == \
semver.parse(self.integration_version)['major']
assert annotations['qontract.sha256sum'] is not None
except KeyError:
return False
except AssertionError:
return False
except ValueError:
# raised by semver.parse
return False
return True
def has_valid_sha256sum(self):
try:
current_sha256sum = \
self.body['metadata']['annotations']['qontract.sha256sum']
return current_sha256sum == self.sha256sum()
except KeyError:
return False
def annotate(self):
"""
Creates a OpenshiftResource with the qontract annotations, and removes
unneeded Openshift fields.
Returns:
openshift_resource: new OpenshiftResource object with
annotations.
"""
# calculate sha256sum of canonical body
canonical_body = self.canonicalize(self.body)
sha256sum = self.calculate_sha256sum(self.serialize(canonical_body))
# create new body object
body = copy.deepcopy(self.body)
# create annotations if not present
body['metadata'].setdefault('annotations', {})
if body['metadata']['annotations'] is None:
body['metadata']['annotations'] = {}
annotations = body['metadata']['annotations']
# add qontract annotations
annotations['qontract.integration'] = self.integration
annotations['qontract.integration_version'] = \
self.integration_version
annotations['qontract.sha256sum'] = sha256sum
now = datetime.datetime.utcnow().replace(microsecond=0).isoformat()
annotations['qontract.update'] = now
if self.caller_name:
annotations['qontract.caller_name'] = self.caller_name
return OpenshiftResource(body, self.integration,
self.integration_version)
def sha256sum(self):
body = self.annotate().body
annotations = body['metadata']['annotations']
return annotations['qontract.sha256sum']
def toJSON(self):
return self.serialize(self.body)
@staticmethod
def canonicalize(body):
body = copy.deepcopy(body)
# create annotations if not present
body['metadata'].setdefault('annotations', {})
if body['metadata']['annotations'] is None:
body['metadata']['annotations'] = {}
annotations = body['metadata']['annotations']
# remove openshift specific params
body['metadata'].pop('creationTimestamp', None)
body['metadata'].pop('resourceVersion', None)
body['metadata'].pop('generation', None)
body['metadata'].pop('selfLink', None)
body['metadata'].pop('uid', None)
body['metadata'].pop('namespace', None)
annotations.pop('kubectl.kubernetes.io/last-applied-configuration',
None)
# remove status
body.pop('status', None)
# Default fields for specific resource types
# ConfigMaps and Secrets are by default Opaque
if body['kind'] in ('ConfigMap', 'Secret') and \
body.get('type') == 'Opaque':
body.pop('type')
if body['kind'] == 'Deployment':
annotations.pop('deployment.kubernetes.io/revision', None)
if body['kind'] == 'Route':
if body['spec'].get('wildcardPolicy') == 'None':
body['spec'].pop('wildcardPolicy')
# remove tls-acme specific params from Route
if 'kubernetes.io/tls-acme' in annotations:
annotations.pop(
'kubernetes.io/tls-acme-awaiting-authorization-owner',
None)
annotations.pop(
'kubernetes.io/tls-acme-awaiting-authorization-at-url',
None)
if 'tls' in body['spec']:
tls = body['spec']['tls']
tls.pop('key', None)
tls.pop('certificate', None)
subdomain = body['spec'].get('subdomain', None)
if subdomain == '':
body['spec'].pop('subdomain', None)
if body['kind'] == 'ServiceAccount':
if 'imagePullSecrets' in body:
body.pop('imagePullSecrets')
if 'secrets' in body:
body.pop('secrets')
if body['kind'] == 'Role':
for rule in body['rules']:
if 'resources' in rule:
rule['resources'].sort()
if 'verbs' in rule:
rule['verbs'].sort()
if 'attributeRestrictions' in rule and \
not rule['attributeRestrictions']:
rule.pop('attributeRestrictions')
if body['kind'] == 'RoleBinding':
if 'groupNames' in body:
body.pop('groupNames')
if 'userNames' in body:
body.pop('userNames')
if 'roleRef' in body:
roleRef = body['roleRef']
if 'namespace' in roleRef:
roleRef.pop('namespace')
if 'apiGroup' in roleRef and \
roleRef['apiGroup'] in body['apiVersion']:
roleRef.pop('apiGroup')
if 'kind' in roleRef:
roleRef.pop('kind')
for subject in body['subjects']:
if 'namespace' in subject:
subject.pop('namespace')
if 'apiGroup' in subject and \
(subject['apiGroup'] == '' or
subject['apiGroup'] in body['apiVersion']):
subject.pop('apiGroup')
# TODO: remove this once we have no 3.11 clusters
if body['apiVersion'] == 'rbac.authorization.k8s.io/v1':
body['apiVersion'] = 'authorization.openshift.io/v1'
if body['kind'] == 'ClusterRoleBinding':
# TODO: remove this once we have no 3.11 clusters
if body['apiVersion'] == 'authorization.openshift.io/v1':
body['apiVersion'] = 'rbac.authorization.k8s.io/v1'
if 'userNames' in body:
body.pop('userNames')
if 'roleRef' in body:
roleRef = body['roleRef']
if 'apiGroup' in roleRef and \
roleRef['apiGroup'] in body['apiVersion']:
roleRef.pop('apiGroup')
if 'kind' in roleRef:
roleRef.pop('kind')
if 'groupNames' in body:
body.pop('groupNames')
if body['kind'] == 'Service':
spec = body['spec']
if spec.get('sessionAffinity') == 'None':
spec.pop('sessionAffinity')
if spec.get('type') == 'ClusterIP':
spec.pop('clusterIP', None)
# remove qontract specific params
annotations.pop('qontract.integration', None)
annotations.pop('qontract.integration_version', None)
annotations.pop('qontract.sha256sum', None)
annotations.pop('qontract.update', None)
return body
@staticmethod
def serialize(body):
return json.dumps(body, sort_keys=True)
@staticmethod
def calculate_sha256sum(body):
m = hashlib.sha256()
m.update(body.encode('utf-8'))
return m.hexdigest()
class ResourceInventory(object):
def __init__(self):
self._clusters = {}
self._error_registered = False
self._lock = Lock()
def initialize_resource_type(self, cluster, namespace, resource_type):
self._clusters.setdefault(cluster, {})
self._clusters[cluster].setdefault(namespace, {})
self._clusters[cluster][namespace].setdefault(resource_type, {
'current': {},
'desired': {}
})
def add_desired(self, cluster, namespace, resource_type, name, value):
with self._lock:
desired = \
self._clusters[cluster][namespace][resource_type]['desired']
if name in desired:
raise ResourceKeyExistsError(name)
desired[name] = value
def add_current(self, cluster, namespace, resource_type, name, value):
with self._lock:
current = \
self._clusters[cluster][namespace][resource_type]['current']
current[name] = value
def __iter__(self):
for cluster in self._clusters.keys():
for namespace in self._clusters[cluster].keys():
for resource_type in self._clusters[cluster][namespace].keys():
data = self._clusters[cluster][namespace][resource_type]
yield (cluster, namespace, resource_type, data)
def register_error(self):
self._error_registered = True
def has_error_registered(self):
return self._error_registered