Debian Codegraph @

ansible_collections/dellemc/unity/plugins/modules/volume.py

raw symbols SCIP
1 #!/usr/bin/python
2 # Copyright: (c) 2020-2025, Dell Technologies
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 """Ansible module for managing volumes on Unity"""
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 DOCUMENTATION = r"""
12
13 module: volume
14 version_added: '1.1.0'
15 short_description: Manage volume on Unity storage system
16 description:
17 - Managing volume on Unity storage system includes-
18 Create new volume,
19 Modify volume attributes,
20 Map Volume to host,
21 Unmap volume to host,
22 Display volume details,
23 Delete volume.
24
25 extends_documentation_fragment:
26 - dellemc.unity.unity
27
28 author:
29 - Arindam Datta (@arindam-emc) <[email protected]>
30 - Pavan Mudunuri(@Pavan-Mudunuri) <[email protected]>
31
32 options:
33 vol_name:
34 description:
35 - The name of the volume. Mandatory only for create operation.
36 type: str
37 vol_id:
38 description:
39 - The id of the volume.
40 - It can be used only for get, modify, map/unmap host, or delete operation.
41 type: str
42 pool_name:
43 description:
44 - This is the name of the pool where the volume will be created.
45 - Either the I(pool_name) or I(pool_id) must be provided to create a new volume.
46 type: str
47 pool_id:
48 description:
49 - This is the id of the pool where the volume will be created.
50 - Either the I(pool_name) or I(pool_id) must be provided to create a new volume.
51 type: str
52 size:
53 description:
54 - The size of the volume.
55 type: int
56 cap_unit:
57 description:
58 - The unit of the volume size. It defaults to C(GB), if not specified.
59 choices: ['GB' , 'TB']
60 type: str
61 description:
62 description:
63 - Description about the volume.
64 - Description can be removed by passing empty string ("").
65 type: str
66 snap_schedule:
67 description:
68 - Snapshot schedule assigned to the volume.
69 - Add/Remove/Modify the snapshot schedule for the volume.
70 type: str
71 compression:
72 description:
73 - Boolean variable, Specifies whether or not to enable compression.
74 Compression is supported only for thin volumes.
75 type: bool
76 advanced_dedup:
77 description:
78 - Boolean variable, Indicates whether or not to enable advanced deduplication.
79 - Compression should be enabled to enable advanced deduplication.
80 - It can only be enabled on the all flash high end platforms.
81 - Deduplicated data will remain as is even after advanced deduplication is disabled.
82 type: bool
83 is_thin:
84 description:
85 - Boolean variable, Specifies whether or not it is a thin volume.
86 - The value is set as C(true) by default if not specified.
87 type: bool
88 sp:
89 description:
90 - Storage Processor for this volume.
91 choices: ['SPA' , 'SPB']
92 type: str
93 io_limit_policy:
94 description:
95 - IO limit policy associated with this volume.
96 Once it is set, it cannot be removed through ansible module but it can
97 be changed.
98 type: str
99 host_name:
100 description:
101 - Name of the host to be mapped/unmapped with this volume.
102 - Either I(host_name) or I(host_id) can be specified in one task along with
103 I(mapping_state).
104 type: str
105 host_id:
106 description:
107 - ID of the host to be mapped/unmapped with this volume.
108 - Either I(host_name) or I(host_id) can be specified in one task along with
109 I(mapping_state).
110 type: str
111 hlu:
112 description:
113 - Host Lun Unit to be mapped/unmapped with this volume.
114 - It is an optional parameter, hlu can be specified along
115 with I(host_name) or I(host_id) and I(mapping_state).
116 - If I(hlu) is not specified, unity will choose it automatically.
117 The maximum value supported is C(255).
118 type: int
119 mapping_state:
120 description:
121 - State of host access for volume.
122 choices: ['mapped' , 'unmapped']
123 type: str
124 new_vol_name:
125 description:
126 - New name of the volume for rename operation.
127 type: str
128 tiering_policy:
129 description:
130 - Tiering policy choices for how the storage resource data will be
131 distributed among the tiers available in the pool.
132 choices: ['AUTOTIER_HIGH', 'AUTOTIER', 'HIGHEST', 'LOWEST']
133 type: str
134 state:
135 description:
136 - State variable to determine whether volume will exist or not.
137 choices: ['absent', 'present']
138 required: true
139 type: str
140 hosts:
141 description:
142 - Name of hosts for mapping to a volume.
143 type: list
144 elements: dict
145 suboptions:
146 host_name:
147 description:
148 - Name of the host.
149 type: str
150 host_id:
151 description:
152 - ID of the host.
153 type: str
154 hlu:
155 description:
156 - Host Lun Unit to be mapped/unmapped with this volume.
157 - It is an optional parameter, I(hlu) can be specified along
158 with I(host_name) or I(host_id) and I(mapping_state).
159 - If I(hlu) is not specified, unity will choose it automatically.
160 The maximum value supported is C(255).
161 type: str
162
163 notes:
164 - The I(check_mode) is not supported.
165 """
166
167 EXAMPLES = r"""
168 - name: Create Volume
169 volume:
170 unispherehost: "{{unispherehost}}"
171 username: "{{username}}"
172 password: "{{password}}"
173 validate_certs: "{{validate_certs}}"
174 vol_name: "{{vol_name}}"
175 description: "{{description}}"
176 pool_name: "{{pool}}"
177 size: 2
178 cap_unit: "{{cap_GB}}"
179 is_thin: true
180 compression: true
181 advanced_dedup: true
182 state: "{{state_present}}"
183
184 - name: Expand Volume by volume id
185 volume:
186 unispherehost: "{{unispherehost}}"
187 username: "{{username}}"
188 password: "{{password}}"
189 validate_certs: "{{validate_certs}}"
190 vol_id: "{{vol_id}}"
191 size: 5
192 cap_unit: "{{cap_GB}}"
193 state: "{{state_present}}"
194
195 - name: Modify Volume, map host by host_name
196 volume:
197 unispherehost: "{{unispherehost}}"
198 username: "{{username}}"
199 password: "{{password}}"
200 validate_certs: "{{validate_certs}}"
201 vol_name: "{{vol_name}}"
202 host_name: "{{host_name}}"
203 hlu: 5
204 mapping_state: "{{state_mapped}}"
205 state: "{{state_present}}"
206
207 - name: Modify Volume, unmap host mapping by host_name
208 volume:
209 unispherehost: "{{unispherehost}}"
210 username: "{{username}}"
211 password: "{{password}}"
212 validate_certs: "{{validate_certs}}"
213 vol_name: "{{vol_name}}"
214 host_name: "{{host_name}}"
215 mapping_state: "{{state_unmapped}}"
216 state: "{{state_present}}"
217
218 - name: Map multiple hosts to a Volume
219 volume:
220 unispherehost: "{{unispherehost}}"
221 username: "{{username}}"
222 password: "{{password}}"
223 validate_certs: "{{validate_certs}}"
224 vol_id: "{{vol_id}}"
225 hosts:
226 - host_name: "10.226.198.248"
227 hlu: 1
228 - host_id: "Host_929"
229 hlu: 2
230 mapping_state: "mapped"
231 state: "present"
232
233 - name: Modify Volume attributes
234 volume:
235 unispherehost: "{{unispherehost}}"
236 username: "{{username}}"
237 password: "{{password}}"
238 validate_certs: "{{validate_certs}}"
239 vol_name: "{{vol_name}}"
240 new_vol_name: "{{new_vol_name}}"
241 tiering_policy: "AUTOTIER"
242 compression: true
243 is_thin: true
244 advanced_dedup: true
245 state: "{{state_present}}"
246
247 - name: Delete Volume by vol name
248 volume:
249 unispherehost: "{{unispherehost}}"
250 username: "{{username}}"
251 password: "{{password}}"
252 validate_certs: "{{validate_certs}}"
253 vol_name: "{{vol_name}}"
254 state: "{{state_absent}}"
255
256 - name: Delete Volume by vol id
257 volume:
258 unispherehost: "{{unispherehost}}"
259 username: "{{username}}"
260 password: "{{password}}"
261 validate_certs: "{{validate_certs}}"
262 vol_id: "{{vol_id}}"
263 state: "{{state_absent}}"
264 """
265
266 RETURN = r'''
267
268 changed:
269 description: Whether or not the resource has changed.
270 returned: always
271 type: bool
272 sample: true
273
274 volume_details:
275 description: Details of the volume.
276 returned: When volume exists
277 type: dict
278 contains:
279 id:
280 description: The system generated ID given to the volume.
281 type: str
282 name:
283 description: Name of the volume.
284 type: str
285 description:
286 description: Description about the volume.
287 type: str
288 is_data_reduction_enabled:
289 description: Whether or not compression enabled on this volume.
290 type: bool
291 size_total_with_unit:
292 description: Size of the volume with actual unit.
293 type: str
294 snap_schedule:
295 description: Snapshot schedule applied to this volume.
296 type: dict
297 tiering_policy:
298 description: Tiering policy applied to this volume.
299 type: str
300 current_sp:
301 description: Current storage processor for this volume.
302 type: str
303 pool:
304 description: The pool in which this volume is allocated.
305 type: dict
306 host_access:
307 description: Host mapped to this volume.
308 type: list
309 io_limit_policy:
310 description: IO limit policy associated with this volume.
311 type: dict
312 wwn:
313 description: The world wide name of this volume.
314 type: str
315 is_thin_enabled:
316 description: Indicates whether thin provisioning is enabled for this
317 volume.
318 type: bool
319 sample: {
320 "current_node": "NodeEnum.SPB",
321 "data_reduction_percent": 0,
322 "data_reduction_ratio": 1.0,
323 "data_reduction_size_saved": 0,
324 "default_node": "NodeEnum.SPB",
325 "description": null,
326 "effective_io_limit_max_iops": null,
327 "effective_io_limit_max_kbps": null,
328 "existed": true,
329 "family_base_lun": {
330 "UnityLun": {
331 "hash": 8774954523796,
332 "id": "sv_27"
333 }
334 },
335 "family_clone_count": 0,
336 "hash": 8774954522426,
337 "health": {
338 "UnityHealth": {
339 "hash": 8774954528278
340 }
341 },
342 "host_access": [
343 {
344 "accessMask": "PRODUCTION",
345 "hlu": 0,
346 "id": "Host_75",
347 "name": "10.226.198.250"
348 }
349 ],
350 "id": "sv_27",
351 "io_limit_policy": null,
352 "is_advanced_dedup_enabled": false,
353 "is_compression_enabled": null,
354 "is_data_reduction_enabled": false,
355 "is_replication_destination": false,
356 "is_snap_schedule_paused": false,
357 "is_thin_clone": false,
358 "is_thin_enabled": false,
359 "metadata_size": 4294967296,
360 "metadata_size_allocated": 4026531840,
361 "name": "VSI-UNITY-test-task",
362 "per_tier_size_used": [
363 111400714240,
364 0,
365 0
366 ],
367 "pool": {
368 "id": "pool_3",
369 "name": "Extreme_Perf_tier"
370 },
371 "size_allocated": 107374182400,
372 "size_total": 107374182400,
373 "size_total_with_unit": "100.0 GB",
374 "size_used": null,
375 "snap_count": 0,
376 "snap_schedule": null,
377 "snap_wwn": "60:06:01:60:5C:F0:50:00:94:3E:91:4D:51:5A:4F:97",
378 "snaps_size": 0,
379 "snaps_size_allocated": 0,
380 "storage_resource": {
381 "UnityStorageResource": {
382 "hash": 8774954518887
383 }
384 },
385 "tiering_policy": "TieringPolicyEnum.AUTOTIER_HIGH",
386 "type": "LUNTypeEnum.VMWARE_ISCSI",
387 "wwn": "60:06:01:60:5C:F0:50:00:00:B5:95:61:2E:34:DB:B2"
388 }
389 '''
390
391 from ansible.module_utils.basic import AnsibleModule
392 from ansible_collections.dellemc.unity.plugins.module_utils.storage.dell \
393 import utils
394
395 LOG = utils.get_logger('volume')
396
397 application_type = "Ansible/1.7.1"
398
399
400 def is_none_or_empty_string(param):
401
402 """ validates the input string for None or empty values
403 """
404 return not param or len(str(param)) <= 0
405
406
407 class Volume(object):
408
409 """Class with volume operations"""
410
411 param_host_id = None
412 param_io_limit_pol_id = None
413 param_snap_schedule_name = None
414
415 def __init__(self):
416 """Define all parameters required by this module"""
417 self.module_params = utils.get_unity_management_host_parameters()
418 self.module_params.update(get_volume_parameters())
419
420 mutually_exclusive = [['vol_name', 'vol_id'],
421 ['pool_name', 'pool_id'],
422 ['host_name', 'host_id']]
423
424 required_one_of = [['vol_name', 'vol_id']]
425
426 # initialize the Ansible module
427 self.module = AnsibleModule(
428 argument_spec=self.module_params,
429 supports_check_mode=False,
430 mutually_exclusive=mutually_exclusive,
431 required_one_of=required_one_of)
432 utils.ensure_required_libs(self.module)
433
434 self.unity_conn = utils.get_unity_unisphere_connection(
435 self.module.params, application_type)
436
437 def get_volume(self, vol_name=None, vol_id=None):
438 """Get the details of a volume.
439 :param vol_name: The name of the volume
440 :param vol_id: The id of the volume
441 :return: instance of the respective volume if exist.
442 """
443
444 id_or_name = vol_id if vol_id else vol_name
445 errormsg = "Failed to get the volume {0} with error {1}"
446
447 try:
448
449 obj_vol = self.unity_conn.get_lun(name=vol_name, _id=vol_id)
450
451 if vol_id and obj_vol.existed:
452 LOG.info("Successfully got the volume object %s ", obj_vol)
453 return obj_vol
454 elif vol_name:
455 LOG.info("Successfully got the volume object %s ", obj_vol)
456 return obj_vol
457 else:
458 LOG.info("Failed to get the volume %s", id_or_name)
459 return None
460
461 except utils.HttpError as e:
462 if e.http_status == 401:
463 cred_err = "Incorrect username or password , {0}".format(
464 e.message)
465 msg = errormsg.format(id_or_name, cred_err)
466 self.module.fail_json(msg=msg)
467 else:
468 msg = errormsg.format(id_or_name, str(e))
469 self.module.fail_json(msg=msg)
470
471 except utils.UnityResourceNotFoundError as e:
472 msg = errormsg.format(id_or_name, str(e))
473 LOG.error(msg)
474 return None
475
476 except Exception as e:
477 msg = errormsg.format(id_or_name, str(e))
478 LOG.error(msg)
479 self.module.fail_json(msg=msg)
480
481 def get_host(self, host_name=None, host_id=None):
482 """Get the instance of a host.
483 :param host_name: The name of the host
484 :param host_id: The id of the volume
485 :return: instance of the respective host if exist.
486 """
487
488 id_or_name = host_id if host_id else host_name
489 errormsg = "Failed to get the host {0} with error {1}"
490
491 try:
492
493 obj_host = self.unity_conn.get_host(name=host_name, _id=host_id)
494
495 if host_id and obj_host.existed:
496 LOG.info("Successfully got the host object %s ", obj_host)
497 return obj_host
498 elif host_name:
499 LOG.info("Successfully got the host object %s ", obj_host)
500 return obj_host
501 else:
502 msg = "Failed to get the host {0}".format(id_or_name)
503 LOG.error(msg)
504 self.module.fail_json(msg=msg)
505
506 except Exception as e:
507
508 msg = errormsg.format(id_or_name, str(e))
509 LOG.error(msg)
510 self.module.fail_json(msg=msg)
511
512 def get_snap_schedule(self, name):
513 """Get the instance of a snapshot schedule.
514 :param name: The name of the snapshot schedule
515 :return: instance of the respective snapshot schedule if exist.
516 """
517
518 errormsg = "Failed to get the snapshot schedule {0} with error {1}"
519
520 try:
521 LOG.debug("Attempting to get Snapshot Schedule with name %s",
522 name)
523 obj_ss = utils.UnitySnapScheduleList.get(self.unity_conn._cli,
524 name=name)
525 if obj_ss and (len(obj_ss) > 0):
526 LOG.info("Successfully got Snapshot Schedule %s", obj_ss)
527 return obj_ss
528 else:
529 msg = "Failed to get snapshot schedule " \
530 "with name {0}".format(name)
531 LOG.error(msg)
532 self.module.fail_json(msg=msg)
533
534 except Exception as e:
535 msg = errormsg.format(name, str(e))
536 LOG.error(msg)
537 self.module.fail_json(msg=msg)
538
539 def get_io_limit_policy(self, name=None, id=None):
540 """Get the instance of a io limit policy.
541 :param name: The io limit policy name
542 :param id: The io limit policy id
543 :return: instance of the respective io_limit_policy if exist.
544 """
545
546 errormsg = "Failed to get the io limit policy {0} with error {1}"
547 id_or_name = name if name else id
548
549 try:
550 obj_iopol = self.unity_conn.get_io_limit_policy(_id=id, name=name)
551 if id and obj_iopol.existed:
552 LOG.info("Successfully got the IO limit policy object %s",
553 obj_iopol)
554 return obj_iopol
555 elif name:
556 LOG.info("Successfully got the IO limit policy object %s ",
557 obj_iopol)
558 return obj_iopol
559 else:
560 msg = "Failed to get the io limit policy with {0}".format(
561 id_or_name)
562 LOG.error(msg)
563 self.module.fail_json(msg=msg)
564
565 except Exception as e:
566 msg = errormsg.format(name, str(e))
567 LOG.error(msg)
568 self.module.fail_json(msg=msg)
569
570 def get_pool(self, pool_name=None, pool_id=None):
571 """Get the instance of a pool.
572 :param pool_name: The name of the pool
573 :param pool_id: The id of the pool
574 :return: Dict containing pool details if exists
575 """
576
577 id_or_name = pool_id if pool_id else pool_name
578 errormsg = "Failed to get the pool {0} with error {1}"
579
580 try:
581 obj_pool = self.unity_conn.get_pool(name=pool_name, _id=pool_id)
582
583 if pool_id and obj_pool.existed:
584 LOG.info("Successfully got the pool object %s",
585 obj_pool)
586 return obj_pool
587 if pool_name:
588 LOG.info("Successfully got pool %s", obj_pool)
589 return obj_pool
590 else:
591 msg = "Failed to get the pool with " \
592 "{0}".format(id_or_name)
593 LOG.error(msg)
594 self.module.fail_json(msg=msg)
595
596 except Exception as e:
597 msg = errormsg.format(id_or_name, str(e))
598 LOG.error(msg)
599 self.module.fail_json(msg=msg)
600
601 def get_node_enum(self, sp):
602 """Get the storage processor enum.
603 :param sp: The storage processor string
604 :return: storage processor enum
605 """
606
607 if sp in utils.NodeEnum.__members__:
608 return utils.NodeEnum[sp]
609 else:
610 errormsg = "Invalid choice {0} for storage processor".format(
611 sp)
612 LOG.error(errormsg)
613 self.module.fail_json(msg=errormsg)
614
615 def get_tiering_policy_enum(self, tiering_policy):
616 """Get the tiering_policy enum.
617 :param tiering_policy: The tiering_policy string
618 :return: tiering_policy enum
619 """
620
621 if tiering_policy in utils.TieringPolicyEnum.__members__:
622 return utils.TieringPolicyEnum[tiering_policy]
623 else:
624 errormsg = "Invalid choice {0} for tiering policy".format(
625 tiering_policy)
626 LOG.error(errormsg)
627 self.module.fail_json(msg=errormsg)
628
629 def create_volume(self, obj_pool, size, host_access=None):
630 """Create a volume.
631 :param obj_pool: pool object instance
632 :param size: size of the volume in GB
633 :param host_access: host to be associated with this volume
634 :return: Volume object on successful creation
635 """
636
637 vol_name = self.module.params['vol_name']
638
639 try:
640
641 description = self.module.params['description']
642 compression = self.module.params['compression']
643 advanced_dedup = self.module.params['advanced_dedup']
644 is_thin = self.module.params['is_thin']
645 snap_schedule = None
646
647 sp = self.module.params['sp']
648 sp = self.get_node_enum(sp) if sp else None
649
650 io_limit_policy = self.get_io_limit_policy(
651 id=self.param_io_limit_pol_id) \
652 if self.module.params['io_limit_policy'] else None
653
654 if self.param_snap_schedule_name:
655 snap_schedule = {"name": self.param_snap_schedule_name}
656
657 tiering_policy = self.module.params['tiering_policy']
658 tiering_policy = self.get_tiering_policy_enum(tiering_policy) \
659 if tiering_policy else None
660
661 obj_vol = obj_pool.create_lun(lun_name=vol_name,
662 size_gb=size,
663 sp=sp,
664 host_access=host_access,
665 is_thin=is_thin,
666 description=description,
667 tiering_policy=tiering_policy,
668 snap_schedule=snap_schedule,
669 io_limit_policy=io_limit_policy,
670 is_compression=compression,
671 is_advanced_dedup_enabled=advanced_dedup)
672
673 LOG.info("Successfully created volume , %s", obj_vol)
674
675 return obj_vol
676
677 except Exception as e:
678 errormsg = "Create volume operation {0} failed" \
679 " with error {1}".format(vol_name, str(e))
680 LOG.error(errormsg)
681 self.module.fail_json(msg=errormsg)
682
683 def host_access_modify_required(self, host_access_list):
684 """Check if host access modification is required
685 :param host_access_list: host access dict list
686 :return: Dict with attributes to modify, or None if no
687 modification is required.
688 """
689
690 try:
691 to_modify = False
692 mapping_state = self.module.params['mapping_state']
693
694 host_id_list = []
695 hlu_list = []
696 new_list = []
697 if not host_access_list and self.new_host_list and\
698 mapping_state == 'unmapped':
699 return to_modify
700
701 elif host_access_list:
702 for host_access in host_access_list.host:
703 host_id_list.append(host_access.id)
704 host = self.get_host(host_id=host_access.id).update()
705 host_dict = host.host_luns._get_properties()
706 LOG.debug("check if hlu present : %s", host_dict)
707
708 if "hlu" in host_dict.keys():
709 hlu_list.append(host_dict['hlu'])
710
711 if mapping_state == 'mapped':
712 if (self.param_host_id not in host_id_list):
713 for item in self.new_host_list:
714 new_list.append(item.get("host_id"))
715 if not list(set(new_list) - set(host_id_list)):
716 return False
717 to_modify = True
718
719 if mapping_state == 'unmapped':
720 if self.new_host_list:
721 for item in self.new_host_list:
722 new_list.append(item.get("host_id"))
723 if list(set(new_list) - set(host_id_list)):
724 return False
725 self.overlapping_list = list(set(host_id_list) - set(new_list))
726 to_modify = True
727 LOG.debug("host_access_modify_required : %s ", str(to_modify))
728 return to_modify
729
730 except Exception as e:
731 errormsg = "Failed to compare the host_access with error {0} " \
732 "{1}".format(host_access_list, str(e))
733 LOG.error(errormsg)
734 self.module.fail_json(msg=errormsg)
735
736 def volume_modify_required(self, obj_vol, cap_unit):
737 """Check if volume modification is required
738 :param obj_vol: volume instance
739 :param cap_unit: capacity unit
740 :return: Boolean value to indicate if modification is required
741 """
742
743 try:
744 to_update = {}
745
746 new_vol_name = self.module.params['new_vol_name']
747 if new_vol_name and obj_vol.name != new_vol_name:
748 to_update.update({'name': new_vol_name})
749
750 description = self.module.params['description']
751 if description and obj_vol.description != description:
752 to_update.update({'description': description})
753
754 size = self.module.params['size']
755 if size and cap_unit:
756 size_byte = int(utils.get_size_bytes(size, cap_unit))
757 if size_byte < obj_vol.size_total:
758 self.module.fail_json(msg="Volume size can be "
759 "expanded only")
760 elif size_byte > obj_vol.size_total:
761 to_update.update({'size': size_byte})
762
763 compression = self.module.params['compression']
764 if compression is not None and \
765 compression != obj_vol.is_data_reduction_enabled:
766 to_update.update({'is_compression': compression})
767
768 advanced_dedup = self.module.params['advanced_dedup']
769 if advanced_dedup is not None and \
770 advanced_dedup != obj_vol.is_advanced_dedup_enabled:
771 to_update.update({'is_advanced_dedup_enabled': advanced_dedup})
772
773 is_thin = self.module.params['is_thin']
774 if is_thin is not None and is_thin != obj_vol.is_thin_enabled:
775 self.module.fail_json(msg="Modifying is_thin is not allowed")
776
777 sp = self.module.params['sp']
778 if sp and self.get_node_enum(sp) != obj_vol.current_node:
779 to_update.update({'sp': self.get_node_enum(sp)})
780
781 tiering_policy = self.module.params['tiering_policy']
782 if tiering_policy and self.get_tiering_policy_enum(
783 tiering_policy) != obj_vol.tiering_policy:
784 to_update.update({'tiering_policy':
785 self.get_tiering_policy_enum(
786 tiering_policy)})
787
788 # prepare io_limit_policy object
789 if self.param_io_limit_pol_id:
790 if (not obj_vol.io_limit_policy) \
791 or (self.param_io_limit_pol_id
792 != obj_vol.io_limit_policy.id):
793 to_update.update(
794 {'io_limit_policy': self.param_io_limit_pol_id})
795
796 # prepare snap_schedule object
797 if self.param_snap_schedule_name:
798 if (not obj_vol.snap_schedule) \
799 or (self.param_snap_schedule_name
800 != obj_vol.snap_schedule.name):
801 to_update.update({'snap_schedule':
802 self.param_snap_schedule_name})
803
804 # for removing existing snap_schedule
805 if self.param_snap_schedule_name == "":
806 if obj_vol.snap_schedule:
807 to_update.update({'is_snap_schedule_paused': False})
808 else:
809 LOG.warn("No snapshot schedule is associated")
810
811 LOG.debug("Volume to modify Dict : %s", to_update)
812 if len(to_update) > 0:
813 return to_update
814 else:
815 return None
816
817 except Exception as e:
818 errormsg = "Failed to determine if volume {0},requires " \
819 "modification, with error {1}".format(obj_vol.name,
820 str(e))
821 LOG.error(errormsg)
822 self.module.fail_json(msg=errormsg)
823
824 def multiple_host_map(self, host_dic_list, obj_vol):
825 """Attach multiple hosts to a volume
826 :param host_dic_list: hosts to map the volume
827 :param obj_vol: volume instance
828 :return: response from API call
829 """
830
831 try:
832 host_access = []
833 current_hosts = self.get_volume_host_access_list(obj_vol)
834 for existing_host in current_hosts:
835 host_access.append(
836 {'accessMask': eval('utils.HostLUNAccessEnum.' + existing_host['accessMask']),
837 'host':
838 {'id': existing_host['id']}, 'hlu': existing_host['hlu']})
839 for item in host_dic_list:
840 host_access.append(
841 {'accessMask': utils.HostLUNAccessEnum.PRODUCTION,
842 'host':
843 {'id': item['host_id']}, 'hlu': item['hlu']})
844 resp = obj_vol.modify(host_access=host_access)
845 return resp
846 except Exception as e:
847 errormsg = "Failed to attach hosts {0} with volume {1} with error {2} ".format(host_dic_list, obj_vol.name, str(e))
848 LOG.error(errormsg)
849 self.module.fail_json(msg=errormsg)
850
851 def multiple_detach(self, host_list_detach, obj_vol):
852 """Detach multiple hosts from a volume
853 :param host_list_detach: hosts to unmap the volume
854 :param obj_vol: volume instance
855 :return: response from API call
856 """
857
858 try:
859 host_access = []
860 for item in host_list_detach:
861 host_access.append({'accessMask': utils.HostLUNAccessEnum.PRODUCTION,
862 'host': {'id': item}})
863 resp = obj_vol.modify(host_access=host_access)
864 return resp
865 except Exception as e:
866 errormsg = "Failed to detach hosts {0} from volume {1} with error {2} ".format(host_list_detach, obj_vol.name, str(e))
867 LOG.error(errormsg)
868 self.module.fail_json(msg=errormsg)
869
870 def modify_volume(self, obj_vol, to_modify_dict):
871 """modify volume attributes
872 :param obj_vol: volume instance
873 :param to_modify_dict: dict containing attributes to be modified.
874 :return: None
875 """
876
877 try:
878
879 if 'io_limit_policy' in to_modify_dict.keys():
880 to_modify_dict['io_limit_policy'] = self.get_io_limit_policy(
881 id=to_modify_dict['io_limit_policy'])
882
883 if 'snap_schedule' in to_modify_dict.keys() and \
884 to_modify_dict['snap_schedule'] != "":
885 to_modify_dict['snap_schedule'] = \
886 {"name": to_modify_dict['snap_schedule']}
887
888 param_list = ['name', 'size', 'host_access', 'description', 'sp',
889 'io_limit_policy', 'tiering_policy',
890 'snap_schedule', 'is_snap_schedule_paused',
891 'is_compression', 'is_advanced_dedup_enabled']
892
893 for item in param_list:
894 if item not in to_modify_dict.keys():
895 to_modify_dict.update({item: None})
896
897 LOG.debug("Final update dict before modify "
898 "api call: %s", to_modify_dict)
899
900 obj_vol.modify(name=to_modify_dict['name'],
901 size=to_modify_dict['size'],
902 host_access=to_modify_dict['host_access'],
903 description=to_modify_dict['description'],
904 sp=to_modify_dict['sp'],
905 io_limit_policy=to_modify_dict['io_limit_policy'],
906 tiering_policy=to_modify_dict['tiering_policy'],
907 snap_schedule=to_modify_dict['snap_schedule'],
908 is_snap_schedule_paused=to_modify_dict['is_snap_schedule_paused'],
909 is_compression=to_modify_dict['is_compression'],
910 is_advanced_dedup_enabled=to_modify_dict['is_advanced_dedup_enabled'])
911
912 except Exception as e:
913 errormsg = "Failed to modify the volume {0} " \
914 "with error {1}".format(obj_vol.name, str(e))
915 LOG.error(errormsg)
916 self.module.fail_json(msg=errormsg)
917
918 def delete_volume(self, vol_id):
919 """Delete volume.
920 :param vol_obj: The object instance of the volume to be deleted
921 """
922
923 try:
924 obj_vol = self.get_volume(vol_id=vol_id)
925 obj_vol.delete(force_snap_delete=False)
926 return True
927
928 except Exception as e:
929 errormsg = "Delete operation of volume id:{0} " \
930 "failed with error {1}".format(id,
931 str(e))
932 LOG.error(errormsg)
933 self.module.fail_json(msg=errormsg)
934
935 def get_volume_host_access_list(self, obj_vol):
936 """
937 Get volume host access list
938 :param obj_vol: volume instance
939 :return: host list
940 """
941 host_list = []
942 if obj_vol.host_access:
943 for host_access in obj_vol.host_access:
944 host = self.get_host(host_id=host_access.host.id).update()
945 hlu = None
946 for host_lun in host.host_luns:
947 if host_lun.lun.name == obj_vol.name:
948 hlu = host_lun.hlu
949 host_list.append({'name': host_access.host.name,
950 'id': host_access.host.id,
951 'accessMask': host_access.access_mask.name,
952 'hlu': hlu})
953 return host_list
954
955 def get_volume_display_attributes(self, obj_vol):
956 """get display volume attributes
957 :param obj_vol: volume instance
958 :return: volume dict to display
959 """
960 try:
961 obj_vol = obj_vol.update()
962 volume_details = obj_vol._get_properties()
963 volume_details['size_total_with_unit'] = utils. \
964 convert_size_with_unit(int(volume_details['size_total']))
965 volume_details.update({'host_access': self.get_volume_host_access_list(obj_vol)})
966 if obj_vol.snap_schedule:
967 volume_details.update(
968 {'snap_schedule': {'name': obj_vol.snap_schedule.name,
969 'id': obj_vol.snap_schedule.id}})
970 if obj_vol.io_limit_policy:
971 volume_details.update(
972 {'io_limit_policy': {'name': obj_vol.io_limit_policy.id,
973 'id': obj_vol.io_limit_policy.id}})
974 if obj_vol.pool:
975 volume_details.update({'pool': {'name': obj_vol.pool.name,
976 'id': obj_vol.pool.id}})
977
978 return volume_details
979
980 except Exception as e:
981 errormsg = "Failed to display the volume {0} with " \
982 "error {1}".format(obj_vol.name, str(e))
983 LOG.error(errormsg)
984 self.module.fail_json(msg=errormsg)
985
986 def validate_input_string(self):
987 """ validates the input string checks if it is empty string
988
989 """
990 invalid_string = ""
991 try:
992 no_chk_list = ['snap_schedule', 'description']
993 for key in self.module.params:
994 val = self.module.params[key]
995 if key not in no_chk_list and isinstance(val, str) \
996 and val == invalid_string:
997 errmsg = 'Invalid input parameter "" for {0}'.format(
998 key)
999 self.module.fail_json(msg=errmsg)
1000
1001 except Exception as e:
1002 errormsg = "Failed to validate the module param with " \
1003 "error {0}".format(str(e))
1004 LOG.error(errormsg)
1005 self.module.fail_json(msg=errormsg)
1006
1007 def validate_host_list(self, host_list_input):
1008 """ validates the host_list_input value for None and empty
1009
1010 """
1011 try:
1012 for host_list in host_list_input:
1013 if ("host_name" in host_list.keys() and "host_id" in host_list.keys()):
1014 if host_list["host_name"] and host_list["host_id"]:
1015 errmsg = 'parameters are mutually exclusive: host_name|host_id'
1016 self.module.fail_json(msg=errmsg)
1017 is_host_details_missing = True
1018 for key, value in host_list.items():
1019 if key == "host_name" and not is_none_or_empty_string(value):
1020 is_host_details_missing = False
1021 elif key == "host_id" and not is_none_or_empty_string(value):
1022 is_host_details_missing = False
1023
1024 if is_host_details_missing:
1025 errmsg = 'Invalid input parameter for {0}'.format(key)
1026 self.module.fail_json(msg=errmsg)
1027
1028 except Exception as e:
1029 errormsg = "Failed to validate the module param with " \
1030 "error {0}".format(str(e))
1031 LOG.error(errormsg)
1032 self.module.fail_json(msg=errormsg)
1033
1034 def resolve_host_mappings(self, hosts):
1035 """ This method creates a dictionary of hosts and hlu parameter values
1036 :param hosts: host and hlu value passed from input file
1037 :return: list of host and hlu dictionary
1038 """
1039 host_list_new = []
1040
1041 if hosts:
1042 for item in hosts:
1043 host_dict = dict()
1044 host_id = None
1045 hlu = None
1046 if item['host_name']:
1047 host = self.get_host(host_name=item['host_name'])
1048 if host:
1049 host_id = host.id
1050 if item['host_id']:
1051 host_id = item['host_id']
1052 if item['hlu']:
1053 hlu = item['hlu']
1054 host_dict['host_id'] = host_id
1055 host_dict['hlu'] = hlu
1056 host_list_new.append(host_dict)
1057 return host_list_new
1058
1059 def perform_module_operation(self):
1060 """
1061 Perform different actions on volume module based on parameters
1062 passed in the playbook
1063 """
1064 self.new_host_list = []
1065 self.overlapping_list = []
1066 vol_name = self.module.params['vol_name']
1067 vol_id = self.module.params['vol_id']
1068 pool_name = self.module.params['pool_name']
1069 pool_id = self.module.params['pool_id']
1070 size = self.module.params['size']
1071 cap_unit = self.module.params['cap_unit']
1072 snap_schedule = self.module.params['snap_schedule']
1073 io_limit_policy = self.module.params['io_limit_policy']
1074 host_name = self.module.params['host_name']
1075 host_id = self.module.params['host_id']
1076 hlu = self.module.params['hlu']
1077 mapping_state = self.module.params['mapping_state']
1078 new_vol_name = self.module.params['new_vol_name']
1079 state = self.module.params['state']
1080 hosts = self.module.params['hosts']
1081
1082 # result is a dictionary to contain end state and volume details
1083 changed = False
1084 result = dict(
1085 changed=False,
1086 volume_details={}
1087 )
1088
1089 to_modify_dict = None
1090 volume_details = None
1091 to_modify_host = False
1092
1093 self.validate_input_string()
1094
1095 if hosts:
1096 self.validate_host_list(hosts)
1097
1098 if size is not None and size == 0:
1099 self.module.fail_json(msg="Size can not be 0 (Zero)")
1100
1101 if size and not cap_unit:
1102 cap_unit = 'GB'
1103
1104 if (cap_unit is not None) and not size:
1105 self.module.fail_json(msg="cap_unit can be specified along "
1106 "with size")
1107
1108 if hlu and (not host_name and not host_id and not hosts):
1109 self.module.fail_json(msg="hlu can be specified with "
1110 "host_id or host_name")
1111 if mapping_state and (not host_name and not host_id and not hosts):
1112 self.module.fail_json(msg="mapping_state can be specified"
1113 " with host_id or host_name or hosts")
1114
1115 obj_vol = self.get_volume(vol_id=vol_id, vol_name=vol_name)
1116
1117 if host_name or host_id:
1118 if not mapping_state:
1119 errmsg = "'mapping_state' is required along with " \
1120 "'host_name' or 'host_id' or 'hosts'"
1121 self.module.fail_json(msg=errmsg)
1122 host = [{'host_name': host_name, 'host_id': host_id, 'hlu': hlu}]
1123 self.new_host_list = self.resolve_host_mappings(host)
1124
1125 if hosts:
1126 if not mapping_state:
1127 errmsg = "'mapping_state' is required along with " \
1128 "'host_name' or 'host_id' or 'hosts'"
1129 self.module.fail_json(msg=errmsg)
1130 self.new_host_list += self.resolve_host_mappings(hosts)
1131
1132 if io_limit_policy:
1133 io_limit_policy = self.get_io_limit_policy(name=io_limit_policy)
1134 self.param_io_limit_pol_id = io_limit_policy.id
1135
1136 if snap_schedule:
1137 snap_schedule = self.get_snap_schedule(name=snap_schedule)
1138 self.param_snap_schedule_name = snap_schedule.name[0]
1139
1140 # this is for removing existing snap_schedule
1141 if snap_schedule == "":
1142 self.param_snap_schedule_name = snap_schedule
1143
1144 if obj_vol:
1145 volume_details = obj_vol._get_properties()
1146 vol_id = obj_vol.get_id()
1147 to_modify_dict = self.volume_modify_required(obj_vol, cap_unit)
1148 LOG.debug("Volume Modify Required: %s", to_modify_dict)
1149 if obj_vol.host_access:
1150 to_modify_host = self.host_access_modify_required(
1151 host_access_list=obj_vol.host_access)
1152 LOG.debug("Host Modify Required in access: %s", to_modify_host)
1153 elif self.new_host_list:
1154 to_modify_host = self.host_access_modify_required(
1155 host_access_list=obj_vol.host_access)
1156 LOG.debug("Host Modify Required: %s", to_modify_host)
1157
1158 if state == 'present' and not volume_details:
1159 if not vol_name:
1160 msg_noname = "volume with id {0} is not found, unable to " \
1161 "create a volume without a valid " \
1162 "vol_name".format(vol_id)
1163 self.module.fail_json(msg=msg_noname)
1164
1165 if snap_schedule == "":
1166 self.module.fail_json(msg="Invalid snap_schedule")
1167
1168 if new_vol_name:
1169 self.module.fail_json(msg="new_vol_name is not required "
1170 "to create a new volume")
1171 if not pool_name and not pool_id:
1172 self.module.fail_json(msg="pool_id or pool_name is required "
1173 "to create new volume")
1174 if not size:
1175 self.module.fail_json(msg="Size is required to create"
1176 " a volume")
1177 host_access = None
1178 if self.new_host_list:
1179 host_access = []
1180 for item in self.new_host_list:
1181 if item['hlu']:
1182 host_access.append(
1183 {'accessMask': utils.HostLUNAccessEnum.PRODUCTION, 'host': {'id': item['host_id']},
1184 'hlu': item['hlu']})
1185 else:
1186 host_access.append(
1187 {'accessMask': utils.HostLUNAccessEnum.PRODUCTION, 'host': {'id': item['host_id']}})
1188
1189 size = utils.get_size_in_gb(size, cap_unit)
1190
1191 obj_pool = self.get_pool(pool_name=pool_name, pool_id=pool_id)
1192
1193 obj_vol = self.create_volume(obj_pool=obj_pool, size=size,
1194 host_access=host_access)
1195 if obj_vol:
1196 LOG.debug("Successfully created volume , %s", obj_vol)
1197 vol_id = obj_vol.id
1198 volume_details = obj_vol._get_properties()
1199 LOG.debug("Got volume id , %s", vol_id)
1200 changed = True
1201
1202 if state == 'present' and volume_details and to_modify_dict:
1203 self.modify_volume(obj_vol=obj_vol, to_modify_dict=to_modify_dict)
1204 changed = True
1205
1206 if (state == 'present' and volume_details
1207 and mapping_state == 'mapped' and to_modify_host):
1208 if self.new_host_list:
1209 resp = self.multiple_host_map(host_dic_list=self.new_host_list, obj_vol=obj_vol)
1210 changed = True if resp else False
1211
1212 if (state == 'present' and volume_details
1213 and mapping_state == 'unmapped' and to_modify_host):
1214 if self.new_host_list:
1215 resp = self.multiple_detach(host_list_detach=self.overlapping_list, obj_vol=obj_vol)
1216 LOG.info(resp)
1217 changed = True if resp else False
1218
1219 if state == 'absent' and volume_details:
1220 changed = self.delete_volume(vol_id)
1221 volume_details = None
1222
1223 if state == 'present' and volume_details:
1224 volume_details = self.get_volume_display_attributes(
1225 obj_vol=obj_vol)
1226
1227 result['changed'] = changed
1228 result['volume_details'] = volume_details
1229 self.module.exit_json(**result)
1230
1231
1232 def get_volume_parameters():
1233 """This method provide parameters required for the ansible volume
1234 module on Unity"""
1235 return dict(
1236 vol_name=dict(required=False, type='str'),
1237 vol_id=dict(required=False, type='str'),
1238 description=dict(required=False, type='str'),
1239 pool_name=dict(required=False, type='str'),
1240 pool_id=dict(required=False, type='str'),
1241 size=dict(required=False, type='int'),
1242 cap_unit=dict(required=False, type='str', choices=['GB', 'TB']),
1243 is_thin=dict(required=False, type='bool'),
1244 compression=dict(required=False, type='bool'),
1245 advanced_dedup=dict(required=False, type='bool'),
1246 sp=dict(required=False, type='str', choices=['SPA', 'SPB']),
1247 io_limit_policy=dict(required=False, type='str'),
1248 snap_schedule=dict(required=False, type='str'),
1249 host_name=dict(required=False, type='str'),
1250 host_id=dict(required=False, type='str'),
1251 hosts=dict(required=False, type='list', elements='dict',
1252 options=dict(
1253 host_id=dict(required=False, type='str'),
1254 host_name=dict(required=False, type='str'),
1255 hlu=dict(required=False, type='str')
1256 )),
1257 hlu=dict(required=False, type='int'),
1258 mapping_state=dict(required=False, type='str',
1259 choices=['mapped', 'unmapped']),
1260 new_vol_name=dict(required=False, type='str'),
1261 tiering_policy=dict(required=False, type='str', choices=[
1262 'AUTOTIER_HIGH', 'AUTOTIER', 'HIGHEST', 'LOWEST']),
1263 state=dict(required=True, type='str', choices=['present', 'absent'])
1264 )
1265
1266
1267 def main():
1268 """ Create Unity volume object and perform action on it
1269 based on user input from playbook"""
1270 obj = Volume()
1271 obj.perform_module_operation()
1272
1273
1274 if __name__ == '__main__':
1275 main()