Debian Codegraph @

ansible_collections/netapp_eseries/santricity/plugins/modules/na_santricity_storagepool.py

raw symbols SCIP
1 #!/usr/bin/python
2
3 # (c) 2024, 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
9 DOCUMENTATION = """
10 ---
11 module: na_santricity_storagepool
12 short_description: NetApp E-Series manage volume groups and disk pools
13 description: Create or remove volume groups and disk pools for NetApp E-series storage arrays.
14 author:
15 - Nathan Swartz (@swartzn)
16 - Vu Tran (@VuTran007)
17 extends_documentation_fragment:
18 - netapp_eseries.santricity.santricity.santricity_doc
19 options:
20 state:
21 description:
22 - Whether the specified storage pool should exist or not.
23 - Note that removing a storage pool currently requires the removal of all defined volumes first.
24 type: str
25 choices: ["present", "absent"]
26 default: "present"
27 name:
28 description:
29 - The name of the storage pool to manage
30 type: str
31 required: true
32 criteria_drive_count:
33 description:
34 - The number of disks to use for building the storage pool.
35 - When I(state=="present") then I(criteria_drive_count) or I(criteria_min_usable_capacity) must be specified.
36 - The pool will be expanded if this number exceeds the number of disks already in place (See expansion note below)
37 type: int
38 required: false
39 criteria_min_usable_capacity:
40 description:
41 - The minimum size of the storage pool (in size_unit).
42 - When I(state=="present") then I(criteria_drive_count) or I(criteria_min_usable_capacity) must be specified.
43 - The pool will be expanded if this value exceeds its current size. (See expansion note below)
44 - Do not use when the storage system contains mixed drives and I(usable_drives) is specified since usable capacities may not be accurate.
45 type: float
46 required: false
47 criteria_drive_type:
48 description:
49 - The type of disk (hdd or ssd) to use when searching for candidates to use.
50 - When not specified each drive type will be evaluated until successful drive candidates are found starting with
51 the most prevalent drive type.
52 type: str
53 choices: ["hdd","ssd"]
54 required: false
55 criteria_size_unit:
56 description:
57 - The unit used to interpret size parameters
58 type: str
59 choices: ["bytes", "b", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb"]
60 default: "gb"
61 required: false
62 criteria_drive_min_size:
63 description:
64 - The minimum individual drive size (in size_unit) to consider when choosing drives for the storage pool.
65 type: float
66 required: false
67 criteria_drive_max_size:
68 description:
69 - The maximum individual drive size (in size_unit) to consider when choosing drives for the storage pool.
70 type: float
71 required: false
72 criteria_drive_interface_type:
73 description:
74 - The interface type to use when selecting drives for the storage pool
75 - If not provided then all interface types will be considered.
76 type: str
77 choices: ["scsi", "fibre", "sata", "pata", "fibre520b", "sas", "sas4k", "nvme4k"]
78 required: false
79 criteria_drive_require_da:
80 description:
81 - Ensures the storage pool will be created with only data assurance (DA) capable drives.
82 - Only available for new storage pools; existing storage pools cannot be converted.
83 type: bool
84 default: false
85 required: false
86 criteria_drive_require_fde:
87 description:
88 - Whether full disk encryption ability is required for drives to be added to the storage pool
89 type: bool
90 default: false
91 required: false
92 usable_drives:
93 description:
94 - Ordered comma-separated list of tray/drive slots to be selected for drive candidates (drives that are used will be skipped).
95 - Each drive entry is represented as <tray_number>:<(optional) drawer_number>:<drive_slot_number> (e.g. 99:0 is the base tray's drive slot 0).
96 - The base tray's default identifier is 99 and expansion trays are added in the order they are attached but these identifiers can be changed by the user.
97 - Be aware that trays with multiple drawers still have a dedicated drive slot for all drives and the slot number does not rely on the drawer; however,
98 if you're planing to have drawer protection you need to order accordingly.
99 - When I(usable_drives) are not provided then the drive candidates will be selected by the storage system.
100 type: str
101 required: false
102 raid_level:
103 description:
104 - The RAID level of the storage pool to be created.
105 - Required only when I(state=="present").
106 - When I(raid_level=="raidDiskPool") then I(criteria_drive_count >= 10 or criteria_drive_count >= 11) is required
107 depending on the storage array specifications.
108 - When I(raid_level=="raid0") then I(1<=criteria_drive_count) is required.
109 - When I(raid_level=="raid1") then I(2<=criteria_drive_count) is required.
110 - When I(raid_level=="raid3") then I(3<=criteria_drive_count<=30) is required.
111 - When I(raid_level=="raid5") then I(3<=criteria_drive_count<=30) is required.
112 - When I(raid_level=="raid6") then I(5<=criteria_drive_count<=30) is required.
113 - Note that raidAll will be treated as raidDiskPool and raid3 as raid5.
114 type: str
115 default: "raidDiskPool"
116 choices: ["raidAll", "raid0", "raid1", "raid3", "raid5", "raid6", "raidDiskPool"]
117 required: false
118 secure_pool:
119 description:
120 - Enables security at rest feature on the storage pool.
121 - Will only work if all drives in the pool are security capable (FDE, FIPS, or mix)
122 - Warning, once security is enabled it is impossible to disable without erasing the drives.
123 type: bool
124 default: false
125 required: false
126 reserve_drive_count:
127 description:
128 - Set the number of drives reserved by the storage pool for reconstruction operations.
129 - Only valid on raid disk pools.
130 type: int
131 required: false
132 remove_volumes:
133 description:
134 - Prior to removing a storage pool, delete all volumes in the pool.
135 type: bool
136 default: true
137 required: false
138 erase_secured_drives:
139 description:
140 - If I(state=="absent") then all storage pool drives will be erase
141 - If I(state=="present") then delete all available storage array drives that have security enabled.
142 type: bool
143 default: true
144 required: false
145 ddp_critical_threshold_pct:
146 description:
147 - Issues a critical alert when threshold of storage has been allocated.
148 - Only applicable when I(raid_level=="raidDiskPool").
149 - Set I(ddp_critical_threshold_pct==0) to disable alert.
150 type: int
151 default: 85
152 required: false
153 ddp_warning_threshold_pct:
154 description:
155 - Issues a warning alert when threshold of storage has been allocated.
156 - Only applicable when I(raid_level=="raidDiskPool").
157 - Set I(ddp_warning_threshold_pct==0) to disable alert.
158 type: int
159 default: 0
160 required: false
161 notes:
162 - The expansion operations are non-blocking due to the time consuming nature of expanding volume groups
163 - Traditional volume groups (raid0, raid1, raid5, raid6) are performed in steps dictated by the storage array. Each
164 required step will be attempted until the request fails which is likely because of the required expansion time.
165 - raidUnsupported will be treated as raid0, raidAll as raidDiskPool and raid3 as raid5.
166 - Tray loss protection and drawer loss protection will be chosen if at all possible.
167 """
168 EXAMPLES = """
169 - name: No disk groups
170 na_santricity_storagepool:
171 ssid: "{{ ssid }}"
172 name: "{{ item }}"
173 state: absent
174 api_url: "{{ netapp_api_url }}"
175 api_username: "{{ netapp_api_username }}"
176 api_password: "{{ netapp_api_password }}"
177 validate_certs: "{{ netapp_api_validate_certs }}"
178 """
179 RETURN = """
180 msg:
181 description: Success message
182 returned: success
183 type: str
184 sample: Json facts for the pool that was created.
185 """
186 import functools
187 from itertools import groupby
188 from time import sleep
189
190 from pprint import pformat
191 from ansible.module_utils._text import to_native
192 from ansible_collections.netapp_eseries.santricity.plugins.module_utils.santricity import NetAppESeriesModule
193
194
195 def get_most_common_elements(iterator):
196 """Returns a generator containing a descending list of most common elements."""
197 if not isinstance(iterator, list):
198 raise TypeError("iterator must be a list.")
199
200 grouped = [(key, len(list(group))) for key, group in groupby(sorted(iterator))]
201 return sorted(grouped, key=lambda x: x[1], reverse=True)
202
203
204 def memoize(func):
205 """Generic memoizer for any function with any number of arguments including zero."""
206
207 @functools.wraps(func)
208 def wrapper(*args, **kwargs):
209 class MemoizeFuncArgs(dict):
210 def __missing__(self, _key):
211 self[_key] = func(*args, **kwargs)
212 return self[_key]
213
214 key = str((args, kwargs)) if args and kwargs else "no_argument_response"
215 return MemoizeFuncArgs().__getitem__(key)
216
217 return wrapper
218
219
220 class NetAppESeriesStoragePool(NetAppESeriesModule):
221 EXPANSION_TIMEOUT_SEC = 10
222 DEFAULT_DISK_POOL_MINIMUM_DISK_COUNT = 11
223
224 def __init__(self):
225 version = "02.00.0000.0000"
226 ansible_options = dict(
227 state=dict(choices=["present", "absent"], default="present", type="str"),
228 name=dict(required=True, type="str"),
229 criteria_size_unit=dict(choices=["bytes", "b", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb"],
230 default="gb", type="str"),
231 criteria_drive_count=dict(type="int"),
232 criteria_drive_interface_type=dict(choices=["scsi", "fibre", "sata", "pata", "fibre520b", "sas", "sas4k", "nvme4k"], type="str"),
233 criteria_drive_type=dict(choices=["ssd", "hdd"], type="str", required=False),
234 criteria_drive_min_size=dict(type="float"),
235 criteria_drive_max_size=dict(type="float"),
236 criteria_drive_require_da=dict(type="bool", required=False, default=False),
237 criteria_drive_require_fde=dict(type="bool", required=False, default=False),
238 criteria_min_usable_capacity=dict(type="float"),
239 usable_drives=dict(type="str", required=False),
240 raid_level=dict(choices=["raidAll", "raid0", "raid1", "raid3", "raid5", "raid6", "raidDiskPool"],
241 default="raidDiskPool"),
242 erase_secured_drives=dict(type="bool", default=True),
243 secure_pool=dict(type="bool", default=False),
244 reserve_drive_count=dict(type="int"),
245 remove_volumes=dict(type="bool", default=True),
246 ddp_critical_threshold_pct=dict(type="int", default=85, required=False),
247 ddp_warning_threshold_pct=dict(type="int", default=0, required=False))
248
249 required_if = [["state", "present", ["raid_level"]]]
250 super(NetAppESeriesStoragePool, self).__init__(ansible_options=ansible_options,
251 web_services_version=version,
252 supports_check_mode=True,
253 required_if=required_if)
254
255 args = self.module.params
256 self.state = args["state"]
257 self.ssid = args["ssid"]
258 self.name = args["name"]
259 self.criteria_drive_count = args["criteria_drive_count"]
260 self.criteria_min_usable_capacity = args["criteria_min_usable_capacity"]
261 self.criteria_size_unit = args["criteria_size_unit"]
262 self.criteria_drive_min_size = args["criteria_drive_min_size"]
263 self.criteria_drive_max_size = args["criteria_drive_max_size"]
264 self.criteria_drive_type = args["criteria_drive_type"]
265 self.criteria_drive_interface_type = args["criteria_drive_interface_type"]
266 self.criteria_drive_require_fde = args["criteria_drive_require_fde"]
267 self.criteria_drive_require_da = args["criteria_drive_require_da"]
268 self.raid_level = args["raid_level"]
269 self.erase_secured_drives = args["erase_secured_drives"]
270 self.secure_pool = args["secure_pool"]
271 self.reserve_drive_count = args["reserve_drive_count"]
272 self.remove_volumes = args["remove_volumes"]
273 self.ddp_critical_threshold_pct = args["ddp_critical_threshold_pct"]
274 self.ddp_warning_threshold_pct = args["ddp_warning_threshold_pct"]
275 self.pool_detail = None
276
277 if self.ddp_critical_threshold_pct < 0 or self.ddp_critical_threshold_pct > 100:
278 self.module.fail_json(msg="Invalid I(ddp_critical_threshold_pct) value! Must between or equal to 0 and 100. Array [%s]" % self.ssid)
279 if self.ddp_warning_threshold_pct < 0 or self.ddp_warning_threshold_pct > 100:
280 self.module.fail_json(msg="Invalid I(ddp_warning_threshold_pct) value! Must between or equal to 0 and 100. Array [%s]" % self.ssid)
281
282 # Change all sizes to be measured in bytes
283 if self.criteria_min_usable_capacity:
284 self.criteria_min_usable_capacity = int(self.criteria_min_usable_capacity * self.SIZE_UNIT_MAP[self.criteria_size_unit])
285 if self.criteria_drive_min_size:
286 self.criteria_drive_min_size = int(self.criteria_drive_min_size * self.SIZE_UNIT_MAP[self.criteria_size_unit])
287 if self.criteria_drive_max_size:
288 self.criteria_drive_max_size = int(self.criteria_drive_max_size * self.SIZE_UNIT_MAP[self.criteria_size_unit])
289 self.criteria_size_unit = "bytes"
290
291 # Adjust unused raid level option to reflect documentation
292 if self.raid_level == "raidAll":
293 self.raid_level = "raidDiskPool"
294 if self.raid_level == "raid3":
295 self.raid_level = "raid5"
296
297 # Parse usable drive string into tray:slot list
298 self.usable_drives = []
299 if args["usable_drives"]:
300 for usable_drive in args["usable_drives"].split(","):
301 location = [int(item) for item in usable_drive.split(":")]
302 if len(location) == 2:
303 tray, slot = location
304 self.usable_drives.append([tray, 0, slot + 1]) # slot must be one-indexed instead of zero.
305 elif len(location) == 3:
306 tray, drawer, slot = location
307 self.usable_drives.append([tray, drawer - 1, slot + 1]) # slot must be one-indexed instead of zero.
308 else:
309 self.module.fail_json(msg="Invalid I(usable_drives) value! Must be a comma-separated list of <TRAY_NUMBER>:<DRIVE_SLOT_NUMBER> entries."
310 " Array [%s]." % self.ssid)
311
312 @property
313 @memoize
314 def available_drives(self):
315 """Determine the list of available drives"""
316 return [drive["id"] for drive in self.drives if drive["available"] and drive["status"] == "optimal"]
317
318 @property
319 @memoize
320 def available_drive_types(self):
321 """Determine the types of available drives sorted by the most common first."""
322 types = [drive["driveMediaType"] for drive in self.drives]
323 return [entry[0] for entry in get_most_common_elements(types)]
324
325 @property
326 @memoize
327 def available_drive_interface_types(self):
328 """Determine the types of available drives."""
329 interfaces = [drive["phyDriveType"] for drive in self.drives]
330 return [entry[0] for entry in get_most_common_elements(interfaces)]
331
332 @property
333 def storage_pool_drives(self):
334 """Retrieve list of drives found in storage pool."""
335 return [drive for drive in self.drives if drive["currentVolumeGroupRef"] == self.pool_detail["id"] and not drive["hotSpare"]]
336
337 @property
338 def expandable_drive_count(self):
339 """Maximum number of drives that a storage pool can be expended at a given time."""
340 capabilities = None
341 if self.raid_level == "raidDiskPool":
342 return len(self.available_drives)
343
344 try:
345 rc, capabilities = self.request("storage-systems/%s/capabilities" % self.ssid)
346 except Exception as error:
347 self.module.fail_json(msg="Failed to fetch maximum expandable drive count. Array id [%s]. Error [%s]."
348 % (self.ssid, to_native(error)))
349
350 return capabilities["featureParameters"]["maxDCEDrives"]
351
352 @property
353 def disk_pool_drive_minimum(self):
354 """Provide the storage array's minimum disk pool drive count."""
355 rc, attr = self.request("storage-systems/%s/symbol/getSystemAttributeDefaults" % self.ssid, ignore_errors=True)
356
357 # Standard minimum is 11 drives but some allow 10 drives. 10 will be the default
358 if (rc != 200 or "minimumDriveCount" not in attr["defaults"]["diskPoolDefaultAttributes"].keys() or
359 attr["defaults"]["diskPoolDefaultAttributes"]["minimumDriveCount"] == 0):
360 return self.DEFAULT_DISK_POOL_MINIMUM_DISK_COUNT
361
362 return attr["defaults"]["diskPoolDefaultAttributes"]["minimumDriveCount"]
363
364 def get_available_drive_capacities(self, drive_id_list=None):
365 """Determine the list of available drive capacities."""
366 if drive_id_list:
367 available_drive_capacities = set([int(drive["usableCapacity"]) for drive in self.drives
368 if drive["id"] in drive_id_list and drive["available"] and
369 drive["status"] == "optimal"])
370 else:
371 available_drive_capacities = set([int(drive["usableCapacity"]) for drive in self.drives
372 if drive["available"] and drive["status"] == "optimal"])
373
374 self.module.log("available drive capacities: %s" % available_drive_capacities)
375 return list(available_drive_capacities)
376
377 @property
378 def drives(self):
379 """Retrieve list of drives found in storage system."""
380 drives = None
381 try:
382 rc, drives = self.request("storage-systems/%s/drives" % self.ssid)
383 except Exception as error:
384 self.module.fail_json(msg="Failed to fetch disk drives. Array id [%s]. Error [%s]." % (self.ssid, to_native(error)))
385
386 return drives
387
388 def tray_by_ids(self):
389 """Retrieve list of trays found in storage system and return dictionary of trays keyed by ids."""
390 tray_by_ids = {}
391 try:
392 rc, inventory = self.request("storage-systems/%s/hardware-inventory" % self.ssid)
393 for tray in inventory["trays"]:
394 tray_by_ids.update({tray["trayRef"]: {"tray_number": tray["trayId"],
395 "drawer_count": tray["driveLayout"]["numRows"] * tray["driveLayout"]["numColumns"]}})
396 except Exception as error:
397 self.module.fail_json(msg="Failed to fetch trays. Array id [%s]. Error [%s]." % (self.ssid, to_native(error)))
398
399 return tray_by_ids
400
401 def convert_drives_list_into_drive_info_by_ids(self):
402 """Determine drive identifiers base on provided drive list. Provide usable_ids list to select subset."""
403 tray_by_ids = self.tray_by_ids()
404
405 drives = []
406 for usable_drive in self.usable_drives:
407 tray, drawer, slot = usable_drive
408 for drive in self.drives:
409 drawer_slot = drawer * tray_by_ids[drive["physicalLocation"]["trayRef"]]["drawer_count"] + slot
410 if drawer_slot == drive["physicalLocation"]["slot"] and tray == tray_by_ids[drive["physicalLocation"]["trayRef"]]["tray_number"]:
411 if drive["available"]:
412 drives.append(drive["id"])
413 break
414
415 return drives
416
417 def is_drive_count_valid(self, drive_count):
418 """Validate drive count criteria is met."""
419 if self.criteria_drive_count and drive_count < self.criteria_drive_count:
420 return False
421
422 if self.raid_level == "raidDiskPool":
423 return drive_count >= self.disk_pool_drive_minimum
424 if self.raid_level == "raid0":
425 return drive_count > 0
426 if self.raid_level == "raid1":
427 return drive_count >= 2 and (drive_count % 2) == 0
428 if self.raid_level in ["raid3", "raid5"]:
429 return 3 <= drive_count <= 30
430 if self.raid_level == "raid6":
431 return 5 <= drive_count <= 30
432 return False
433
434 @property
435 def storage_pool(self):
436 """Retrieve storage pool information."""
437 storage_pools_resp = None
438 try:
439 rc, storage_pools_resp = self.request("storage-systems/%s/storage-pools" % self.ssid)
440 except Exception as err:
441 self.module.fail_json(msg="Failed to get storage pools. Array id [%s]. Error [%s]. State[%s]."
442 % (self.ssid, to_native(err), self.state))
443
444 pool_detail = [pool for pool in storage_pools_resp if pool["name"] == self.name]
445 return pool_detail[0] if pool_detail else dict()
446
447 @property
448 def storage_pool_volumes(self):
449 """Retrieve list of volumes associated with storage pool."""
450 volumes_resp = None
451 try:
452 rc, volumes_resp = self.request("storage-systems/%s/volumes" % self.ssid)
453 except Exception as err:
454 self.module.fail_json(msg="Failed to get storage pools. Array id [%s]. Error [%s]. State[%s]."
455 % (self.ssid, to_native(err), self.state))
456
457 group_ref = self.storage_pool["volumeGroupRef"]
458 storage_pool_volume_list = [volume["id"] for volume in volumes_resp if volume["volumeGroupRef"] == group_ref]
459 return storage_pool_volume_list
460
461 def get_ddp_capacity(self, expansion_drive_list):
462 """Return the total usable capacity based on the additional drives."""
463
464 def get_ddp_error_percent(_drive_count, _extent_count):
465 """Determine the space reserved for reconstruction"""
466 if _drive_count <= 36:
467 if _extent_count <= 600:
468 return 0.40
469 elif _extent_count <= 1400:
470 return 0.35
471 elif _extent_count <= 6200:
472 return 0.20
473 elif _extent_count <= 50000:
474 return 0.15
475 elif _drive_count <= 64:
476 if _extent_count <= 600:
477 return 0.20
478 elif _extent_count <= 1400:
479 return 0.15
480 elif _extent_count <= 6200:
481 return 0.10
482 elif _extent_count <= 50000:
483 return 0.05
484 elif _drive_count <= 480:
485 if _extent_count <= 600:
486 return 0.20
487 elif _extent_count <= 1400:
488 return 0.15
489 elif _extent_count <= 6200:
490 return 0.10
491 elif _extent_count <= 50000:
492 return 0.05
493
494 self.module.fail_json(msg="Drive count exceeded the error percent table. Array[%s]" % self.ssid)
495
496 def get_ddp_reserved_drive_count(_disk_count):
497 """Determine the number of reserved drive."""
498 reserve_count = 0
499
500 if self.reserve_drive_count:
501 reserve_count = self.reserve_drive_count
502 elif _disk_count >= 256:
503 reserve_count = 8
504 elif _disk_count >= 192:
505 reserve_count = 7
506 elif _disk_count >= 128:
507 reserve_count = 6
508 elif _disk_count >= 64:
509 reserve_count = 4
510 elif _disk_count >= 32:
511 reserve_count = 3
512 elif _disk_count >= 12:
513 reserve_count = 2
514 elif _disk_count == 11:
515 reserve_count = 1
516
517 return reserve_count
518
519 if self.pool_detail:
520 drive_count = len(self.storage_pool_drives) + len(expansion_drive_list)
521 else:
522 drive_count = len(expansion_drive_list)
523
524 drive_usable_capacity = min(*self.get_available_drive_capacities(),
525 *self.get_available_drive_capacities(expansion_drive_list))
526
527 drive_data_extents = ((drive_usable_capacity - 8053063680) / 536870912)
528 maximum_stripe_count = (drive_count * drive_data_extents) / 10
529
530 error_percent = get_ddp_error_percent(drive_count, drive_data_extents)
531 error_overhead = (drive_count * drive_data_extents / 10 * error_percent + 10) / 10
532
533 total_stripe_count = maximum_stripe_count - error_overhead
534 stripe_count_per_drive = total_stripe_count / drive_count
535 reserved_stripe_count = get_ddp_reserved_drive_count(drive_count) * stripe_count_per_drive
536 available_stripe_count = total_stripe_count - reserved_stripe_count
537
538 return available_stripe_count * 4294967296
539
540 def get_candidate_drive_request(self):
541 """Perform request for new volume creation."""
542
543 candidates_list = list()
544 drive_types = [self.criteria_drive_type] if self.criteria_drive_type else self.available_drive_types
545 interface_types = [self.criteria_drive_interface_type] \
546 if self.criteria_drive_interface_type else self.available_drive_interface_types
547
548 for interface_type in interface_types:
549 for drive_type in drive_types:
550 candidates = None
551 volume_candidate_request_data = dict(
552 type="diskPool" if self.raid_level == "raidDiskPool" else "traditional",
553 diskPoolVolumeCandidateRequestData=dict(
554 reconstructionReservedDriveCount=65535))
555 candidate_selection_type = dict(
556 candidateSelectionType="count",
557 driveRefList=dict(driveRef=self.available_drives))
558 criteria = dict(raidLevel=self.raid_level,
559 phyDriveType=interface_type,
560 dssPreallocEnabled=False,
561 securityType="capable" if self.criteria_drive_require_fde else "none",
562 driveMediaType=drive_type,
563 onlyProtectionInformationCapable=True if self.criteria_drive_require_da else False,
564 volumeCandidateRequestData=volume_candidate_request_data,
565 allocateReserveSpace=False,
566 securityLevel="fde" if self.criteria_drive_require_fde else "none",
567 candidateSelectionType=candidate_selection_type)
568
569 try:
570 rc, candidates = self.request("storage-systems/%s/symbol/getVolumeCandidates?verboseError"
571 "Response=true" % self.ssid, data=criteria, method="POST")
572 except Exception as error:
573 self.module.fail_json(msg="Failed to retrieve volume candidates. Array [%s]. Error [%s]."
574 % (self.ssid, to_native(error)))
575
576 if candidates:
577 candidates_list.extend(candidates["volumeCandidate"])
578
579 if candidates_list and not self.usable_drives:
580 def candidate_sort_function(entry):
581 """Orders candidates based on tray/drawer loss protection."""
582 preference = 3
583 if entry["drawerLossProtection"]:
584 preference -= 1
585 if entry["trayLossProtection"]:
586 preference -= 2
587 return preference
588
589 candidates_list.sort(key=candidate_sort_function)
590
591 # Replace drive selection with required usable drives
592 if self.usable_drives:
593 drives = self.convert_drives_list_into_drive_info_by_ids()
594 for candidates in candidates_list:
595 candidates["driveRefList"].update({"driveRef": drives[0:candidates["driveCount"]]})
596
597 return candidates_list
598
599 @memoize
600 def get_candidate_drives(self):
601 """Retrieve set of drives candidates for creating a new storage pool."""
602 for candidate in self.get_candidate_drive_request():
603
604 # Evaluate candidates for required drive count, collective drive usable capacity and minimum drive size
605 if self.criteria_drive_count:
606 if self.criteria_drive_count != int(candidate["driveCount"]):
607 continue
608 if self.criteria_min_usable_capacity:
609 if ((self.raid_level == "raidDiskPool" and self.criteria_min_usable_capacity >
610 self.get_ddp_capacity(candidate["driveRefList"]["driveRef"])) or
611 self.criteria_min_usable_capacity > int(candidate["usableSize"])):
612 continue
613 if self.criteria_drive_min_size:
614 if self.criteria_drive_min_size > min(self.get_available_drive_capacities(candidate["driveRefList"]["driveRef"])):
615 continue
616 if self.criteria_drive_max_size:
617 if self.criteria_drive_max_size < min(self.get_available_drive_capacities(candidate["driveRefList"]["driveRef"])):
618 continue
619
620 return candidate
621
622 self.module.fail_json(msg="Not enough drives to meet the specified criteria. Array [%s]." % self.ssid)
623
624 @memoize
625 def get_expansion_candidate_drives(self):
626 """Retrieve required expansion drive list.
627
628 Note: To satisfy the expansion criteria each item in the candidate list must added specified group since there
629 is a potential limitation on how many drives can be incorporated at a time.
630 * Traditional raid volume groups must be added two drives maximum at a time. No limits on raid disk pools.
631
632 :return list(candidate): list of candidate structures from the getVolumeGroupExpansionCandidates symbol endpoint
633 """
634
635 def get_expansion_candidate_drive_request():
636 """Perform the request for expanding existing volume groups or disk pools.
637
638 Note: the list of candidate structures do not necessarily produce candidates that meet all criteria.
639 """
640 candidates_list = None
641 url = "storage-systems/%s/symbol/getVolumeGroupExpansionCandidates?verboseErrorResponse=true" % self.ssid
642 if self.raid_level == "raidDiskPool":
643 url = "storage-systems/%s/symbol/getDiskPoolExpansionCandidates?verboseErrorResponse=true" % self.ssid
644
645 try:
646 rc, candidates_list = self.request(url, method="POST", data=self.pool_detail["id"])
647 except Exception as error:
648 self.module.fail_json(msg="Failed to retrieve volume candidates. Array [%s]. Error [%s]."
649 % (self.ssid, to_native(error)))
650
651 return candidates_list["candidates"]
652
653 required_candidate_list = list()
654 required_additional_drives = 0
655 required_additional_capacity = 0
656 total_required_capacity = 0
657
658 # determine whether and how much expansion is need to satisfy the specified criteria
659 if self.criteria_min_usable_capacity:
660 total_required_capacity = self.criteria_min_usable_capacity
661 required_additional_capacity = self.criteria_min_usable_capacity - int(self.pool_detail["totalRaidedSpace"])
662
663 if self.criteria_drive_count:
664 required_additional_drives = self.criteria_drive_count - len(self.storage_pool_drives)
665
666 # Determine the appropriate expansion candidate list
667 if required_additional_drives > 0 or required_additional_capacity > 0:
668 for candidate in get_expansion_candidate_drive_request():
669
670 if self.criteria_drive_min_size:
671 if self.criteria_drive_min_size > min(self.get_available_drive_capacities(candidate["drives"])):
672 continue
673 if self.criteria_drive_max_size:
674 if self.criteria_drive_max_size < min(self.get_available_drive_capacities(candidate["drives"])):
675 continue
676
677 if self.raid_level == "raidDiskPool":
678 if (len(candidate["drives"]) >= required_additional_drives and
679 self.get_ddp_capacity(candidate["drives"]) >= total_required_capacity):
680 required_candidate_list.append(candidate)
681 break
682 else:
683 required_additional_drives -= len(candidate["drives"])
684 required_additional_capacity -= int(candidate["usableCapacity"])
685 required_candidate_list.append(candidate)
686
687 # Determine if required drives and capacities are satisfied
688 if required_additional_drives <= 0 and required_additional_capacity <= 0:
689 break
690 else:
691 self.module.fail_json(msg="Not enough drives to meet the specified criteria. Array [%s]." % self.ssid)
692
693 return required_candidate_list
694
695 def get_reserve_drive_count(self):
696 """Retrieve the current number of reserve drives for raidDiskPool (Only for raidDiskPool)."""
697
698 if not self.pool_detail:
699 self.module.fail_json(msg="The storage pool must exist. Array [%s]." % self.ssid)
700
701 if self.raid_level != "raidDiskPool":
702 self.module.fail_json(msg="The storage pool must be a raidDiskPool. Pool [%s]. Array [%s]."
703 % (self.pool_detail["id"], self.ssid))
704
705 return self.pool_detail["volumeGroupData"]["diskPoolData"]["reconstructionReservedDriveCount"]
706
707 def get_maximum_reserve_drive_count(self):
708 """Retrieve the maximum number of reserve drives for storage pool (Only for raidDiskPool)."""
709 if self.raid_level != "raidDiskPool":
710 self.module.fail_json(msg="The storage pool must be a raidDiskPool. Pool [%s]. Array [%s]."
711 % (self.pool_detail["id"], self.ssid))
712
713 drives_ids = list()
714
715 if self.pool_detail:
716 drives_ids.extend(self.storage_pool_drives)
717 for candidate in self.get_expansion_candidate_drives():
718 drives_ids.extend((candidate["drives"]))
719 else:
720 candidate = self.get_candidate_drives()
721 drives_ids.extend(candidate["driveRefList"]["driveRef"])
722
723 drive_count = len(drives_ids)
724 maximum_reserve_drive_count = min(int(drive_count * 0.2 + 1), drive_count - 10)
725 if maximum_reserve_drive_count > 10:
726 maximum_reserve_drive_count = 10
727
728 return maximum_reserve_drive_count
729
730 def set_reserve_drive_count(self, check_mode=False):
731 """Set the reserve drive count for raidDiskPool."""
732 changed = False
733
734 if self.raid_level == "raidDiskPool" and self.reserve_drive_count:
735 maximum_count = self.get_maximum_reserve_drive_count()
736
737 if self.reserve_drive_count < 0 or self.reserve_drive_count > maximum_count:
738 self.module.fail_json(msg="Supplied reserve drive count is invalid or exceeds the maximum allowed. "
739 "Note that it may be necessary to wait for expansion operations to complete "
740 "before the adjusting the reserve drive count. Maximum [%s]. Array [%s]."
741 % (maximum_count, self.ssid))
742
743 if self.reserve_drive_count != self.get_reserve_drive_count():
744 changed = True
745
746 if not check_mode:
747 try:
748 rc, resp = self.request("storage-systems/%s/symbol/setDiskPoolReservedDriveCount" % self.ssid,
749 method="POST", data=dict(volumeGroupRef=self.pool_detail["id"],
750 newDriveCount=self.reserve_drive_count))
751 except Exception as error:
752 self.module.fail_json(msg="Failed to set reserve drive count for disk pool. Disk Pool [%s]."
753 " Array [%s]." % (self.pool_detail["id"], self.ssid))
754
755 return changed
756
757 def erase_all_available_secured_drives(self, check_mode=False):
758 """Erase all available drives that have encryption at rest feature enabled."""
759 changed = False
760 drives_list = list()
761 for drive in self.drives:
762 if drive["available"] and drive["fdeEnabled"]:
763 changed = True
764 drives_list.append(drive["id"])
765
766 if drives_list and not check_mode:
767 try:
768 rc, resp = self.request("storage-systems/%s/symbol/reprovisionDrive?verboseErrorResponse=true"
769 % self.ssid, method="POST", data=dict(driveRef=drives_list))
770 except Exception as error:
771 self.module.fail_json(msg="Failed to erase all secured drives. Array [%s]" % self.ssid)
772
773 return changed
774
775 def create_storage_pool(self):
776 """Create new storage pool."""
777 url = "storage-systems/%s/symbol/createVolumeGroup?verboseErrorResponse=true" % self.ssid
778 request_body = dict(label=self.name,
779 candidate=self.get_candidate_drives())
780
781 if self.raid_level == "raidDiskPool":
782 url = "storage-systems/%s/symbol/createDiskPool?verboseErrorResponse=true" % self.ssid
783
784 request_body.update(
785 dict(backgroundOperationPriority="useDefault",
786 criticalReconstructPriority="useDefault",
787 degradedReconstructPriority="useDefault",
788 poolUtilizationCriticalThreshold=self.ddp_critical_threshold_pct,
789 poolUtilizationWarningThreshold=self.ddp_warning_threshold_pct))
790
791 if self.reserve_drive_count:
792 request_body.update(dict(volumeCandidateData=dict(
793 diskPoolVolumeCandidateData=dict(reconstructionReservedDriveCount=self.reserve_drive_count))))
794
795 try:
796 rc, resp = self.request(url, method="POST", data=request_body)
797 except Exception as error:
798 self.module.fail_json(msg="Failed to create storage pool. Array id [%s]. Error [%s]."
799 % (self.ssid, to_native(error)))
800
801 # Update drive and storage pool information
802 self.pool_detail = self.storage_pool
803
804 def delete_storage_pool(self):
805 """Delete storage pool."""
806 storage_pool_drives = [drive["id"] for drive in self.storage_pool_drives if drive["fdeEnabled"]]
807 try:
808 delete_volumes_parameter = "?delete-volumes=true" if self.remove_volumes else ""
809 rc, resp = self.request("storage-systems/%s/storage-pools/%s%s"
810 % (self.ssid, self.pool_detail["id"], delete_volumes_parameter), method="DELETE")
811 except Exception as error:
812 self.module.fail_json(msg="Failed to delete storage pool. Pool id [%s]. Array id [%s]. Error [%s]."
813 % (self.pool_detail["id"], self.ssid, to_native(error)))
814
815 if storage_pool_drives and self.erase_secured_drives:
816 try:
817 rc, resp = self.request("storage-systems/%s/symbol/reprovisionDrive?verboseErrorResponse=true"
818 % self.ssid, method="POST", data=dict(driveRef=storage_pool_drives))
819 except Exception as error:
820 self.module.fail_json(msg="Failed to erase drives prior to creating new storage pool. Array [%s]."
821 " Error [%s]." % (self.ssid, to_native(error)))
822
823 def secure_storage_pool(self, check_mode=False):
824 """Enable security on an existing storage pool"""
825 self.pool_detail = self.storage_pool
826 needs_secure_pool = False
827
828 if not self.secure_pool and self.pool_detail["securityType"] == "enabled":
829 self.module.fail_json(msg="It is not possible to disable storage pool security! See array documentation.")
830 if self.secure_pool and self.pool_detail["securityType"] != "enabled":
831 needs_secure_pool = True
832
833 if needs_secure_pool and not check_mode:
834 try:
835 rc, resp = self.request("storage-systems/%s/storage-pools/%s" % (self.ssid, self.pool_detail["id"]),
836 data=dict(securePool=True), method="POST")
837 except Exception as error:
838 self.module.fail_json(msg="Failed to secure storage pool. Pool id [%s]. Array [%s]. Error"
839 " [%s]." % (self.pool_detail["id"], self.ssid, to_native(error)))
840
841 self.pool_detail = self.storage_pool
842 return needs_secure_pool
843
844 def migrate_raid_level(self, check_mode=False):
845 """Request storage pool raid level migration."""
846 needs_migration = self.raid_level != self.pool_detail["raidLevel"]
847 if needs_migration and self.pool_detail["raidLevel"] == "raidDiskPool":
848 self.module.fail_json(msg="Raid level cannot be changed for disk pools")
849
850 if needs_migration and not check_mode:
851 sp_raid_migrate_req = dict(raidLevel=self.raid_level)
852
853 try:
854 rc, resp = self.request("storage-systems/%s/storage-pools/%s/raid-type-migration"
855 % (self.ssid, self.name), data=sp_raid_migrate_req, method="POST")
856 except Exception as error:
857 self.module.fail_json(msg="Failed to change the raid level of storage pool. Array id [%s]."
858 " Error [%s]." % (self.ssid, to_native(error)))
859
860 self.pool_detail = self.storage_pool
861 return needs_migration
862
863 def update_ddp_settings(self, check_mode=False):
864 """Update dynamic disk pool settings."""
865 if self.raid_level != "raidDiskPool":
866 return False
867
868 needs_update = False
869 if (self.pool_detail["volumeGroupData"]["diskPoolData"]["poolUtilizationWarningThreshold"] != self.ddp_warning_threshold_pct or
870 self.pool_detail["volumeGroupData"]["diskPoolData"]["poolUtilizationCriticalThreshold"] != self.ddp_critical_threshold_pct):
871 needs_update = True
872
873 if needs_update and check_mode:
874 if self.pool_detail["volumeGroupData"]["diskPoolData"]["poolUtilizationWarningThreshold"] != self.ddp_warning_threshold_pct:
875 try:
876 rc, update = self.request("storage-systems/%s/storage-pools/%s" % (self.ssid, self.pool_detail["id"]), method="POST",
877 data={"id": self.pool_detail["id"],
878 "poolThreshold": {"thresholdType": "warning", "value": self.ddp_warning_threshold_pct}})
879 except Exception as error:
880 self.module.fail_json(msg="Failed to update DDP warning alert threshold! Pool [%s]. Array [%s]."
881 " Error [%s]" % (self.name, self.ssid, to_native(error)))
882
883 if self.pool_detail["volumeGroupData"]["diskPoolData"]["poolUtilizationCriticalThreshold"] != self.ddp_critical_threshold_pct:
884 try:
885 rc, update = self.request("storage-systems/%s/storage-pools/%s" % (self.ssid, self.pool_detail["id"]), method="POST",
886 data={"id": self.pool_detail["id"],
887 "poolThreshold": {"thresholdType": "critical", "value": self.ddp_critical_threshold_pct}})
888 except Exception as error:
889 self.module.fail_json(msg="Failed to update DDP critical alert threshold! Pool [%s]. Array [%s]."
890 " Error [%s]" % (self.name, self.ssid, to_native(error)))
891 return needs_update
892
893 def expand_storage_pool(self, check_mode=False):
894 """Add drives to existing storage pool.
895
896 :return bool: whether drives were required to be added to satisfy the specified criteria."""
897 expansion_candidate_list = self.get_expansion_candidate_drives()
898 changed_required = bool(expansion_candidate_list)
899 estimated_completion_time = 0.0
900
901 # build expandable groupings of traditional raid candidate
902 required_expansion_candidate_list = list()
903 while expansion_candidate_list:
904 subset = list()
905 while expansion_candidate_list and len(subset) < self.expandable_drive_count:
906 subset.extend(expansion_candidate_list.pop()["drives"])
907 required_expansion_candidate_list.append(subset)
908
909 if required_expansion_candidate_list and not check_mode:
910 url = "storage-systems/%s/symbol/startVolumeGroupExpansion?verboseErrorResponse=true" % self.ssid
911 if self.raid_level == "raidDiskPool":
912 url = "storage-systems/%s/symbol/startDiskPoolExpansion?verboseErrorResponse=true" % self.ssid
913
914 while required_expansion_candidate_list:
915 candidate_drives_list = required_expansion_candidate_list.pop()
916 request_body = dict(volumeGroupRef=self.pool_detail["volumeGroupRef"],
917 driveRef=candidate_drives_list)
918 try:
919 rc, resp = self.request(url, method="POST", data=request_body)
920 except Exception as error:
921 rc, actions_resp = self.request("storage-systems/%s/storage-pools/%s/action-progress"
922 % (self.ssid, self.pool_detail["id"]), ignore_errors=True)
923 if rc == 200 and actions_resp:
924 actions = [action["currentAction"] for action in actions_resp
925 if action["volumeRef"] in self.storage_pool_volumes]
926 self.module.fail_json(msg="Failed to add drives to the storage pool possibly because of actions"
927 " in progress. Actions [%s]. Pool id [%s]. Array id [%s]. Error [%s]."
928 % (", ".join(actions), self.pool_detail["id"], self.ssid,
929 to_native(error)))
930
931 self.module.fail_json(msg="Failed to add drives to storage pool. Pool id [%s]. Array id [%s]."
932 " Error [%s]." % (self.pool_detail["id"], self.ssid, to_native(error)))
933
934 # Wait for expansion completion unless it is the last request in the candidate list
935 if required_expansion_candidate_list:
936 for dummy in range(self.EXPANSION_TIMEOUT_SEC):
937 rc, actions_resp = self.request("storage-systems/%s/storage-pools/%s/action-progress"
938 % (self.ssid, self.pool_detail["id"]), ignore_errors=True)
939 if rc == 200:
940 for action in actions_resp:
941 if (action["volumeRef"] in self.storage_pool_volumes and
942 action["currentAction"] == "remappingDce"):
943 sleep(1)
944 estimated_completion_time = action["estimatedTimeToCompletion"]
945 break
946 else:
947 estimated_completion_time = 0.0
948 break
949
950 return changed_required, estimated_completion_time
951
952 def apply(self):
953 """Apply requested state to storage array."""
954 changed = False
955
956 if self.state == "present":
957 if self.criteria_drive_count is None and self.criteria_min_usable_capacity is None:
958 self.module.fail_json(msg="One of criteria_min_usable_capacity or criteria_drive_count must be"
959 " specified.")
960 if self.criteria_drive_count and not self.is_drive_count_valid(self.criteria_drive_count):
961 self.module.fail_json(msg="criteria_drive_count must be valid for the specified raid level.")
962
963 self.pool_detail = self.storage_pool
964 self.module.log(pformat(self.pool_detail))
965
966 if self.state == "present" and self.erase_secured_drives:
967 self.erase_all_available_secured_drives(check_mode=True)
968
969 # Determine whether changes need to be applied to the storage array
970 if self.pool_detail:
971
972 if self.state == "absent":
973 changed = True
974
975 elif self.state == "present":
976
977 if self.criteria_drive_count and self.criteria_drive_count < len(self.storage_pool_drives):
978 self.module.fail_json(msg="Failed to reduce the size of the storage pool. Array [%s]. Pool [%s]."
979 % (self.ssid, self.pool_detail["id"]))
980
981 if self.criteria_drive_type and self.criteria_drive_type != self.pool_detail["driveMediaType"]:
982 self.module.fail_json(msg="Failed! It is not possible to modify storage pool media type."
983 " Array [%s]. Pool [%s]." % (self.ssid, self.pool_detail["id"]))
984
985 if (self.criteria_drive_require_da is not False and self.criteria_drive_require_da !=
986 self.pool_detail["protectionInformationCapabilities"]["protectionInformationCapable"]):
987 self.module.fail_json(msg="Failed! It is not possible to modify DA-capability. Array [%s]."
988 " Pool [%s]." % (self.ssid, self.pool_detail["id"]))
989
990 # Evaluate current storage pool for required change.
991 needs_expansion, estimated_completion_time = self.expand_storage_pool(check_mode=True)
992 if needs_expansion:
993 changed = True
994 if self.migrate_raid_level(check_mode=True):
995 changed = True
996 if self.secure_storage_pool(check_mode=True):
997 changed = True
998 if self.set_reserve_drive_count(check_mode=True):
999 changed = True
1000 if self.update_ddp_settings(check_mode=True):
1001 changed = True
1002
1003 elif self.state == "present":
1004 changed = True
1005
1006 # Apply changes to storage array
1007 msg = "No changes were required for the storage pool [%s]."
1008 if changed and not self.module.check_mode:
1009 if self.state == "present":
1010 if self.erase_secured_drives:
1011 self.erase_all_available_secured_drives()
1012
1013 if self.pool_detail:
1014 change_list = list()
1015
1016 # Expansion needs to occur before raid level migration to account for any sizing needs.
1017 expanded, estimated_completion_time = self.expand_storage_pool()
1018 if expanded:
1019 change_list.append("expanded")
1020 if self.migrate_raid_level():
1021 change_list.append("raid migration")
1022 if self.secure_storage_pool():
1023 change_list.append("secured")
1024 if self.set_reserve_drive_count():
1025 change_list.append("adjusted reserve drive count")
1026
1027 if self.update_ddp_settings():
1028 change_list.append("updated ddp settings")
1029
1030 if change_list:
1031 msg = "Following changes have been applied to the storage pool [%s]: " + ", ".join(change_list)
1032
1033 if expanded:
1034 msg += "\nThe expansion operation will complete in an estimated %s minutes." % estimated_completion_time
1035 else:
1036 self.create_storage_pool()
1037 msg = "Storage pool [%s] was created."
1038
1039 if self.secure_storage_pool():
1040 msg = "Storage pool [%s] was created and secured."
1041 if self.set_reserve_drive_count():
1042 msg += " Adjusted reserve drive count."
1043
1044 elif self.pool_detail:
1045 self.delete_storage_pool()
1046 msg = "Storage pool [%s] removed."
1047
1048 self.pool_detail = self.storage_pool
1049 self.module.log(pformat(self.pool_detail))
1050 self.module.log(msg % self.name)
1051 self.module.exit_json(msg=msg % self.name, changed=changed, **self.pool_detail)
1052
1053
1054 def main():
1055 storage_pool = NetAppESeriesStoragePool()
1056 storage_pool.apply()
1057
1058
1059 if __name__ == "__main__":
1060 main()