Debian Codegraph @

lib/ansible/module_utils/facts/timeout.py

raw
1 # This file is part of Ansible
2 #
3 # Ansible is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # Ansible is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
15
16 from __future__ import annotations
17
18 import multiprocessing
19 import multiprocessing.pool as mp
20
21 # timeout function to make sure some fact gathering
22 # steps do not exceed a time limit
23
24 GATHER_TIMEOUT = None
25 DEFAULT_GATHER_TIMEOUT = 10
26
27
28 class TimeoutError(Exception):
29 pass
30
31
32 def timeout(seconds=None, error_message="Timer expired"):
33 """
34 Timeout decorator to expire after a set number of seconds. This raises an
35 ansible.module_utils.facts.TimeoutError if the timeout is hit before the
36 function completes.
37 """
38 def decorator(func):
39 def wrapper(*args, **kwargs):
40 timeout_value = seconds
41 if timeout_value is None:
42 timeout_value = globals().get('GATHER_TIMEOUT') or DEFAULT_GATHER_TIMEOUT
43
44 pool = mp.ThreadPool(processes=1)
45 res = pool.apply_async(func, args, kwargs)
46 pool.close()
47 try:
48 return res.get(timeout_value)
49 except multiprocessing.TimeoutError:
50 # This is an ansible.module_utils.common.facts.timeout.TimeoutError
51 raise TimeoutError(f'{error_message} after {timeout_value} seconds')
52 finally:
53 pool.terminate()
54
55 return wrapper
56
57 # If we were called as @timeout, then the first parameter will be the
58 # function we are to wrap instead of the number of seconds. Detect this
59 # and correct it by setting seconds to our default value and return the
60 # inner decorator function manually wrapped around the function
61 if callable(seconds):
62 func = seconds
63 seconds = None
64 return decorator(func)
65
66 # If we were called as @timeout([...]) then python itself will take
67 # care of wrapping the inner decorator around the function
68
69 return decorator