Debian Codegraph @

test/support/integration/plugins/modules/pkgng.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2013, bleader
5 # Written by bleader <[email protected]>
6 # Based on pkgin module written by Shaun Zinck <shaun.zinck at gmail.com>
7 # that was based on pacman module written by Afterburn <https://github.com/afterburn>
8 # that was based on apt module written by Matthew Williams <[email protected]>
9 #
10 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
11
12 from __future__ import annotations
13
14
15 ANSIBLE_METADATA = {'metadata_version': '1.1',
16 'status': ['preview'],
17 'supported_by': 'community'}
18
19
20 DOCUMENTATION = """
21 ---
22 module: pkgng
23 short_description: Package manager for FreeBSD >= 9.0
24 description:
25 - Manage binary packages for FreeBSD using 'pkgng' which is available in versions after 9.0.
26 version_added: "1.2"
27 options:
28 name:
29 description:
30 - Name or list of names of packages to install/remove.
31 required: true
32 state:
33 description:
34 - State of the package.
35 - 'Note: "latest" added in 2.7'
36 choices: [ 'present', 'latest', 'absent' ]
37 required: false
38 default: present
39 cached:
40 description:
41 - Use local package base instead of fetching an updated one.
42 type: bool
43 required: false
44 default: no
45 annotation:
46 description:
47 - A comma-separated list of keyvalue-pairs of the form
48 C(<+/-/:><key>[=<value>]). A C(+) denotes adding an annotation, a
49 C(-) denotes removing an annotation, and C(:) denotes modifying an
50 annotation.
51 If setting or modifying annotations, a value must be provided.
52 required: false
53 version_added: "1.6"
54 pkgsite:
55 description:
56 - For pkgng versions before 1.1.4, specify packagesite to use
57 for downloading packages. If not specified, use settings from
58 C(/usr/local/etc/pkg.conf).
59 - For newer pkgng versions, specify a the name of a repository
60 configured in C(/usr/local/etc/pkg/repos).
61 required: false
62 rootdir:
63 description:
64 - For pkgng versions 1.5 and later, pkg will install all packages
65 within the specified root directory.
66 - Can not be used together with I(chroot) or I(jail) options.
67 required: false
68 chroot:
69 version_added: "2.1"
70 description:
71 - Pkg will chroot in the specified environment.
72 - Can not be used together with I(rootdir) or I(jail) options.
73 required: false
74 jail:
75 version_added: "2.4"
76 description:
77 - Pkg will execute in the given jail name or id.
78 - Can not be used together with I(chroot) or I(rootdir) options.
79 autoremove:
80 version_added: "2.2"
81 description:
82 - Remove automatically installed packages which are no longer needed.
83 required: false
84 type: bool
85 default: no
86 author: "bleader (@bleader)"
87 notes:
88 - When using pkgsite, be careful that already in cache packages won't be downloaded again.
89 - When used with a `loop:` each package will be processed individually,
90 it is much more efficient to pass the list directly to the `name` option.
91 """
92
93 EXAMPLES = """
94 - name: Install package foo
95 pkgng:
96 name: foo
97 state: present
98
99 - name: Annotate package foo and bar
100 pkgng:
101 name: foo,bar
102 annotation: '+test1=baz,-test2,:test3=foobar'
103
104 - name: Remove packages foo and bar
105 pkgng:
106 name: foo,bar
107 state: absent
108
109 # "latest" support added in 2.7
110 - name: Upgrade package baz
111 pkgng:
112 name: baz
113 state: latest
114 """
115
116
117 import re
118 from ansible.module_utils.basic import AnsibleModule
119
120
121 def query_package(module, pkgng_path, name, dir_arg):
122
123 rc, out, err = module.run_command("%s %s info -g -e %s" % (pkgng_path, dir_arg, name))
124
125 if rc == 0:
126 return True
127
128 return False
129
130
131 def query_update(module, pkgng_path, name, dir_arg, old_pkgng, pkgsite):
132
133 # Check to see if a package upgrade is available.
134 # rc = 0, no updates available or package not installed
135 # rc = 1, updates available
136 if old_pkgng:
137 rc, out, err = module.run_command("%s %s upgrade -g -n %s" % (pkgsite, pkgng_path, name))
138 else:
139 rc, out, err = module.run_command("%s %s upgrade %s -g -n %s" % (pkgng_path, dir_arg, pkgsite, name))
140
141 if rc == 1:
142 return True
143
144 return False
145
146
147 def pkgng_older_than(module, pkgng_path, compare_version):
148
149 rc, out, err = module.run_command("%s -v" % pkgng_path)
150 version = [int(x) for x in re.split(r'[\._]', out)]
151
152 i = 0
153 new_pkgng = True
154 while compare_version[i] == version[i]:
155 i += 1
156 if i == min(len(compare_version), len(version)):
157 break
158 else:
159 if compare_version[i] > version[i]:
160 new_pkgng = False
161 return not new_pkgng
162
163
164 def remove_packages(module, pkgng_path, packages, dir_arg):
165
166 remove_c = 0
167 # Using a for loop in case of error, we can report the package that failed
168 for package in packages:
169 # Query the package first, to see if we even need to remove
170 if not query_package(module, pkgng_path, package, dir_arg):
171 continue
172
173 if not module.check_mode:
174 rc, out, err = module.run_command("%s %s delete -y %s" % (pkgng_path, dir_arg, package))
175
176 if not module.check_mode and query_package(module, pkgng_path, package, dir_arg):
177 module.fail_json(msg="failed to remove %s: %s" % (package, out))
178
179 remove_c += 1
180
181 if remove_c > 0:
182
183 return (True, "removed %s package(s)" % remove_c)
184
185 return (False, "package(s) already absent")
186
187
188 def install_packages(module, pkgng_path, packages, cached, pkgsite, dir_arg, state):
189
190 install_c = 0
191
192 # as of pkg-1.1.4, PACKAGESITE is deprecated in favor of repository definitions
193 # in /usr/local/etc/pkg/repos
194 old_pkgng = pkgng_older_than(module, pkgng_path, [1, 1, 4])
195 if pkgsite != "":
196 if old_pkgng:
197 pkgsite = "PACKAGESITE=%s" % (pkgsite)
198 else:
199 pkgsite = "-r %s" % (pkgsite)
200
201 # This environment variable skips mid-install prompts,
202 # setting them to their default values.
203 batch_var = 'env BATCH=yes'
204
205 if not module.check_mode and not cached:
206 if old_pkgng:
207 rc, out, err = module.run_command("%s %s update" % (pkgsite, pkgng_path))
208 else:
209 rc, out, err = module.run_command("%s %s update" % (pkgng_path, dir_arg))
210 if rc != 0:
211 module.fail_json(msg="Could not update catalogue [%d]: %s %s" % (rc, out, err))
212
213 for package in packages:
214 already_installed = query_package(module, pkgng_path, package, dir_arg)
215 if already_installed and state == "present":
216 continue
217
218 update_available = query_update(module, pkgng_path, package, dir_arg, old_pkgng, pkgsite)
219 if not update_available and already_installed and state == "latest":
220 continue
221
222 if not module.check_mode:
223 if already_installed:
224 action = "upgrade"
225 else:
226 action = "install"
227 if old_pkgng:
228 rc, out, err = module.run_command("%s %s %s %s -g -U -y %s" % (batch_var, pkgsite, pkgng_path, action, package))
229 else:
230 rc, out, err = module.run_command("%s %s %s %s %s -g -U -y %s" % (batch_var, pkgng_path, dir_arg, action, pkgsite, package))
231
232 if not module.check_mode and not query_package(module, pkgng_path, package, dir_arg):
233 module.fail_json(msg="failed to %s %s: %s" % (action, package, out), stderr=err)
234
235 install_c += 1
236
237 if install_c > 0:
238 return (True, "added %s package(s)" % (install_c))
239
240 return (False, "package(s) already %s" % (state))
241
242
243 def annotation_query(module, pkgng_path, package, tag, dir_arg):
244 rc, out, err = module.run_command("%s %s info -g -A %s" % (pkgng_path, dir_arg, package))
245 match = re.search(r'^\s*(?P<tag>%s)\s*:\s*(?P<value>\w+)' % tag, out, flags=re.MULTILINE)
246 if match:
247 return match.group('value')
248 return False
249
250
251 def annotation_add(module, pkgng_path, package, tag, value, dir_arg):
252 _value = annotation_query(module, pkgng_path, package, tag, dir_arg)
253 if not _value:
254 # Annotation does not exist, add it.
255 rc, out, err = module.run_command('%s %s annotate -y -A %s %s "%s"'
256 % (pkgng_path, dir_arg, package, tag, value))
257 if rc != 0:
258 module.fail_json(msg="could not annotate %s: %s"
259 % (package, out), stderr=err)
260 return True
261 elif _value != value:
262 # Annotation exists, but value differs
263 module.fail_json(
264 mgs="failed to annotate %s, because %s is already set to %s, but should be set to %s"
265 % (package, tag, _value, value))
266 return False
267 else:
268 # Annotation exists, nothing to do
269 return False
270
271
272 def annotation_delete(module, pkgng_path, package, tag, value, dir_arg):
273 _value = annotation_query(module, pkgng_path, package, tag, dir_arg)
274 if _value:
275 rc, out, err = module.run_command('%s %s annotate -y -D %s %s'
276 % (pkgng_path, dir_arg, package, tag))
277 if rc != 0:
278 module.fail_json(msg="could not delete annotation to %s: %s"
279 % (package, out), stderr=err)
280 return True
281 return False
282
283
284 def annotation_modify(module, pkgng_path, package, tag, value, dir_arg):
285 _value = annotation_query(module, pkgng_path, package, tag, dir_arg)
286 if not value:
287 # No such tag
288 module.fail_json(msg="could not change annotation to %s: tag %s does not exist"
289 % (package, tag))
290 elif _value == value:
291 # No change in value
292 return False
293 else:
294 rc, out, err = module.run_command('%s %s annotate -y -M %s %s "%s"'
295 % (pkgng_path, dir_arg, package, tag, value))
296 if rc != 0:
297 module.fail_json(msg="could not change annotation annotation to %s: %s"
298 % (package, out), stderr=err)
299 return True
300
301
302 def annotate_packages(module, pkgng_path, packages, annotation, dir_arg):
303 annotate_c = 0
304 annotations = map(lambda _annotation:
305 re.match(r'(?P<operation>[\+-:])(?P<tag>\w+)(=(?P<value>\w+))?',
306 _annotation).groupdict(),
307 re.split(r',', annotation))
308
309 operation = {
310 '+': annotation_add,
311 '-': annotation_delete,
312 ':': annotation_modify
313 }
314
315 for package in packages:
316 for _annotation in annotations:
317 if operation[_annotation['operation']](module, pkgng_path, package, _annotation['tag'], _annotation['value']):
318 annotate_c += 1
319
320 if annotate_c > 0:
321 return (True, "added %s annotations." % annotate_c)
322 return (False, "changed no annotations")
323
324
325 def autoremove_packages(module, pkgng_path, dir_arg):
326 rc, out, err = module.run_command("%s %s autoremove -n" % (pkgng_path, dir_arg))
327
328 autoremove_c = 0
329
330 match = re.search('^Deinstallation has been requested for the following ([0-9]+) packages', out, re.MULTILINE)
331 if match:
332 autoremove_c = int(match.group(1))
333
334 if autoremove_c == 0:
335 return False, "no package(s) to autoremove"
336
337 if not module.check_mode:
338 rc, out, err = module.run_command("%s %s autoremove -y" % (pkgng_path, dir_arg))
339
340 return True, "autoremoved %d package(s)" % (autoremove_c)
341
342
343 def main():
344 module = AnsibleModule(
345 argument_spec=dict(
346 state=dict(default="present", choices=["present", "latest", "absent"], required=False),
347 name=dict(aliases=["pkg"], required=True, type='list'),
348 cached=dict(default=False, type='bool'),
349 annotation=dict(default="", required=False),
350 pkgsite=dict(default="", required=False),
351 rootdir=dict(default="", required=False, type='path'),
352 chroot=dict(default="", required=False, type='path'),
353 jail=dict(default="", required=False, type='str'),
354 autoremove=dict(default=False, type='bool')),
355 supports_check_mode=True,
356 mutually_exclusive=[["rootdir", "chroot", "jail"]])
357
358 pkgng_path = module.get_bin_path('pkg', True)
359
360 p = module.params
361
362 pkgs = p["name"]
363
364 changed = False
365 msgs = []
366 dir_arg = ""
367
368 if p["rootdir"] != "":
369 old_pkgng = pkgng_older_than(module, pkgng_path, [1, 5, 0])
370 if old_pkgng:
371 module.fail_json(msg="To use option 'rootdir' pkg version must be 1.5 or greater")
372 else:
373 dir_arg = "--rootdir %s" % (p["rootdir"])
374
375 if p["chroot"] != "":
376 dir_arg = '--chroot %s' % (p["chroot"])
377
378 if p["jail"] != "":
379 dir_arg = '--jail %s' % (p["jail"])
380
381 if p["state"] in ("present", "latest"):
382 _changed, _msg = install_packages(module, pkgng_path, pkgs, p["cached"], p["pkgsite"], dir_arg, p["state"])
383 changed = changed or _changed
384 msgs.append(_msg)
385
386 elif p["state"] == "absent":
387 _changed, _msg = remove_packages(module, pkgng_path, pkgs, dir_arg)
388 changed = changed or _changed
389 msgs.append(_msg)
390
391 if p["autoremove"]:
392 _changed, _msg = autoremove_packages(module, pkgng_path, dir_arg)
393 changed = changed or _changed
394 msgs.append(_msg)
395
396 if p["annotation"]:
397 _changed, _msg = annotate_packages(module, pkgng_path, pkgs, p["annotation"], dir_arg)
398 changed = changed or _changed
399 msgs.append(_msg)
400
401 module.exit_json(changed=changed, msg=", ".join(msgs))
402
403
404 if __name__ == '__main__':
405 main()