-
Notifications
You must be signed in to change notification settings - Fork 18
/
build23_up2.py
2242 lines (1972 loc) · 87.9 KB
/
build23_up2.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
#
# Copyright (c) 2021 Incisive Technology Ltd
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This program generates all the 'model' package & api version modules
This program works off a specified Kubernetes swagger file and from there
builds out the model sub-package of hikaru. It first removes all existing
content of this package and then re-creates it from scratch. If the swagger
file hasn't changed, then these generated modules will be identical, otherwise
they will contain the new contents from the swagger file.
Usage is:
python build.py <path to swagger file>
The assumption is to create the 'build' package in the cwd.
Just some notes to remember how this all works:
For the collection types, you must parameterize the
types from typing (List, Dict, etc).
If you want an optional type, you can use typing.Optional,
which turns into Union[T, NoneType].
You can use dataclasses.field(default_factory=list) to indicate
where optional args should be defaulted to new empty lists.
You can acquire the fields of class X with
dataclasses.fields(X). The type annotation for the field is
stored in the 'type' attribute.
You now want to understand Union and List types. There are two
different ways to do this; the change comes at Py3.8. This
are both performed on the type object found in the above
mentioned attribute:
Operation Pre-3.8 3.8 and later
========================================================
get origin __origin__ typing.get_origin()
get args __args__ typing.get_args()
inspect.signature() can give the argument signature for a
method; can find how many required positional args there are.
"""
from itertools import chain, permutations
from functools import lru_cache
import importlib
from pathlib import Path
import keyword
import sys
from typing import List, Dict, Optional, Union, Tuple, Any, Set
import json
from collections import defaultdict
import re
from warnings import warn
from black import NothingChanged, format_str, Mode
from hikaru.naming import (process_swagger_name, full_swagger_name,
dprefix, camel_to_pep8)
from hikaru.meta import (HikaruBase, HikaruDocumentBase, KubernetesException,
WatcherDescriptor)
class VersionStr(str):
"""
Special string for holding version values;
"""
major_stage_minor = re.compile("v(?P<major>[0-9]+)(?P<stage>[a-z]*)(?P<minor>[0-9]*)")
@lru_cache
def get_msm(self) -> list:
parts = []
m = VersionStr.major_stage_minor.match(self)
if m is not None:
parts.append(int(m.group('major')))
stage = m.group('stage')
if stage:
parts.append(stage)
minor = m.group('minor')
if minor:
parts.append(int(minor))
return parts
def is_ga(self, msm: Optional[List] = None):
if msm is None:
msm = self.get_msm()
return len(msm) == 1
@lru_cache
def __lt__(self, other):
sparts = self.get_msm()
oparts = other.get_msm()
# OK, first check if either/both are GA; GA is never less than non-GA,
# and if both are GA then just compare the release numbers
s_is_ga = len(sparts) == 1
o_is_ga = len(oparts) == 1
if s_is_ga ^ o_is_ga:
# only one is GA; is self is then it is not less than since it is GA
return False if s_is_ga else True
if s_is_ga and o_is_ga:
return sparts[0] < oparts[0]
# if we get here then neither is GA; then compare stages (which must be there)
if sparts[1] != oparts[1]:
return sparts[1] < oparts[1]
# next compare releases
if sparts[0] != oparts[0]:
return sparts[0] < oparts[0]
# OK, the stages are the same, so check the minor version
s_has_minor = len(sparts) == 3
o_has_minor = len(oparts) == 3
if s_has_minor and o_has_minor:
return sparts[2] < oparts[2]
if s_has_minor ^ o_has_minor:
return False if s_has_minor else True
return False
@lru_cache
def __gt__(self, other):
return self != other and not (self < other)
@lru_cache
def __le__(self, other):
return self == other or self < other
@lru_cache
def __ge__(self, other):
return self == other or self > other
# version, opid
written_methods: Set[Tuple[VersionStr, str]] = set()
NoneType = type(None)
types_map = {"boolean": "bool",
"integer": "int",
"string": "str",
"float": "float",
"number": "float"}
model_package = "hikaru/model"
unversioned_module_name = "unversioned"
_copyright_string = \
"""#
# Copyright (c) 2021 Incisive Technology Ltd
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE."""
_module_docstring = f'''{_copyright_string}
"""
DO NOT EDIT THIS FILE!
This module is automatically generated using the Hikaru build program that turns
a Kubernetes swagger spec into the code for the hikaru.model package.
"""
'''
_package_init_code = \
"""
try:
from .v1 import *
except ImportError: # pragma: no cover
pass
from .deprecations import *
__version__ = '%s'"""
_deprecation_warning = \
"""
warnings.filterwarnings('default', category=PendingDeprecationWarning)
warnings.warn("Consider migrating from release %s of K8s; this is the last "
"Hikaru release that will support it",
category=PendingDeprecationWarning)
warnings.filterwarnings('ignore', category=PendingDeprecationWarning)"""
_module_footer = '''globs = dict(globals())
__all__ = [c.__name__ for c in globs.values()
if type(c) == type]
del globs'''
_package_version_init_code = \
"""
try:
from .{} import *
except ImportError: # pragma: no cover
pass"""
build_helper_data: dict = {}
class PropertyDescriptor(object):
def __init__(self, containing_class: 'ClassDescriptor', name: str, d: dict):
"""
capture the information
:param containing_class:
:param d:
"""
name = name.replace('-', '_')
if keyword.iskeyword(name):
python_name = f'{name}_'
elif name.startswith("$"):
python_name = f'{dprefix}{name.strip("$")}'
else:
python_name = name
self.name = python_name
self.default_value = None
self.containing_class = containing_class
self.description = d.get('description', "")
# all possible attributes that could be populated
self.container_type = self.item_type = self.prop_type = None
ctype = d.get("type")
if ctype == "array":
self.container_type = list
items = d["items"]
self.item_type = items.get('type')
if self.item_type is None or self.item_type == "object":
# then it is a list of objects; possibly of one of the defs
ref = items.get("$ref")
if ref:
item_ref = find_cd_by_property_ref(ref)
else:
itype = items.get("type")
if itype:
if itype == "object":
item_ref = "object"
else:
item_ref = itype
else:
raise RuntimeError(f"Don't know how to process type of {name} "
f"in {self.containing_class.hikaru_name}")
self.item_type = item_ref
elif self.item_type in types_map:
self.item_type = types_map[self.item_type]
else:
raise TypeError(f"Unknown type: {self.item_type} in property {self.name}")
elif ctype == "object":
# This can be a couple of things, depending on the release
# of the spec. Sometimes it's just used to allow any content,
# and sometimes it's for a untyped key/value object
# We'll look for the presence of 'additionalProperties' and if
# found, we'll treat it as a dict, otherwise an object
if 'additionalProperties' in d:
self.container_type = dict
else:
self.container_type = object
else:
self.container_type = None
if self.container_type is None:
if ctype in types_map:
self.prop_type = types_map[ctype]
else:
ref_class = find_cd_by_property_ref(d["$ref"])
self.prop_type = ref_class
@staticmethod
def as_required(anno: str, as_required: bool) -> str:
return anno if as_required else f"Optional[{anno}]"
def depends_on(self) -> Optional['ClassDescriptor']:
result = None
if isinstance(self.item_type, ClassDescriptor):
result = self.item_type
elif isinstance(self.prop_type, ClassDescriptor):
result = self.prop_type
return result
def change_dep(self, new_dep):
if isinstance(self.item_type, ClassDescriptor):
self.item_type = new_dep
elif isinstance(self.prop_type, ClassDescriptor):
self.prop_type = new_dep
def as_python_typeanno(self, as_required: bool) -> str:
parts = [" ", self.name, ": "]
if self.container_type is None:
# then a straight-up type, either scalar or another object
if isinstance(self.prop_type, str):
parts.append(self.as_required(self.prop_type, as_required))
elif isinstance(self.prop_type, ClassDescriptor):
parts.append(self.as_required(f"'{self.prop_type.hikaru_name}'",
as_required))
elif self.container_type is list:
if isinstance(self.item_type, ClassDescriptor):
parts.append(self.as_required(f"List['{self.item_type.hikaru_name}']",
as_required))
else:
parts.append(self.as_required(f"List[{self.item_type}]",
as_required))
elif self.container_type is dict:
parts.append(self.as_required("Dict[str, str]", as_required))
elif self.container_type is object:
parts.append(self.as_required("object", as_required))
else:
raise TypeError(f"Unknown attribute {self.name} in "
f"{self.containing_class.hikaru_name}, "
f"prop_type:{self.prop_type}, "
f"container:{self.container_type}")
# now check if we should add a field default
if not as_required:
# then we need to add a default value so we don't have to
# supply this argument when creating it programmatically
if self.container_type is not None:
# then we need a field
factory = "list" if self.container_type is list else "dict"
parts.append(f" = field(default_factory={factory})")
else:
# just default it to None
parts.append(f" = {self.default_value}")
return "".join(parts)
def process_gvk_dict(gvk: dict) -> Tuple[str, VersionStr, str]:
version = VersionStr(gvk['version'])
group = gvk['group']
kind = gvk['kind']
if not group:
group = ''
else:
group = group.split('.')[0]
return group, version, kind
class OpParameter(object):
def __init__(self, name: str, ptype: Any, description: str, required: bool):
self.name = name
self.ptype = ptype
self.description = description
self.required = required
self.is_bodyany: bool = True if name == 'body' and ptype == 'Any' else False
def docstring(self, prefix="", hanging_indent=" ", linelen=70):
name = camel_to_pep8(self.name)
name = f"{name}_" if keyword.iskeyword(name) else name
line = f':param {name}: {self.description}'
final_lines = ClassDescriptor.split_line(line, prefix=prefix,
hanging_indent=hanging_indent,
linelen=linelen)
return "\n".join(final_lines)
def as_python(self) -> str:
if type(self.ptype) == type:
ptype = self.ptype.__name__
elif isinstance(self.ptype, ClassDescriptor):
ptype = f"'{self.ptype.hikaru_name}'"
else:
ptype = self.ptype
ptype = (ptype
if self.required
else f"Optional[{ptype}] = None")
name = camel_to_pep8(self.name)
name = f"{name}_" if keyword.iskeyword(name) else name
return f"{name}: {ptype}"
class OpResponse(object):
def __init__(self, code: int, description: str, ref: Optional[str] = None):
self.code = code
self.description = description
self.ref = ref
def is_object(self) -> bool:
return isinstance(self.ref, ClassDescriptor)
def get_path_version(path: str) -> VersionStr:
version = None
parts = path.split('/')
for part in parts:
if part.startswith('v1') or part.startswith('v2'):
version = VersionStr(part)
break
return version
# the following strings are used to format an Operation's method body
_method_body_template = \
"""if client is not None:
client_to_use = client
else:
# noinspection PyDataclass
client_to_use = self.client
inst = {k8s_class_name}(api_client=client_to_use)
the_method = getattr(inst, '{k8s_method_name}_with_http_info')
if the_method is None: # pragma: no cover
raise RuntimeError("Unable to locate method "
"{k8s_method_name}_with_http_info "
"on {k8s_class_name}; possible release mismatch?")
all_args = dict()
{arg_assignment_lines}
body = get_clean_dict(self)
all_args['{body_key}'] = body
all_args['async_req'] = async_req
result = the_method(**all_args)
codes_returning_objects = {codes_returning_objects}
resp: Response['{returned_type}'] = Response['{returned_type}'](result,
codes_returning_objects)
return resp
"""
_static_method_body_template = \
"""client_to_use = client
inst = {k8s_class_name}(api_client=client_to_use)
the_method = getattr(inst, '{k8s_method_name}_with_http_info')
if the_method is None: # pragma: no cover
raise RuntimeError("Unable to locate method "
"{k8s_method_name}_with_http_info "
"on {k8s_class_name}; possible release mismatch?")
all_args = dict()
{arg_assignment_lines}
if body is not None:
body = get_clean_dict(body) if isinstance(body, HikaruBase) else body
all_args['{body_key}'] = body
all_args['async_req'] = async_req
result = the_method(**all_args)
codes_returning_objects = {codes_returning_objects}
resp: Response['{returned_type}'] = Response['{returned_type}'](result,
codes_returning_objects)
return resp
"""
_static_method_nobody_template = \
"""client_to_use = client
inst = {k8s_class_name}(api_client=client_to_use)
the_method = getattr(inst, '{k8s_method_name}_with_http_info')
if the_method is None: # pragma: no cover
raise RuntimeError("Unable to locate method "
"{k8s_method_name}_with_http_info "
"on {k8s_class_name}; possible release mismatch?")
all_args = dict()
{arg_assignment_lines}
all_args['async_req'] = async_req
result = the_method(**all_args)
codes_returning_objects = {codes_returning_objects}
resp: Response['{returned_type}'] = Response['{returned_type}'](result,
codes_returning_objects)
return resp
"""
class Operation(object):
"""
A single operation from paths; associated with a verb such as 'get' or 'post'
The same path may have multiple operations with different verbs, and hence
may also involve different input params/outputs
"""
regexp = re.compile(r'{(?P<pname>[a-z]+)}')
# the crud_registry allows derived classes to register with Operation
# as to their support for specific crud verbs (create, read, etc).
# keys are one of the verbs, all lower case, and values are a class object
# that is derived from SyntheticOperation
crud_registry: Dict[str, type] = {}
def __init__(self, verb: str, op_path: str, op_id: str, description: str,
gvk_dict: dict):
self.owning_cd: Optional['ClassDescriptor'] = None
self.should_render = True
self.verb = verb
self.op_path = op_path
self.version: VersionStr = get_path_version(self.op_path)
self.gvk_version: VersionStr = VersionStr(gvk_dict.get('version'))
self.group = gvk_dict.get('group', 'custom_objects')
self.kind = gvk_dict.get('kind')
self.op_id = op_id
self.description = description
self.is_staticmethod = False
# flag if this can be 'watched'
self.supports_watch = False
# support for 1.16; some 'body' inputs don't have a type beside
# 'object' which we treat as Any,
# but in every case it appears they should be 'self' and treated
# as the type of the receiving object. this captures those as
# they come in, and if we need to update the type to a ClassDescriptor
# then we can find the correct OpParameter quickly
self.bodyany: Optional[OpParameter] = None
self.parameters: List[OpParameter] = list()
# self_param is a special parameter, usually named 'body',
# that is passed as an argument to another method and which
# refers to 'self' of the owning object
self.self_param: Optional[OpParameter] = None
self.returns: Dict[int, OpResponse] = {}
self.k8s_access_tuple = None
# OK, now we need to check for implicit params in the path
# itself; we'll record these as OpParam objects
search_str = self.op_path
match = self.regexp.search(search_str)
url_params = []
while match is not None:
url_params.append(match.group('pname'))
search_str = search_str[match.end():]
match = self.regexp.search(search_str)
url_params.sort()
for pname in url_params:
self.add_parameter(pname, "str", f"{pname} for the resource", required=True)
# determine the method name for this operation
version: VersionStr = get_path_version(self.op_path)
if version is None:
version = VersionStr("")
else:
version = version.replace('v', 'V')
self.meth_name = self.op_id.replace(version, '') if self.op_id else None
def set_owning_class_descriptor(self, cd: 'ClassDescriptor'):
self.owning_cd = cd
def depends_on(self) -> list:
deps = [p.ptype for p in self.parameters if isinstance(p.ptype, ClassDescriptor)]
if self.self_param and isinstance(self.self_param.ptype, ClassDescriptor):
deps.append(self.self_param.ptype)
return deps
def add_parameter(self, name: str, ptype: Any, description: str,
required: bool = False) -> 'OpParameter':
if name == 'watch':
self.supports_watch = True
ptype = types_map.get(ptype, ptype)
new_param = OpParameter(name, ptype, description, required)
if self.self_param is None and (isinstance(ptype, ClassDescriptor) or
ptype == 'Any'):
self.self_param = new_param
elif not any([name == p.name for p in self.parameters]):
self.parameters.append(new_param)
if new_param.is_bodyany:
self.bodyany = new_param
return new_param
def set_k8s_access(self, t):
"""
Stores the names that tie this operation to the k8s client method
:param t: a 4-tuple of strings consisting of:
pkg, mod, cls, meth
pkg: the package name to use in importlib.import_module
mod: the module name to use in the above function
cls: the class name to get out of the module
meth: the method name to access in the class for the operation
"""
self.k8s_access_tuple = t
def add_return(self, code: str, ptype: Optional[str], description: str):
ptype = types_map.get(ptype, ptype)
code = int(code)
self.returns[code] = OpResponse(code, description, ref=ptype)
def response_codes_returning_object(self) -> List[int]:
return [r.code for r in self.returns.values()
if r.is_object()]
def _get_method_body(self, k8s_class_name: str, k8s_method_name: str,
arg_assignment_lines: List[str],
codes_returning_objects: str,
body_key: str = 'body',
use_body: bool = True) -> List[str]:
if self.is_staticmethod:
if use_body:
rez = _static_method_body_template.format(k8s_class_name=k8s_class_name,
k8s_method_name=k8s_method_name,
body_key=body_key,
arg_assignment_lines="\n".join(
arg_assignment_lines),
codes_returning_objects=
codes_returning_objects,
returned_type=
self.owning_cd.hikaru_name)
else:
rez = _static_method_nobody_template.format(k8s_class_name=
k8s_class_name,
k8s_method_name=
k8s_method_name,
arg_assignment_lines=
"\n".join(
arg_assignment_lines),
codes_returning_objects=
codes_returning_objects,
returned_type=
self.owning_cd.hikaru_name)
else:
rez = _method_body_template.format(k8s_class_name=k8s_class_name,
k8s_method_name=k8s_method_name,
body_key=body_key,
arg_assignment_lines="\n".join(
arg_assignment_lines),
codes_returning_objects=
codes_returning_objects,
returned_type=self.owning_cd.hikaru_name)
return rez.split("\n")
# this prefix is used to detect methods in rel_1_15 for DeleteOptions
# where the instead of the object being the 'body' parameter it is the
# (UNSPECIFIED!) 'v1_delete_options' parameter. Horrifying...
del_collection_prefix = "delete_collection"
def make_docstring(self, parameters: List['OpParameter']) -> List[str]:
docstring_parts = [' r"""', f' {self.description}']
docstring_parts.append("")
docstring_parts.append(f' operationID: {self.get_effective_op_id()}')
docstring_parts.append(f' path: {self.op_path}')
if parameters:
docstring_parts.append("")
for p in parameters:
ds = p.docstring(hanging_indent=" ", linelen=80)
docstring_parts.append(f' {ds}')
docstring_parts.append(" :param client: optional; instance of "
"kubernetes.client.api_client.ApiClient")
docstring_parts.extend(self.get_async_doc())
docstring_parts.extend(self.make_return_doc())
docstring_parts.append(' """')
return docstring_parts
def get_async_doc(self) -> List[str]:
return [" :param async_req: bool; if True, call is "
"async and the caller must invoke ",
" .get() on the returned Response object. Default "
"is False, which makes ",
" the call blocking."]
def make_return_doc(self) -> List[str]:
docstring_parts = []
if self.returns:
docstring_parts.append("")
docstring_parts.append(" :return: hikaru.utils.Response[T] instance with "
"the following codes and ")
docstring_parts.append(" obj value types:")
docstring_parts.append(' Code ObjType Description')
docstring_parts.append(' -----------------------------')
for ret in self.returns.values():
rettype = (ret.ref.hikaru_name if isinstance(ret.ref, ClassDescriptor)
else ret.ref)
docstring_parts.append(f" {ret.code} {rettype} "
f" {ret.description}")
return docstring_parts
def get_effective_op_id(self) -> str:
return self.op_id
def crud_counterpart_name(self) -> Optional[str]:
"""
If self is a kind of CRUD method, return the associated CRUD verb name
Checks self.op_id and decides if the id could be a synonym for a CRUD verb.
:return: str which is the name of the CRUD verb to use or None if no
CRUD verb maps to this operation
"""
if self.op_id.startswith('create') and self.op_id != 'create':
return 'create'
if (self.op_id.startswith('read') and self.op_id != 'read' and
not self.op_id.endswith('Log')):
return 'read'
if self.op_id.startswith('patch') and self.op_id != 'patch':
return 'update'
if (self.op_id.startswith('delete') and
not self.op_id.startswith('deleteCollection') and
self.op_id != 'delete'):
return 'delete'
return None
def as_crud_python_method(self, cd: Optional['ClassDescriptor'] = None) -> List[str]:
crud_lines = []
# Scale is full of read methods! skip it entirely
if cd and cd.name == 'Scale':
return crud_lines
crud_name = self.crud_counterpart_name()
if crud_name is None:
return crud_lines
crud_class = self.crud_registry.get(crud_name)
if crud_class is None:
return crud_lines
assert issubclass(crud_class, SyntheticOperation)
if crud_class.op_name in cd.crud_ops_created:
return crud_lines
cd.crud_ops_created.add(crud_class.op_name)
crud_lines.extend(["", ""])
crud_op: Operation = crud_class(self)
crud_lines.extend(crud_op.as_python_method(cd))
return crud_lines
def get_meth_decorators(self) -> List[str]:
return ["@staticmethod"] if self.is_staticmethod else []
def get_meth_defline(self, parameters: Optional[List['OpParameter']] = None) -> str:
def_parts = []
if parameters is None:
parameters = self.parameters
def_parts.append(f"def {self.meth_name}(")
required = [p for p in parameters if p.required]
optional = [p for p in parameters if not p.required]
params = []
if not self.is_staticmethod:
params.append('self')
params.extend([p.as_python()
for p in chain(required, optional)])
# here, we add any standard parameter(s) that all should have:
params.append('client: ApiClient = None')
params.extend(self.get_async_param())
# end standards
def_parts.append(", ".join(params))
def_parts.append(f") -> {self.get_meth_return()}:")
return "".join(def_parts)
def get_async_param(self) -> List[str]:
return ['async_req: bool = False']
def get_meth_return(self) -> str:
return f"Response['{self.owning_cd.hikaru_name}']"
def get_meth_body(self, parameters: Optional[List['OpParameter']] = None,
cd: Optional['ClassDescriptor'] = None) -> List[str]:
assignment_list = []
body_seen = False
if parameters is None:
parameters = self.parameters
required = [p for p in parameters if p.required]
optional = [p for p in parameters if not p.required]
for p in chain(required, optional):
assert isinstance(p, OpParameter)
if not body_seen and p.name in ('v1_delete_options', 'body'):
body_seen = True
if keyword.iskeyword(p.name):
assignment_list.append(f"all_args['_{p.name}'] = {p.name}_")
else:
assignment_list.append(f"all_args['{camel_to_pep8(p.name)}'] = "
f"{camel_to_pep8(p.name)}")
# ok, now cover a weird case where if we have a body param that
# is not the same type as the current class we're building, and the
# method is static, we need to include this in the set of params we
# set
if (self.self_param and self.self_param.name == 'body' and
self.self_param.ptype != cd and self.op_id.startswith('delete')):
assignment_list.append(f"all_args['body'] = body")
if (cd and cd.name == "DeleteOptions"
and _release_in_process == 'rel_1_15' and
self.k8s_access_tuple[3].startswith(self.del_collection_prefix)):
body_key = 'v1_delete_options'
else:
body_key = 'body'
object_response_codes = str(tuple(self.response_codes_returning_object()))
body_lines = self._get_method_body(self.k8s_access_tuple[2],
self.k8s_access_tuple[3],
assignment_list,
object_response_codes,
body_key=body_key,
use_body=body_seen)
body = [f" {bl}" for bl in body_lines]
return body
def prep_inbound_params(self) -> List['OpParameter']:
return list(self.parameters)
def prep_outbound_params(self) -> List['OpParameter']:
return self.prep_inbound_params()
def as_python_method(self, cd: Optional['ClassDescriptor'] = None) -> List[str]:
if self.op_id is None:
return []
written_methods.add((self.version, self.op_id))
parameters = self.prep_inbound_params()
if self.is_staticmethod and self.self_param:
parameters.append(self.self_param)
lines = []
lines.extend(self.get_meth_decorators())
lines.append(self.get_meth_defline(parameters=parameters))
ds = self.make_docstring(parameters=parameters)
if ds:
lines.extend(ds)
lines.extend(self.get_meth_body(parameters=self.prep_outbound_params(),
cd=cd))
lines.extend(self.as_crud_python_method(cd))
return lines
def register_crud_class(verb: str):
def rcc(cls):
Operation.crud_registry[verb] = cls
return cls
return rcc
class SyntheticOperation(Operation):
op_name = 'noop' # must be overridden by derived classes for the real op name
def __init__(self, base_op: Operation):
gvk = {'group': base_op.group,
'version': base_op.gvk_version,
'kind': base_op.kind}
super(SyntheticOperation, self).__init__(base_op.verb, base_op.op_path,
self.op_name,
base_op.description,
gvk)
for p in base_op.parameters:
self.add_parameter(p.name, p.ptype, p.description, p.required)
for r in base_op.returns.values():
assert isinstance(r, OpResponse)
self.add_return(str(r.code), r.ref, r.description)
self.base_op = base_op
def get_effective_op_id(self) -> str:
return self.base_op.op_id
def make_return_doc(self) -> List[str]:
doc = list()
doc.append(' :return: returns self; the state of self may be '
'permuted with a returned')
doc.append(' HikaruDocumentBase object, whose values will be '
'merged into self ')
doc.append('(if of the same type).')
doc.append(' :raises: KubernetesException. Raised only by the CRUD '
'methods to signal ')
doc.append(' that a return code of 400 or higher was returned by the '
'underlying ')
doc.append(' Kubernetes library.')
return doc
def get_meth_return(self) -> str:
return f"'{self.base_op.owning_cd.hikaru_name}'"
def get_async_param(self) -> List[str]:
return []
def get_async_doc(self) -> List[str]:
return []
def as_python_method(self, cd: Optional['ClassDescriptor'] = None) -> List[str]:
code = super(SyntheticOperation, self).as_python_method(cd=cd)
code.extend(self.post_method_code(cd=cd))
return code
def post_method_code(self, cd: Optional['ClassDescriptor'] = None) -> List[str]:
return []
_create_body_with_namespace = \
"""
# noinspection PyDataclass
client = client or self.client
if namespace is not None:
effective_namespace = namespace
elif not self.metadata or not self.metadata.namespace:
raise RuntimeError("There must be a namespace supplied in either "
"the arguments to {op_name}() or in a "
"{classname}'s metadata")
else:
effective_namespace = self.metadata.namespace
res = self.{methname}({paramlist})
if not 200 <= res.code <= 299:
raise KubernetesException("Kubernetes returned error " + str(res.code))
if self.__class__.__name__ == res.obj.__class__.__name__:
self.merge(res.obj, overwrite=True)
return self
"""
_create_body_no_namespace = \
"""
# noinspection PyDataclass
client = client or self.client
res = self.{methname}({paramlist})
if not 200 <= res.code <= 299:
raise KubernetesException("Kubernetes returned error " + str(res.code))
if self.__class__.__name__ == res.obj.__class__.__name__:
self.merge(res.obj, overwrite=True)
return self
"""
@register_crud_class('create')
class CreateOperation(SyntheticOperation):
"""
A synthetic operation; making a synonym named 'create()' for whatever the
actual create method is
"""
op_name = 'create'
def get_meth_decorators(self) -> List[str]:
return []
def prep_inbound_params(self) -> List['OpParameter']:
params = [p for p in self.prep_outbound_params()
if p.name not in ('name', 'async_req')]
return params
def prep_outbound_params(self) -> List['OpParameter']:
params = []
for p in self.parameters:
if p.name == 'namespace':
p.required = False
p.description = f"{p.description}. NOTE: if you leave out the " \
f"namespace from the arguments you *must* have " \
f"filled in the namespace attribute in the metadata " \
f"for the resource!"
if p.name == "async_req":
continue
params.append(p)
return params
def _with_namespace_template(self):
return _create_body_with_namespace
def _without_namespace_template(self):
return _create_body_no_namespace
def namespace_name(self):
return 'effective_namespace'
def name_name(self):
return 'self.metadata.name'
def get_meth_body(self, parameters: Optional[List['OpParameter']] = None,
cd: Optional['ClassDescriptor'] = None) -> List[str]:
required = [p for p in parameters if p.required]
optional = [p for p in parameters if not p.required]
param_assignments = []
seen_namespace = False
for p in chain(required, optional):
assert isinstance(p, OpParameter)
if p.name == "namespace":
seen_namespace = True
local_name = self.namespace_name()
param_name = camel_to_pep8(p.name)
elif p.name == 'name':
local_name = self.name_name()
param_name = camel_to_pep8(p.name)
else:
local_name = param_name = camel_to_pep8(p.name)
param_assignments.append(f"{param_name}={local_name}")
param_assignments.append("client=client")
body_str = (self._with_namespace_template()
if seen_namespace else
self._without_namespace_template())
fdict = {"classname": cd.hikaru_name if cd else 'UNKNOWN',
"methname": self.base_op.meth_name,
'paramlist': ", ".join(param_assignments),
'op_name': self.op_name}
body = body_str.format(**fdict)
return body.split("\n")
_update_context_manager = \
"""
def __enter__(self):
return self
def __exit__(self, ex_type, ex_value, ex_traceback):
passed = ex_type is None and ex_value is None and ex_traceback is None
has_rollback = hasattr(self, "__rollback")
if passed:
try:
self.update()