Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2014, Jakub Jirutka <[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: layman
12 author: "Jakub Jirutka (@jirutka)"
13 short_description: Manage Gentoo overlays
14 deprecated:
15 removed_in: 14.0.0
16 why: Gentoo deprecated C(layman) in mid-2023.
17 alternative: None.
18 description:
19 - Uses Layman to manage an additional repositories for the Portage package manager on Gentoo Linux. Please note that Layman
20 must be installed on a managed node prior using this module.
21 requirements:
22 - layman python module
23 extends_documentation_fragment:
24 - community.general._attributes
25 attributes:
26 check_mode:
27 support: full
28 diff_mode:
29 support: none
30 options:
31 name:
32 description:
33 - The overlay ID to install, synchronize, or uninstall. Use V(ALL) to sync all of the installed overlays (can be used
34 only when O(state=updated)).
35 required: true
36 type: str
37 list_url:
38 description:
39 - An URL of the alternative overlays list that defines the overlay to install. This list is fetched and saved under
40 C(${overlay_defs}/${name}.xml), where C(overlay_defs) is read from the Layman's configuration.
41 aliases: [url]
42 type: str
43 state:
44 description:
45 - Whether to install (V(present)), sync (V(updated)), or uninstall (V(absent)) the overlay.
46 default: present
47 choices: [present, absent, updated]
48 type: str
49 validate_certs:
50 description:
51 - If V(false), SSL certificates are not validated. This should only be set to V(false) when no other option exists.
52 type: bool
53 default: true
54 """
55
56 EXAMPLES = r"""
57 - name: Install the overlay mozilla which is on the central overlays list
58 community.general.layman:
59 name: mozilla
60
61 - name: Install the overlay cvut from the specified alternative list
62 community.general.layman:
63 name: cvut
64 list_url: 'http://raw.github.com/cvut/gentoo-overlay/master/overlay.xml'
65
66 - name: Update (sync) the overlay cvut or install if not installed yet
67 community.general.layman:
68 name: cvut
69 list_url: 'http://raw.github.com/cvut/gentoo-overlay/master/overlay.xml'
70 state: updated
71
72 - name: Update (sync) all of the installed overlays
73 community.general.layman:
74 name: ALL
75 state: updated
76
77 - name: Uninstall the overlay cvut
78 community.general.layman:
79 name: cvut
80 state: absent
81 """
82
83 import shutil
84 import traceback
85 from os import path
86
87 LAYMAN_IMP_ERR = None
88 try:
89 from layman.api import LaymanAPI
90 from layman.config import BareConfig
91
92 HAS_LAYMAN_API = True
93 except ImportError:
94 LAYMAN_IMP_ERR = traceback.format_exc()
95 HAS_LAYMAN_API = False
96
97 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
98 from ansible.module_utils.urls import fetch_url
99
100 USERAGENT = "ansible-httpget"
101
102
103 class ModuleError(Exception):
104 pass
105
106
107 def init_layman(config=None):
108 """Returns the initialized ``LaymanAPI``.
109
110 :param config: the layman's configuration to use (optional)
111 """
112 if config is None:
113 config = BareConfig(read_configfile=True, quietness=1)
114 return LaymanAPI(config)
115
116
117 def download_url(module, url, dest):
118 """
119 :param url: the URL to download
120 :param dest: the absolute path of where to save the downloaded content to;
121 it must be writable and not a directory
122
123 :raises ModuleError
124 """
125
126 # Hack to add params in the form that fetch_url expects
127 module.params["http_agent"] = USERAGENT
128 response, info = fetch_url(module, url)
129 if info["status"] != 200:
130 raise ModuleError(f"Failed to get {url}: {info['msg']}")
131
132 try:
133 with open(dest, "w") as f:
134 shutil.copyfileobj(response, f)
135 except OSError as e:
136 raise ModuleError(f"Failed to write: {e}") from e
137
138
139 def install_overlay(module, name, list_url=None):
140 """Installs the overlay repository. If not on the central overlays list,
141 then :list_url of an alternative list must be provided. The list will be
142 fetched and saved under ``%(overlay_defs)/%(name.xml)`` (location of the
143 ``overlay_defs`` is read from the Layman's configuration).
144
145 :param name: the overlay id
146 :param list_url: the URL of the remote repositories list to look for the overlay
147 definition (optional, default: None)
148
149 :returns: True if the overlay was installed, or False if already exists
150 (i.e. nothing has changed)
151 :raises ModuleError
152 """
153 # read Layman configuration
154 layman_conf = BareConfig(read_configfile=True)
155 layman = init_layman(layman_conf)
156
157 if layman.is_installed(name):
158 return False
159
160 if module.check_mode:
161 mymsg = f"Would add layman repo '{name}'"
162 module.exit_json(changed=True, msg=mymsg)
163
164 if not layman.is_repo(name):
165 if not list_url:
166 raise ModuleError(
167 f"Overlay '{name}' is not on the list of known overlays and URL of the remote list was not provided."
168 )
169
170 overlay_defs = layman_conf.get_option("overlay_defs")
171 dest = path.join(overlay_defs, f"{name}.xml")
172
173 download_url(module, list_url, dest)
174
175 # reload config
176 layman = init_layman()
177
178 if not layman.add_repos(name):
179 raise ModuleError(layman.get_errors())
180
181 return True
182
183
184 def uninstall_overlay(module, name):
185 """Uninstalls the given overlay repository from the system.
186
187 :param name: the overlay id to uninstall
188
189 :returns: True if the overlay was uninstalled, or False if doesn't exist
190 (i.e. nothing has changed)
191 :raises ModuleError
192 """
193 layman = init_layman()
194
195 if not layman.is_installed(name):
196 return False
197
198 if module.check_mode:
199 mymsg = f"Would remove layman repo '{name}'"
200 module.exit_json(changed=True, msg=mymsg)
201
202 layman.delete_repos(name)
203 if layman.get_errors():
204 raise ModuleError(layman.get_errors())
205
206 return True
207
208
209 def sync_overlay(name):
210 """Synchronizes the specified overlay repository.
211
212 :param name: the overlay repository id to sync
213 :raises ModuleError
214 """
215 layman = init_layman()
216
217 if not layman.sync(name):
218 messages = [str(item[1]) for item in layman.sync_results[2]]
219 raise ModuleError(messages)
220
221
222 def sync_overlays():
223 """Synchronize all of the installed overlays.
224
225 :raises ModuleError
226 """
227 layman = init_layman()
228
229 for name in layman.get_installed():
230 sync_overlay(name)
231
232
233 def main():
234 # define module
235 module = AnsibleModule(
236 argument_spec=dict(
237 name=dict(required=True),
238 list_url=dict(aliases=["url"]),
239 state=dict(default="present", choices=["present", "absent", "updated"]),
240 validate_certs=dict(default=True, type="bool"),
241 ),
242 supports_check_mode=True,
243 )
244
245 if not HAS_LAYMAN_API:
246 module.fail_json(msg=missing_required_lib("Layman"), exception=LAYMAN_IMP_ERR)
247
248 state, name, url = (module.params[key] for key in ["state", "name", "list_url"])
249
250 changed = False
251 try:
252 if state == "present":
253 changed = install_overlay(module, name, url)
254
255 elif state == "updated":
256 if name == "ALL":
257 sync_overlays()
258 elif install_overlay(module, name, url):
259 changed = True
260 else:
261 sync_overlay(name)
262 else:
263 changed = uninstall_overlay(module, name)
264
265 except ModuleError as e:
266 module.fail_json(msg=e.message)
267 else:
268 module.exit_json(changed=changed, name=name)
269
270
271 if __name__ == "__main__":
272 main()