Debian Codegraph @

ansible_collections/ibm/storage_virtualize/plugins/modules/ibm_svc_manage_replicationgroup.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 #
7 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9 from __future__ import absolute_import, division, print_function
10
11 __metaclass__ = type
12
13 DOCUMENTATION = '''
14 ---
15 module: ibm_svc_manage_replicationgroup
16 short_description: This module manages remote copy consistency group on
17 IBM Storage Virtualize family systems
18 version_added: "1.3.0"
19 description:
20 - Ansible interface to manage 'mkrcconsistgrp', 'chrcconsistgrp', and 'rmrcconsistgrp'
21 remote copy consistency group commands.
22 options:
23 name:
24 description:
25 - Specifies the name for the new consistency group.
26 required: true
27 type: str
28 state:
29 description:
30 - Creates or updates (C(present)) removes (C(absent))
31 a consistency group.
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 log_path:
62 description:
63 - Path of debug log file.
64 type: str
65 validate_certs:
66 description:
67 - Validates certification.
68 default: false
69 type: bool
70 remotecluster:
71 description:
72 - Specifies the name of the remote system.
73 Only used while creating a consistency group.
74 type: str
75 force:
76 description:
77 - If used to delete a consistency group,
78 it specifies that you want the system to remove any
79 relationship that belongs to the consistency
80 group before the group is deleted.
81 - If used to start a consistency group,
82 it specifies that you want the system to process the
83 copy operation even if it causes a temporary loss of
84 consistency during synchronization.
85 - It is required if the consistency group is in the ConsistentStopped
86 state, but is not synchronized or is in the idling state -
87 except if consistency protection is configured.
88 type: bool
89 copytype:
90 description:
91 - Specifies the mirror type of the remote copy. 'metro' means MetroMirror, 'global' means GlobalMirror.
92 - If not specified, a MetroMirror remote copy will be created when creating a remote copy I(state=present).
93 type: str
94 choices: [ 'metro', 'global' ]
95 cyclingmode:
96 description:
97 - Specifies the behavior of Global Mirror for the relationship.
98 - Active-active relationships and relationships with cycling modes set to Multiple must always be configured with change volumes.
99 - Applies when I(state=present) and I(copytype=global).
100 type: str
101 choices: [ 'multi', 'none' ]
102 cyclingperiod:
103 description:
104 - Specifies the cycle period in seconds.
105 type: int
106 author:
107 - rohit(@rohitk-github)
108 notes:
109 - This module supports C(check_mode).
110 '''
111
112 EXAMPLES = '''
113 - name: Define a new rc consistency group
114 ibm.storage_virtualize.ibm_svc_manage_replicationgroup:
115 clustername: "{{ clustername }}"
116 domain: "{{ domain }}"
117 username: "{{ username }}"
118 password: "{{ password }}"
119 log_path: /tmp/playbook.debug
120 name: rccg4test
121 remotecluster: remotecluster
122 state: present
123 - name: Delete rc consistency group
124 ibm.storage_virtualize.ibm_svc_manage_replicationgroup:
125 clustername: "{{ clustername }}"
126 domain: "{{ domain }}"
127 username: "{{ username }}"
128 password: "{{ password }}"
129 log_path: /tmp/playbook.debug
130 name: rccg4test
131 force: true
132 state: absent
133 - name: Update rc consistency group
134 ibm.storage_virtualize.ibm_svc_manage_replicationgroup:
135 clustername: "{{ clustername }}"
136 domain: "{{ domain }}"
137 username: "{{ username }}"
138 password: "{{ password }}"
139 log_path: /tmp/playbook.debug
140 name: rccg4test
141 cyclingperiod: 60
142 state: present
143 '''
144
145 RETURN = '''#'''
146
147 from traceback import format_exc
148 from ansible.module_utils.basic import AnsibleModule
149 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import \
150 IBMSVCRestApi, svc_argument_spec, get_logger
151 from ansible.module_utils._text import to_native
152
153
154 class IBMSVCRCCG(object):
155 def __init__(self):
156 argument_spec = svc_argument_spec()
157
158 argument_spec.update(
159 dict(
160 name=dict(type='str', required=True),
161 state=dict(type='str', required=True, choices=['absent',
162 'present']),
163 remotecluster=dict(type='str', required=False),
164 force=dict(type='bool', required=False),
165 copytype=dict(type='str', choices=['metro', 'global']),
166 cyclingmode=dict(type='str', required=False, choices=['multi', 'none']),
167 cyclingperiod=dict(type='int', required=False)
168 )
169 )
170
171 self.module = AnsibleModule(argument_spec=argument_spec,
172 supports_check_mode=True)
173
174 # logging setup
175 log_path = self.module.params['log_path']
176 log = get_logger(self.__class__.__name__, log_path)
177 self.log = log.info
178
179 # Required
180 self.name = self.module.params['name']
181 self.state = self.module.params['state']
182
183 # Optional
184 self.cluster = self.module.params.get('remotecluster', None)
185 self.force = self.module.params.get('force', False)
186 self.copytype = self.module.params.get('copytype', None)
187 self.cyclingmode = self.module.params.get('cyclingmode', None)
188 self.cyclingperiod = self.module.params.get('cyclingperiod', None)
189
190 # Handling missing mandatory paratmeter name
191 if not self.name:
192 self.module.fail_json(msg='Missing mandatory parameter: name')
193
194 self.restapi = IBMSVCRestApi(
195 module=self.module,
196 clustername=self.module.params['clustername'],
197 domain=self.module.params['domain'],
198 username=self.module.params['username'],
199 password=self.module.params['password'],
200 validate_certs=self.module.params['validate_certs'],
201 log_path=log_path,
202 token=self.module.params['token']
203 )
204
205 def get_existing_rccg(self):
206 merged_result = {}
207
208 data = self.restapi.svc_obj_info(cmd='lsrcconsistgrp', cmdopts=None,
209 cmdargs=[self.name])
210
211 if isinstance(data, list):
212 for d in data:
213 merged_result.update(d)
214 else:
215 merged_result = data
216
217 return merged_result
218
219 def rccg_probe(self, data):
220 props = {}
221 propscv = {}
222 if self.copytype and self.copytype != data['copy_type']:
223 if self.copytype == 'global':
224 props['global'] = True
225 elif self.copytype == 'metro':
226 props['metro'] = True
227 else:
228 self.module.fail_json(msg="Unsupported mirror type: %s. Only 'global' and 'metro' are supported when modifying" % self.copytype)
229
230 if self.copytype == 'global' and self.cyclingperiod and self.cyclingperiod != int(data['cycle_period_seconds']):
231 propscv['cycleperiodseconds'] = self.cyclingperiod
232 if self.copytype == 'global' and self.cyclingmode and self.cyclingmode != data['cycling_mode']:
233 propscv['cyclingmode'] = self.cyclingmode
234
235 return props, propscv
236
237 def rccg_create(self):
238 if self.module.check_mode:
239 self.changed = True
240 return
241
242 rccg_data = self.get_existing_rccg()
243 if rccg_data:
244 self.rccg_update(rccg_data)
245 self.log("creating rc consistgrp '%s'", self.name)
246
247 # Make command
248 cmd = 'mkrcconsistgrp'
249 cmdopts = {'name': self.name}
250 if self.cluster:
251 cmdopts['cluster'] = self.cluster
252
253 self.log("creating rc consistgrp command '%s' opts", self.cluster)
254
255 # Run command
256 result = self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
257 self.log("create rc consistgrp result '%s'", result)
258 msg = "succeeded to create rc consistgrp '%s'" % self.name
259 self.log(msg)
260
261 if 'message' in result:
262 self.log("create rc consistgrp result message '%s'",
263 result['message'])
264 self.module.exit_json(msg="rc consistgrp '%s' is created" %
265 self.name, changed=True)
266
267 else:
268 self.module.fail_json(msg=result)
269
270 def rccg_update(self, modify, modifycv):
271
272 if modify:
273 self.log("updating chrcconsistgrp with properties %s", modify)
274 cmd = 'chrcconsistgrp'
275 cmdopts = {}
276 for prop in modify:
277 cmdopts[prop] = modify[prop]
278 cmdargs = [self.name]
279
280 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
281
282 # Any error would have been raised in svc_run_command
283 # chrcconsistgrp does not output anything when successful.
284 self.changed = True
285 if modifycv:
286 self.log("updating chrcconsistgrp with properties %s", modifycv)
287 cmd = 'chrcconsistgrp'
288 cmdargs = [self.name]
289 for prop in modifycv:
290 cmdopts = {}
291 cmdopts[prop] = modifycv[prop]
292 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
293
294 # Any error would have been raised in svc_run_command
295 # chrcconsistgrp does not output anything when successful.
296 self.changed = True
297 if not modify and not modifycv:
298 self.log("There is no property to be updated")
299 self.changed = False
300
301 def rccg_delete(self):
302 if self.module.check_mode:
303 self.changed = True
304 return
305
306 self.log("deleting rc consistgrp '%s'", self.name)
307
308 cmd = 'rmrcconsistgrp'
309 cmdopts = {'force': True} if self.force else None
310 cmdargs = [self.name]
311
312 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
313
314 # Any error will have been raised in svc_run_command
315 # rmrcconsistgrp does not output anything when successful.
316 msg = "rc consistgrp '%s' is deleted" % self.name
317 self.log(msg)
318 self.module.exit_json(msg=msg, changed=True)
319
320 def apply(self):
321 changed = False
322 msg = None
323 modify = {}
324 rccg_data = self.get_existing_rccg()
325 if rccg_data:
326 if self.state == 'absent':
327 self.log(
328 "CHANGED: RemoteCopy group exists, requested state is 'absent'")
329 changed = True
330 elif self.state == 'present':
331 modify, modifycv = self.rccg_probe(rccg_data)
332 if modify or modifycv:
333 changed = True
334 else:
335 if self.state == 'present':
336 if self.copytype:
337 self.module.fail_json(msg="copytype cannot be passed while creating a consistency group")
338 changed = True
339 self.log(
340 "CHANGED: Remotecopy group does not exist, but requested state is '%s'", self.state)
341 if changed:
342 if self.state == 'present':
343 if not rccg_data:
344 self.rccg_create()
345 msg = "remote copy group %s has been created." % self.name
346 else:
347 self.rccg_update(modify, modifycv)
348 msg = "remote copy group [%s] has been modified." % self.name
349 elif self.state == 'absent':
350 self.rccg_delete()
351 msg = "remote copy group [%s] has been deleted." % self.name
352
353 if self.module.check_mode:
354 msg = 'skipping changes due to check mode.'
355 else:
356 self.log("exiting with no changes")
357 if self.state in ['absent']:
358 msg = "Remotecopy group [%s] does not exist." % self.name
359 else:
360 msg = "No Modifications detected, Remotecopy group [%s] already exists." % self.name
361
362 self.module.exit_json(msg=msg, changed=changed)
363
364
365 def main():
366 v = IBMSVCRCCG()
367 try:
368 v.apply()
369 except Exception as e:
370 v.log("Exception in apply(): \n%s", format_exc())
371 v.module.fail_json(msg="Module failed. Error [%s]." % to_native(e))
372
373
374 if __name__ == '__main__':
375 main()