Debian Codegraph @

ansible_collections/community/docker/plugins/modules/docker_plugin.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2021 Red Hat | Ansible Sakar Mehra<@[email protected] | @sakar97>
4 # Copyright (c) 2019, Vladimir Porshkevich (@porshkevich) <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: docker_plugin
12 short_description: Manage Docker plugins
13 version_added: 1.3.0
14 description:
15 - This module allows to install, delete, enable and disable Docker plugins.
16 - Performs largely the same function as the C(docker plugin) CLI subcommand.
17 notes:
18 - The C(--grant-all-permissions) CLI flag is true by default in this module.
19 extends_documentation_fragment:
20 - community.docker._docker.api_documentation
21 - community.docker._attributes
22 - community.docker._attributes.actiongroup_docker
23
24 attributes:
25 check_mode:
26 support: full
27 diff_mode:
28 support: full
29 idempotent:
30 support: full
31
32 options:
33 plugin_name:
34 description:
35 - Name of the plugin to operate on.
36 required: true
37 type: str
38
39 state:
40 description:
41 - V(absent) remove the plugin.
42 - V(present) install the plugin, if it does not already exist.
43 - V(enable) enable the plugin.
44 - V(disable) disable the plugin.
45 default: present
46 choices:
47 - absent
48 - present
49 - enable
50 - disable
51 type: str
52
53 alias:
54 description:
55 - Local name for plugin.
56 type: str
57 version_added: 1.8.0
58
59 plugin_options:
60 description:
61 - Dictionary of plugin settings.
62 type: dict
63 default: {}
64
65 force_remove:
66 description:
67 - Remove even if the plugin is enabled.
68 default: false
69 type: bool
70
71 enable_timeout:
72 description:
73 - Timeout in seconds.
74 type: int
75 default: 0
76
77 author:
78 - Sakar Mehra (@sakar97)
79 - Vladimir Porshkevich (@porshkevich)
80
81 requirements:
82 - "Docker API >= 1.25"
83 """
84
85 EXAMPLES = r"""
86 ---
87 - name: Install a plugin
88 community.docker.docker_plugin:
89 plugin_name: plugin_one
90 state: present
91
92 - name: Remove a plugin
93 community.docker.docker_plugin:
94 plugin_name: plugin_one
95 state: absent
96
97 - name: Enable the plugin
98 community.docker.docker_plugin:
99 plugin_name: plugin_one
100 state: enable
101
102 - name: Disable the plugin
103 community.docker.docker_plugin:
104 plugin_name: plugin_one
105 state: disable
106
107 - name: Install a plugin with options
108 community.docker.docker_plugin:
109 plugin_name: weaveworks/net-plugin:latest_release
110 plugin_options:
111 IPALLOC_RANGE: "10.32.0.0/12"
112 WEAVE_PASSWORD: "PASSWORD"
113 """
114
115 RETURN = r"""
116 plugin:
117 description:
118 - Plugin inspection results for the affected plugin.
119 returned: success
120 type: dict
121 sample: {}
122 actions:
123 description:
124 - List of actions performed during task execution.
125 returned: when O(state) is not V(absent)
126 type: list
127 """
128
129 import traceback
130 import typing as t
131
132 from ansible.module_utils.common.text.converters import to_text
133
134 from ansible_collections.community.docker.plugins.module_utils._api import auth
135 from ansible_collections.community.docker.plugins.module_utils._api.errors import (
136 APIError,
137 DockerException,
138 NotFound,
139 )
140 from ansible_collections.community.docker.plugins.module_utils._common_api import (
141 AnsibleDockerClient,
142 RequestException,
143 )
144 from ansible_collections.community.docker.plugins.module_utils._util import (
145 DifferenceTracker,
146 DockerBaseClass,
147 )
148
149
150 class TaskParameters(DockerBaseClass):
151 plugin_name: str
152
153 def __init__(self, client: AnsibleDockerClient) -> None:
154 super().__init__()
155 self.client = client
156 self.alias: str | None = None
157 self.plugin_options: dict[str, t.Any] = {}
158 self.debug: bool = False
159 self.force_remove: bool = False
160 self.enable_timeout: int = 0
161 self.state: t.Literal["present", "absent", "enable", "disable"] = "present"
162
163 for key, value in client.module.params.items():
164 setattr(self, key, value)
165
166
167 def prepare_options(options: dict[str, t.Any] | None) -> list[str]:
168 return (
169 [f"{k}={v if v is not None else ''}" for k, v in options.items()]
170 if options
171 else []
172 )
173
174
175 def parse_options(options_list: list[str] | None) -> dict[str, str]:
176 return dict(x.split("=", 1) for x in options_list) if options_list else {}
177
178
179 class DockerPluginManager:
180 def __init__(self, client: AnsibleDockerClient) -> None:
181 self.client = client
182
183 self.parameters = TaskParameters(client)
184 self.preferred_name = self.parameters.alias or self.parameters.plugin_name
185 self.check_mode = self.client.check_mode
186 self.diff = self.client.module._diff
187 self.diff_tracker = DifferenceTracker()
188 self.diff_result: dict[str, t.Any] = {}
189
190 self.actions: list[str] = []
191 self.changed = False
192
193 self.existing_plugin = self.get_existing_plugin()
194
195 state = self.parameters.state
196 if state == "present":
197 self.present()
198 elif state == "absent":
199 self.absent()
200 elif state == "enable":
201 self.enable()
202 elif state == "disable":
203 self.disable()
204
205 if self.diff:
206 self.diff_result["before"], self.diff_result["after"] = (
207 self.diff_tracker.get_before_after()
208 )
209
210 def get_existing_plugin(self) -> dict[str, t.Any] | None:
211 try:
212 return self.client.get_json("/plugins/{0}/json", self.preferred_name)
213 except NotFound:
214 return None
215 except APIError as e:
216 self.client.fail(to_text(e))
217
218 def has_different_config(self) -> DifferenceTracker:
219 """
220 Return the list of differences between the current parameters and the existing plugin.
221
222 :return: list of options that differ
223 """
224 assert self.existing_plugin is not None
225 differences = DifferenceTracker()
226 if self.parameters.plugin_options:
227 settings = self.existing_plugin.get("Settings")
228 if not settings:
229 differences.add(
230 "plugin_options",
231 parameter=self.parameters.plugin_options,
232 active=settings,
233 )
234 else:
235 existing_options = parse_options(settings.get("Env"))
236
237 for key, value in self.parameters.plugin_options.items():
238 if (
239 (not existing_options.get(key) and value)
240 or not value
241 or value != existing_options[key]
242 ):
243 differences.add(
244 f"plugin_options.{key}",
245 parameter=value,
246 active=existing_options.get(key),
247 )
248
249 return differences
250
251 def install_plugin(self) -> None:
252 if not self.existing_plugin:
253 if not self.check_mode:
254 try:
255 # Get privileges
256 headers = {}
257 registry, dummy_repo_name = auth.resolve_repository_name(
258 self.parameters.plugin_name
259 )
260 header = auth.get_config_header(self.client, registry)
261 if header:
262 headers["X-Registry-Auth"] = header
263 privileges = self.client.get_json(
264 "/plugins/privileges",
265 params={"remote": self.parameters.plugin_name},
266 headers=headers,
267 )
268 # Pull plugin
269 params = {
270 "remote": self.parameters.plugin_name,
271 }
272 if self.parameters.alias:
273 params["name"] = self.parameters.alias
274 response = self.client._post_json(
275 self.client._url("/plugins/pull"),
276 params=params,
277 headers=headers,
278 data=privileges,
279 stream=True,
280 )
281 self.client._raise_for_status(response)
282 for dummy in self.client._stream_helper(response, decode=True):
283 pass
284 # Inspect and configure plugin
285 self.existing_plugin = self.client.get_json(
286 "/plugins/{0}/json", self.preferred_name
287 )
288 if self.parameters.plugin_options:
289 data = prepare_options(self.parameters.plugin_options)
290 self.client.post_json(
291 "/plugins/{0}/set", self.preferred_name, data=data
292 )
293 except APIError as e:
294 self.client.fail(to_text(e))
295
296 self.actions.append(f"Installed plugin {self.preferred_name}")
297 self.changed = True
298
299 def remove_plugin(self) -> None:
300 force = self.parameters.force_remove
301 if self.existing_plugin:
302 if not self.check_mode:
303 try:
304 self.client.delete_call(
305 "/plugins/{0}", self.preferred_name, params={"force": force}
306 )
307 except APIError as e:
308 self.client.fail(to_text(e))
309
310 self.actions.append(f"Removed plugin {self.preferred_name}")
311 self.changed = True
312
313 def update_plugin(self) -> None:
314 if self.existing_plugin:
315 differences = self.has_different_config()
316 if not differences.empty:
317 if not self.check_mode:
318 try:
319 data = prepare_options(self.parameters.plugin_options)
320 self.client.post_json(
321 "/plugins/{0}/set", self.preferred_name, data=data
322 )
323 except APIError as e:
324 self.client.fail(to_text(e))
325 self.actions.append(f"Updated plugin {self.preferred_name} settings")
326 self.changed = True
327 else:
328 self.client.fail("Cannot update the plugin: Plugin does not exist")
329
330 def present(self) -> None:
331 differences = DifferenceTracker()
332 if self.existing_plugin:
333 differences = self.has_different_config()
334
335 self.diff_tracker.add(
336 "exists", parameter=True, active=self.existing_plugin is not None
337 )
338
339 if self.existing_plugin:
340 self.update_plugin()
341 else:
342 self.install_plugin()
343
344 if self.diff or self.check_mode or self.parameters.debug:
345 self.diff_tracker.merge(differences)
346
347 def absent(self) -> None:
348 self.remove_plugin()
349
350 def enable(self) -> None:
351 timeout = self.parameters.enable_timeout
352 if self.existing_plugin:
353 if not self.existing_plugin.get("Enabled"):
354 if not self.check_mode:
355 try:
356 self.client.post_json(
357 "/plugins/{0}/enable",
358 self.preferred_name,
359 params={"timeout": timeout},
360 )
361 except APIError as e:
362 self.client.fail(to_text(e))
363 self.actions.append(f"Enabled plugin {self.preferred_name}")
364 self.changed = True
365 else:
366 self.install_plugin()
367 if not self.check_mode:
368 try:
369 self.client.post_json(
370 "/plugins/{0}/enable",
371 self.preferred_name,
372 params={"timeout": timeout},
373 )
374 except APIError as e:
375 self.client.fail(to_text(e))
376 self.actions.append(f"Enabled plugin {self.preferred_name}")
377 self.changed = True
378
379 def disable(self) -> None:
380 if self.existing_plugin:
381 if self.existing_plugin.get("Enabled"):
382 if not self.check_mode:
383 try:
384 self.client.post_json(
385 "/plugins/{0}/disable", self.preferred_name
386 )
387 except APIError as e:
388 self.client.fail(to_text(e))
389 self.actions.append(f"Disable plugin {self.preferred_name}")
390 self.changed = True
391 else:
392 self.client.fail("Plugin not found: Plugin does not exist.")
393
394 @property
395 def result(self) -> dict[str, t.Any]:
396 plugin_data = {}
397 if self.parameters.state != "absent":
398 try:
399 plugin_data = self.client.get_json(
400 "/plugins/{0}/json", self.preferred_name
401 )
402 except NotFound:
403 # This can happen in check mode
404 pass
405 result: dict[str, t.Any] = {
406 "actions": self.actions,
407 "changed": self.changed,
408 "diff": self.diff_result,
409 "plugin": plugin_data,
410 }
411 if (
412 self.parameters.state == "present"
413 and not self.check_mode
414 and not self.parameters.debug
415 ):
416 result["actions"] = None
417 return {k: v for k, v in result.items() if v is not None}
418
419
420 def main() -> None:
421 argument_spec = {
422 "alias": {"type": "str"},
423 "plugin_name": {"type": "str", "required": True},
424 "state": {
425 "type": "str",
426 "default": "present",
427 "choices": ["present", "absent", "enable", "disable"],
428 },
429 "plugin_options": {"type": "dict", "default": {}},
430 "debug": {"type": "bool", "default": False},
431 "force_remove": {"type": "bool", "default": False},
432 "enable_timeout": {"type": "int", "default": 0},
433 }
434 client = AnsibleDockerClient(
435 argument_spec=argument_spec,
436 supports_check_mode=True,
437 )
438
439 try:
440 cm = DockerPluginManager(client)
441 client.module.exit_json(**cm.result)
442 except DockerException as e:
443 client.fail(
444 f"An unexpected docker error occurred: {e}",
445 exception=traceback.format_exc(),
446 )
447 except RequestException as e:
448 client.fail(
449 f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
450 exception=traceback.format_exc(),
451 )
452
453
454 if __name__ == "__main__":
455 main()