Skip to content

Commit a37561d

Browse files
authored
class-generator: do not collect deprecated resources (#2064)
* class-generator: do not collect deprecated resources * uncomment code * add tests files * Fix namespace match * Fix namespace match, again * pod: remove deprecated warn and remove get_containers
1 parent 97638c4 commit a37561d

18 files changed

+170029
-970
lines changed

class_generator/class_generator.py

Lines changed: 42 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@
55
import shlex
66
import os
77
import sys
8+
import requests
89
from pathlib import Path
910
from packaging.version import Version
1011

1112
import textwrap
1213
from typing import Any, Dict, List, Tuple
1314
import click
1415
import re
15-
import requests
1616
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
1717
import cloup
1818
from cloup.constraints import If, IsSet, accept_none, require_one
@@ -36,32 +36,48 @@
3636
RESOURCES_MAPPING_FILE: str = os.path.join(SCHEMA_DIR, "__resources-mappings.json")
3737

3838

39-
def _is_kind_and_namespaced(client: str, _data: Dict[str, Any]) -> Dict[str, Any]:
39+
def _is_kind_and_namespaced(client: str, _key: str, _data: Dict[str, Any]) -> Dict[str, Any]:
4040
x_kubernetes_group_version_kind = _data["x-kubernetes-group-version-kind"][0]
4141
_kind = x_kubernetes_group_version_kind["kind"]
4242
_group = x_kubernetes_group_version_kind.get("group")
4343
_version = x_kubernetes_group_version_kind.get("version")
4444
_group_and_version = f"{_group}/{_version}" if _group else _version
4545

46-
if run_command(command=shlex.split(f"{client} explain {_kind}"), check=False, log_errors=False)[0]:
47-
namespaced = (
46+
not_resource_dict = {"is_kind": False, "kind": _key}
47+
48+
# if explain command failed, this is not a resource
49+
if not run_command(command=shlex.split(f"{client} explain {_kind}"), check=False, log_errors=False)[0]:
50+
return not_resource_dict
51+
52+
# check if this as a valid version for the resource.
53+
api_resources_base_cmd = f"bash -c '{client} api-resources"
54+
55+
if run_command(
56+
command=shlex.split(f"{api_resources_base_cmd} | grep -w {_kind} | grep {_group_and_version}'"),
57+
check=False,
58+
log_errors=False,
59+
)[0]:
60+
# Check if the resource if namespaced.
61+
_data["namespaced"] = (
4862
run_command(
4963
command=shlex.split(
50-
f"bash -c '{client} api-resources --namespaced | grep -w {_kind} | grep {_group_and_version} | wc -l'"
64+
f"{api_resources_base_cmd} --namespaced | grep -w {_kind} | grep {_group_and_version} | wc -l'"
5165
),
5266
check=False,
67+
log_errors=False,
5368
)[1].strip()
5469
== "1"
5570
)
56-
_data["namespaced"] = namespaced
57-
return {"is_kind": True, "kind": _kind, "data": _data}
71+
return {"is_kind": True, "kind": _key, "data": _data}
5872

59-
return {"is_kind": False, "kind": _kind}
73+
return not_resource_dict
6074

6175

6276
def map_kind_to_namespaced(client: str):
6377
not_kind_file: str = os.path.join(SCHEMA_DIR, "__not-kind.txt")
6478

79+
resources_mapping = read_resources_mapping_file()
80+
6581
if os.path.isfile(not_kind_file):
6682
with open(not_kind_file) as fd:
6783
not_kind_list = fd.read().split("\n")
@@ -71,37 +87,45 @@ def map_kind_to_namespaced(client: str):
7187
with open(SCHEMA_DEFINITION_FILE) as fd:
7288
_definitions_json_data = json.load(fd)
7389

74-
resources_mapping: Dict[Any, List[Any]] = {}
75-
7690
_kind_data_futures: List[Future] = []
7791
with ThreadPoolExecutor() as executor:
78-
for _data in _definitions_json_data["definitions"].values():
92+
for _key, _data in _definitions_json_data["definitions"].items():
7993
_group_version_kind = _data.get("x-kubernetes-group-version-kind")
8094
if not _group_version_kind:
8195
continue
8296

83-
if _group_version_kind[0]["kind"] in not_kind_list:
97+
if _key in not_kind_list:
8498
continue
8599

86-
_kind_data_futures.append(executor.submit(_is_kind_and_namespaced, client=client, _data=_data))
100+
_kind_data_futures.append(executor.submit(_is_kind_and_namespaced, client=client, _key=_key, _data=_data))
87101

102+
_temp_resources_mappings: Dict[Any, Any] = {}
88103
for res in as_completed(_kind_data_futures):
89104
_res = res.result()
105+
# _res["kind"] is group.version.kind, set only kind as key in the final dict
106+
kind_key = _res["kind"].rsplit(".", 1)[-1].lower()
107+
90108
if _res["is_kind"]:
91-
resources_mapping.setdefault(_res["kind"].lower(), []).append(_res["data"])
109+
_temp_resources_mappings.setdefault(kind_key, []).append(_res["data"])
92110
else:
93111
not_kind_list.append(_res["kind"])
94112

113+
# Update the resources mapping dict with the one that we filled to avoid duplication in the lists
114+
resources_mapping.update(_temp_resources_mappings)
115+
95116
with open(RESOURCES_MAPPING_FILE, "w") as fd:
96-
json.dump(resources_mapping, fd)
117+
json.dump(resources_mapping, fd, indent=4)
97118

98119
with open(not_kind_file, "w") as fd:
99120
fd.writelines("\n".join(not_kind_list))
100121

101122

102123
def read_resources_mapping_file() -> Dict[Any, Any]:
103-
with open(RESOURCES_MAPPING_FILE) as fd:
104-
return json.load(fd)
124+
try:
125+
with open(RESOURCES_MAPPING_FILE) as fd:
126+
return json.load(fd)
127+
except (FileNotFoundError, json.JSONDecodeError):
128+
return {}
105129

106130

107131
def get_server_version(client: str):
@@ -142,7 +166,7 @@ def update_kind_schema():
142166

143167
if not run_command(command=shlex.split("which openapi2jsonschema"), check=False, log_errors=False)[0]:
144168
LOGGER.error(
145-
f"{openapi2jsonschema_str}not found. Install it using `pipx install --python python3.9 openapi2jsonschema`"
169+
f"{openapi2jsonschema_str} not found. Install it using `pipx install --python python3.9 openapi2jsonschema`"
146170
)
147171
sys.exit(1)
148172

0 commit comments

Comments
 (0)