Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, 2017 Jasper Lievisse Adriaanse <[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: imgadm
11 short_description: Manage SmartOS images
12 description:
13 - Manage SmartOS virtual machine images through imgadm(8).
14 author: Jasper Lievisse Adriaanse (@jasperla)
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: none
20 diff_mode:
21 support: none
22 options:
23 force:
24 type: bool
25 description:
26 - Force a given operation (where supported by imgadm(8)).
27 pool:
28 default: zones
29 description:
30 - The zpool to import to or delete images from.
31 type: str
32 source:
33 description:
34 - URI for the image source.
35 type: str
36 state:
37 required: true
38 choices: [present, absent, deleted, imported, updated, vacuumed]
39 description:
40 - State the object operated on should be in. V(imported) is an alias for for V(present) and V(deleted) for V(absent).
41 When set to V(vacuumed) and O(uuid=*), it removes all unused images.
42 type: str
43
44 type:
45 choices: [imgapi, docker, dsapi]
46 default: imgapi
47 description:
48 - Type for image sources.
49 type: str
50
51 uuid:
52 description:
53 - Image UUID. Can either be a full UUID or V(*) for all images.
54 type: str
55 seealso:
56 - name: imgadm(8)
57 description: Complete manual page for the command C(imgadm).
58 link: https://smartos.org/man/8/imgadm
59 """
60
61 EXAMPLES = r"""
62 - name: Import an image
63 community.general.imgadm:
64 uuid: '70e3ae72-96b6-11e6-9056-9737fd4d0764'
65 state: imported
66
67 - name: Delete an image
68 community.general.imgadm:
69 uuid: '70e3ae72-96b6-11e6-9056-9737fd4d0764'
70 state: deleted
71
72 - name: Update all images
73 community.general.imgadm:
74 uuid: '*'
75 state: updated
76
77 - name: Update a single image
78 community.general.imgadm:
79 uuid: '70e3ae72-96b6-11e6-9056-9737fd4d0764'
80 state: updated
81
82 - name: Add a source
83 community.general.imgadm:
84 source: 'https://datasets.project-fifo.net'
85 state: present
86
87 - name: Add a Docker source
88 community.general.imgadm:
89 source: 'https://docker.io'
90 type: docker
91 state: present
92
93 - name: Remove a source
94 community.general.imgadm:
95 source: 'https://docker.io'
96 state: absent
97 """
98
99 RETURN = r"""
100 source:
101 description: Source that is managed.
102 returned: When not managing an image.
103 type: str
104 sample: https://datasets.project-fifo.net
105 uuid:
106 description: UUID for an image operated on.
107 returned: When not managing an image source.
108 type: str
109 sample: 70e3ae72-96b6-11e6-9056-9737fd4d0764
110 state:
111 description: State of the target, after execution.
112 returned: success
113 type: str
114 sample: 'present'
115 """
116
117 import re
118
119 from ansible.module_utils.basic import AnsibleModule
120
121 # Shortcut for the imgadm(8) command. While imgadm(8) supports a
122 # -E option to return any errors in JSON, the generated JSON does not play well
123 # with the JSON parsers of Python. The returned message contains '\n' as part of
124 # the stacktrace, which breaks the parsers.
125
126
127 class Imgadm:
128 def __init__(self, module):
129 self.module = module
130 self.params = module.params
131 self.cmd = module.get_bin_path("imgadm", required=True)
132 self.changed = False
133 self.uuid = module.params["uuid"]
134
135 # Since there are a number of (natural) aliases, prevent having to look
136 # them up every time we operate on `state`.
137 if self.params["state"] in ["present", "imported", "updated"]:
138 self.present = True
139 else:
140 self.present = False
141
142 # Perform basic UUID validation upfront.
143 if self.uuid and self.uuid != "*":
144 if not re.match("^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$", self.uuid, re.IGNORECASE):
145 module.fail_json(msg="Provided value for uuid option is not a valid UUID.")
146
147 # Helper method to massage stderr
148 def errmsg(self, stderr):
149 match = re.match(r"^imgadm .*?: error \(\w+\): (.*): .*", stderr)
150 if match:
151 return match.groups()[0]
152 else:
153 return "Unexpected failure"
154
155 def update_images(self):
156 if self.uuid == "*":
157 cmd = [self.cmd, "update"]
158 else:
159 cmd = [self.cmd, "update", self.uuid]
160
161 (rc, stdout, stderr) = self.module.run_command(cmd)
162
163 if rc != 0:
164 self.module.fail_json(msg=f"Failed to update images: {self.errmsg(stderr)}")
165
166 # There is no feedback from imgadm(8) to determine if anything
167 # was actually changed. So treat this as an 'always-changes' operation.
168 # Note that 'imgadm -v' produces unparsable JSON...
169 self.changed = True
170
171 def manage_sources(self):
172 force = self.params["force"]
173 source = self.params["source"]
174 imgtype = self.params["type"]
175
176 cmd = [self.cmd, "sources"]
177
178 if force:
179 cmd = cmd + ["-f"]
180
181 if self.present:
182 cmd = cmd + ["-a", source, "-t", imgtype]
183 (rc, stdout, stderr) = self.module.run_command(cmd)
184
185 if rc != 0:
186 self.module.fail_json(msg=f"Failed to add source: {self.errmsg(stderr)}")
187
188 # Check the various responses.
189 # Note that trying to add a source with the wrong type is handled
190 # above as it results in a non-zero status.
191
192 regex = f'Already have "{imgtype}" image source "{source}", no change'
193 if re.match(regex, stdout):
194 self.changed = False
195
196 regex = f'Added "{imgtype}" image source "{source}"'
197 if re.match(regex, stdout):
198 self.changed = True
199 else:
200 # Type is ignored by imgadm(8) here
201 cmd += f" -d {source}"
202 (rc, stdout, stderr) = self.module.run_command(cmd)
203
204 if rc != 0:
205 self.module.fail_json(msg=f"Failed to remove source: {self.errmsg(stderr)}")
206
207 regex = f'Do not have image source "{source}", no change'
208 if re.match(regex, stdout):
209 self.changed = False
210
211 regex = f'Deleted ".*" image source "{source}"'
212 if re.match(regex, stdout):
213 self.changed = True
214
215 def manage_images(self):
216 pool = self.params["pool"]
217 state = self.params["state"]
218
219 if state == "vacuumed":
220 # Unconditionally pass '--force', otherwise we're prompted with 'y/N'
221 cmd = [self.cmd, "vacuum", "-f"]
222
223 (rc, stdout, stderr) = self.module.run_command(cmd)
224
225 if rc != 0:
226 self.module.fail_json(msg=f"Failed to vacuum images: {self.errmsg(stderr)}")
227 else:
228 if stdout == "":
229 self.changed = False
230 else:
231 self.changed = True
232 if self.present:
233 cmd = [self.cmd, "import", "-P", pool, "-q"] + ([self.uuid] if self.uuid else [])
234 (rc, stdout, stderr) = self.module.run_command(cmd)
235
236 if rc != 0:
237 self.module.fail_json(msg=f"Failed to import image: {self.errmsg(stderr)}")
238
239 regex = rf"Image {self.uuid} \(.*\) is already installed, skipping"
240 if re.match(regex, stdout):
241 self.changed = False
242
243 regex = ".*ActiveImageNotFound.*"
244 if re.match(regex, stderr):
245 self.changed = False
246
247 regex = f"Imported image {self.uuid}.*"
248 if re.match(regex, stdout.splitlines()[-1]):
249 self.changed = True
250 else:
251 cmd = [self.cmd, "delete", "-P", pool] + ([self.uuid] if self.uuid else [])
252 (rc, stdout, stderr) = self.module.run_command(cmd)
253
254 regex = ".*ImageNotInstalled.*"
255 if re.match(regex, stderr):
256 # Even if the 'rc' was non-zero (3), we handled the situation
257 # in order to determine if there was a change.
258 self.changed = False
259
260 regex = f"Deleted image {self.uuid}"
261 if re.match(regex, stdout):
262 self.changed = True
263
264
265 def main():
266 module = AnsibleModule(
267 argument_spec=dict(
268 force=dict(type="bool"),
269 pool=dict(default="zones"),
270 source=dict(),
271 state=dict(required=True, choices=["present", "absent", "deleted", "imported", "updated", "vacuumed"]),
272 type=dict(default="imgapi", choices=["imgapi", "docker", "dsapi"]),
273 uuid=dict(),
274 ),
275 # This module relies largely on imgadm(8) to enforce idempotency, which does not
276 # provide a "noop" (or equivalent) mode to do a dry-run.
277 supports_check_mode=False,
278 )
279 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
280
281 imgadm = Imgadm(module)
282
283 uuid = module.params["uuid"]
284 source = module.params["source"]
285 state = module.params["state"]
286
287 result = {"state": state}
288
289 # Either manage sources or images.
290 if source:
291 result["source"] = source
292 imgadm.manage_sources()
293 else:
294 result["uuid"] = uuid
295
296 if state == "updated":
297 imgadm.update_images()
298 else:
299 # Make sure operate on a single image for the following actions
300 if (uuid == "*") and (state != "vacuumed"):
301 module.fail_json(msg='Can only specify uuid as "*" when updating image(s)')
302 imgadm.manage_images()
303
304 result["changed"] = imgadm.changed
305 module.exit_json(**result)
306
307
308 if __name__ == "__main__":
309 main()