Debian Codegraph @

ansible_collections/kubernetes/core/plugins/module_utils/k8s/waiter.py

raw symbols SCIP
1 import time
2 from functools import partial
3 from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union
4
5 from ansible.module_utils.parsing.convert_bool import boolean
6 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
7 CoreException,
8 )
9
10 try:
11 from kubernetes.dynamic.exceptions import NotFoundError
12 from kubernetes.dynamic.resource import Resource, ResourceField, ResourceInstance
13 except ImportError:
14 # These are defined only for the sake of Ansible's checked import requirement
15 Resource = Any # type: ignore
16 ResourceInstance = Any # type: ignore
17 pass
18
19 try:
20 from urllib3.exceptions import HTTPError
21 except ImportError:
22 # Handled during module setup
23 pass
24
25
26 def deployment_ready(deployment: ResourceInstance) -> bool:
27 # FIXME: frustratingly bool(deployment.status) is True even if status is empty
28 # Furthermore deployment.status.availableReplicas == deployment.status.replicas == None if status is empty
29 # deployment.status.replicas is None is perfectly ok if desired replicas == 0
30 # Scaling up means that we also need to check that we're not in a
31 # situation where status.replicas == status.availableReplicas
32 # but spec.replicas != status.replicas
33 return bool(
34 deployment.status
35 and deployment.spec.replicas == (deployment.status.replicas or 0)
36 and deployment.status.availableReplicas == deployment.status.replicas
37 and deployment.status.observedGeneration == deployment.metadata.generation
38 and not deployment.status.unavailableReplicas
39 )
40
41
42 def pod_ready(pod: ResourceInstance) -> bool:
43 return bool(
44 pod.status
45 and pod.status.containerStatuses is not None
46 and all(container.ready for container in pod.status.containerStatuses)
47 )
48
49
50 def daemonset_ready(daemonset: ResourceInstance) -> bool:
51 return bool(
52 daemonset.status
53 and daemonset.status.desiredNumberScheduled is not None
54 and (daemonset.status.updatedNumberScheduled or 0)
55 == daemonset.status.desiredNumberScheduled
56 and daemonset.status.numberReady == daemonset.status.desiredNumberScheduled
57 and daemonset.status.observedGeneration == daemonset.metadata.generation
58 and not daemonset.status.unavailableReplicas
59 )
60
61
62 def statefulset_ready(statefulset: ResourceInstance) -> bool:
63 if statefulset.spec.updateStrategy.type == "OnDelete":
64 return bool(
65 statefulset.status
66 and statefulset.status.observedGeneration
67 == (statefulset.metadata.generation or 0)
68 and statefulset.status.replicas == statefulset.spec.replicas
69 )
70 # These may be None
71 updated_replicas = statefulset.status.updatedReplicas or 0
72 ready_replicas = statefulset.status.readyReplicas or 0
73 return bool(
74 statefulset.status
75 and statefulset.spec.updateStrategy.type == "RollingUpdate"
76 and statefulset.status.observedGeneration
77 == (statefulset.metadata.generation or 0)
78 and statefulset.status.updateRevision == statefulset.status.currentRevision
79 and updated_replicas == statefulset.spec.replicas
80 and ready_replicas == statefulset.spec.replicas
81 and statefulset.status.replicas == statefulset.spec.replicas
82 )
83
84
85 def custom_condition(condition: Dict, resource: ResourceInstance) -> bool:
86 if not resource.status or not resource.status.conditions:
87 return False
88 matches = [x for x in resource.status.conditions if x.type == condition["type"]]
89 if not matches:
90 return False
91 # There should never be more than one condition of a specific type
92 match: ResourceField = matches[0]
93 if match.status == "Unknown":
94 if match.status == condition["status"]:
95 if "reason" not in condition:
96 return True
97 if condition["reason"]:
98 return match.reason == condition["reason"]
99 return False
100 status = True if match.status == "True" else False
101 if status == boolean(condition["status"], strict=False):
102 if condition.get("reason"):
103 return match.reason == condition["reason"]
104 return True
105 return False
106
107
108 def resource_absent(resource: ResourceInstance) -> bool:
109 return not exists(resource)
110
111
112 def exists(resource: Optional[ResourceInstance]) -> bool:
113 """Simple predicate to check for existence of a resource.
114
115 While a List type resource technically always exists, this will only return
116 true if the List contains items."""
117 return bool(resource) and not empty_list(resource)
118
119
120 def cluster_operator_ready(resource: ResourceInstance) -> bool:
121 """
122 Predicate to check if a single ClusterOperator is healthy.
123 Returns True if:
124 - "Available" is True
125 - "Degraded" is False
126 - "Progressing" is False
127 """
128 if not resource:
129 return False
130
131 # Extract conditions from the resource's status
132 conditions = resource.get("status", {}).get("conditions", [])
133
134 status = {x.get("type", ""): x.get("status") for x in conditions}
135 return (
136 (status.get("Degraded") == "False")
137 and (status.get("Progressing") == "False")
138 and (status.get("Available") == "True")
139 )
140
141
142 RESOURCE_PREDICATES = {
143 "DaemonSet": daemonset_ready,
144 "Deployment": deployment_ready,
145 "Pod": pod_ready,
146 "StatefulSet": statefulset_ready,
147 "ClusterOperator": cluster_operator_ready,
148 }
149
150
151 def empty_list(resource: ResourceInstance) -> bool:
152 return resource["kind"].endswith("List") and not resource.get("items")
153
154
155 def clock(total: int, interval: int) -> Iterator[int]:
156 start = time.monotonic()
157 yield 0
158 while (time.monotonic() - start) < total:
159 time.sleep(interval)
160 yield int(time.monotonic() - start)
161
162
163 class Waiter:
164 def __init__(
165 self, client, resource: Resource, predicate: Callable[[ResourceInstance], bool]
166 ):
167 self.client = client
168 self.resource = resource
169 self.predicate = predicate
170
171 def wait(
172 self,
173 timeout: int,
174 sleep: int,
175 name: Optional[str] = None,
176 namespace: Optional[str] = None,
177 label_selectors: Optional[List[str]] = None,
178 field_selectors: Optional[List[str]] = None,
179 ) -> Tuple[bool, Dict, int]:
180 params = {}
181
182 if name:
183 params["name"] = name
184
185 if namespace:
186 params["namespace"] = namespace
187
188 if label_selectors:
189 params["label_selector"] = ",".join(label_selectors)
190
191 if field_selectors:
192 params["field_selector"] = ",".join(field_selectors)
193
194 instance = {}
195 response = None
196 elapsed = 0
197 for i in clock(timeout, sleep):
198 exception = None
199 elapsed = i
200 try:
201 response = self.client.get(self.resource, **params)
202 except NotFoundError:
203 response = None
204 # Retry connection errors as it may be intermittent network issues
205 except HTTPError as e:
206 exception = e
207 if self.predicate(response):
208 break
209 if exception:
210 msg = (
211 "Exception '{0}' raised while trying to get resource using {1}".format(
212 exception, params
213 )
214 )
215 raise CoreException(msg) from exception
216 if response:
217 instance = response.to_dict()
218 return self.predicate(response), instance, elapsed
219
220
221 class DummyWaiter:
222 """A no-op waiter that simply returns the item being waited on.
223
224 No API call will be made with this waiter; the function returns
225 immediately. This waiter is useful for waiting on resource instances in
226 check mode, for example.
227 """
228
229 def wait(
230 self,
231 definition: Dict,
232 timeout: int,
233 sleep: int,
234 label_selectors: Optional[List[str]] = None,
235 ) -> Tuple[bool, Optional[Dict], int]:
236 return True, definition, 0
237
238
239 # The better solution would be typing.Protocol, but this is only in 3.8+
240 SupportsWait = Union[Waiter, DummyWaiter]
241
242
243 def get_waiter(
244 client,
245 resource: Resource,
246 state: str = "present",
247 condition: Optional[Dict] = None,
248 check_mode: Optional[bool] = False,
249 ) -> SupportsWait:
250 """Create a Waiter object based on the specified resource.
251
252 This is a convenience method for creating a waiter from a resource.
253 Based on the arguments and the kind of resource, an appropriate waiter
254 will be returned. A waiter can also be created directly, of course.
255 """
256 if check_mode:
257 return DummyWaiter()
258 if state == "present":
259 if condition:
260 predicate: Callable[[ResourceInstance], bool] = partial(
261 custom_condition, condition
262 )
263 else:
264 predicate = RESOURCE_PREDICATES.get(resource.kind, exists)
265 else:
266 predicate = resource_absent
267 return Waiter(client, resource, predicate)