Debian Codegraph @

ansible_collections/community/general/plugins/modules/snap.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2024, Lincoln Wallace (locnnil) <[email protected]>
4 # Copyright (c) 2021, Alexei Znamensky (russoz) <[email protected]>
5 # Copyright (c) 2021, Marcus Rickert <[email protected]>
6 # Copyright (c) 2018, Stanislas Lange (angristan) <[email protected]>
7 # Copyright (c) 2018, Victor Carceler <[email protected]>
8
9 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
10 # SPDX-License-Identifier: GPL-3.0-or-later
11
12 from __future__ import annotations
13
14 DOCUMENTATION = r"""
15 module: snap
16 short_description: Manages snaps
17 description:
18 - Manages snaps packages.
19 extends_documentation_fragment:
20 - community.general._attributes
21 attributes:
22 check_mode:
23 support: full
24 diff_mode:
25 support: none
26 options:
27 name:
28 description:
29 - Name of the snaps to be installed.
30 - Any named snap accepted by the C(snap) command is valid.
31 - O(dangerous=true) may be necessary when installing C(.snap) files. See O(dangerous) for more details.
32 - The special name V(system) refers to the snapd system-wide configuration namespace.
33 When used with O(options), it runs C(snap set system <key=value>).
34 It is always considered present and only V(state=present) and O(options) are meaningful for it.
35 Support for V(system) was added in community.general 13.0.0.
36 required: true
37 type: list
38 elements: str
39 state:
40 description:
41 - Desired state of the package.
42 - When O(state=present) the module uses C(snap install) if the snap is not installed, and C(snap refresh) if it is installed
43 but from a different channel.
44 default: present
45 choices: [absent, present, enabled, disabled]
46 type: str
47 classic:
48 description:
49 - Install a snap that has classic confinement.
50 - This option corresponds to the C(--classic) argument of the C(snap install) command.
51 - This level of confinement is permissive, granting full system access, similar to that of traditionally packaged applications
52 that do not use sandboxing mechanisms. This option can only be specified when the task involves a single snap.
53 - See U(https://snapcraft.io/docs/snap-confinement) for more details about classic confinement and confinement levels.
54 type: bool
55 default: false
56 channel:
57 description:
58 - Define which release of a snap is installed and tracked for updates. This option can only be specified if there is
59 a single snap in the task.
60 - If not passed, the C(snap) command defaults to V(stable).
61 - If the value passed does not contain the C(track), it defaults to C(latest). For example, if V(edge) is passed, the
62 module assumes the channel to be V(latest/edge).
63 - See U(https://snapcraft.io/docs/channels) for more details about snap channels.
64 type: str
65 options:
66 description:
67 - Set options with pattern C(key=value) or C(snap:key=value). If a snap name is given, the option is applied to that
68 snap only. If the snap name is omitted, the options are applied to all snaps listed in O(name). Options are only applied
69 to active snaps.
70 - Options are only applied when C(state) is set to V(present). This is done after the necessary installation or refresh
71 (upgrade/downgrade) of all the snaps listed in O(name).
72 - See U(https://snapcraft.io/docs/configuration-in-snaps) for more details about snap configuration options.
73 type: list
74 elements: str
75 version_added: 4.4.0
76 dangerous:
77 description:
78 - Install the snap in dangerous mode, without validating its assertions and signatures.
79 - This is useful when installing local snaps that are either unsigned or have signatures that have not been acknowledged.
80 - See U(https://snapcraft.io/docs/install-modes) for more details about installation modes.
81 type: bool
82 default: false
83 version_added: 7.2.0
84 devmode:
85 description:
86 - Install the snap in developer mode, granting the snap full system access and disabling security confinement.
87 - See U(https://snapcraft.io/docs/install-modes) for more details about installation modes.
88 type: bool
89 default: false
90 version_added: 13.0.0
91 revision:
92 description:
93 - Install a specific revision of the snap.
94 - This option can only be specified if there is a single snap in the task.
95 - Mutually exclusive with O(channel).
96 - When a specific revision is set, the snap is held (C(snap refresh --hold)) to prevent automatic updates from
97 overriding the pinned revision.
98 - "B(Note:) running C(snap refresh <name>) manually bypasses the hold and will update the snap regardless.
99 The hold only prevents snapd's automatic background refreshes.
100 See U(https://snapcraft.io/docs/how-to-guides/manage-snaps/manage-updates/) for details."
101 - See U(https://snapcraft.io/docs/revisions) for more details about snap revisions.
102 type: int
103 version_added: 13.0.0
104 notes:
105 - Privileged operations, such as installing and configuring snaps, require root priviledges. This is only the case if the
106 user has not logged in to the Snap Store.
107 author:
108 - Victor Carceler (@vcarceler) <[email protected]>
109 - Stanislas Lange (@angristan) <[email protected]>
110
111 seealso:
112 - module: community.general.snap_alias
113 """
114
115 EXAMPLES = r"""
116 # Install "foo" and "bar" snap
117 - name: Install foo
118 community.general.snap:
119 name:
120 - foo
121 - bar
122
123 # Install "foo" snap with options par1=A and par2=B
124 - name: Install "foo" with options
125 community.general.snap:
126 name:
127 - foo
128 options:
129 - par1=A
130 - par2=B
131
132 # Install "foo" and "bar" snaps with common option com=A and specific options fooPar=X and barPar=Y
133 - name: Install "foo" and "bar" with options
134 community.general.snap:
135 name:
136 - foo
137 - bar
138 options:
139 - com=A
140 - foo:fooPar=X
141 - bar:barPar=Y
142
143 # Remove "foo" snap
144 - name: Remove foo
145 community.general.snap:
146 name: foo
147 state: absent
148
149 # Install a snap with classic confinement
150 - name: Install "foo" with option --classic
151 community.general.snap:
152 name: foo
153 classic: true
154
155 # Install a snap with from a specific channel
156 - name: Install "foo" with option --channel=latest/edge
157 community.general.snap:
158 name: foo
159 channel: latest/edge
160
161 # Install a specific revision of a snap (automatically held to prevent auto-updates)
162 - name: Install revision 481 of "helm"
163 community.general.snap:
164 name: helm
165 classic: true
166 revision: 481
167
168 # Set snap system-wide configuration
169 - name: Configure snapd proxy
170 community.general.snap:
171 name: system
172 options:
173 - proxy.http=http://proxy.example.com:3128/
174 - proxy.https=http://proxy.example.com:3128/
175 """
176
177 RETURN = r"""
178 classic:
179 description: Whether or not the snaps were installed with the classic confinement.
180 type: bool
181 returned: When snaps are installed
182 channel:
183 description: The channel the snaps were installed from.
184 type: str
185 returned: When snaps are installed
186 cmd:
187 description: The command that was executed on the host.
188 type: str
189 returned: When changed is true
190 snaps_installed:
191 description: The list of actually installed snaps.
192 type: list
193 returned: When any snaps have been installed
194 snaps_removed:
195 description: The list of actually removed snaps.
196 type: list
197 returned: When any snaps have been removed
198 options_changed:
199 description: The list of options set/changed in format C(snap:key=value).
200 type: list
201 returned: When any options have been changed/set
202 version_added: 4.4.0
203 revision:
204 description: The revision of the snap that was installed.
205 type: int
206 returned: When snaps are installed with a specific revision
207 version_added: 13.0.0
208 version:
209 description: Versions of snap components as reported by C(snap version).
210 type: dict
211 returned: always
212 version_added: 10.3.0
213 """
214
215 import json
216 import numbers
217 import re
218
219 from ansible.module_utils.common.text.converters import to_native
220
221 _VIRTUAL_SNAPS = frozenset({"system"})
222
223 from ansible_collections.community.general.plugins.module_utils._module_helper import StateModuleHelper
224 from ansible_collections.community.general.plugins.module_utils._snap import get_version, snap_runner
225
226
227 class Snap(StateModuleHelper):
228 NOT_INSTALLED = 0
229 CHANNEL_MISMATCH = 1
230 INSTALLED = 2
231 REVISION_MISMATCH = 3
232 HOLD_MISMATCH = 4
233
234 __disable_re = re.compile(r"(?:\S+\s+){5}(?P<notes>\S+)")
235 __set_param_re = re.compile(r"(?P<snap_prefix>\S+:)?(?P<key>\S+)\s*=\s*(?P<value>.+)")
236 __list_re = re.compile(r"^(?P<name>\S+)\s+\S+\s+(?P<rev>\S+)\s+(?P<channel>\S+)\s+\S+\s+(?P<notes>\S+)")
237 module = dict(
238 argument_spec={
239 "name": dict(type="list", elements="str", required=True),
240 "state": dict(type="str", default="present", choices=["absent", "present", "enabled", "disabled"]),
241 "classic": dict(type="bool", default=False),
242 "channel": dict(type="str"),
243 "options": dict(type="list", elements="str"),
244 "dangerous": dict(type="bool", default=False),
245 "devmode": dict(type="bool", default=False),
246 "revision": dict(type="int"),
247 },
248 mutually_exclusive=[["channel", "revision"]],
249 supports_check_mode=True,
250 )
251
252 @staticmethod
253 def _first_non_zero(a):
254 for elem in a:
255 if elem != 0:
256 return elem
257
258 return 0
259
260 def __init_module__(self):
261 self.runner = snap_runner(self.module)
262 self.vars.version = get_version(self.runner)
263 # if state=present there might be file names passed in 'name', in
264 # which case they must be converted to their actual snap names, which
265 # is done using the names_from_snaps() method calling 'snap info'.
266 self.vars.set("snapinfo_run_info", [], output=(self.verbosity >= 4))
267 self.vars.set("status_run_info", [], output=(self.verbosity >= 4))
268 self.vars.set("status_out", None, output=(self.verbosity >= 4))
269 self.vars.set("run_info", [], output=(self.verbosity >= 4))
270
271 if self.vars.state == "present":
272 self.vars.set("snap_names", self.names_from_snaps(self.vars.name))
273 status_var = "snap_names"
274 else:
275 status_var = "name"
276 self.vars.set("status_var", status_var, output=False)
277 self.vars.set(
278 "snap_status",
279 self.snap_status(self.vars[self.vars.status_var], self.vars.channel, self.vars.revision),
280 output=False,
281 change=True,
282 )
283 self.vars.set("snap_status_map", dict(zip(self.vars.name, self.vars.snap_status)), output=False, change=True)
284
285 def __quit_module__(self):
286 self.vars.snap_status = self.snap_status(self.vars[self.vars.status_var], self.vars.channel, self.vars.revision)
287 if self.vars.channel is None:
288 self.vars.channel = "stable"
289
290 def _run_multiple_commands(self, commands, actionable_names, bundle=True, refresh=False):
291 results_cmd = []
292 results_rc = []
293 results_out = []
294 results_err = []
295 results_run_info = []
296
297 state = "refresh" if refresh else self.vars.state
298
299 with self.runner(commands + ["name"]) as ctx:
300 if bundle:
301 rc, out, err = ctx.run(state=state, name=actionable_names)
302 results_cmd.append(commands + actionable_names)
303 results_rc.append(rc)
304 results_out.append(out.strip())
305 results_err.append(err.strip())
306 results_run_info.append(ctx.run_info)
307 else:
308 for name in actionable_names:
309 rc, out, err = ctx.run(state=state, name=name)
310 results_cmd.append(commands + [name])
311 results_rc.append(rc)
312 results_out.append(out.strip())
313 results_err.append(err.strip())
314 results_run_info.append(ctx.run_info)
315
316 return (
317 "; ".join([to_native(x) for x in results_cmd]),
318 self._first_non_zero(results_rc),
319 "\n".join(results_out),
320 "\n".join(results_err),
321 results_run_info,
322 )
323
324 def convert_json_subtree_to_map(self, json_subtree, prefix=None):
325 option_map = {}
326
327 if not isinstance(json_subtree, dict):
328 self.do_raise(
329 "Non-dict non-leaf element encountered while parsing option map. "
330 "The output format of 'snap set' may have changed. Aborting!"
331 )
332
333 for key, value in json_subtree.items():
334 full_key = key if prefix is None else f"{prefix}.{key}"
335
336 if isinstance(value, (str, float, bool, numbers.Integral)):
337 option_map[full_key] = str(value)
338 else:
339 option_map.update(self.convert_json_subtree_to_map(json_subtree=value, prefix=full_key))
340
341 return option_map
342
343 def convert_json_to_map(self, json_string):
344 json_object = json.loads(json_string)
345 return self.convert_json_subtree_to_map(json_object)
346
347 def retrieve_option_map(self, snap_name):
348 with self.runner("get name") as ctx:
349 rc, out, err = ctx.run(name=snap_name)
350
351 if rc != 0:
352 return {}
353
354 result = out.splitlines()
355
356 if "has no configuration" in result[0]:
357 return {}
358
359 try:
360 option_map = self.convert_json_to_map(out)
361 return option_map
362 except Exception as e:
363 self.do_raise(
364 msg=f"Parsing option map returned by 'snap get {snap_name}' triggers exception '{e}', output:\n'{out}'"
365 )
366
367 def names_from_snaps(self, snaps):
368 real_snaps = [s for s in snaps if s not in _VIRTUAL_SNAPS]
369
370 if not real_snaps:
371 return list(snaps)
372
373 def process_one(rc, out, err):
374 res = [line for line in out.split("\n") if line.startswith("name:")]
375 name = res[0].split()[1]
376 return [name]
377
378 def process_many(rc, out, err):
379 # This needs to be "\n---" instead of just "---" because otherwise
380 # if a snap uses "---" in its description then that will incorrectly
381 # be interpreted as a separator between snaps in the output.
382 outputs = out.split("\n---")
383 res = []
384 for sout in outputs:
385 res.extend(process_one(rc, sout, ""))
386 return res
387
388 def process(rc, out, err):
389 if len(real_snaps) == 1:
390 check_error = err
391 process_ = process_one
392 else:
393 check_error = out
394 process_ = process_many
395
396 if "warning: no snap found" in check_error:
397 snaps_not_found = [x.split()[-1] for x in out.split("\n") if x.startswith("warning: no snap found")]
398 self.do_raise(f"Snaps not found: {snaps_not_found}.")
399 return process_(rc, out, err)
400
401 real_names = []
402 with self.runner("info name", output_process=process) as ctx:
403 try:
404 real_names = ctx.run(name=real_snaps)
405 finally:
406 self.vars.snapinfo_run_info.append(ctx.run_info)
407
408 real_name_iter = iter(real_names)
409 return [s if s in _VIRTUAL_SNAPS else next(real_name_iter) for s in snaps]
410
411 def snap_status(self, snap_name, channel, revision=None):
412 should_be_held = revision is not None
413
414 def _status_check(name, channel, revision, installed):
415 if name in _VIRTUAL_SNAPS:
416 return Snap.INSTALLED
417 match = [(r, c, notes) for n, r, c, notes in installed if n == name]
418 if not match:
419 return Snap.NOT_INSTALLED
420 installed_rev, installed_channel, installed_notes = match[0]
421 if revision is not None and str(revision) != installed_rev:
422 return Snap.REVISION_MISMATCH
423 if channel and installed_channel not in (channel, f"latest/{channel}"):
424 return Snap.CHANNEL_MISMATCH
425 if should_be_held:
426 is_held = "held" in installed_notes.split(",")
427 if not is_held:
428 return Snap.HOLD_MISMATCH
429 return Snap.INSTALLED
430
431 with self.runner("_list") as ctx:
432 rc, out, err = ctx.run(check_rc=True)
433 list_out = out.split("\n")[1:]
434 list_out = [self.__list_re.match(x) for x in list_out]
435 list_out = [(m.group("name"), m.group("rev"), m.group("channel"), m.group("notes")) for m in list_out if m]
436 self.vars.status_out = list_out
437 self.vars.status_run_info = ctx.run_info
438
439 return [_status_check(n, channel, revision, list_out) for n in snap_name]
440
441 def is_snap_enabled(self, snap_name):
442 with self.runner("_list name") as ctx:
443 rc, out, err = ctx.run(name=snap_name)
444 if rc != 0:
445 return None
446 result = out.splitlines()[1]
447 match = self.__disable_re.match(result)
448 if not match:
449 self.do_raise(msg=f"Unable to parse 'snap list {snap_name}' output:\n{out}")
450 notes = match.group("notes")
451 return "disabled" not in notes.split(",")
452
453 def _present(self, actionable_snaps, refresh=False):
454 self.changed = True
455 self.vars.snaps_installed = actionable_snaps
456
457 if self.check_mode:
458 return
459
460 params = ["state", "classic", "channel", "revision", "dangerous", "devmode"] # get base cmd parts
461 has_one_pkg_params = bool(self.vars.classic) or self.vars.channel != "stable" or self.vars.revision is not None
462 has_multiple_snaps = len(actionable_snaps) > 1
463
464 if has_one_pkg_params and has_multiple_snaps:
465 self.vars.cmd, rc, out, err, run_info = self._run_multiple_commands(
466 params, actionable_snaps, bundle=False, refresh=refresh
467 )
468 else:
469 self.vars.cmd, rc, out, err, run_info = self._run_multiple_commands(
470 params, actionable_snaps, refresh=refresh
471 )
472 self.vars.run_info = run_info
473
474 if rc == 0:
475 return
476
477 classic_snap_pattern = re.compile(
478 r'^error: This revision of snap "(?P<package_name>\w+)"'
479 r" was published using classic confinement"
480 )
481 match = classic_snap_pattern.match(err)
482 if match:
483 err_pkg = match.group("package_name")
484 msg = f"Couldn't install {err_pkg} because it requires classic confinement"
485 else:
486 msg = f"Ooops! Snap installation failed while executing '{self.vars.cmd}', please examine logs and error output for more details."
487 self.do_raise(msg=msg)
488
489 def _apply_hold(self, snaps):
490 if not snaps:
491 return
492 self.changed = True
493 if self.check_mode:
494 return
495 for snap_name in snaps:
496 with self.runner("state hold name") as ctx:
497 rc, out, err = ctx.run(state="refresh", hold=True, name=snap_name)
498 if rc != 0:
499 self.do_raise(msg=f"Snap hold failed for '{snap_name}': {err}")
500
501 def state_present(self):
502 self.vars.set_meta("classic", output=True)
503 self.vars.set_meta("channel", output=True)
504 self.vars.set_meta("revision", output=True)
505
506 actionable_refresh = [
507 snap
508 for snap in self.vars.name
509 if self.vars.snap_status_map[snap] in (Snap.CHANNEL_MISMATCH, Snap.REVISION_MISMATCH)
510 ]
511 if actionable_refresh:
512 self._present(actionable_refresh, refresh=True)
513 actionable_install = [snap for snap in self.vars.name if self.vars.snap_status_map[snap] == Snap.NOT_INSTALLED]
514 if actionable_install:
515 self._present(actionable_install)
516
517 if self.vars.revision is not None:
518 hold_mismatch = [snap for snap in self.vars.name if self.vars.snap_status_map[snap] == Snap.HOLD_MISMATCH]
519 self._apply_hold(actionable_install + actionable_refresh + hold_mismatch)
520
521 self.set_options()
522
523 def set_options(self):
524 if self.vars.options is None:
525 return
526
527 actionable_snaps = [s for s in self.vars.name if self.vars.snap_status_map[s] != Snap.NOT_INSTALLED]
528 overall_options_changed = []
529
530 for snap_name in actionable_snaps:
531 option_map = self.retrieve_option_map(snap_name=snap_name)
532
533 options_changed = []
534
535 for option_string in self.vars.options:
536 match = self.__set_param_re.match(option_string)
537
538 if not match:
539 msg = f"Cannot parse set option '{option_string}'"
540 self.do_raise(msg)
541
542 snap_prefix = match.group("snap_prefix")
543 selected_snap_name = snap_prefix[:-1] if snap_prefix else None
544
545 if selected_snap_name is not None and selected_snap_name not in self.vars.name:
546 msg = f"Snap option '{option_string}' refers to snap which is not in the list of snap names"
547 self.do_raise(msg)
548
549 if selected_snap_name is None or (snap_name is not None and snap_name == selected_snap_name):
550 key = match.group("key")
551 value = match.group("value").strip()
552
553 if key not in option_map or key in option_map and option_map[key] != value:
554 option_without_prefix = f"{key}={value}"
555 option_with_prefix = (
556 option_string if selected_snap_name is not None else f"{snap_name}:{option_string}"
557 )
558 options_changed.append(option_without_prefix)
559 overall_options_changed.append(option_with_prefix)
560
561 if options_changed:
562 self.changed = True
563
564 if not self.check_mode:
565 with self.runner("_set name options") as ctx:
566 rc, out, err = ctx.run(name=snap_name, options=options_changed)
567 if rc != 0:
568 if 'has no "configure" hook' in err:
569 msg = f"Snap '{snap_name}' does not have any configurable options"
570 self.do_raise(msg)
571
572 msg = f"Cannot set options '{' '.join(options_changed)}' for snap '{snap_name}': error={err}"
573 self.do_raise(msg)
574
575 if overall_options_changed:
576 self.vars.options_changed = overall_options_changed
577
578 def _generic_state_action(self, actionable_func, actionable_var, params):
579 actionable_snaps = [s for s in self.vars.name if actionable_func(s)]
580 if not actionable_snaps:
581 return
582 self.changed = True
583 self.vars[actionable_var] = actionable_snaps
584 if self.check_mode:
585 return
586 self.vars.cmd, rc, out, err, run_info = self._run_multiple_commands(params, actionable_snaps)
587 self.vars.run_info = run_info
588 if rc == 0:
589 return
590 msg = f"Ooops! Snap operation failed while executing '{self.vars.cmd}', please examine logs and error output for more details."
591 self.do_raise(msg=msg)
592
593 def state_absent(self):
594 self._generic_state_action(
595 lambda s: self.vars.snap_status_map[s] != Snap.NOT_INSTALLED,
596 "snaps_removed",
597 ["classic", "channel", "state"],
598 )
599
600 def state_enabled(self):
601 self._generic_state_action(
602 lambda s: not self.is_snap_enabled(s), "snaps_enabled", ["classic", "channel", "state"]
603 )
604
605 def state_disabled(self):
606 self._generic_state_action(self.is_snap_enabled, "snaps_disabled", ["classic", "channel", "state"])
607
608
609 def main():
610 Snap.execute()
611
612
613 if __name__ == "__main__":
614 main()