Debian Codegraph @

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

raw symbols SCIP
1 # Copyright: (c) 2021, Red Hat | Ansible
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 import hashlib
5 import os
6 from typing import Any, Dict, List, Optional
7
8 from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
9 AUTH_ARG_MAP,
10 AUTH_ARG_SPEC,
11 AUTH_PROXY_HEADERS_SPEC,
12 )
13 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
14 requires as _requires,
15 )
16 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
17 CoreException,
18 )
19
20 try:
21 from ansible_collections.kubernetes.core.plugins.module_utils import (
22 k8sdynamicclient,
23 )
24 from ansible_collections.kubernetes.core.plugins.module_utils.client.discovery import (
25 LazyDiscoverer,
26 )
27 except ImportError:
28 # Handled in module setup
29 pass
30
31 try:
32 import kubernetes
33 from kubernetes.dynamic.exceptions import (
34 ResourceNotFoundError,
35 ResourceNotUniqueError,
36 )
37 from kubernetes.dynamic.resource import Resource
38 except ImportError:
39 # kubernetes import error is handled in module setup
40 # This is defined only for the sake of Ansible's checked import requirement
41 Resource = Any # type: ignore
42
43 try:
44 import urllib3
45
46 urllib3.disable_warnings()
47 except ImportError:
48 # Handled in module setup
49 pass
50
51
52 _pool = {}
53
54
55 class unique_string(str):
56 _low = None
57
58 def __hash__(self):
59 return id(self)
60
61 def __eq__(self, other):
62 return self is other
63
64 def lower(self):
65 if self._low is None:
66 lower = str.lower(self)
67 if str.__eq__(lower, self):
68 self._low = self
69 else:
70 self._low = unique_string(lower)
71 return self._low
72
73
74 def _create_auth_spec(module=None, **kwargs) -> Dict:
75 auth: Dict = {}
76 # If authorization variables aren't defined, look for them in environment variables
77 for true_name, arg_name in AUTH_ARG_MAP.items():
78 if module and module.params.get(arg_name) is not None:
79 auth[true_name] = module.params.get(arg_name)
80 elif arg_name in kwargs and kwargs.get(arg_name) is not None:
81 auth[true_name] = kwargs.get(arg_name)
82 elif true_name in kwargs and kwargs.get(true_name) is not None:
83 # Aliases in kwargs
84 auth[true_name] = kwargs.get(true_name)
85 elif arg_name == "proxy_headers":
86 # specific case for 'proxy_headers' which is a dictionary
87 proxy_headers = {}
88 for key in AUTH_PROXY_HEADERS_SPEC.keys():
89 env_value = os.getenv(
90 "K8S_AUTH_PROXY_HEADERS_{0}".format(key.upper()), None
91 )
92 if env_value is not None:
93 if AUTH_PROXY_HEADERS_SPEC[key].get("type") == "bool":
94 env_value = env_value.lower() not in ["0", "false", "no"]
95 proxy_headers[key] = env_value
96 if proxy_headers is not {}:
97 auth[true_name] = proxy_headers
98 else:
99 env_value = os.getenv(
100 "K8S_AUTH_{0}".format(arg_name.upper()), None
101 ) or os.getenv("K8S_AUTH_{0}".format(true_name.upper()), None)
102 if env_value is not None:
103 if AUTH_ARG_SPEC[arg_name].get("type") == "bool":
104 env_value = env_value.lower() not in ["0", "false", "no"]
105 auth[true_name] = env_value
106
107 return auth
108
109
110 def _load_config(auth: Dict) -> None:
111 kubeconfig = auth.get("kubeconfig")
112 optional_arg = {
113 "context": auth.get("context"),
114 "persist_config": auth.get("persist_config"),
115 }
116 if kubeconfig:
117 if isinstance(kubeconfig, str):
118 kubernetes.config.load_kube_config(config_file=kubeconfig, **optional_arg)
119 elif isinstance(kubeconfig, dict):
120 kubernetes.config.load_kube_config_from_dict(
121 config_dict=kubeconfig, **optional_arg
122 )
123 else:
124 kubernetes.config.load_kube_config(config_file=None, **optional_arg)
125
126
127 def _create_configuration(auth: Dict):
128 def auth_set(*names: list) -> bool:
129 return all(auth.get(name) for name in names)
130
131 if auth_set("host"):
132 # Removing trailing slashes if any from hostname
133 auth["host"] = auth.get("host").rstrip("/")
134
135 if (
136 auth_set("username", "password", "host")
137 or auth_set("api_key", "host")
138 or auth_set("cert_file", "key_file", "host")
139 ):
140 # We have enough in the parameters to authenticate, no need to load incluster or kubeconfig
141 pass
142 elif auth_set("kubeconfig") or auth_set("context"):
143 try:
144 _load_config(auth)
145 except Exception as err:
146 raise err
147
148 else:
149 # First try to do incluster config, then kubeconfig
150 try:
151 kubernetes.config.load_incluster_config()
152 except kubernetes.config.ConfigException:
153 try:
154 _load_config(auth)
155 except Exception as err:
156 raise err
157
158 # Override any values in the default configuration with Ansible parameters
159 # As of kubernetes-client v12.0.0, get_default_copy() is required here
160 try:
161 configuration = kubernetes.client.Configuration().get_default_copy()
162 except AttributeError:
163 configuration = kubernetes.client.Configuration()
164
165 for key, value in auth.items():
166 if key in AUTH_ARG_MAP.keys() and value is not None:
167 if key == "api_key":
168 setattr(
169 configuration, key, {"authorization": "Bearer {0}".format(value)}
170 )
171 elif key == "proxy_headers":
172 headers = urllib3.util.make_headers(**value)
173 setattr(configuration, key, headers)
174 else:
175 setattr(configuration, key, value)
176
177 return configuration
178
179
180 def _create_headers(module=None, **kwargs):
181 header_map = {
182 "impersonate_user": "Impersonate-User",
183 "impersonate_groups": "Impersonate-Group",
184 }
185
186 headers = {}
187 for arg_name, header_name in header_map.items():
188 value = None
189 if module and module.params.get(arg_name) is not None:
190 value = module.params.get(arg_name)
191 elif arg_name in kwargs and kwargs.get(arg_name) is not None:
192 value = kwargs.get(arg_name)
193 else:
194 value = os.getenv("K8S_AUTH_{0}".format(arg_name.upper()), None)
195 if value is not None:
196 if AUTH_ARG_SPEC[arg_name].get("type") == "list":
197 value = [x for x in value.split(",") if x != ""]
198 if value:
199 headers[header_name] = value
200 return headers
201
202
203 def _configuration_digest(configuration, **kwargs) -> str:
204 m = hashlib.sha256()
205 for k in AUTH_ARG_MAP:
206 if not hasattr(configuration, k):
207 v = None
208 else:
209 v = getattr(configuration, k)
210 if v and k in ["ssl_ca_cert", "cert_file", "key_file"]:
211 with open(str(v), "r") as fd:
212 content = fd.read()
213 m.update(content.encode())
214 else:
215 m.update(str(v).encode())
216 for k, v in kwargs.items():
217 content = "{0}: {1}".format(k, v)
218 m.update(content.encode())
219 digest = m.hexdigest()
220
221 return digest
222
223
224 def _set_header(client, header, value):
225 if isinstance(value, list):
226 for v in value:
227 client.set_default_header(header_name=unique_string(header), header_value=v)
228 else:
229 client.set_default_header(header_name=header, header_value=value)
230
231
232 def cache(func):
233 def wrapper(*args, **kwargs):
234 client = None
235 hashable_kwargs = {}
236 for k, v in kwargs.items():
237 if isinstance(v, list):
238 hashable_kwargs[k] = ",".join(sorted(v))
239 else:
240 hashable_kwargs[k] = v
241 digest = _configuration_digest(*args, **hashable_kwargs)
242 if digest in _pool:
243 client = _pool[digest]
244 else:
245 client = func(*args, **kwargs)
246 _pool[digest] = client
247
248 return client
249
250 return wrapper
251
252
253 @cache
254 def create_api_client(configuration, **headers):
255 client = kubernetes.client.ApiClient(configuration)
256 for header, value in headers.items():
257 _set_header(client, header, value)
258 return k8sdynamicclient.K8SDynamicClient(client, discoverer=LazyDiscoverer)
259
260
261 class K8SClient:
262 """A Client class for K8S modules.
263
264 This class has the primary purpose to proxy the kubernetes client and resource objects.
265 If there is a need for other methods or attributes to be proxied, they can be added here.
266 """
267
268 K8S_SERVER_DRY_RUN = "All"
269
270 def __init__(self, configuration, client, dry_run: bool = False) -> None:
271 self.configuration = configuration
272 self.client = client
273 self.dry_run = dry_run
274
275 @property
276 def resources(self) -> List[Any]:
277 return self.client.resources
278
279 def _find_resource_with_prefix(
280 self, prefix: str, kind: str, api_version: str
281 ) -> Resource:
282 for attribute in ["kind", "name", "singular_name"]:
283 try:
284 return self.client.resources.get(
285 **{"prefix": prefix, "api_version": api_version, attribute: kind}
286 )
287 except (ResourceNotFoundError, ResourceNotUniqueError):
288 pass
289 return self.client.resources.get(
290 prefix=prefix, api_version=api_version, short_names=[kind]
291 )
292
293 def resource(self, kind: str, api_version: str) -> Resource:
294 """Fetch a kubernetes client resource.
295
296 This will attempt to find a kubernetes resource trying, in order, kind,
297 name, singular_name and short_names.
298 """
299 try:
300 if api_version == "v1":
301 return self._find_resource_with_prefix("api", kind, api_version)
302 except ResourceNotFoundError:
303 pass
304 return self._find_resource_with_prefix(None, kind, api_version)
305
306 def _ensure_dry_run(self, params: Dict) -> Dict:
307 if self.dry_run:
308 params["dry_run"] = self.K8S_SERVER_DRY_RUN
309 return params
310
311 def validate(
312 self, resource, version: Optional[str] = None, strict: Optional[bool] = False
313 ):
314 return self.client.validate(resource, version, strict)
315
316 def get(self, resource, **params):
317 return resource.get(**params)
318
319 def delete(self, resource, **params):
320 return resource.delete(**self._ensure_dry_run(params))
321
322 def apply(self, resource, definition, namespace, **params):
323 return resource.apply(
324 definition, namespace=namespace, **self._ensure_dry_run(params)
325 )
326
327 def create(self, resource, definition, **params):
328 return resource.create(definition, **self._ensure_dry_run(params))
329
330 def replace(self, resource, definition, **params):
331 return resource.replace(definition, **self._ensure_dry_run(params))
332
333 def patch(self, resource, definition, **params):
334 return resource.patch(definition, **self._ensure_dry_run(params))
335
336
337 def get_api_client(module=None, **kwargs: Optional[Any]) -> K8SClient:
338 auth_spec = _create_auth_spec(module, **kwargs)
339 if module:
340 requires = module.requires
341 else:
342 requires = _requires
343 if isinstance(auth_spec.get("kubeconfig"), dict):
344 requires("kubernetes", "17.17.0", "to use in-memory config")
345 if auth_spec.get("no_proxy"):
346 requires("kubernetes", "19.15.0", "to use the no_proxy feature")
347
348 try:
349 configuration = _create_configuration(auth_spec)
350 headers = _create_headers(module, **kwargs)
351 client = create_api_client(configuration, **headers)
352 except kubernetes.config.ConfigException as e:
353 msg = "Could not create API client: {0}".format(e)
354 raise CoreException(msg) from e
355
356 dry_run = False
357 if module and module.server_side_dry_run:
358 dry_run = True
359
360 k8s_client = K8SClient(
361 configuration=configuration,
362 client=client,
363 dry_run=dry_run,
364 )
365
366 return k8s_client