-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_utils.py
More file actions
194 lines (163 loc) · 6.33 KB
/
example_utils.py
File metadata and controls
194 lines (163 loc) · 6.33 KB
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
"""Utilities for working with vendored example manifests in tests."""
from __future__ import annotations
import os
import subprocess
from functools import lru_cache
from pathlib import Path
import yaml
from helpers import kubectl, wait_for, wait_for_stateful_set_ready
def _discover_repo_root(start: Path) -> Path:
for candidate in (start, *start.parents):
if (candidate / "examples" / "recommendations.json").is_file():
return candidate
raise RuntimeError("unable to locate repo root from example_utils.py")
_EXAMPLES_ROOT_OVERRIDE = os.environ.get("EXAMPLES_ROOT")
if _EXAMPLES_ROOT_OVERRIDE:
EXAMPLES_ROOT = Path(_EXAMPLES_ROOT_OVERRIDE).resolve()
REPO_ROOT = EXAMPLES_ROOT.parent
else:
REPO_ROOT = _discover_repo_root(Path(__file__).resolve().parent)
EXAMPLES_ROOT = (REPO_ROOT / "examples").resolve()
INVALID_EXAMPLES_ROOT = EXAMPLES_ROOT / "invalid"
EXCLUDED_VALID_EXAMPLE_ROOTS = {
EXAMPLES_ROOT / "gpus",
}
OPTIONAL_API_GROUPS = {
"autoscaling.k8s.io": [
EXAMPLES_ROOT / "automationstrategy" / "vpa-filter.yaml",
EXAMPLES_ROOT / "automationstrategy" / "vpa-filter-default.yaml",
EXAMPLES_ROOT / "automationstrategy" / "vpa-filter-explicit-containers.yaml",
EXAMPLES_ROOT / "automationstrategy" / "vpa-filter-recommendation-managed.yaml",
EXAMPLES_ROOT / "automationstrategy" / "vpa-filter-prevpa.yaml",
],
"keda.sh": [
EXAMPLES_ROOT / "staticpolicy" / "with-keda-hpa-filter.yaml",
],
}
def all_valid_example_manifests() -> list[Path]:
return sorted(
path
for path in EXAMPLES_ROOT.rglob("*.yaml")
if INVALID_EXAMPLES_ROOT not in path.parents
and not any(excluded in path.parents for excluded in EXCLUDED_VALID_EXAMPLE_ROOTS)
)
def all_invalid_example_manifests() -> list[Path]:
return sorted(INVALID_EXAMPLES_ROOT.rglob("*.yaml"))
def manifest_documents(manifest_path: Path) -> list[dict]:
with manifest_path.open() as handle:
return [
doc
for doc in yaml.safe_load_all(handle)
if doc and doc.get("kind") and doc.get("metadata", {}).get("name")
]
@lru_cache(maxsize=None)
def api_group_available(kube_context: str, api_group: str) -> bool:
output = kubectl(
"api-resources",
"--api-group",
api_group,
"-o",
"name",
context=kube_context,
)
return bool(output.strip())
def skip_reason(path: Path, kube_context: str) -> str | None:
for api_group, manifests in OPTIONAL_API_GROUPS.items():
if path in manifests and not api_group_available(kube_context, api_group):
return f"optional API group {api_group} is not installed in the cluster"
if path == EXAMPLES_ROOT / "automationstrategy" / "hpa-filter-container.yaml":
result = subprocess.run(
[
"kubectl",
"--context",
kube_context,
"explain",
"--api-version=autoscaling/v2",
"horizontalpodautoscaler.spec.metrics.containerResource",
],
capture_output=True,
text=True,
)
if result.returncode != 0:
detail = result.stderr.strip()
if detail:
return (
"cluster does not support the HPA containerResource metric used by this example: "
f"{detail}"
)
return "cluster does not support the HPA containerResource metric used by this example"
return None
def apply_manifest(manifest_path: Path, kube_context: str) -> None:
kubectl("apply", "-f", str(manifest_path), context=kube_context)
def delete_manifest_in_reverse(manifest_path: Path, kube_context: str) -> None:
"""Delete manifest resources in reverse document order."""
for doc in reversed(manifest_documents(manifest_path)):
kind = doc["kind"]
name = doc["metadata"]["name"]
namespace = doc["metadata"].get("namespace")
cmd = [
"kubectl",
"--context",
kube_context,
"delete",
kind,
name,
"--ignore-not-found",
"--wait=false",
]
if namespace:
cmd += ["-n", namespace]
subprocess.run(cmd, capture_output=True)
if kind == "Namespace":
wait_for(
lambda: not subprocess.run(
[
"kubectl",
"--context",
kube_context,
"get",
"namespace",
name,
],
capture_output=True,
text=True,
).returncode
== 0,
timeout=60,
message=f"namespace {name} deletion",
)
def assert_declared_resources_exist(manifest_path: Path, kube_context: str) -> None:
for doc in manifest_documents(manifest_path):
kind = doc["kind"]
name = doc["metadata"]["name"]
namespace = doc["metadata"].get("namespace")
args = ["get", kind, name, "-o", "name"]
if namespace:
args += ["-n", namespace]
kubectl(*args, context=kube_context)
def wait_for_declared_workloads_ready(manifest_path: Path, k8s_clients) -> None:
def wait_for_ready(read_workload, kind: str, namespace: str, name: str, expected_replicas: int):
wait_for(
lambda: (
(workload := read_workload(name, namespace))
and (workload.status.ready_replicas or 0) >= expected_replicas
),
timeout=180,
message=f"{kind.lower()} {namespace}/{name} readiness",
)
for doc in manifest_documents(manifest_path):
kind = doc["kind"]
namespace = doc["metadata"].get("namespace")
name = doc["metadata"]["name"]
expected_replicas = doc.get("spec", {}).get("replicas", 1)
if kind == "Deployment":
wait_for_ready(
k8s_clients.apps.read_namespaced_deployment,
kind,
namespace,
name,
expected_replicas,
)
continue
if kind == "StatefulSet":
wait_for_stateful_set_ready(k8s_clients.apps, namespace, name, expected_replicas)