Debian Codegraph @

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

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