Debian Codegraph @

ansible_collections/community/dns/plugins/plugin_utils/_resolver.py

raw
1 # Copyright (c) 2023, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this plugin util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import typing as t
11 from collections.abc import Callable
12
13 from ansible.errors import AnsibleError
14 from ansible.module_utils.basic import missing_required_lib
15 from ansible.module_utils.common.text.converters import to_native
16
17 from ansible_collections.community.dns.plugins.module_utils._resolver import (
18 ResolverError,
19 )
20
21 DNSPYTHON_IMPORTERROR: ImportError | None
22 try:
23 import dns # pylint: disable=unused-import
24 import dns.exception # pylint: disable=unused-import
25 import dns.message # pylint: disable=unused-import
26 import dns.name # pylint: disable=unused-import
27 import dns.query # pylint: disable=unused-import
28 import dns.rcode # pylint: disable=unused-import
29 import dns.rdatatype # pylint: disable=unused-import
30 import dns.resolver # pylint: disable=unused-import
31 import dns.version
32 except ImportError as exc:
33 DNSPYTHON_IMPORTERROR = exc
34 else:
35 DNSPYTHON_IMPORTERROR = None # type: ignore # TODO
36
37 if t.TYPE_CHECKING:
38 _T = t.TypeVar("_T")
39
40
41 def guarded_run(
42 runner: Callable[[], _T],
43 error_class: type[Exception] = AnsibleError,
44 server: str | None = None,
45 ) -> _T:
46 suffix = f" for {server}" if server is not None else ""
47 try:
48 return runner()
49 except ResolverError as e:
50 raise error_class(f"Unexpected resolving error{suffix}: {to_native(e)}") from e
51 except dns.exception.DNSException as e:
52 raise error_class(f"Unexpected DNS error{suffix}: {to_native(e)}") from e
53
54
55 def assert_requirements_present(plugin_name: str, plugin_type: str) -> None:
56 if DNSPYTHON_IMPORTERROR is not None:
57 msg = f'The {plugin_name} {plugin_type} plugin is missing requirements: {missing_required_lib("dnspython >= 2.0.0")}'
58 raise AnsibleError(msg) from DNSPYTHON_IMPORTERROR
59 if dns.version.MAJOR < 2:
60 msg = (
61 f'The {plugin_name} {plugin_type} plugin is missing requirements: {missing_required_lib("dnspython >= 2.0.0")}.'
62 f" Found version {dns.version.version}."
63 )
64 raise AnsibleError(msg)