Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2
3 # (c) 2026, 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 __metaclass__ = type
8
9
10 DOCUMENTATION = """
11 ---
12 module: na_santricity_volume
13 short_description: NetApp E-Series manage storage volumes (standard and thin)
14 description:
15 - Create or remove volumes (standard and thin) for NetApp E/EF-series storage arrays.
16 author:
17 - Nathan Swartz (@swartzn)
18 - Vu Tran (@VuTran007)
19 extends_documentation_fragment:
20 - netapp_eseries.santricity.santricity.santricity_doc
21 options:
22 state:
23 description:
24 - Whether the specified volume should exist
25 type: str
26 choices: ["present", "absent"]
27 default: "present"
28 name:
29 description:
30 - The name of the volume to manage.
31 type: str
32 required: true
33 storage_pool_name:
34 description:
35 - Required only when requested I(state=="present").
36 - Name of the storage pool wherein the volume should reside.
37 type: str
38 required: false
39 size_unit:
40 description:
41 - The unit used to interpret the size parameter
42 - pct unit defines a percent of total usable storage pool size.
43 type: str
44 choices: ["bytes", "b", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb", "pct"]
45 default: "gb"
46 size:
47 description:
48 - Required only when I(state=="present").
49 - Size of the volume in I(size_unit).
50 - Size of the virtual volume in the case of a thin volume in I(size_unit).
51 - Maximum virtual volume size of a thin provisioned volume is 256tb; however other OS-level restrictions may exist.
52 type: float
53 required: true
54 size_tolerance_b:
55 description:
56 - Tolerance for total volume size measured in bytes; so, if the total volumes size is within
57 +/- I(size_tolerance_b) then no resizing will be expected.
58 - This parameter can be useful in the case of existing volumes not created by na_santricity_volume
59 since providing the exact size can be difficult due to volume alignment and overhead.
60 type: int
61 required: false
62 default: 10485760
63 segment_size_kb:
64 description:
65 - Segment size of the volume
66 - All values are in kibibytes.
67 - Some common choices include 8, 16, 32, 64, 128, 256, and 512 but options are system
68 dependent.
69 - Retrieve the definitive system list from M(netapp_eseries.santricity.na_santricity_facts)
70 under segment_sizes.
71 - Segment size migrations are not allowed in this module
72 type: int
73 default: 128
74 raid_level:
75 description:
76 - Sets the RAID level for the volume in a raidDiskPool.
77 - Only relevant when the volume is created in a raidDiskPool.
78 - I(raid1) in a raidDiskPool is newly introduced in Raider (12.00) CFW.
79 type: str
80 choices: ["raid1", "raid6"]
81 required: false
82 thin_provision:
83 description:
84 - Whether the volume should be thin provisioned.
85 - Thin volumes can only be created in a raidDiskPool.
86 - Generally, use of thin-provisioning is not recommended due to performance impacts.
87 type: bool
88 default: false
89 required: false
90 thin_volume_repo_size:
91 description:
92 - This value (in size_unit) sets the allocated space for the thin provisioned repository.
93 - Initial value must between or equal to 4gb and 256gb in increments of 4gb.
94 - During expansion operations the increase must be between or equal to 4gb and 256gb in increments of 4gb.
95 - This option has no effect during expansion if I(thin_volume_expansion_policy=="automatic").
96 - Generally speaking you should almost always use I(thin_volume_expansion_policy=="automatic).
97 type: int
98 required: false
99 thin_volume_max_repo_size:
100 description:
101 - This is the maximum amount the thin volume repository will be allowed to grow.
102 - Only has significance when I(thin_volume_expansion_policy=="automatic").
103 - When the pct I(thin_volume_repo_size) of I(thin_volume_max_repo_size) exceeds
104 I(thin_volume_growth_alert_threshold) then a warning will be issued and the storage array will execute
105 the I(thin_volume_expansion_policy) policy.
106 - Expansion operations when I(thin_volume_expansion_policy=="automatic") will increase the maximum
107 repository size.
108 - Default will be the same as I(size).
109 type: float
110 required: false
111 thin_volume_expansion_policy:
112 description:
113 - This is the thin volume expansion policy.
114 - When I(thin_volume_expansion_policy=="automatic") and I(thin_volume_growth_alert_threshold) is exceed the
115 I(thin_volume_max_repo_size) will be automatically expanded.
116 - When I(thin_volume_expansion_policy=="manual") and I(thin_volume_growth_alert_threshold) is exceeded the
117 storage system will wait for manual intervention.
118 - The thin volume_expansion policy can not be modified on existing thin volumes in this module.
119 - Generally speaking you should almost always use I(thin_volume_expansion_policy=="automatic).
120 type: str
121 choices: ["automatic", "manual"]
122 default: "automatic"
123 required: false
124 thin_volume_growth_alert_threshold:
125 description:
126 - This is the thin provision repository utilization threshold (in percent).
127 - When the pct of used storage of the maximum repository size exceeds this value then a alert will
128 be issued and the I(thin_volume_expansion_policy) will be executed.
129 - Values must be between or equal to 10 and 99.
130 type: int
131 default: 95
132 required: false
133 owning_controller:
134 description:
135 - Specifies which controller will be the primary owner of the volume
136 - Not specifying will allow the controller to choose ownership.
137 type: str
138 choices: ["A", "B"]
139 required: false
140 ssd_cache_enabled:
141 description:
142 - Whether an existing SSD cache should be enabled on the volume (fails if no SSD cache defined)
143 - The default value is to ignore existing SSD cache setting.
144 type: bool
145 default: false
146 required: false
147 data_assurance_enabled:
148 description:
149 - Determines whether data assurance (DA) should be enabled for the volume
150 - Only available when creating a new volume and on a storage pool with drives supporting the DA capability.
151 type: bool
152 default: false
153 required: false
154 read_cache_enable:
155 description:
156 - Indicates whether read caching should be enabled for the volume.
157 type: bool
158 default: true
159 required: false
160 read_ahead_enable:
161 description:
162 - Indicates whether or not automatic cache read-ahead is enabled.
163 - This option has no effect on thinly provisioned volumes since the architecture for thin volumes cannot
164 benefit from read ahead caching.
165 type: bool
166 default: true
167 required: false
168 write_cache_enable:
169 description:
170 - Indicates whether write-back caching should be enabled for the volume.
171 type: bool
172 default: true
173 required: false
174 write_cache_mirror_enable:
175 description:
176 - Indicates whether write cache mirroring should be enabled.
177 type: bool
178 default: true
179 required: false
180 cache_without_batteries:
181 description:
182 - Indicates whether caching should be used without battery backup.
183 - Warning, I(cache_without_batteries==true) and the storage system looses power and there is no battery backup, data will be lost!
184 type: bool
185 default: false
186 required: false
187 workload_name:
188 description:
189 - Label for the workload defined by the metadata.
190 - When I(workload_name) and I(metadata) are specified then the defined workload will be added to the storage
191 array.
192 - When I(workload_name) exists on the storage array but the metadata is different then the workload
193 definition will be updated. (Changes will update all associated volumes!)
194 - Existing workloads can be retrieved using M(netapp_eseries.santricity.na_santricity_facts).
195 type: str
196 required: false
197 workload_metadata:
198 description:
199 - Dictionary containing meta data for the use, user, location, etc of the volume (dictionary is arbitrarily
200 defined for whatever the user deems useful)
201 - When I(workload_name) exists on the storage array but the metadata is different then the workload
202 definition will be updated. (Changes will update all associated volumes!)
203 - I(workload_name) must be specified when I(metadata) are defined.
204 - Dictionary key cannot be longer than 16 characters
205 - Dictionary values cannot be longer than 60 characters
206 type: dict
207 required: false
208 aliases:
209 - metadata
210 volume_metadata:
211 description:
212 - Dictionary containing metadata for the volume itself.
213 - Dictionary key cannot be longer than 14 characters
214 - Dictionary values cannot be longer than 240 characters
215 type: dict
216 required: false
217 allow_expansion:
218 description:
219 - Allows volume size to expand to meet the required specification.
220 - Warning, when I(allows_expansion==false) and the existing volume needs to be expanded the module will continue with a warning.
221 type: bool
222 default: false
223 required: false
224 wait_for_initialization:
225 description:
226 - Forces the module to wait for expansion operations to complete before continuing.
227 type: bool
228 default: false
229 required: false
230 """
231 EXAMPLES = """
232 - name: Create simple volume with workload tags (volume meta data)
233 na_santricity_volume:
234 ssid: "1"
235 api_url: "https://192.168.1.100:8443/devmgr/v2"
236 api_username: "admin"
237 api_password: "adminpass"
238 validate_certs: true
239 state: present
240 name: volume
241 storage_pool_name: storage_pool
242 size: 300
243 size_unit: gb
244 workload_name: volume_tag
245 metadata:
246 key1: value1
247 key2: value2
248
249 - name: Create a thin volume
250 na_santricity_volume:
251 ssid: "1"
252 api_url: "https://192.168.1.100:8443/devmgr/v2"
253 api_username: "admin"
254 api_password: "adminpass"
255 validate_certs: true
256 state: present
257 name: volume1
258 storage_pool_name: storage_pool
259 size: 131072
260 size_unit: gb
261 thin_provision: true
262 thin_volume_repo_size: 32
263 thin_volume_max_repo_size: 1024
264
265 - name: Expand thin volume's virtual size
266 na_santricity_volume:
267 ssid: "1"
268 api_url: "https://192.168.1.100:8443/devmgr/v2"
269 api_username: "admin"
270 api_password: "adminpass"
271 validate_certs: true
272 state: present
273 name: volume1
274 storage_pool_name: storage_pool
275 size: 262144
276 size_unit: gb
277 thin_provision: true
278 thin_volume_repo_size: 32
279 thin_volume_max_repo_size: 1024
280
281 - name: Expand thin volume's maximum repository size
282 na_santricity_volume:
283 ssid: "1"
284 api_url: "https://192.168.1.100:8443/devmgr/v2"
285 api_username: "admin"
286 api_password: "adminpass"
287 validate_certs: true
288 state: present
289 name: volume1
290 storage_pool_name: storage_pool
291 size: 262144
292 size_unit: gb
293 thin_provision: true
294 thin_volume_repo_size: 32
295 thin_volume_max_repo_size: 2048
296
297 - name: Delete volume
298 na_santricity_volume:
299 ssid: "1"
300 api_url: "https://192.168.1.100:8443/devmgr/v2"
301 api_username: "admin"
302 api_password: "adminpass"
303 validate_certs: true
304 state: absent
305 name: volume
306 """
307 RETURN = """
308 msg:
309 description: State of volume
310 type: str
311 returned: always
312 sample: "Standard volume [workload_vol_1] has been created."
313 """
314
315 import time
316
317 from ansible_collections.netapp_eseries.santricity.plugins.module_utils.santricity import NetAppESeriesModule
318 from ansible.module_utils._text import to_native
319
320
321 class NetAppESeriesVolume(NetAppESeriesModule):
322 VOLUME_CREATION_BLOCKING_TIMEOUT_SEC = 300
323 MAXIMUM_VOLUME_METADATA_KEY_LENGTH = 14
324 MAXIMUM_VOLUME_METADATA_VALUE_LENGTH = 240
325 MAXIMUM_VOLUME_METADATA_VALUE_SEGMENT_LENGTH = 60
326
327 def __init__(self):
328 ansible_options = dict(
329 state=dict(choices=["present", "absent"], default="present"),
330 name=dict(required=True, type="str"),
331 storage_pool_name=dict(type="str"),
332 size_unit=dict(default="gb", choices=["bytes", "b", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb", "pct"], type="str"),
333 size=dict(type="float", required=True),
334 size_tolerance_b=dict(type="int", required=False, default=10485760),
335 segment_size_kb=dict(type="int", default=128, required=False),
336 owning_controller=dict(type="str", choices=["A", "B"], required=False),
337 raid_level=dict(type="str", choices=["raid1", "raid6"], required=False),
338 ssd_cache_enabled=dict(type="bool", default=False),
339 data_assurance_enabled=dict(type="bool", default=False),
340 thin_provision=dict(type="bool", default=False),
341 thin_volume_repo_size=dict(type="int", required=False),
342 thin_volume_max_repo_size=dict(type="float", required=False),
343 thin_volume_expansion_policy=dict(type="str", choices=["automatic", "manual"], default="automatic", required=False),
344 thin_volume_growth_alert_threshold=dict(type="int", default=95),
345 read_cache_enable=dict(type="bool", default=True),
346 read_ahead_enable=dict(type="bool", default=True),
347 write_cache_enable=dict(type="bool", default=True),
348 write_cache_mirror_enable=dict(type="bool", default=True),
349 cache_without_batteries=dict(type="bool", default=False),
350 workload_name=dict(type="str", required=False),
351 workload_metadata=dict(type="dict", required=False, aliases=["metadata"]),
352 volume_metadata=dict(type="dict", required=False),
353 allow_expansion=dict(type="bool", default=False),
354 wait_for_initialization=dict(type="bool", default=False))
355
356 required_if = [
357 ["state", "present", ["storage_pool_name", "size"]],
358 ["thin_provision", "true", ["thin_volume_repo_size"]]
359 ]
360
361 super(NetAppESeriesVolume, self).__init__(ansible_options=ansible_options,
362 web_services_version="02.00.0000.0000",
363 supports_check_mode=True,
364 required_if=required_if)
365
366 args = self.module.params
367 self.state = args["state"]
368 self.name = args["name"]
369 self.storage_pool_name = args["storage_pool_name"]
370 self.size_unit = args["size_unit"]
371 self.size_tolerance_b = args["size_tolerance_b"]
372 self.segment_size_kb = args["segment_size_kb"]
373 self.raid_level = args.get("raid_level")
374
375 if args["size"]:
376 if self.size_unit == "pct":
377 if args["thin_provision"]:
378 self.module.fail_json(msg="'pct' is an invalid size unit for thin provisioning! Array [%s]." % self.ssid)
379 self.size_percent = args["size"]
380 else:
381 self.size_b = self.convert_to_aligned_bytes(args["size"])
382
383 self.owning_controller_id = None
384 if args["owning_controller"]:
385 self.owning_controller_id = "070000000000000000000001" if args["owning_controller"] == "A" else "070000000000000000000002"
386
387 self.read_cache_enable = args["read_cache_enable"]
388 self.read_ahead_enable = args["read_ahead_enable"]
389 self.write_cache_enable = args["write_cache_enable"]
390 self.write_cache_mirror_enable = args["write_cache_mirror_enable"]
391 self.ssd_cache_enabled = args["ssd_cache_enabled"]
392 self.cache_without_batteries = args["cache_without_batteries"]
393 self.data_assurance_enabled = args["data_assurance_enabled"]
394
395 self.thin_provision = args["thin_provision"]
396 self.thin_volume_expansion_policy = args["thin_volume_expansion_policy"]
397 self.thin_volume_growth_alert_threshold = int(args["thin_volume_growth_alert_threshold"])
398 self.thin_volume_repo_size_b = None
399 self.thin_volume_max_repo_size_b = None
400
401 if args["thin_volume_repo_size"]:
402 self.thin_volume_repo_size_b = self.convert_to_aligned_bytes(args["thin_volume_repo_size"])
403 if args["thin_volume_max_repo_size"]:
404 self.thin_volume_max_repo_size_b = self.convert_to_aligned_bytes(args["thin_volume_max_repo_size"])
405
406 self.workload_name = args["workload_name"]
407 self.allow_expansion = args["allow_expansion"]
408 self.wait_for_initialization = args["wait_for_initialization"]
409
410 # convert metadata to a list of dictionaries containing the keys "key" and "value" corresponding to
411 # each of the workload attributes dictionary entries
412 self.metadata = []
413 if self.state == "present" and args["workload_metadata"]:
414 if not self.workload_name:
415 self.module.fail_json(msg="When metadata is specified then the name for the workload must be specified. Array [%s]." % self.ssid)
416
417 for key, value in args["workload_metadata"].items():
418 self.metadata.append({"key": key, "value": value})
419
420 self.volume_metadata = []
421 if self.state == "present" and args["volume_metadata"]:
422 for key, value in args["volume_metadata"].items():
423 key, value = str(key), str(value)
424
425 if len(key) > self.MAXIMUM_VOLUME_METADATA_KEY_LENGTH:
426 self.module.fail_json(msg="Volume metadata keys must be less than %s characters long. Array [%s]."
427 % (str(self.MAXIMUM_VOLUME_METADATA_KEY_LENGTH), self.ssid))
428
429 if len(value) > self.MAXIMUM_VOLUME_METADATA_VALUE_LENGTH:
430 self.module.fail_json(msg="Volume metadata values must be less than %s characters long. Array [%s]."
431 % (str(self.MAXIMUM_VOLUME_METADATA_VALUE_LENGTH), self.ssid))
432
433 if value:
434 for index, start in enumerate(range(0, len(value), self.MAXIMUM_VOLUME_METADATA_VALUE_SEGMENT_LENGTH)):
435 if len(value) > start + self.MAXIMUM_VOLUME_METADATA_VALUE_SEGMENT_LENGTH:
436 self.volume_metadata.append({"key": "%s~%s" % (key, str(index)),
437 "value": value[start:start + self.MAXIMUM_VOLUME_METADATA_VALUE_SEGMENT_LENGTH]})
438 else:
439 self.volume_metadata.append({"key": "%s~%s" % (key, str(index)), "value": value[start:len(value)]})
440 else:
441 self.volume_metadata.append({"key": "%s~0" % key, "value": ""})
442
443 if self.state == "present" and self.thin_provision:
444 if not self.thin_volume_max_repo_size_b:
445 self.thin_volume_max_repo_size_b = self.size_b
446
447 if not self.thin_volume_expansion_policy:
448 self.thin_volume_expansion_policy = "automatic"
449
450 if self.size_b > 256 * 1024 ** 4:
451 self.module.fail_json(msg="Thin provisioned volumes must be less than or equal to 256tb is size."
452 " Attempted size [%sg]" % (self.size_b * 1024 ** 3))
453
454 if (self.thin_volume_repo_size_b and self.thin_volume_max_repo_size_b and
455 self.thin_volume_repo_size_b > self.thin_volume_max_repo_size_b):
456 self.module.fail_json(msg="The initial size of the thin volume must not be larger than the maximum"
457 " repository size. Array [%s]." % self.ssid)
458
459 if self.thin_volume_growth_alert_threshold < 10 or self.thin_volume_growth_alert_threshold > 99:
460 self.module.fail_json(msg="thin_volume_growth_alert_threshold must be between or equal to 10 and 99."
461 "thin_volume_growth_alert_threshold [%s]. Array [%s]."
462 % (self.thin_volume_growth_alert_threshold, self.ssid))
463
464 self.volume_detail = None
465 self.pool_detail = None
466 self.workload_id = None
467
468 def convert_to_aligned_bytes(self, size):
469 """Convert size to the truncated byte size that aligns on the segment size."""
470 size_bytes = int(size * self.SIZE_UNIT_MAP[self.size_unit])
471 segment_size_bytes = int(self.segment_size_kb * self.SIZE_UNIT_MAP["kb"])
472 segment_count = int(size_bytes / segment_size_bytes)
473 return segment_count * segment_size_bytes
474
475 def get_volume(self):
476 """Retrieve volume details from storage array."""
477 volumes = list()
478 thin_volumes = list()
479 try:
480 rc, volumes = self.request("storage-systems/%s/volumes" % self.ssid)
481 except Exception as err:
482 self.module.fail_json(msg="Failed to obtain list of thick volumes. Array Id [%s]. Error[%s]."
483 % (self.ssid, to_native(err)))
484 try:
485 rc, thin_volumes = self.request("storage-systems/%s/thin-volumes" % self.ssid)
486 except Exception as err:
487 self.module.fail_json(msg="Failed to obtain list of thin volumes. Array Id [%s]. Error[%s]."
488 % (self.ssid, to_native(err)))
489
490 volume_detail = [volume for volume in volumes + thin_volumes if volume["name"] == self.name]
491 return volume_detail[0] if volume_detail else dict()
492
493 def wait_for_volume_availability(self, retries=VOLUME_CREATION_BLOCKING_TIMEOUT_SEC / 5):
494 """Waits until volume becomes available.
495
496 :raises AnsibleFailJson when retries are exhausted.
497 """
498 if retries == 0:
499 self.module.fail_json(msg="Timed out waiting for the volume %s to become available. Array [%s]."
500 % (self.name, self.ssid))
501 if not self.get_volume():
502 time.sleep(5)
503 self.wait_for_volume_availability(retries=retries - 1)
504
505 def wait_for_volume_action(self, timeout=None):
506 """Waits until volume action is complete is complete.
507 :param: int timeout: Wait duration measured in seconds. Waits indefinitely when None.
508 """
509 action = "unknown"
510 percent_complete = None
511 while action != "complete":
512 time.sleep(5)
513
514 try:
515 rc, operations = self.request("storage-systems/%s/symbol/getLongLivedOpsProgress" % self.ssid)
516
517 # Search long lived operations for volume
518 action = "complete"
519 for operation in operations["longLivedOpsProgress"]:
520 if operation["volAction"] is not None:
521 for key in operation.keys():
522 if (operation[key] is not None and "volumeRef" in operation[key] and
523 (operation[key]["volumeRef"] == self.volume_detail["id"] or
524 ("storageVolumeRef" in self.volume_detail and operation[key]["volumeRef"] == self.volume_detail["storageVolumeRef"]))):
525 action = operation["volAction"]
526 percent_complete = operation["init"]["percentComplete"]
527 except Exception as err:
528 self.module.fail_json(msg="Failed to get volume expansion progress. Volume [%s]. Array Id [%s]."
529 " Error[%s]." % (self.name, self.ssid, to_native(err)))
530
531 if timeout is not None:
532 if timeout <= 0:
533 self.module.warn("Expansion action, %s, failed to complete during the allotted time. Time remaining"
534 " [%s]. Array Id [%s]." % (action, percent_complete, self.ssid))
535 self.module.fail_json(msg="Expansion action failed to complete. Time remaining [%s]. Array Id [%s]." % (percent_complete, self.ssid))
536 if timeout:
537 timeout -= 5
538
539 self.module.log("Expansion action, %s, is %s complete." % (action, percent_complete))
540 self.module.log("Expansion action is complete.")
541
542 def get_storage_pool(self):
543 """Retrieve storage pool details from the storage array."""
544 storage_pools = list()
545 try:
546 rc, storage_pools = self.request("storage-systems/%s/storage-pools" % self.ssid)
547 except Exception as err:
548 self.module.fail_json(msg="Failed to obtain list of storage pools. Array Id [%s]. Error[%s]."
549 % (self.ssid, to_native(err)))
550
551 pool_detail = [storage_pool for storage_pool in storage_pools if storage_pool["name"] == self.storage_pool_name]
552 return pool_detail[0] if pool_detail else dict()
553
554 def check_storage_pool_sufficiency(self):
555 """Perform a series of checks as to the sufficiency of the storage pool for the volume."""
556 if not self.pool_detail:
557 self.module.fail_json(msg='Requested storage pool (%s) not found' % self.storage_pool_name)
558
559 if not self.volume_detail:
560 if self.thin_provision and not self.pool_detail['diskPool']:
561 self.module.fail_json(msg='Thin provisioned volumes can only be created on raid disk pools.')
562
563 if (self.data_assurance_enabled and not
564 (self.pool_detail["protectionInformationCapabilities"]["protectionInformationCapable"] and
565 self.pool_detail["protectionInformationCapabilities"]["protectionType"] == "type2Protection")):
566 self.module.fail_json(msg="Data Assurance (DA) requires the storage pool to be DA-compatible."
567 " Array [%s]." % self.ssid)
568
569 if int(self.pool_detail["freeSpace"]) < self.size_b and not self.thin_provision:
570 self.module.fail_json(msg="Not enough storage pool free space available for the volume's needs."
571 " Array [%s]." % self.ssid)
572 else:
573 # Check for expansion
574 if (int(self.pool_detail["freeSpace"]) < int(self.volume_detail["totalSizeInBytes"]) - self.size_b and
575 not self.thin_provision):
576 self.module.fail_json(msg="Not enough storage pool free space available for the volume's needs."
577 " Array [%s]." % self.ssid)
578
579 def update_workload_tags(self, check_mode=False):
580 """Check the status of the workload tag and update storage array definitions if necessary.
581
582 When the workload attributes are not provided but an existing workload tag name is, then the attributes will be
583 used.
584
585 :return bool: Whether changes were required to be made."""
586 change_required = False
587 workload_tags = None
588 request_body = None
589 ansible_profile_id = None
590
591 if self.workload_name:
592 try:
593 rc, workload_tags = self.request("storage-systems/%s/workloads" % self.ssid)
594 except Exception as error:
595 self.module.fail_json(msg="Failed to retrieve storage array workload tags. Array [%s]" % self.ssid)
596
597 ansible_profile_id = "Other_1"
598 request_body = dict(name=self.workload_name,
599 profileId=ansible_profile_id,
600 workloadInstanceIndex=None,
601 isValid=True)
602
603 # evaluate and update storage array when needed
604 for tag in workload_tags:
605 if tag["name"] == self.workload_name:
606 self.workload_id = tag["id"]
607
608 if not self.metadata:
609 break
610
611 # Determine if core attributes (everything but profileId) is the same
612 metadata_set = set(tuple(sorted(attr.items())) for attr in self.metadata)
613 tag_set = set(tuple(sorted(attr.items()))
614 for attr in tag["workloadAttributes"] if attr["key"] != "profileId")
615 if metadata_set != tag_set:
616 self.module.log("Workload tag change is required!")
617 change_required = True
618
619 # only perform the required action when check_mode==False
620 if change_required and not check_mode:
621 self.metadata.append(dict(key="profileId", value=ansible_profile_id))
622 request_body.update(dict(isNewWorkloadInstance=False,
623 isWorkloadDataInitialized=True,
624 isWorkloadCardDataToBeReset=True,
625 workloadAttributes=self.metadata))
626 try:
627 rc, resp = self.request("storage-systems/%s/workloads/%s" % (self.ssid, tag["id"]),
628 data=request_body, method="POST")
629 except Exception as error:
630 self.module.fail_json(msg="Failed to create new workload tag. Array [%s]. Error [%s]"
631 % (self.ssid, to_native(error)))
632 self.module.log("Workload tag [%s] required change." % self.workload_name)
633 break
634
635 # existing workload tag not found so create new workload tag
636 else:
637 change_required = True
638 self.module.log("Workload tag creation is required!")
639
640 if change_required and not check_mode:
641 if self.metadata:
642 self.metadata.append(dict(key="profileId", value=ansible_profile_id))
643 else:
644 self.metadata = [dict(key="profileId", value=ansible_profile_id)]
645
646 request_body.update(dict(isNewWorkloadInstance=True,
647 isWorkloadDataInitialized=False,
648 isWorkloadCardDataToBeReset=False,
649 workloadAttributes=self.metadata))
650 try:
651 rc, resp = self.request("storage-systems/%s/workloads" % self.ssid,
652 method="POST", data=request_body)
653 self.workload_id = resp["id"]
654 except Exception as error:
655 self.module.fail_json(msg="Failed to create new workload tag. Array [%s]. Error [%s]"
656 % (self.ssid, to_native(error)))
657 self.module.log("Workload tag [%s] was added." % self.workload_name)
658
659 return change_required
660
661 def get_volume_property_changes(self):
662 """Retrieve the volume update request body when change(s) are required.
663
664 :raise AnsibleFailJson when attempting to change segment size on existing volume.
665 :return dict: request body when change(s) to a volume's properties are required.
666 """
667 change = False
668 request_body = dict(flashCache=self.ssd_cache_enabled, metaTags=[],
669 cacheSettings=dict(readCacheEnable=self.read_cache_enable,
670 writeCacheEnable=self.write_cache_enable,
671 mirrorEnable=self.write_cache_mirror_enable))
672
673 # check for invalid modifications
674 if self.segment_size_kb * 1024 != int(self.volume_detail["segmentSize"]):
675 self.module.fail_json(msg="Existing volume segment size is %s and cannot be modified."
676 % self.volume_detail["segmentSize"])
677
678 # common thick/thin volume properties
679 if (self.read_cache_enable != self.volume_detail["cacheSettings"]["readCacheEnable"] or
680 self.write_cache_enable != self.volume_detail["cacheSettings"]["writeCacheEnable"] or
681 self.write_cache_mirror_enable != self.volume_detail["cacheSettings"]["mirrorEnable"] or
682 self.ssd_cache_enabled != self.volume_detail["flashCached"]):
683 change = True
684
685 # controller ownership
686 if self.owning_controller_id and self.owning_controller_id != self.volume_detail["preferredManager"]:
687 change = True
688 request_body.update(dict(owningControllerId=self.owning_controller_id))
689
690 # volume meta tags
691 request_body["metaTags"].extend(self.volume_metadata)
692 for entry in self.volume_metadata:
693 if entry not in self.volume_detail["metadata"]:
694 change = True
695
696 if self.workload_name:
697 request_body["metaTags"].extend([{"key": "workloadId", "value": self.workload_id},
698 {"key": "volumeTypeId", "value": "volume"}])
699
700 if ({"key": "workloadId", "value": self.workload_id} not in self.volume_detail["metadata"] or
701 {"key": "volumeTypeId", "value": "volume"} not in self.volume_detail["metadata"]):
702 change = True
703
704 if len(self.volume_detail["metadata"]) != len(request_body["metaTags"]):
705 change = True
706
707 # thick/thin volume specific properties
708 if self.thin_provision:
709 if self.thin_volume_growth_alert_threshold != int(self.volume_detail["growthAlertThreshold"]):
710 change = True
711 request_body.update(dict(growthAlertThreshold=self.thin_volume_growth_alert_threshold))
712 if self.thin_volume_expansion_policy != self.volume_detail["expansionPolicy"]:
713 change = True
714 request_body.update(dict(expansionPolicy=self.thin_volume_expansion_policy))
715 else:
716 if self.read_ahead_enable != (int(self.volume_detail["cacheSettings"]["readAheadMultiplier"]) > 0):
717 change = True
718 request_body["cacheSettings"].update(dict(readAheadEnable=self.read_ahead_enable))
719 if self.cache_without_batteries != self.volume_detail["cacheSettings"]["cwob"]:
720 change = True
721 request_body["cacheSettings"].update(dict(cacheWithoutBatteries=self.cache_without_batteries))
722
723 return request_body if change else dict()
724
725 def get_expand_volume_changes(self):
726 """Expand the storage specifications for the existing thick/thin volume.
727
728 :raise AnsibleFailJson when a thick/thin volume expansion request fails.
729 :return dict: dictionary containing all the necessary values for volume expansion request
730 """
731 request_body = dict()
732
733 if self.size_b < int(self.volume_detail["capacity"]) - self.size_tolerance_b:
734 self.module.fail_json(msg="Reducing the size of volumes is not permitted. Volume [%s]. Array [%s]"
735 % (self.name, self.ssid))
736
737 if self.volume_detail["thinProvisioned"]:
738 if self.size_b > int(self.volume_detail["capacity"]) + self.size_tolerance_b:
739 request_body.update(dict(sizeUnit="bytes", newVirtualSize=self.size_b))
740 self.module.log("Thin volume virtual size have been expanded.")
741
742 if self.volume_detail["expansionPolicy"] == "automatic":
743 if self.thin_volume_max_repo_size_b > int(self.volume_detail["provisionedCapacityQuota"]) + self.size_tolerance_b:
744 request_body.update(dict(sizeUnit="bytes", newRepositorySize=self.thin_volume_max_repo_size_b))
745 self.module.log("Thin volume maximum repository size have been expanded (automatic policy).")
746
747 elif self.volume_detail["expansionPolicy"] == "manual":
748 if self.thin_volume_repo_size_b > int(self.volume_detail["currentProvisionedCapacity"]) + self.size_tolerance_b:
749 change = self.thin_volume_repo_size_b - int(self.volume_detail["currentProvisionedCapacity"])
750 if change < 4 * 1024 ** 3 or change > 256 * 1024 ** 3 or change % (4 * 1024 ** 3) != 0:
751 self.module.fail_json(msg="The thin volume repository increase must be between or equal to 4gb"
752 " and 256gb in increments of 4gb. Attempted size [%sg]."
753 % (self.thin_volume_repo_size_b * 1024 ** 3))
754
755 request_body.update(dict(sizeUnit="bytes", newRepositorySize=self.thin_volume_repo_size_b))
756 self.module.log("Thin volume maximum repository size have been expanded (manual policy).")
757
758 elif self.size_b > int(self.volume_detail["capacity"]) + self.size_tolerance_b:
759 request_body.update(dict(sizeUnit="bytes", expansionSize=self.size_b))
760 self.module.log("Volume storage capacities have been expanded.")
761
762 if request_body and not self.allow_expansion:
763 self.module.warn("Expansion not allowed! Change allow_expansion flag to true to allow volume expansions. Array Id [%s]." % self.ssid)
764 return dict()
765
766 return request_body
767
768 def create_volume(self):
769 """Create thick/thin volume according to the specified criteria."""
770 is_disk_pool = self.pool_detail.get("diskPool", False)
771
772 body = dict(name=self.name, poolId=self.pool_detail["id"], sizeUnit="bytes",
773 dataAssuranceEnabled=self.data_assurance_enabled)
774
775 if self.volume_metadata:
776 body.update({"metaTags": self.volume_metadata})
777
778 if self.thin_provision:
779 body.update(dict(virtualSize=self.size_b,
780 repositorySize=self.thin_volume_repo_size_b,
781 maximumRepositorySize=self.thin_volume_max_repo_size_b,
782 expansionPolicy=self.thin_volume_expansion_policy,
783 growthAlertThreshold=self.thin_volume_growth_alert_threshold))
784 try:
785 rc, volume = self.request("storage-systems/%s/thin-volumes" % self.ssid, data=body, method="POST")
786 except Exception as error:
787 self.module.fail_json(msg="Failed to create thin volume. Volume [%s]. Array Id [%s]. Error[%s]."
788 % (self.name, self.ssid, to_native(error)))
789
790 self.module.log("New thin volume created [%s]." % self.name)
791
792 else:
793 body.update(dict(size=self.size_b, segSize=self.segment_size_kb))
794 if is_disk_pool and self.raid_level:
795 body.update(dict(raidLevel=self.raid_level))
796 try:
797 rc, volume = self.request("storage-systems/%s/volumes" % self.ssid, data=body, method="POST")
798 except Exception as error:
799 self.module.fail_json(msg="Failed to create volume. Volume [%s]. Array Id [%s]. Error[%s]."
800 % (self.name, self.ssid, to_native(error)))
801 self.module.log("New volume created [%s]." % self.name)
802
803 def update_volume_properties(self):
804 """Update existing thin-volume or volume properties.
805
806 :raise AnsibleFailJson when either thick/thin volume update request fails.
807 :return bool: whether update was applied
808 """
809 self.wait_for_volume_availability()
810 self.volume_detail = self.get_volume()
811
812 request_body = self.get_volume_property_changes()
813
814 if request_body:
815 if self.thin_provision:
816 try:
817 rc, resp = self.request("storage-systems/%s/thin-volumes/%s"
818 % (self.ssid, self.volume_detail["id"]), data=request_body, method="POST")
819 except Exception as error:
820 self.module.fail_json(msg="Failed to update thin volume properties. Volume [%s]. Array Id [%s]."
821 " Error[%s]." % (self.name, self.ssid, to_native(error)))
822 else:
823 try:
824 rc, resp = self.request("storage-systems/%s/volumes/%s" % (self.ssid, self.volume_detail["id"]),
825 data=request_body, method="POST")
826 except Exception as error:
827 self.module.fail_json(msg="Failed to update volume properties. Volume [%s]. Array Id [%s]."
828 " Error[%s]." % (self.name, self.ssid, to_native(error)))
829 return True
830 return False
831
832 def expand_volume(self):
833 """Expand the storage specifications for the existing thick/thin volume.
834
835 :raise AnsibleFailJson when a thick/thin volume expansion request fails.
836 """
837 request_body = self.get_expand_volume_changes()
838 if request_body:
839 if self.volume_detail["thinProvisioned"]:
840 try:
841 rc, resp = self.request("storage-systems/%s/thin-volumes/%s/expand"
842 % (self.ssid, self.volume_detail["id"]), data=request_body, method="POST")
843 except Exception as err:
844 self.module.fail_json(msg="Failed to expand thin volume. Volume [%s]. Array Id [%s]. Error[%s]."
845 % (self.name, self.ssid, to_native(err)))
846 self.module.log("Thin volume specifications have been expanded.")
847
848 else:
849 try:
850 rc, resp = self.request(
851 "storage-systems/%s/volumes/%s/expand" % (self.ssid, self.volume_detail['id']),
852 data=request_body, method="POST")
853 except Exception as err:
854 self.module.fail_json(msg="Failed to expand volume. Volume [%s]. Array Id [%s]. Error[%s]."
855 % (self.name, self.ssid, to_native(err)))
856
857 self.module.log("Volume storage capacities have been expanded.")
858
859 def delete_volume(self):
860 """Delete existing thin/thick volume."""
861 if self.thin_provision:
862 try:
863 rc, resp = self.request("storage-systems/%s/thin-volumes/%s" % (self.ssid, self.volume_detail["id"]),
864 method="DELETE")
865 except Exception as error:
866 self.module.fail_json(msg="Failed to delete thin volume. Volume [%s]. Array Id [%s]. Error[%s]."
867 % (self.name, self.ssid, to_native(error)))
868 self.module.log("Thin volume deleted [%s]." % self.name)
869 else:
870 try:
871 rc, resp = self.request("storage-systems/%s/volumes/%s" % (self.ssid, self.volume_detail["id"]),
872 method="DELETE")
873 except Exception as error:
874 self.module.fail_json(msg="Failed to delete volume. Volume [%s]. Array Id [%s]. Error[%s]."
875 % (self.name, self.ssid, to_native(error)))
876 self.module.log("Volume deleted [%s]." % self.name)
877
878 def apply(self):
879 """Determine and apply any changes necessary to satisfy the specified criteria.
880
881 :raise AnsibleExitJson when completes successfully"""
882 change = False
883 msg = None
884
885 self.volume_detail = self.get_volume()
886 self.pool_detail = self.get_storage_pool()
887
888 if self.pool_detail and self.size_unit == "pct":
889 space_mb = round(float(self.pool_detail["totalRaidedSpace"]), -8) / 1024 ** 2 - 100
890 self.size_unit = "mb"
891 self.size_b = self.convert_to_aligned_bytes(space_mb * (self.size_percent / 100))
892
893 # Determine whether changes need to be applied to existing workload tags
894 if self.state == 'present' and self.update_workload_tags(check_mode=True):
895 change = True
896
897 # Determine if any changes need to be applied
898 if self.volume_detail:
899 if self.state == 'absent':
900 change = True
901
902 elif self.state == 'present':
903 # Must check the property changes first as it makes sure the segment size has no change before
904 # using the size to determine if the volume expansion is needed which will cause an irrelevant
905 # error message to show up.
906 if self.get_volume_property_changes() or self.get_expand_volume_changes():
907 change = True
908
909 elif self.state == 'present':
910 if self.thin_provision and (self.thin_volume_repo_size_b < 4 * 1024 ** 3 or
911 self.thin_volume_repo_size_b > 256 * 1024 ** 3 or
912 self.thin_volume_repo_size_b % (4 * 1024 ** 3) != 0):
913 self.module.fail_json(msg="The initial thin volume repository size must be between 4gb and 256gb in"
914 " increments of 4gb. Attempted size [%sg]."
915 % (self.thin_volume_repo_size_b * 1024 ** 3))
916 change = True
917
918 self.module.log("Update required: [%s]." % change)
919
920 # Apply any necessary changes
921 if change and not self.module.check_mode:
922 if self.state == 'present':
923 if self.update_workload_tags():
924 msg = "Workload tag change occurred."
925
926 if not self.volume_detail:
927 self.check_storage_pool_sufficiency()
928 self.create_volume()
929 self.update_volume_properties()
930 msg = msg[:-1] + " and volume [%s] was created." if msg else "Volume [%s] has been created."
931 else:
932 if self.update_volume_properties():
933 msg = "Volume [%s] properties were updated."
934
935 if self.get_expand_volume_changes():
936 self.expand_volume()
937 msg = msg[:-1] + " and was expanded." if msg else "Volume [%s] was expanded."
938
939 if self.wait_for_initialization:
940 self.module.log("Waiting for volume operation to complete.")
941 self.wait_for_volume_action()
942
943 elif self.state == 'absent':
944 self.delete_volume()
945 msg = "Volume [%s] has been deleted."
946
947 else:
948 msg = "Volume [%s] does not exist." if self.state == 'absent' else "Volume [%s] exists."
949
950 self.module.exit_json(msg=(msg % self.name if msg and "%s" in msg else msg), changed=change)
951
952
953 def main():
954 volume = NetAppESeriesVolume()
955 volume.apply()
956
957
958 if __name__ == '__main__':
959 main()