Debian Codegraph @

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