Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/idrac_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) 2024-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: idrac_storage_volume
19 short_description: Configures the RAID configuration attributes
20 version_added: "9.1.0"
21 description:
22 - This module is responsible for configuring the RAID attributes.
23 extends_documentation_fragment:
24 - dellemc.openmanage.idrac_x_auth_options
25 options:
26 state:
27 type: str
28 description:
29 - C(create), performs create volume operation.
30 - C(delete), performs remove volume operation.
31 - C(view), returns storage view.
32 choices: ['create', 'delete', 'view']
33 default: 'view'
34 span_depth:
35 type: int
36 description:
37 - Number of spans in the RAID configuration.
38 - I(span_depth) is required for C(create) and its value depends on I(volume_type).
39 default: 1
40 span_length:
41 type: int
42 description:
43 - Number of disks in a span.
44 - I(span_length) is required for C(create) and its value depends on I(volume_type).
45 default: 1
46 number_dedicated_hot_spare:
47 type: int
48 description: Number of Dedicated Hot Spare.
49 default: 0
50 volume_type:
51 type: str
52 description: Provide the the required RAID level.
53 choices: ['RAID 0', 'RAID 1', 'RAID 5', 'RAID 6', 'RAID 10', 'RAID 50', 'RAID 60']
54 default: 'RAID 0'
55 disk_cache_policy:
56 type: str
57 description: Disk Cache Policy.
58 choices: ["Default", "Enabled", "Disabled"]
59 default: "Default"
60 write_cache_policy:
61 type: str
62 description: Write cache policy.
63 choices: ["WriteThrough", "WriteBack", "WriteBackForce"]
64 default: "WriteThrough"
65 read_cache_policy:
66 type: str
67 description: Read cache policy.
68 choices: ["NoReadAhead", "ReadAhead", "AdaptiveReadAhead"]
69 default: "NoReadAhead"
70 stripe_size:
71 type: int
72 description: Stripe size value to be provided in multiples of 64 * 1024.
73 default: 65536
74 controller_id:
75 type: str
76 description:
77 - Fully Qualified Device Descriptor (FQDD) of the storage controller, for example 'RAID.Integrated.1-1'.
78 Controller FQDD is required for C(create) RAID configuration.
79 media_type:
80 type: str
81 description: Media type.
82 choices: ['HDD', 'SSD']
83 protocol:
84 type: str
85 description: Bus protocol.
86 choices: ['SAS', 'SATA', 'PCIE']
87 volume_id:
88 type: str
89 description:
90 - Fully Qualified Device Descriptor (FQDD) of the virtual disk, for example 'Disk.virtual.0:RAID.Slot.1-1'.
91 This option is used to get the virtual disk information.
92 volumes:
93 type: list
94 elements: dict
95 description:
96 - A list of virtual disk specific iDRAC attributes. This is applicable for C(create) and C(delete) operations.
97 - For C(create) operation, name and drives are applicable options, other volume options can also be specified.
98 - The drives is a required option for C(create) operation and accepts either location (list of drive slot)
99 or id (list of drive fqdd).
100 - In iDRAC8, there is no pre-validation for the state of drives. The disk ID or slot number of the drive
101 provided may or may not be in Ready state. Enter the disk ID or slot number of the drive that is already
102 in Ready state.
103 - For C(delete) operation, only name option is applicable.
104 - See the examples for more details.
105 capacity:
106 type: float
107 description: Virtual disk size in GB.
108 raid_reset_config:
109 type: str
110 description:
111 - This option represents whether a reset config operation needs to be performed on the RAID controller.
112 Reset Config operation deletes all the virtual disks present on the RAID controller.
113 choices: ['true', 'false']
114 default: 'false'
115 raid_init_operation:
116 type: str
117 description: This option represents initialization configuration operation to be performed on the virtual disk.
118 choices: [None, Fast]
119 job_wait:
120 description:
121 - This parameter provides the option to wait for the job completion.
122 - This is applicable when I(state) is C(create) or C(delete).
123 type: bool
124 default: true
125 job_wait_timeout:
126 description:
127 - This parameter is the maximum wait time of I(job_wait) in seconds.
128 - This option is applicable when I(job_wait) is C(true).
129 type: int
130 default: 900
131 time_to_wait:
132 description:
133 - The maximum wait time before shutdown in seconds for the Server Configuration Profile (SCP) import operation.
134 - This option is applicable when I(state) is C(create) or C(delete).
135 type: int
136 default: 300
137
138 requirements:
139 - "python >= 3.9.6"
140 author:
141 - "Felix Stephen (@felixs88)"
142 - "Kritika Bhateja (@Kritika-Bhateja-03)"
143 - "Abhishek Sinha(@ABHISHEK-SINHA10)"
144 - "Akash Shendge(@shenda1)"
145 notes:
146 - Run this module from a system that has direct access to Integrated Dell Remote Access Controller.
147 - This module supports both IPv4 and IPv6 address for I(idrac_ip).
148 - This module supports C(check_mode).
149 - This module does not display the controller battery details for the C(view) operation of the storage in iDRAC8.
150 '''
151
152 EXAMPLES = r'''
153 ---
154 - name: Create single volume
155 dellemc.openmanage.idrac_storage_volume:
156 idrac_ip: "192.168.0.1"
157 idrac_user: "username"
158 idrac_password: "password"
159 ca_path: "/path/to/ca_cert.pem"
160 state: "create"
161 controller_id: "RAID.Slot.1-1"
162 volumes:
163 - drives:
164 location: [5]
165
166 - name: Create multiple volume
167 dellemc.openmanage.idrac_storage_volume:
168 idrac_ip: "192.168.0.1"
169 idrac_user: "username"
170 idrac_password: "password"
171 ca_path: "/path/to/ca_cert.pem"
172 raid_reset_config: "True"
173 state: "create"
174 controller_id: "RAID.Slot.1-1"
175 volume_type: "RAID 1"
176 span_depth: 1
177 span_length: 2
178 number_dedicated_hot_spare: 1
179 disk_cache_policy: "Enabled"
180 write_cache_policy: "WriteBackForce"
181 read_cache_policy: "ReadAhead"
182 stripe_size: 65536
183 capacity: 100
184 raid_init_operation: "Fast"
185 volumes:
186 - name: "volume_1"
187 drives:
188 id: ["Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-1", "Disk.Bay.2:Enclosure.Internal.0-1:RAID.Slot.1-1"]
189 - name: "volume_2"
190 volume_type: "RAID 5"
191 span_length: 3
192 span_depth: 1
193 drives:
194 location: [7, 3, 5]
195 disk_cache_policy: "Disabled"
196 write_cache_policy: "WriteBack"
197 read_cache_policy: "NoReadAhead"
198 stripe_size: 131072
199 capacity: "200"
200 raid_init_operation: "None"
201
202 - name: View all volume details
203 dellemc.openmanage.idrac_storage_volume:
204 idrac_ip: "192.168.0.1"
205 idrac_user: "username"
206 idrac_password: "password"
207 ca_path: "/path/to/ca_cert.pem"
208 state: "view"
209
210 - name: View specific volume details
211 dellemc.openmanage.idrac_storage_volume:
212 idrac_ip: "192.168.0.1"
213 idrac_user: "username"
214 idrac_password: "password"
215 ca_path: "/path/to/ca_cert.pem"
216 state: "view"
217 controller_id: "RAID.Slot.1-1"
218 volume_id: "Disk.Virtual.0:RAID.Slot.1-1"
219
220 - name: Delete single volume
221 dellemc.openmanage.idrac_storage_volume:
222 idrac_ip: "192.168.0.1"
223 idrac_user: "username"
224 idrac_password: "password"
225 ca_path: "/path/to/ca_cert.pem"
226 state: "delete"
227 volumes:
228 - name: "volume_1"
229
230 - name: Delete multiple volume
231 dellemc.openmanage.idrac_storage_volume:
232 idrac_ip: "192.168.0.1"
233 idrac_user: "username"
234 idrac_password: "password"
235 ca_path: "/path/to/ca_cert.pem"
236 state: "delete"
237 volumes:
238 - name: "volume_1"
239 - name: "volume_2"
240 '''
241
242 RETURN = r'''
243 ---
244 msg:
245 type: str
246 description: Overall status of the storage configuration operation.
247 returned: always
248 sample: "Successfully completed the view storage volume operation"
249 storage_status:
250 type: dict
251 description: Storage configuration job and progress details from the iDRAC.
252 returned: success
253 sample:
254 {
255 "Id": "JID_XXXXXXXXX",
256 "JobState": "Completed",
257 "JobType": "ImportConfiguration",
258 "Message": "Successfully imported and applied Server Configuration Profile.",
259 "MessageId": "XXX123",
260 "Name": "Import Configuration",
261 "PercentComplete": 100,
262 "StartTime": "TIME_NOW",
263 "TargetSettingsURI": null,
264 }
265 error_info:
266 description: Details of the HTTP Error.
267 returned: on HTTP error
268 type: dict
269 sample: {
270 "error": {
271 "code": "Base.1.0.GeneralError",
272 "message": "A general error has occurred. See ExtendedInfo for more information.",
273 "@Message.ExtendedInfo": [
274 {
275 "MessageId": "GEN1234",
276 "RelatedProperties": [],
277 "Message": "Unable to process the request because an error occurred.",
278 "MessageArgs": [],
279 "Severity": "Critical",
280 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
281 }
282 ]
283 }
284 }
285 '''
286
287 import re
288 import operator
289 from urllib.error import HTTPError, URLError
290 from copy import deepcopy
291 from ansible_collections.dellemc.openmanage.plugins.module_utils.idrac_redfish import iDRACRedfishAPI, IdracAnsibleModule
292 from ansible.module_utils.urls import ConnectionError, SSLValidationError
293 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import (
294 get_dynamic_uri, validate_and_get_first_resource_id_uri, xml_data_conversion, idrac_redfish_job_tracking, remove_key, get_idrac_firmware_version)
295
296
297 SYSTEMS_URI = "/redfish/v1/Systems"
298 iDRAC_JOB_URI = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs/{job_id}"
299 CONTROLLER_NOT_EXIST_ERROR = "Specified Controller {controller_id} does not exist in the System."
300 CONTROLLER_NOT_DEFINED = "Controller ID is required."
301 SUCCESSFUL_OPERATION_MSG = "Successfully completed the {operation} storage volume operation."
302 DRIVES_NOT_EXIST_ERROR = "No Drive(s) are attached to the specified Controller Id: {controller_id}."
303 DRIVES_NOT_MATCHED = "Following Drive(s) {specified_drives} are not attached to the specified Controller Id: {controller_id}."
304 NEGATIVE_OR_ZERO_MSG = "The value for the `{parameter}` parameter cannot be negative or zero."
305 NEGATIVE_MSG = "The value for the `{parameter}` parameter cannot be negative."
306 INVALID_VALUE_MSG = "The value for the `{parameter}` parameter is invalid."
307 ID_AND_LOCATION_BOTH_DEFINED = "Either id or location is allowed."
308 ID_AND_LOCATION_BOTH_NOT_DEFINED = "Either id or location should be specified."
309 DRIVES_NOT_DEFINED = "Drives must be defined for volume creation."
310 NOT_ENOUGH_DRIVES = "Number of sufficient disks not found in Controller '{controller_id}'!"
311 WAIT_TIMEOUT_MSG = "The job is not complete after {0} seconds."
312 TIME_TO_WAIT_MSG = "Time to wait value is invalid. Minimum value is 300 and Maximum is 3600 seconds."
313 JOB_TRIGERRED = "Successfully triggered the {0} storage volume operation."
314 VOLUME_NAME_REQUIRED_FOR_DELETE = "Virtual disk name is a required parameter for remove virtual disk operations."
315 VOLUME_NOT_FOUND = "Unable to find the virtual disk."
316 CHANGES_NOT_FOUND = "No changes found to commit!"
317 CHANGES_FOUND = "Changes found to commit!"
318 ODATA_ID = "@odata.id"
319 ODATA_REGEX = "(.*?)@odata"
320 ATTRIBUTE = "</Attribute>"
321 VIEW_OPERATION_FAILED = "Failed to fetch storage details."
322 VIEW_CONTROLLER_DETAILS_NOT_FOUND = "Failed to find the controller {controller_id}."
323 VIEW_OPERATION_CONTROLLER_NOT_SPECIFIED = "Controller identifier parameter is missing."
324 VIEW_VIRTUAL_DISK_DETAILS_NOT_FOUND = "Failed to find the volume : {volume_id} in controller : {controller_id}."
325 SUCCESS_STATUS = "Success"
326 FAILED_STATUS = "Failed"
327 ERROR_CODES = ["SYS041", "SYS044", "SYS045", "SYS046", "SYS047", "SYS048", "SYS050", "SYS051", "SYS062",
328 "SYS063", "SYS064", "SYS065", "SYS067", "SYS068", "SYS070", "SYS071", "SYS072",
329 "SYS073", "SYS075", "SYS076", "SYS077", "SYS078", "SYS079", "SYS080"]
330
331
332 class StorageBase:
333 def __init__(self, idrac, module):
334 self.module_ext_params = self.module_extend_input(module)
335 self.idrac = idrac
336 self.module = module
337
338 def data_conversion(self, module, each_volume):
339 volume_related_input = [
340 'volume_type', 'span_length', 'span_depth',
341 'number_dedicated_hot_spare', 'disk_cache_policy',
342 'write_cache_policy', 'read_cache_policy', 'stripe_size',
343 'capacity', 'raid_init_operation', 'protocol', 'media_type'
344 ]
345 for key in volume_related_input:
346 value = module.params.get(key)
347 if key not in each_volume:
348 each_volume[key] = value
349 return each_volume
350
351 def module_extend_input(self, module):
352 """
353 Extends the input module with additional volume-related parameters.
354
355 Args:
356 module (object): The module object.
357
358 Returns:
359 object: The updated module object.
360 """
361
362 module_copy = deepcopy(module.params)
363 volumes = module_copy.get('volumes')
364 if volumes:
365 for index in range(len(volumes)):
366 volumes[index] = self.data_conversion(module, volumes[index])
367 else:
368 tmp_volume = self.data_conversion(module, {})
369 required_pd = int(module_copy.get('span_length', 1)) * int(module_copy.get('span_depth', 1))
370 tmp_volume['drives'] = {'id': [(-i) for i in range(1, required_pd + 1)]}
371 module_copy['volumes'] = [tmp_volume]
372
373 int_input = ['span_length', 'span_depth', 'number_dedicated_hot_spare',
374 'stripe_size']
375 if volumes:
376 for each_volume in volumes:
377 for each_input in each_volume:
378 if each_input in int_input:
379 each_volume[each_input] = int(each_volume[each_input])
380 return module_copy
381
382 def payload_for_disk(self, volume):
383 disk_payload = ''
384 if 'drives' in volume and 'id' in volume['drives']:
385 for each_pd_id in volume['drives']['id']:
386 scp = '<Attribute Name="IncludedPhysicalDiskID">{id}</Attribute>'.format(id=each_pd_id)
387 disk_payload = disk_payload + scp
388 if 'dedicated_hot_spare' in volume:
389 for each_dhs in volume['dedicated_hot_spare']:
390 scp = '<Attribute Name="RAIDdedicatedSpare">{id}</Attribute>'.format(id=each_dhs)
391 disk_payload = disk_payload + scp
392 return disk_payload
393
394 def construct_volume_payload(self, vd_id, volume):
395
396 """
397 Constructs a payload dictionary for the given key mappings.
398
399 Returns:
400 dict: The constructed payload dictionary.
401 """
402 key_mapping: dict = {
403 'raid_init_operation': 'RAIDinitOperation',
404 'state': "RAIDaction",
405 'disk_cache_policy': "DiskCachePolicy",
406 'write_cache_policy': "RAIDdefaultWritePolicy",
407 'read_cache_policy': "RAIDdefaultReadPolicy",
408 'stripe_size': "StripeSize",
409 'span_depth': "SpanDepth",
410 'span_length': "SpanLength",
411 'volume_type': "RAIDTypes",
412 'name': 'Name',
413 'capacity': 'Size',
414 }
415 controller_id = self.module_ext_params.get("controller_id")
416 state = self.module_ext_params.get("state")
417 # Including state in each_volume as it mapped to RAIDaction
418 volume.update({'state': state.capitalize()})
419 payload = ''
420 attr = {}
421 vdfqdd = "Disk.Virtual.{0}:{1}".format(vd_id, controller_id)
422 for key in volume:
423 if volume[key] and key in key_mapping:
424 attr[key_mapping[key]] = volume[key]
425 disk_paylod = self.payload_for_disk(volume)
426 payload = xml_data_conversion(attr, vdfqdd, disk_paylod)
427 return payload
428
429 def constuct_payload(self, name_id_mapping):
430 number_of_existing_vd = len(name_id_mapping)
431 volume_payload, attr = '', {}
432 raid_reset_config_value = self.module_ext_params.get('raid_reset_config')
433 raid_key_mapping = {'raid_reset_config': 'RAIDresetConfig'}
434 if raid_reset_config_value == 'true':
435 raid_reset_config_value = 'True'
436 attr = {raid_key_mapping['raid_reset_config']: raid_reset_config_value}
437 for each_volume in self.module_ext_params.get('volumes'):
438 volume_payload = volume_payload + self.construct_volume_payload(number_of_existing_vd,
439 each_volume)
440 number_of_existing_vd = number_of_existing_vd + 1
441 raid_payload = xml_data_conversion(attr, self.module_ext_params.get('controller_id'), volume_payload)
442 return raid_payload
443
444 def wait_for_job_completion(self, job_resp):
445 job_wait = self.module_ext_params.get('job_wait')
446 job_wait_timeout = self.module_ext_params.get('job_wait_timeout')
447 job_dict = {}
448 if (job_tracking_uri := job_resp.headers.get("Location")):
449 job_id = job_tracking_uri.split("/")[-1]
450 job_uri = iDRAC_JOB_URI.format(job_id=job_id)
451 if job_wait:
452 job_failed, msg, job_dict, wait_time = idrac_redfish_job_tracking(self.idrac, job_uri,
453 max_job_wait_sec=job_wait_timeout,
454 sleep_interval_secs=1)
455 job_dict = remove_key(job_dict, regex_pattern=ODATA_REGEX)
456 if int(wait_time) >= int(job_wait_timeout):
457 self.module.exit_json(msg=WAIT_TIMEOUT_MSG.format(job_wait_timeout), changed=True, storage_status=job_dict)
458 if job_failed or job_dict.get("MessageId", "") in ERROR_CODES:
459 self.module.exit_json(msg=job_dict.get("Message"), storage_status=job_dict, failed=True)
460 else:
461 job_resp = self.idrac.invoke_request(job_uri, 'GET')
462 job_dict = job_resp.json_data
463 job_dict = remove_key(job_dict, regex_pattern=ODATA_REGEX)
464 self.module.exit_json(msg=JOB_TRIGERRED.format(self.module.params.get('state')), storage_status=job_dict, changed=True)
465 return job_dict
466
467
468 class StorageData:
469 def __init__(self, idrac, module):
470 self.idrac = idrac
471 self.module = module
472
473 def fetch_controllers_uri(self):
474 uri, err_msg = validate_and_get_first_resource_id_uri(
475 self.module, self.idrac, SYSTEMS_URI)
476 if err_msg:
477 self.module.exit_json(msg=err_msg, failed=True)
478 storage_controllers = get_dynamic_uri(self.idrac, uri, 'Storage')
479 return storage_controllers
480
481 def fetch_api_data(self, uri, key_index_from_end):
482 key = uri.split("/")[key_index_from_end]
483 uri_data = self.idrac.invoke_request(uri, "GET")
484 return key, uri_data
485
486 def all_storage_data(self):
487 storage_info = {"Controllers": {}}
488 controllers_details_uri = self.fetch_controllers_uri()[ODATA_ID] + "?$expand=*($levels=1)"
489 controllers_list = get_dynamic_uri(self.idrac, controllers_details_uri)
490 for each_controller in controllers_list["Members"]:
491 controller_id = each_controller.get("Id")
492 if controller_id.startswith("CPU"):
493 continue
494 storage_info["Controllers"][controller_id] = deepcopy(each_controller)
495 storage_info["Controllers"][controller_id]["Drives"] = {}
496 storage_info["Controllers"][controller_id]["Volumes"] = {}
497 storage_info["Controllers"][controller_id]["Links"]["Enclosures"] = {}
498 # To fetch drives data
499 for each_drive_uri in each_controller["Drives"]:
500 key, uri_data = self.fetch_api_data(each_drive_uri[ODATA_ID], -1)
501 storage_info["Controllers"][controller_id]["Drives"][key] = uri_data.json_data
502
503 # To fetch volumes data
504 volume_uri = each_controller['Volumes'][ODATA_ID]
505 volumes_list = get_dynamic_uri(self.idrac, volume_uri, "Members")
506 for each_volume_uri in volumes_list:
507 key, uri_data = self.fetch_api_data(each_volume_uri[ODATA_ID], -1)
508 storage_info["Controllers"][controller_id]["Volumes"][key] = uri_data.json_data
509 # To fetch enclosures
510 for each_enclosure_uri in each_controller["Links"]["Enclosures"]:
511 key, uri_data = self.fetch_api_data(each_enclosure_uri[ODATA_ID], -1)
512 storage_info["Controllers"][controller_id]["Links"]["Enclosures"][key] = uri_data.json_data
513 return storage_info
514
515 def fetch_storage_data(self):
516 storage_info = {"Controller": {}}
517 storage_data = self.all_storage_data()
518 firm_ver = get_idrac_firmware_version(self.idrac)
519 for controller_id, controller_data in storage_data["Controllers"].items():
520 storage_info["Controller"][controller_id] = {
521 "ControllerSensor": {controller_id: {}}
522 }
523 if firm_ver >= "3.00":
524 battery_data = controller_data["Oem"]["Dell"].get("DellControllerBattery")
525 if battery_data:
526 storage_info["Controller"][controller_id]["ControllerSensor"][controller_id]["ControllerBattery"] = [battery_data["Id"]]
527 self.fetch_volumes(controller_id, controller_data, storage_info)
528 self.fetch_enclosures_and_physical_disk(controller_id, controller_data, storage_info)
529 return storage_info
530
531 def fetch_volumes(self, controller_id, controller_data, storage_info):
532 if controller_data["Volumes"]:
533 storage_info.setdefault("Controller", {}).setdefault(controller_id, {})["VirtualDisk"] = {}
534 for volume_id, volume_data in controller_data["Volumes"].items():
535 physical_disk = [self.fetch_api_data(drive[ODATA_ID], -1)[0] for drive in volume_data["Links"]["Drives"]]
536 storage_info["Controller"][controller_id]["VirtualDisk"][volume_id] = {"PhysicalDisk": physical_disk}
537
538 def fetch_enclosures_and_physical_disk(self, controller_id, controller_data, storage_info):
539 enclosures = [enclosure_id for enclosure_id in controller_data["Links"]["Enclosures"].keys() if enclosure_id.startswith("Enclosure")]
540 if len(enclosures) >= 1:
541 storage_info.setdefault("Controller", {})
542 storage_info["Controller"].setdefault(controller_id, {})
543 storage_info["Controller"][controller_id].setdefault("Enclosure", {})
544 for enclosure_id in enclosures:
545 storage_info["Controller"][controller_id]["Enclosure"][enclosure_id] = {"EnclosureSensor": {enclosure_id: {}}}
546 physical_disk = [self.fetch_api_data(drive[ODATA_ID], -1)[0] for drive in
547 controller_data["Links"]["Enclosures"][enclosure_id]["Links"]["Drives"]]
548 if physical_disk:
549 storage_info["Controller"][controller_id]["Enclosure"][enclosure_id]["PhysicalDisk"] = physical_disk
550 else:
551 if controller_data["Drives"].keys():
552 storage_info["Controller"][controller_id]["PhysicalDisk"] = list(controller_data["Drives"].keys())
553
554
555 class StorageValidation(StorageBase):
556 def __init__(self, idrac, module):
557 super().__init__(idrac, module)
558 self.idrac_data = StorageData(idrac, module).all_storage_data()
559 self.controller_id = module.params.get("controller_id")
560
561 def validate_time_to_wait(self):
562 to_wait = self.module_ext_params.get("time_to_wait")
563 if to_wait < 300 or to_wait > 3600:
564 self.module.exit_json(msg=TIME_TO_WAIT_MSG, failed=True)
565
566 def validate_controller_exists(self):
567 if not self.controller_id:
568 self.module.exit_json(msg=CONTROLLER_NOT_DEFINED, failed=True)
569 controllers = self.idrac_data["Controllers"]
570 if self.controller_id not in controllers.keys():
571 self.module.exit_json(msg=CONTROLLER_NOT_EXIST_ERROR.format(controller_id=self.controller_id), failed=True)
572
573 def validate_job_wait_negative_values(self):
574 if self.module_ext_params.get("job_wait") and self.module_ext_params.get("job_wait_timeout") <= 0:
575 self.module.exit_json(msg=NEGATIVE_OR_ZERO_MSG.format(parameter="job_wait_timeout"), failed=True)
576
577 def validate_negative_values_for_volume_params(self, each_volume):
578 inner_params = ["span_depth", "span_length", "capacity", "strip_size"]
579 for param in inner_params:
580 value = each_volume.get(param)
581 if value is not None and value <= 0:
582 self.module.exit_json(msg=NEGATIVE_OR_ZERO_MSG.format(parameter=param), failed=True)
583 if each_volume.get("number_dedicated_hot_spare") < 0:
584 self.module.exit_json(msg=NEGATIVE_MSG.format(parameter="number_dedicated_hot_spare"), failed=True)
585
586 def validate_volume_drives(self, specified_volume):
587 specified_drives = specified_volume.get("drives")
588 if not specified_drives:
589 self.module.exit_json(msg=DRIVES_NOT_DEFINED, failed=True)
590 if specified_drives.get("id") and specified_drives.get("location"):
591 self.module.exit_json(msg=ID_AND_LOCATION_BOTH_DEFINED, failed=True)
592 elif "id" not in specified_drives and "location" not in specified_drives:
593 self.module.exit_json(msg=ID_AND_LOCATION_BOTH_NOT_DEFINED, failed=True)
594 drives_count = len(specified_drives.get("location")) if specified_drives.get("location") is not None else len(specified_drives.get("id"))
595 return self.raid_std_validation(specified_volume.get("span_length"),
596 specified_volume.get("span_depth"),
597 specified_volume.get("volume_type"),
598 drives_count)
599
600 def raid_std_validation(self, span_length, span_depth, volume_type, pd_count):
601 raid_std = {
602 "RAID 0": {'pd_slots': range(1, 2), 'span_length': 1, 'checks': operator.ge, 'span_depth': 1},
603 "RAID 1": {'pd_slots': range(1, 3), 'span_length': 2, 'checks': operator.eq, 'span_depth': 1},
604 "RAID 5": {'pd_slots': range(1, 4), 'span_length': 3, 'checks': operator.ge, 'span_depth': 1},
605 "RAID 6": {'pd_slots': range(1, 5), 'span_length': 4, 'checks': operator.ge, 'span_depth': 1},
606 "RAID 10": {'pd_slots': range(1, 5), 'span_length': 2, 'checks': operator.ge, 'span_depth': 2},
607 "RAID 50": {'pd_slots': range(1, 7), 'span_length': 3, 'checks': operator.ge, 'span_depth': 2},
608 "RAID 60": {'pd_slots': range(1, 9), 'span_length': 4, 'checks': operator.ge, 'span_depth': 2}
609 }
610 raid_info = raid_std.get(volume_type)
611 if not raid_info.get('checks')(span_length, raid_info.get('span_length')):
612 self.module.exit_json(msg=INVALID_VALUE_MSG.format(parameter="span_length"), failed=True)
613 if volume_type in ["RAID 0", "RAID 1", "RAID 5", "RAID 6"] and operator.ne(span_depth, raid_info.get('span_depth')):
614 self.module.exit_json(msg=INVALID_VALUE_MSG.format(parameter="span_depth"), failed=True)
615 if volume_type in ["RAID 10", "RAID 50", "RAID 60"] and operator.lt(span_depth, raid_info.get('span_depth')):
616 self.module.exit_json(msg=INVALID_VALUE_MSG.format(parameter="span_depth"), failed=True)
617 if not operator.eq(pd_count, span_depth * span_length):
618 self.module.exit_json(msg=INVALID_VALUE_MSG.format(parameter="drives"), failed=True)
619 return True
620
621
622 class StorageCreate(StorageValidation):
623 def disk_slot_location_to_id_conversion(self, each_volume):
624 drives = {}
625 if "location" in each_volume['drives']:
626 regex_pattern = r"\d+"
627 physical_disk = self.idrac_data["Controllers"][self.controller_id]["Drives"]
628 slot_id_mapping = {int(re.search(regex_pattern, key).group()): key for key in physical_disk.keys()}
629 drives['id'] = [slot_id_mapping.get(each_pd) for each_pd in each_volume['drives']['location']
630 if slot_id_mapping.get(each_pd)]
631 elif "id" in each_volume['drives']:
632 drives['id'] = each_volume['drives']['id']
633 return drives
634
635 def perform_intersection_on_disk(self, each_volume, healthy_disk, available_disk,
636 media_type_supported_disk, protocol_supported_disk):
637 filtered_disk = healthy_disk
638 firm_ver = get_idrac_firmware_version(self.idrac)
639 if firm_ver >= "3.00":
640 filtered_disk = filtered_disk.intersection(available_disk)
641 if filtered_disk and each_volume.get('media_type'):
642 filtered_disk = filtered_disk.intersection(media_type_supported_disk)
643 if filtered_disk and each_volume.get('protocol'):
644 filtered_disk = filtered_disk.intersection(protocol_supported_disk)
645 return sorted(list(filtered_disk))
646
647 def filter_disk(self, each_volume):
648 disk_dict = self.idrac_data["Controllers"][self.controller_id]["Drives"]
649 healthy_disk = set()
650 available_disk = set()
651 media_type_supported_disk = set()
652 protocol_supported_disk = set()
653 raid_reset_config_value = self.module_ext_params.get('raid_reset_config')
654 raid_status_list = ["Ready", "NonRAID"]
655 if raid_reset_config_value == "true":
656 raid_status_list.append("Online")
657 for key, value in disk_dict.items():
658 if each_volume.get('media_type') and value.get('MediaType') == each_volume.get('media_type'):
659 media_type_supported_disk.add(key)
660 if each_volume.get('protocol') and value.get('Protocol') == each_volume.get('protocol'):
661 protocol_supported_disk.add(key)
662 status = value.get('Status', {}).get('Health', {})
663 if status == "OK":
664 healthy_disk.add(key)
665 raid_status = value.get('Oem', {}).get('Dell', {}).get('DellPhysicalDisk', {}).get('RaidStatus', {})
666 if raid_status in raid_status_list:
667 available_disk.add(key)
668 return self.perform_intersection_on_disk(each_volume, healthy_disk, available_disk,
669 media_type_supported_disk, protocol_supported_disk)
670
671 def updating_drives_module_input_when_given(self, each_volume, filter_disk_output):
672 updated_disk_id_list = []
673 if 'id' in each_volume['drives']:
674 for each_pd in each_volume['drives']['id']:
675 if each_pd in filter_disk_output:
676 updated_disk_id_list.append(each_pd)
677 return updated_disk_id_list
678
679 def updating_volume_module_input_for_hotspare(self, each_volume, filter_disk_output, reserved_pd, drives_exists_in_id):
680 tmp_list = []
681 if 'number_dedicated_hot_spare' in each_volume and each_volume['number_dedicated_hot_spare'] > 0:
682 for each_pd in filter_disk_output:
683 if each_pd not in reserved_pd and each_pd not in drives_exists_in_id:
684 tmp_list.append(each_pd)
685 if len(tmp_list) == each_volume['number_dedicated_hot_spare']:
686 break
687 return tmp_list
688
689 def updating_volume_module_input(self, drives_exists_in_id):
690 volumes = self.module_ext_params.get('volumes', [])
691 reserved_pd = []
692 for each in volumes:
693 required_pd = int(each['span_depth']) * int(each['span_length'])
694 filtered_disk = self.filter_disk(each)
695 if 'stripe_size' in each:
696 each['stripe_size'] = int(each['stripe_size'] / 512)
697
698 if each.get('capacity') is not None:
699 each['capacity'] = str(int(float(each['capacity']) * 1073741824))
700
701 if self.module.params.get('volumes') is None:
702 each['drives']['id'] = filtered_disk[:required_pd]
703
704 if 'drives' in each:
705 drives_id_list = self.updating_drives_module_input_when_given(each, filtered_disk)
706 reserved_pd += drives_id_list
707 each['drives']['id'] = drives_id_list
708
709 if 'number_dedicated_hot_spare' in each:
710 hotspare_disk_list = self.updating_volume_module_input_for_hotspare(each, filtered_disk, reserved_pd,
711 drives_exists_in_id)
712 reserved_pd += hotspare_disk_list
713 each['dedicated_hot_spare'] = hotspare_disk_list
714 self.validate_enough_drives_available(each)
715 if self.module.check_mode:
716 self.module.exit_json(msg=CHANGES_FOUND, changed=True)
717 self.module_ext_params['volumes'] = volumes
718
719 def validate_enough_drives_available(self, each_volume):
720 controller_id = self.module_ext_params.get('controller_id')
721 required_pd = each_volume['span_depth'] * each_volume['span_length']
722 drives_available = each_volume['drives']['id']
723 dedicated_hot_spare_required = int(each_volume['number_dedicated_hot_spare'])
724 dedicated_hot_spare_available = len(each_volume['dedicated_hot_spare'])
725 changed, failed = False, False
726 if (required_pd > len(drives_available) or dedicated_hot_spare_required != dedicated_hot_spare_available):
727 if not self.module.check_mode:
728 msg, failed = NOT_ENOUGH_DRIVES.format(controller_id=controller_id), True
729 else:
730 msg, changed = CHANGES_NOT_FOUND, False
731 self.module.exit_json(msg=msg, changed=changed, failed=failed)
732
733 def validate(self):
734 # Validate upper layer input
735 self.validate_time_to_wait()
736 self.validate_controller_exists()
737 self.validate_job_wait_negative_values()
738 # Validate std raid validation for inner layer
739 drives_exists_in_id = []
740 for each_volume in self.module_ext_params.get('volumes', []):
741 # Validatiing for negative values
742 self.validate_negative_values_for_volume_params(each_volume)
743 self.validate_volume_drives(each_volume)
744 if 'location' in each_volume['drives'] and each_volume['drives']['location']:
745 each_volume['drives'] = self.disk_slot_location_to_id_conversion(each_volume)
746 drives_exists_in_id += each_volume['drives']['id']
747 # Extendeding volume module input in module_ext_params for drives id and hotspare
748 self.updating_volume_module_input(drives_exists_in_id)
749
750 def execute(self):
751 self.validate()
752 job_dict = {}
753 name_id_mapping = {value.get('Name'): key for key, value in self.idrac_data["Controllers"][self.controller_id]["Volumes"].items()}
754 parent_payload = """<SystemConfiguration>{0}</SystemConfiguration>"""
755 payload = self.constuct_payload(name_id_mapping)
756 parent_payload = parent_payload.format(payload)
757 resp = self.idrac.import_scp(import_buffer=parent_payload, target=["RAID"], job_wait=False, time_to_wait=self.module.params.get('time_to_wait'))
758 job_dict = self.wait_for_job_completion(resp)
759 return job_dict
760
761
762 class StorageDelete(StorageValidation):
763 def check_even_single_given_volume_exists(self, volume_name_input_list):
764 for each_name in volume_name_input_list:
765 for cntrl_id, detail in self.idrac_data.get('Controllers').items():
766 for vol_id, volume in detail.get('Volumes').items():
767 if each_name == volume.get('Name'):
768 return True
769
770 def validate_volume_exists_in_server(self, volume_name_input_list):
771 changed, failed = False, False
772 single_volume_name_matched = self.check_even_single_given_volume_exists(volume_name_input_list)
773 if single_volume_name_matched:
774 if self.module.check_mode:
775 msg, changed = CHANGES_FOUND, True
776 else:
777 return
778 else:
779 msg, failed = VOLUME_NOT_FOUND, True
780 self.module.exit_json(msg=msg, failed=failed, changed=changed)
781
782 def validate(self):
783 # Validate upper layer input
784 self.validate_time_to_wait()
785 self.validate_job_wait_negative_values()
786
787 # Validate for volume and volume_name
788 if (not (volumes := self.module.params.get('volumes'))) or (volumes and not all("name" in each for each in volumes)):
789 self.module.exit_json(msg=VOLUME_NAME_REQUIRED_FOR_DELETE, failed=True)
790
791 def construct_payload_for_delete(self, cntrl_id_vd_id_mapping):
792 parent_payload = """<SystemConfiguration>{0}</SystemConfiguration>"""
793 raid_payload = ""
794 for each_controller, value in cntrl_id_vd_id_mapping.items():
795 volume_payload = ""
796 for each_value in value:
797 volume_payload += xml_data_conversion({'RAIDaction': 'Delete'}, each_value)
798 raid_payload += xml_data_conversion({}, each_controller, volume_payload)
799 parent_payload = parent_payload.format(raid_payload)
800 return parent_payload
801
802 def get_vd_id_based_on_controller_id_vd_name(self, user_volume_input_list):
803 cntrl_id_vd_id_mapping = {}
804 for cntrl_id, detail in self.idrac_data.get('Controllers').items():
805 for vd_id, volume in detail.get('Volumes').items():
806 if volume.get('Name') in user_volume_input_list:
807 if cntrl_id not in cntrl_id_vd_id_mapping:
808 cntrl_id_vd_id_mapping[cntrl_id] = [vd_id]
809 else:
810 cntrl_id_vd_id_mapping[cntrl_id].append(vd_id)
811 return cntrl_id_vd_id_mapping
812
813 def execute(self):
814 self.validate()
815 job_dict = {}
816 volume_name_input_list = [each.get('name') for each in self.module.params.get('volumes')]
817 self.validate_volume_exists_in_server(set(volume_name_input_list))
818 cntrl_id_vd_id_mapping = self.get_vd_id_based_on_controller_id_vd_name(set(volume_name_input_list))
819 payload = self.construct_payload_for_delete(cntrl_id_vd_id_mapping)
820 resp = self.idrac.import_scp(import_buffer=payload, target=["RAID"], job_wait=False, time_to_wait=self.module.params.get('time_to_wait'))
821 job_dict = self.wait_for_job_completion(resp)
822 return job_dict
823
824
825 class StorageView(StorageData):
826 def __init__(self, idrac, module):
827 super().__init__(idrac, module)
828
829 def execute(self):
830 status = SUCCESS_STATUS
831 storage_data = self.fetch_storage_data()
832 controller_id = self.module.params.get("controller_id")
833 volume_id = self.module.params.get("volume_id")
834 if volume_id:
835 status, storage_data = self.process_volume_id(volume_id, controller_id, storage_data)
836 elif controller_id:
837 status, storage_data = self.process_controller_id(controller_id, storage_data)
838 return {"Message": storage_data, "Status": status}
839
840 def process_volume_id(self, volume_id, controller_id, storage_data):
841 status = SUCCESS_STATUS
842 if controller_id:
843 ctrl_data = storage_data["Controller"].get(controller_id)
844 if ctrl_data:
845 virtual_disk = ctrl_data.get("VirtualDisk")
846 if not virtual_disk or volume_id not in virtual_disk:
847 status = FAILED_STATUS
848 message = VIEW_VIRTUAL_DISK_DETAILS_NOT_FOUND.format(volume_id=volume_id, controller_id=controller_id)
849 self.module.exit_json(msg=VIEW_OPERATION_FAILED,
850 storage_status={"Message": message, "Status": status},
851 failed=True)
852 else:
853 storage_data[controller_id] = {"VirtualDisk": ctrl_data["VirtualDisk"]}
854 del storage_data["Controller"]
855 else:
856 status = FAILED_STATUS
857 message = VIEW_CONTROLLER_DETAILS_NOT_FOUND.format(controller_id=controller_id)
858 self.module.exit_json(msg=VIEW_OPERATION_FAILED,
859 storage_status={"Message": message, "Status": status},
860 failed=True)
861 else:
862 status = FAILED_STATUS
863 message = VIEW_OPERATION_CONTROLLER_NOT_SPECIFIED
864 self.module.exit_json(msg=VIEW_OPERATION_FAILED,
865 storage_status={"Message": message, "Status": status},
866 failed=True)
867 return status, storage_data
868
869 def process_controller_id(self, controller_id, storage_data):
870 status = SUCCESS_STATUS
871 ctrl_data = storage_data["Controller"].get(controller_id)
872 if ctrl_data:
873 storage_data[controller_id] = ctrl_data
874 del storage_data["Controller"]
875 else:
876 status = FAILED_STATUS
877 message = VIEW_CONTROLLER_DETAILS_NOT_FOUND.format(controller_id=controller_id)
878 self.module.exit_json(msg=VIEW_OPERATION_FAILED,
879 storage_status={"Message": message, "Status": status},
880 failed=True)
881 return status, storage_data
882
883
884 def main():
885 specs = {
886 "state": {"choices": ['create', 'delete', 'view'], "default": 'view'},
887 "volume_id": {"type": 'str'},
888 "volumes": {"type": 'list', "elements": 'dict'},
889 "span_depth": {"type": 'int', "default": 1},
890 "span_length": {"type": 'int', "default": 1},
891 "number_dedicated_hot_spare": {"type": 'int', "default": 0},
892 "volume_type": {"choices": ['RAID 0', 'RAID 1', 'RAID 5', 'RAID 6', 'RAID 10', 'RAID 50', 'RAID 60'],
893 "default": 'RAID 0'},
894 "disk_cache_policy": {"choices": ["Default", "Enabled", "Disabled"],
895 "default": "Default"},
896 "write_cache_policy": {"choices": ["WriteThrough", "WriteBack", "WriteBackForce"],
897 "default": "WriteThrough"},
898 "read_cache_policy": {"choices": ["NoReadAhead", "ReadAhead", "AdaptiveReadAhead"],
899 "default": "NoReadAhead"},
900 "stripe_size": {"type": 'int', "default": 64 * 1024},
901 "capacity": {"type": 'float'},
902 "controller_id": {"type": 'str'},
903 "media_type": {"choices": ['HDD', 'SSD']},
904 "protocol": {"choices": ['SAS', 'SATA', 'PCIE']},
905 "raid_reset_config": {"choices": ['true', 'false'], "default": 'false'},
906 "raid_init_operation": {"choices": ['None', 'Fast']},
907 "job_wait": {"type": "bool", "default": True},
908 "job_wait_timeout": {"type": "int", "default": 900},
909 "time_to_wait": {"type": "int", "default": 300}
910 }
911
912 module = IdracAnsibleModule(
913 argument_spec=specs,
914 supports_check_mode=True)
915 try:
916 with iDRACRedfishAPI(module.params) as idrac:
917 changed = False
918 state_class_mapping = {
919 'create': StorageCreate,
920 'view': StorageView,
921 'delete': StorageDelete,
922 }
923 state_type = state_class_mapping.get(module.params['state'])
924 obj = state_type(idrac, module)
925 output = obj.execute()
926 msg = SUCCESSFUL_OPERATION_MSG.format(operation=module.params['state'])
927 changed = True if module.params['state'] in ['create', 'delete'] else False
928 module.exit_json(msg=msg, changed=changed, storage_status=output)
929 except HTTPError as err:
930 import json
931 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
932 except URLError as err:
933 module.exit_json(msg=str(err), unreachable=True)
934 except (SSLValidationError, ConnectionError, TypeError, ValueError, OSError) as err:
935 module.exit_json(msg=str(err), failed=True)
936
937
938 if __name__ == '__main__':
939 main()