Debian Codegraph @

ansible_collections/community/dns/plugins/module_utils/_http.py

raw
1 # Copyright (c) 2021 Felix Fontein
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 module 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 abc
11 import typing as t
12 from urllib.error import HTTPError
13
14 from ansible.module_utils.common.text.converters import to_native
15 from ansible.module_utils.urls import (
16 ConnectionError, # noqa: A004
17 NoSSLError,
18 fetch_url,
19 open_url,
20 )
21
22 if t.TYPE_CHECKING:
23 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
24
25 HTTPMethod = t.Literal["DELETE", "GET", "HEAD", "POST", "PUT"] # pragma: no cover
26
27
28 class NetworkError(Exception):
29 pass
30
31
32 class HTTPHelper(metaclass=abc.ABCMeta):
33 @abc.abstractmethod
34 def fetch_url(
35 self,
36 url: str,
37 *,
38 method: HTTPMethod = "GET",
39 headers: dict[str, str] | None = None,
40 data: bytes | None = None,
41 timeout: int | None = None,
42 ) -> tuple[bytes | None, dict[str, t.Any]]:
43 """
44 Execute a HTTP request and return a tuple (response_content, info).
45
46 In case of errors, either raise NetworkError or terminate the program (for modules only!).
47 """
48
49
50 class ModuleHTTPHelper(HTTPHelper):
51 def __init__(
52 self,
53 module: AnsibleModule,
54 ) -> None:
55 self.module: AnsibleModule = module
56
57 def fetch_url(
58 self,
59 url: str,
60 *,
61 method: HTTPMethod = "GET",
62 headers: dict[str, str] | None = None,
63 data: bytes | None = None,
64 timeout: int | None = None,
65 ) -> tuple[bytes | None, dict[str, t.Any]]:
66 response, info = fetch_url(
67 self.module, url, method=method, headers=headers, data=data, timeout=timeout
68 )
69 try:
70 # read() from a closed response returns ''
71 if response.closed:
72 raise TypeError
73 content = response.read()
74 except (AttributeError, TypeError):
75 content = info.pop("body", None)
76 return content, info
77
78
79 class OpenURLHelper(HTTPHelper):
80 def fetch_url(
81 self,
82 url: str,
83 *,
84 method: HTTPMethod = "GET",
85 headers: dict[str, str] | None = None,
86 data: bytes | None = None,
87 timeout: int | None = None,
88 ) -> tuple[bytes | None, dict[str, t.Any]]:
89 info = {}
90 try:
91 req = open_url(
92 url, method=method, headers=headers, data=data, timeout=timeout
93 )
94 result = req.read()
95 info.update({k.lower(): v for k, v in req.info().items()})
96 info["status"] = req.code
97 info["url"] = req.geturl()
98 req.close()
99 except HTTPError as e:
100 try:
101 result = e.read()
102 except AttributeError:
103 result = ""
104 try:
105 info.update({k.lower(): v for k, v in e.info().items()})
106 except Exception: # pragma: no cover
107 pass # pragma: no cover
108 info["status"] = e.code
109 except NoSSLError as e:
110 raise NetworkError(f"Cannot connect via SSL: {to_native(e)}") from e
111 except (ConnectionError, ValueError) as e:
112 raise NetworkError(f"Connection error: {to_native(e)}") from e
113
114 return result, info