Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2017-2020, Yann Amar <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: dpkg_divert
11 short_description: Override a debian package's version of a file
12 version_added: '0.2.0'
13 author:
14 - quidame (@quidame)
15 description:
16 - A diversion is for C(dpkg) the knowledge that only a given package (or the local administrator) is allowed to install
17 a file at a given location. Other packages shipping their own version of this file are forced to O(divert) it, that is
18 to install it at another location. It allows one to keep changes in a file provided by a debian package by preventing
19 it being overwritten on package upgrade.
20 - This module manages diversions of debian packages files using the C(dpkg-divert) commandline tool. It can either create
21 or remove a diversion for a given file, but also update an existing diversion to modify its O(holder) and/or its O(divert)
22 location.
23 extends_documentation_fragment:
24 - community.general._attributes
25 attributes:
26 check_mode:
27 support: full
28 diff_mode:
29 support: full
30 options:
31 path:
32 description:
33 - The original and absolute path of the file to be diverted or undiverted. This path is unique, in other words it is
34 not possible to get two diversions for the same O(path).
35 required: true
36 type: path
37 state:
38 description:
39 - When O(state=absent), remove the diversion of the specified O(path); when O(state=present), create the diversion if
40 it does not exist, or update its package O(holder) or O(divert) location, if it already exists.
41 type: str
42 default: present
43 choices: [absent, present]
44 holder:
45 description:
46 - The name of the package whose copy of file is not diverted, also known as the diversion holder or the package the
47 diversion belongs to.
48 - The actual package does not have to be installed or even to exist for its name to be valid. If not specified, the
49 diversion is hold by 'LOCAL', that is reserved by/for dpkg for local diversions.
50 - This parameter is ignored when O(state=absent).
51 type: str
52 divert:
53 description:
54 - The location where the versions of file are diverted.
55 - Default is to add suffix C(.distrib) to the file path.
56 - This parameter is ignored when O(state=absent).
57 type: path
58 rename:
59 description:
60 - Actually move the file aside (when O(state=present)) or back (when O(state=absent)), but only when changing the state
61 of the diversion. This parameter has no effect when attempting to add a diversion that already exists or when removing
62 an unexisting one.
63 - Unless O(force=true), renaming fails if the destination file already exists (this lock being a dpkg-divert feature,
64 and bypassing it being a module feature).
65 type: bool
66 default: false
67 force:
68 description:
69 - When O(rename=true) and O(force=true), renaming is performed even if the target of the renaming exists, in other words
70 the existing contents of the file at this location are lost.
71 - This parameter is ignored when O(rename=false).
72 type: bool
73 default: false
74 requirements:
75 - dpkg-divert >= 1.15.0 (Debian family)
76 """
77
78 EXAMPLES = r"""
79 - name: Divert /usr/bin/busybox to /usr/bin/busybox.distrib and keep file in place
80 community.general.dpkg_divert:
81 path: /usr/bin/busybox
82
83 - name: Divert /usr/bin/busybox by package 'branding'
84 community.general.dpkg_divert:
85 path: /usr/bin/busybox
86 holder: branding
87
88 - name: Divert and rename busybox to busybox.dpkg-divert
89 community.general.dpkg_divert:
90 path: /usr/bin/busybox
91 divert: /usr/bin/busybox.dpkg-divert
92 rename: true
93
94 - name: Remove the busybox diversion and move the diverted file back
95 community.general.dpkg_divert:
96 path: /usr/bin/busybox
97 state: absent
98 rename: true
99 force: true
100 """
101
102 RETURN = r"""
103 commands:
104 description: The dpkg-divert commands ran internally by the module.
105 type: list
106 returned: on_success
107 elements: str
108 sample: "/usr/bin/dpkg-divert --no-rename --remove /etc/foobarrc"
109 messages:
110 description: The dpkg-divert relevant messages (stdout or stderr).
111 type: list
112 returned: on_success
113 elements: str
114 sample: "Removing 'local diversion of /etc/foobarrc to /etc/foobarrc.distrib'"
115 diversion:
116 description: The status of the diversion after task execution.
117 type: dict
118 returned: always
119 contains:
120 divert:
121 description: The location of the diverted file.
122 type: str
123 holder:
124 description: The package holding the diversion.
125 type: str
126 path:
127 description: The path of the file to divert/undivert.
128 type: str
129 state:
130 description: The state of the diversion.
131 type: str
132 sample:
133 {
134 "divert": "/etc/foobarrc.distrib",
135 "holder": "LOCAL",
136 "path": "/etc/foobarrc",
137 "state": "present"
138 }
139 """
140
141
142 import os
143 import re
144
145 from ansible.module_utils.basic import AnsibleModule
146 from ansible.module_utils.common.text.converters import to_bytes
147
148 from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
149
150
151 def diversion_state(module, command, path):
152 diversion = dict(path=path, state="absent", divert=None, holder=None)
153 rc, out, err = module.run_command([command, "--listpackage", path], check_rc=True)
154 if out:
155 diversion["state"] = "present"
156 diversion["holder"] = out.rstrip()
157 rc, out, err = module.run_command([command, "--truename", path], check_rc=True)
158 diversion["divert"] = out.rstrip()
159 return diversion
160
161
162 def main():
163 module = AnsibleModule(
164 argument_spec=dict(
165 path=dict(required=True, type="path"),
166 state=dict(type="str", default="present", choices=["absent", "present"]),
167 holder=dict(type="str"),
168 divert=dict(type="path"),
169 rename=dict(type="bool", default=False),
170 force=dict(type="bool", default=False),
171 ),
172 supports_check_mode=True,
173 )
174 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
175
176 path = module.params["path"]
177 state = module.params["state"]
178 holder = module.params["holder"]
179 divert = module.params["divert"]
180 rename = module.params["rename"]
181 force = module.params["force"]
182
183 diversion_wanted = dict(path=path, state=state)
184 changed = False
185
186 DPKG_DIVERT = module.get_bin_path("dpkg-divert", required=True)
187 MAINCOMMAND = [DPKG_DIVERT]
188
189 # Option --listpackage is needed and comes with 1.15.0
190 rc, stdout, stderr = module.run_command([DPKG_DIVERT, "--version"], check_rc=True)
191 [current_version] = [x for x in stdout.splitlines()[0].split() if re.match("^[0-9]+[.][0-9]", x)]
192 if LooseVersion(current_version) < LooseVersion("1.15.0"):
193 module.fail_json(msg="Unsupported dpkg version (<1.15.0).")
194 no_rename_is_supported = LooseVersion(current_version) >= LooseVersion("1.19.1")
195
196 b_path = to_bytes(path, errors="surrogate_or_strict")
197 path_exists = os.path.exists(b_path)
198 # Used for things not doable with a single dpkg-divert command (as forced
199 # renaming of files, and diversion's 'holder' or 'divert' updates).
200 target_exists = False
201 truename_exists = False
202
203 diversion_before = diversion_state(module, DPKG_DIVERT, path)
204 if diversion_before["state"] == "present":
205 b_divert = to_bytes(diversion_before["divert"], errors="surrogate_or_strict")
206 truename_exists = os.path.exists(b_divert)
207
208 # Append options as requested in the task parameters, but ignore some of
209 # them when removing the diversion.
210 if rename:
211 MAINCOMMAND.append("--rename")
212 elif no_rename_is_supported:
213 MAINCOMMAND.append("--no-rename")
214
215 if state == "present":
216 if holder and holder != "LOCAL":
217 MAINCOMMAND.extend(["--package", holder])
218 diversion_wanted["holder"] = holder
219 else:
220 MAINCOMMAND.append("--local")
221 diversion_wanted["holder"] = "LOCAL"
222
223 if divert:
224 MAINCOMMAND.extend(["--divert", divert])
225 target = divert
226 else:
227 target = f"{path}.distrib"
228
229 MAINCOMMAND.extend(["--add", path])
230 diversion_wanted["divert"] = target
231 b_target = to_bytes(target, errors="surrogate_or_strict")
232 target_exists = os.path.exists(b_target)
233
234 else:
235 MAINCOMMAND.extend(["--remove", path])
236 diversion_wanted["divert"] = None
237 diversion_wanted["holder"] = None
238
239 # Start to populate the returned objects.
240 diversion = diversion_before.copy()
241 maincommand = " ".join(MAINCOMMAND)
242 commands = [maincommand]
243
244 if module.check_mode or diversion_wanted == diversion_before:
245 MAINCOMMAND.insert(1, "--test")
246 diversion_after = diversion_wanted
247
248 # Just try and see
249 rc, stdout, stderr = module.run_command(MAINCOMMAND)
250
251 if rc == 0:
252 messages = [stdout.rstrip()]
253
254 # else... cases of failure with dpkg-divert are:
255 # - The diversion does not belong to the same package (or LOCAL)
256 # - The divert filename is not the same (e.g. path.distrib != path.divert)
257 # - The renaming is forbidden by dpkg-divert (i.e. both the file and the
258 # diverted file exist)
259
260 elif state != diversion_before["state"]:
261 # There should be no case with 'divert' and 'holder' when creating the
262 # diversion from none, and they're ignored when removing the diversion.
263 # So this is all about renaming...
264 if (
265 rename
266 and path_exists
267 and ((state == "absent" and truename_exists) or (state == "present" and target_exists))
268 ):
269 if not force:
270 msg = "Set 'force' param to True to force renaming of files."
271 module.fail_json(
272 changed=changed, cmd=maincommand, rc=rc, msg=msg, stderr=stderr, stdout=stdout, diversion=diversion
273 )
274 else:
275 msg = "Unexpected error while changing state of the diversion."
276 module.fail_json(
277 changed=changed, cmd=maincommand, rc=rc, msg=msg, stderr=stderr, stdout=stdout, diversion=diversion
278 )
279
280 to_remove = path
281 if state == "present":
282 to_remove = target
283
284 if not module.check_mode:
285 try:
286 b_remove = to_bytes(to_remove, errors="surrogate_or_strict")
287 os.unlink(b_remove)
288 except OSError as e:
289 msg = f"Failed to remove {to_remove}: {e}"
290 module.fail_json(
291 changed=changed, cmd=maincommand, rc=rc, msg=msg, stderr=stderr, stdout=stdout, diversion=diversion
292 )
293 rc, stdout, stderr = module.run_command(MAINCOMMAND, check_rc=True)
294
295 messages = [stdout.rstrip()]
296
297 # The situation is that we want to modify the settings (holder or divert)
298 # of an existing diversion. dpkg-divert does not handle this, and we have
299 # to remove the existing diversion first, and then set a new one.
300 else:
301 RMDIVERSION = [DPKG_DIVERT, "--remove", path]
302 if no_rename_is_supported:
303 RMDIVERSION.insert(1, "--no-rename")
304 rmdiversion = " ".join(RMDIVERSION)
305
306 if module.check_mode:
307 RMDIVERSION.insert(1, "--test")
308
309 if rename:
310 MAINCOMMAND.remove("--rename")
311 if no_rename_is_supported:
312 MAINCOMMAND.insert(1, "--no-rename")
313 maincommand = " ".join(MAINCOMMAND)
314
315 commands = [rmdiversion, maincommand]
316 rc, rmdout, rmderr = module.run_command(RMDIVERSION, check_rc=True)
317
318 if module.check_mode:
319 messages = [rmdout.rstrip(), "Running in check mode"]
320 else:
321 rc, stdout, stderr = module.run_command(MAINCOMMAND, check_rc=True)
322 messages = [rmdout.rstrip(), stdout.rstrip()]
323
324 # Avoid if possible to orphan files (i.e. to dereference them in diversion
325 # database but let them in place), but do not make renaming issues fatal.
326 # BTW, this module is not about state of files involved in the diversion.
327 old = diversion_before["divert"]
328 new = diversion_wanted["divert"]
329 if new != old:
330 b_old = to_bytes(old, errors="surrogate_or_strict")
331 b_new = to_bytes(new, errors="surrogate_or_strict")
332 if os.path.exists(b_old) and not os.path.exists(b_new):
333 try:
334 os.rename(b_old, b_new)
335 except OSError:
336 pass
337
338 if not module.check_mode:
339 diversion_after = diversion_state(module, DPKG_DIVERT, path)
340
341 diversion = diversion_after.copy()
342 diff = dict()
343 if module._diff:
344 diff["before"] = diversion_before
345 diff["after"] = diversion_after
346
347 if diversion_after != diversion_before:
348 changed = True
349
350 if diversion_after == diversion_wanted:
351 module.exit_json(changed=changed, diversion=diversion, commands=commands, messages=messages, diff=diff)
352 else:
353 msg = "Unexpected error: see stdout and stderr for details."
354 module.fail_json(
355 changed=changed, cmd=maincommand, rc=rc, msg=msg, stderr=stderr, stdout=stdout, diversion=diversion
356 )
357
358
359 if __name__ == "__main__":
360 main()