Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright 2016 Dino Occhialini <[email protected]>
4 #
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: xbps
12 short_description: Manage packages with XBPS
13 description:
14 - Manage packages with the XBPS package manager.
15 author:
16 - "Dino Occhialini (@dinoocch)"
17 - "Michael Aldridge (@the-maldridge)"
18 extends_documentation_fragment:
19 - community.general._attributes
20 attributes:
21 check_mode:
22 support: full
23 diff_mode:
24 support: none
25 options:
26 name:
27 description:
28 - Name of the package to install, upgrade, or remove.
29 aliases: [pkg, package]
30 type: list
31 elements: str
32 state:
33 description:
34 - Desired state of the package.
35 default: "present"
36 choices: ["present", "absent", "latest", "installed", "removed"]
37 type: str
38 recurse:
39 description:
40 - When removing a package, also remove its dependencies, provided that they are not required by other packages and were
41 not explicitly installed by a user.
42 type: bool
43 default: false
44 update_cache:
45 description:
46 - Whether or not to refresh the master package lists. This can be run as part of a package installation or as a separate
47 step.
48 type: bool
49 default: true
50 upgrade:
51 description:
52 - Whether or not to upgrade whole system.
53 type: bool
54 default: false
55 upgrade_xbps:
56 description:
57 - Whether or not to upgrade the C(xbps) package when necessary. Before installing new packages, C(xbps) requires the
58 user to update itself. Thus when this option is set to V(false), upgrades and installations fail when C(xbps) is not
59 up to date.
60 type: bool
61 default: true
62 version_added: '0.2.0'
63 root:
64 description:
65 - The full path for the target root directory.
66 type: path
67 version_added: '10.2.0'
68 repositories:
69 description:
70 - Repository URL(s) to prepend to the repository list for the package installation. The URL can be remote repositories
71 or paths for local repositories.
72 type: list
73 elements: str
74 version_added: '10.2.0'
75 accept_pubkey:
76 description:
77 - Whether or not repository signing keys should be automatically accepted.
78 type: bool
79 default: false
80 version_added: '10.2.0'
81 """
82
83 EXAMPLES = r"""
84 - name: Install package foo (automatically updating the xbps package if needed)
85 community.general.xbps:
86 name: foo
87 state: present
88
89 - name: Upgrade package foo
90 community.general.xbps:
91 name: foo
92 state: latest
93 update_cache: true
94
95 - name: Remove packages foo and bar
96 community.general.xbps:
97 name:
98 - foo
99 - bar
100 state: absent
101
102 - name: Recursively remove package foo
103 community.general.xbps:
104 name: foo
105 state: absent
106 recurse: true
107
108 - name: Update package cache
109 community.general.xbps:
110 update_cache: true
111
112 - name: Upgrade packages
113 community.general.xbps:
114 upgrade: true
115
116 - name: Install a package, failing if the xbps package is out of date
117 community.general.xbps:
118 name: foo
119 state: present
120 upgrade_xbps: false
121
122 - name: Find repository keys to install into a new void system on a mounted partition
123 ansible.builtin.find:
124 path: /var/db/xbps/keys
125 pattern: "*.plist"
126 register: xbps_keys
127
128 - name: Copy repository keys to into a new void system on a mounted partition
129 ansible.builtin.copy:
130 remote_src: true
131 src: "{{ item }}"
132 dest: "/mnt/{{ item }}"
133 owner: root
134 group: root
135 mode: "0644"
136 when: xbps_keys.matched > 0
137 loop: "{{ xbps_keys.files | map(attribute='path') }}"
138
139 - name: Install a new void system on a mounted partition
140 community.general.xbps:
141 name: base-system
142 state: present
143 repositories: https://repo-default.voidlinux.org/current
144 root: /mnt
145 """
146
147 RETURN = r"""
148 msg:
149 description: Message about results.
150 returned: success
151 type: str
152 sample: "System Upgraded"
153 packages:
154 description: Packages that are affected/would be affected.
155 type: list
156 sample: ["ansible"]
157 returned: success
158 """
159
160
161 import os
162
163 from ansible.module_utils.basic import AnsibleModule
164
165
166 def is_installed(xbps_output):
167 """Returns package install state"""
168 return bool(len(xbps_output))
169
170
171 def append_flags(module, xbps_path, cmd, skip_repo=False):
172 """Appends the repository/root flags when needed"""
173 if module.params["root"]:
174 cmd = cmd + ["-r", module.params["root"]]
175 if module.params["repositories"] and cmd[0] != xbps_path["remove"] and not skip_repo:
176 for repo in module.params["repositories"]:
177 cmd = cmd + [f"--repository={repo}"]
178
179 return cmd
180
181
182 def query_package(module, xbps_path, name, state="present"):
183 """Returns Package info"""
184 if state == "present":
185 lcmd = [xbps_path["query"], name]
186 lcmd = append_flags(module, xbps_path, lcmd, skip_repo=True)
187 lrc, lstdout, lstderr = module.run_command(lcmd, check_rc=False)
188 if not is_installed(lstdout):
189 # package is not installed locally
190 return False, False
191
192 rcmd = [xbps_path["install"], "-Sun"]
193 rcmd = append_flags(module, xbps_path, rcmd)
194 rrc, rstdout, rstderr = module.run_command(rcmd, check_rc=False)
195 if rrc == 0 or rrc == 17:
196 """Return True to indicate that the package is installed locally,
197 and the result of the version number comparison to determine if the
198 package is up-to-date"""
199 return True, name not in rstdout
200
201 return False, False
202
203
204 def update_package_db(module, xbps_path):
205 """Returns True if update_package_db changed"""
206 cmd = [xbps_path["install"], "-S"]
207 cmd = append_flags(module, xbps_path, cmd)
208 if module.params["accept_pubkey"]:
209 stdin = "y\n"
210 else:
211 stdin = "n\n"
212 rc, stdout, stderr = module.run_command(cmd, check_rc=False, data=stdin)
213
214 if "Failed to import pubkey" in stderr:
215 module.fail_json(msg="Failed to import pubkey for repository")
216 if rc != 0:
217 module.fail_json(msg="Could not update package db")
218 return "avg rate" in stdout
219
220
221 def upgrade_xbps(module, xbps_path, exit_on_success=False):
222 cmdupgradexbps = [xbps_path["install"], "-uy", "xbps"]
223 cmdupgradexbps = append_flags(module, xbps_path, cmdupgradexbps)
224 rc, stdout, stderr = module.run_command(cmdupgradexbps, check_rc=False)
225 if rc != 0:
226 module.fail_json(msg="Could not upgrade xbps itself")
227
228
229 def upgrade(module, xbps_path):
230 """Returns true is full upgrade succeeds"""
231 cmdupgrade = [xbps_path["install"], "-uy"]
232 cmdneedupgrade = [xbps_path["install"], "-un"]
233 cmdupgrade = append_flags(module, xbps_path, cmdupgrade)
234 cmdneedupgrade = append_flags(module, xbps_path, cmdneedupgrade)
235
236 rc, stdout, stderr = module.run_command(cmdneedupgrade, check_rc=False)
237 if rc == 0:
238 if len(stdout.splitlines()) == 0:
239 module.exit_json(changed=False, msg="Nothing to upgrade")
240 elif module.check_mode:
241 module.exit_json(changed=True, msg="Would have performed upgrade")
242 else:
243 rc, stdout, stderr = module.run_command(cmdupgrade, check_rc=False)
244 if rc == 0:
245 module.exit_json(changed=True, msg="System upgraded")
246 elif rc == 16 and module.params["upgrade_xbps"]:
247 upgrade_xbps(module, xbps_path)
248 # avoid loops by not trying self-upgrade again
249 module.params["upgrade_xbps"] = False
250 upgrade(module, xbps_path)
251 else:
252 module.fail_json(msg="Could not upgrade")
253 else:
254 module.fail_json(msg="Could not upgrade")
255
256
257 def remove_packages(module, xbps_path, packages):
258 """Returns true if package removal succeeds"""
259 changed_packages = []
260 # Using a for loop in case of error, we can report the package that failed
261 for package in packages:
262 # Query the package first, to see if we even need to remove
263 installed, updated = query_package(module, xbps_path, package)
264 if not installed:
265 continue
266
267 cmd = [xbps_path["remove"], "-y", package]
268 cmd = append_flags(module, xbps_path, cmd, skip_repo=True)
269 rc, stdout, stderr = module.run_command(cmd, check_rc=False)
270
271 if rc != 0:
272 module.fail_json(msg=f"failed to remove {package}")
273
274 changed_packages.append(package)
275
276 if len(changed_packages) > 0:
277 module.exit_json(changed=True, msg=f"removed {len(changed_packages)} package(s)", packages=changed_packages)
278
279 module.exit_json(changed=False, msg="package(s) already absent")
280
281
282 def install_packages(module, xbps_path, state, packages):
283 """Returns true if package install succeeds."""
284 toInstall = []
285 for package in packages:
286 """If the package is installed and state == present or state == latest
287 and is up-to-date then skip"""
288 installed, updated = query_package(module, xbps_path, package)
289 if installed and (state == "present" or (state == "latest" and updated)):
290 continue
291
292 toInstall.append(package)
293
294 if len(toInstall) == 0:
295 module.exit_json(changed=False, msg="Nothing to Install")
296
297 cmd = [xbps_path["install"], "-y"] + toInstall
298 cmd = append_flags(module, xbps_path, cmd)
299 rc, stdout, stderr = module.run_command(cmd, check_rc=False)
300
301 if rc == 16 and module.params["upgrade_xbps"]:
302 upgrade_xbps(module, xbps_path)
303 # avoid loops by not trying self-update again
304 module.params["upgrade_xbps"] = False
305 install_packages(module, xbps_path, state, packages)
306 elif rc != 0 and not (state == "latest" and rc == 17):
307 module.fail_json(msg=f"failed to install {len(toInstall)} packages(s)", packages=toInstall)
308
309 module.exit_json(changed=True, msg=f"installed {len(toInstall)} package(s)", packages=toInstall)
310
311
312 def check_packages(module, xbps_path, packages, state):
313 """Returns change status of command"""
314 would_be_changed = []
315 for package in packages:
316 installed, updated = query_package(module, xbps_path, package)
317 if (
318 (state in ["present", "latest"] and not installed)
319 or (state == "absent" and installed)
320 or (state == "latest" and not updated)
321 ):
322 would_be_changed.append(package)
323 if would_be_changed:
324 if state == "absent":
325 state = "removed"
326 module.exit_json(
327 changed=True, msg=f"{len(would_be_changed)} package(s) would be {state}", packages=would_be_changed
328 )
329 else:
330 module.exit_json(changed=False, msg=f"package(s) already {state}", packages=[])
331
332
333 def update_cache(module, xbps_path, upgrade_planned):
334 """Update package cache"""
335 if module.check_mode:
336 if upgrade_planned:
337 return
338 module.exit_json(changed=True, msg="Would have updated the package cache")
339 changed = update_package_db(module, xbps_path)
340 if not upgrade_planned:
341 module.exit_json(
342 changed=changed, msg=("Updated the package master lists" if changed else "Package list already up to date")
343 )
344
345
346 def main():
347 """Returns, calling appropriate command"""
348
349 module = AnsibleModule(
350 argument_spec=dict(
351 name=dict(aliases=["pkg", "package"], type="list", elements="str"),
352 state=dict(default="present", choices=["present", "installed", "latest", "absent", "removed"]),
353 recurse=dict(default=False, type="bool"),
354 upgrade=dict(default=False, type="bool"),
355 update_cache=dict(default=True, type="bool"),
356 upgrade_xbps=dict(default=True, type="bool"),
357 root=dict(type="path"),
358 repositories=dict(type="list", elements="str"),
359 accept_pubkey=dict(default=False, type="bool"),
360 ),
361 required_one_of=[["name", "update_cache", "upgrade"]],
362 supports_check_mode=True,
363 )
364 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
365
366 xbps_path = dict()
367 xbps_path["install"] = module.get_bin_path("xbps-install", True)
368 xbps_path["query"] = module.get_bin_path("xbps-query", True)
369 xbps_path["remove"] = module.get_bin_path("xbps-remove", True)
370
371 if not os.path.exists(xbps_path["install"]):
372 module.fail_json(msg=f"cannot find xbps, in path {xbps_path['install']}")
373
374 p = module.params
375
376 # normalize the state parameter
377 if p["state"] in ["present", "installed"]:
378 p["state"] = "present"
379 elif p["state"] in ["absent", "removed"]:
380 p["state"] = "absent"
381
382 if p["update_cache"]:
383 update_cache(module, xbps_path, (p["name"] or p["upgrade"]))
384
385 if p["upgrade"]:
386 upgrade(module, xbps_path)
387
388 if p["name"]:
389 pkgs = p["name"]
390
391 if module.check_mode:
392 check_packages(module, xbps_path, pkgs, p["state"])
393
394 if p["state"] in ["present", "latest"]:
395 install_packages(module, xbps_path, p["state"], pkgs)
396 elif p["state"] == "absent":
397 remove_packages(module, xbps_path, pkgs)
398
399
400 if __name__ == "__main__":
401 main()