-
Notifications
You must be signed in to change notification settings - Fork 18
/
build16to18.py
2087 lines (1832 loc) · 81 KB
/
build16to18.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
import importlib
from pathlib import Path
import sys
from typing import List, Dict, Optional, Union, Tuple, Any, Set
import json
import re
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)
NoneType = type(None)
def _clean_directory(dirpath: str, including_dirpath=False):
path = Path(dirpath)
for p in path.iterdir():
if p.is_file():
p.unlink()
elif p.is_dir():
_clean_directory(str(p), including_dirpath=True)
if including_dirpath:
p.rmdir()
_package_init_code = \
"""
try:
from .v1 import *
except ImportError: # pragma: no cover
pass"""
_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)"""
def _setup_dir(directory: str) -> Path:
path = Path(directory)
if not path.exists():
path.mkdir(parents=True)
else:
if not path.is_dir():
path.unlink()
path.mkdir(parents=True)
return path
def prep_model_root(directory: str) -> Path:
path = _setup_dir(directory)
return path
def make_root_init(directory: str, default_rel: str):
path = Path(directory)
init = path / "__init__.py"
if init.exists():
init.unlink()
f = init.open('w')
f.write(_module_docstring)
f.write(f"default_release = '{default_rel}'\n")
f.close()
def prep_rel_package(directory: str, deprecated: bool = False) -> Path:
"""
This function empties the directory named 'directory', creating it if needed
:param directory: string; name of an empty directory to create. Creates it
if needed, and removes any existing content if it's already there.
:param deprecated: True if the package should be marked as deprecated and
prints a warning if imported.
"""
path = _setup_dir(directory)
init = path / "__init__.py"
init.touch()
f = init.open('w')
print(_module_docstring, file=f)
if deprecated:
print("import warnings", file=f)
print(_package_init_code, file=f)
if deprecated:
print(_deprecation_warning % path.name, file=f)
print(file=f)
output_footer(stream=f)
return path
_package_version_init_code = \
"""
try:
from .{} import *
except ImportError: # pragma: no cover
pass"""
def prep_version_package(directory: str, version: str) -> Path:
"""
This function creates an initializes the supplied version directory, creating if
needed
:param directory: string; name of a directory to create to hold the files for a
single version in a release
:param version: string; name of the version package to prep within directory
:return: the Path object created for the version package
"""
path = _setup_dir(directory)
_clean_directory(str(path))
init = path / "__init__.py"
init.touch()
f = init.open('w')
print(_module_docstring, file=f)
print(_package_version_init_code.format(version), file=f)
print(file=f)
output_footer(stream=f)
return path
_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.
"""
'''
def output_boilerplate(stream=sys.stdout, other_imports=None):
"""
Write out the standard module header imports
:param stream: where to write; sys.stdout default
:param other_imports: None, or a list of strings to generate import
statements for
"""
print(_module_docstring, file=stream)
print(file=stream)
print(f"from hikaru.meta import {HikaruBase.__name__}, "
f"{HikaruDocumentBase.__name__}, {KubernetesException.__name__}, "
f"{WatcherDescriptor.__name__}",
file=stream)
print("from hikaru.generate import get_clean_dict", file=stream)
print("from hikaru.utils import Response", file=stream)
print("from typing import Dict, List, Optional, Any", file=stream)
print("from dataclasses import dataclass, field, InitVar", file=stream)
print("from kubernetes.client import CoreV1Api", file=stream)
if other_imports is not None:
for line in other_imports:
print(line, file=stream)
print(file=stream)
_module_footer = '''globs = dict(globals())
__all__ = [c.__name__ for c in globs.values()
if type(c) == type]
del globs'''
def output_footer(stream=sys.stdout):
"""
Write out the footer that defines '__all__'
:param stream: file to write the footer to
"""
print(_module_footer, file=stream)
def write_classes(class_list, for_version: str, stream=sys.stdout):
for cd in class_list:
assert isinstance(cd, ClassDescriptor)
if not cd.has_properties():
print(f'Skipping code generation for attribute-less class {cd.short_name}, '
f'v {cd.version} for version {for_version}')
continue
print(cd.as_python_class(for_version), file=stream)
print(file=stream)
_documents_init_code = \
"""
try:
from .{} import *
except ImportError: # pragma: no cover
pass
from hikaru import HikaruDocumentBase
__all__ = [o.__name__ for o in globals().values()
if type(o) is type and issubclass(o, HikaruDocumentBase)]
"""
def write_documents_module(path: Path, version: str):
path.touch()
f = path.open('w')
print(_module_docstring, file=f)
print(_documents_init_code.format(version), file=f)
print(file=f)
f.close()
def write_modules(pkgpath: str):
pkg = Path(pkgpath)
d = module_defs()
mod_names = []
base = d.get(None)
# first, create the module with un-versioned object defs
if base:
unversioned = pkg / f'{unversioned_module_name}.py'
assert isinstance(base, ModuleDef)
f = unversioned.open('w')
base.as_python_module(stream=f, import_unversioned=False)
f.close()
# next, write out all the version-specific object defs
for k, md in d.items():
if k is not None:
assert isinstance(md, ModuleDef)
version_path = pkg / md.version
prep_version_package(str(version_path), md.version)
mod_names.append(md.version)
mod = version_path / f'{md.version}.py'
f = mod.open('w')
md.as_python_module(stream=f)
f.close()
documents_path = version_path / "documents.py"
write_documents_module(documents_path, md.version)
watchables_path = version_path / "watchables.py"
write_watchables_module(watchables_path, md)
# finally, capture the names of all the version modules in version module
versions = pkg / 'versions.py'
f = versions.open('w')
print(f"versions = {str(mod_names)}", file=f)
f.close()
# 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}
return Response['{returned_type}'](result, codes_returning_objects)
"""
_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}
return Response['{returned_type}'](result, codes_returning_objects)
"""
_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}
return Response['{returned_type}'](result, codes_returning_objects)
"""
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 = get_path_version(self.op_path)
self.gvk_version = 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 = get_path_version(self.op_path)
if version is None:
version = ""
else:
version = version.replace('v', 'V')
self.meth_name = self.op_id.replace(version, '') if self.op_id else None
def set_owning_cd(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.short_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.short_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.short_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.short_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.short_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.short_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 p.name in python_reserved:
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.short_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.kind}'"
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.short_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()
except Exception:
if has_rollback:
self.merge(getattr(self, "__rollback"), overwrite=True)
delattr(self, "__rollback")
raise
if has_rollback:
if not passed:
self.merge(getattr(self, "__rollback"), overwrite=True)
delattr(self, "__rollback")
return False
"""
@register_crud_class('update')
class UpdateOperation(CreateOperation):
"""
A synthetic operation to make an 'update()' crud method to provide a synonym
to the patch method
"""
op_name = 'update'
def post_method_code(self, cd: Optional['ClassDescriptor'] = None) -> List[str]:
return _update_context_manager.split("\n")
_delete_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
if name is not None:
effective_name = name
elif not self.metadata or not self.metadata.name:
raise RuntimeError("There must be a name supplied in either "
"the arguments to {op_name}() or in a "
"{classname}'s metadata")
else:
effective_name = self.metadata.name
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
"""
_delete_body_without_namespace = \
"""
# noinspection PyDataclass
client = client or self.client
if name is not None:
effective_name = name
elif not self.metadata or not self.metadata.name:
raise RuntimeError("There must be a name supplied in either "
"the arguments to {op_name}() or in a "
"{classname}'s metadata")
else:
effective_name = self.metadata.name
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('delete')
class DeleteOperation(CreateOperation):
op_name = 'delete'
def get_meth_decorators(self) -> List[str]:
return []
def prep_inbound_params(self) -> List['OpParameter']:
return self.prep_outbound_params()
def prep_outbound_params(self) -> List['OpParameter']:
params = []
for p in self.parameters:
if p.name in ('namespace', 'name'):
p.required = False
p.description = f"{p.description}. NOTE: if you leave out the " \
f"{p.name} from the arguments you *must* have " \
f"filled in the {p.name} attribute in the metadata " \
f"for the resource!"
if p.name == 'async_req':
continue
params.append(p)
return params
def name_name(self):