Debian Codegraph @

ansible_collections/dellemc/powerflex/plugins/modules/replication_consistency_group.py

raw symbols SCIP
1 #!/usr/bin/python
2
3 # Copyright: (c) 2022, Dell Technologies
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 """ Ansible module for managing replication consistency groups on Dell Technologies (Dell) PowerFlex"""
7
8 from __future__ import (absolute_import, division, print_function)
9
10 __metaclass__ = type
11
12 DOCUMENTATION = r'''
13 module: replication_consistency_group
14 version_added: '1.5.0'
15 short_description: Manage replication consistency groups on Dell PowerFlex
16 description:
17 - Managing replication consistency groups on PowerFlex storage system includes
18 getting details, creating, modifying, creating snapshots, pause, resume, freeze, unfreeze,
19 activate, failover, reverse, restore, sync, switchover,
20 inactivate and deleting a replication consistency group.
21 author:
22 - Trisha Datta (@Trisha-Datta) <[email protected]>
23 - Jennifer John (@Jennifer-John) <[email protected]>
24 extends_documentation_fragment:
25 - dellemc.powerflex.powerflex
26 options:
27 rcg_name:
28 description:
29 - The name of the replication consistency group.
30 - It is unique across the PowerFlex array.
31 - Mutually exclusive with I(rcg_id).
32 type: str
33 rcg_id:
34 description:
35 - The ID of the replication consistency group.
36 - Mutually exclusive with I(rcg_name).
37 type: str
38 create_snapshot:
39 description:
40 - Whether to create the snapshot of the replication consistency group.
41 type: bool
42 rpo:
43 description:
44 - Desired RPO in seconds.
45 type: int
46 protection_domain_id:
47 description:
48 - Protection domain id.
49 - Mutually exclusive with I(protection_domain_name).
50 type: str
51 protection_domain_name:
52 description:
53 - Protection domain name.
54 - Mutually exclusive with I(protection_domain_id).
55 type: str
56 activity_mode:
57 description:
58 - Activity mode of RCG.
59 - This parameter is supported for version 3.6 and above.
60 choices: ['Active', 'Inactive']
61 type: str
62 rcg_state:
63 description:
64 - Specify an action for RCG.
65 - Failover the RCG.
66 - Reverse the RCG.
67 - Restore the RCG.
68 - Switchover the RCG.
69 - Pause or resume the RCG.
70 - Freeze or unfreeze the RCG.
71 - Synchronize the RCG.
72 choices: ['failover', 'reverse', 'restore',
73 'switchover', 'sync', 'pause',
74 'resume', 'freeze', 'unfreeze']
75 type: str
76 force:
77 description:
78 - Force switchover the RCG.
79 type: bool
80 pause_mode:
81 description:
82 - Pause mode.
83 - It is required if pause is set as true.
84 choices: ['StopDataTransfer', 'OnlyTrackChanges']
85 type: str
86 target_volume_access_mode:
87 description:
88 - Target volume access mode.
89 choices: ['ReadOnly', 'NoAccess']
90 type: str
91 is_consistent:
92 description:
93 - Consistency of RCG.
94 type: bool
95 new_rcg_name:
96 description:
97 - Name of RCG to rename to.
98 type: str
99 remote_peer:
100 description:
101 - Remote peer system.
102 type: dict
103 suboptions:
104 hostname:
105 required: true
106 description:
107 - IP or FQDN of the remote peer gateway host.
108 type: str
109 aliases:
110 - gateway_host
111 username:
112 type: str
113 required: true
114 description:
115 - The username of the remote peer gateway host.
116 password:
117 type: str
118 required: true
119 description:
120 - The password of the remote peer gateway host.
121 validate_certs:
122 type: bool
123 default: true
124 aliases:
125 - verifycert
126 description:
127 - Boolean variable to specify whether or not to validate SSL
128 certificate.
129 - C(true) - Indicates that the SSL certificate should be verified.
130 - C(false) - Indicates that the SSL certificate should not be verified.
131 port:
132 description:
133 - Port number through which communication happens with remote peer
134 gateway host.
135 type: int
136 default: 443
137 timeout:
138 description:
139 - Time after which connection will get terminated.
140 - It is to be mentioned in seconds.
141 type: int
142 default: 120
143 protection_domain_id:
144 description:
145 - Remote protection domain id.
146 - Mutually exclusive with I(protection_domain_name).
147 type: str
148 protection_domain_name:
149 description:
150 - Remote protection domain name.
151 - Mutually exclusive with I(protection_domain_id).
152 type: str
153 state:
154 description:
155 - State of the replication consistency group.
156 choices: ['present', 'absent']
157 default: present
158 type: str
159 notes:
160 - The I(check_mode) is supported.
161 - Idempotency is not supported for create snapshot operation.
162 - There is a delay in reflection of final state of RCG after few update operations on RCG.
163 - In 3.6 and above, the replication consistency group will return back to consistent mode on changing to inconsistent mode
164 if consistence barrier arrives. Hence idempotency on setting to inconsistent mode will return changed as true.
165 - The pause and freeze parameters are removed in 3.0.0 version. Use 'rcg_state' param instead.
166 '''
167
168 EXAMPLES = r'''
169
170 - name: Get RCG details
171 dellemc.powerflex.replication_consistency_group:
172 hostname: "{{hostname}}"
173 username: "{{username}}"
174 password: "{{password}}"
175 validate_certs: "{{validate_certs}}"
176 port: "{{port}}"
177 rcg_name: "{{rcg_name}}"
178
179 - name: Create a snapshot of the RCG
180 dellemc.powerflex.replication_consistency_group:
181 hostname: "{{hostname}}"
182 username: "{{username}}"
183 password: "{{password}}"
184 validate_certs: "{{validate_certs}}"
185 port: "{{port}}"
186 rcg_id: "{{rcg_id}}"
187 create_snapshot: true
188 state: "present"
189
190 - name: Create a replication consistency group
191 dellemc.powerflex.replication_consistency_group:
192 hostname: "{{hostname}}"
193 username: "{{username}}"
194 password: "{{password}}"
195 validate_certs: "{{validate_certs}}"
196 port: "{{port}}"
197 rcg_name: "rcg_test"
198 rpo: 60
199 protection_domain_name: "domain1"
200 activity_mode: "active"
201 remote_peer:
202 hostname: "{{hostname}}"
203 username: "{{username}}"
204 password: "{{password}}"
205 validate_certs: "{{validate_certs}}"
206 port: "{{port}}"
207 protection_domain_name: "domain1"
208
209 - name: Modify replication consistency group
210 dellemc.powerflex.replication_consistency_group:
211 hostname: "{{hostname}}"
212 username: "{{username}}"
213 password: "{{password}}"
214 validate_certs: "{{validate_certs}}"
215 port: "{{port}}"
216 rcg_name: "rcg_test"
217 rpo: 60
218 target_volume_access_mode: "ReadOnly"
219 activity_mode: "Inactive"
220 is_consistent: true
221
222 - name: Rename replication consistency group
223 dellemc.powerflex.replication_consistency_group:
224 hostname: "{{hostname}}"
225 username: "{{username}}"
226 password: "{{password}}"
227 validate_certs: "{{validate_certs}}"
228 port: "{{port}}"
229 rcg_name: "rcg_test"
230 new_rcg_name: "rcg_test_rename"
231
232 - name: Pause replication consistency group
233 dellemc.powerflex.replication_consistency_group:
234 hostname: "{{hostname}}"
235 username: "{{username}}"
236 password: "{{password}}"
237 validate_certs: "{{validate_certs}}"
238 port: "{{port}}"
239 rcg_name: "rcg_test"
240 rcg_state: "pause"
241 pause_mode: "StopDataTransfer"
242
243 - name: Resume replication consistency group
244 dellemc.powerflex.replication_consistency_group:
245 hostname: "{{hostname}}"
246 username: "{{username}}"
247 password: "{{password}}"
248 validate_certs: "{{validate_certs}}"
249 port: "{{port}}"
250 rcg_name: "rcg_test"
251 rcg_state: "resume"
252
253 - name: Freeze replication consistency group
254 dellemc.powerflex.replication_consistency_group:
255 hostname: "{{hostname}}"
256 username: "{{username}}"
257 password: "{{password}}"
258 validate_certs: "{{validate_certs}}"
259 port: "{{port}}"
260 rcg_name: "rcg_test"
261 rcg_state: "freeze"
262
263 - name: UnFreeze replication consistency group
264 dellemc.powerflex.replication_consistency_group:
265 hostname: "{{hostname}}"
266 username: "{{username}}"
267 password: "{{password}}"
268 validate_certs: "{{validate_certs}}"
269 port: "{{port}}"
270 rcg_name: "rcg_test"
271 rcg_state: "unfreeze"
272
273 - name: Failover replication consistency group
274 dellemc.powerflex.replication_consistency_group:
275 hostname: "{{hostname}}"
276 username: "{{username}}"
277 password: "{{password}}"
278 validate_certs: "{{validate_certs}}"
279 port: "{{port}}"
280 rcg_name: "rcg_test"
281 rcg_state: "failover"
282
283 - name: Reverse replication consistency group
284 dellemc.powerflex.replication_consistency_group:
285 hostname: "{{hostname}}"
286 username: "{{username}}"
287 password: "{{password}}"
288 validate_certs: "{{validate_certs}}"
289 port: "{{port}}"
290 rcg_name: "rcg_test"
291 rcg_state: "reverse"
292
293 - name: Restore replication consistency group
294 dellemc.powerflex.replication_consistency_group:
295 hostname: "{{hostname}}"
296 username: "{{username}}"
297 password: "{{password}}"
298 validate_certs: "{{validate_certs}}"
299 port: "{{port}}"
300 rcg_name: "rcg_test"
301 rcg_state: "restore"
302
303 - name: Switchover replication consistency group
304 dellemc.powerflex.replication_consistency_group:
305 hostname: "{{hostname}}"
306 username: "{{username}}"
307 password: "{{password}}"
308 validate_certs: "{{validate_certs}}"
309 port: "{{port}}"
310 rcg_name: "rcg_test"
311 rcg_state: "switchover"
312
313 - name: Synchronize replication consistency group
314 dellemc.powerflex.replication_consistency_group:
315 hostname: "{{hostname}}"
316 username: "{{username}}"
317 password: "{{password}}"
318 validate_certs: "{{validate_certs}}"
319 port: "{{port}}"
320 rcg_name: "rcg_test"
321 rcg_state: "sync"
322
323 - name: Delete replication consistency group
324 dellemc.powerflex.replication_consistency_group:
325 hostname: "{{hostname}}"
326 username: "{{username}}"
327 password: "{{password}}"
328 validate_certs: "{{validate_certs}}"
329 port: "{{port}}"
330 rcg_name: "rcg_test"
331 state: "absent"
332 '''
333
334 RETURN = r'''
335 changed:
336 description: Whether or not the resource has changed.
337 returned: always
338 type: bool
339 sample: 'false'
340 replication_consistency_group_details:
341 description: Details of the replication consistency group.
342 returned: When replication consistency group exists
343 type: dict
344 contains:
345 id:
346 description: The ID of the replication consistency group.
347 type: str
348 name:
349 description: The name of the replication consistency group.
350 type: str
351 protectionDomainId:
352 description: The Protection Domain ID of the replication consistency group.
353 type: str
354 peerMdmId:
355 description: The ID of the peer MDM of the replication consistency group.
356 type: str
357 remoteId:
358 description: The ID of the remote replication consistency group.
359 type: str
360 remoteMdmId:
361 description: The ID of the remote MDM of the replication consistency group.
362 type: str
363 currConsistMode:
364 description: The current consistency mode of the replication consistency group.
365 type: str
366 freezeState:
367 description: The freeze state of the replication consistency group.
368 type: str
369 lifetimeState:
370 description: The Lifetime state of the replication consistency group.
371 type: str
372 pauseMode:
373 description: The Lifetime state of the replication consistency group.
374 type: str
375 snapCreationInProgress:
376 description: Whether the process of snapshot creation of the replication consistency group is in progress or not.
377 type: bool
378 lastSnapGroupId:
379 description: ID of the last snapshot of the replication consistency group.
380 type: str
381 lastSnapCreationRc:
382 description: The return code of the last snapshot of the replication consistency group.
383 type: int
384 targetVolumeAccessMode:
385 description: The access mode of the target volume of the replication consistency group.
386 type: str
387 remoteProtectionDomainId:
388 description: The ID of the remote Protection Domain.
389 type: str
390 remoteProtectionDomainName:
391 description: The Name of the remote Protection Domain.
392 type: str
393 failoverType:
394 description: The type of failover of the replication consistency group.
395 type: str
396 failoverState:
397 description: The state of failover of the replication consistency group.
398 type: str
399 activeLocal:
400 description: Whether the local replication consistency group is active.
401 type: bool
402 activeRemote:
403 description: Whether the remote replication consistency group is active
404 type: bool
405 abstractState:
406 description: The abstract state of the replication consistency group.
407 type: str
408 localActivityState:
409 description: The state of activity of the local replication consistency group.
410 type: str
411 remoteActivityState:
412 description: The state of activity of the remote replication consistency group..
413 type: str
414 inactiveReason:
415 description: The reason for the inactivity of the replication consistency group.
416 type: int
417 rpoInSeconds:
418 description: The RPO value of the replication consistency group in seconds.
419 type: int
420 replicationDirection:
421 description: The direction of the replication of the replication consistency group.
422 type: str
423 disasterRecoveryState:
424 description: The state of disaster recovery of the local replication consistency group.
425 type: str
426 remoteDisasterRecoveryState:
427 description: The state of disaster recovery of the remote replication consistency group.
428 type: str
429 error:
430 description: The error code of the replication consistency group.
431 type: int
432 type:
433 description: The type of the replication consistency group.
434 type: str
435 sample: {
436 "protectionDomainId": "b969400500000000",
437 "peerMdmId": "6c3d94f600000000",
438 "remoteId": "2130961a00000000",
439 "remoteMdmId": "0e7a082862fedf0f",
440 "currConsistMode": "Consistent",
441 "freezeState": "Unfrozen",
442 "lifetimeState": "Normal",
443 "pauseMode": "None",
444 "snapCreationInProgress": false,
445 "lastSnapGroupId": "e58280b300000001",
446 "lastSnapCreationRc": "SUCCESS",
447 "targetVolumeAccessMode": "NoAccess",
448 "remoteProtectionDomainId": "4eeb304600000000",
449 "remoteProtectionDomainName": "domain1",
450 "failoverType": "None",
451 "failoverState": "None",
452 "activeLocal": true,
453 "activeRemote": true,
454 "abstractState": "Ok",
455 "localActivityState": "Active",
456 "remoteActivityState": "Active",
457 "inactiveReason": 11,
458 "rpoInSeconds": 30,
459 "replicationDirection": "LocalToRemote",
460 "disasterRecoveryState": "None",
461 "remoteDisasterRecoveryState": "None",
462 "error": 65,
463 "name": "test_rcg",
464 "type": "User",
465 "id": "aadc17d500000000"
466 }
467 '''
468
469 from ansible.module_utils.basic import AnsibleModule
470 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell \
471 import utils
472 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell.libraries.powerflex_base \
473 import powerflex_compatibility
474 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell.libraries.powerflex_base \
475 import PowerFlexBase
476
477 LOG = utils.get_logger('replication_consistency_group')
478
479
480 @powerflex_compatibility(min_ver='3.6', max_ver='5.0')
481 class PowerFlexReplicationConsistencyGroup(PowerFlexBase):
482 """Class with replication consistency group operations"""
483
484 def __init__(self):
485 """ Define all parameters required by this module"""
486 argument_spec = get_powerflex_replication_consistency_group_parameters()
487 mut_ex_args = [['rcg_name', 'rcg_id'], ['protection_domain_id', 'protection_domain_name']]
488 required_one_of_args = [['rcg_name', 'rcg_id']]
489
490 ansible_module_params = {
491 'argument_spec': argument_spec,
492 'supports_check_mode': True,
493 'mutually_exclusive': mut_ex_args,
494 'required_one_of': required_one_of_args
495 }
496 super().__init__(AnsibleModule, ansible_module_params)
497 super().check_module_compatibility()
498
499 def get_rcg(self, rcg_name=None, rcg_id=None):
500 """Get rcg details
501 :param rcg_name: Name of the RCG
502 :param rcg_id: ID of the RCG
503 :return: RCG details
504 """
505 name_or_id = rcg_id if rcg_id else rcg_name
506 try:
507 rcg_details = None
508 if rcg_id:
509 rcg_details = self.powerflex_conn.replication_consistency_group.get(
510 filter_fields={'id': rcg_id})
511
512 if rcg_name:
513 rcg_details = self.powerflex_conn.replication_consistency_group.get(
514 filter_fields={'name': rcg_name})
515
516 if rcg_details:
517 rcg_details[0]['statistics'] = \
518 self.powerflex_conn.replication_consistency_group.get_statistics(rcg_details[0]['id'])
519 rcg_details[0].pop('links', None)
520 self.append_protection_domain_name(rcg_details[0])
521 return rcg_details[0]
522
523 except Exception as e:
524 errormsg = "Failed to get the replication consistency group {0} with" \
525 " error {1}".format(name_or_id, str(e))
526 LOG.error(errormsg)
527 self.module.fail_json(msg=errormsg)
528
529 def create_rcg_snapshot(self, rcg_id):
530 """Create RCG snapshot
531 :param rcg_id: Unique identifier of the RCG.
532 :return: Boolean indicating if create snapshot operation is successful
533 """
534 try:
535 if not self.module.check_mode:
536 self.powerflex_conn.replication_consistency_group.create_snapshot(
537 rcg_id=rcg_id)
538 return True
539
540 except Exception as e:
541 errormsg = "Create RCG snapshot for RCG with id {0} operation failed with " \
542 "error {1}".format(rcg_id, str(e))
543 LOG.error(errormsg)
544 self.module.fail_json(msg=errormsg)
545
546 def create_rcg(self, rcg_params):
547 """Create RCG"""
548 try:
549 resp = None
550 # Get remote system details
551 self.remote_powerflex_conn = utils.get_powerflex_gateway_host_connection(
552 self.module.params['remote_peer'])
553 LOG.info("Got the remote peer connection object instance")
554 protection_domain_id = rcg_params['protection_domain_id']
555 if rcg_params['protection_domain_name']:
556 protection_domain_id = \
557 self.get_protection_domain(self.powerflex_conn, rcg_params['protection_domain_name'])['id']
558
559 remote_protection_domain_id = rcg_params['remote_peer']['protection_domain_id']
560 if rcg_params['remote_peer']['protection_domain_name']:
561 remote_protection_domain_id = \
562 self.get_protection_domain(self.remote_powerflex_conn,
563 rcg_params['remote_peer']['protection_domain_name'])['id']
564
565 if not self.module.check_mode:
566 resp = self.powerflex_conn.replication_consistency_group.create(
567 rpo=rcg_params['rpo'],
568 protection_domain_id=protection_domain_id,
569 remote_protection_domain_id=remote_protection_domain_id,
570 destination_system_id=self.remote_powerflex_conn.system.get()[0]['id'],
571 name=rcg_params['rcg_name'],
572 activity_mode=rcg_params['activity_mode'])
573 return True, resp
574
575 except Exception as e:
576 errormsg = "Create replication consistency group failed with error {0}".format(str(e))
577 LOG.error(errormsg)
578 self.module.fail_json(msg=errormsg)
579
580 def modify_rpo(self, rcg_id, rpo):
581 """Modify rpo
582 :param rcg_id: Unique identifier of the RCG.
583 :param rpo: rpo value in seconds
584 :return: Boolean indicates if modify rpo is successful
585 """
586 try:
587 if not self.module.check_mode:
588 self.powerflex_conn.replication_consistency_group.modify_rpo(
589 rcg_id, rpo)
590 return True
591
592 except Exception as e:
593 errormsg = "Modify rpo for replication consistency group {0} failed with " \
594 "error {1}".format(rcg_id, str(e))
595 LOG.error(errormsg)
596 self.module.fail_json(msg=errormsg)
597
598 def modify_target_volume_access_mode(self, rcg_id, target_volume_access_mode):
599 """Modify target volume access mode
600 :param rcg_id: Unique identifier of the RCG.
601 :param target_volume_access_mode: Target volume access mode.
602 :return: Boolean indicates if modify operation is successful
603 """
604 try:
605 if not self.module.check_mode:
606 self.powerflex_conn.replication_consistency_group.modify_target_volume_access_mode(
607 rcg_id, target_volume_access_mode)
608 return True
609
610 except Exception as e:
611 errormsg = "Modify target volume access mode for replication consistency group {0} failed with " \
612 "error {1}".format(rcg_id, str(e))
613 LOG.error(errormsg)
614 self.module.fail_json(msg=errormsg)
615
616 def modify_activity_mode(self, rcg_id, rcg_details, activity_mode):
617 """Modify activity mode
618 :param rcg_id: Unique identifier of the RCG.
619 :param rcg_details: RCG details.
620 :param activity_mode: RCG activity mode.
621 :return: Boolean indicates if modify operation is successful
622 """
623 try:
624 if activity_mode == 'Active' and rcg_details['localActivityState'].lower() == 'inactive':
625 if not self.module.check_mode:
626 self.powerflex_conn.replication_consistency_group.activate(rcg_id)
627 return True
628 elif activity_mode == 'Inactive' and rcg_details['localActivityState'].lower() == 'active':
629 if not self.module.check_mode:
630 rcg_details = self.powerflex_conn.replication_consistency_group.inactivate(rcg_id)
631 return True
632 except Exception as e:
633 errormsg = "Modify activity_mode for replication consistency group {0} failed with " \
634 "error {1}".format(rcg_id, str(e))
635 LOG.error(errormsg)
636 self.module.fail_json(msg=errormsg)
637
638 def pause_or_resume_rcg(self, rcg_id, rcg_details, pause, pause_mode=None):
639 """Perform specified rcg action
640 :param rcg_id: Unique identifier of the RCG.
641 :param rcg_details: RCG details.
642 :param pause: Pause or resume RCG.
643 :param pause_mode: Specifies the pause mode if pause is True.
644 :return: Boolean indicates if RCG action is successful
645 """
646 if pause and rcg_details['pauseMode'] == 'None':
647 if not pause_mode:
648 self.module.fail_json(msg="Specify pause_mode to perform pause on replication consistency group.")
649 return self.pause(rcg_id, pause_mode)
650
651 if not pause and (rcg_details['pauseMode'] != 'None' or rcg_details['failoverType'] in ['Failover', 'Switchover']):
652 return self.resume(rcg_id)
653
654 def freeze_or_unfreeze_rcg(self, rcg_id, rcg_details, freeze):
655 """Perform specified RCG action
656 :param rcg_id: Unique identifier of the RCG.
657 :param rcg_details: RCG details.
658 :param freeze: Freeze or unfreeze RCG.
659 :return: Boolean indicates if RCG action is successful
660 """
661 if freeze and rcg_details['freezeState'].lower() == 'unfrozen':
662 return self.freeze(rcg_id)
663
664 if not freeze and rcg_details['freezeState'].lower() == 'frozen':
665 return self.unfreeze(rcg_id)
666
667 def freeze(self, rcg_id):
668 try:
669 if not self.module.check_mode:
670 self.powerflex_conn.replication_consistency_group.freeze(rcg_id)
671 return True
672 except Exception as e:
673 errormsg = "Freeze replication consistency group {0} failed with error {1}".format(rcg_id, str(e))
674 LOG.error(errormsg)
675 self.module.fail_json(msg=errormsg)
676
677 def unfreeze(self, rcg_id):
678 try:
679 if not self.module.check_mode:
680 self.powerflex_conn.replication_consistency_group.unfreeze(rcg_id)
681 return True
682 except Exception as e:
683 errormsg = "Unfreeze replication consistency group {0} failed with error {1}".format(rcg_id, str(e))
684 LOG.error(errormsg)
685 self.module.fail_json(msg=errormsg)
686
687 def pause(self, rcg_id, pause_mode):
688 try:
689 if not self.module.check_mode:
690 self.powerflex_conn.replication_consistency_group.pause(rcg_id, pause_mode)
691 return True
692 except Exception as e:
693 errormsg = "Pause replication consistency group {0} failed with error {1}".format(rcg_id, str(e))
694 LOG.error(errormsg)
695 self.module.fail_json(msg=errormsg)
696
697 def resume(self, rcg_id):
698 try:
699 if not self.module.check_mode:
700 self.powerflex_conn.replication_consistency_group.resume(rcg_id)
701 return True
702 except Exception as e:
703 errormsg = "Resume replication consistency group {0} failed with error {1}".format(rcg_id, str(e))
704 LOG.error(errormsg)
705 self.module.fail_json(msg=errormsg)
706
707 def failover(self, rcg_id):
708 """Perform failover
709 :param rcg_id: Unique identifier of the RCG.
710 :return: Boolean indicates if RCG failover is successful
711 """
712 try:
713 if not self.module.check_mode:
714 self.powerflex_conn.replication_consistency_group.failover(rcg_id)
715 return True
716 except Exception as e:
717 errormsg = f"Failover replication consistency group {rcg_id} failed with error {e}"
718 LOG.error(errormsg)
719 self.module.fail_json(msg=errormsg)
720
721 def reverse(self, rcg_id):
722 """Perform reverse
723 :param rcg_id: Unique identifier of the RCG.
724 :return: Boolean indicates if RCG reverse is successful
725 """
726 try:
727 if not self.module.check_mode:
728 self.powerflex_conn.replication_consistency_group.reverse(rcg_id)
729 return True
730 except Exception as e:
731 errormsg = f"Reverse replication consistency group {rcg_id} failed with error {e}"
732 LOG.error(errormsg)
733 self.module.fail_json(msg=errormsg)
734
735 def restore(self, rcg_id):
736 """Perform restore
737 :param rcg_id: Unique identifier of the RCG.
738 :return: Boolean indicates if RCG restore is successful
739 """
740 try:
741 if not self.module.check_mode:
742 self.powerflex_conn.replication_consistency_group.restore(rcg_id)
743 return True
744 except Exception as e:
745 errormsg = f"Restore replication consistency group {rcg_id} failed with error {e}"
746 LOG.error(errormsg)
747 self.module.fail_json(msg=errormsg)
748
749 def switchover(self, rcg_id, force):
750 """Perform switchover
751 :param rcg_id: Unique identifier of the RCG.
752 :param force: Force switchover.
753 :return: Boolean indicates if RCG switchover is successful
754 """
755 try:
756 if not self.module.check_mode:
757 self.powerflex_conn.replication_consistency_group.switchover(rcg_id, force)
758 return True
759 except Exception as e:
760 errormsg = f"Switchover replication consistency group {rcg_id} failed with error {e}"
761 LOG.error(errormsg)
762 self.module.fail_json(msg=errormsg)
763
764 def perform_rcg_action(self, rcg_id, rcg_details):
765 """Perform failover, reverse, restore or switchover
766 :param rcg_id: Unique identifier of the RCG.
767 :param rcg_details: RCG details.
768 :return: Boolean indicates if RCG action is successful
769 """
770 rcg_state = self.module.params['rcg_state']
771 force = self.module.params['force']
772
773 if rcg_state == 'failover' and rcg_details['failoverType'] != 'Failover':
774 return self.failover(rcg_id)
775
776 if rcg_state == 'switchover' and rcg_details['failoverType'] != 'Switchover':
777 return self.switchover(rcg_id, force)
778
779 if rcg_state == 'reverse' and rcg_details['failoverType']:
780 return self.reverse(rcg_id)
781
782 if rcg_state == 'restore' and rcg_details['failoverType'] != 'None':
783 return self.restore(rcg_id)
784
785 def sync(self, rcg_id):
786 """Perform sync
787 :param rcg_id: Unique identifier of the RCG.
788 :return: Boolean indicates if RCG sync is successful
789 """
790 try:
791 if not self.module.check_mode:
792 self.powerflex_conn.replication_consistency_group.sync(rcg_id)
793 return True
794 except Exception as e:
795 errormsg = f"Synchronization of replication consistency group {rcg_id} failed with error {e}"
796 LOG.error(errormsg)
797 self.module.fail_json(msg=errormsg)
798
799 def set_consistency(self, rcg_id, rcg_details, is_consistent):
800 """Set rcg to specified mode
801 :param rcg_id: Unique identifier of the RCG.
802 :param rcg_details: RCG details.
803 :param is_consistent: RCG consistency.
804 :return: Boolean indicates if set consistency is successful
805 """
806 try:
807 if is_consistent and rcg_details['currConsistMode'].lower() not in ('consistent', 'consistentpending'):
808 if not self.module.check_mode:
809 self.powerflex_conn.replication_consistency_group.set_as_consistent(rcg_id)
810 return True
811 elif not is_consistent and rcg_details['currConsistMode'].lower() not in ('inconsistent', 'inconsistentpending'):
812 if not self.module.check_mode:
813 self.powerflex_conn.replication_consistency_group.set_as_inconsistent(rcg_id)
814 return True
815 except Exception as e:
816 errormsg = "Modifying consistency of replication consistency group failed with error {0}".format(str(e))
817 LOG.error(errormsg)
818 self.module.fail_json(msg=errormsg)
819
820 def rename_rcg(self, rcg_id, rcg_details, new_name):
821 """Rename rcg
822 :param rcg_id: Unique identifier of the RCG.
823 :param rcg_details: RCG details
824 :param new_name: RCG name to rename to.
825 :return: Boolean indicates if rename is successful
826 """
827 try:
828 if rcg_details['name'] != new_name:
829 if not self.module.check_mode:
830 self.powerflex_conn.replication_consistency_group.rename_rcg(rcg_id, new_name)
831 return True
832 except Exception as e:
833 errormsg = "Renaming replication consistency group to {0} failed with error {1}".format(new_name, str(e))
834 LOG.error(errormsg)
835 self.module.fail_json(msg=errormsg)
836
837 def delete_rcg(self, rcg_id):
838 """Delete RCG
839 :param rcg_id: Unique identifier of the RCG.
840 :return: Boolean indicates if delete RCG operation is successful
841 """
842 try:
843 if not self.module.check_mode:
844 self.powerflex_conn.replication_consistency_group.delete(
845 rcg_id=rcg_id)
846 return True
847
848 except Exception as e:
849 errormsg = "Delete replication consistency group {0} failed with " \
850 "error {1}".format(rcg_id, str(e))
851 LOG.error(errormsg)
852 self.module.fail_json(msg=errormsg)
853
854 def get_protection_domain(self, conn, protection_domain_name=None, protection_domain_id=None):
855 """
856 Get protection domain details
857 :param conn: local or remote connection
858 :param protection_domain_name: Name of the protection domain
859 :param protection_domain_id: ID of the protection domain
860 :return: Protection domain id if exists
861 :rtype: str
862 """
863 name_or_id = protection_domain_id if protection_domain_id \
864 else protection_domain_name
865 try:
866 pd_details = []
867 if protection_domain_id:
868 pd_details = conn.protection_domain.get(
869 filter_fields={'id': protection_domain_id})
870
871 if protection_domain_name:
872 pd_details = conn.protection_domain.get(
873 filter_fields={'name': protection_domain_name})
874
875 if len(pd_details) == 0:
876 error_msg = "Unable to find the protection domain with " \
877 "'%s'." % name_or_id
878 self.module.fail_json(msg=error_msg)
879
880 return pd_details[0]
881 except Exception as e:
882 error_msg = "Failed to get the protection domain '%s' with " \
883 "error '%s'" % (name_or_id, str(e))
884 LOG.error(error_msg)
885 self.module.fail_json(msg=error_msg)
886
887 def validate_create(self, rcg_params):
888 """Validate create RCG params"""
889 params = ['create_snapshot', 'new_rcg_name']
890 for param in params:
891 if rcg_params[param] is not None:
892 self.module.fail_json(msg="%s cannot be specified while creating replication consistency group" % param)
893 if not rcg_params['rpo']:
894 self.module.fail_json(msg='Enter rpo to create replication consistency group')
895 if not rcg_params['remote_peer']:
896 self.module.fail_json(msg='Enter remote_peer to create replication consistency group')
897 if not rcg_params['protection_domain_id'] and not rcg_params['protection_domain_name']:
898 self.module.fail_json(msg='Enter protection_domain_name or protection_domain_id to create replication consistency group')
899 if (not rcg_params['remote_peer']['protection_domain_id'] and not rcg_params['remote_peer']['protection_domain_name']) or \
900 (rcg_params['remote_peer']['protection_domain_id'] is not None and
901 rcg_params['remote_peer']['protection_domain_name'] is not None):
902 self.module.fail_json(msg='Enter remote protection_domain_name or protection_domain_id to create replication consistency group')
903
904 def get_pause_and_freeze_value(self):
905 """
906 Get Pause and Freeze values
907 :return: Boolean for pause and freeze
908 :rtype: (bool,bool)
909 """
910 rcg_state = self.module.params['rcg_state']
911
912 pause = None
913 freeze = None
914 if rcg_state == 'pause':
915 pause = True
916 if rcg_state == 'resume':
917 pause = False
918 if rcg_state == 'freeze':
919 freeze = True
920 if rcg_state == 'unfreeze':
921 freeze = False
922
923 if self.module.params['pause_mode'] and not pause:
924 self.module.fail_json(msg="Specify rcg_state as 'pause' to pause replication consistency group")
925
926 return pause, freeze
927
928 def modify_rcg(self, rcg_id, rcg_details):
929 rcg_state = self.module.params['rcg_state']
930 create_snapshot = self.module.params['create_snapshot']
931 rpo = self.module.params['rpo']
932 target_volume_access_mode = self.module.params['target_volume_access_mode']
933 is_consistent = self.module.params['is_consistent']
934 activity_mode = self.module.params['activity_mode']
935 new_rcg_name = self.module.params['new_rcg_name']
936
937 pause, freeze = self.get_pause_and_freeze_value()
938
939 changed = self.create_snap(rcg_id, create_snapshot)
940
941 rpo_changed = self.rpo_mod(rcg_id, rcg_details, rpo)
942
943 if target_volume_access_mode and \
944 rcg_details['targetVolumeAccessMode'] != target_volume_access_mode:
945 changed = \
946 self.modify_target_volume_access_mode(
947 rcg_id, target_volume_access_mode)
948 if activity_mode and \
949 self.modify_activity_mode(rcg_id, rcg_details, activity_mode):
950 changed = True
951 rcg_details = self.get_rcg(rcg_id=rcg_details['id'])
952 if pause is not None and \
953 self.pause_or_resume_rcg(rcg_id, rcg_details, pause, self.module.params['pause_mode']):
954 changed = True
955 if freeze is not None and \
956 self.freeze_or_unfreeze_rcg(rcg_id, rcg_details, freeze):
957 changed = True
958 if is_consistent is not None and \
959 self.set_consistency(rcg_id, rcg_details, is_consistent):
960 changed = True
961 if new_rcg_name and self.rename_rcg(rcg_id, rcg_details, new_rcg_name):
962 changed = True
963 if rcg_state == 'sync' and self.sync(rcg_id):
964 changed = True
965
966 rcg_action_status = self.perform_rcg_action(rcg_id, rcg_details)
967
968 return rpo_changed or changed or rcg_action_status
969
970 def rpo_mod(self, rcg_id, rcg_details, rpo):
971 changed = False
972 if rpo and rcg_details['rpoInSeconds'] and \
973 rpo != rcg_details['rpoInSeconds']:
974 changed = self.modify_rpo(rcg_id, rpo)
975 return changed
976
977 def create_snap(self, rcg_id, create_snapshot):
978 changed = False
979 if create_snapshot is True:
980 changed = self.create_rcg_snapshot(rcg_id)
981 return changed
982
983 def validate_input(self, rcg_params):
984 try:
985 api_version = self.powerflex_conn.system.get()[0]['mdmCluster']['master']['versionInfo']
986 if rcg_params['activity_mode'] is not None and utils.is_version_less(
987 utils.parse_version(api_version), '3.6'):
988 self.module.fail_json(msg='activity_mode is supported only from version 3.6 and above')
989 params = ['rcg_name', 'new_rcg_name']
990 for param in params:
991 if rcg_params[param] and utils.is_invalid_name(rcg_params[param]):
992 self.module.fail_json(msg='Enter a valid %s' % param)
993 except Exception as e:
994 error_msg = "Validating input parameters failed with " \
995 "error '%s'" % (str(e))
996 LOG.error(error_msg)
997 self.module.fail_json(msg=error_msg)
998
999 def append_protection_domain_name(self, rcg_details):
1000 try:
1001 # Append protection domain name
1002 if 'protectionDomainId' in rcg_details \
1003 and rcg_details['protectionDomainId']:
1004 pd_details = self.get_protection_domain(
1005 conn=self.powerflex_conn,
1006 protection_domain_id=rcg_details['protectionDomainId'])
1007 rcg_details['protectionDomainName'] = pd_details['name']
1008 except Exception as e:
1009 error_msg = "Updating replication consistency group details with protection domain name failed with " \
1010 "error '%s'" % (str(e))
1011 LOG.error(error_msg)
1012 self.module.fail_json(msg=error_msg)
1013
1014 def perform_module_operation(self):
1015 """
1016 Perform different actions on replication consistency group based on parameters passed in
1017 the playbook
1018 """
1019 self.validate_input(self.module.params)
1020 rcg_name = self.module.params['rcg_name']
1021 new_rcg_name = self.module.params['new_rcg_name']
1022 rcg_id = self.module.params['rcg_id']
1023 state = self.module.params['state']
1024
1025 # result is a dictionary to contain end state and RCG details
1026 changed = False
1027 result = dict(
1028 changed=False,
1029 replication_consistency_group_details=[]
1030 )
1031 # get RCG details
1032 rcg_details = self.get_rcg(rcg_name, rcg_id)
1033 if rcg_details:
1034 result['replication_consistency_group_details'] = rcg_details
1035 rcg_id = rcg_details['id']
1036 msg = "Fetched the RCG details {0}".format(str(rcg_details))
1037 LOG.info(msg)
1038
1039 # perform create
1040 if state == "present":
1041 if not rcg_details:
1042 self.validate_create(self.module.params)
1043 changed, rcg_details = self.create_rcg(self.module.params)
1044 if rcg_details:
1045 rcg_id = rcg_details['id']
1046
1047 if rcg_details and self.modify_rcg(rcg_id, rcg_details):
1048 changed = True
1049
1050 if state == "absent" and rcg_details:
1051 changed = self.delete_rcg(rcg_id=rcg_details['id'])
1052
1053 # Returning the RCG details
1054 if changed:
1055 result['replication_consistency_group_details'] = \
1056 self.get_rcg(new_rcg_name or rcg_name, rcg_id)
1057 result['changed'] = changed
1058 self.module.exit_json(**result)
1059
1060
1061 def get_powerflex_replication_consistency_group_parameters():
1062 """This method provide parameter required for the replication_consistency_group
1063 module on PowerFlex"""
1064 return dict(
1065 rcg_name=dict(), rcg_id=dict(),
1066 create_snapshot=dict(type='bool'),
1067 rpo=dict(type='int'), protection_domain_id=dict(),
1068 protection_domain_name=dict(), new_rcg_name=dict(),
1069 activity_mode=dict(choices=['Active', 'Inactive']),
1070 force=dict(type='bool'),
1071 rcg_state=dict(choices=['failover', 'reverse',
1072 'restore', 'switchover',
1073 'sync', 'pause', 'resume',
1074 'freeze', 'unfreeze']),
1075 pause_mode=dict(choices=['StopDataTransfer', 'OnlyTrackChanges']),
1076 target_volume_access_mode=dict(choices=['ReadOnly', 'NoAccess']),
1077 is_consistent=dict(type='bool'),
1078 remote_peer=dict(type='dict',
1079 options=dict(hostname=dict(type='str', aliases=['gateway_host'], required=True),
1080 username=dict(type='str', required=True),
1081 password=dict(type='str', required=True, no_log=True),
1082 validate_certs=dict(type='bool', aliases=['verifycert'], default=True),
1083 port=dict(type='int', default=443),
1084 timeout=dict(type='int', default=120),
1085 protection_domain_id=dict(),
1086 protection_domain_name=dict())),
1087 state=dict(default='present', type='str', choices=['present', 'absent'])
1088 )
1089
1090
1091 def main():
1092 """ Create PowerFlex Replication Consistency Group object and perform actions on it
1093 based on user input from playbook"""
1094 obj = PowerFlexReplicationConsistencyGroup()
1095 obj.perform_module_operation()
1096
1097
1098 if __name__ == '__main__':
1099 main()