Debian Codegraph @

tools/run_tests/xds_k8s_test_driver/framework/infrastructure/k8s.py

raw
1 # Copyright 2020 gRPC authors.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 # TODO(sergiitk): to k8s/ package, and get rid of k8s_internal, which is only
15 # added to get around circular dependencies caused by k8s.py clashing with
16 # k8s/__init__.py
17 import datetime
18 import functools
19 import json
20 import logging
21 import pathlib
22 import threading
23 from typing import List, Optional, Tuple
24
25 from kubernetes import client
26 from kubernetes import utils
27 import kubernetes.config
28 import yaml
29
30 from framework.helpers import retryers
31 import framework.helpers.highlighter
32 from framework.infrastructure.k8s_internal import k8s_log_collector
33 from framework.infrastructure.k8s_internal import k8s_port_forwarder
34
35 logger = logging.getLogger(__name__)
36 # Type aliases
37 _HighlighterYaml = framework.helpers.highlighter.HighlighterYaml
38 PodLogCollector = k8s_log_collector.PodLogCollector
39 PortForwarder = k8s_port_forwarder.PortForwarder
40 V1Deployment = client.V1Deployment
41 V1ServiceAccount = client.V1ServiceAccount
42 V1Pod = client.V1Pod
43 V1PodList = client.V1PodList
44 V1Service = client.V1Service
45 V1Namespace = client.V1Namespace
46 ApiException = client.ApiException
47
48
49 def simple_resource_get(func):
50
51 def wrap_not_found_return_none(*args, **kwargs):
52 try:
53 return func(*args, **kwargs)
54 except client.ApiException as e:
55 if e.status == 404:
56 # Ignore 404
57 return None
58 raise
59
60 return wrap_not_found_return_none
61
62
63 def label_dict_to_selector(labels: dict) -> str:
64 return ','.join(f'{k}=={v}' for k, v in labels.items())
65
66
67 class KubernetesApiManager:
68
69 def __init__(self, context):
70 self.context = context
71 self.client = self._cached_api_client_for_context(context)
72 self.apps = client.AppsV1Api(self.client)
73 self.core = client.CoreV1Api(self.client)
74
75 def close(self):
76 self.client.close()
77
78 @classmethod
79 @functools.lru_cache(None)
80 def _cached_api_client_for_context(cls, context: str) -> client.ApiClient:
81 client_instance = kubernetes.config.new_client_from_config(
82 context=context)
83 logger.info('Using kubernetes context "%s", active host: %s', context,
84 client_instance.configuration.host)
85 return client_instance
86
87
88 class KubernetesNamespace: # pylint: disable=too-many-public-methods
89 NEG_STATUS_META = 'cloud.google.com/neg-status'
90 DELETE_GRACE_PERIOD_SEC: int = 5
91 WAIT_SHORT_TIMEOUT_SEC: int = 60
92 WAIT_SHORT_SLEEP_SEC: int = 1
93 WAIT_MEDIUM_TIMEOUT_SEC: int = 5 * 60
94 WAIT_MEDIUM_SLEEP_SEC: int = 10
95 WAIT_LONG_TIMEOUT_SEC: int = 10 * 60
96 WAIT_LONG_SLEEP_SEC: int = 30
97 WAIT_POD_START_TIMEOUT_SEC: int = 3 * 60
98
99 def __init__(self, api: KubernetesApiManager, name: str):
100 self._highlighter = _HighlighterYaml()
101 self.name = name
102 self.api = api
103
104 def apply_manifest(self, manifest):
105 return utils.create_from_dict(self.api.client,
106 manifest,
107 namespace=self.name)
108
109 @simple_resource_get
110 def get_service(self, name) -> V1Service:
111 return self.api.core.read_namespaced_service(name, self.name)
112
113 @simple_resource_get
114 def get_service_account(self, name) -> V1Service:
115 return self.api.core.read_namespaced_service_account(name, self.name)
116
117 def delete_service(self,
118 name,
119 grace_period_seconds=DELETE_GRACE_PERIOD_SEC):
120 self.api.core.delete_namespaced_service(
121 name=name,
122 namespace=self.name,
123 body=client.V1DeleteOptions(
124 propagation_policy='Foreground',
125 grace_period_seconds=grace_period_seconds))
126
127 def delete_service_account(self,
128 name,
129 grace_period_seconds=DELETE_GRACE_PERIOD_SEC):
130 self.api.core.delete_namespaced_service_account(
131 name=name,
132 namespace=self.name,
133 body=client.V1DeleteOptions(
134 propagation_policy='Foreground',
135 grace_period_seconds=grace_period_seconds))
136
137 @simple_resource_get
138 def get(self) -> V1Namespace:
139 return self.api.core.read_namespace(self.name)
140
141 def delete(self, grace_period_seconds=DELETE_GRACE_PERIOD_SEC):
142 self.api.core.delete_namespace(
143 name=self.name,
144 body=client.V1DeleteOptions(
145 propagation_policy='Foreground',
146 grace_period_seconds=grace_period_seconds))
147
148 def wait_for_service_deleted(self,
149 name: str,
150 timeout_sec: int = WAIT_SHORT_TIMEOUT_SEC,
151 wait_sec: int = WAIT_SHORT_SLEEP_SEC) -> None:
152 retryer = retryers.constant_retryer(
153 wait_fixed=datetime.timedelta(seconds=wait_sec),
154 timeout=datetime.timedelta(seconds=timeout_sec),
155 check_result=lambda service: service is None)
156 retryer(self.get_service, name)
157
158 def wait_for_service_account_deleted(
159 self,
160 name: str,
161 timeout_sec: int = WAIT_SHORT_TIMEOUT_SEC,
162 wait_sec: int = WAIT_SHORT_SLEEP_SEC) -> None:
163 retryer = retryers.constant_retryer(
164 wait_fixed=datetime.timedelta(seconds=wait_sec),
165 timeout=datetime.timedelta(seconds=timeout_sec),
166 check_result=lambda service_account: service_account is None)
167 retryer(self.get_service_account, name)
168
169 def wait_for_namespace_deleted(self,
170 timeout_sec: int = WAIT_LONG_TIMEOUT_SEC,
171 wait_sec: int = WAIT_LONG_SLEEP_SEC) -> None:
172 retryer = retryers.constant_retryer(
173 wait_fixed=datetime.timedelta(seconds=wait_sec),
174 timeout=datetime.timedelta(seconds=timeout_sec),
175 check_result=lambda namespace: namespace is None)
176 retryer(self.get)
177
178 def wait_for_service_neg(self,
179 name: str,
180 timeout_sec: int = WAIT_SHORT_TIMEOUT_SEC,
181 wait_sec: int = WAIT_SHORT_SLEEP_SEC) -> None:
182 timeout = datetime.timedelta(seconds=timeout_sec)
183 retryer = retryers.constant_retryer(
184 wait_fixed=datetime.timedelta(seconds=wait_sec),
185 timeout=timeout,
186 check_result=self._check_service_neg_annotation)
187 try:
188 retryer(self.get_service, name)
189 except retryers.RetryError as e:
190 logger.error(
191 'Timeout %s (h:mm:ss) waiting for service %s to report NEG '
192 'status. Last service status:\n%s', timeout, name,
193 self._pretty_format_status(e.result()))
194 raise
195
196 def get_service_neg(self, service_name: str,
197 service_port: int) -> Tuple[str, List[str]]:
198 service = self.get_service(service_name)
199 neg_info: dict = json.loads(
200 service.metadata.annotations[self.NEG_STATUS_META])
201 neg_name: str = neg_info['network_endpoint_groups'][str(service_port)]
202 neg_zones: List[str] = neg_info['zones']
203 return neg_name, neg_zones
204
205 @simple_resource_get
206 def get_deployment(self, name) -> V1Deployment:
207 return self.api.apps.read_namespaced_deployment(name, self.name)
208
209 def delete_deployment(
210 self,
211 name: str,
212 grace_period_seconds: int = DELETE_GRACE_PERIOD_SEC) -> None:
213 self.api.apps.delete_namespaced_deployment(
214 name=name,
215 namespace=self.name,
216 body=client.V1DeleteOptions(
217 propagation_policy='Foreground',
218 grace_period_seconds=grace_period_seconds))
219
220 def list_deployment_pods(self, deployment: V1Deployment) -> List[V1Pod]:
221 # V1LabelSelector.match_expressions not supported at the moment
222 return self.list_pods_with_labels(deployment.spec.selector.match_labels)
223
224 def wait_for_deployment_available_replicas(
225 self,
226 name: str,
227 count: int = 1,
228 timeout_sec: int = WAIT_MEDIUM_TIMEOUT_SEC,
229 wait_sec: int = WAIT_SHORT_SLEEP_SEC) -> None:
230 timeout = datetime.timedelta(seconds=timeout_sec)
231 retryer = retryers.constant_retryer(
232 wait_fixed=datetime.timedelta(seconds=wait_sec),
233 timeout=timeout,
234 check_result=lambda depl: self._replicas_available(depl, count))
235 try:
236 retryer(self.get_deployment, name)
237 except retryers.RetryError as e:
238 logger.error(
239 'Timeout %s (h:mm:ss) waiting for deployment %s to report %i '
240 'replicas available. Last status:\n%s', timeout, name, count,
241 self._pretty_format_status(e.result()))
242 raise
243
244 def wait_for_deployment_replica_count(
245 self,
246 deployment: V1Deployment,
247 count: int = 1,
248 *,
249 timeout_sec: int = WAIT_MEDIUM_TIMEOUT_SEC,
250 wait_sec: int = WAIT_SHORT_SLEEP_SEC) -> None:
251 timeout = datetime.timedelta(seconds=timeout_sec)
252 retryer = retryers.constant_retryer(
253 wait_fixed=datetime.timedelta(seconds=wait_sec),
254 timeout=timeout,
255 check_result=lambda pods: len(pods) == count)
256 try:
257 retryer(self.list_deployment_pods, deployment)
258 except retryers.RetryError as e:
259 result = e.result(default=[])
260 logger.error(
261 'Timeout %s (h:mm:ss) waiting for pod count %i, got: %i. '
262 'Pod statuses:\n%s', timeout, count, len(result),
263 self._pretty_format_statuses(result))
264 raise
265
266 def wait_for_deployment_deleted(
267 self,
268 deployment_name: str,
269 timeout_sec: int = WAIT_MEDIUM_TIMEOUT_SEC,
270 wait_sec: int = WAIT_MEDIUM_SLEEP_SEC) -> None:
271 retryer = retryers.constant_retryer(
272 wait_fixed=datetime.timedelta(seconds=wait_sec),
273 timeout=datetime.timedelta(seconds=timeout_sec),
274 check_result=lambda deployment: deployment is None)
275 retryer(self.get_deployment, deployment_name)
276
277 def list_pods_with_labels(self, labels: dict) -> List[V1Pod]:
278 pod_list: V1PodList = self.api.core.list_namespaced_pod(
279 self.name, label_selector=label_dict_to_selector(labels))
280 return pod_list.items
281
282 def get_pod(self, name: str) -> V1Pod:
283 return self.api.core.read_namespaced_pod(name, self.name)
284
285 def wait_for_pod_started(self,
286 pod_name: str,
287 timeout_sec: int = WAIT_POD_START_TIMEOUT_SEC,
288 wait_sec: int = WAIT_SHORT_SLEEP_SEC) -> None:
289 timeout = datetime.timedelta(seconds=timeout_sec)
290 retryer = retryers.constant_retryer(
291 wait_fixed=datetime.timedelta(seconds=wait_sec),
292 timeout=timeout,
293 check_result=self._pod_started)
294 try:
295 retryer(self.get_pod, pod_name)
296 except retryers.RetryError as e:
297 logger.error(
298 'Timeout %s (h:mm:ss) waiting for pod %s to start. '
299 'Pod status:\n%s', timeout, pod_name,
300 self._pretty_format_status(e.result()))
301 raise
302
303 def port_forward_pod(
304 self,
305 pod: V1Pod,
306 remote_port: int,
307 local_port: Optional[int] = None,
308 local_address: Optional[str] = None,
309 ) -> k8s_port_forwarder.PortForwarder:
310 pf = k8s_port_forwarder.PortForwarder(self.api.context, self.name,
311 f"pod/{pod.metadata.name}",
312 remote_port, local_port,
313 local_address)
314 pf.connect()
315 return pf
316
317 def pod_start_logging(self,
318 *,
319 pod_name: str,
320 log_path: pathlib.Path,
321 log_stop_event: threading.Event,
322 log_to_stdout: bool = False,
323 log_timestamps: bool = False) -> PodLogCollector:
324 pod_log_collector = PodLogCollector(
325 pod_name=pod_name,
326 namespace_name=self.name,
327 read_pod_log_fn=self.api.core.read_namespaced_pod_log,
328 stop_event=log_stop_event,
329 log_path=log_path,
330 log_to_stdout=log_to_stdout,
331 log_timestamps=log_timestamps)
332 pod_log_collector.start()
333 return pod_log_collector
334
335 def _pretty_format_statuses(self,
336 k8s_objects: List[Optional[object]]) -> str:
337 return '\n'.join(
338 self._pretty_format_status(k8s_object)
339 for k8s_object in k8s_objects)
340
341 def _pretty_format_status(self, k8s_object: Optional[object]) -> str:
342 if k8s_object is None:
343 return 'No data'
344
345 # Parse the name if present.
346 if hasattr(k8s_object, 'metadata') and hasattr(k8s_object.metadata,
347 'name'):
348 name = k8s_object.metadata.name
349 else:
350 name = 'Can\'t parse resource name'
351
352 # Pretty-print the status if present.
353 if hasattr(k8s_object, 'status'):
354 try:
355 status = self._pretty_format(k8s_object.status.to_dict())
356 except Exception as e: # pylint: disable=broad-except
357 # Catching all exceptions because not printing the status
358 # isn't as important as the system under test.
359 status = f'Can\'t parse resource status: {e}'
360 else:
361 status = 'Can\'t parse resource status'
362
363 # Return the name of k8s object, and its pretty-printed status.
364 return f'{name}:\n{status}\n'
365
366 def _pretty_format(self, data: dict) -> str:
367 """Return a string with pretty-printed yaml data from a python dict."""
368 yaml_out: str = yaml.dump(data, explicit_start=True, explicit_end=True)
369 return self._highlighter.highlight(yaml_out)
370
371 @classmethod
372 def _check_service_neg_annotation(cls,
373 service: Optional[V1Service]) -> bool:
374 return (isinstance(service, V1Service) and
375 cls.NEG_STATUS_META in service.metadata.annotations)
376
377 @classmethod
378 def _pod_started(cls, pod: V1Pod) -> bool:
379 return (isinstance(pod, V1Pod) and
380 pod.status.phase not in ('Pending', 'Unknown'))
381
382 @classmethod
383 def _replicas_available(cls, deployment: V1Deployment, count: int) -> bool:
384 return (isinstance(deployment, V1Deployment) and
385 deployment.status.available_replicas is not None and
386 deployment.status.available_replicas >= count)