Debian Codegraph @

ansible_collections/dellemc/unity/plugins/modules/consistencygroup.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 consistency group on Unity"""
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 DOCUMENTATION = r"""
12 module: consistencygroup
13 version_added: '1.1.0'
14 short_description: Manage consistency groups on Unity storage system
15 description:
16 - Managing the consistency group on the Unity storage system includes
17 creating new consistency group, adding volumes to consistency
18 group, removing volumes from consistency group, mapping hosts to
19 consistency group, unmapping hosts from consistency group,
20 renaming consistency group, modifying attributes of consistency group,
21 enabling replication in consistency group, disabling replication in
22 consistency group and deleting consistency group.
23
24 extends_documentation_fragment:
25 - dellemc.unity.unity
26
27 author:
28 - Akash Shendge (@shenda1) <[email protected]>
29
30 options:
31 cg_name:
32 description:
33 - The name of the consistency group.
34 - It is mandatory for the create operation.
35 - Specify either I(cg_name) or I(cg_id) (but not both) for any operation.
36 type: str
37 cg_id:
38 description:
39 - The ID of the consistency group.
40 - It can be used only for get, modify, add/remove volumes, or delete
41 operations.
42 type: str
43 volumes:
44 description:
45 - This is a list of volumes.
46 - Either the volume ID or name must be provided for adding/removing
47 existing volumes from consistency group.
48 - If I(volumes) are given, then I(vol_state) should also be specified.
49 - Volumes cannot be added/removed from consistency group, if the
50 consistency group or the volume has snapshots.
51 type: list
52 elements: dict
53 suboptions:
54 vol_id:
55 description:
56 - The ID of the volume.
57 type: str
58 vol_name:
59 description:
60 - The name of the volume.
61 type: str
62 vol_state:
63 description:
64 - String variable, describes the state of volumes inside consistency
65 group.
66 - If I(volumes) are given, then I(vol_state) should also be specified.
67 choices: [present-in-group , absent-in-group]
68 type: str
69 new_cg_name:
70 description:
71 - The new name of the consistency group, used in rename operation.
72 type: str
73 description:
74 description:
75 - Description of the consistency group.
76 type: str
77 snap_schedule:
78 description:
79 - Snapshot schedule assigned to the consistency group.
80 - Specifying an empty string "" removes the existing snapshot schedule
81 from consistency group.
82 type: str
83 tiering_policy:
84 description:
85 - Tiering policy choices for how the storage resource data will be
86 distributed among the tiers available in the pool.
87 choices: ['AUTOTIER_HIGH', 'AUTOTIER', 'HIGHEST', 'LOWEST']
88 type: str
89 hosts:
90 description:
91 - This is a list of hosts.
92 - Either the host ID or name must be provided for mapping/unmapping
93 hosts for a consistency group.
94 - If I(hosts) are given, then I(mapping_state) should also be specified.
95 - Hosts cannot be mapped to a consistency group, if the
96 consistency group has no volumes.
97 - When a consistency group is being mapped to the host,
98 users should not use the volume module to map the volumes
99 in the consistency group to hosts.
100 type: list
101 elements: dict
102 suboptions:
103 host_id:
104 description:
105 - The ID of the host.
106 type: str
107 host_name:
108 description:
109 - The name of the host.
110 type: str
111 mapping_state:
112 description:
113 - String variable, describes the state of hosts inside the consistency
114 group.
115 - If I(hosts) are given, then I(mapping_state) should also be specified.
116 choices: [mapped , unmapped]
117 type: str
118 replication_params:
119 description:
120 - Settings required for enabling replication.
121 type: dict
122 suboptions:
123 destination_cg_name:
124 description:
125 - Name of the destination consistency group.
126 - Default value will be source consistency group name prefixed by 'DR_'.
127 type: str
128 replication_mode:
129 description:
130 - The replication mode.
131 type: str
132 required: true
133 choices: ['asynchronous', 'manual']
134 rpo:
135 description:
136 - Maximum time to wait before the system syncs the source and destination LUNs.
137 - Option I(rpo) should be specified if the I(replication_mode) is C(asynchronous).
138 - The value should be in range of C(5) to C(1440).
139 type: int
140 replication_type:
141 description:
142 - Type of replication.
143 choices: ['local', 'remote']
144 default: local
145 type: str
146 remote_system:
147 description:
148 - Details of remote system to which the replication is being configured.
149 - The I(remote_system) option should be specified if the I(replication_type) is C(remote).
150 type: dict
151 suboptions:
152 remote_system_host:
153 required: true
154 description:
155 - IP or FQDN for remote Unity unisphere Host.
156 type: str
157 remote_system_username:
158 type: str
159 required: true
160 description:
161 - User name of remote Unity unisphere Host.
162 remote_system_password:
163 type: str
164 required: true
165 description:
166 - Password of remote Unity unisphere Host.
167 remote_system_verifycert:
168 type: bool
169 default: true
170 description:
171 - Boolean variable to specify whether or not to validate SSL
172 certificate of remote Unity unisphere Host.
173 - C(true) - Indicates that the SSL certificate should be verified.
174 - C(false) - Indicates that the SSL certificate should not be
175 verified.
176 remote_system_port:
177 description:
178 - Port at which remote Unity unisphere is hosted.
179 type: int
180 default: 443
181 destination_pool_name:
182 description:
183 - Name of pool to allocate destination Luns.
184 - Mutually exclusive with I(destination_pool_id).
185 type: str
186 destination_pool_id:
187 description:
188 - Id of pool to allocate destination Luns.
189 - Mutually exclusive with I(destination_pool_name).
190 type: str
191 replication_state:
192 description:
193 - State of the replication.
194 choices: ['enable', 'disable']
195 type: str
196 state:
197 description:
198 - Define whether the consistency group should exist or not.
199 choices: [absent, present]
200 required: true
201 type: str
202 notes:
203 - The I(check_mode) is not supported.
204 """
205
206 EXAMPLES = r"""
207 - name: Create consistency group
208 consistencygroup:
209 unispherehost: "{{unispherehost}}"
210 validate_certs: "{{validate_certs}}"
211 username: "{{username}}"
212 password: "{{password}}"
213 cg_name: "{{cg_name}}"
214 description: "{{description}}"
215 snap_schedule: "{{snap_schedule1}}"
216 state: "present"
217
218 - name: Get details of consistency group using id
219 consistencygroup:
220 unispherehost: "{{unispherehost}}"
221 username: "{{username}}"
222 password: "{{password}}"
223 validate_certs: "{{validate_certs}}"
224 cg_id: "{{cg_id}}"
225 state: "present"
226
227 - name: Add volumes to consistency group
228 consistencygroup:
229 unispherehost: "{{unispherehost}}"
230 username: "{{username}}"
231 password: "{{password}}"
232 validate_certs: "{{validate_certs}}"
233 cg_id: "{{cg_id}}"
234 volumes:
235 - vol_name: "Ansible_Test-3"
236 - vol_id: "sv_1744"
237 vol_state: "{{vol_state_present}}"
238 state: "present"
239
240 - name: Rename consistency group
241 consistencygroup:
242 unispherehost: "{{unispherehost}}"
243 username: "{{username}}"
244 password: "{{password}}"
245 validate_certs: "{{validate_certs}}"
246 cg_name: "{{cg_name}}"
247 new_cg_name: "{{new_cg_name}}"
248 state: "present"
249
250 - name: Modify consistency group details
251 consistencygroup:
252 unispherehost: "{{unispherehost}}"
253 username: "{{username}}"
254 password: "{{password}}"
255 validate_certs: "{{validate_certs}}"
256 cg_name: "{{new_cg_name}}"
257 snap_schedule: "{{snap_schedule2}}"
258 tiering_policy: "{{tiering_policy1}}"
259 state: "present"
260
261 - name: Map hosts to a consistency group
262 consistencygroup:
263 unispherehost: "{{unispherehost}}"
264 username: "{{username}}"
265 password: "{{password}}"
266 validate_certs: "{{validate_certs}}"
267 cg_id: "{{cg_id}}"
268 hosts:
269 - host_name: "10.226.198.248"
270 - host_id: "Host_511"
271 mapping_state: "mapped"
272 state: "present"
273
274 - name: Unmap hosts from a consistency group
275 consistencygroup:
276 unispherehost: "{{unispherehost}}"
277 username: "{{username}}"
278 password: "{{password}}"
279 validate_certs: "{{validate_certs}}"
280 cg_id: "{{cg_id}}"
281 hosts:
282 - host_id: "Host_511"
283 - host_name: "10.226.198.248"
284 mapping_state: "unmapped"
285 state: "present"
286
287 - name: Remove volumes from consistency group
288 consistencygroup:
289 unispherehost: "{{unispherehost}}"
290 username: "{{username}}"
291 password: "{{password}}"
292 validate_certs: "{{validate_certs}}"
293 cg_name: "{{new_cg_name}}"
294 volumes:
295 - vol_name: "Ansible_Test-3"
296 - vol_id: "sv_1744"
297 vol_state: "{{vol_state_absent}}"
298 state: "present"
299
300 - name: Delete consistency group
301 consistencygroup:
302 unispherehost: "{{unispherehost}}"
303 username: "{{username}}"
304 password: "{{password}}"
305 validate_certs: "{{validate_certs}}"
306 cg_name: "{{new_cg_name}}"
307 state: "absent"
308
309 - name: Enable replication for consistency group
310 consistencygroup:
311 unispherehost: "{{unispherehost}}"
312 username: "{{username}}"
313 password: "{{password}}"
314 validate_certs: "{{validate_certs}}"
315 cg_id: "cg_id_1"
316 replication_params:
317 destination_cg_name: "destination_cg_1"
318 replication_mode: "asynchronous"
319 rpo: 60
320 replication_type: "remote"
321 remote_system:
322 remote_system_host: '10.1.2.3'
323 remote_system_verifycert: false
324 remote_system_username: 'username'
325 remote_system_password: 'password'
326 destination_pool_name: "pool_test_1"
327 replication_state: "enable"
328 state: "present"
329
330 - name: Disable replication for consistency group
331 consistencygroup:
332 unispherehost: "{{unispherehost}}"
333 username: "{{username}}"
334 password: "{{password}}"
335 validate_certs: "{{validate_certs}}"
336 cg_name: "dis_repl_ans_source"
337 replication_state: "disable"
338 state: "present"
339 """
340
341 RETURN = r'''
342 changed:
343 description: Whether or not the resource has changed.
344 returned: always
345 type: bool
346 sample: true
347
348 consistency_group_details:
349 description: Details of the consistency group.
350 returned: When consistency group exists
351 type: dict
352 contains:
353 id:
354 description: The system ID given to the consistency group.
355 type: str
356 relocation_policy:
357 description: FAST VP tiering policy for the consistency group.
358 type: str
359 cg_replication_enabled:
360 description: Whether or not the replication is enabled..
361 type: bool
362 snap_schedule:
363 description: Snapshot schedule applied to consistency group.
364 type: dict
365 contains:
366 UnitySnapSchedule:
367 description: Snapshot schedule applied to consistency
368 group.
369 type: dict
370 contains:
371 id:
372 description: The system ID given to the
373 snapshot schedule.
374 type: str
375 name:
376 description: The name of the snapshot schedule.
377 type: str
378 luns:
379 description: Details of volumes part of consistency group.
380 type: dict
381 contains:
382 UnityLunList:
383 description: List of volumes part of consistency group.
384 type: list
385 contains:
386 UnityLun:
387 description: Detail of volume.
388 type: dict
389 contains:
390 id:
391 description: The system ID given to volume.
392 type: str
393 name:
394 description: The name of the volume.
395 type: str
396 snapshots:
397 description: List of snapshots of consistency group.
398 type: list
399 contains:
400 name:
401 description: Name of the snapshot.
402 type: str
403 creation_time:
404 description: Date and time on which the snapshot was taken.
405 type: str
406 expirationTime:
407 description: Date and time after which the snapshot will expire.
408 type: str
409 storageResource:
410 description: Storage resource for which the snapshot was
411 taken.
412 type: dict
413 contains:
414 UnityStorageResource:
415 description: Details of the storage resource.
416 type: dict
417 contains:
418 id:
419 description: The id of the storage
420 resource.
421 type: str
422 block_host_access:
423 description: Details of hosts mapped to the consistency group.
424 type: dict
425 contains:
426 UnityBlockHostAccessList:
427 description: List of hosts mapped to consistency group.
428 type: list
429 contains:
430 UnityBlockHostAccess:
431 description: Details of host.
432 type: dict
433 contains:
434 id:
435 description: The ID of the host.
436 type: str
437 name:
438 description: The name of the host.
439 type: str
440 sample: {
441 "advanced_dedup_status": "DedupStatusEnum.DISABLED",
442 "block_host_access": null,
443 "cg_replication_enabled": false,
444 "data_reduction_percent": 0,
445 "data_reduction_ratio": 1.0,
446 "data_reduction_size_saved": 0,
447 "data_reduction_status": "DataReductionStatusEnum.DISABLED",
448 "datastores": null,
449 "dedup_status": null,
450 "description": "Ansible testing",
451 "esx_filesystem_block_size": null,
452 "esx_filesystem_major_version": null,
453 "existed": true,
454 "filesystem": null,
455 "hash": 8776023812033,
456 "health": {
457 "UnityHealth": {
458 "hash": 8776023811889
459 }
460 },
461 "host_v_vol_datastore": null,
462 "id": "res_7477",
463 "is_replication_destination": false,
464 "is_snap_schedule_paused": null,
465 "luns": null,
466 "metadata_size": 0,
467 "metadata_size_allocated": 0,
468 "name": "Ansible_CG_Testing",
469 "per_tier_size_used": null,
470 "pools": null,
471 "relocation_policy": "TieringPolicyEnum.MIXED",
472 "replication_type": "ReplicationTypeEnum.NONE",
473 "size_allocated": 0,
474 "size_total": 0,
475 "size_used": null,
476 "snap_count": 0,
477 "snap_schedule": null,
478 "snaps_size_allocated": 0,
479 "snaps_size_total": 0,
480 "snapshots": [],
481 "thin_status": "ThinStatusEnum.FALSE",
482 "type": "StorageResourceTypeEnum.CONSISTENCY_GROUP",
483 "virtual_volumes": null,
484 "vmware_uuid": null
485 }
486 '''
487
488 import logging
489 from ansible.module_utils.basic import AnsibleModule
490 from ansible_collections.dellemc.unity.plugins.module_utils.storage.dell \
491 import utils
492
493 LOG = utils.get_logger('consistencygroup',
494 log_devel=logging.INFO)
495
496 application_type = "Ansible/1.7.1"
497
498
499 class ConsistencyGroup(object):
500 """Class with consistency group operations"""
501
502 def __init__(self):
503 """Define all parameters required by this module"""
504 self.module_params = utils.get_unity_management_host_parameters()
505 self.module_params.update(get_consistencygroup_parameters())
506
507 mutually_exclusive = [['cg_name', 'cg_id']]
508 required_one_of = [['cg_name', 'cg_id']]
509 required_together = [['volumes', 'vol_state'], ['hosts', 'mapping_state']]
510
511 # initialize the Ansible module
512 self.module = AnsibleModule(
513 argument_spec=self.module_params,
514 supports_check_mode=False,
515 mutually_exclusive=mutually_exclusive,
516 required_one_of=required_one_of,
517 required_together=required_together
518 )
519 utils.ensure_required_libs(self.module)
520
521 self.unity_conn = utils.get_unity_unisphere_connection(
522 self.module.params, application_type)
523
524 def return_cg_instance(self, cg_name):
525 """Return the consistency group instance.
526 :param cg_name: The name of the consistency group
527 :return: Instance of the consistency group
528 """
529
530 try:
531 cg_details = self.unity_conn.get_cg(name=cg_name)
532 cg_id = cg_details.get_id()
533 cg_obj = utils.cg.UnityConsistencyGroup.get(self.unity_conn._cli,
534 cg_id)
535 return cg_obj
536
537 except Exception as e:
538 msg = "Failed to get the consistency group {0} instance with " \
539 "error {1}".format(cg_name, str(e))
540 LOG.error(msg)
541 self.module.fail_json(msg=msg)
542
543 def get_details(self, cg_id=None, cg_name=None):
544 """Get consistency group details.
545 :param cg_id: The id of the consistency group
546 :param cg_name: The name of the consistency group
547 :return: Dict containing consistency group details if exists
548 """
549
550 id_or_name = cg_id if cg_id else cg_name
551 errormsg = "Failed to get details of consistency group {0} with" \
552 " error {1}"
553
554 try:
555 cg_details = self.unity_conn.get_cg(_id=cg_id, name=cg_name)
556 if cg_name is None:
557 cg_name = cg_details.name
558
559 if cg_details.existed:
560 cg_obj = self.return_cg_instance(cg_name)
561 snapshots = cg_obj.snapshots
562
563 snapshot_list = [snap._get_properties() for snap in snapshots]
564
565 cg_ret_details = cg_details._get_properties()
566
567 # Append details of host mapped to the consistency group
568 # in return response
569 if cg_ret_details['block_host_access']:
570 for i in range(len(cg_details.block_host_access)):
571 cg_ret_details['block_host_access']['UnityBlockHostAccessList'][i]['UnityBlockHostAccess'][
572 'id'] = cg_details.block_host_access[i].host.id
573 cg_ret_details['block_host_access']['UnityBlockHostAccessList'][i]['UnityBlockHostAccess'][
574 'name'] = cg_details.block_host_access[i].host.name
575 cg_ret_details['snapshots'] = snapshot_list
576
577 # Add volume name to the dict
578 if cg_ret_details['luns'] is not None:
579 for i in range(len(cg_details.luns)):
580 cg_ret_details['luns']['UnityLunList'][i]['UnityLun'][
581 'name'] = cg_details.luns[i].name
582
583 # Add snapshot schedule name to the dict
584 if cg_ret_details['snap_schedule'] is not None:
585 cg_ret_details['snap_schedule']['UnitySnapSchedule'][
586 'name'] = cg_details.snap_schedule.name
587
588 # Status of cg replication
589 cg_ret_details['cg_replication_enabled'] = True if cg_details.check_cg_is_replicated() else False
590
591 return cg_ret_details
592 else:
593 LOG.info("Failed to get details of consistency group %s",
594 id_or_name)
595 return None
596
597 except utils.HttpError as e:
598 if e.http_status == 401:
599 auth_err = "Incorrect username or password, {0}".format(
600 e.message)
601 msg = errormsg.format(id_or_name, auth_err)
602 LOG.error(msg)
603 self.module.fail_json(msg=msg)
604 else:
605 msg = errormsg.format(id_or_name, str(e))
606 LOG.error(msg)
607 self.module.fail_json(msg=msg)
608
609 except utils.UnityResourceNotFoundError as e:
610 msg = errormsg.format(id_or_name, str(e))
611 LOG.error(msg)
612 return None
613
614 except Exception as e:
615 msg = errormsg.format(id_or_name, str(e))
616 LOG.error(msg)
617 self.module.fail_json(msg=msg)
618
619 def get_host_id_by_name(self, host_name):
620 """ Get host ID by host name
621 :param host_name: str
622 :return: unity host ID
623 :rtype: str
624 """
625 try:
626 host_obj = self.unity_conn.get_host(name=host_name)
627 if host_obj and host_obj.existed:
628 return host_obj.id
629 else:
630 msg = "Host name: %s does not exists" % host_name
631 LOG.error(msg)
632 self.module.fail_json(msg=msg)
633 except Exception as e:
634 msg = "Failed to get host ID by name: %s error: %s" % (
635 host_name, str(e))
636 LOG.error(msg)
637 self.module.fail_json(msg=msg)
638
639 def get_volume_details(self, vol_name=None, vol_id=None):
640 """Get the details of a volume.
641 :param vol_name: The name of the volume
642 :param vol_id: The id of the volume
643 :return: Dict containing volume details if exists
644 """
645
646 id_or_name = vol_id if vol_id else vol_name
647
648 try:
649 lun = self.unity_conn.get_lun(name=vol_name, _id=vol_id)
650
651 cg = None
652 if lun.existed:
653 lunid = lun.get_id()
654 unitylun = utils.UnityLun.get(self.unity_conn._cli, lunid)
655 if unitylun.cg is not None:
656 cg = unitylun.cg
657 else:
658 errormsg = "The volume {0} not found.".format(id_or_name)
659 LOG.error(errormsg)
660 self.module.fail_json(msg=errormsg)
661
662 cg_details = self.get_details(
663 cg_id=self.module.params['cg_id'],
664 cg_name=self.module.params['cg_name'])
665
666 # Check if volume is already part of another consistency group
667 if cg is None:
668 return lun._get_properties()['id']
669
670 errormsg = "The volume {0} is already part of consistency group" \
671 " {1}".format(id_or_name, cg.name)
672
673 if cg_details is None:
674 LOG.error(errormsg)
675 self.module.fail_json(msg=errormsg)
676
677 if cg.id != cg_details['id']:
678 LOG.error(errormsg)
679 self.module.fail_json(msg=errormsg)
680
681 return lun._get_properties()['id']
682
683 except Exception as e:
684 msg = "Failed to get the volume {0} with error {1}".format(
685 id_or_name, str(e))
686 LOG.error(msg)
687 self.module.fail_json(msg=msg)
688
689 def remove_volumes_from_cg(self, cg_name, volumes):
690 """Remove volumes from consistency group.
691 :param cg_name: The name of the consistency group
692 :param volumes: The list of volumes to be removed
693 :return: Boolean value to indicate if volumes are removed from
694 consistency group
695 """
696
697 cg_details = self.unity_conn.get_cg(name=cg_name)._get_properties()
698 existing_volumes_in_cg = cg_details['luns']
699 existing_vol_ids = []
700
701 if existing_volumes_in_cg:
702 existing_vol_ids = [vol['UnityLun']['id'] for vol in
703 existing_volumes_in_cg['UnityLunList']]
704
705 ids_to_remove = []
706 vol_name_list = []
707 vol_id_list = []
708
709 for vol in volumes:
710 if 'vol_id' in vol and not (vol['vol_id'] in vol_id_list):
711 vol_id_list.append(vol['vol_id'])
712 elif 'vol_name' in vol and not (vol['vol_name'] in vol_name_list):
713 vol_name_list.append(vol['vol_name'])
714
715 """remove volume by name"""
716 for vol in vol_name_list:
717 ids_to_remove.append(self.get_volume_details(vol_name=vol))
718
719 vol_id_list = list(set(vol_id_list + ids_to_remove))
720 ids_to_remove = list(set(existing_vol_ids).intersection(set(vol_id_list)))
721
722 LOG.info("Volume IDs to remove %s", ids_to_remove)
723
724 if len(ids_to_remove) == 0:
725 return False
726
727 vol_remove_list = []
728 for vol in ids_to_remove:
729 vol_dict = {"id": vol}
730 vol_remove_list.append(vol_dict)
731
732 cg_obj = self.return_cg_instance(cg_name)
733
734 try:
735 cg_obj.modify(lun_remove=vol_remove_list)
736 return True
737 except Exception as e:
738 errormsg = "Remove existing volumes from consistency group {0} " \
739 "failed with error {1}".format(cg_name, str(e))
740 LOG.error(errormsg)
741 self.module.fail_json(msg=errormsg)
742
743 def add_volumes_to_cg(self, cg_name, volumes, tiering_policy):
744 """Add volumes to consistency group.
745 :param cg_name: The name of the consistency group
746 :param volumes: The list of volumes to be added to consistency
747 group
748 :param tiering_policy: The tiering policy that is to be applied to
749 consistency group
750 :return: The boolean value to indicate if volumes are added to
751 consistency group
752 """
753
754 cg_details = self.unity_conn.get_cg(name=cg_name)._get_properties()
755 existing_volumes_in_cg = cg_details['luns']
756 existing_vol_ids = []
757
758 if existing_volumes_in_cg:
759 existing_vol_ids = [vol['UnityLun']['id'] for vol in
760 existing_volumes_in_cg['UnityLunList']]
761
762 ids_to_add = []
763 vol_name_list = []
764 vol_id_list = []
765 all_vol_ids = []
766
767 for vol in volumes:
768 if 'vol_id' in vol and not (vol['vol_id'] in vol_id_list):
769 vol_id_list.append(vol['vol_id'])
770 elif 'vol_name' in vol and not (vol['vol_name'] in vol_name_list):
771 vol_name_list.append(vol['vol_name'])
772
773 """add volume by name"""
774 for vol in vol_name_list:
775 ids_to_add.append(self.get_volume_details(vol_name=vol))
776
777 """add volume by id"""
778 for vol in vol_id_list:
779 """verifying if volume id exists in array"""
780 ids_to_add.append(self.get_volume_details(vol_id=vol))
781
782 all_vol_ids = ids_to_add + existing_vol_ids
783 ids_to_add = list(set(all_vol_ids) - set(existing_vol_ids))
784
785 LOG.info("Volume IDs to add %s", ids_to_add)
786
787 if len(ids_to_add) == 0:
788 return False
789
790 vol_add_list = []
791 for vol in ids_to_add:
792 vol_dict = {"id": vol}
793 vol_add_list.append(vol_dict)
794
795 cg_obj = self.return_cg_instance(cg_name)
796
797 policy_enum = None
798 if tiering_policy:
799 if utils.TieringPolicyEnum[tiering_policy]:
800 policy_enum = utils.TieringPolicyEnum[tiering_policy]
801 else:
802 errormsg = "Invalid choice {0} for tiering policy".format(
803 tiering_policy)
804 LOG.error(errormsg)
805 self.module.fail_json(msg=errormsg)
806
807 try:
808 cg_obj.modify(lun_add=vol_add_list, tiering_policy=policy_enum)
809 return True
810 except Exception as e:
811 errormsg = "Add existing volumes to consistency group {0} " \
812 "failed with error {1}".format(cg_name, str(e))
813 LOG.error(errormsg)
814 self.module.fail_json(msg=errormsg)
815
816 def map_hosts_to_cg(self, cg_name, add_hosts):
817 """Map hosts to consistency group.
818 :param cg_name: The name of the consistency group
819 :param add_hosts: List of hosts that are to be mapped to cg
820 :return: Boolean value to indicate if hosts were mapped to cg
821 """
822 cg_details = self.unity_conn.get_cg(name=cg_name)
823 existing_volumes_in_cg = cg_details.luns
824
825 existing_hosts_in_cg = cg_details.block_host_access
826 existing_host_ids = []
827
828 """Get list of existing hosts in consistency group"""
829 if existing_hosts_in_cg:
830 for i in range(len(existing_hosts_in_cg)):
831 existing_host_ids.append(existing_hosts_in_cg[i].host.id)
832
833 host_id_list = []
834 host_name_list = []
835 add_hosts_id = []
836 host_add_list = []
837 all_hosts = []
838
839 for host in add_hosts:
840 if 'host_id' in host and not (host['host_id'] in host_id_list):
841 host_id_list.append(host['host_id'])
842 elif 'host_name' in host and not (host['host_name'] in host_name_list):
843 host_name_list.append(host['host_name'])
844
845 """add hosts by name"""
846 for host_name in host_name_list:
847 add_hosts_id.append(self.get_host_id_by_name(host_name))
848
849 all_hosts = host_id_list + existing_host_ids + add_hosts_id
850 add_hosts_id = list(set(all_hosts) - set(existing_host_ids))
851
852 if len(add_hosts_id) == 0:
853 return False
854
855 if existing_volumes_in_cg:
856
857 for host_id in add_hosts_id:
858 host_dict = {"id": host_id}
859 host_add_list.append(host_dict)
860
861 LOG.info("List of hosts to be added to consistency group "
862 "%s ", host_add_list)
863 cg_obj = self.return_cg_instance(cg_name)
864 try:
865 cg_obj.modify(name=cg_name, host_add=host_add_list)
866 return True
867 except Exception as e:
868 errormsg = "Adding host to consistency group {0} " \
869 "failed with error {1}".format(cg_name, str(e))
870 LOG.error(errormsg)
871 self.module.fail_json(msg=errormsg)
872
873 def unmap_hosts_to_cg(self, cg_name, remove_hosts):
874 """Unmap hosts to consistency group.
875 :param cg_name: The name of the consistency group
876 :param remove_hosts: List of hosts that are to be unmapped from cg
877 :return: Boolean value to indicate if hosts were mapped to cg
878 """
879 cg_details = self.unity_conn.get_cg(name=cg_name)
880 existing_hosts_in_cg = cg_details.block_host_access
881 existing_host_ids = []
882
883 """Get host ids existing in consistency group"""
884 if existing_hosts_in_cg:
885 for i in range(len(existing_hosts_in_cg)):
886 existing_host_ids.append(existing_hosts_in_cg[i].host.id)
887
888 host_remove_list = []
889 host_id_list = []
890 host_name_list = []
891 remove_hosts_id = []
892
893 for host in remove_hosts:
894 if 'host_id' in host and not (host['host_id'] in host_id_list):
895 host_id_list.append(host['host_id'])
896 elif 'host_name' in host and not (host['host_name'] in host_name_list):
897 host_name_list.append(host['host_name'])
898
899 """remove hosts by name"""
900 for host in host_name_list:
901 remove_hosts_id.append(self.get_host_id_by_name(host))
902
903 host_id_list = list(set(host_id_list + remove_hosts_id))
904 remove_hosts_id = list(set(existing_host_ids).intersection(set(host_id_list)))
905
906 if len(remove_hosts_id) == 0:
907 return False
908
909 for host in remove_hosts_id:
910 host_dict = {"id": host}
911 host_remove_list.append(host_dict)
912 cg_obj = self.return_cg_instance(cg_name)
913 try:
914 cg_obj.modify(name=cg_name, host_remove=host_remove_list)
915 return True
916 except Exception as e:
917 errormsg = "Removing host from consistency group {0} " \
918 "failed with error {1}".format(cg_name, str(e))
919 LOG.error(errormsg)
920 self.module.fail_json(msg=errormsg)
921
922 def rename_cg(self, cg_name, new_cg_name):
923 """Rename consistency group.
924 :param cg_name: The name of the consistency group
925 :param new_cg_name: The new name of the consistency group
926 :return: Boolean value to indicate if consistency group renamed
927 """
928 cg_obj = self.return_cg_instance(cg_name)
929
930 try:
931 cg_obj.modify(name=new_cg_name)
932 return True
933 except Exception as e:
934 errormsg = "Rename operation of consistency group {0} failed " \
935 "with error {1}".format(cg_name, str(e))
936 LOG.error(errormsg)
937 self.module.fail_json(msg=errormsg)
938
939 def is_cg_modified(self, cg_details):
940 """Check if the desired consistency group state is different from
941 existing consistency group.
942 :param cg_details: The dict containing consistency group details
943 :return: Boolean value to indicate if modification is needed
944 """
945 modified = False
946
947 if self.module.params['tiering_policy'] and cg_details['luns'] is \
948 None and self.module.params['volumes'] is None:
949 self.module.fail_json(msg="The system cannot assign a tiering"
950 " policy to an empty consistency group."
951 )
952
953 if self.module.params['hosts'] and cg_details['luns'] is \
954 None and self.module.params['volumes'] is None:
955 self.module.fail_json(msg="The system cannot assign hosts"
956 " to an empty consistency group.")
957
958 if ((cg_details['description'] is not None and
959 self.module.params['description'] is not None and
960 cg_details['description'] != self.module.params['description'])
961 or (cg_details['description'] is None and
962 self.module.params['description'] is not None)) or \
963 ((cg_details['snap_schedule'] is not None and
964 self.module.params['snap_schedule'] is not None and
965 cg_details['snap_schedule']['UnitySnapSchedule']['name'] !=
966 self.module.params['snap_schedule']) or
967 (cg_details['snap_schedule'] is None and
968 self.module.params['snap_schedule'])):
969 modified = True
970
971 if cg_details['relocation_policy']:
972 tier_policy = cg_details['relocation_policy'].split('.')
973 if self.module.params['tiering_policy'] is not None and \
974 tier_policy[1] != self.module.params['tiering_policy']:
975 modified = True
976
977 return modified
978
979 def create_cg(self, cg_name, description, snap_schedule):
980 """Create a consistency group.
981 :param cg_name: The name of the consistency group
982 :param description: The description of the consistency group
983 :param snap_schedule: The name of the snapshot schedule
984 :return: The boolean value to indicate if consistency group
985 created and also returns the CG object
986 """
987
988 try:
989 if snap_schedule is not None:
990 snap_schedule = {"name": snap_schedule}
991
992 cg_obj = utils.cg.UnityConsistencyGroup.create(
993 self.unity_conn._cli, name=cg_name, description=description,
994 snap_schedule=snap_schedule)
995 return True, cg_obj
996 except Exception as e:
997 errormsg = "Create operation of consistency group {0} failed" \
998 " with error {1}".format(cg_name, str(e))
999 LOG.error(errormsg)
1000 self.module.fail_json(msg=errormsg)
1001
1002 def modify_cg(self, cg_name, description, snap_schedule, tiering_policy):
1003 """Modify consistency group.
1004 :param cg_name: The name of the consistency group
1005 :param description: The description of the consistency group
1006 :param snap_schedule: The name of the snapshot schedule
1007 :param tiering_policy: The tiering policy that is to be applied to
1008 consistency group
1009 :return: The boolean value to indicate if consistency group
1010 modified
1011 """
1012 cg_obj = self.return_cg_instance(cg_name)
1013 is_snap_schedule_paused = None
1014
1015 if self.module.params['snap_schedule'] == "":
1016 is_snap_schedule_paused = False
1017
1018 if snap_schedule is not None:
1019 if snap_schedule == "":
1020 snap_schedule = {"name": None}
1021 else:
1022 snap_schedule = {"name": snap_schedule}
1023
1024 policy_enum = None
1025 if tiering_policy:
1026 if utils.TieringPolicyEnum[tiering_policy]:
1027 policy_enum = utils.TieringPolicyEnum[tiering_policy]
1028 else:
1029 errormsg = "Invalid choice {0} for tiering policy".format(
1030 tiering_policy)
1031 LOG.error(errormsg)
1032 self.module.fail_json(msg=errormsg)
1033
1034 try:
1035 cg_obj.modify(description=description,
1036 snap_schedule=snap_schedule,
1037 tiering_policy=policy_enum,
1038 is_snap_schedule_paused=is_snap_schedule_paused)
1039 return True
1040
1041 except Exception as e:
1042 errormsg = "Modify operation of consistency group {0} failed " \
1043 "with error {1}".format(cg_name, str(e))
1044 LOG.error(errormsg)
1045 self.module.fail_json(msg=errormsg)
1046
1047 def delete_cg(self, cg_name):
1048 """Delete consistency group.
1049 :param cg_name: The name of the consistency group
1050 :return: The boolean value to indicate if consistency group deleted
1051 """
1052 cg_obj = self.return_cg_instance(cg_name)
1053
1054 try:
1055 cg_obj.delete()
1056 return True
1057
1058 except Exception as e:
1059 errormsg = "Delete operation of consistency group {0} failed " \
1060 "with error {1}".format(cg_name, str(e))
1061 LOG.error(errormsg)
1062 self.module.fail_json(msg=errormsg)
1063
1064 def refine_volumes(self, volumes):
1065 """Refine volumes.
1066 :param volumes: Volumes that is to be added/removed
1067 :return: List of volumes with each volume being identified with either
1068 vol_id or vol_name
1069 """
1070 for vol in volumes:
1071 if vol['vol_id'] is not None and vol['vol_name'] is None:
1072 del vol['vol_name']
1073 elif vol['vol_name'] is not None and vol['vol_id'] is None:
1074 del vol['vol_id']
1075 return volumes
1076
1077 def refine_hosts(self, hosts):
1078 """Refine hosts.
1079 :param hosts: Hosts that is to be mapped/unmapped
1080 :return: List of hosts with each host being identified with either
1081 host_id or host_name
1082 """
1083 for host in hosts:
1084 if host['host_id'] is not None and host['host_name'] is None:
1085 del host['host_name']
1086 elif host['host_name'] is not None and host['host_id'] is None:
1087 del host['host_id']
1088 return hosts
1089
1090 def validate_volumes(self, volumes):
1091 """Validate the volumes.
1092 :param volumes: List of volumes
1093 """
1094
1095 for vol in volumes:
1096 if ('vol_id' in vol) and ('vol_name' in vol):
1097 errormsg = "Both name and id are found for volume {0}. No" \
1098 " action would be taken. Please specify either" \
1099 " name or id.".format(vol)
1100 LOG.error(errormsg)
1101 self.module.fail_json(msg=errormsg)
1102 elif 'vol_id' in vol and (len(vol['vol_id'].strip()) == 0):
1103 errormsg = "vol_id is blank. Please specify valid vol_id."
1104 LOG.error(errormsg)
1105 self.module.fail_json(msg=errormsg)
1106 elif 'vol_name' in vol and (len(vol.get('vol_name').strip()) == 0):
1107 errormsg = "vol_name is blank. Please specify valid vol_name."
1108 LOG.error(errormsg)
1109 self.module.fail_json(msg=errormsg)
1110 elif 'vol_name' in vol:
1111 self.get_volume_details(vol_name=vol['vol_name'])
1112 elif 'vol_id' in vol:
1113 self.get_volume_details(vol_id=vol['vol_id'])
1114 else:
1115 errormsg = "Expected either vol_name or vol_id, found" \
1116 " neither for volume {0}".format(vol)
1117 LOG.error(errormsg)
1118 self.module.fail_json(msg=errormsg)
1119
1120 def validate_hosts(self, hosts):
1121 """Validate hosts.
1122 :param hosts: List of hosts
1123 """
1124
1125 for host in hosts:
1126 if ('host_id' in host) and ('host_name' in host):
1127 errormsg = "Both name and id are found for host {0}. No" \
1128 " action would be taken. Please specify either" \
1129 " name or id.".format(host)
1130 LOG.error(errormsg)
1131 self.module.fail_json(msg=errormsg)
1132 elif 'host_id' in host and (len(host['host_id'].strip()) == 0):
1133 errormsg = "host_id is blank. Please specify valid host_id."
1134 LOG.error(errormsg)
1135 self.module.fail_json(msg=errormsg)
1136 elif 'host_name' in host and (len(host.get('host_name').strip()) == 0):
1137 errormsg = "host_name is blank. Please specify valid host_name."
1138 LOG.error(errormsg)
1139 self.module.fail_json(msg=errormsg)
1140 elif 'host_name' in host:
1141 self.get_host_id_by_name(host_name=host['host_name'])
1142 elif 'host_id' in host:
1143 host_obj = self.unity_conn.get_host(_id=host['host_id'])
1144 if host_obj is None or host_obj.existed is False:
1145 msg = "Host id: %s does not exists" % host['host_id']
1146 LOG.error(msg)
1147 self.module.fail_json(msg=msg)
1148
1149 else:
1150 errormsg = "Expected either host_name or host_id, found" \
1151 " neither for host {0}".format(host)
1152 LOG.error(errormsg)
1153 self.module.fail_json(msg=errormsg)
1154
1155 def update_replication_params(self, replication):
1156 ''' Update replication params '''
1157
1158 if 'replication_type' in replication and replication['replication_type'] == 'remote':
1159 connection_params = {
1160 'unispherehost': replication['remote_system']['remote_system_host'],
1161 'username': replication['remote_system']['remote_system_username'],
1162 'password': replication['remote_system']['remote_system_password'],
1163 'validate_certs': replication['remote_system']['remote_system_verifycert'],
1164 'port': replication['remote_system']['remote_system_port']
1165 }
1166 remote_system_conn = utils.get_unity_unisphere_connection(
1167 connection_params, application_type)
1168 replication['remote_system_name'] = remote_system_conn.name
1169 if replication['destination_pool_name'] is not None:
1170 pool_object = remote_system_conn.get_pool(name=replication['destination_pool_name'])
1171 replication['destination_pool_id'] = pool_object.id
1172 else:
1173 if replication['destination_pool_name'] is not None:
1174 pool_object = self.unity_conn.get_pool(name=replication['destination_pool_name'])
1175 replication['destination_pool_id'] = pool_object.id
1176
1177 def get_destination_cg_luns(self, source_lun_list):
1178 ''' Form destination cg lun list '''
1179 destination_cg_lun_list = []
1180 if source_lun_list is not None:
1181 for source_lun in source_lun_list:
1182 destination_cg_lun_info = utils.UnityStorageResource()
1183 destination_cg_lun_info.name = "DR_" + source_lun.name
1184 destination_cg_lun_info.is_thin_enabled = source_lun.is_thin_enabled
1185 destination_cg_lun_info.size_total = source_lun.size_total
1186 destination_cg_lun_info.id = source_lun.id
1187 destination_cg_lun_info.is_data_reduction_enabled = source_lun.is_data_reduction_enabled
1188 destination_cg_lun_list.append(destination_cg_lun_info)
1189 return destination_cg_lun_list
1190
1191 def enable_cg_replication(self, cg_name, replication):
1192 ''' Add replication to the consistency group '''
1193 try:
1194 # Validate replication params
1195 self.validate_cg_replication_params(replication)
1196
1197 # Get cg instance
1198 cg_object = self.return_cg_instance(cg_name)
1199
1200 # Check if replication is enabled for cg
1201 if cg_object.check_cg_is_replicated():
1202 return False
1203
1204 # Update replication params
1205 self.update_replication_params(replication)
1206
1207 # Get destination pool id
1208 replication_args_list = {
1209 'dst_pool_id': replication['destination_pool_id']
1210 }
1211
1212 # Get replication mode
1213 if 'replication_mode' in replication and replication['replication_mode'] == 'asynchronous':
1214 replication_args_list['max_time_out_of_sync'] = replication['rpo']
1215 else:
1216 replication_args_list['max_time_out_of_sync'] = -1
1217
1218 # Get remote system
1219 if 'replication_type' in replication and replication['replication_type'] == 'remote':
1220 remote_system_name = replication['remote_system_name']
1221 remote_system_list = self.unity_conn.get_remote_system()
1222 for remote_system in remote_system_list:
1223 if remote_system.name == remote_system_name:
1224 replication_args_list['remote_system'] = remote_system
1225 break
1226 if 'remote_system' not in replication_args_list.keys():
1227 errormsg = "Remote system %s is not found" % (remote_system_name)
1228 LOG.error(errormsg)
1229 self.module.fail_json(msg=errormsg)
1230
1231 # Form destination LUNs list
1232 source_lun_list = cg_object.luns
1233 replication_args_list['source_luns'] = self.get_destination_cg_luns(source_lun_list)
1234
1235 # Form destination cg name
1236 if 'destination_cg_name' in replication and replication['destination_cg_name'] is not None:
1237 replication_args_list['dst_cg_name'] = replication['destination_cg_name']
1238 else:
1239 replication_args_list['dst_cg_name'] = "DR_" + cg_object.name
1240
1241 LOG.info(("Enabling replication to the consistency group %s", cg_object.name))
1242 cg_object.replicate_cg_with_dst_resource_provisioning(**replication_args_list)
1243 return True
1244 except Exception as e:
1245 errormsg = "Enabling replication to the consistency group %s failed " \
1246 "with error %s" % (cg_object.name, str(e))
1247 LOG.error(errormsg)
1248 self.module.fail_json(msg=errormsg)
1249
1250 def disable_cg_replication(self, cg_name):
1251 ''' Remove replication from the consistency group '''
1252 try:
1253 # Get cg instance
1254 cg_object = self.return_cg_instance(cg_name)
1255
1256 # Check if replication is enabled for cg
1257 if not cg_object.check_cg_is_replicated():
1258 return False
1259
1260 LOG.info(("Disabling replication from the consistency group %s", cg_object.name))
1261 curr_cg_repl_session = self.unity_conn.get_replication_session(src_resource_id=cg_object.id)
1262 for repl_session in curr_cg_repl_session:
1263 repl_session.delete()
1264 return True
1265 except Exception as e:
1266 errormsg = "Disabling replication to the consistency group %s failed " \
1267 "with error %s" % (cg_object.name, str(e))
1268 LOG.error(errormsg)
1269 self.module.fail_json(msg=errormsg)
1270
1271 def perform_module_operation(self):
1272 """
1273 Perform different actions on consistency group module based on
1274 parameters chosen in playbook
1275 """
1276 cg_name = self.module.params['cg_name']
1277 cg_id = self.module.params['cg_id']
1278 description = self.module.params['description']
1279 volumes = self.module.params['volumes']
1280 snap_schedule = self.module.params['snap_schedule']
1281 new_cg_name = self.module.params['new_cg_name']
1282 tiering_policy = self.module.params['tiering_policy']
1283 vol_state = self.module.params['vol_state']
1284 hosts = self.module.params['hosts']
1285 mapping_state = self.module.params['mapping_state']
1286 replication = self.module.params['replication_params']
1287 replication_state = self.module.params['replication_state']
1288 state = self.module.params['state']
1289
1290 # result is a dictionary that contains changed status and consistency
1291 # group details
1292 result = dict(
1293 changed=False,
1294 create_cg='',
1295 modify_cg='',
1296 rename_cg='',
1297 add_vols_to_cg='',
1298 remove_vols_from_cg='',
1299 delete_cg='',
1300 add_hosts_to_cg='',
1301 remove_hosts_from_cg='',
1302 consistency_group_details={}
1303 )
1304 cg_details = self.get_details(cg_id=cg_id, cg_name=cg_name)
1305
1306 if cg_name is None and cg_details:
1307 cg_id = None
1308 cg_name = cg_details['name']
1309 if volumes:
1310 volumes = self.refine_volumes(volumes)
1311 self.validate_volumes(volumes)
1312 if hosts:
1313 hosts = self.refine_hosts(hosts)
1314 self.validate_hosts(hosts)
1315
1316 modified = False
1317
1318 if cg_details:
1319 modified = self.is_cg_modified(cg_details)
1320
1321 if vol_state and not volumes:
1322 self.module.fail_json(msg="Please specify volumes along with vol_state")
1323
1324 if mapping_state and not hosts:
1325 self.module.fail_json(msg="Please specify hosts along with mapping_state")
1326
1327 if replication and replication_state is None:
1328 self.module.fail_json(msg="Please specify replication_state along with replication_params")
1329
1330 if state == 'present' and not cg_details:
1331 if not volumes and tiering_policy:
1332 self.module.fail_json(msg="The system cannot assign a"
1333 " tiering policy to an empty"
1334 " consistency group")
1335 if not volumes and hosts:
1336 self.module.fail_json(msg="The system cannot assign"
1337 " hosts to an empty"
1338 " consistency group")
1339
1340 if not cg_name:
1341 msg = "The parameter cg_name length is 0. It is too short." \
1342 " The min length is 1."
1343 self.module.fail_json(msg=msg)
1344
1345 if new_cg_name:
1346 self.module.fail_json(msg="Invalid argument, new_cg_name is"
1347 " not required")
1348
1349 result['create_cg'], cg_details = self.create_cg(
1350 cg_name, description, snap_schedule)
1351 elif state == 'absent' and cg_details:
1352 if cg_details['cg_replication_enabled']:
1353 self.module.fail_json(msg="Consistency group cannot be deleted"
1354 " because it is participating"
1355 " in a replication session.")
1356 if cg_details['luns']:
1357 self.module.fail_json(msg="Please remove all volumes which"
1358 " are part of consistency group"
1359 " before deleting it.")
1360 result['delete_cg'] = self.delete_cg(cg_name)
1361
1362 if state == 'present' and vol_state == 'present-in-group' and \
1363 cg_details and volumes:
1364 result['add_vols_to_cg'] = self.add_volumes_to_cg(cg_name,
1365 volumes,
1366 tiering_policy)
1367 elif state == 'present' and vol_state == 'absent-in-group' and \
1368 cg_details and volumes:
1369 result['remove_vols_from_cg'] = self.remove_volumes_from_cg(
1370 cg_name, volumes)
1371
1372 if hosts and mapping_state == 'mapped' and \
1373 cg_details:
1374 result['add_hosts_to_cg'] = self.map_hosts_to_cg(cg_name, hosts)
1375
1376 if hosts and mapping_state == 'unmapped' and \
1377 cg_details:
1378 result['remove_hosts_from_cg'] = self.unmap_hosts_to_cg(cg_name, hosts)
1379
1380 if state == 'present' and new_cg_name is not None:
1381 if not new_cg_name:
1382 msg = "The parameter new_cg_name length is 0. It is too" \
1383 " short. The min length is 1."
1384 self.module.fail_json(msg=msg)
1385
1386 if cg_name != new_cg_name:
1387 result['rename_cg'] = self.rename_cg(cg_name, new_cg_name)
1388 cg_name = new_cg_name
1389
1390 if state == 'present' and cg_details and modified:
1391 result['modify_cg'] = self.modify_cg(cg_name, description,
1392 snap_schedule, tiering_policy
1393 )
1394
1395 if state == 'present' and cg_details and replication_state is not None:
1396 if replication_state == 'enable':
1397 result['changed'] = self.enable_cg_replication(cg_name, replication)
1398 else:
1399 result['changed'] = self.disable_cg_replication(cg_name)
1400
1401 if result['create_cg'] or result['modify_cg'] or result[
1402 'add_vols_to_cg'] or result['remove_vols_from_cg'] or result[
1403 'delete_cg'] or result['rename_cg'] or result[
1404 'add_hosts_to_cg'] or result['remove_hosts_from_cg']:
1405 result['changed'] = True
1406
1407 result['consistency_group_details'] = self.get_details(cg_id=cg_id,
1408 cg_name=cg_name
1409 )
1410
1411 self.module.exit_json(**result)
1412
1413 def validate_destination_pool_info(self, replication):
1414 if replication['destination_pool_id'] is not None and replication['destination_pool_name'] is not None:
1415 errormsg = "'destination_pool_id' and 'destination_pool_name' is mutually exclusive."
1416 LOG.error(errormsg)
1417 self.module.fail_json(msg=errormsg)
1418
1419 if replication['destination_pool_id'] is None and replication['destination_pool_name'] is None:
1420 errormsg = "Either 'destination_pool_id' or 'destination_pool_name' is required."
1421 LOG.error(errormsg)
1422 self.module.fail_json(msg=errormsg)
1423
1424 def validate_replication_mode(self, replication):
1425 if 'replication_mode' in replication and replication['replication_mode'] == 'asynchronous':
1426 if replication['rpo'] is None:
1427 errormsg = "rpo is required together with 'asynchronous' replication_mode."
1428 LOG.error(errormsg)
1429 self.module.fail_json(msg=errormsg)
1430 if replication['rpo'] < 5 or replication['rpo'] > 1440:
1431 errormsg = "rpo value should be in range of 5 to 1440"
1432 LOG.error(errormsg)
1433 self.module.fail_json(msg=errormsg)
1434
1435 def validate_cg_replication_params(self, replication):
1436 ''' Validate cg replication params '''
1437 # Valdiate replication
1438 if replication is None:
1439 errormsg = "Please specify replication_params to enable replication."
1440 LOG.error(errormsg)
1441 self.module.fail_json(msg=errormsg)
1442 else:
1443 self.validate_destination_pool_info(replication)
1444 self.validate_replication_mode(replication)
1445 # Validate replication type
1446 if replication['replication_type'] == 'remote' and replication['remote_system'] is None:
1447 errormsg = "remote_system is required together with 'remote' replication_type"
1448 LOG.error(errormsg)
1449 self.module.fail_json(msg=errormsg)
1450 # Validate destination cg name
1451 if 'destination_cg_name' in replication and replication['destination_cg_name'] is not None:
1452 dst_cg_name_length = len(replication['destination_cg_name'])
1453 if dst_cg_name_length == 0 or dst_cg_name_length > 95:
1454 errormsg = "destination_cg_name value should be in range of 1 to 95"
1455 LOG.error(errormsg)
1456 self.module.fail_json(msg=errormsg)
1457
1458
1459 def get_consistencygroup_parameters():
1460 """This method provide parameters required for the ansible consistency
1461 group module on Unity"""
1462 return dict(
1463 cg_name=dict(required=False, type='str'),
1464 cg_id=dict(required=False, type='str'),
1465 description=dict(required=False, type='str'),
1466 volumes=dict(required=False, type='list', elements='dict',
1467 options=dict(
1468 vol_name=dict(type='str'),
1469 vol_id=dict(type='str')
1470 )
1471 ),
1472 snap_schedule=dict(required=False, type='str'),
1473 new_cg_name=dict(required=False, type='str'),
1474 tiering_policy=dict(required=False, type='str', choices=[
1475 'AUTOTIER_HIGH', 'AUTOTIER', 'HIGHEST', 'LOWEST']),
1476 vol_state=dict(required=False, type='str',
1477 choices=['present-in-group', 'absent-in-group']),
1478 hosts=dict(required=False, type='list', elements='dict',
1479 options=dict(
1480 host_name=dict(type='str'),
1481 host_id=dict(type='str')
1482 )),
1483 mapping_state=dict(required=False, type='str',
1484 choices=['mapped', 'unmapped']),
1485 replication_params=dict(type='dict', options=dict(
1486 destination_cg_name=dict(type='str'),
1487 replication_mode=dict(type='str', choices=['asynchronous', 'manual'], required=True),
1488 rpo=dict(type='int'),
1489 replication_type=dict(type='str', choices=['local', 'remote'], default='local'),
1490 remote_system=dict(type='dict',
1491 options=dict(
1492 remote_system_host=dict(type='str', required=True, no_log=True),
1493 remote_system_verifycert=dict(type='bool', required=False,
1494 default=True),
1495 remote_system_username=dict(type='str', required=True),
1496 remote_system_password=dict(type='str', required=True, no_log=True),
1497 remote_system_port=dict(type='int', required=False, default=443, no_log=True)
1498 )),
1499 destination_pool_name=dict(type='str'),
1500 destination_pool_id=dict(type='str')
1501 )),
1502 replication_state=dict(type='str', choices=['enable', 'disable']),
1503 state=dict(required=True, type='str', choices=['present', 'absent'])
1504 )
1505
1506
1507 def main():
1508 """ Create Unity consistency group object and perform action on it
1509 based on user input from playbook"""
1510 obj = ConsistencyGroup()
1511 obj.perform_module_operation()
1512
1513
1514 if __name__ == '__main__':
1515 main()