Debian Codegraph @

ansible_collections/netapp/ontap/plugins/modules/na_ontap_firmware_upgrade.py

raw
1 #!/usr/bin/python
2
3 # (c) 2019-2025, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 from __future__ import absolute_import, division, print_function
6 __metaclass__ = type
7
8 DOCUMENTATION = '''
9 author: NetApp Ansible Team (@carchi8py) <[email protected]>
10 description:
11 - Update ONTAP service-prosessor firmware
12 - The recommend procedure is to
13 1. download the firmware package from the NetApp Support site
14 2. copy the package to a web server
15 3. download the package from the web server using this module
16 - Once a disk qualification, disk, shelf, or ACP firmware package is downloaded, ONTAP will automatically update the related resources in background.
17 - It may take some time to complete.
18 - For service processor, the update requires a node reboot to take effect.
19 extends_documentation_fragment:
20 - netapp.ontap.netapp.na_ontap
21 module: na_ontap_firmware_upgrade
22 options:
23 state:
24 description:
25 - Whether the specified ONTAP firmware should be upgraded or not.
26 default: present
27 type: str
28 node:
29 description:
30 - Node on which the device is located.
31 - With REST, this parameter is ignored when package_url is provided but it is used with ZAPI.
32 not required if package_url is present and force_disruptive_update is False.
33 - With REST, if this option is not given, the firmware will be downloaded on all nodes in the cluster
34 and the resources will be updated in background on all nodes, except for service processor.
35 - with ZAPI, this parameter is used to specify the target node for firmware download.
36 - with ZAPI, if not specified firmware will be downloaded on all nodes in the cluster (using '*').
37 - For service processor, the upgrade will happen automatically when each node is rebooted.
38 type: str
39 clear_logs:
40 description:
41 - Clear logs on the device after update. Default value is true.
42 - Not used if force_disruptive_update is False.
43 - Not supported with REST when set to false.
44 type: bool
45 default: true
46 package:
47 description:
48 - Name of the package file containing the firmware to be installed. Not required when -baseline is true.
49 - Not used if force_disruptive_update is False.
50 - Not supported with REST.
51 type: str
52 package_url:
53 description:
54 - URL of the package file containing the firmware to be downloaded.
55 - Once the package file is downloaded to a node, the firmware update will happen automatically in background.
56 - For SP, the upgrade will happen automatically when a node is rebooted.
57 - For SP, the upgrade will happen automatically if autoupdate is enabled (which is the recommended setting).
58 version_added: "20.5.0"
59 type: str
60 force_disruptive_update:
61 description:
62 - If set to C(False), and URL is given, the upgrade is non disruptive. If URL is not given, no operation is performed.
63 - Do not set this to C(True), unless directed by NetApp Tech Support.
64 - It will force an update even if the resource is not ready for it, and can be disruptive.
65 - Not supported with REST when set to true.
66 type: bool
67 version_added: "20.5.0"
68 default: false
69 shelf_module_fw:
70 description:
71 - Shelf module firmware to be updated to.
72 - Not used if force_disruptive_update is False (ONTAP will automatically select the firmware)
73 - Not supported with REST.
74 type: str
75 disk_fw:
76 description:
77 - disk firmware to be updated to.
78 - Not used if force_disruptive_update is False (ONTAP will automatically select the firmware)
79 - Not supported with REST.
80 type: str
81 update_type:
82 description:
83 - Type of firmware update to be performed. Options include serial_full, serial_differential, network_full.
84 - Not used if force_disruptive_update is False (ONTAP will automatically select the firmware)
85 - Not supported with REST.
86 type: str
87 install_baseline_image:
88 description:
89 - Install the version packaged with ONTAP if this parameter is set to true. Otherwise, package must be used to specify the package to install.
90 - Not used if force_disruptive_update is False (ONTAP will automatically select the firmware)
91 - Not supported with REST when set to true.
92 type: bool
93 default: false
94 firmware_type:
95 description:
96 - Type of firmware to be upgraded. Options include shelf, ACP, service-processor, and disk.
97 - For shelf firmware upgrade the operation is asynchronous, and therefore returns no errors that might occur during the download process.
98 - Shelf firmware upgrade is idempotent if shelf_module_fw is provided .
99 - disk firmware upgrade is idempotent if disk_fw is provided .
100 - With check mode, SP, ACP, disk, and shelf firmware upgrade is not idempotent.
101 - This operation will only update firmware on shelves/disk that do not have the latest firmware-revision.
102 - For normal operations, choose one of storage or service-processor.
103 - Type storage includes acp, shelf and disk and ONTAP will automatically determine what to do.
104 - With REST, the module does not validate that the package matches the firmware type. ONTAP determines the type automatically.
105 - With REST, C(storage) downloads any firmware, including service-processor firmware.
106 - With REST, C(service-processor) unlocks SP reboot options.
107 choices: ['storage', 'service-processor', 'shelf', 'acp', 'disk']
108 type: str
109 default: storage
110 fail_on_502_error:
111 description:
112 - The firmware download may take time if the web server is slow and if there are many nodes in the cluster.
113 - ONTAP will break the ZAPI connection after 5 minutes with a 502 Bad Gateway error, even though the download
114 is still happening.
115 - By default, this module ignores this error and assumes the download is progressing as ONTAP does not
116 provide a way to check the status.
117 - When setting this option to true, the module will report 502 as an error.
118 - Not supported with REST when set to true.
119 type: bool
120 default: false
121 version_added: "20.6.0"
122 rename_package:
123 description:
124 - Rename the package.
125 - Only available if 'firmware_type' is 'service-processor'.
126 - Not supported with REST.
127 type: str
128 version_added: "20.7.0"
129 replace_package:
130 description:
131 - Replace the local package.
132 - Only available if 'firmware_type' is 'service-processor'.
133 - Not supported with REST when set to false.
134 type: bool
135 version_added: "20.7.0"
136 reboot_sp:
137 description:
138 - Reboot service processor before downloading package.
139 - Only available if 'firmware_type' is 'service-processor'.
140 - Defaults to True if not set when 'firmware_type' is 'service-processor'.
141 - Set this explictly to true to avoid a warning, and to false to not reboot the SP.
142 - Rebooting the SP before download is strongly recommended.
143 type: bool
144 version_added: "20.7.0"
145 reboot_sp_after_download:
146 description:
147 - Reboot service processor after downloading package.
148 - Only available if 'firmware_type' is 'service-processor'.
149 type: bool
150 version_added: "21.15.0"
151 server_username:
152 description:
153 - username to authenticate with the firmware package server.
154 - Ignored with ZAPI.
155 type: str
156 version_added: "21.15.0"
157 server_password:
158 description:
159 - password to authenticate with the firmware package server.
160 - Ignored with ZAPI.
161 type: str
162 version_added: "21.15.0"
163 short_description: NetApp ONTAP firmware upgrade for SP, shelf, ACP, and disk.
164 version_added: 2.9.0
165 '''
166
167 EXAMPLES = """
168 - name: Firmware upgrade using REST - node parameter ignored when using REST with package_url
169 netapp.ontap.na_ontap_firmware_upgrade:
170 state: present
171 package_url: "{{ web_link }}"
172 node: node1 # This will be ignored when using REST with package_url
173 hostname: "{{ netapp_hostname }}"
174 username: "{{ netapp_username }}"
175 password: "{{ netapp_password }}"
176
177 - name: Firmware upgrade using ZAPI - node parameter is used to target specific node
178 netapp.ontap.na_ontap_firmware_upgrade:
179 state: present
180 package_url: "{{ web_link }}"
181 node: node1 # This will be used to target specific node with ZAPI
182 use_rest: never
183 hostname: "{{ netapp_hostname }}"
184 username: "{{ netapp_username }}"
185 password: "{{ netapp_password }}"
186
187 - name: Firmware upgrade, confirm successful download
188 netapp.ontap.na_ontap_firmware_upgrade:
189 state: present
190 package_url: "{{ web_link }}"
191 hostname: "{{ netapp_hostname }}"
192 username: "{{ netapp_username }}"
193 password: "{{ netapp_password }}"
194 fail_on_502_error: true
195
196 - name: SP firmware upgrade
197 netapp.ontap.na_ontap_firmware_upgrade:
198 state: present
199 node: vsim1
200 package: "{{ file name }}"
201 package_url: "{{ web_link }}"
202 clear_logs: true
203 install_baseline_image: false
204 update_type: serial_full
205 force_disruptive_update: false
206 firmware_type: service-processor
207 hostname: "{{ netapp_hostname }}"
208 username: "{{ netapp_username }}"
209 password: "{{ netapp_password }}"
210
211 - name: SP firmware download replace package
212 netapp.ontap.na_ontap_firmware_upgrade:
213 state: present
214 node: vsim1
215 package_url: "{{ web_link }}"
216 firmware_type: service-processor
217 replace_package: true
218 reboot_sp: true
219 hostname: "{{ netapp_hostname }}"
220 username: "{{ netapp_username }}"
221 password: "{{ netapp_password }}"
222 https: true
223 validate_certs: false
224
225 - name: SP firmware download rename package
226 netapp.ontap.na_ontap_firmware_upgrade:
227 state: present
228 node: vsim1
229 package_url: "{{ web_link }}"
230 firmware_type: service-processor
231 rename_package: SP_FW.zip
232 hostname: "{{ netapp_hostname }}"
233 username: "{{ netapp_username }}"
234 password: "{{ netapp_password }}"
235 https: true
236 validate_certs: false
237
238 - name: ACP firmware download and upgrade
239 netapp.ontap.na_ontap_firmware_upgrade:
240 state: present
241 node: vsim1
242 firmware_type: acp
243 package_url: "{{ web_link }}"
244 hostname: "{{ netapp_hostname }}"
245 username: "{{ netapp_username }}"
246 password: "{{ netapp_password }}"
247
248 - name: Shelf firmware upgrade
249 netapp.ontap.na_ontap_firmware_upgrade:
250 state: present
251 firmware_type: shelf
252 package_url: "{{ web_link }}"
253 hostname: "{{ netapp_hostname }}"
254 username: "{{ netapp_username }}"
255 password: "{{ netapp_password }}"
256
257 - name: Disk firmware upgrade
258 netapp.ontap.na_ontap_firmware_upgrade:
259 state: present
260 firmware_type: disk
261 package_url: "{{ web_link }}"
262 hostname: "{{ netapp_hostname }}"
263 username: "{{ netapp_username }}"
264 password: "{{ netapp_password }}"
265
266 - name: SP firmware upgrade with reboots (REST)
267 netapp.ontap.na_ontap_firmware_upgrade:
268 state: present
269 package_url: "{{ web_link }}"
270 firmware_type: service-processor
271 reboot_sp: true
272 reboot_sp_after_download: true
273 hostname: "{{ netapp_hostname }}"
274 username: "{{ netapp_username }}"
275 password: "{{ netapp_password }}"
276 """
277
278 RETURN = """
279 msg:
280 description: Returns additional information in case of success.
281 returned: always
282 type: str
283 """
284
285 import time
286 import traceback
287 from ansible.module_utils.basic import AnsibleModule
288 from ansible.module_utils._text import to_native
289 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
290 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
291 from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI
292 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
293
294
295 MSGS = dict(
296 no_action='No action taken.',
297 dl_completed='Firmware download completed.',
298 dl_completed_slowly='Firmware download completed, slowly.',
299 dl_in_progress='Firmware download still in progress.'
300 )
301
302
303 class NetAppONTAPFirmwareUpgrade:
304 """
305 Class with ONTAP firmware upgrade methods
306 """
307
308 def __init__(self):
309 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
310 self.argument_spec.update(dict(
311 state=dict(required=False, type='str', default='present'),
312 node=dict(required=False, type='str'),
313 firmware_type=dict(type='str', choices=['storage', 'service-processor', 'shelf', 'acp', 'disk'], default='storage'),
314 clear_logs=dict(required=False, type='bool', default=True),
315 package=dict(required=False, type='str'),
316 install_baseline_image=dict(required=False, type='bool', default=False),
317 update_type=dict(required=False, type='str'),
318 shelf_module_fw=dict(required=False, type='str'),
319 disk_fw=dict(required=False, type='str'),
320 package_url=dict(required=False, type='str'),
321 force_disruptive_update=dict(required=False, type='bool', default=False),
322 fail_on_502_error=dict(required=False, type='bool', default=False),
323 rename_package=dict(required=False, type='str'),
324 replace_package=dict(required=False, type='bool'),
325 reboot_sp=dict(required=False, type='bool'),
326 reboot_sp_after_download=dict(required=False, type='bool'),
327 server_username=dict(required=False, type='str'),
328 server_password=dict(required=False, type='str', no_log=True),
329 ))
330
331 self.module = AnsibleModule(
332 argument_spec=self.argument_spec,
333 required_if=[
334 ('firmware_type', 'acp', ['node']),
335 ('firmware_type', 'disk', ['node']),
336 ('firmware_type', 'service-processor', ['node']),
337 ('force_disruptive_update', True, ['firmware_type']),
338 ('reboot_sp', True, ['node']),
339 ('reboot_sp_after_download', True, ['node']),
340 ],
341 required_together=[['server_username', 'server_password']],
342 supports_check_mode=True
343 )
344
345 self.na_helper = NetAppModule()
346 self.parameters = self.na_helper.set_parameters(self.module.params)
347 self._node_uuid = None # to cache calls to get_node_uuid
348
349 self.rest_api = OntapRestAPI(self.module)
350 unsupported_rest_properties = ['package', 'update_type', 'rename_package', 'shelf_module_fw', 'disk_fw']
351 # only accept default value for these 5 options (2 True and 3 False)
352 # accept the default value (for replace_package, this is implicit for REST) but switch to ZAPI or error out if set to False
353 unsupported_rest_properties.extend(option for option in ('clear_logs', 'replace_package') if self.parameters.get(option) is False)
354 # accept the default value of False, but switch to ZAPI or error out if set to True
355 unsupported_rest_properties.extend(option for option in ('install_baseline_image', 'force_disruptive_update', 'fail_on_502_error')
356 if self.parameters[option])
357
358 self.use_rest = self.rest_api.is_rest_supported_properties(self.parameters, unsupported_rest_properties)
359
360 if self.parameters.get('firmware_type') == 'storage' and self.parameters.get('force_disruptive_update'):
361 self.module.fail_json(msg='Do not set force_disruptive_update to True, unless directed by NetApp Tech Support')
362
363 for option in ('reboot_sp', 'reboot_sp_after_download'):
364 if self.parameters.get('firmware_type') != 'service-processor' and self.parameters.get(option):
365 self.module.warn('%s is ignored when firmware_type is not set to service-processor' % option)
366 if self.parameters.get('firmware_type') == 'service-processor' and self.parameters.get('reboot_sp') is None:
367 self.module.warn('Forcing a reboot of SP before download - set reboot_sp: true to disable this warning.')
368 self.parameters['reboot_sp'] = True
369 if not self.use_rest and self.parameters.get('firmware_type') == 'service-processor':
370 msg = 'With ZAPI and firmware_type set to service-processor: '
371 if 'node' not in self.parameters:
372 self.module.fail_json(msg=msg + 'parameter node should be present.')
373 if self.parameters.get('install_baseline_image') and self.parameters.get('package') is not None:
374 self.module.fail_json(msg=msg + 'do not specify both package and install_baseline_image: true.')
375 if self.parameters.get('force_disruptive_update') \
376 and self.parameters.get('install_baseline_image') is False \
377 and self.parameters.get('package') is None:
378 self.module.fail_json(msg=msg + 'specify at least one of package or install_baseline_image: true.')
379
380 if not self.use_rest:
381 if not netapp_utils.has_netapp_lib():
382 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
383 else:
384 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, wrap_zapi=True)
385
386 def firmware_image_get_iter(self):
387 """
388 Compose NaElement object to query current firmware version
389 :return: NaElement object for firmware_image_get_iter with query
390 """
391 firmware_image_get = netapp_utils.zapi.NaElement('service-processor-get-iter')
392 query = netapp_utils.zapi.NaElement('query')
393 firmware_image_info = netapp_utils.zapi.NaElement('service-processor-info')
394 firmware_image_info.add_new_child('node', self.parameters['node'])
395 query.add_child_elem(firmware_image_info)
396 firmware_image_get.add_child_elem(query)
397 return firmware_image_get
398
399 def firmware_image_get(self, node_name):
400 """
401 Get current firmware image info
402 :return: True if query successful, else return None
403 """
404 firmware_image_get_iter = self.firmware_image_get_iter()
405 try:
406 result = self.server.invoke_successfully(firmware_image_get_iter, enable_tunneling=True)
407 except netapp_utils.zapi.NaApiError as error:
408 self.module.fail_json(msg='Error fetching firmware image details: %s: %s'
409 % (self.parameters['node'], to_native(error)),
410 exception=traceback.format_exc())
411 # return firmware image details
412 if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) > 0:
413 sp_info = result.get_child_by_name('attributes-list').get_child_by_name('service-processor-info')
414 return sp_info.get_child_content('firmware-version')
415 return None
416
417 def acp_firmware_update_required(self):
418 """
419 where acp firmware upgrade is required
420 :return: True is firmware upgrade is required else return None
421 """
422 acp_firmware_get_iter = netapp_utils.zapi.NaElement('storage-shelf-acp-module-get-iter')
423 query = netapp_utils.zapi.NaElement('query')
424 acp_info = netapp_utils.zapi.NaElement('storage-shelf-acp-module')
425 query.add_child_elem(acp_info)
426 acp_firmware_get_iter.add_child_elem(query)
427 try:
428 result = self.server.invoke_successfully(acp_firmware_get_iter, enable_tunneling=True)
429 except netapp_utils.zapi.NaApiError as error:
430 self.module.fail_json(msg='Error fetching acp firmware details details: %s'
431 % (to_native(error)), exception=traceback.format_exc())
432 acp_module_info = self.na_helper.safe_get(result, ['attributes-list', 'storage-shelf-acp-module'])
433 if acp_module_info:
434 state = acp_module_info.get_child_content('state')
435 if state == 'firmware_update_required':
436 # acp firmware version upgrade required
437 return True
438 return False
439
440 def sp_firmware_image_update_progress_get(self, node_name):
441 """
442 Get current firmware image update progress info
443 :return: Dictionary of firmware image update progress if query successful, else return None
444 """
445 firmware_update_progress_get = netapp_utils.zapi.NaElement('service-processor-image-update-progress-get')
446 firmware_update_progress_get.add_new_child('node', self.parameters['node'])
447
448 firmware_update_progress_info = {}
449 try:
450 result = self.server.invoke_successfully(firmware_update_progress_get, enable_tunneling=True)
451 except netapp_utils.zapi.NaApiError as error:
452 self.module.fail_json(msg='Error fetching firmware image upgrade progress details: %s'
453 % (to_native(error)), exception=traceback.format_exc())
454 # return firmware image update progress details
455 if result.get_child_by_name('attributes').get_child_by_name('service-processor-image-update-progress-info'):
456 update_progress_info = result.get_child_by_name('attributes').get_child_by_name('service-processor-image-update-progress-info')
457 firmware_update_progress_info['is-in-progress'] = update_progress_info.get_child_content('is-in-progress')
458 firmware_update_progress_info['node'] = update_progress_info.get_child_content('node')
459 return firmware_update_progress_info
460
461 def shelf_firmware_info_get(self):
462 """
463 Get the current firmware of shelf module
464 :return:dict with module id and firmware info
465 """
466 shelf_id_fw_info = {}
467 shelf_firmware_info_get = netapp_utils.zapi.NaElement('storage-shelf-info-get-iter')
468 desired_attributes = netapp_utils.zapi.NaElement('desired-attributes')
469 storage_shelf_info = netapp_utils.zapi.NaElement('storage-shelf-info')
470 shelf_module = netapp_utils.zapi.NaElement('shelf-modules')
471 shelf_module_info = netapp_utils.zapi.NaElement('storage-shelf-module-info')
472 shelf_module.add_child_elem(shelf_module_info)
473 storage_shelf_info.add_child_elem(shelf_module)
474 desired_attributes.add_child_elem(storage_shelf_info)
475 shelf_firmware_info_get.add_child_elem(desired_attributes)
476
477 try:
478 result = self.server.invoke_successfully(shelf_firmware_info_get, enable_tunneling=True)
479 except netapp_utils.zapi.NaApiError as error:
480 self.module.fail_json(msg='Error fetching shelf module firmware details: %s'
481 % (to_native(error)), exception=traceback.format_exc())
482 if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) > 0:
483 shelf_info = result.get_child_by_name('attributes-list').get_child_by_name('storage-shelf-info')
484 if (shelf_info.get_child_by_name('shelf-modules') and
485 shelf_info.get_child_by_name('shelf-modules').get_child_by_name('storage-shelf-module-info')):
486 shelves = shelf_info['shelf-modules'].get_children()
487 for shelf in shelves:
488 shelf_id_fw_info[shelf.get_child_content('module-id')] = shelf.get_child_content('module-fw-revision')
489 return shelf_id_fw_info
490
491 def disk_firmware_info_get(self):
492 """
493 Get the current firmware of disks module
494 :return:
495 """
496 disk_id_fw_info = {}
497 disk_firmware_info_get = netapp_utils.zapi.NaElement('storage-disk-get-iter')
498 desired_attributes = netapp_utils.zapi.NaElement('desired-attributes')
499 storage_disk_info = netapp_utils.zapi.NaElement('storage-disk-info')
500 disk_inv = netapp_utils.zapi.NaElement('disk-inventory-info')
501 storage_disk_info.add_child_elem(disk_inv)
502 desired_attributes.add_child_elem(storage_disk_info)
503 disk_firmware_info_get.add_child_elem(desired_attributes)
504 try:
505 result = self.server.invoke_successfully(disk_firmware_info_get, enable_tunneling=True)
506 except netapp_utils.zapi.NaApiError as error:
507 self.module.fail_json(msg='Error fetching disk module firmware details: %s'
508 % (to_native(error)), exception=traceback.format_exc())
509 if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) > 0:
510 disk_info = result.get_child_by_name('attributes-list')
511 disks = disk_info.get_children()
512 for disk in disks:
513 disk_id_fw_info[disk.get_child_content('disk-uid')] = disk.get_child_by_name('disk-inventory-info').get_child_content('firmware-revision')
514 return disk_id_fw_info
515
516 def disk_firmware_update_required(self):
517 """
518 Check weather disk firmware upgrade is required or not
519 :return: True if the firmware upgrade is required
520 """
521 disk_firmware_info = self.disk_firmware_info_get()
522 return any(
523 disk_firmware_info[disk] != self.parameters['disk_fw']
524 for disk in disk_firmware_info
525 )
526
527 def shelf_firmware_update_required(self):
528 """
529 Check weather shelf firmware upgrade is required or not
530 :return: True if the firmware upgrade is required
531 """
532 shelf_firmware_info = self.shelf_firmware_info_get()
533 return any(
534 shelf_firmware_info[module] != self.parameters['shelf_module_fw']
535 for module in shelf_firmware_info
536 )
537
538 def sp_firmware_image_update(self):
539 """
540 Update current firmware image
541 """
542 firmware_update_info = netapp_utils.zapi.NaElement('service-processor-image-update')
543 if self.parameters.get('package') is not None:
544 firmware_update_info.add_new_child('package', self.parameters['package'])
545 if self.parameters.get('clear_logs') is not None:
546 firmware_update_info.add_new_child('clear-logs', str(self.parameters['clear_logs']))
547 if self.parameters.get('install_baseline_image') is not None:
548 firmware_update_info.add_new_child('install-baseline-image', str(self.parameters['install_baseline_image']))
549 firmware_update_info.add_new_child('node', self.parameters['node'])
550 firmware_update_info.add_new_child('update-type', self.parameters['update_type'])
551
552 try:
553 self.server.invoke_successfully(firmware_update_info, enable_tunneling=True)
554 except netapp_utils.zapi.NaApiError as error:
555 # Current firmware version matches the version to be installed
556 if to_native(error.code) == '13001' and (error.message.startswith('Service Processor update skipped')):
557 return False
558 self.module.fail_json(msg='Error updating firmware image for %s: %s'
559 % (self.parameters['node'], to_native(error)),
560 exception=traceback.format_exc())
561 return True
562
563 def shelf_firmware_upgrade(self):
564 """
565 Upgrade shelf firmware image
566 """
567 shelf_firmware_update_info = netapp_utils.zapi.NaElement('storage-shelf-firmware-update')
568 try:
569 self.server.invoke_successfully(shelf_firmware_update_info, enable_tunneling=True)
570 return True
571 except netapp_utils.zapi.NaApiError as error:
572 self.module.fail_json(msg='Error updating shelf firmware image : %s'
573 % (to_native(error)), exception=traceback.format_exc())
574
575 def acp_firmware_upgrade(self):
576
577 """
578 Upgrade shelf firmware image
579 """
580 acp_firmware_update_info = netapp_utils.zapi.NaElement('storage-shelf-acp-firmware-update')
581 acp_firmware_update_info.add_new_child('node-name', self.parameters['node'])
582 try:
583 self.server.invoke_successfully(acp_firmware_update_info, enable_tunneling=True)
584 except netapp_utils.zapi.NaApiError as error:
585 self.module.fail_json(msg='Error updating acp firmware image : %s'
586 % (to_native(error)), exception=traceback.format_exc())
587
588 def disk_firmware_upgrade(self):
589
590 """
591 Upgrade disk firmware
592 """
593 disk_firmware_update_info = netapp_utils.zapi.NaElement('disk-update-disk-fw')
594 disk_firmware_update_info.add_new_child('node-name', self.parameters['node'])
595 try:
596 self.server.invoke_successfully(disk_firmware_update_info, enable_tunneling=True)
597 except netapp_utils.zapi.NaApiError as error:
598 self.module.fail_json(msg='Error updating disk firmware image : %s'
599 % (to_native(error)), exception=traceback.format_exc())
600 return True
601
602 def download_firmware(self):
603 if self.use_rest:
604 return self.download_software_rest()
605
606 ''' calls the system-cli ZAPI as there is no ZAPI for this feature '''
607 msg = MSGS['dl_completed']
608 command = ['storage', 'firmware', 'download', '-node', self.parameters['node'] if self.parameters.get('node') else '*',
609 '-package-url', self.parameters['package_url']]
610 command_obj = netapp_utils.zapi.NaElement("system-cli")
611
612 args_obj = netapp_utils.zapi.NaElement("args")
613 for arg in command:
614 args_obj.add_new_child('arg', arg)
615 command_obj.add_child_elem(args_obj)
616 command_obj.add_new_child('priv', 'advanced')
617
618 output = None
619 try:
620 output = self.server.invoke_successfully(command_obj, True)
621
622 except netapp_utils.zapi.NaApiError as error:
623 # with netapp_lib, error.code may be a number or a string
624 try:
625 err_num = int(error.code)
626 except ValueError:
627 err_num = -1
628 if err_num == 60: # API did not finish on time
629 # even if the ZAPI reports a timeout error, it does it after the command completed
630 msg = MSGS['dl_completed_slowly']
631 elif err_num == 502 and not self.parameters['fail_on_502_error']: # Bad Gateway
632 # ONTAP proxy breaks the connection after 5 minutes, we can assume the download is progressing slowly
633 msg = MSGS['dl_in_progress']
634 else:
635 self.module.fail_json(msg='Error running command %s: %s' % (command, to_native(error)),
636 exception=traceback.format_exc())
637 except netapp_utils.zapi.etree.XMLSyntaxError as error:
638 self.module.fail_json(msg='Error decoding output from command %s: %s' % (command, to_native(error)),
639 exception=traceback.format_exc())
640
641 if output is not None:
642 # command completed, check for success
643 status = output.get_attr('status')
644 cli_output = output.get_child_content('cli-output')
645 if status is None or status != 'passed' or cli_output is None or cli_output == "":
646 if status is None:
647 extra_info = "'status' attribute missing"
648 elif status != 'passed':
649 extra_info = "check 'status' value"
650 else:
651 extra_info = 'check console permissions'
652 self.module.fail_json(msg='unable to download package from %s: %s. Received: %s' %
653 (self.parameters['package_url'], extra_info, output.to_string()))
654
655 if cli_output is not None:
656 if cli_output.startswith('Error:') or \
657 'Failed to download package from' in cli_output:
658 self.module.fail_json(msg='failed to download package from %s: %s' % (self.parameters['package_url'], cli_output))
659 msg += " Extra info: %s" % cli_output
660
661 return msg
662
663 def download_sp_image(self):
664 fetch_package = netapp_utils.zapi.NaElement('system-image-fetch-package')
665 fetch_package.add_new_child('node', self.parameters['node'])
666 fetch_package.add_new_child('package', self.parameters['package_url'])
667 if self.parameters.get('rename_package'):
668 fetch_package.add_new_child('rename-package', self.parameters['rename_package'])
669 if self.parameters.get('replace_package'):
670 fetch_package.add_new_child('replace-package', str(self.parameters['replace_package']))
671 try:
672 self.server.invoke_successfully(fetch_package, enable_tunneling=True)
673 except netapp_utils.zapi.NaApiError as error:
674 self.module.fail_json(msg='Error fetching system image package from %s: %s'
675 % (self.parameters['package_url'], to_native(error)),
676 exception=traceback.format_exc())
677
678 def download_sp_image_progress(self):
679 progress = netapp_utils.zapi.NaElement('system-image-update-progress-get')
680 progress.add_new_child('node', self.parameters['node'])
681 progress_info = {}
682 try:
683 result = self.server.invoke_successfully(progress, enable_tunneling=True)
684 except netapp_utils.zapi.NaApiError as error:
685 self.module.fail_json(msg='Error fetching system image package download progress: %s'
686 % (to_native(error)), exception=traceback.format_exc())
687 if result.get_child_by_name('phase'):
688 progress_info['phase'] = result.get_child_content('phase')
689 else:
690 progress_info['phase'] = None
691 if result.get_child_by_name('exit-message'):
692 progress_info['exit_message'] = result.get_child_content('exit-message')
693 else:
694 progress_info['exit_message'] = None
695 if result.get_child_by_name('exit-status'):
696 progress_info['exit_status'] = result.get_child_content('exit-status')
697 else:
698 progress_info['exit_status'] = None
699 if result.get_child_by_name('last-message'):
700 progress_info['last_message'] = result.get_child_content('last-message')
701 else:
702 progress_info['last_message'] = None
703 if result.get_child_by_name('run-status'):
704 progress_info['run_status'] = result.get_child_content('run-status')
705 else:
706 progress_info['run_status'] = None
707 return progress_info
708
709 def reboot_sp(self):
710 if self.use_rest:
711 return self.reboot_sp_rest()
712 reboot = netapp_utils.zapi.NaElement('service-processor-reboot')
713 reboot.add_new_child('node', self.parameters['node'])
714 try:
715 self.server.invoke_successfully(reboot, enable_tunneling=True)
716 except netapp_utils.zapi.NaApiError as error:
717 self.module.fail_json(msg='Error rebooting service processor: %s'
718 % (to_native(error)),
719 exception=traceback.format_exc())
720
721 def get_node_uuid(self):
722 if self._node_uuid is not None:
723 return self._node_uuid
724 api = 'cluster/nodes'
725 query = {'name': self.parameters['node']}
726 node, error = rest_generic.get_one_record(self.rest_api, api, query, fields='uuid')
727 if error:
728 self.module.fail_json(msg='Error reading node UUID: %s' % error)
729 if not node:
730 self.module.fail_json(msg='Error: node not found %s, current nodes: %s.' % (self.parameters['node'], ', '.join(self.get_node_names())))
731 self._node_uuid = node['uuid']
732 return node['uuid']
733
734 def get_node_names(self):
735 api = 'cluster/nodes'
736 nodes, error = rest_generic.get_0_or_more_records(self.rest_api, api, fields='name')
737 if error:
738 self.module.fail_json(msg='Error reading nodes: %s' % error)
739 return [node['name'] for node in nodes]
740
741 def reboot_sp_rest_cli(self):
742 """ for older versions of ONTAP, use the REST CLI passthrough """
743 api = 'private/cli/sp/reboot-sp'
744 query = {'node': self.parameters['node']}
745 dummy, error = rest_generic.patch_async(self.rest_api, api, None, None, query)
746 return error
747
748 def get_sp_state(self):
749 api = 'cluster/nodes/%s' % self.get_node_uuid()
750 node, error = rest_generic.get_one_record(self.rest_api, api, fields='service_processor.state')
751 if error:
752 self.module.fail_json(msg='Error getting node SP state: %s' % error)
753 if node:
754 return self.na_helper.safe_get(node, ['service_processor', 'state'])
755
756 def wait_for_sp_reboot(self):
757 for dummy in range(20):
758 time.sleep(15)
759 state = self.get_sp_state()
760 if state != 'rebooting':
761 break
762 else:
763 self.module.warn('node did not finish up booting in 5 minutes!')
764
765 def reboot_sp_rest(self):
766 uuid = self.get_node_uuid()
767 api = 'cluster/nodes'
768 body = {'service_processor.action': 'reboot'}
769 dummy, error = rest_generic.patch_async(self.rest_api, api, uuid, body)
770 if error and 'Unexpected argument "service_processor.action"' in error:
771 error = self.reboot_sp_rest_cli()
772 if error:
773 error = 'reboot_sp requires ONTAP 9.10.1 or newer, falling back to CLI passthrough failed: ' + error
774 if error:
775 self.module.fail_json(msg='Error rebooting node SP: %s' % error)
776
777 def download_sp_firmware(self):
778 if self.parameters.get('reboot_sp'):
779 self.reboot_sp()
780 if self.use_rest:
781 return self.download_software_rest()
782 self.download_sp_image()
783 progress = self.download_sp_image_progress()
784 # progress only show the current or most recent update/install operation.
785 if progress['phase'] == 'Download':
786 while progress['run_status'] is not None and progress['run_status'] != 'Exited':
787 time.sleep(10)
788 progress = self.download_sp_image_progress()
789 if progress['exit_status'] != 'Success':
790 self.module.fail_json(msg=progress['exit_message'], exception=traceback.format_exc())
791 return MSGS['dl_completed']
792 return MSGS['no_action']
793
794 def download_software_rest(self):
795 body = {'url': self.parameters['package_url']}
796 for attr in ('username', 'password'):
797 value = self.parameters.get('server_%s' % attr)
798 if value:
799 body[attr] = value
800 api = 'cluster/software/download'
801 # burt 1442080 - when timeout is 30, the API may return a 500 error, though the job says download completed!
802 message, error = rest_generic.post_async(self.rest_api, api, body, job_timeout=self.parameters.get('time_out', 180), timeout=0)
803 if error:
804 self.module.fail_json(msg='Error downloading software: %s' % error)
805 return message
806
807 def apply(self):
808 """
809 Apply action to upgrade firmware
810 """
811 changed = False
812 msg = MSGS['no_action']
813 if self.parameters.get('package_url'):
814 if not self.module.check_mode:
815 if self.parameters.get('firmware_type') == 'service-processor':
816 msg = self.download_sp_firmware()
817 if self.parameters.get('reboot_sp') and self.use_rest:
818 self.wait_for_sp_reboot()
819 else:
820 msg = self.download_firmware()
821 changed = True
822 if not self.parameters['force_disruptive_update'] and not self.parameters.get('reboot_sp_after update'):
823 # disk_qual, disk, shelf, and ACP are automatically updated in background
824 # The SP firmware is automatically updated on reboot
825 self.module.exit_json(changed=changed, msg=msg)
826 if msg == MSGS['dl_in_progress']:
827 # can't force an update if the software is still downloading
828 self.module.fail_json(msg="Cannot force update: %s" % msg)
829 self.disruptive_update(changed)
830
831 def disruptive_update(self, changed):
832 if self.parameters.get('firmware_type') == 'service-processor':
833 if self.parameters.get('reboot_sp_after update'):
834 self.reboot_sp()
835 if not self.parameters['force_disruptive_update']:
836 return
837 # service-processor firmware upgrade
838 current = self.firmware_image_get(self.parameters['node'])
839
840 if self.parameters.get('state') == 'present' and current:
841 if not self.module.check_mode:
842 if self.sp_firmware_image_update():
843 changed = True
844 firmware_update_progress = self.sp_firmware_image_update_progress_get(self.parameters['node'])
845 while firmware_update_progress.get('is-in-progress') == 'true':
846 time.sleep(25)
847 firmware_update_progress = self.sp_firmware_image_update_progress_get(self.parameters['node'])
848 else:
849 # we don't know until we try the upgrade
850 changed = True
851
852 elif self.parameters.get('firmware_type') == 'shelf':
853 # shelf firmware upgrade
854 if self.parameters.get('shelf_module_fw'):
855 if self.shelf_firmware_update_required():
856 changed = True if self.module.check_mode else self.shelf_firmware_upgrade()
857 else:
858 # with check_mode, we don't know until we try the upgrade -- assuming the worst
859 changed = True if self.module.check_mode else self.shelf_firmware_upgrade()
860 elif self.parameters.get('firmware_type') == 'acp' and self.acp_firmware_update_required():
861 # acp firmware upgrade
862 if not self.module.check_mode:
863 self.acp_firmware_upgrade()
864 changed = True
865 elif self.parameters.get('firmware_type') == 'disk':
866 # Disk firmware upgrade
867 if self.parameters.get('disk_fw'):
868 if self.disk_firmware_update_required():
869 changed = True if self.module.check_mode else self.disk_firmware_upgrade()
870 else:
871 # with check_mode, we don't know until we try the upgrade -- assuming the worst
872 changed = True if self.module.check_mode else self.disk_firmware_upgrade()
873 self.module.exit_json(changed=changed, msg='forced update for %s' % self.parameters.get('firmware_type'))
874
875
876 def main():
877 """Execute action"""
878 fwupgrade_obj = NetAppONTAPFirmwareUpgrade()
879 fwupgrade_obj.apply()
880
881
882 if __name__ == '__main__':
883 main()