Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_api/context/api.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-2025 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 json
15 import os
16 import typing as t
17
18 from .. import errors
19 from .config import (
20 METAFILE,
21 get_current_context_name,
22 get_meta_dir,
23 write_context_name_to_docker_config,
24 )
25 from .context import Context
26
27 if t.TYPE_CHECKING:
28 from ..tls import TLSConfig
29
30
31 def create_default_context() -> Context:
32 host = None
33 if os.environ.get("DOCKER_HOST"):
34 host = os.environ.get("DOCKER_HOST")
35 return Context(
36 "default", "swarm", host, description="Current DOCKER_HOST based configuration"
37 )
38
39
40 class ContextAPI:
41 """Context API.
42 Contains methods for context management:
43 create, list, remove, get, inspect.
44 """
45
46 DEFAULT_CONTEXT = None
47
48 @classmethod
49 def get_default_context(cls) -> Context:
50 context = cls.DEFAULT_CONTEXT
51 if context is None:
52 context = create_default_context()
53 cls.DEFAULT_CONTEXT = context
54 return context
55
56 @classmethod
57 def create_context(
58 cls,
59 name: str,
60 orchestrator: str | None = None,
61 host: str | None = None,
62 tls_cfg: TLSConfig | None = None,
63 default_namespace: str | None = None,
64 skip_tls_verify: bool = False,
65 ) -> Context:
66 """Creates a new context.
67 Returns:
68 (Context): a Context object.
69 Raises:
70 :py:class:`docker.errors.MissingContextParameter`
71 If a context name is not provided.
72 :py:class:`docker.errors.ContextAlreadyExists`
73 If a context with the name already exists.
74 :py:class:`docker.errors.ContextException`
75 If name is default.
76
77 Example:
78
79 >>> from docker.context import ContextAPI
80 >>> ctx = ContextAPI.create_context(name='test')
81 >>> print(ctx.Metadata)
82 {
83 "Name": "test",
84 "Metadata": {},
85 "Endpoints": {
86 "docker": {
87 "Host": "unix:///var/run/docker.sock",
88 "SkipTLSVerify": false
89 }
90 }
91 }
92 """
93 if not name:
94 raise errors.MissingContextParameter("name")
95 if name == "default":
96 raise errors.ContextException('"default" is a reserved context name')
97 ctx = Context.load_context(name)
98 if ctx:
99 raise errors.ContextAlreadyExists(name)
100 endpoint = "docker"
101 if orchestrator and orchestrator != "swarm":
102 endpoint = orchestrator
103 ctx = Context(name, orchestrator)
104 ctx.set_endpoint(
105 endpoint,
106 host,
107 tls_cfg,
108 skip_tls_verify=skip_tls_verify,
109 def_namespace=default_namespace,
110 )
111 ctx.save()
112 return ctx
113
114 @classmethod
115 def get_context(cls, name: str | None = None) -> Context | None:
116 """Retrieves a context object.
117 Args:
118 name (str): The name of the context
119
120 Example:
121
122 >>> from docker.context import ContextAPI
123 >>> ctx = ContextAPI.get_context(name='test')
124 >>> print(ctx.Metadata)
125 {
126 "Name": "test",
127 "Metadata": {},
128 "Endpoints": {
129 "docker": {
130 "Host": "unix:///var/run/docker.sock",
131 "SkipTLSVerify": false
132 }
133 }
134 }
135 """
136 if not name:
137 name = get_current_context_name()
138 if name == "default":
139 return cls.get_default_context()
140 return Context.load_context(name)
141
142 @classmethod
143 def contexts(cls) -> list[Context]:
144 """Context list.
145 Returns:
146 (Context): List of context objects.
147 Raises:
148 :py:class:`docker.errors.APIError`
149 If something goes wrong.
150 """
151 names = []
152 for dirname, dummy, fnames in os.walk(get_meta_dir()):
153 for filename in fnames:
154 if filename == METAFILE:
155 filepath = os.path.join(dirname, filename)
156 try:
157 with open(filepath, "rt", encoding="utf-8") as f:
158 data = json.load(f)
159 name = data["Name"]
160 if name == "default":
161 raise ValueError('"default" is a reserved context name')
162 names.append(name)
163 except Exception as e:
164 raise errors.ContextException(
165 f"Failed to load metafile {filepath}: {e}"
166 ) from e
167
168 contexts = [cls.get_default_context()]
169 for name in names:
170 context = Context.load_context(name)
171 if not context:
172 raise errors.ContextException(f"Context {name} cannot be found")
173 contexts.append(context)
174 return contexts
175
176 @classmethod
177 def get_current_context(cls) -> Context | None:
178 """Get current context.
179 Returns:
180 (Context): current context object.
181 """
182 return cls.get_context()
183
184 @classmethod
185 def set_current_context(cls, name: str = "default") -> None:
186 ctx = cls.get_context(name)
187 if not ctx:
188 raise errors.ContextNotFound(name)
189
190 err = write_context_name_to_docker_config(name)
191 if err:
192 raise errors.ContextException(f"Failed to set current context: {err}")
193
194 @classmethod
195 def remove_context(cls, name: str) -> None:
196 """Remove a context. Similar to the ``docker context rm`` command.
197
198 Args:
199 name (str): The name of the context
200
201 Raises:
202 :py:class:`docker.errors.MissingContextParameter`
203 If a context name is not provided.
204 :py:class:`docker.errors.ContextNotFound`
205 If a context with the name does not exist.
206 :py:class:`docker.errors.ContextException`
207 If name is default.
208
209 Example:
210
211 >>> from docker.context import ContextAPI
212 >>> ContextAPI.remove_context(name='test')
213 >>>
214 """
215 if not name:
216 raise errors.MissingContextParameter("name")
217 if name == "default":
218 raise errors.ContextException('context "default" cannot be removed')
219 ctx = Context.load_context(name)
220 if not ctx:
221 raise errors.ContextNotFound(name)
222 if name == get_current_context_name():
223 write_context_name_to_docker_config(None)
224 ctx.remove()
225
226 @classmethod
227 def inspect_context(cls, name: str = "default") -> dict[str, t.Any]:
228 """Inspect a context. Similar to the ``docker context inspect`` command.
229
230 Args:
231 name (str): The name of the context
232
233 Raises:
234 :py:class:`docker.errors.MissingContextParameter`
235 If a context name is not provided.
236 :py:class:`docker.errors.ContextNotFound`
237 If a context with the name does not exist.
238
239 Example:
240
241 >>> from docker.context import ContextAPI
242 >>> ContextAPI.remove_context(name='test')
243 >>>
244 """
245 if not name:
246 raise errors.MissingContextParameter("name")
247 if name == "default":
248 return cls.get_default_context()()
249 ctx = Context.load_context(name)
250 if not ctx:
251 raise errors.ContextNotFound(name)
252
253 return ctx()