Debian Codegraph @

ansible_collections/theforeman/foreman/plugins/module_utils/_apypie.py

raw symbols SCIP
1 # pylint: disable=ansible-format-automatic-specification,raise-missing-from
2 from __future__ import absolute_import, division, print_function
3 __metaclass__ = type
4 from typing import Any, Iterable, List, Optional, Set, Tuple, cast # pylint: disable=unused-import # noqa: F401
5
6
7 """
8 Apypie Action module
9 """
10
11
12 class Action(object):
13 """
14 Apipie Action
15 """
16
17 def __init__(self, name, resource, api):
18 # type: (str, str, Api) -> None
19 self.name = name
20 self.resource = resource
21 self.api = api
22
23 @property
24 def apidoc(self):
25 # type: () -> dict
26 """
27 The apidoc of this action.
28
29 :returns: The apidoc.
30 """
31
32 resource_methods = self.api.apidoc['docs']['resources'][self.resource]['methods']
33 return [method for method in resource_methods if method['name'] == self.name][0]
34
35 @property
36 def routes(self):
37 # type: () -> List[Route]
38 """
39 The routes this action can be invoked by.
40
41 :returns: The routes
42 """
43
44 return [Route(route['api_url'], route['http_method'], route['short_description']) for route in self.apidoc['apis']]
45
46 @property
47 def params(self):
48 # type: () -> List[Param]
49 """
50 The params accepted by this action.
51
52 :returns: The params.
53 """
54
55 return [Param(**param) for param in self.apidoc['params']]
56
57 @property
58 def examples(self):
59 # type: () -> List[Example]
60 """
61 The examples of this action.
62
63 :returns: The examples.
64 """
65
66 return [Example.parse(example) for example in self.apidoc['examples']]
67
68 def call(self, params=None, headers=None, options=None, data=None, files=None): # pylint: disable=too-many-arguments
69 # type: (Optional[dict], Optional[dict], Optional[dict], Optional[Any], Optional[dict]) -> Optional[dict]
70 """
71 Call the API to execute the action.
72
73 :param params: The params that should be passed to the API.
74 :param headers: Additional headers to be passed to the API.
75 :param options: Options
76 :param data: Binary data to be submitted to the API.
77 :param files: Files to be submitted to the API.
78
79 :returns: The API response.
80 """
81
82 return self.api.call(self.resource, self.name, params, headers, options, data, files)
83
84 def find_route(self, params=None):
85 # type: (Optional[dict]) -> Route
86 """
87 Find the best matching route for a given set of params.
88
89 :param params: Params that should be submitted to the API.
90
91 :returns: The best route.
92 """
93
94 param_keys = set(self.filter_empty_params(params).keys())
95 sorted_routes = sorted(self.routes, key=lambda route: [-1 * len(route.params_in_path), route.path])
96 for route in sorted_routes:
97 if set(route.params_in_path) <= param_keys:
98 return route
99 return sorted_routes[-1]
100
101 def validate(self, values, data=None, files=None):
102 # type: (dict, Optional[Any], Optional[dict]) -> None
103 """
104 Validate a given set of parameter values against the required set of parameters.
105
106 :param values: The values to validate.
107 :param data: Additional binary data to validate.
108 :param files: Additional files to validate.
109 """
110
111 self._validate(self.params, values, data, files)
112
113 @staticmethod
114 def _add_to_path(path=None, additions=None):
115 # type: (Optional[str], Optional[List[str]]) -> str
116 if path is None:
117 path = ''
118 if additions is None:
119 additions = []
120 for addition in additions:
121 if path == '':
122 path = "{}".format(addition)
123 else:
124 path = "{}[{}]".format(path, addition)
125 return path
126
127 def _validate(self, params, values, data=None, files=None, path=None): # pylint: disable=too-many-arguments,too-many-locals
128 # type: (Iterable[Param], dict, Optional[Any], Optional[dict], Optional[str]) -> None
129 if not isinstance(values, dict):
130 raise InvalidArgumentTypesError
131 given_params = set(values.keys())
132 given_files = set((files or {}).keys())
133 given_data = set((data or {}).keys())
134 required_params = {param.name for param in params if param.required}
135 missing_params = required_params - given_params - given_files - given_data
136 if missing_params:
137 missing_params_with_path = [self._add_to_path(path, [param]) for param in missing_params]
138 message = "The following required parameters are missing: {}".format(', '.join(missing_params_with_path))
139 raise MissingArgumentsError(message)
140
141 for param, value in values.items():
142 param_descriptions = [p for p in params if p.name == param]
143 if param_descriptions:
144 param_description = param_descriptions[0]
145 if param_description.params and value is not None:
146 if param_description.expected_type == 'array':
147 for num, item in enumerate(value):
148 self._validate(param_description.params, item, path=self._add_to_path(path, [param_description.name, str(num)]))
149 elif param_description.expected_type == 'hash':
150 self._validate(param_description.params, value, path=self._add_to_path(path, [param_description.name]))
151 if (param_description.expected_type == 'numeric' and isinstance(value, str)):
152 try:
153 value = int(value)
154 except ValueError:
155 # this will be caught in the next check
156 pass
157 if (not param_description.allow_nil and value is None):
158 raise ValueError("{} can't be {}".format(param, value))
159 # pylint: disable=too-many-boolean-expressions
160 if (value is not None
161 and ((param_description.expected_type == 'boolean' and not isinstance(value, bool) and not (isinstance(value, int) and value in [0, 1]))
162 or (param_description.expected_type == 'numeric' and not isinstance(value, int))
163 or (param_description.expected_type == 'string' and not isinstance(value, (str, int))))):
164 raise ValueError("{} ({}): {}".format(param, value, param_description.validator))
165
166 @staticmethod
167 def filter_empty_params(params=None):
168 # type: (Optional[dict]) -> dict
169 """
170 Filter out any params that have no value.
171
172 :param params: The params to filter.
173
174 :returns: The filtered params.
175 """
176 result = {}
177 if params is not None:
178 if isinstance(params, dict):
179 result = {k: v for k, v in params.items() if v is not None}
180 else:
181 raise InvalidArgumentTypesError
182 return result
183
184 def prepare_params(self, input_dict):
185 # type: (dict) -> dict
186 """
187 Transform a dict with data into one that can be accepted as params for calling the action.
188
189 This will ignore any keys that are not accepted as params when calling the action.
190 It also allows generating nested params without forcing the user to care about them.
191
192 :param input_dict: a dict with data that should be used to fill in the params
193 :return: :class:`dict` object
194 :rtype: dict
195
196 Usage::
197
198 >>> action.prepare_params({'id': 1})
199 {'user': {'id': 1}}
200 """
201 params = self._prepare_params(self.params, input_dict)
202 route_params = self._prepare_route_params(input_dict)
203 params.update(route_params)
204 return params
205
206 def _prepare_params(self, action_params, input_dict):
207 # type: (Iterable[Param], dict) -> dict
208 result = {}
209
210 for param in action_params:
211 if param.expected_type == 'hash' and param.params:
212 nested_dict = input_dict.get(param.name, input_dict)
213 nested_result = self._prepare_params(param.params, nested_dict)
214 if nested_result:
215 result[param.name] = nested_result
216 elif param.name in input_dict:
217 result[param.name] = input_dict[param.name]
218
219 return result
220
221 def _prepare_route_params(self, input_dict):
222 # type: (dict) -> dict
223 result = {}
224
225 route = self.find_route(input_dict)
226
227 for url_param in route.params_in_path:
228 if url_param in input_dict:
229 result[url_param] = input_dict[url_param]
230
231 return result
232
233
234 """
235 Apypie Api module
236 """
237
238
239 import errno
240 import glob
241 import json
242 from json.decoder import JSONDecodeError # type: ignore
243
244 import os
245 from urllib.parse import urljoin # type: ignore
246 try:
247 import requests
248 except ImportError:
249 pass
250
251 try:
252 from requests_gssapi import HTTPKerberosAuth # type: ignore
253 except ImportError:
254 try:
255 from requests_kerberos import HTTPKerberosAuth # type: ignore
256 except ImportError:
257 HTTPKerberosAuth = None
258
259 try:
260 from requests_oauthlib import OAuth1 # type: ignore
261 except ImportError:
262 OAuth1 = None
263
264 NO_CONTENT = 204
265
266
267 def _qs_param(param):
268 # type: (Any) -> Any
269 if isinstance(param, bool):
270 return str(param).lower()
271 return param
272
273
274 def _qs_key(k, v):
275 if isinstance(v, (list, tuple)):
276 return f"{k}[]"
277 return k
278
279
280 class Api(object):
281 """
282 Apipie API bindings
283
284 :param uri: base URL of the server
285 :param username: username to access the API
286 :param password: password to access the API
287 :param client_cert: client cert to access the API
288 :param client_key: client key to access the API
289 :param kerberos: use Kerberos/GSSAPI for authentication with the API. Requires either `requests-gssapi` or `requests-kerberos`.
290 :param oauth1_consumer_key: OAuth1 consumer key. Requires `requests-oauthlib`.
291 :param oauth1_consumer_secret: OAuth1 consumer secret. Requires `requests-oauthlib`.
292 :param api_version: version of the API. Defaults to `1`
293 :param language: prefered locale for the API description
294 :param apidoc_cache_base_dir: base directory for building apidoc_cache_dir. Defaults to `~/.cache/apipie_bindings`.
295 :param apidoc_cache_dir: where to cache the JSON description of the API. Defaults to `apidoc_cache_base_dir/<URI>`.
296 :param apidoc_cache_name: name of the cache file. If there is cache in the `apidoc_cache_dir`, it is used. Defaults to `default`.
297 :param verify_ssl: should the SSL certificate be verified. Defaults to `True`.
298 :param session: a `requests.Session` compatible object. Defaults to `requests.Session()`.
299
300 Usage::
301
302 >>> import apypie
303 >>> api = apypie.Api(uri='https://api.example.com', username='admin', password='changeme')
304 """
305
306 def __init__(self, **kwargs):
307 self.uri = kwargs.get('uri')
308 self.api_version = kwargs.get('api_version', 1)
309 self.language = kwargs.get('language')
310
311 # Find where to put the cache by default according to the XDG spec
312 # Not using just get('XDG_CACHE_HOME', '~/.cache') because the spec says
313 # that the defaut should be used if "$XDG_CACHE_HOME is either not set or empty"
314 xdg_cache_home = os.environ.get('XDG_CACHE_HOME', None)
315 if not xdg_cache_home:
316 xdg_cache_home = '~/.cache'
317
318 apidoc_cache_base_dir = kwargs.get('apidoc_cache_base_dir', os.path.join(os.path.expanduser(xdg_cache_home), 'apypie'))
319 apidoc_cache_dir_default = os.path.join(apidoc_cache_base_dir, self.uri.replace(':', '_').replace('/', '_'), 'v{}'.format(self.api_version))
320 self.apidoc_cache_dir = kwargs.get('apidoc_cache_dir', apidoc_cache_dir_default)
321 self.apidoc_cache_name = kwargs.get('apidoc_cache_name', self._find_cache_name())
322
323 self._session = kwargs.get('session') or requests.Session()
324 self._session.verify = kwargs.get('verify_ssl', True)
325
326 self._session.headers['Accept'] = 'application/json;version={}'.format(self.api_version)
327 self._session.headers['User-Agent'] = 'apypie (https://github.com/Apipie/apypie)'
328 if self.language:
329 self._session.headers['Accept-Language'] = self.language
330
331 if kwargs.get('username') and kwargs.get('password'):
332 self._session.auth = (kwargs['username'], kwargs['password'])
333
334 if kwargs.get('client_cert') and kwargs.get('client_key'):
335 self._session.cert = (kwargs['client_cert'], kwargs['client_key'])
336
337 if kwargs.get('kerberos'):
338 if HTTPKerberosAuth is not None:
339 self._session.auth = HTTPKerberosAuth()
340 else:
341 raise ValueError('Kerberos authentication requested, but neither requests-gssapi nor requests-kerberos found.')
342
343 oauth1_consumer_key = kwargs.get('oauth1_consumer_key')
344 oauth1_consumer_secret = kwargs.get('oauth1_consumer_secret')
345 if oauth1_consumer_key and oauth1_consumer_secret:
346 if OAuth1 is not None:
347 self._session.auth = OAuth1(
348 oauth1_consumer_key,
349 client_secret=oauth1_consumer_secret,
350 )
351 else:
352 raise ValueError('OAuth1 authentication requested, but requests-oauthlib not found.')
353
354 self._apidoc = None
355
356 @property
357 def apidoc(self):
358 # type: () -> dict
359 """
360 The full apidoc.
361
362 The apidoc will be fetched from the server, if that didn't happen yet.
363
364 :returns: The apidoc.
365 """
366
367 if self._apidoc is None:
368 self._apidoc = self._load_apidoc()
369 return self._apidoc
370
371 @property
372 def apidoc_cache_file(self):
373 # type: () -> str
374 """
375 Full local path to the cached apidoc.
376 """
377
378 return os.path.join(self.apidoc_cache_dir, '{0}{1}'.format(self.apidoc_cache_name, self.cache_extension))
379
380 def _cache_dir_contents(self):
381 # type: () -> Iterable[str]
382 return glob.iglob(os.path.join(self.apidoc_cache_dir, '*{}'.format(self.cache_extension)))
383
384 def _find_cache_name(self, default='default'):
385 cache_file = next(self._cache_dir_contents(), None)
386 cache_name = default
387 if cache_file:
388 cache_name = os.path.basename(cache_file)[:-len(self.cache_extension)]
389 return cache_name
390
391 def validate_cache(self, cache_name=None):
392 # type: (Optional[str]) -> None
393 """
394 Ensure the cached apidoc matches the one presented by the server.
395
396 :param cache_name: The name of the apidoc on the server.
397 """
398
399 if cache_name is not None and cache_name != self.apidoc_cache_name:
400 self.clean_cache()
401 self.apidoc_cache_name = os.path.basename(os.path.normpath(cache_name))
402
403 def clean_cache(self):
404 # type: () -> None
405 """
406 Remove any locally cached apidocs.
407 """
408
409 self._apidoc = None
410 for filename in self._cache_dir_contents():
411 os.unlink(filename)
412
413 @property
414 def resources(self):
415 # type: () -> Iterable
416 """
417 List of available resources.
418
419 Usage::
420
421 >>> api.resources
422 ['comments', 'users']
423 """
424 return sorted(self.apidoc['docs']['resources'].keys())
425
426 def resource(self, name):
427 # type: (str) -> Resource
428 """
429 Get a resource.
430
431 :param name: the name of the resource to load
432 :return: :class:`Resource <Resource>` object
433 :rtype: apypie.Resource
434
435 Usage::
436
437 >>> api.resource('users')
438 """
439 if name in self.resources:
440 return Resource(self, name)
441 message = "Resource '{}' does not exist in the API. Existing resources: {}".format(name, ', '.join(sorted(self.resources)))
442 raise KeyError(message)
443
444 def _load_apidoc(self):
445 # type: () -> dict
446 try:
447 with open(self.apidoc_cache_file, 'r') as apidoc_file: # pylint:disable=all
448 api_doc = json.load(apidoc_file)
449 except (IOError, JSONDecodeError):
450 api_doc = self._retrieve_apidoc()
451 return api_doc
452
453 def _retrieve_apidoc(self):
454 # type: () -> dict
455 try:
456 os.makedirs(self.apidoc_cache_dir)
457 except OSError as err:
458 if err.errno != errno.EEXIST or not os.path.isdir(self.apidoc_cache_dir):
459 raise
460 response = None
461 if self.language:
462 response = self._retrieve_apidoc_call('/apidoc/v{0}.{1}.json'.format(self.api_version, self.language), safe=True)
463 language_family = self.language.split('_')[0]
464 if not response and language_family != self.language:
465 response = self._retrieve_apidoc_call('/apidoc/v{0}.{1}.json'.format(self.api_version, language_family), safe=True)
466 if not response:
467 try:
468 response = self._retrieve_apidoc_call('/apidoc/v{}.json'.format(self.api_version))
469 except Exception as exc:
470 raise DocLoadingError("""Could not load data from {0}: {1}
471 - is your server down?""".format(self.uri, exc))
472 if not response:
473 raise DocLoadingError("""Could not load data from {0}""".format(self.uri))
474 with open(self.apidoc_cache_file, 'w') as apidoc_file: # pylint:disable=all
475 apidoc_file.write(json.dumps(response))
476 return response
477
478 def _retrieve_apidoc_call(self, path, safe=False):
479 # type: (str, bool) -> Optional[dict]
480 try:
481 return self.http_call('get', path)
482 except Exception:
483 if not safe:
484 raise
485 return None
486
487 def call(self, resource_name, action_name, params=None, headers=None, options=None, data=None, files=None): # pylint: disable=too-many-arguments
488 # type: (str, str, Optional[dict], Optional[dict], Optional[dict], Optional[dict], Optional[dict]) -> Optional[dict]
489 """
490 Call an action in the API.
491
492 It finds most fitting route based on given parameters
493 with other attributes necessary to do an API call.
494
495 :param resource_name: name of the resource
496 :param action_name: action_name name of the action
497 :param params: Dict of parameters to be sent in the request
498 :param headers: Dict of headers to be sent in the request
499 :param options: Dict of options to influence the how the call is processed
500 * `skip_validation` (Bool) *false* - skip validation of parameters
501 :param data: Binary data to be sent in the request
502 :param files: Binary files to be sent in the request
503 :return: :class:`dict` object
504 :rtype: dict
505
506 Usage::
507
508 >>> api.call('users', 'show', {'id': 1})
509 """
510 if options is None:
511 options = {}
512 if params is None:
513 params = {}
514
515 resource = Resource(self, resource_name)
516 action = resource.action(action_name)
517 if not options.get('skip_validation', False):
518 action.validate(params, data, files)
519
520 return self._call_action(action, params, headers, data, files)
521
522 def _call_action(self, action, params=None, headers=None, data=None, files=None): # pylint: disable=too-many-arguments
523 # type: (Action, Optional[dict], Optional[dict], Optional[dict], Optional[dict]) -> Optional[dict]
524 if params is None:
525 params = {}
526
527 route = action.find_route(params)
528 get_params = {key: value for key, value in params.items() if key not in route.params_in_path}
529 return self.http_call(
530 route.method,
531 route.path_with_params(params),
532 get_params,
533 headers, data, files)
534
535 def http_call(self, http_method, path, params=None, headers=None, data=None, files=None): # pylint: disable=too-many-arguments
536 # type: (str, str, Optional[dict], Optional[dict], Optional[dict], Optional[dict]) -> Optional[dict]
537 """
538 Execute an HTTP request.
539
540 :param params: Dict of parameters to be sent in the request
541 :param headers: Dict of headers to be sent in the request
542 :param data: Binary data to be sent in the request
543 :param files: Binary files to be sent in the request
544
545 :return: :class:`dict` object
546 :rtype: dict
547 """
548
549 full_path = urljoin(self.uri, path)
550 kwargs = {
551 'verify': self._session.verify,
552 }
553
554 if headers:
555 kwargs['headers'] = headers
556
557 if params:
558 if http_method in ['get', 'head']:
559 kwargs['params'] = {_qs_key(k, v): _qs_param(v) for k, v in params.items()}
560 else:
561 kwargs['json'] = params
562 elif http_method in ['post', 'put', 'patch'] and not data and not files:
563 kwargs['json'] = {}
564
565 if files:
566 kwargs['files'] = files
567
568 if data:
569 kwargs['data'] = data
570
571 request = self._session.request(http_method, full_path, **kwargs)
572 request.raise_for_status()
573 self.validate_cache(request.headers.get('apipie-checksum'))
574 if request.status_code == NO_CONTENT:
575 return None
576 return request.json()
577
578 @property
579 def cache_extension(self):
580 # type: () -> str
581 """
582 File extension for the local cache file.
583
584 Will include the language if set.
585 """
586
587 if self.language:
588 ext = '.{}.json'.format(self.language)
589 else:
590 ext = '.json'
591 return ext
592
593
594 """
595 Apypie Example module
596 """
597
598
599 import re
600
601 EXAMPLE_PARSER = re.compile(r'(\w+)\s+([^\n]*)\n?(.*)\n(\d+)\n(.*)', re.DOTALL)
602
603
604 class Example(object): # pylint: disable=too-few-public-methods
605 """
606 Apipie Example
607 """
608
609 def __init__(self, http_method, path, args, status, response): # pylint: disable=too-many-arguments
610 # type: (str, str, str, str, str) -> None
611 self.http_method = http_method
612 self.path = path
613 self.args = args
614 self.status = int(status)
615 self.response = response
616
617 @classmethod
618 def parse(cls, example):
619 """
620 Parse an example from an apidoc string
621
622 :returns: The parsed :class:`Example`
623 """
624 parsed = EXAMPLE_PARSER.match(example)
625 return cls(*parsed.groups())
626
627
628 """
629 Apypie Exceptions
630 """
631
632
633 class DocLoadingError(Exception):
634 """
635 Exception to be raised when apidoc could not be loaded.
636 """
637
638
639 class MissingArgumentsError(Exception):
640 """
641 Exception to be raised when required arguments are missing.
642 """
643
644
645 class InvalidArgumentTypesError(Exception):
646 """
647 Exception to be raised when arguments are of the wrong type.
648 """
649
650
651 """
652 Apypie Foreman module
653
654 opinionated helpers to use Apypie with Foreman
655 """
656
657 import time
658
659 # Foreman supports "per_page=all" since 2.2 (https://projects.theforeman.org/issues/29909)
660 # But plugins, especially Katello, do not: https://github.com/Katello/katello/pull/11126
661 # To still be able to fetch all results without pagination, we have this constant for now
662 PER_PAGE = 2 << 31
663
664
665 class ForemanApiException(Exception):
666 """
667 General Exception, raised by any issue in ForemanApi
668 """
669
670 def __init__(self, msg, error=None):
671 if error:
672 super().__init__(f'{msg} - {error}')
673 else:
674 super().__init__(msg)
675
676 @classmethod
677 def from_exception(cls, exc, msg):
678 """
679 Create a ForemanException from any other Exception
680
681 Especially useful to gather the error message from HTTP responses.
682 """
683 error = None
684 if hasattr(exc, 'response') and exc.response is not None:
685 try:
686 response = exc.response.json()
687 if 'error' in response:
688 error = response['error']
689 else:
690 error = response
691 except Exception: # pylint: disable=broad-except
692 error = exc.response.text
693 return cls(msg=msg, error=error)
694
695
696 class ForemanApi(Api):
697 """
698 `apypie.Api` with default settings and helper functions for Foreman
699
700 Usage::
701
702 >>> import apypie
703 >>> api = apypie.ForemanApi(uri='https://foreman.example.com', username='admin', password='changeme')
704 """
705
706 def __init__(self, **kwargs):
707 self.task_timeout = kwargs.pop('task_timeout', 60)
708 self.task_poll = 4
709 kwargs['api_version'] = 2
710 super().__init__(**kwargs)
711 if kwargs.get('kerberos'):
712 self.call('users', 'extlogin')
713
714 def _resource(self, resource: str) -> 'Resource':
715 if resource not in self.resources:
716 raise ForemanApiException(msg=f"The server doesn't know about {resource}, is the right plugin installed?")
717 return self.resource(resource)
718
719 def _resource_call(self, resource: str, *args, **kwargs) -> Optional[dict]:
720 return self._resource(resource).call(*args, **kwargs)
721
722 def _resource_prepare_params(self, resource: str, action: str, params: dict) -> dict:
723 api_action = self._resource(resource).action(action)
724 return api_action.prepare_params(params)
725
726 def resource_action(self, resource: str, action: str, params: dict, options=None, data=None, files=None, # pylint: disable=too-many-arguments
727 ignore_task_errors: bool = False) -> Optional[dict]:
728 """
729 Perform a generic action on a resource
730
731 Will wait for tasks if the action returns one
732 """
733 resource_payload = self._resource_prepare_params(resource, action, params)
734 if options is None:
735 options = {}
736 try:
737 result = self._resource_call(resource, action, resource_payload, options=options, data=data, files=files)
738 is_foreman_task = isinstance(result, dict) and 'action' in result and 'state' in result and 'started_at' in result
739 if result and is_foreman_task:
740 result = self.wait_for_task(result, ignore_errors=ignore_task_errors)
741 except Exception as exc:
742 msg = f'Error while performing {action} on {resource}: {exc}'
743 raise ForemanApiException.from_exception(exc, msg) from exc
744 return result
745
746 def wait_for_task(self, task: dict, ignore_errors: bool = False) -> dict:
747 """
748 Wait for a foreman-tasks task, polling it every ``self.task_poll`` seconds.
749
750 Will raise a ForemanApiException when task has not finished in ``self.task_timeout`` seconds.
751 """
752 duration = self.task_timeout
753 while task['state'] not in ['paused', 'stopped']:
754 duration -= self.task_poll
755 if duration <= 0:
756 raise ForemanApiException(msg=f"Timeout waiting for Task {task['id']}")
757 time.sleep(self.task_poll)
758
759 resource_payload = self._resource_prepare_params('foreman_tasks', 'show', {'id': task['id']})
760 task = cast(dict, self._resource_call('foreman_tasks', 'show', resource_payload))
761 if not ignore_errors and task['result'] != 'success':
762 msg = f"Task {task['action']}({task['id']}) did not succeed. Task information: {task['humanized']['errors']}"
763 raise ForemanApiException(msg=msg)
764 return task
765
766 def show(self, resource: str, resource_id: int, params: Optional[dict] = None) -> Optional[dict]:
767 """
768 Execute the ``show`` action on an entity.
769
770 :param resource: Plural name of the api resource to show
771 :param resource_id: The ID of the entity to show
772 :param params: Lookup parameters (i.e. parent_id for nested entities)
773
774 :return: The entity
775 """
776 payload = {'id': resource_id}
777 if params:
778 payload.update(params)
779 return self.resource_action(resource, 'show', payload)
780
781 def list(self, resource: str, search: Optional[str] = None, params: Optional[dict] = None) -> list:
782 """
783 Execute the ``index`` action on an resource.
784
785 :param resource: Plural name of the api resource to show
786 :param search: Search string as accepted by the API to limit the results
787 :param params: Lookup parameters (i.e. parent_id for nested entities)
788
789 :return: List of results
790 """
791 payload: dict = {'per_page': PER_PAGE}
792 if search is not None:
793 payload['search'] = search
794 if params:
795 payload.update(params)
796
797 result = self.resource_action(resource, 'index', payload)
798 if result:
799 return result['results']
800 return []
801
802 def create(self, resource: str, desired_entity: dict, params: Optional[dict] = None) -> Optional[dict]:
803 """
804 Create entity with given properties
805
806 :param resource: Plural name of the api resource to manipulate
807 :param desired_entity: Desired properties of the entity
808 :param params: Lookup parameters (i.e. parent_id for nested entities)
809
810 :return: The new current state of the entity
811 """
812 payload = desired_entity.copy()
813 if params:
814 payload.update(params)
815 return self.resource_action(resource, 'create', payload)
816
817 def update(self, resource: str, desired_entity: dict, params: Optional[dict] = None) -> Optional[dict]:
818 """
819 Update entity with given properties
820
821 :param resource: Plural name of the api resource to manipulate
822 :param desired_entity: Desired properties of the entity
823 :param params: Lookup parameters (i.e. parent_id for nested entities)
824
825 :return: The new current state of the entity
826 """
827 payload = desired_entity.copy()
828 if params:
829 payload.update(params)
830 return self.resource_action(resource, 'update', payload)
831
832 def delete(self, resource: str, current_entity: dict, params: Optional[dict] = None) -> None:
833 """
834 Delete a given entity
835
836 :param resource: Plural name of the api resource to manipulate
837 :param current_entity: Current properties of the entity
838 :param params: Lookup parameters (i.e. parent_id for nested entities)
839
840 :return: The new current state of the entity
841 """
842 payload = {'id': current_entity['id']}
843 if params:
844 payload.update(params)
845 entity = self.resource_action(resource, 'destroy', payload)
846
847 # this is a workaround for https://projects.theforeman.org/issues/26937
848 if entity and isinstance(entity, dict) and 'error' in entity and 'message' in entity['error']:
849 raise ForemanApiException(msg=entity['error']['message'])
850
851 def validate_payload(self, resource: str, action: str, payload: dict) -> Tuple[dict, Set[str]]:
852 """
853 Check whether the payload only contains supported keys.
854
855 :param resource: Plural name of the api resource to check
856 :param action: Name of the action to check payload against
857 :param payload: API paylod to be checked
858
859 :return: The payload as it can be submitted to the API and set of unssuported parameters
860 """
861 filtered_payload = self._resource_prepare_params(resource, action, payload)
862 unsupported_parameters = set(payload.keys()) - _recursive_dict_keys(filtered_payload)
863 return (filtered_payload, unsupported_parameters)
864
865
866 def _recursive_dict_keys(a_dict: dict) -> set:
867 """Find all keys of a nested dictionary"""
868 keys = set(a_dict.keys())
869 for value in a_dict.values():
870 if isinstance(value, dict):
871 keys.update(_recursive_dict_keys(value))
872 return keys
873
874
875 """
876 Apypie Inflector module
877
878 Based on ActiveSupport Inflector (https://github.com/rails/rails.git)
879 Inflection rules taken from davidcelis's Inflections (https://github.com/davidcelis/inflections.git)
880 """
881
882
883 import re
884
885
886 class Inflections(object):
887 """
888 Inflections - rules how to convert words from singular to plural and vice versa.
889 """
890
891 def __init__(self):
892 self.plurals = []
893 self.singulars = []
894 self.uncountables = []
895 self.humans = []
896 self.acronyms = {}
897 self.acronym_regex = r'/(?=a)b/'
898
899 def acronym(self, word):
900 # type: (str) -> None
901 """
902 Add a new acronym.
903 """
904
905 self.acronyms[word.lower()] = word
906 self.acronym_regex = '|'.join(self.acronyms.values())
907
908 def plural(self, rule, replacement):
909 # type: (str, str) -> None
910 """
911 Add a new plural rule.
912 """
913
914 if rule in self.uncountables:
915 self.uncountables.remove(rule)
916 if replacement in self.uncountables:
917 self.uncountables.remove(replacement)
918
919 self.plurals.insert(0, (rule, replacement))
920
921 def singular(self, rule, replacement):
922 # type: (str, str) -> None
923 """
924 Add a new singular rule.
925 """
926
927 if rule in self.uncountables:
928 self.uncountables.remove(rule)
929 if replacement in self.uncountables:
930 self.uncountables.remove(replacement)
931
932 self.singulars.insert(0, (rule, replacement))
933
934 def irregular(self, singular, plural):
935 # type: (str, str) -> None
936 """
937 Add a new irregular rule
938 """
939
940 if singular in self.uncountables:
941 self.uncountables.remove(singular)
942 if plural in self.uncountables:
943 self.uncountables.remove(plural)
944
945 sfirst = singular[0]
946 srest = singular[1:]
947
948 pfirst = plural[0]
949 prest = plural[1:]
950
951 if sfirst.upper() == pfirst.upper():
952 self.plural(r'(?i)({}){}$'.format(sfirst, srest), r'\1' + prest)
953 self.plural(r'(?i)({}){}$'.format(pfirst, prest), r'\1' + prest)
954
955 self.singular(r'(?i)({}){}$'.format(sfirst, srest), r'\1' + srest)
956 self.singular(r'(?i)({}){}$'.format(pfirst, prest), r'\1' + srest)
957 else:
958 self.plural(r'{}(?i){}$'.format(sfirst.upper(), srest), pfirst.upper() + prest)
959 self.plural(r'{}(?i){}$'.format(sfirst.lower(), srest), pfirst.lower() + prest)
960 self.plural(r'{}(?i){}$'.format(pfirst.upper(), prest), pfirst.upper() + prest)
961 self.plural(r'{}(?i){}$'.format(pfirst.lower(), prest), pfirst.lower() + prest)
962
963 self.singular(r'{}(?i){}$'.format(sfirst.upper(), srest), sfirst.upper() + srest)
964 self.singular(r'{}(?i){}$'.format(sfirst.lower(), srest), sfirst.lower() + srest)
965 self.singular(r'{}(?i){}$'.format(pfirst.upper(), prest), sfirst.upper() + srest)
966 self.singular(r'{}(?i){}$'.format(pfirst.lower(), prest), sfirst.lower() + srest)
967
968 def uncountable(self, *words):
969 """
970 Add new uncountables.
971 """
972
973 self.uncountables.extend(words)
974
975 def human(self, rule, replacement):
976 # type: (str, str) -> None
977 """
978 Add a new humanize rule.
979 """
980
981 self.humans.insert(0, (rule, replacement))
982
983
984 class Inflector(object):
985 """
986 Inflector - perform inflections
987 """
988
989 def __init__(self):
990 # type: () -> None
991 self.inflections = Inflections()
992 self.inflections.plural(r'$', 's')
993 self.inflections.plural(r'(?i)([sxz]|[cs]h)$', r'\1es')
994 self.inflections.plural(r'(?i)([^aeiouy]o)$', r'\1es')
995 self.inflections.plural(r'(?i)([^aeiouy])y$', r'\1ies')
996
997 self.inflections.singular(r'(?i)s$', r'')
998 self.inflections.singular(r'(?i)(ss)$', r'\1')
999 self.inflections.singular(r'([sxz]|[cs]h)es$', r'\1')
1000 self.inflections.singular(r'([^aeiouy]o)es$', r'\1')
1001 self.inflections.singular(r'(?i)([^aeiouy])ies$', r'\1y')
1002
1003 self.inflections.irregular('child', 'children')
1004 self.inflections.irregular('man', 'men')
1005 self.inflections.irregular('medium', 'media')
1006 self.inflections.irregular('move', 'moves')
1007 self.inflections.irregular('person', 'people')
1008 self.inflections.irregular('self', 'selves')
1009 self.inflections.irregular('sex', 'sexes')
1010 self.inflections.irregular('erratum', 'errata')
1011
1012 self.inflections.uncountable('equipment', 'information', 'money', 'species', 'series', 'fish', 'sheep', 'police')
1013
1014 def pluralize(self, word):
1015 # type: (str) -> str
1016 """
1017 Pluralize a word.
1018 """
1019
1020 return self._apply_inflections(word, self.inflections.plurals)
1021
1022 def singularize(self, word):
1023 # type: (str) -> str
1024 """
1025 Singularize a word.
1026 """
1027
1028 return self._apply_inflections(word, self.inflections.singulars)
1029
1030 def _apply_inflections(self, word, rules):
1031 # type: (str, Iterable[Tuple[str, str]]) -> str
1032 result = word
1033
1034 if word != '' and result.lower() not in self.inflections.uncountables:
1035 for (rule, replacement) in rules:
1036 result = re.sub(rule, replacement, result)
1037 if result != word:
1038 break
1039
1040 return result
1041
1042
1043 """
1044 Apypie Param module
1045 """
1046
1047
1048 import re
1049
1050 HTML_STRIP = re.compile(r'<\/?[^>]+?>')
1051
1052
1053 class Param(object): # pylint: disable=too-many-instance-attributes,too-few-public-methods
1054 """
1055 Apipie Param
1056 """
1057
1058 def __init__(self, **kwargs):
1059 self.allow_nil = kwargs.get('allow_nil')
1060 self.description = HTML_STRIP.sub('', kwargs.get('description'))
1061 self.expected_type = kwargs.get('expected_type')
1062 self.full_name = kwargs.get('full_name')
1063 self.name = kwargs.get('name')
1064 self.params = [Param(**param) for param in kwargs.get('params', [])]
1065 self.required = bool(kwargs.get('required'))
1066 self.validator = kwargs.get('validator')
1067
1068
1069 """
1070 Apypie Resource module
1071 """
1072
1073
1074 class Resource(object):
1075 """
1076 Apipie Resource
1077 """
1078
1079 def __init__(self, api, name):
1080 # type: (Api, str) -> None
1081 self.api = api
1082 self.name = name
1083
1084 @property
1085 def actions(self):
1086 # type: () -> List
1087 """
1088 Actions available for this resource.
1089
1090 :returns: The actions.
1091 """
1092 return sorted([method['name'] for method in self.api.apidoc['docs']['resources'][self.name]['methods']])
1093
1094 def action(self, name):
1095 # type: (str) -> Action
1096 """
1097 Get an :class:`Action` for this resource.
1098
1099 :param name: The name of the action.
1100 """
1101 if self.has_action(name):
1102 return Action(name, self.name, self.api)
1103 message = "Unknown action '{}'. Supported actions: {}".format(name, ', '.join(sorted(self.actions)))
1104 raise KeyError(message)
1105
1106 def has_action(self, name):
1107 # type: (str) -> bool
1108 """
1109 Check whether the resource has a given action.
1110
1111 :param name: The name of the action.
1112 """
1113 return name in self.actions
1114
1115 def call(self, action, params=None, headers=None, options=None, data=None, files=None): # pylint: disable=too-many-arguments
1116 # type: (str, Optional[dict], Optional[dict], Optional[dict], Optional[Any], Optional[dict]) -> Optional[dict]
1117 """
1118 Call the API to execute an action for this resource.
1119
1120 :param action: The action to call.
1121 :param params: The params that should be passed to the API.
1122 :param headers: Additional headers to be passed to the API.
1123 :param options: Options
1124 :param data: Binary data to be submitted to the API.
1125 :param files: Files to be submitted to the API.
1126
1127 :returns: The API response.
1128 """
1129
1130 return self.api.call(self.name, action, params, headers, options, data, files)
1131
1132
1133 """
1134 Apypie Route module
1135 """
1136
1137 from urllib.parse import quote # type: ignore
1138
1139
1140 class Route(object):
1141 """
1142 Apipie Route
1143 """
1144
1145 def __init__(self, path, method, description=""):
1146 # type: (str, str, str) -> None
1147 self.path = path
1148 self.method = method.lower()
1149 self.description = description
1150
1151 @property
1152 def params_in_path(self):
1153 # type: () -> List
1154 """
1155 Params that can be passed in the path (URL) of the route.
1156
1157 :returns: The params.
1158 """
1159 return [part[1:] for part in self.path.split('/') if part.startswith(':')]
1160
1161 def path_with_params(self, params=None):
1162 # type: (Optional[dict]) -> str
1163 """
1164 Fill in the params into the path.
1165
1166 :returns: The path with params.
1167 """
1168 result = self.path
1169 if params is not None:
1170 for param in self.params_in_path:
1171 if param in params:
1172 result = result.replace(':{}'.format(param), quote(str(params[param]), safe=''))
1173 else:
1174 raise KeyError("missing param '{}' in parameters".format(param))
1175 return result