Debian Codegraph @

ansible_collections/ibm/storage_virtualize/plugins/modules/ibm_svc_manage_replication.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (C) 2020 IBM CORPORATION
5 # Author(s): Rohit Kumar <[email protected]>
6 # Shilpi Jain <[email protected]>
7 #
8 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9
10 from __future__ import absolute_import, division, print_function
11 __metaclass__ = type
12
13 DOCUMENTATION = '''
14 ---
15 module: ibm_svc_manage_replication
16 short_description: This module manages remote copies (or rcrelationship) on
17 IBM Storage Virtualize family systems
18 version_added: "1.3.0"
19
20 description:
21 - Ansible interface to manage remote copy replication.
22
23 options:
24 name:
25 description:
26 - Specifies the name to assign to the new remote copy relationship or to operate on the existing remote copy.
27 type: str
28 state:
29 description:
30 - Creates or updates (C(present)), removes (C(absent)) a
31 remote copy relationship.
32 choices: [absent, present]
33 required: true
34 type: str
35 clustername:
36 description:
37 - The hostname or management IP of the Storage Virtualize system.
38 type: str
39 required: true
40 domain:
41 description:
42 - Domain for the Storage Virtualize system.
43 - Valid when hostname is used for the parameter I(clustername).
44 type: str
45 username:
46 description:
47 - REST API username for the Storage Virtualize system.
48 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
49 type: str
50 password:
51 description:
52 - REST API password for the Storage Virtualize system.
53 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
54 type: str
55 token:
56 description:
57 - The authentication token to verify a user on the Storage Virtualize system.
58 - To generate a token, use the ibm_svc_auth module.
59 type: str
60 version_added: '1.5.0'
61 copytype:
62 description:
63 - Specifies the mirror type of the remote copy. 'metro' means MetroMirror,
64 'global' means GlobalMirror, and 'GMCV' means GlobalMirror with change volume.
65 - If not specified, a MetroMirror remote copy will be created when creating a remote copy I(state=present).
66 type: str
67 choices: [ 'metro', 'global' , 'GMCV']
68 master:
69 description:
70 - Specifies the master volume name when creating a remote copy.
71 type: str
72 aux:
73 description:
74 - Specifies the auxiliary volume name when creating a remote copy.
75 type: str
76 cyclingperiod:
77 description:
78 - Specifies the cycle period in seconds. The default cycle is of 300 seconds.
79 type: int
80 remotecluster:
81 description:
82 - Specifies the name of remote cluster when creating a remote copy.
83 type: str
84 sync:
85 description:
86 - Specifies whether to create a synchronized relationship.
87 default: false
88 type: bool
89 force:
90 description:
91 - Specifies that the relationship must be deleted even if it results in the secondary volume containing inconsistent data.
92 type: bool
93 consistgrp:
94 description:
95 - Specifies a consistency group that this relationship will join. If not specified by user, the relationship is created as a stand-alone relationship.
96 - Applies when I(state=present).
97 type: str
98 noconsistgrp:
99 description:
100 - Specifies whether to remove the specified relationship from a consistency
101 group, making the relationship a stand-alone relationship.
102 - Applies when I(state=present).
103 default: false
104 type: bool
105 validate_certs:
106 description:
107 - Validates certification.
108 default: false
109 type: bool
110 log_path:
111 description:
112 - Path of debug log file.
113 type: str
114 notes:
115 - The parameters I(primary) and I(aux) are mandatory only when a remote copy relationship does not exist.
116 - This module supports C(check_mode).
117 - Parameters copytype, cyclingperiod are not supported for update operation when the relationship is a part of consistency group.
118 In case these parameters are specified, Ansible will return the following error,
119 "CMMVC5951E Individual relationship cannot be updated while it is part of a consistency group."
120 - Only one update operation is supported in a single task for remote copy relationships, if multiple are detected, Ansible will return the following error,
121 "CMMVC5713E Only 1 update operation supported in one task"
122 author:
123 - rohit(@rohitk-github)
124 - Shilpi Jain (@Shilpi-Jain1)
125 '''
126
127 EXAMPLES = '''
128 - name: Create remote copy
129 ibm.storage_virtualize.ibm_svc_manage_replication:
130 name: sample_rcopy
131 clustername: "{{ clustername }}"
132 username: "{{ username }}"
133 password: "{{ password }}"
134 log_path: /tmp/ansible.log
135 state: present
136 remotecluster: "{{ remotecluster }}"
137 master: SourceVolume0
138 aux: TargetVolume0
139 copytype: global
140 sync: true
141 consistgrp: sample_rccg
142 register: result
143 - name: Exclude the remote copy from consistency group
144 ibm.storage_virtualize.ibm_svc_manage_replication:
145 name: sample_rcopy2
146 clustername: "{{ clustername }}"
147 username: "{{ username }}"
148 password: "{{ password }}"
149 log_path: /tmp/ansible.log
150 state: present
151 noconsistgrp: true
152 - name: Delete remote copy
153 ibm.storage_virtualize.ibm_svc_manage_replication:
154 name: sample_rcopy3
155 clustername: "{{ clustername }}"
156 username: "{{ username }}"
157 password: "{{ password }}"
158 log_path: /tmp/ansible.log
159 state: absent
160 - name: Create GlobalMirror remote copy relationship with change volume
161 ibm.storage_virtualize.ibm_svc_manage_replication:
162 name: sample_rcopy4
163 clustername: "{{ clustername }}"
164 username: "{{ username }}"
165 password: "{{ password }}"
166 log_path: /tmp/ansible.log
167 state: present
168 remotecluster: "{{ remotecluster }}"
169 master: SourceVolume1
170 aux: TargetVolume1
171 copytype: GMCV
172 sync: true
173 register: result
174 '''
175
176 RETURN = '''#'''
177
178
179 from ansible.module_utils._text import to_native
180 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import IBMSVCRestApi, svc_argument_spec, get_logger
181 from ansible.module_utils.basic import AnsibleModule
182 from traceback import format_exc
183
184
185 class IBMSVCManageReplication(object):
186 def __init__(self):
187 argument_spec = svc_argument_spec()
188
189 argument_spec.update(
190 dict(
191 name=dict(type='str'),
192 state=dict(type='str',
193 required=True,
194 choices=['present', 'absent']),
195 remotecluster=dict(type='str'),
196 copytype=dict(type='str', choices=['metro', 'global', 'GMCV']),
197 master=dict(type='str'),
198 aux=dict(type='str'),
199 force=dict(type='bool', required=False),
200 consistgrp=dict(type='str'),
201 noconsistgrp=dict(type='bool', default=False),
202 sync=dict(type='bool', default=False),
203 cyclingperiod=dict(type='int')
204 )
205 )
206
207 self.module = AnsibleModule(argument_spec=argument_spec,
208 supports_check_mode=True)
209
210 # logging setup
211 log_path = self.module.params['log_path']
212 log = get_logger(self.__class__.__name__, log_path)
213 self.log = log.info
214
215 # Required
216 self.name = self.module.params['name']
217 self.state = self.module.params['state']
218 self.remotecluster = self.module.params['remotecluster']
219
220 # Optional
221 self.consistgrp = self.module.params.get('consistgrp', None)
222 self.aux = self.module.params.get('aux')
223 self.master = self.module.params.get('master')
224 self.sync = self.module.params.get('sync', False)
225 self.noconsistgrp = self.module.params.get('noconsistgrp', False)
226 self.copytype = self.module.params.get('copytype', None)
227 self.force = self.module.params.get('force', False)
228 self.cyclingperiod = self.module.params.get('cyclingperiod')
229
230 # Handling missing mandatory parameter name
231 if not self.name:
232 self.module.fail_json(msg='Missing mandatory parameter: name')
233
234 if self.consistgrp and self.noconsistgrp:
235 self.module.fail_json(msg='Mutually exclusive parameters: consistgrp and noconsistgrp')
236
237 self.restapi = IBMSVCRestApi(
238 module=self.module,
239 clustername=self.module.params['clustername'],
240 domain=self.module.params['domain'],
241 username=self.module.params['username'],
242 password=self.module.params['password'],
243 validate_certs=self.module.params['validate_certs'],
244 log_path=log_path,
245 token=self.module.params['token']
246 )
247
248 def existing_vdisk(self, volname):
249 merged_result = {}
250
251 data = self.restapi.svc_obj_info(cmd='lsvdisk', cmdopts={'bytes': True},
252 cmdargs=[volname])
253
254 if not data:
255 self.log("source volume %s does not exist", volname)
256 return
257 if isinstance(data, list):
258 for d in data:
259 merged_result.update(d)
260 else:
261 merged_result = data
262
263 return merged_result
264
265 def cycleperiod_update(self):
266 """
267 Use the chrcrelationship command to update cycling period in remote copy
268 relationship.
269 """
270 if self.module.check_mode:
271 self.changed = True
272 return
273
274 if (self.copytype == 'GMCV') and (self.cyclingperiod):
275 cmd = 'chrcrelationship'
276 cmdopts = {}
277 cmdopts['cycleperiodseconds'] = self.cyclingperiod
278 cmdargs = [self.name]
279
280 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
281 else:
282 self.log("not updating chrcrelationship with cyclingperiod %s", self.cyclingperiod)
283
284 def cyclemode_update(self):
285 """
286 Use the chrcrelationship command to update cycling mode in remote copy
287 relationship.
288 """
289 if self.module.check_mode:
290 self.changed = True
291 return
292
293 cmd = 'chrcrelationship'
294 cmdopts = {}
295 cmdargs = [self.name]
296
297 if self.copytype == 'GMCV':
298 self.log("updating chrcrelationship with cyclingmode multi")
299 cmdopts['cyclingmode'] = 'multi'
300 else:
301 self.log("updating chrcrelationship with no cyclingmode")
302 cmdopts['cyclingmode'] = 'none'
303
304 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
305
306 def existing_rc(self):
307 """
308 find the remote copy relationships such as Metro Mirror, Global Mirror
309 relationships visible to the system.
310
311 Returns:
312 None if no matching instances or a list including all the matching
313 instances
314 """
315 self.log('Trying to get the remote copy relationship %s', self.name)
316 data = self.restapi.svc_obj_info(cmd='lsrcrelationship',
317 cmdopts=None, cmdargs=[self.name])
318
319 return data
320
321 def rcrelationship_probe(self, data):
322 props = {}
323 propscv = {}
324 relationship_in_cg_error = "CMMVC5951E Individual relationship cannot be updated while it is part of a consistency group."
325 if data['consistency_group_name']:
326 if self.cyclingperiod and self.cyclingperiod != data['cycle_period_seconds']:
327 self.module.fail_json(msg=relationship_in_cg_error)
328 if self.copytype:
329 if self.copytype == 'GMCV':
330 if (data['copy_type'] != 'global' or data['cycling_mode'] != 'multi'):
331 self.module.fail_json(msg=(relationship_in_cg_error))
332 elif self.copytype == 'global':
333 if (data['copy_type'] != 'global' or data['cycling_mode'] != 'none'):
334 self.module.fail_json(msg=relationship_in_cg_error)
335 elif self.copytype and self.copytype != data['copy_type']:
336 self.module.fail_json(msg=relationship_in_cg_error)
337 if self.master is not None and self.master != data['master_vdisk_name']:
338 self.module.fail_json(msg="Parameter not supported for update operation: master")
339 if self.aux is not None and self.aux != data['aux_vdisk_name']:
340 self.module.fail_json(msg="Parameter not supported for update operation: aux")
341 if data['consistency_group_name'] and self.noconsistgrp:
342 props['noconsistgrp'] = self.noconsistgrp
343 if self.consistgrp is not None and self.consistgrp != data['consistency_group_name']:
344 props['consistgrp'] = self.consistgrp
345 if self.copytype == 'global' and data['copy_type'] == 'metro':
346 props['global'] = True
347
348 if (self.copytype == 'metro' or self.copytype is None) and (data['copy_type'] == 'global' and data['cycling_mode'] == 'multi'):
349 self.module.fail_json(msg="Changing relationship type from GMCV to metro is not allowed")
350 elif (self.copytype == 'metro' or self.copytype is None) and data['copy_type'] == 'global':
351 props['metro'] = True
352
353 if self.copytype == 'GMCV' and data['copy_type'] == 'global':
354 if data['cycling_mode'] != 'multi':
355 propscv['cyclingmode'] = 'multi'
356 if self.cyclingperiod is not None and self.cyclingperiod != int(data['cycle_period_seconds']):
357 propscv['cycleperiodseconds'] = self.cyclingperiod
358 if self.copytype == 'global' and (data['copy_type'] == 'global' and data['cycling_mode'] == 'multi'):
359 propscv['cyclingmode'] = 'none'
360 if self.copytype == 'GMCV' and data['copy_type'] == 'metro':
361 self.module.fail_json(msg="Changing relationship type from metro to GMCV is not allowed")
362 if self.copytype != 'metro' and self.copytype != 'global' and self.copytype != 'GMCV' and self.copytype is not None:
363 self.module.fail_json(msg="Unsupported mirror type: %s. Only 'global', 'metro' and 'GMCV' are supported when modifying" % self.copytype)
364 if len(props) > 1:
365 self.module.fail_json(msg=f"CMMVC5713E Only 1 update operation supported in one task, {len(props)} operations detected: {props}")
366 return props, propscv
367
368 def rcrelationship_update(self, modify, modifycv):
369 """
370 Use the chrcrelationship command to modify certain attributes of an
371 existing relationship, such as to add a relationship to a consistency
372 group to remove a relationship from a consistency group.
373 You can change one attribute at a time.
374 """
375 if self.module.check_mode:
376 self.changed = True
377 return
378
379 if modify:
380 self.log("updating chrcrelationship with properties %s", modify)
381 cmd = 'chrcrelationship'
382 cmdopts = {}
383 for prop in modify:
384 cmdopts[prop] = modify[prop]
385 cmdargs = [self.name]
386
387 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
388
389 # Error(if any) will be raised in svc_run_command
390 self.changed = True
391 if modifycv:
392 if 'cycleperiodseconds' in modifycv:
393 self.cycleperiod_update()
394 self.log("cyclingperiod in change volume updated")
395 if 'cyclingmode' in modifycv:
396 self.cyclemode_update()
397 self.log("cyclingmode in change volume updated")
398 # Error(if any) will be raised in svc_run_command
399 self.changed = True
400 if not modify and not modifycv:
401 self.log("There is no property need to be updated")
402 self.changed = False
403
404 def create(self):
405 """
406 Specify the mkrcrelationship command to create a new Global Mirror,
407 Metro Mirror in the same system, forming an intrasystem Metro Mirror
408 relationship or intersystem
409 relationship (if it involves more than one system).
410
411 Returns:
412 a remote copy instance
413 """
414 if not self.name:
415 self.module.fail_json(msg="You must pass in name to the module.")
416 if not self.master:
417 self.module.fail_json(msg="You must pass in master to the module.")
418 if not self.aux:
419 self.module.fail_json(msg="You must pass in aux to the module.")
420 if not self.remotecluster:
421 self.module.fail_json(msg="You must pass in remotecluster to the module.")
422
423 if self.module.check_mode:
424 self.changed = True
425 return
426
427 self.log("Creating remote copy '%s'", self.name)
428
429 # Make command
430 cmd = 'mkrcrelationship'
431 cmdopts = {}
432 if self.remotecluster:
433 cmdopts['cluster'] = self.remotecluster
434 if self.master:
435 cmdopts['master'] = self.master
436 if self.aux:
437 cmdopts['aux'] = self.aux
438 if self.name:
439 cmdopts['name'] = self.name
440
441 if self.copytype:
442 if self.copytype == 'global' or self.copytype == 'GMCV':
443 cmdopts['global'] = True
444 if self.copytype == 'GMCV':
445 cmdopts['cyclingmode'] = 'multi'
446 elif self.copytype == 'metro' or self.copytype == 'blank':
447 pass
448 else:
449 msg = "Invalid parameter specified as the Copy Type(%s) when creating Remotecopy" % self.copytype
450 self.module.fail_json(msg=msg)
451
452 if self.copytype != 'GMCV' and self.cyclingperiod is not None:
453 msg = "Provided copytype is %s. Copy Type must be GMCV when creating Remotecopy relationship with change volumes and cycling period" % self.copytype
454 self.module.fail_json(msg=msg)
455
456 if self.consistgrp:
457 cmdopts['consistgrp'] = self.consistgrp
458 if self.sync:
459 cmdopts['sync'] = self.sync
460
461 # Run command
462 self.log("Command %s opts %s", cmd, cmdopts)
463 result = self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
464 self.log("create remote copy result %s", result)
465
466 if 'message' in result:
467 self.changed = True
468 data = self.existing_rc()
469 self.log("Succeeded to create remote copy result message %s",
470 result['message'])
471 return data
472 else:
473 msg = "Failed to create remote copy [%s]" % self.name
474 self.module.fail_json(msg=msg)
475
476 def delete(self):
477 """
478 Use the rmrcrelationship command to delete an existing remote copy
479 relationship.
480 """
481 if self.module.check_mode:
482 self.changed = True
483 return
484
485 cmd = 'rmrcrelationship'
486 cmdopts = {}
487 if self.force:
488 cmdopts['force'] = self.force
489 cmdargs = [self.name]
490
491 result = self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
492
493 # Any error will have been raised in svc_run_command
494 # Command does not output anything when successful.
495 if result == '':
496 self.changed = True
497 self.log("succeeded to delete the remote copy %s", self.name)
498 elif 'message' in result:
499 self.changed = True
500 self.log("delete the remote copy %s with result message %s",
501 self.name, result['message'])
502 else:
503 self.module.fail_json(
504 msg="Failed to delete the remote copy [%s]" % self.name)
505
506 def apply(self):
507 changed = False
508 msg = None
509 modify = {}
510 modifycv = {}
511 rcrelationship_data = self.existing_rc()
512 if rcrelationship_data:
513 if self.state == 'absent':
514 self.log(
515 "CHANGED: RemoteCopy relationship exists, requested state is 'absent'")
516 changed = True
517 elif self.state == 'present':
518 modify, modifycv = self.rcrelationship_probe(rcrelationship_data)
519 if modify or modifycv:
520 changed = True
521 else:
522 if self.state == 'present':
523 changed = True
524 self.log(
525 "CHANGED: Remotecopy relationship does not exist, but requested state is '%s'", self.state)
526
527 if changed:
528 if self.state == 'present':
529 if not rcrelationship_data:
530 self.create()
531 if self.copytype == 'GMCV' and self.consistgrp is None:
532 self.cycleperiod_update()
533 self.cyclemode_update()
534 msg = "remote copy relationship with change volume %s has been created." % self.name
535 else:
536 msg = "remote copy relationship %s has been created." % self.name
537 else:
538 self.rcrelationship_update(modify, modifycv)
539 msg = "remote copy relationship [%s] has been modified." % self.name
540 elif self.state == 'absent':
541 self.delete()
542 msg = "remote copy relationship [%s] has been deleted." % self.name
543
544 if self.module.check_mode:
545 msg = 'skipping changes due to check mode.'
546 else:
547 self.log("exiting with no changes")
548 if self.state in ['absent']:
549 msg = "Remotecopy relationship [%s] does not exist." % self.name
550 else:
551 msg = "No Modifications detected, Remotecopy relationship [%s] already exists." % self.name
552
553 self.module.exit_json(msg=msg, changed=changed)
554
555
556 def main():
557 v = IBMSVCManageReplication()
558 try:
559 v.apply()
560 except Exception as e:
561 v.log("Exception in apply(): \n%s", format_exc())
562 v.module.fail_json(msg="Module failed. Error [%s]." % to_native(e))
563
564
565 if __name__ == '__main__':
566 main()