Debian Codegraph @

ansible_collections/dellemc/enterprise_sonic/plugins/modules/sonic_image_management.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright 2025 Dell Inc. or its subsidiaries. All Rights Reserved.
4 # GNU General Public License v3.0+
5 # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 """
8 The module file for sonic_image_management
9 """
10
11 from __future__ import absolute_import, division, print_function
12 __metaclass__ = type
13
14 DOCUMENTATION = """
15 ---
16 module: sonic_image_management
17 version_added: '2.4.0'
18 short_description: Manage installation of Enterprise SONiC image, software patch and firmware updater
19 description:
20 - Manage installation of Enterprise SONiC image, software patch and firmware updater.
21 author: 'Arun Saravanan Balachandran (@ArunSaravananBalachandran), Aravind Mani (@aravindmani-1)'
22
23 options:
24 image:
25 description:
26 - Manage installation of Enterprise SONiC image.
27 type: dict
28 suboptions:
29 command:
30 description:
31 - Specifies the image manangement operation to be performed.
32 - C(install) - Install image specified by I(path).
33 - C(cancel) - Cancel image installation.
34 - C(remove) - Remove image specified by I(name).
35 - C(set-default) - Set the image specified by I(name) as default boot image.
36 - C(get-list) - Retrieve list of installed images.
37 - C(get-status) - Retrieve image installation status.
38 - C(gpg-key) - Install GPG key.
39 - C(verify) - Verify the image specified by I(path) using GPG or PKI method.
40 type: str
41 choices:
42 - install
43 - cancel
44 - remove
45 - set-default
46 - get-list
47 - get-status
48 - gpg-key
49 - verify
50 required: true
51 path:
52 description:
53 - When I(command=install) or I(command=verify) specifies the path of the image to be installed.
54 - Path can be a file in the device (file://filepath) or URL (http:// or https://).
55 type: str
56 name:
57 description:
58 - When I(command=remove) or I(command=set-default) specifies the name of the image.
59 - When I(command=remove), name can be specified as C(all) to remove all images which are not current or next.
60 type: str
61 keyserver:
62 version_added: '3.0.0'
63 description:
64 - GPG Key server URL.
65 - Required when I(command=gpg-key).
66 type: str
67 pubkeyid:
68 version_added: '3.0.0'
69 description:
70 - GPG Key ID to be installed.
71 - Required when I(command=gpg-key).
72 type: str
73 signaturefile:
74 version_added: '3.0.0'
75 description:
76 - GPG/PKI file to be verified.
77 - Required when I(command=verify).
78 type: str
79 pubkeyfilename:
80 version_added: '3.0.0'
81 description:
82 - Specifies the certificate for signature file.
83 - Required when I(command=verify) and I(verifymethod=pki).
84 type: str
85 verifymethod:
86 version_added: '3.0.0'
87 description:
88 - Image verification GPG or PKI method
89 - Required when I(command=verify).
90 type: str
91 choices:
92 - gpg
93 - pki
94 patch:
95 description:
96 - Manage installation of software patch.
97 type: dict
98 suboptions:
99 command:
100 description:
101 - Specifies the patch manangement operation to be performed.
102 - C(install) - Install patch specified by I(path).
103 - C(rollback) - Remove an installed patch specified by I(name).
104 - C(get-history) - Retrieve history of patches applied/rolled back.
105 - C(get-list) - Retrieve list of installed patches.
106 - C(get-status) - Retrieve patch installation/removal status.
107 type: str
108 choices:
109 - install
110 - rollback
111 - get-history
112 - get-list
113 - get-status
114 required: true
115 path:
116 description:
117 - When I(command=install), specifies the path of the patch to be installed.
118 - Path can be a file in the device (file://filepath) or URL (http:// or https://).
119 type: str
120 name:
121 description:
122 - When I(command=rollback), specifies the name of the patch.
123 type: str
124 firmware:
125 description:
126 - Manage installation of Firmware updater
127 type: dict
128 suboptions:
129 command:
130 description:
131 - Specifies the firmware updater manangement operation to be performed.
132 - C(install) - Stage firmware updater specified by I(path).
133 - C(cancel) - Cancel a pending firmware updater.
134 - C(get-list) - Retrieve details of pending firmware updater and result of installed firmware updater.
135 - C(get-status) - Retrieve firmware updater staging status.
136 type: str
137 choices:
138 - install
139 - cancel
140 - get-list
141 - get-status
142 required: true
143 path:
144 description:
145 - When I(command=install), specifies the path of the firmware updater to be staged.
146 - Path can be a file in the device (file://filepath) or URL (http:// or https://).
147 type: str
148 """
149
150 EXAMPLES = """
151
152 - name: Install Enterprise SONiC image
153 dellemc.enterprise_sonic.sonic_image_management:
154 image:
155 command: install
156 path: 'file://home/admin/sonic.bin'
157
158 - name: Get image installation status
159 dellemc.enterprise_sonic.sonic_image_management:
160 image:
161 command: get-status
162
163 - name: Get list of installed images
164 dellemc.enterprise_sonic.sonic_image_management:
165 image:
166 command: get-list
167
168 - name: Stage a firmware updater
169 dellemc.enterprise_sonic.sonic_image_management:
170 firmware:
171 command: install
172 path: 'file://home/admin/onie-update-full.bin'
173
174 - name: Install GPG Key for image verification
175 dellemc.enterprise_sonic.sonic_image_management:
176 image:
177 command: gpg-key
178 keyserver: 'hkp://keyserver.ubuntu.com:80'
179 pubkeyid: 'DAFWQGEW12345678'
180
181 - name: Verify Enterprise SONiC image
182 dellemc.enterprise_sonic.sonic_image_management:
183 image:
184 command: verify
185 path: 'home://sonic.bin'
186 verifymethod: 'gpg'
187 signaturefile: 'sign.gpg'
188 """
189
190 RETURN = """
191 status:
192 description: Status of the operation performed.
193 returned: when I(command) is not C(get-status), C(get-list) and C(get-history)
194 type: str
195 sample: SUCCESS
196 info:
197 description: Details returned by the specified get operation.
198 returned: when I(command=get-status) or I(command=get-list) or I(command=get-history)
199 type: dict
200 sample: >
201 {
202 "file-download-speed" : "106200",
203 "file-progress" : 100,
204 "file-size" : "1304997870",
205 "file-transfer-bytes" : "1304997870",
206 "install-end-time" : "1695714740",
207 "install-start-time" : "1695714698",
208 "install-status" : "INSTALL_STATE_SUCCESS",
209 "install-status-detail" : "Image install success",
210 "operation-status" : "GLOBAL_STATE_SUCCESS",
211 "transfer-end-time" : "1695714669",
212 "transfer-start-time" : "1695714657",
213 "transfer-status" : "TRANSFER_STATE_SUCCESS",
214 "transfer-status-detail" : "DOWNLOADING IMAGE"
215 }
216 """
217
218
219 from ansible.module_utils.basic import AnsibleModule
220 from ansible.module_utils.connection import ConnectionError
221 from ansible_collections.dellemc.enterprise_sonic.plugins.module_utils.network.sonic.sonic import (
222 to_request,
223 edit_config
224 )
225
226
227 def validate_and_retrieve_params(module, warnings):
228 """
229 Validates the module parameters
230 """
231 params = {}
232 for category in ('image', 'patch', 'firmware'):
233 if module.params.get(category) and module.params[category].get('command'):
234 if params.get('category') is None:
235 params['category'] = category
236 params.update(module.params[category])
237 else:
238 module.fail_json(msg="Only one image management operation can be performed at a time")
239
240 if module.check_mode and not params['command'].startswith('get-'):
241 module.fail_json(msg='Only get commands are supported while using check mode, but {0} was provided'.format(params['command']))
242
243 if params['command'] == 'install':
244 if not params.get('path'):
245 module.fail_json(msg="{0} -> path is required when {0} -> command = install".format(params['category']))
246 if params.get('name'):
247 warnings.append("{0} -> name is ignored when {0} -> command = install".format(params['category']))
248 elif params['command'] in ('remove', 'set-default', 'rollback'):
249 if not params.get('name'):
250 module.fail_json(msg="{0} -> name is required when {0} -> command = {1}".format(params['category'], params['command']))
251 if params.get('path'):
252 warnings.append("{0} -> path is ignored when {0} -> command = {1}".format(params['category'], params['command']))
253 elif params['command'] == 'gpg-key':
254 if not params.get('keyserver') or not params.get('pubkeyid'):
255 module.fail_json(msg="{0} -> keyserver URL and Key ID are required when {0} -> command = {1}".format(params['category'], params['command']))
256 elif params['command'] == 'verify':
257 if not params.get('verifymethod'):
258 module.fail_json(msg="{0} -> verifymethod is required when {0} -> command = verify".format(params['category']))
259 if params.get('verifymethod') == 'gpg':
260 if not params.get('path') or not params.get('signaturefile'):
261 module.fail_json(msg="{0} -> Image path and GPG signature are required when {0} -> command = {1}".format(params['category'], params['command']))
262 else:
263 if not params.get('path') or not params.get('signaturefile') or not params.get('pubkeyfilename'):
264 module.fail_json(
265 msg="{0} -> Image path, PKI signature and certificate are required when {0} -> command = {1}".format(params['category'], params['command']))
266 return params
267
268
269 def execute_command(module, params, result):
270 """
271 Executes the specified command and updates the result
272 """
273 command_map = {
274 'image': {
275 'install': {
276 'path': 'operations/openconfig-image-management:image-install',
277 'status': 'Check image -> command = get-status for image install progress'
278 },
279 'cancel': {
280 'path': 'operations/openconfig-image-management:image-install-cancel'
281 },
282 'remove': {
283 'path': 'operations/openconfig-image-management:image-remove'
284 },
285 'set-default': {
286 'path': 'operations/openconfig-image-management:image-default'
287 },
288 'get-status': {
289 'path': 'data/openconfig-image-management:image-management/install/state',
290 'response_key': 'openconfig-image-management:state'
291 },
292 'get-list': {
293 'path': 'data/openconfig-image-management:image-management',
294 'response_key': 'openconfig-image-management:image-management'
295 },
296 'gpg-key': {
297 'path': 'operations/openconfig-image-management:image-gpg-install'
298 },
299 'verify': {
300 'path': 'operations/openconfig-image-management:image-verify'
301 }
302 },
303 'patch': {
304 'install': {
305 'path': 'operations/openconfig-image-management:do-patch-install',
306 'status': 'Check patch -> command = get-status for patch install progress'
307 },
308 'rollback': {
309 'path': 'operations/openconfig-image-management:do-patch-rollback',
310 'status': 'Check patch -> command = get-status for patch rollback progress'
311 },
312 'get-history': {
313 'path': 'data/openconfig-image-management:patch-management/patch-history',
314 'response_key': 'openconfig-image-management:patch-history'
315 },
316 'get-status': {
317 'path': 'data/openconfig-image-management:patch-management/patch-install',
318 'response_key': 'openconfig-image-management:patch-install'
319 },
320 'get-list': {
321 'path': 'data/openconfig-image-management:patch-management/patch-list',
322 'response_key': 'openconfig-image-management:patch-list'
323 }
324 },
325 'firmware': {
326 'install': {
327 'path': 'operations/openconfig-image-management:do-fwpkg-install',
328 'status': 'Check firmware -> command = get-status for firmware package staging progress'
329 },
330 'cancel': {
331 'path': 'operations/openconfig-image-management:do-fwpkg-install-cancel'
332 },
333 'get-list': {
334 'path': 'data/openconfig-image-management:fwpkg-management',
335 'response_key': 'openconfig-image-management:fwpkg-management'
336 },
337 'get-status': {
338 'path': 'data/openconfig-image-management:fwpkg-management/fwpkg-install',
339 'response_key': 'openconfig-image-management:fwpkg-install'
340 }
341 }
342 }
343
344 path = command_map[params['category']][params['command']]['path']
345 if params['command'].startswith('get-'):
346 method = 'GET'
347 request = [{'path': path, 'method': method}]
348
349 try:
350 response = edit_config(module, to_request(module, request))
351 except ConnectionError as exc:
352 module.fail_json(msg=str(exc), code=exc.code)
353
354 info = {}
355 response = response[0][1].get(command_map[params['category']][params['command']]['response_key'])
356 if response:
357 if params['category'] == 'image':
358 if params['command'] == 'get-list':
359 if response.get('global') and response['global'].get('state'):
360 if response['global']['state'].get('current'):
361 info['current'] = response['global']['state']['current']
362 if response['global']['state'].get('next-boot'):
363 info['next'] = response['global']['state']['next-boot']
364 if response.get('images') and response['images'].get('image'):
365 info['available'] = []
366 for element in response['images']['image']:
367 if element.get('image-name'):
368 info['available'].append(element['image-name'])
369
370 elif params['command'] == 'get-status':
371 keys = list(response.keys())
372 info.update(response)
373 install_status = info.get('install-status', 'IDLE')
374 transfer_status = info.get('transfer-status', 'IDLE')
375 for key in keys:
376 if ((key.startswith(('file', 'transfer')) and 'IDLE' in transfer_status)
377 or (key.startswith('install') and 'IDLE' in install_status)):
378 del info[key]
379
380 elif params['category'] == 'patch':
381 if params['command'] in ('get-history', 'get-list'):
382 info_key = params['command'].split('-')[1]
383 if response.get('patch'):
384 patches = sorted(response['patch'], key=lambda item: (item['patch-time']), reverse=True)
385 info[info_key] = []
386 for patch in patches:
387 if patch.get('state'):
388 info[info_key].append(patch['state'])
389
390 elif params['command'] == 'get-status':
391 install_state = response.get('install-state', {})
392 download_state = response.get('download-state', {})
393 if install_state.get('trigger') == 'install' and 'IDLE' not in download_state.get('transfer-status', 'IDLE'):
394 info.update(download_state)
395
396 for oper_type in ('install', 'rollback', 'recovery'):
397 if 'IDLE' not in install_state.get('{0}-status'.format(oper_type), 'IDLE'):
398 for key in install_state.keys():
399 if key.startswith(oper_type):
400 info[key] = install_state[key]
401
402 elif params['category'] == 'firmware':
403 if params['command'] == 'get-list':
404 for info_key in ('pending', 'result'):
405 key = 'fwpkg-{0}'.format(info_key)
406 if response.get(key) and response[key].get('fwpkg'):
407 info[info_key] = []
408 for entry in response[key]['fwpkg']:
409 info[info_key].append(entry['state'])
410
411 elif params['command'] == 'get-status':
412 if response.get('download-state') and 'IDLE' not in response['download-state'].get('transfer-status', 'IDLE'):
413 info.update(response['download-state'])
414 if response.get('stage-state') and 'IDLE' not in response['stage-state'].get('stage-status', 'IDLE'):
415 info.update(response['stage-state'])
416
417 result['info'] = info
418
419 else:
420 method = 'POST'
421 payload = {'openconfig-image-management:input': {}}
422 if params['category'] == 'image':
423 if params['command'] == 'install':
424 payload['openconfig-image-management:input'] = {'image-name': params['path']}
425 elif (params['command'] == 'remove' and params['name'] != 'all') or params['command'] == 'set-default':
426 payload['openconfig-image-management:input'] = {'image-name': params['name']}
427 elif params['command'] == 'gpg-key':
428 payload['openconfig-image-management:input'] = {"key-server": params['keyserver'], "key-id": params['pubkeyid']}
429 elif params['command'] == 'verify':
430 if params['verifymethod'] == 'gpg':
431 payload['openconfig-image-management:input'] = {
432 "image-name": params['path'], "verify-method": params['verifymethod'], "sigfilename": params['signaturefile']
433 }
434 else:
435 payload['openconfig-image-management:input'] = {
436 "image-name": params['path'], "verify-method": params['verifymethod'],
437 "sigfilename": params['signaturefile'], "keyfilename": params['pubkeyfilename']
438 }
439 elif params['category'] == 'patch':
440 if params['command'] == 'install':
441 payload['openconfig-image-management:input'] = {'patch-name': params['path'], 'skip-image-check': ''}
442 elif params['command'] == 'rollback':
443 payload['openconfig-image-management:input'] = {'patch-name': params['name']}
444 elif params['category'] == 'firmware':
445 if params['command'] == 'install':
446 payload['openconfig-image-management:input'] = {'fwpkg-name': params['path']}
447
448 request = [{'path': path, 'method': method, 'data': payload}]
449 try:
450 response = edit_config(module, to_request(module, request))
451 except ConnectionError as exc:
452 module.fail_json(msg=str(exc), code=exc.code)
453
454 status = ''
455 response = response[0][1].get('openconfig-image-management:output')
456 if response:
457 if response['status'] != 0:
458 status = response['status-detail']
459 else:
460 status = command_map[params['category']][params['command']].get('status', response['status-detail'])
461
462 result['status'] = status
463
464
465 def main():
466 """
467 Main entry point for module execution
468 """
469 argument_spec = {
470 'image': {
471 'type': 'dict',
472 'options': {
473 'command': {
474 'type': 'str',
475 'required': True,
476 'choices': ['install', 'cancel', 'remove', 'set-default', 'get-list', 'get-status', 'gpg-key', 'verify']
477 },
478 'name': {'type': 'str'},
479 'path': {'type': 'str'},
480 'keyserver': {'type': 'str'},
481 'pubkeyid': {'type': 'str'},
482 'pubkeyfilename': {'type': 'str'},
483 'signaturefile': {'type': 'str'},
484 'verifymethod': {
485 'type': 'str',
486 'choices': ['gpg', 'pki']
487 }
488 }
489 },
490 'patch': {
491 'type': 'dict',
492 'options': {
493 'command': {
494 'type': 'str',
495 'required': True,
496 'choices': ['install', 'rollback', 'get-history', 'get-list', 'get-status']
497 },
498 'name': {'type': 'str'},
499 'path': {'type': 'str'}
500 }
501 },
502 'firmware': {
503 'type': 'dict',
504 'options': {
505 'command': {
506 'type': 'str',
507 'required': True,
508 'choices': ['install', 'cancel', 'get-list', 'get-status']
509 },
510 'path': {'type': 'str'}
511 }
512 }
513 }
514
515 module = AnsibleModule(argument_spec=argument_spec,
516 supports_check_mode=True)
517 warnings = []
518 result = {'changed': False, 'warnings': warnings}
519
520 params = validate_and_retrieve_params(module, warnings)
521 execute_command(module, params, result)
522
523 module.exit_json(**result)
524
525
526 if __name__ == '__main__':
527 main()