Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_api/errors.py

raw
1 # This code is part of the Ansible collection community.docker, but is an independent component.
2 # This particular file, and this file only, is based on the Docker SDK for Python (https://github.com/docker/docker-py/)
3 #
4 # Copyright (c) 2016-2022 Docker, Inc.
5 #
6 # It is licensed under the Apache 2.0 license (see LICENSES/Apache-2.0.txt in this collection)
7 # SPDX-License-Identifier: Apache-2.0
8
9 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
10 # Do not use this from other collections or standalone plugins/modules!
11
12 from __future__ import annotations
13
14 import typing as t
15
16 from ansible.module_utils.common.text.converters import to_text
17
18 from ._import_helper import HTTPError as _HTTPError
19
20 if t.TYPE_CHECKING:
21 from requests import Response
22
23
24 class DockerException(Exception):
25 """
26 A base class from which all other exceptions inherit.
27
28 If you want to catch all errors that the Docker SDK might raise,
29 catch this base exception.
30 """
31
32
33 def create_api_error_from_http_exception(e: _HTTPError) -> t.NoReturn:
34 """
35 Create a suitable APIError from requests.exceptions.HTTPError.
36 """
37 response = e.response
38 try:
39 explanation = response.json()["message"]
40 except ValueError:
41 explanation = to_text((response.content or "").strip())
42 cls = APIError
43 if response.status_code == 404:
44 if explanation and (
45 "No such image" in str(explanation)
46 or "not found: does not exist or no pull access" in str(explanation)
47 or "repository does not exist" in str(explanation)
48 ):
49 cls = ImageNotFound
50 else:
51 cls = NotFound
52 raise cls(e, response=response, explanation=explanation) from e
53
54
55 class APIError(_HTTPError, DockerException):
56 """
57 An HTTP error from the API.
58 """
59
60 def __init__(
61 self,
62 message: str | Exception,
63 response: Response | None = None,
64 explanation: str | None = None,
65 ) -> None:
66 # requests 1.2 supports response as a keyword argument, but
67 # requests 1.1 does not
68 super().__init__(message)
69 self.response = response
70 self.explanation = explanation or ""
71
72 def __str__(self) -> str:
73 message = super().__str__()
74
75 if self.is_client_error():
76 message = f"{self.response.status_code} Client Error for {self.response.url}: {self.response.reason}"
77
78 elif self.is_server_error():
79 message = f"{self.response.status_code} Server Error for {self.response.url}: {self.response.reason}"
80
81 if self.explanation:
82 message = f'{message} ("{self.explanation}")'
83
84 return message
85
86 @property
87 def status_code(self) -> int | None:
88 if self.response is not None:
89 return self.response.status_code
90 return None
91
92 def is_error(self) -> bool:
93 return self.is_client_error() or self.is_server_error()
94
95 def is_client_error(self) -> bool:
96 if self.status_code is None:
97 return False
98 return 400 <= self.status_code < 500
99
100 def is_server_error(self) -> bool:
101 if self.status_code is None:
102 return False
103 return 500 <= self.status_code < 600
104
105
106 class NotFound(APIError):
107 pass
108
109
110 class ImageNotFound(NotFound):
111 pass
112
113
114 class InvalidVersion(DockerException):
115 pass
116
117
118 class InvalidRepository(DockerException):
119 pass
120
121
122 class InvalidConfigFile(DockerException):
123 pass
124
125
126 class InvalidArgument(DockerException):
127 pass
128
129
130 class DeprecatedMethod(DockerException):
131 pass
132
133
134 class TLSParameterError(DockerException):
135 def __init__(self, msg: str) -> None:
136 self.msg = msg
137
138 def __str__(self) -> str:
139 return self.msg + (
140 ". TLS configurations should map the Docker CLI "
141 "client configurations. See "
142 "https://docs.docker.com/engine/articles/https/ "
143 "for API details."
144 )
145
146
147 class NullResource(DockerException, ValueError):
148 pass
149
150
151 class ContainerError(DockerException):
152 """
153 Represents a container that has exited with a non-zero exit code.
154 """
155
156 def __init__(
157 self,
158 container: str,
159 exit_status: int,
160 command: list[str],
161 image: str,
162 stderr: str | None,
163 ):
164 self.container = container
165 self.exit_status = exit_status
166 self.command = command
167 self.image = image
168 self.stderr = stderr
169
170 err = f": {stderr}" if stderr is not None else ""
171 msg = f"Command '{command}' in image '{image}' returned non-zero exit status {exit_status}{err}"
172
173 super().__init__(msg)
174
175
176 class StreamParseError(RuntimeError):
177 def __init__(self, reason: Exception) -> None:
178 self.msg = reason
179
180
181 class BuildError(DockerException):
182 def __init__(self, reason: str, build_log: str) -> None:
183 super().__init__(reason)
184 self.msg = reason
185 self.build_log = build_log
186
187
188 class ImageLoadError(DockerException):
189 pass
190
191
192 def create_unexpected_kwargs_error(name: str, kwargs: dict[str, t.Any]) -> TypeError:
193 quoted_kwargs = [f"'{k}'" for k in sorted(kwargs)]
194 text = [f"{name}() "]
195 if len(quoted_kwargs) == 1:
196 text.append("got an unexpected keyword argument ")
197 else:
198 text.append("got unexpected keyword arguments ")
199 text.append(", ".join(quoted_kwargs))
200 return TypeError("".join(text))
201
202
203 class MissingContextParameter(DockerException):
204 def __init__(self, param: str) -> None:
205 self.param = param
206
207 def __str__(self) -> str:
208 return f"missing parameter: {self.param}"
209
210
211 class ContextAlreadyExists(DockerException):
212 def __init__(self, name: str) -> None:
213 self.name = name
214
215 def __str__(self) -> str:
216 return f"context {self.name} already exists"
217
218
219 class ContextException(DockerException):
220 def __init__(self, msg: str) -> None:
221 self.msg = msg
222
223 def __str__(self) -> str:
224 return self.msg
225
226
227 class ContextNotFound(DockerException):
228 def __init__(self, name: str) -> None:
229 self.name = name
230
231 def __str__(self) -> str:
232 return f"context '{self.name}' not found"
233
234
235 class MissingRequirementException(DockerException):
236 def __init__(
237 self, msg: str, requirement: str, import_exception: ImportError | str
238 ) -> None:
239 self.msg = msg
240 self.requirement = requirement
241 self.import_exception = import_exception
242
243 def __str__(self) -> str:
244 return self.msg