-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperatorlib.py
2908 lines (2569 loc) · 102 KB
/
operatorlib.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 aiohttp
import argparse
import asyncio
import os
import random
import re
import string
import traceback
import yaml
from aiohttp import web
from base64 import b64encode, b64decode
from datetime import datetime
from collections import defaultdict
from math import ceil
from kubernetes_asyncio import client, config, watch
from kubernetes_asyncio.client.exceptions import ApiException
from passlib.context import CryptContext
from time import time
bcrypt_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
UPPER_FOLLOWED_BY_LOWER_RE = re.compile("(.)([A-Z][a-z]+)")
LOWER_OR_NUM_FOLLOWED_BY_UPPER_RE = re.compile("([a-z0-9])([A-Z])")
IMMUTABLE_FIELD = {"x-kubernetes-validations": [{
"message": "Value is immutable",
"rule": "self == oldSelf"}]}
STATUS_SUBRESOURCE = {
"properties": {
"phase": {
"type": "string"
},
"conditions": {
"items": {
"properties": {
"lastTransitionTime": {
"format": "date-time",
"type": "string"
},
"message": {
"maxLength": 32768,
"type": "string"
},
"reason": {
"maxLength": 1024,
"minLength": 1,
"pattern": "^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$",
"type": "string"
},
"status": {
"enum": [
"True",
"False",
"Unknown"
],
"type": "string"
},
"type": {
"maxLength": 316,
"pattern": "^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\\\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$",
"type": "string"
}
},
"required": [
"lastTransitionTime",
"status",
"type"
],
"type": "object"
},
"type": "array"
}
},
"type": "object"
}
def sentence_case(string):
if string != "":
result = re.sub("([A-Z])", r" \1", string)
return result[:1].upper() + result[1:].lower()
return
class NoAliasDumper(yaml.SafeDumper):
def increase_indent(self, flow=False, *args, **kwargs):
return super().increase_indent(flow=flow, indentless=False)
def ignore_aliases(self, data):
return True
class Operator():
"""
Base class for implementing Kubernetes operators in Python
"""
tasks = {}
@classmethod
def generate_operator_cluster_role_rules(cls):
if False:
yield None
@classmethod
def get_base_printer_columns(cls):
return []
@classmethod
def get_required_base_properties(cls):
return []
@classmethod
def get_optional_base_properties(cls):
return []
@classmethod
def generate_operator_crd_definition(cls):
return []
@classmethod
def get_service_account_name(cls):
return "%s-%s" % (cls.GROUP.replace(".", "-"), cls.OPERATOR)
@classmethod
def get_operator_namespace(cls):
raise NotImplementedError("get_operator_namespace() method not overridden")
@classmethod
def generate_operator_tasks(cls, api_client, co, args):
return []
@classmethod
def generate_random_string(self, size):
return "".join([random.choice(
string.ascii_letters + string.digits) for j in range(size)])
@classmethod
def generate_operator_deployment_definition(cls, image):
sts_name = cls.OPERATOR
resources = [{
"apiVersion": "apps/v1",
"kind": "StatefulSet",
"metadata": {
"name": sts_name,
},
"spec": {
"revisionHistoryLimit": 0,
"replicas": 1,
"serviceName": sts_name,
"selector": {
"matchLabels": {
"app": sts_name,
}
},
"template": {
"metadata": {
"labels": {
"app": sts_name,
}
},
"spec": {
"serviceAccountName": cls.get_service_account_name(),
"enableServiceLinks": False,
"imagePullSecrets": [{
"name": "regcred"
}],
"containers": [{
"name": cls.OPERATOR,
"image": image,
"ports": [{
"containerPort": 8000,
"name": "metrics",
}],
"resources": {
"limits": {
"cpu": "500m",
"memory": "128Mi",
}, "requests": {
"cpu": "1m",
"memory": "64Mi",
}
}
}]
}
}
}
}, {
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"name": sts_name,
"labels": {
"app": sts_name
}
},
"spec": {
"ports": [{
"port": 8000,
"protocol": "TCP",
"name": "metrics"
}],
"selector": {
"app": sts_name
}
}
}, {
"apiVersion": "monitoring.coreos.com/v1",
"kind": "ServiceMonitor",
"metadata": {
"name": sts_name,
},
"spec": {
"selector": {
"matchLabels": {
"app": sts_name
}
},
"endpoints": [{
"port": "metrics"
}]
}
}]
ns = cls.get_operator_namespace()
if ns:
for resource in resources:
resource["metadata"]["namespace"] = ns
return resources
@classmethod
def generate_operator_rbac_definition(cls):
VALID_VERBS = set(["get", "create", "update", "patch", "delete", "list", "watch"])
cluster_role_name = cls.get_service_account_name()
merged = defaultdict(set)
for group, resource, verbs in cls.generate_operator_cluster_role_rules():
key = group.lower(), resource.lower()
verbs = set(verbs)
assert verbs.issubset(VALID_VERBS), verbs
merged[key].update(verbs)
regrouping = defaultdict(set)
for (group, resource), verbs in merged.items():
regrouping[(group, tuple(sorted(verbs)))].add(resource)
unique_rules = sorted([(k[0], tuple(sorted(v)), k[1]) for (k, v) in regrouping.items()])
yield {
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "ClusterRole",
"metadata": {
"name": cluster_role_name,
},
"rules": [{
"apiGroups": [g],
"resources": r,
"verbs": v
} for (g, r, v) in unique_rules]
}
yield {
"apiVersion": "v1",
"kind": "ServiceAccount",
"metadata": {
"name": cluster_role_name,
"namespace": cls.get_operator_namespace(),
}
}
yield {
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "ClusterRoleBinding",
"metadata": {
"name": cluster_role_name,
},
"subjects": [{
"kind": "ServiceAccount",
"name": cluster_role_name,
"namespace": cls.get_operator_namespace(),
}],
"roleRef": {
"kind": "ClusterRole",
"name": cluster_role_name,
"apiGroup": "rbac.authorization.k8s.io",
}
}
def get_annotations(self):
"""
Add `app.kubernetes.io/managed-by` annotation to generated resources
"""
return [
("app.kubernetes.io/managed-by", "%s/%s" % (self.GROUP, self.OPERATOR))
]
@classmethod
def get_json_utcnow(cls):
return "%sZ" % (datetime.utcnow().isoformat()[:19])
def generate_manifests(self):
"""
Generate array of desired Kubernetes resource manifests
"""
return []
@classmethod
def build_argument_parser(cls):
"""
Add `--dry-run` command line argument handling
"""
parser = argparse.ArgumentParser(description="Run %s operator" % cls.__name__)
subcommands = parser.add_subparsers(dest="subcommand")
_ = subcommands.add_parser(
"generate-rbac",
description="Generate RBAC definitions")
_ = subcommands.add_parser(
"generate-crds",
description="Generate CRD definitions")
_ = subcommands.add_parser(
"nuke",
description="Generate command for completely removing the operator")
generate_deployment_parser = subcommands.add_parser(
"generate-deployment",
description="Generate deployment definitions")
generate_deployment_parser.add_argument("--image", help="Docker image")
run_parser = subcommands.add_parser("run", description="Run the operator")
run_parser.add_argument("--dry-run", action="store_true", help="Disable state mutation")
return parser
@classmethod
async def generate_operator_metrics(cls):
"""
Base Operator metrics
"""
if False:
yield
@classmethod
async def _run(cls):
args = vars(cls.build_argument_parser().parse_args())
if args["subcommand"] == "run":
print("Starting %s/%s" % (cls.GROUP, cls.OPERATOR))
if os.getenv("KUBECONFIG"):
await config.load_kube_config()
else:
config.load_incluster_config()
api_client = client.ApiClient()
co = client.CustomObjectsApi(api_client)
args.pop("subcommand")
tasks = cls.generate_operator_tasks(api_client, co, args)
print(" Starting coroutines:")
for task in tasks:
print(" Starting", task.__name__)
await asyncio.gather(*tasks)
elif args["subcommand"] == "generate-crds":
docs = sorted(
cls.generate_operator_crd_definition(),
key=lambda e: e["metadata"]["name"],
reverse=True)
for doc in docs:
for version in doc["spec"]["versions"]:
if not version["additionalPrinterColumns"]:
version.pop("additionalPrinterColumns")
print(cls.dump_yaml(docs))
elif args["subcommand"] == "generate-rbac":
print(cls.dump_yaml(cls.generate_operator_rbac_definition()))
elif args["subcommand"] == "generate-deployment":
print(cls.dump_yaml(cls.generate_operator_deployment_definition(args["image"])))
elif args["subcommand"] == "nuke":
for cmd in cls.generate_nuke_command():
print(cmd)
else:
raise NotImplementedError("Not implemented subcommand: %s" % args["subcommand"])
@classmethod
def generate_nuke_command(cls):
if False:
yield None
@classmethod
def dump_yaml(cls, docs):
buf = yaml.dump_all(docs, Dumper=NoAliasDumper, width=80)
assert not buf.startswith("---"), repr(buf)
assert buf.endswith("\n"), repr(buf)
return "---\n" + buf[:-1]
@classmethod
def run(cls):
"""
Run the asyncio event loop for this operator
"""
asyncio.run(cls._run())
class InstanceMixin():
cached_instances = {}
INSTANCE_STATE_PENDING = "Pending"
INSTANCE_STATE_ERROR = "Error"
INSTANCE_STATE_BOUND = "Bound"
INSTANCE_STATE_RELEASED = "Released"
@classmethod
async def generate_operator_metrics(cls):
"""
Base Operator metrics
"""
async for descriptor, value, labels in super().generate_operator_metrics():
yield descriptor, value, labels
yield cls.METRIC_OPERATOR_INSTANCE_RECONCILE_LOOP_RESTART_COUNT, \
cls._counter_instance_reconcile_loop_restart_count, \
(cls.GROUP, cls.SINGULAR, cls.VERSION)
yield cls.METRIC_OPERATOR_INSTANCE_RECONCILE_COUNT, \
cls._counter_instance_reconcile_count, \
(cls.GROUP, cls.SINGULAR, cls.VERSION)
class InstanceConditionNotSet(Exception):
pass
async def generate_instance_metrics(self):
if False:
yield
@classmethod
def generate_nuke_command(cls):
yield from super().generate_nuke_command()
yield "kubectl delete --all=true %s.%s" % (
cls.SINGULAR,
cls.GROUP)
yield "kubectl delete customresourcedefinition %s.%s" % (
cls.PLURAL.lower(),
cls.GROUP)
def create_instance_tasks(self):
if False:
yield None
@classmethod
def get_required_instance_properties(cls):
return cls.get_required_base_properties()
@classmethod
def generate_operator_crd_definition(cls):
return super().generate_operator_crd_definition() + [
cls.generate_instance_definition()]
@classmethod
def generate_operator_cluster_role_rules(cls):
yield from super().generate_operator_cluster_role_rules()
yield cls.GROUP, cls.PLURAL, ("get", "list", "watch")
yield cls.GROUP, cls.PLURAL + "/status", ("update", "patch")
def get_instance_owner(self):
"""
Return the instance as the owner for generated resources
"""
return {
"apiVersion": "%s/%s" % (self.GROUP, self.VERSION),
"kind": self.SINGULAR,
"name": self.name,
"uid": self.uid,
}
CONDITION_INSTANCE_RESOURCES = "Resources"
@classmethod
def get_instance_condition_set(cls):
return [
cls.CONDITION_INSTANCE_RESOURCES,
]
async def patch_instance_status(self, patches):
return await self.co.patch_cluster_custom_object_status(
self.GROUP, self.VERSION,
self.PLURAL.lower(), self.name, patches)
def get_instance_condition(self, condition):
for j in self.status["conditions"]:
if j["type"] == condition:
if j["status"] == "True":
return j.get("message", ""), datetime.strptime(
j["lastTransitionTime"], "%Y-%m-%dT%H:%M:%SZ")
raise self.InstanceConditionNotSet()
async def clear_instance_condition(self, condition, msg=""):
for index, j in enumerate(self.status["conditions"]):
if j["type"] == condition:
if j["status"] == "False":
return
else:
path = "/status/conditions/%d" % index
patches = [{
"op": "test",
"path": "%s/type" % path,
"value": condition,
}, {
"op": "replace",
"path": "%s/status" % path,
"value": "False",
}, {
"op": "remove",
"path": "%s/message" % path,
}, {
"op": "replace",
"path": "%s/lastTransitionTime" % path,
"value": self.get_json_utcnow(),
}]
break
else:
raise ValueError("Condition set not initialized correctly")
try:
await self.patch_instance_status(patches)
except ApiException as e:
if e.status == 409:
print("Failed to update %s %s status: %s" % (
self.SINGULAR,
self.name,
e))
else:
raise
# Update conditions array in the cached instance
for j in self.status["conditions"]:
if j["type"] == condition:
j["status"] = "False"
break
async def set_instance_condition(self, condition, msg=""):
for index, j in enumerate(self.status["conditions"]):
if j["type"] == condition:
if j["status"] == "True" and j.get("message", "") == msg:
return
else:
path = "/status/conditions/%d" % index
patches = [{
"op": "test",
"path": "%s/type" % path,
"value": condition,
}, {
"op": "replace",
"path": "%s/status" % path,
"value": "True",
}, {
"op": "replace",
"path": "%s/message" % path,
"value": msg,
}, {
"op": "replace",
"path": "%s/lastTransitionTime" % path,
"value": self.get_json_utcnow(),
}]
break
else:
raise ValueError("Condition set not initialized correctly")
try:
await self.patch_instance_status(patches)
except ApiException as e:
if e.status == 409:
print("Failed to update %s %s status: %s" % (
self.SINGULAR,
self.name,
e))
else:
raise
# Update conditions array in the cached instance
for j in self.status["conditions"]:
if j["type"] == condition:
j["status"] = "True"
break
@classmethod
def generate_instance_conditions(cls):
return [{
"type": s,
"status": "False",
"lastTransitionTime": cls.get_json_utcnow(),
} for s in cls.get_instance_condition_set()]
async def reconcile_instance(self):
"""
Reconcile resources for this custom resource
"""
desired_state = self.generate_manifests()
for manifest in desired_state:
group, _, version = manifest["apiVersion"].partition("/")
if version == "":
version = group
group = "core"
# Take care for the case e.g. api_type is "apiextensions.k8s.io"
# Only replace the last instance
group = "".join(group.rsplit(".k8s.io", 1))
# convert group name from DNS subdomain format to
# python class name convention
group = "".join(word.capitalize() for word in group.split("."))
fcn_to_call = "{0}{1}Api".format(group, version.capitalize())
k8s_api = getattr(client, fcn_to_call)(self.api_client)
kind = manifest["kind"]
kind = UPPER_FOLLOWED_BY_LOWER_RE.sub(r"\1_\2", kind)
kind = LOWER_OR_NUM_FOLLOWED_BY_UPPER_RE.sub(r"\1_\2", kind).lower()
try:
func = getattr(k8s_api, "read_namespaced_{0}".format(kind))
except AttributeError as e:
print("No API for %s" % e)
raise
resp = await func(
manifest["metadata"]["name"],
manifest["metadata"]["namespace"],
_preload_content=False)
if not resp or resp.status == 404:
print(" Creating %s %s/%s" % (manifest["kind"], manifest["metadata"]["namespace"], manifest["metadata"]["name"]))
resp = await getattr(k8s_api, "create_namespaced_{0}".format(kind))(
manifest["metadata"]["namespace"],
manifest,
_preload_content=False)
status = await resp.json()
if status["kind"] == "Status" and status["status"] == "Failure":
print(" Failed to create %s %s/%s",
manifest["kind"],
manifest["metadata"]["namespace"],
manifest["metadata"]["name"],
"because:", status["message"])
else:
print(" Patching %s %s/%s" % (manifest["kind"], manifest["metadata"]["namespace"], manifest["metadata"]["name"]))
resp = await getattr(k8s_api, "patch_namespaced_{0}".format(kind))(
manifest["metadata"]["name"],
manifest["metadata"]["namespace"],
manifest,
_preload_content=False)
status = await resp.json()
if status["kind"] == "Status" and status["status"] == "Failure":
print(" Failed to patch %s %s/%s",
manifest["kind"],
manifest["metadata"]["namespace"],
manifest["metadata"]["name"],
"because:", status["message"])
await self.set_instance_condition(self.CONDITION_INSTANCE_RESOURCES)
def get_label_selector(self, **extra):
"""
Build labels and label selector for application/instance
"""
labels = {
"app.kubernetes.io/name": self.OPERATOR,
"app.kubernetes.io/instance": self.get_target_name(),
**extra
}
expressions = []
for key, value in labels.items():
expressions.append({
"key": key,
"operator": "In",
"values": [value]
})
selector = {
"matchExpressions": expressions
}
return labels, selector
def get_target_name(self):
"""
Generate target resource name
"""
return self.name
def get_target_namespace(self):
"""
Generate target namespace
"""
return self.namespace
@classmethod
def get_operator_namespace(cls):
return cls.get_target_namespace()
def __init__(self, body, dry_run=True):
"""
Instantiate Python representation of the source custom resource
"""
self.namespace = body["spec"]["claimRef"]["namespace"]
self.name = body["metadata"]["name"]
self.spec = body["spec"]
self.uid = body["metadata"]["uid"]
self.generation = body["metadata"]["generation"]
self.status = body["status"]
self.dry_run = dry_run
def setup(self):
"""
Set up additional attributes for the Python representation of the source custom resource
"""
self.labels, self.label_selector = self.get_label_selector()
self.annotations = dict(self.get_annotations())
@classmethod
async def _construct_resource(cls, args, co, body):
inst = cls(body, *args)
inst.setup()
return inst
_counter_instance_reconcile_loop_restart_count = 0
_counter_instance_reconcile_count = 0
METRIC_OPERATOR_INSTANCE_RECONCILE_LOOP_RESTART_COUNT = "codemowers_operator_instance_reconcile_loop_restart_count", \
"Instance reconciler loop restart count", \
["group", "kind", "version"]
METRIC_OPERATOR_INSTANCE_RECONCILE_COUNT = "codemowers_operator_instance_reconcile_count", \
"Instance reconciler loop restart count", \
["group", "kind", "version"]
@classmethod
async def run_instance_reconciler_loop(cls, api_client, co, args):
"""
Instance reconciler loop
"""
w = watch.Watch()
kwargs = {}
cls.cached_instances.clear()
while True:
try:
cls._counter_instance_reconcile_loop_restart_count += 1
async for event in w.stream(co.list_cluster_custom_object, cls.GROUP, cls.VERSION, cls.PLURAL.lower(), **kwargs):
if isinstance(event, str):
print("Resource definition of %s not installed" % (
cls.SINGULAR))
await asyncio.sleep(60)
continue
body = event["object"]
kwargs["resource_version"] = body["metadata"]["resourceVersion"]
if event["type"] in ("ADDED", "MODIFIED"):
if "uid" not in body["spec"]["claimRef"]:
print("%s %s/%s gone, aborting %s %s reconcile" % (
cls.get_claim_singular(),
body["spec"]["claimRef"]["namespace"],
body["spec"]["claimRef"]["name"],
cls.SINGULAR,
body["metadata"]["name"]))
continue
try:
instance = await cls._construct_resource(args, co, body, api_client)
instance.setup()
prev_instance = cls.cached_instances.get(body["metadata"]["name"], None)
if prev_instance and prev_instance.generation == instance.generation:
continue
print("Reconciling %s %s" % (cls.SINGULAR, instance.name))
cls._counter_instance_reconcile_count += 1
await instance.reconcile_instance()
except ReconcileDeferred as e:
print("Deferring %s %s reconcile due to: %s" % (
cls.SINGULAR,
body["metadata"]["name"],
e))
continue
except ReconcileError as e:
print("Instance reconciliation error:", e)
await cls.set_instance_phase(co, body["metadata"], cls.INSTANCE_STATE_ERROR)
except Exception as e:
print("Unhandled exception raised during instance reconcile:", e)
await cls.set_instance_phase(co, body["metadata"], cls.INSTANCE_STATE_ERROR)
raise
else:
cls.cached_instances[body["metadata"]["name"]] = instance
await cls.set_instance_phase(co, body["metadata"], cls.INSTANCE_STATE_BOUND)
elif event["type"] == "DELETED":
print("Deleting instance %s" % body["metadata"]["name"])
cls.cached_instances.pop(body["metadata"]["name"], None)
await instance.cleanup_instance()
else:
print("Don't know how to handle event type", event)
except aiohttp.client_exceptions.ClientPayloadError as e:
print("Unexpected aiohttp error in instance reconciler loop:", e)
await asyncio.sleep(15)
except ApiException as e:
if e.status == 410:
print("Watch for %s expired, restarting" % cls.PLURAL)
kwargs.pop("resource_version", None)
await asyncio.sleep(3)
else:
print("Kubernetes API error in instance reconciler loop:", e)
traceback.print_exc()
await asyncio.sleep(15)
async def cleanup_instance(self):
pass
@classmethod
def generate_operator_tasks(cls, api_client, co, args):
return super().generate_operator_tasks(api_client, co, args) + [
cls.run_instance_reconciler_loop(api_client, co, args)
]
@classmethod
def get_optional_instance_properties(cls):
"""
Return optional instance properties
"""
return cls.get_optional_base_properties()
@classmethod
def get_base_printer_columns(cls):
"""
Return instance and claim base printer columns
"""
return super().get_base_printer_columns() + [{
"jsonPath": ".status.phase",
"name": "Phase",
"type": "string",
}]
@classmethod
def get_instance_printer_columns(cls):
"""
Return instance printer columns
"""
return cls.get_base_printer_columns()
@classmethod
def generate_instance_definition(cls):
"""
Generate CRD definitions for this operator
"""
props = dict(cls.get_required_instance_properties())
return {
"apiVersion": "apiextensions.k8s.io/v1",
"kind": "CustomResourceDefinition",
"metadata": {
"name": "%s.%s" % (cls.PLURAL.lower(), cls.GROUP),
},
"spec": {
"scope": "Cluster",
"group": cls.GROUP,
"names": {
"plural": cls.PLURAL.lower(),
"singular": cls.SINGULAR.lower(),
"kind": cls.SINGULAR,
},
"versions": [{
"subresources": {
"status": {}
},
"name": cls.VERSION,
"served": True,
"storage": True,
"additionalPrinterColumns": cls.get_instance_printer_columns(),
"schema": {
"openAPIV3Schema": {
"type": "object",
"required": ["spec"],
"properties": {
"status": STATUS_SUBRESOURCE,
"spec": {
"type": "object",
"required": list(sorted(props.keys())),
"properties": dict(cls.get_optional_instance_properties()) | props,
}
}
}
}
}],
}
}
class ReconcileError(Exception):
pass
class ReconcileDeferred(ReconcileError):
pass
class OperatorClassNotFound(ReconcileError):
pass
class UpstreamSecretNotFound(ReconcileError):
pass
class InstanceSecretMixin():
CONDITION_INSTANCE_SECRET_CREATED = "SecretCreated"
@classmethod
def generate_operator_cluster_role_rules(cls):
yield from super().generate_operator_cluster_role_rules()
yield "", "secrets", ("get", "create")
@classmethod
def get_instance_condition_set(cls):
return super().get_instance_condition_set() + [
cls.CONDITION_INSTANCE_SECRET_CREATED,
]
def get_instance_secret_name(self):
return self.get_target_name()
async def generate_instance_secret(self):
raise NotImplementedError()
async def reconcile_instance(self):
secret_name = self.get_instance_secret_name()
namespace = self.get_target_namespace()
try:
resp = await self.v1.read_namespaced_secret(secret_name, namespace)
except ApiException as e:
if e.status == 404:
self.instance_secret = dict([j async for j in self.generate_instance_secret()])
body = {
"metadata": {
"name": secret_name,
"namespace": namespace,
"ownerReferences": [self.get_instance_owner()]
},
"data": dict([(k, b64encode(v.encode("ascii")).decode("ascii"))
for k, v in self.instance_secret.items()]),
}
try:
resp = await self.v1.create_namespaced_secret(
namespace,
client.V1Secret(**body))
except ApiException as e:
if e.status == 409:
pass
else:
raise
else:
print("Instance secret %s/%s created" % (namespace, secret_name))
else:
raise
else:
self.instance_secret = dict([(k, b64decode(v.encode("ascii")).decode("ascii"))
for k, v in resp.data.items()])
await self.set_instance_condition(self.CONDITION_INSTANCE_SECRET_CREATED)
await super().reconcile_instance()
class ClaimSecretMixin():
CONDITION_CLAIM_SECRET = "ClaimSecret"
@classmethod
def generate_operator_cluster_role_rules(cls):
yield from super().generate_operator_cluster_role_rules()
yield "", "secrets", ("get", "create", "update")
@classmethod
def get_claim_condition_set(cls):
return super().get_claim_condition_set() + [
cls.CONDITION_CLAIM_SECRET,
]
def get_claim_secret_name(self):
return "%s-%s-owner-secrets" % (
self.SINGULAR.lower(),
self.spec["claimRef"]["name"])
async def reconcile_instance(self):
await super().reconcile_instance()
secret_name = self.get_claim_secret_name()
namespace = self.namespace
try:
resp = await self.v1.read_namespaced_secret(secret_name, namespace)
except ApiException as e:
if e.status == 404:
self.claim_secret = dict([j async for j in self.generate_claim_secret()])
body = {
"metadata": {
"name": secret_name,
"namespace": self.namespace,
"ownerReferences": [self.spec["claimRef"]]
},
"data": dict([(k, b64encode(v.encode("ascii")).decode("ascii"))
for k, v in self.claim_secret.items()]),
}
try:
resp = await self.v1.create_namespaced_secret(
self.namespace,
client.V1Secret(**body))
except ApiException as e: