Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/redfish_storage_volume.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.3.0
7 # Copyright (C) 2019-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
8
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10 #
11
12
13 from __future__ import (absolute_import, division, print_function)
14 __metaclass__ = type
15
16 DOCUMENTATION = r'''
17 ---
18 module: redfish_storage_volume
19 short_description: Manages the storage volume configuration
20 version_added: "2.1.0"
21 description:
22 - This module allows to create, modify, initialize, or delete a single storage volume.
23 extends_documentation_fragment:
24 - dellemc.openmanage.redfish_auth_options
25 options:
26 controller_id:
27 description:
28 - Fully Qualified Device Descriptor (FQDD) of the storage controller.
29 - For example- RAID.Slot.1-1.
30 - This option is mandatory when I(state) is C(present) while creating a volume.
31 type: str
32 volume_id:
33 description:
34 - FQDD of existing volume.
35 - For example- Disk.Virtual.4:RAID.Slot.1-1.
36 - This option is mandatory in the following scenarios,
37 - >-
38 I(state) is C(present), when updating a volume.
39 - >-
40 I(state) is C(absent), when deleting a volume.
41 - >-
42 I(command) is C(initialize), when initializing a volume.
43 type: str
44 state:
45 description:
46 - >-
47 C(present) creates a storage volume for the specified I (controller_id), or modifies the storage volume for the
48 specified I (volume_id).
49 "Note: Modification of an existing volume properties depends on drive and controller capabilities".
50 - C(absent) deletes the volume for the specified I(volume_id).
51 type: str
52 choices: [present, absent]
53 command:
54 description:
55 - C(initialize) initializes an existing storage volume for a specified I(volume_id).
56 type: str
57 choices: [initialize]
58 volume_type:
59 description:
60 - One of the following volume types must be selected to create a volume.
61 - C(NonRedundant) The volume is a non-redundant storage device.
62 - C(Mirrored) The volume is a mirrored device.
63 - C(StripedWithParity) The volume is a device which uses parity to retain redundant information.
64 - C(SpannedMirrors) The volume is a spanned set of mirrored devices.
65 - C(SpannedStripesWithParity) The volume is a spanned set of devices which uses parity to retain redundant
66 information.
67 - I(volume_type) is mutually exclusive with I(raid_type).
68 type: str
69 choices: [NonRedundant, Mirrored, StripedWithParity, SpannedMirrors, SpannedStripesWithParity]
70 name:
71 description:
72 - Name of the volume to be created.
73 - Only applicable when I(state) is C(present).
74 type: str
75 aliases: ['volume_name']
76 drives:
77 description:
78 - FQDD of the Physical disks.
79 - For example- Disk.Bay.0:Enclosure.Internal.0-1:RAID.Slot.1-1.
80 - Only applicable when I(state) is C(present) when creating a new volume.
81 type: list
82 elements: str
83 block_size_bytes:
84 description:
85 - (deprecated) Block size in bytes.Only applicable when I(state) is C(present).
86 type: int
87 capacity_bytes:
88 description:
89 - Volume size in bytes.
90 - Only applicable when I(state) is C(present).
91 type: str
92 optimum_io_size_bytes:
93 description:
94 - Stripe size value must be in multiples of 64 * 1024.
95 - Only applicable when I(state) is C(present).
96 type: int
97 encryption_types:
98 description:
99 - (deprecated) The following encryption types can be selected.
100 - C(ControllerAssisted) The volume is encrypted by the storage controller entity.
101 - C(NativeDriveEncryption) The volume utilizes the native drive encryption capabilities
102 of the drive hardware.
103 - C(SoftwareAssisted) The volume is encrypted by the software running
104 on the system or the operating system.
105 - Only applicable when I(state) is C(present).
106 type: str
107 choices: [NativeDriveEncryption, ControllerAssisted, SoftwareAssisted]
108 encrypted:
109 description:
110 - Indicates whether volume is currently utilizing encryption or not.
111 - Only applicable when I(state) is C(present).
112 type: bool
113 oem:
114 description:
115 - Includes OEM extended payloads.
116 - Only applicable when I(state) is I(present).
117 type: dict
118 initialize_type:
119 description:
120 - Initialization type of existing volume.
121 - Only applicable when I(command) is C(initialize).
122 type: str
123 choices: [Fast, Slow]
124 default: Fast
125 raid_type:
126 description:
127 - C(RAID0) to create a RAID0 type volume.
128 - C(RAID1) to create a RAID1 type volume.
129 - C(RAID5) to create a RAID5 type volume.
130 - C(RAID6) to create a RAID6 type volume.
131 - C(RAID10) to create a RAID10 type volume.
132 - C(RAID50) to create a RAID50 type volume.
133 - C(RAID60) to create a RAID60 type volume.
134 - I(raid_type) is mutually exclusive with I(volume_type).
135 type: str
136 choices: [RAID0, RAID1, RAID5, RAID6, RAID10, RAID50, RAID60]
137 version_added: 8.3.0
138 apply_time:
139 description:
140 - Apply time of the Volume configuration.
141 - C(Immediate) allows you to apply the volume configuration on the host server immediately and apply the changes. This is applicable for I(job_wait).
142 - C(OnReset) allows you to apply the changes on the next reboot of the host server.
143 - I(apply_time) has a default value based on the different types of the controller.
144 For example, BOSS-S1 and BOSS-N1 controllers have a default value of I(apply_time) as C(OnReset),
145 and PERC controllers have a default value of I(apply_time) as C(Immediate).
146 type: str
147 choices: [Immediate, OnReset]
148 version_added: 8.5.0
149 reboot_server:
150 description:
151 - Reboot the server to apply the changes.
152 - I(reboot_server) is applicable only when I(apply_timeout) is C(OnReset) or when the default value for the apply time of the controller is C(OnReset).
153 type: bool
154 default: false
155 version_added: 8.5.0
156 force_reboot:
157 description:
158 - Reboot the server forcefully to apply the changes when the normal reboot fails.
159 - I(force_reboot) is applicable only when I(reboot_server) is C(true).
160 type: bool
161 default: false
162 version_added: 8.5.0
163 job_wait:
164 description:
165 - This parameter provides the option to wait for the job completion.
166 - This is applicable when I(apply_time) is C(Immediate).
167 - This is applicable when I(apply_time) is C(OnReset) and I(reboot_server) is C(true).
168 type: bool
169 default: false
170 version_added: 8.5.0
171 job_wait_timeout:
172 description:
173 - This parameter is the maximum wait time of I(job_wait) in seconds.
174 - This option is applicable when I(job_wait) is C(true).
175 type: int
176 default: 1200
177 version_added: 8.5.0
178
179
180 requirements:
181 - "python >= 3.9.6"
182 author:
183 - "Sajna Shetty(@Sajna-Shetty)"
184 - "Kritika Bhateja(@Kritika-Bhateja-03)"
185 - "Shivam Sharma(@ShivamSh3)"
186 notes:
187 - Run this module from a system that has direct access to Redfish APIs.
188 - This module supports C(check_mode).
189 - This module always reports changes when I(name) and I(volume_id) are not specified.
190 Either I(name) or I(volume_id) is required to support C(check_mode).
191 - This module does not support the create operation of RAID6 and RAID60 storage volume on iDRAC8
192 - This module supports IPv4 and IPv6 addresses.
193 '''
194
195 EXAMPLES = r'''
196 ---
197 - name: Create a volume with supported options
198 dellemc.openmanage.redfish_storage_volume:
199 baseuri: "192.168.0.1"
200 username: "username"
201 password: "password"
202 ca_path: "/path/to/ca_cert.pem"
203 state: "present"
204 volume_type: "Mirrored"
205 name: "VD0"
206 controller_id: "RAID.Slot.1-1"
207 drives:
208 - Disk.Bay.5:Enclosure.Internal.0-1:RAID.Slot.1-1
209 - Disk.Bay.6:Enclosure.Internal.0-1:RAID.Slot.1-1
210 capacity_bytes: 299439751168
211 optimum_io_size_bytes: 65536
212 encrypted: true
213
214 - name: Create a volume with minimum options
215 dellemc.openmanage.redfish_storage_volume:
216 baseuri: "192.168.0.1"
217 username: "username"
218 password: "password"
219 ca_path: "/path/to/ca_cert.pem"
220 state: "present"
221 controller_id: "RAID.Slot.1-1"
222 volume_type: "NonRedundant"
223 drives:
224 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-1
225
226 - name: Create a RAID0 on PERC controller on reset
227 dellemc.openmanage.redfish_storage_volume:
228 baseuri: "192.168.0.1"
229 username: "username"
230 password: "password"
231 state: "present"
232 controller_id: "RAID.Slot.1-1"
233 raid_type: "RAID0"
234 drives:
235 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-1
236 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-2
237 apply_time: OnReset
238
239 - name: Create a RAID0 on BOSS controller with restart
240 dellemc.openmanage.redfish_storage_volume:
241 baseuri: "192.168.0.1"
242 username: "username"
243 password: "password"
244 state: "present"
245 controller_id: "RAID.Slot.1-1"
246 raid_type: "RAID0"
247 drives:
248 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-1
249 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-2
250 apply_time: OnReset
251 reboot_server: true
252
253 - name: Create a RAID0 on BOSS controller with force restart
254 dellemc.openmanage.redfish_storage_volume:
255 baseuri: "192.168.0.1"
256 username: "username"
257 password: "password"
258 state: "present"
259 controller_id: "RAID.Slot.1-1"
260 raid_type: "RAID0"
261 drives:
262 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-1
263 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-2
264 reboot_server: true
265 force_reboot: true
266
267 - name: Modify a volume's encryption type settings
268 dellemc.openmanage.redfish_storage_volume:
269 baseuri: "192.168.0.1"
270 username: "username"
271 password: "password"
272 ca_path: "/path/to/ca_cert.pem"
273 state: "present"
274 volume_id: "Disk.Virtual.5:RAID.Slot.1-1"
275 encrypted: true
276
277 - name: Delete an existing volume
278 dellemc.openmanage.redfish_storage_volume:
279 baseuri: "192.168.0.1"
280 username: "username"
281 password: "password"
282 ca_path: "/path/to/ca_cert.pem"
283 state: "absent"
284 volume_id: "Disk.Virtual.5:RAID.Slot.1-1"
285
286 - name: Initialize an existing volume
287 dellemc.openmanage.redfish_storage_volume:
288 baseuri: "192.168.0.1"
289 username: "username"
290 password: "password"
291 ca_path: "/path/to/ca_cert.pem"
292 command: "initialize"
293 volume_id: "Disk.Virtual.6:RAID.Slot.1-1"
294 initialize_type: "Slow"
295
296 - name: Create a RAID6 volume
297 dellemc.openmanage.redfish_storage_volume:
298 baseuri: "192.168.0.1"
299 username: "username"
300 password: "password"
301 state: "present"
302 controller_id: "RAID.Slot.1-1"
303 raid_type: "RAID6"
304 drives:
305 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-1
306 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-2
307 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-3
308 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-4
309
310 - name: Create a RAID60 volume
311 dellemc.openmanage.redfish_storage_volume:
312 baseuri: "192.168.0.1"
313 username: "username"
314 password: "password"
315 state: "present"
316 controller_id: "RAID.Slot.1-1"
317 raid_type: "RAID60"
318 drives:
319 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-1
320 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-2
321 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-3
322 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-4
323 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-5
324 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-6
325 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-7
326 - Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-8
327 '''
328
329 RETURN = r'''
330 ---
331 msg:
332 description: Overall status of the storage configuration operation.
333 returned: always
334 type: str
335 sample: "Successfully submitted create volume task."
336 task:
337 type: dict
338 description: Returns ID and URI of the created task.
339 returned: success
340 sample: {
341 "id": "JID_XXXXXXXXXXXXX",
342 "uri": "/redfish/v1/Managers/iDRAC.Embedded.1/Jobs/JID_XXXXXXXXXXXXX"
343 }
344 error_info:
345 type: dict
346 description: Details of a http error.
347 returned: on http error
348 sample: {
349 "error": {
350 "@Message.ExtendedInfo": [
351 {
352 "Message": "Unable to perform configuration operations because a
353 configuration job for the device already exists.",
354 "MessageArgs": [],
355 "[email protected]": 0,
356 "MessageId": "IDRAC.1.6.STOR023",
357 "RelatedProperties": [],
358 "[email protected]": 0,
359 "Resolution": "Wait for the current job for the device to complete
360 or cancel the current job before attempting more configuration
361 operations on the device.",
362 "Severity": "Informational"
363 }
364 ],
365 "code": "Base.1.2.GeneralError",
366 "message": "A general error has occurred. See ExtendedInfo for more information"
367 }
368 }
369 '''
370
371 import json
372 import copy
373 from ssl import SSLError
374 from ansible_collections.dellemc.openmanage.plugins.module_utils.redfish import Redfish, RedfishAnsibleModule
375 from ansible.module_utils.compat.version import LooseVersion
376 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
377 from ansible.module_utils.urls import ConnectionError, SSLValidationError
378 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import MANAGER_JOB_ID_URI_10, wait_for_redfish_reboot_job, \
379 strip_substr_dict, wait_for_job_completion
380
381
382 VOLUME_INITIALIZE_URI = "{storage_base_uri}/{controller_id}/Volumes/{volume_id}/Actions/Volume.Initialize"
383 DRIVES_URI = "{storage_base_uri}/Drives/{driver_id}"
384 CONTROLLER_URI = "{storage_base_uri}/{controller_id}"
385 SETTING_VOLUME_ID_URI = "{storage_base_uri}/{controller_id}/Volumes/{volume_id}/Settings"
386 CONTROLLER_VOLUME_URI = "{storage_base_uri}/{controller_id}/Volumes"
387 VOLUME_ID_URI = "{storage_base_uri}/{controller_id}/Volumes/{volume_id}"
388 APPLY_TIME_INFO_API = CONTROLLER_URI + "/Volumes"
389 REBOOT_API = "Actions/ComputerSystem.Reset"
390 storage_collection_map = {}
391 CHANGES_FOUND = "Changes found to be applied."
392 NO_CHANGES_FOUND = "No changes found to be applied."
393 RAID_TYPE_NOT_SUPPORTED_MSG = "RAID Type {raid_type} is not supported."
394 APPLY_TIME_NOT_SUPPORTED_MSG = "Apply time {apply_time} is not supported. The supported values \
395 are {supported_apply_time_values}. Enter the valid values and retry the operation."
396 JOB_COMPLETION = "The job is successfully completed."
397 JOB_SUBMISSION = "The job is successfully submitted."
398 JOB_FAILURE_PROGRESS_MSG = "Unable to complete the task initiated for creating the storage volume."
399 REBOOT_FAIL = "Failed to reboot the server."
400 CONTROLLER_NOT_EXIST_ERROR = "Specified Controller {controller_id} does not exist in the System."
401 TIMEOUT_NEGATIVE_OR_ZERO_MSG = "The parameter job_wait_timeout value cannot be negative or zero."
402 SYSTEM_ID = "System.Embedded.1"
403 GET_IDRAC_FIRMWARE_VER_URI = "/redfish/v1/Managers/iDRAC.Embedded.1?$select=FirmwareVersion"
404 ODATA_ID = "@odata.id"
405 TARGET_OUT_OF_BAND = "Target out-of-band controller does not support storage feature using Redfish API."
406 volume_type_map = {"NonRedundant": "RAID0",
407 "Mirrored": "RAID1",
408 "StripedWithParity": "RAID5",
409 "SpannedMirrors": "RAID10",
410 "SpannedStripesWithParity": "RAID50"}
411
412
413 def fetch_storage_resource(module, session_obj):
414 try:
415 system_uri = "{0}{1}".format(session_obj.root_uri, "Systems")
416 system_resp = session_obj.invoke_request("GET", system_uri)
417 system_members = system_resp.json_data.get("Members")
418 if system_members:
419 system_id_res = system_members[0][ODATA_ID]
420 _SYSTEM_ID = system_id_res.split('/')[-1]
421 system_id_res_resp = session_obj.invoke_request("GET", system_id_res)
422 system_id_res_data = system_id_res_resp.json_data.get("Storage")
423 if system_id_res_data:
424 storage_collection_map.update({"storage_base_uri": system_id_res_data[ODATA_ID]})
425 else:
426 module.fail_json(msg=TARGET_OUT_OF_BAND)
427 else:
428 module.fail_json(msg=TARGET_OUT_OF_BAND)
429 except HTTPError as err:
430 if err.code in [404, 405]:
431 module.fail_json(msg=TARGET_OUT_OF_BAND,
432 error_info=json.load(err))
433 raise err
434 except (URLError, SSLValidationError, ConnectionError, TypeError, ValueError) as err:
435 raise err
436
437
438 def volume_payload(module, greater_version):
439 params = module.params
440 drives = params.get("drives")
441 capacity_bytes = params.get("capacity_bytes")
442 physical_disks = []
443 oem = params.get("oem")
444 encrypted = params.get("encrypted")
445 volume_type = params.get("volume_type")
446 raid_type = params.get("raid_type")
447 apply_time = params.get("apply_time")
448 if capacity_bytes:
449 capacity_bytes = int(capacity_bytes)
450 if drives:
451 storage_base_uri = storage_collection_map["storage_base_uri"]
452 physical_disks = [{ODATA_ID: DRIVES_URI.format(storage_base_uri=storage_base_uri,
453 driver_id=drive_id)} for drive_id in drives]
454 raid_mapper = {
455 "Name": params.get("name"),
456 "CapacityBytes": capacity_bytes,
457 "OptimumIOSizeBytes": params.get("optimum_io_size_bytes"),
458 "Links": {"Drives": physical_disks}
459 }
460 raid_payload = dict([(k, v) for k, v in raid_mapper.items() if v])
461 if oem:
462 raid_payload.update(params.get("oem"))
463 if encrypted is not None:
464 raid_payload.update({"Encrypted": encrypted})
465 if volume_type and greater_version:
466 raid_payload.update({"RAIDType": volume_type_map.get(volume_type)})
467 if raid_type and greater_version:
468 raid_payload.update({"RAIDType": raid_type})
469 if volume_type and greater_version is False:
470 raid_payload.update({"VolumeType": volume_type})
471 if raid_type and greater_version is False:
472 raid_map = {value: key for key, value in volume_type_map.items()}
473 raid_payload.update({"VolumeType": raid_map.get(raid_type)})
474 if apply_time is not None:
475 raid_payload.update({"@Redfish.OperationApplyTime": apply_time})
476 return raid_payload
477
478
479 def check_physical_disk_exists(module, drives):
480 """
481 validation to check if physical disks(drives) available for the specified controller
482 """
483 specified_drives = module.params.get("drives")
484 if specified_drives:
485 existing_drives = []
486 specified_controller_id = module.params.get("controller_id")
487 if drives:
488 for drive in drives:
489 drive_uri = drive['@odata.id']
490 drive_id = drive_uri.split("/")[-1]
491 existing_drives.append(drive_id)
492 else:
493 module.fail_json(msg="No Drive(s) are attached to the specified "
494 "Controller Id: {0}.".format(specified_controller_id))
495 invalid_drives = list(set(specified_drives) - set(existing_drives))
496 if invalid_drives:
497 invalid_drive_msg = ",".join(invalid_drives)
498 module.fail_json(msg="Following Drive(s) {0} are not attached to the "
499 "specified Controller Id: {1}.".format(invalid_drive_msg, specified_controller_id))
500 return True
501
502
503 def check_specified_identifier_exists_in_the_system(module, session_obj, uri, err_message):
504 """
505 common validation to check if , specified volume or controller id exist in the system or not
506 """
507 try:
508 resp = session_obj.invoke_request('GET', uri)
509 return resp
510 except HTTPError as err:
511 if err.code == 404:
512 if module.params.get("state") == "absent" and module.params.get("volume_id"):
513 module.exit_json(msg=NO_CHANGES_FOUND)
514 module.exit_json(msg=err_message, failed=True)
515 raise err
516 except (URLError, SSLValidationError, ConnectionError, TypeError, ValueError) as err:
517 raise err
518
519
520 def check_controller_id_exists(module, session_obj):
521 """
522 Controller availability Validation
523 """
524 specified_controller_id = module.params.get("controller_id")
525 uri = CONTROLLER_URI.format(storage_base_uri=storage_collection_map["storage_base_uri"], controller_id=specified_controller_id)
526 err_message = CONTROLLER_NOT_EXIST_ERROR.format(controller_id=specified_controller_id)
527 resp = check_specified_identifier_exists_in_the_system(module, session_obj, uri, err_message)
528 if resp.success:
529 return check_physical_disk_exists(module, resp.json_data["Drives"])
530 else:
531 module.fail_json(msg="Failed to retrieve the details of the specified Controller Id "
532 "{0}.".format(specified_controller_id))
533
534
535 def check_volume_id_exists(module, session_obj, volume_id):
536 """
537 validation to check if volume id is valid in case of modify, delete, initialize operation
538 """
539 uri = VOLUME_ID_URI.format(
540 storage_base_uri=storage_collection_map["storage_base_uri"],
541 volume_id=volume_id,
542 controller_id=volume_id.split(":")[1])
543 err_message = "Specified Volume Id {0} does not exist in the System.".format(volume_id)
544 resp = check_specified_identifier_exists_in_the_system(module, session_obj, uri, err_message)
545 return resp
546
547
548 def check_initialization_progress(module, session_obj, volume_id):
549 """
550 validation check if any operation is running in specified volume id.
551 """
552 operations = []
553 resp = check_volume_id_exists(module, session_obj, volume_id)
554 if resp.success:
555 operations = resp.json_data["Operations"]
556 return operations
557
558
559 def perform_storage_volume_action(method, uri, session_obj, action, payload=None):
560 """
561 common request call for raid creation update delete and initialization
562 """
563 try:
564 resp = session_obj.invoke_request(method, uri, data=payload)
565 task_uri = resp.headers["Location"]
566 if not task_uri:
567 msg = resp.json_data["@Message.ExtendedInfo"][1]["Message"]
568 status_message = {"msg": msg}
569 return status_message
570 return get_success_message(action, task_uri)
571 except (HTTPError, URLError, SSLValidationError, ConnectionError,
572 TypeError, ValueError) as err:
573 raise err
574
575
576 def check_mode_validation(module, session_obj, action, uri, greater_version):
577 volume_id = module.params.get('volume_id')
578 name = module.params.get("name")
579 capacity_bytes = module.params.get("capacity_bytes")
580 optimum_io_size_bytes = module.params.get("optimum_io_size_bytes")
581 encrypted = module.params.get("encrypted")
582 volume_type = module.params.get("volume_type")
583 raid_type = module.params.get("raid_type")
584 drives = module.params.get("drives")
585 if name is None and volume_id is None and module.check_mode:
586 module.exit_json(msg=CHANGES_FOUND, changed=True)
587 if action == "create" and name is not None:
588 volume_id = _create_name(module, session_obj, uri, name, volume_id)
589 if volume_id is not None:
590 _volume_id_check_mode(module, session_obj, greater_version, volume_id,
591 name, capacity_bytes, optimum_io_size_bytes,
592 encrypted, volume_type, raid_type, drives)
593 return None
594
595
596 def _volume_id_check_mode(module, session_obj, greater_version, volume_id, name,
597 capacity_bytes, optimum_io_size_bytes,
598 encrypted, volume_type, raid_type, drives):
599 resp = session_obj.invoke_request("GET", SETTING_VOLUME_ID_URI.format(
600 storage_base_uri=storage_collection_map["storage_base_uri"],
601 volume_id=volume_id,
602 controller_id=volume_id.split(":")[1]))
603 resp_data = resp.json_data
604 exist_value = _get_payload_for_version(greater_version, resp_data)
605 exit_value_filter = dict(
606 [(k, v) for k, v in exist_value.items() if v is not None])
607 cp_exist_value = copy.deepcopy(exit_value_filter)
608 req_value = get_request_value(greater_version, name, optimum_io_size_bytes,
609 encrypted, volume_type, raid_type)
610 if capacity_bytes is not None:
611 req_value["CapacityBytes"] = int(capacity_bytes)
612 req_value_filter = dict([(k, v)
613 for k, v in req_value.items() if v is not None])
614 cp_exist_value.update(req_value_filter)
615 exist_drive, req_drive = [], []
616 if resp_data["Links"]:
617 exist_drive = [
618 disk[ODATA_ID].split("/")[-1] for disk in resp_data["Links"]["Drives"]]
619 if drives is not None:
620 req_drive = sorted(drives)
621 diff_changes = [bool(set(exit_value_filter.items()) ^ set(cp_exist_value.items())) or
622 bool(set(exist_drive) ^ set(req_drive))]
623 if module.check_mode and any(diff_changes) is True:
624 module.exit_json(msg=CHANGES_FOUND, changed=True)
625 elif (module.check_mode and any(diff_changes) is False) or \
626 (not module.check_mode and any(diff_changes) is False):
627 module.exit_json(msg=NO_CHANGES_FOUND)
628
629
630 def get_request_value(greater_version, name, optimum_io_size_bytes, encrypted, volume_type, raid_type):
631 if greater_version:
632 req_value = {"Name": name,
633 "Encrypted": encrypted, "OptimumIOSizeBytes": optimum_io_size_bytes,
634 "RAIDType": raid_type}
635 else:
636 req_value = {"Name": name,
637 "Encrypted": encrypted, "OptimumIOSizeBytes": optimum_io_size_bytes,
638 "VolumeType": volume_type}
639 return req_value
640
641
642 def _get_payload_for_version(greater_version, resp_data):
643 if greater_version:
644 exist_value = {"Name": resp_data["Name"],
645 "CapacityBytes": resp_data["CapacityBytes"], "Encrypted": resp_data["Encrypted"],
646 "EncryptionTypes": resp_data["EncryptionTypes"][0],
647 "OptimumIOSizeBytes": resp_data["OptimumIOSizeBytes"], "RAIDType": resp_data["RAIDType"]}
648 else:
649 exist_value = {"Name": resp_data["Name"],
650 "CapacityBytes": resp_data["CapacityBytes"], "Encrypted": resp_data["Encrypted"],
651 "EncryptionTypes": resp_data["EncryptionTypes"][0],
652 "OptimumIOSizeBytes": resp_data["OptimumIOSizeBytes"], "VolumeType": resp_data["VolumeType"]}
653 return exist_value
654
655
656 def _create_name(module, session_obj, uri, name, volume_id):
657 volume_resp = session_obj.invoke_request("GET", uri)
658 volume_resp_data = volume_resp.json_data
659 if volume_resp_data.get("[email protected]") == 0 and module.check_mode:
660 module.exit_json(msg=CHANGES_FOUND, changed=True)
661 elif 0 < volume_resp_data.get("[email protected]"):
662 for mem in volume_resp_data.get("Members"):
663 mem_resp = session_obj.invoke_request("GET", mem[ODATA_ID])
664 if mem_resp.json_data["Name"] == name:
665 volume_id = mem_resp.json_data["Id"]
666 break
667 if name is not None and module.check_mode and volume_id is None:
668 module.exit_json(msg=CHANGES_FOUND, changed=True)
669 return volume_id
670
671
672 def check_raid_type_supported(module, session_obj):
673 volume_type = module.params.get("volume_type")
674 if volume_type:
675 raid_type = volume_type_map.get(volume_type)
676 else:
677 raid_type = module.params.get("raid_type")
678 if raid_type:
679 try:
680 specified_controller_id = module.params.get("controller_id")
681 uri = CONTROLLER_URI.format(storage_base_uri=storage_collection_map["storage_base_uri"], controller_id=specified_controller_id)
682 resp = session_obj.invoke_request("GET", uri)
683 supported_raid_types = resp.json_data['StorageControllers'][0]['SupportedRAIDTypes']
684 if raid_type not in supported_raid_types:
685 module.exit_json(msg=RAID_TYPE_NOT_SUPPORTED_MSG.format(raid_type=raid_type), failed=True)
686 except (HTTPError, URLError, SSLValidationError, ConnectionError, TypeError, ValueError) as err:
687 raise err
688
689
690 def get_apply_time(module, session_obj, controller_id, greater_version):
691 """
692 gets the apply time from user if given otherwise fetches from server
693 """
694 apply_time = module.params.get("apply_time")
695 try:
696 uri = APPLY_TIME_INFO_API.format(storage_base_uri=storage_collection_map["storage_base_uri"], controller_id=controller_id)
697 resp = session_obj.invoke_request("GET", uri)
698 if greater_version:
699 supported_apply_time_values = resp.json_data['@Redfish.OperationApplyTimeSupport']['SupportedValues']
700 else:
701 return apply_time
702 if apply_time:
703 if apply_time not in supported_apply_time_values:
704 module.exit_json(msg=APPLY_TIME_NOT_SUPPORTED_MSG.format(apply_time=apply_time, supported_apply_time_values=supported_apply_time_values),
705 failed=True)
706 else:
707 apply_time = supported_apply_time_values[0]
708 return apply_time
709 except (HTTPError, URLError, SSLValidationError, ConnectionError, TypeError, ValueError) as err:
710 raise err
711
712
713 def check_apply_time_supported_and_reboot_required(module, session_obj, controller_id, greater_version):
714 """
715 checks whether the apply time is supported and reboot operation is required or not.
716 """
717 apply_time = get_apply_time(module, session_obj, controller_id, greater_version)
718 reboot_server = module.params.get("reboot_server")
719 if reboot_server and apply_time == "OnReset":
720 return True
721 return False
722
723
724 def perform_volume_create_modify(module, session_obj, greater_version):
725 """
726 perform volume creation and modification for state present
727 """
728 specified_controller_id = module.params.get("controller_id")
729 volume_id = module.params.get("volume_id")
730 if greater_version:
731 check_raid_type_supported(module, session_obj)
732 action, uri, method = None, None, None
733 if specified_controller_id is not None:
734 check_controller_id_exists(module, session_obj)
735 uri = CONTROLLER_VOLUME_URI.format(storage_base_uri=storage_collection_map["storage_base_uri"],
736 controller_id=specified_controller_id)
737 method = "POST"
738 action = "create"
739 else:
740 resp = check_volume_id_exists(module, session_obj, volume_id)
741 if resp.success:
742 uri = SETTING_VOLUME_ID_URI.format(storage_base_uri=storage_collection_map["storage_base_uri"],
743 volume_id=volume_id,
744 controller_id=volume_id.split(":")[1])
745 method = "PATCH"
746 action = "modify"
747 payload = volume_payload(module, greater_version)
748 check_mode_validation(module, session_obj, action, uri, greater_version)
749 if not payload:
750 module.fail_json(msg="Input options are not provided for the {0} volume task.".format(action))
751 return perform_storage_volume_action(method, uri, session_obj, action, payload)
752
753
754 def perform_volume_deletion(module, session_obj):
755 """
756 perform volume deletion for state absent
757 """
758 volume_id = module.params.get("volume_id")
759 if volume_id:
760 resp = check_volume_id_exists(module, session_obj, volume_id)
761 if hasattr(resp, "success") and resp.success and not module.check_mode:
762 uri = VOLUME_ID_URI.format(
763 storage_base_uri=storage_collection_map["storage_base_uri"],
764 volume_id=volume_id,
765 controller_id=volume_id.split(":")[1])
766 method = "DELETE"
767 return perform_storage_volume_action(method, uri, session_obj, "delete")
768 elif hasattr(resp, "success") and resp.success and module.check_mode:
769 module.exit_json(msg=CHANGES_FOUND, changed=True)
770 elif hasattr(resp, "code") and resp.code == 404 and module.check_mode:
771 module.exit_json(msg=NO_CHANGES_FOUND)
772 else:
773 module.fail_json(msg="'volume_id' option is a required property for deleting a volume.")
774
775
776 def perform_volume_initialization(module, session_obj):
777 """
778 perform volume initialization for command initialize
779 """
780 specified_volume_id = module.params.get("volume_id")
781 if specified_volume_id:
782 operations = check_initialization_progress(module, session_obj, specified_volume_id)
783 if operations:
784 operation_message = "Cannot perform the configuration operations because a " \
785 "configuration job for the device already exists."
786 operation_name = operations[0].get("OperationName")
787 percentage_complete = operations[0].get("PercentageComplete")
788 if operation_name and percentage_complete:
789 operation_message = "Cannot perform the configuration operation because the configuration job '{0}'" \
790 " in progress is at '{1}' percentage.".format(operation_name, percentage_complete)
791 module.fail_json(msg=operation_message)
792 else:
793 method = "POST"
794 uri = VOLUME_INITIALIZE_URI.format(storage_base_uri=storage_collection_map["storage_base_uri"],
795 volume_id=specified_volume_id,
796 controller_id=specified_volume_id.split(":")[1])
797 payload = {"InitializeType": module.params["initialize_type"]}
798 return perform_storage_volume_action(method, uri, session_obj, "initialize", payload)
799 else:
800 module.fail_json(msg="'volume_id' option is a required property for initializing a volume.")
801
802
803 def configure_raid_operation(module, session_obj, greater_version):
804 """
805 configure raid action based on state and command input
806 """
807 module_params = module.params
808 state = module_params.get("state")
809 command = module_params.get("command")
810 if state is not None and state == "present":
811 return perform_volume_create_modify(module, session_obj, greater_version)
812 elif state is not None and state == "absent":
813 return perform_volume_deletion(module, session_obj)
814 elif command is not None and command == "initialize":
815 return perform_volume_initialization(module, session_obj)
816
817
818 def get_success_message(action, task_uri):
819 """
820 message for different types of raid actions
821 """
822 msg = "Successfully submitted {0} volume task.".format(action)
823 status_message = {"msg": msg}
824 if task_uri is not None:
825 task_id = task_uri.split("/")[-1]
826 status_message.update({"task_uri": task_uri, "task_id": task_id})
827 return status_message
828
829
830 def validate_inputs(module):
831 """
832 validation check for state and command input for null values.
833 """
834 module_params = module.params
835 state = module_params.get("state")
836 command = module_params.get("command")
837 if state is None and command is None:
838 module.fail_json(msg="Either state or command should be provided to further actions.")
839 elif state == "present" and\
840 module_params.get("controller_id") is None and\
841 module_params.get("volume_id") is None:
842 module.fail_json(msg="When state is present, either controller_id or"
843 " volume_id must be specified to perform further actions.")
844
845
846 def perform_force_reboot(module, session_obj):
847 payload = {"ResetType": "ForceRestart"}
848 job_resp_status, reset_status, reset_fail = wait_for_redfish_reboot_job(session_obj, SYSTEM_ID, payload=payload)
849 if reset_status and job_resp_status:
850 job_uri = MANAGER_JOB_ID_URI_10.format(job_resp_status["Id"])
851 resp, msg = wait_for_job_completion(session_obj, job_uri, wait_timeout=module.params.get("job_wait_timeout"))
852 if resp:
853 job_data = strip_substr_dict(resp.json_data)
854 if job_data["JobState"] == "Failed":
855 module.exit_json(msg=REBOOT_FAIL, job_status=job_data, failed=True)
856 else:
857 resp = session_obj.invoke_request("GET", job_uri)
858 job_data = strip_substr_dict(resp.json_data)
859 module.exit_json(msg=msg, job_status=job_data)
860
861
862 def perform_reboot(module, session_obj):
863 force_reboot = module.params.get("force_reboot")
864 payload = {"ResetType": "ForceRestart" if force_reboot else "GracefulRestart"}
865 job_resp_status, reset_status, reset_fail = wait_for_redfish_reboot_job(session_obj, SYSTEM_ID, payload=payload)
866 if reset_status and job_resp_status:
867 job_uri = MANAGER_JOB_ID_URI_10.format(job_resp_status["Id"])
868 resp, msg = wait_for_job_completion(session_obj, job_uri, wait_timeout=module.params.get("job_wait_timeout"))
869 if resp:
870 job_data = strip_substr_dict(resp.json_data)
871 if force_reboot and job_data["JobState"] == "Failed":
872 perform_force_reboot(module, session_obj)
873 else:
874 resp = session_obj.invoke_request("GET", job_uri)
875 job_data = strip_substr_dict(resp.json_data)
876 module.exit_json(msg=msg, job_status=job_data)
877
878
879 def perform_reboot_all(module: RedfishAnsibleModule, session_obj: Redfish, gt9: bool):
880 if gt9:
881 reboot_gte_idrac10(module, session_obj, module.params.get("force_reboot"))
882 else:
883 perform_reboot(module, session_obj)
884
885
886 def reboot_gte_idrac10(module: RedfishAnsibleModule, session_obj: Redfish, force_reboot: bool):
887 SYSTEM_RESET_URI = "/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset"
888 payload = {"ResetType": "ForceRestart" if force_reboot else "GracefulRestart"}
889 resp = session_obj.invoke_request('POST', SYSTEM_RESET_URI, data=payload, api_timeout=120)
890 if resp.status_code != 204:
891 module.exit_json(msg=REBOOT_FAIL +
892 " Virtual Disk creation task has been created and will run" +
893 " when the server is rebooted again.",
894 changed=True,
895 failed=True)
896
897
898 def check_job_tracking_required(module, session_obj, reboot_required, controller_id, greater_version):
899 job_wait = module.params.get("job_wait")
900 apply_time = None
901 if controller_id:
902 apply_time = get_apply_time(module, session_obj, controller_id, greater_version)
903 if job_wait:
904 if apply_time == "OnReset" and not reboot_required:
905 return False
906 return True
907 return False
908
909
910 def track_job(module, session_obj, job_id, job_url):
911 resp, msg = wait_for_job_completion(session_obj, job_url,
912 wait_timeout=module.params.get("job_wait_timeout"))
913 if resp:
914 job_data = strip_substr_dict(resp.json_data)
915 if job_data["JobState"] == "Failed":
916 changed, failed = False, True
917 module.exit_json(msg=JOB_FAILURE_PROGRESS_MSG, task={"id": job_id, "uri": job_url},
918 changed=changed, job_status=job_data, failed=failed)
919 elif job_data["JobState"] == "Scheduled":
920 task_status = {"uri": job_url, "id": job_id}
921 module.exit_json(msg=JOB_SUBMISSION, task=task_status, job_status=job_data, changed=True)
922 else:
923 changed, failed = True, False
924 module.exit_json(msg=JOB_COMPLETION, task={"id": job_id, "uri": job_url},
925 changed=changed, job_status=job_data, failed=failed)
926 else:
927 module.exit_json(msg=msg)
928
929
930 def validate_negative_job_time_out(module):
931 if module.params.get("job_wait") and module.params.get("job_wait_timeout") <= 0:
932 module.exit_json(msg=TIMEOUT_NEGATIVE_OR_ZERO_MSG, failed=True)
933
934
935 def is_fw_ver_greater(session_obj):
936 firmware_details = session_obj.get_server_generation
937 server_hw_model = firmware_details[2]
938 version = firmware_details[1]
939 hw_model_gt_9: bool = server_hw_model != "iDRAC 9"
940 if server_hw_model in ['iDRAC 9', 'iDRAC 10'] and LooseVersion(version) >= '1.0':
941 return True, hw_model_gt_9
942 else:
943 return False, hw_model_gt_9
944
945
946 def main():
947 specs = {
948 "state": {"type": "str", "required": False, "choices": ['present', 'absent']},
949 "command": {"type": "str", "required": False, "choices": ['initialize']},
950 "volume_type": {"type": "str", "required": False,
951 "choices": ['NonRedundant', 'Mirrored',
952 'StripedWithParity', 'SpannedMirrors',
953 'SpannedStripesWithParity']},
954 "raid_type": {"type": "str", "required": False,
955 "choices": ['RAID0', 'RAID1', 'RAID5',
956 'RAID6', 'RAID10', 'RAID50', 'RAID60']},
957 "name": {"required": False, "type": "str", "aliases": ['volume_name']},
958 "controller_id": {"required": False, "type": "str"},
959 "drives": {"elements": "str", "required": False, "type": "list"},
960 "block_size_bytes": {"required": False, "type": "int"},
961 "capacity_bytes": {"required": False, "type": "str"},
962 "optimum_io_size_bytes": {"required": False, "type": "int"},
963 "encryption_types": {"type": "str", "required": False,
964 "choices": ['NativeDriveEncryption', 'ControllerAssisted', 'SoftwareAssisted']},
965 "encrypted": {"required": False, "type": "bool"},
966 "volume_id": {"required": False, "type": "str"},
967 "oem": {"required": False, "type": "dict"},
968 "initialize_type": {"type": "str", "required": False, "choices": ['Fast', 'Slow'], "default": "Fast"},
969 "apply_time": {"required": False, "type": "str", "choices": ['Immediate', 'OnReset']},
970 "reboot_server": {"required": False, "type": "bool", "default": False},
971 "force_reboot": {"required": False, "type": "bool", "default": False},
972 "job_wait": {"required": False, "type": "bool", "default": False},
973 "job_wait_timeout": {"required": False, "type": "int", "default": 1200}
974 }
975 module = RedfishAnsibleModule(
976 argument_spec=specs,
977 mutually_exclusive=[['state', 'command'], ['volume_type', 'raid_type']],
978 required_one_of=[['state', 'command']],
979 required_if=[['command', 'initialize', ['volume_id']],
980 ['state', 'absent', ['volume_id']], ],
981 supports_check_mode=True)
982
983 try:
984 validate_inputs(module)
985 validate_negative_job_time_out(module)
986 with Redfish(module.params, req_session=True) as session_obj:
987 greater_version, gt9 = is_fw_ver_greater(session_obj)
988 fetch_storage_resource(module, session_obj)
989 controller_id = module.params.get("controller_id")
990 volume_id = module.params.get("volume_id")
991 reboot_server = module.params.get("reboot_server")
992 reboot_required = module.params.get("reboot_required")
993 if controller_id:
994 uri = CONTROLLER_URI.format(storage_base_uri=storage_collection_map["storage_base_uri"], controller_id=controller_id)
995 resp = check_specified_identifier_exists_in_the_system(module, session_obj, uri, CONTROLLER_NOT_EXIST_ERROR.format(controller_id=controller_id))
996 reboot_required = check_apply_time_supported_and_reboot_required(module, session_obj, controller_id, greater_version)
997 status_message = configure_raid_operation(module, session_obj, greater_version)
998 if volume_id and reboot_server:
999 controller_id = volume_id.split(":")[-1]
1000 uri = CONTROLLER_URI.format(storage_base_uri=storage_collection_map["storage_base_uri"], controller_id=controller_id)
1001 resp = check_specified_identifier_exists_in_the_system(module, session_obj, uri, CONTROLLER_NOT_EXIST_ERROR.format(controller_id=controller_id))
1002 reboot_required = check_apply_time_supported_and_reboot_required(module, session_obj, controller_id, greater_version)
1003 if reboot_required:
1004 perform_reboot_all(module, session_obj, gt9)
1005 if status_message.get("task_id"):
1006 job_tracking_required = check_job_tracking_required(module, session_obj, reboot_required, controller_id, greater_version)
1007 job_id = status_message.get("task_id")
1008 job_url = MANAGER_JOB_ID_URI_10.format(job_id)
1009 if job_tracking_required and job_id:
1010 track_job(module, session_obj, job_id, job_url)
1011 else:
1012 task_status = {"uri": job_url, "id": job_id}
1013 resp = session_obj.invoke_request("GET", job_url)
1014 job_data = strip_substr_dict(resp.json_data)
1015 module.exit_json(msg=status_message["msg"], task=task_status, job_status=job_data, changed=True)
1016 else:
1017 module.exit_json(msg=status_message["msg"])
1018 except HTTPError as err:
1019 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
1020 except URLError as err:
1021 module.exit_json(msg=str(err), unreachable=True)
1022 except (SSLValidationError, ConnectionError, ImportError, ValueError,
1023 RuntimeError, TypeError, OSError, SSLError) as err:
1024 module.exit_json(msg=str(err), failed=True)
1025
1026
1027 if __name__ == '__main__':
1028 main()