Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (C) 2021 IBM CORPORATION
5 # Author(s): Sreshtant Bohidar <[email protected]>
6 # Lavanya C R <[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_flashcopy
16 short_description: This module manages FlashCopy mappings on IBM Storage Virtualize
17 family systems
18 description:
19 - Ansible interface to manage 'mkfcmap', 'rmfcmap', and 'chfcmap' volume commands.
20 This module configures "clone", "snapshot" or "backup" type FlashCopy mappings.
21 version_added: "1.4.0"
22 options:
23 name:
24 description:
25 - Specifies the name of the FlashCopy mapping.
26 required: true
27 type: str
28 state:
29 description:
30 - Creates or updates (C(present)) or removes (C(absent)) a FlashCopy mapping.
31 choices: [ present, absent ]
32 required: true
33 type: str
34 clustername:
35 description:
36 - The hostname or management IP of the Storage Virtualize system.
37 type: str
38 required: true
39 domain:
40 description:
41 - Domain for the Storage Virtualize system.
42 - Valid when hostname is used for the parameter I(clustername).
43 type: str
44 username:
45 description:
46 - REST API username for the Storage Virtualize system.
47 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
48 type: str
49 password:
50 description:
51 - REST API password for the Storage Virtualize system.
52 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
53 type: str
54 token:
55 description:
56 - The authentication token to verify a user on the Storage Virtualize system.
57 - To generate a token, use the ibm_svc_auth module.
58 type: str
59 version_added: '1.5.0'
60 copytype:
61 description:
62 - Specifies the copy type when creating the FlashCopy mapping.
63 - Required when I(state=present), to create a FlashCopy mapping.
64 choices: [ snapshot, clone, backup ]
65 type: str
66 source:
67 description:
68 - Specifies the name/UID of the source volume.
69 - Required when I(state=present), to create a FlashCopy mapping.
70 type: str
71 target:
72 description:
73 - Specifies the name/UID of the target volume.
74 - Required when I(state=present), to create a FlashCopy mapping.
75 type: str
76 mdiskgrp:
77 description:
78 - Specifies the name of the storage pool to use when creating the target volume.
79 - If unspecified, the pool associated with the source volume is used.
80 - Valid when I(state=present), to create a FlashCopy mapping.
81 type: str
82 consistgrp:
83 description:
84 - Specifies the name of the consistency group to which the FlashCopy mapping is to be added.
85 - Parameters I(consistgrp) and I(noconsistgrp) are mutually exclusive.
86 - Valid when I(state=present), to create or modify a FlashCopy mapping.
87 type: str
88 noconsistgrp:
89 description:
90 - If specified True, FlashCopy mapping is removed from the consistency group.
91 - Parameters I(noconsistgrp) and I(consistgrp) are mutually exclusive.
92 - Valid when I(state=present), to modify a FlashCopy mapping.
93 type: bool
94 copyrate:
95 description:
96 - Specifies the copy rate. The rate varies between 0-150.
97 - If unspecified, the default copy rate of 50 for clone and 0 for snapshot is used.
98 - Valid when I(state=present), to create or modify a FlashCopy mapping.
99 type: int
100 cleanrate:
101 description:
102 - Specifies the clean rate. The rate varies between 0-150.
103 - If unspecified, the default clean rate is 50.
104 - Valid when I(state=present), to create or modify a FlashCopy mapping.
105 type: int
106 version_added: 2.7.0
107 grainsize:
108 description:
109 - Specifies the grain size for the FlashCopy mapping.
110 - The grainsize can be set to 64 or 256. The default value is 256.
111 - Valid when I(state=present), to create a FlashCopy mapping.
112 type: str
113 force:
114 description:
115 - Brings the target volume online. This parameter is required if the FlashCopy mapping is in the stopped state.
116 - Valid when I(state=absent), to delete a FlashCopy mapping.
117 type: bool
118 old_name:
119 description:
120 - Specifies the old name of an mdiskgrp.
121 - Applies when I(state=present), to rename the existing mdiskgrp.
122 type: str
123 validate_certs:
124 description:
125 - Validates certification.
126 default: false
127 type: bool
128 log_path:
129 description:
130 - Path of debug log file.
131 type: str
132 author:
133 - Sreshtant Bohidar(@Sreshtant-Bohidar)
134 - Lavanya C R(@lavanyacr)
135 notes:
136 - This module supports C(check_mode).
137 '''
138
139 EXAMPLES = '''
140 - name: Create FlashCopy mapping for snapshot
141 ibm.storage_virtualize.ibm_svc_manage_flashcopy:
142 clustername: "{{ clustername }}"
143 domain: "{{ domain }}"
144 username: "{{ username }}"
145 password: "{{ password }}"
146 log_path: /tmp/playbook.debug
147 state: present
148 name: snapshot-name
149 copytype: snapshot
150 source: source-volume-name
151 target: target-volume-name
152 mdiskgrp: Pool0
153 consistgrp: consistencygroup-name
154 copyrate: 50
155 cleanrate: 60
156 grainsize: 64
157 - name: Update FlashCopy mapping
158 ibm.storage_virtualize.ibm_svc_manage_flashcopy:
159 clustername: "{{ clustername }}"
160 domain: "{{ domain }}"
161 username: "{{ username }}"
162 password: "{{ password }}"
163 log_path: /tmp/playbook.debug
164 state: present
165 name: snapshot-name
166 consistgrp: consistencygroup-name
167 copyrate: 50
168 cleanrate: 60
169 - name: Create FlashCopy mapping for clone
170 ibm.storage_virtualize.ibm_svc_manage_flashcopy:
171 clustername: "{{ clustername }}"
172 domain: "{{ domain }}"
173 username: "{{ username }}"
174 password: "{{ password }}"
175 log_path: /tmp/playbook.debug
176 state: present
177 name: snapshot-name
178 copytype: clone
179 source: source-volume-name
180 target: target-volume-name
181 mdiskgrp: Pool0
182 consistgrp: consistencygroup-name
183 copyrate: 50
184 grainsize: 64
185 - name: Create FlashCopy mapping for backup
186 ibm.storage_virtualize.ibm_svc_manage_flashcopy:
187 clustername: "{{ clustername }}"
188 domain: "{{ domain }}"
189 username: "{{ username }}"
190 password: "{{ password }}"
191 log_path: /tmp/playbook.debug
192 state: present
193 name: snapshot-name
194 copytype: backup
195 source: source-volume-name
196 target: target-volume-name
197 mdiskgrp: Pool0
198 copyrate: 50
199 grainsize: 64
200 - name: Delete FlashCopy mapping for snapshot
201 ibm.storage_virtualize.ibm_svc_manage_flashcopy:
202 clustername: "{{ clustername }}"
203 domain: "{{ domain }}"
204 username: "{{ username }}"
205 password: "{{ password }}"
206 log_path: /tmp/playbook.debug
207 name: snapshot-name
208 state: absent
209 force: true
210 - name: Delete FlashCopy mapping for clone
211 ibm.storage_virtualize.ibm_svc_manage_flashcopy:
212 clustername: "{{ clustername }}"
213 domain: "{{ domain }}"
214 username: "{{ username }}"
215 password: "{{ password }}"
216 log_path: /tmp/playbook.debug
217 name: clone-name
218 state: absent
219 force: true
220 - name: Create FlashCopy mapping with existing target volume.
221 ibm.storage_virtualize.ibm_svc_manage_flashcopy:
222 clustername: "{{ clustername }}"
223 domain: "{{ domain }}"
224 username: "{{ username }}"
225 password: "{{ password }}"
226 log_path: /tmp/playbook.debug
227 state: present
228 name: snapshot-name
229 copytype: clone
230 source: source-volume-name
231 target: target-volume-name
232 consistgrp: consistencygroup-name
233 copyrate: 50
234 grainsize: 64
235 '''
236
237 RETURN = '''#'''
238
239 from traceback import format_exc
240 from ansible.module_utils.basic import AnsibleModule
241 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import IBMSVCRestApi, svc_argument_spec, get_logger
242 from ansible.module_utils._text import to_native
243 import time
244
245
246 class IBMSVCFlashcopy(object):
247 def __init__(self):
248 argument_spec = svc_argument_spec()
249 argument_spec.update(
250 dict(
251 name=dict(type='str', required=True),
252 copytype=dict(type='str', required=False, choices=['snapshot', 'clone', 'backup']),
253 source=dict(type='str', required=False),
254 target=dict(type='str', required=False),
255 mdiskgrp=dict(type='str', required=False),
256 state=dict(type='str', required=True, choices=['present', 'absent']),
257 consistgrp=dict(type='str', required=False),
258 noconsistgrp=dict(type='bool', required=False),
259 copyrate=dict(type='int', required=False),
260 cleanrate=dict(type='int', required=False),
261 grainsize=dict(type='str', required=False),
262 force=dict(type='bool', required=False),
263 old_name=dict(type='str')
264 )
265 )
266
267 self.module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
268
269 # logging setup
270 log_path = self.module.params['log_path']
271 log = get_logger(self.__class__.__name__, log_path)
272 self.log = log.info
273
274 # Required
275 self.name = self.module.params['name']
276 self.state = self.module.params['state']
277
278 # Optional
279 self.copytype = self.module.params.get('copytype', False)
280 self.source = self.module.params.get('source', False)
281 self.target = self.module.params.get('target', False)
282 self.mdiskgrp = self.module.params.get('mdiskgrp', False)
283 self.consistgrp = self.module.params.get('consistgrp', False)
284 self.noconsistgrp = self.module.params.get('noconsistgrp', False)
285 self.grainsize = self.module.params.get('grainsize', False)
286 self.copyrate = self.module.params.get('copyrate', False)
287 self.cleanrate = self.module.params.get('cleanrate', False)
288 self.force = self.module.params.get('force', False)
289 self.old_name = self.module.params.get('old_name', '')
290
291 self.basic_checks()
292 self.changed = False
293
294 self.restapi = IBMSVCRestApi(
295 module=self.module,
296 clustername=self.module.params['clustername'],
297 domain=self.module.params['domain'],
298 username=self.module.params['username'],
299 password=self.module.params['password'],
300 validate_certs=self.module.params['validate_certs'],
301 log_path=log_path,
302 token=self.module.params['token']
303 )
304
305 def basic_checks(self):
306 if self.state == 'absent':
307 invalids = ('copytype', 'source', 'target', 'mdiskgrp', 'consistgrp', 'noconsistgrp', 'copyrate', 'cleanrate', 'grainsize')
308 invalid_exists = ', '.join((var for var in invalids if getattr(self, var) not in {'', None}))
309 if invalid_exists:
310 self.module.fail_json(
311 msg='state=absent but following parameters have been passed: {0}'.format(invalid_exists)
312 )
313
314 def run_command(self, cmd):
315 return self.restapi.svc_obj_info(cmd=cmd[0], cmdopts=cmd[1], cmdargs=cmd[2])
316
317 def mdata_exists(self, name):
318 merged_result = {}
319 data = self.restapi.svc_obj_info(cmd='lsfcmap', cmdopts=None, cmdargs=[name])
320 if isinstance(data, list):
321 for d in data:
322 merged_result.update(d)
323 else:
324 merged_result = data
325
326 return merged_result
327
328 def gather_data(self):
329 result = [None, None, None, []]
330 commands = [["lsfcmap", None, [self.name]]]
331 if self.state == "present" and self.source:
332 commands.append(["lsvdisk", {'bytes': True, 'filtervalue': 'name=%s' % self.source}, None])
333 if self.state == "present" and self.target:
334 commands.append(["lsvdisk", {'bytes': True, 'filtervalue': 'name=%s' % self.target}, None])
335 commands.append(["lsvdisk", {'bytes': True, 'filtervalue': 'name=%s' % self.target + "_temp_*"}, None])
336 res = list(map(self.run_command, commands))
337 if len(res) == 1:
338 result[0] = res[0]
339 elif len(res) == 2:
340 result[0] = res[0]
341 result[1] = res[1]
342 elif len(res) == 4:
343 result = res
344 return result
345
346 def target_create(self, temp_target_name, sdata):
347 cmd = 'mkvdisk'
348 cmdopts = {}
349 cmdopts['name'] = temp_target_name
350 if self.mdiskgrp:
351 cmdopts['mdiskgrp'] = self.mdiskgrp
352 else:
353 cmdopts['mdiskgrp'] = sdata['mdisk_grp_name']
354 cmdopts['size'] = sdata['capacity']
355 cmdopts['unit'] = 'b'
356 cmdopts['iogrp'] = sdata['IO_group_name']
357 if self.copytype == 'snapshot':
358 cmdopts['rsize'] = '0%'
359 cmdopts['autoexpand'] = True
360
361 if self.module.check_mode:
362 self.changed = True
363 return
364
365 self.log("Creating vdisk.. Command %s opts %s", cmd, cmdopts)
366
367 # Run command
368 result = self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
369 self.log("Create target volume result %s", result)
370
371 if 'message' in result:
372 self.changed = True
373 self.log("Create target volume result message %s",
374 result['message'])
375 else:
376 self.module.fail_json(
377 msg="Failed to create target volume [%s]" % self.target)
378
379 def fcmap_create(self, temp_target_name):
380 if self.copyrate:
381 if self.copytype in ('clone', 'backup'):
382 if self.copyrate not in range(1, 151):
383 self.module.fail_json(msg="Copyrate for clone and backup must be in range 1-150")
384 if self.copytype == 'snapshot':
385 if self.copyrate not in range(0, 151):
386 self.module.fail_json(msg="Copyrate for snapshot must be in range 0-150")
387 else:
388 if self.copytype in ('clone', 'backup'):
389 self.copyrate = 50
390 elif self.copytype == 'snapshot':
391 self.copyrate = 0
392
393 if self.module.check_mode:
394 self.changed = True
395 return
396
397 cmd = 'mkfcmap'
398 cmdopts = {}
399 cmdopts['name'] = self.name
400 cmdopts['source'] = self.source
401 cmdopts['target'] = temp_target_name
402 cmdopts['copyrate'] = self.copyrate
403 cmdopts['cleanrate'] = self.cleanrate
404 if self.grainsize:
405 cmdopts['grainsize'] = self.grainsize
406 if self.consistgrp:
407 cmdopts['consistgrp'] = self.consistgrp
408 if self.copytype == 'clone':
409 cmdopts['autodelete'] = True
410 if self.copytype == 'backup':
411 cmdopts['incremental'] = True
412 self.log("Creating fc mapping.. Command %s opts %s",
413 cmd, cmdopts)
414 # Run command
415 result = self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
416 self.log("Create flash copy mapping relationship result %s", result)
417
418 if 'message' in result:
419 self.changed = True
420 self.log("Create flash copy mapping relationship result "
421 "message %s", result['message'])
422 else:
423 self.module.fail_json(msg="Failed to create FlashCopy mapping "
424 "relationship [%s]" % self.name)
425
426 def fcmap_delete(self):
427 self.log("Deleting flash copy mapping relationship'%s'", self.name)
428
429 if self.module.check_mode:
430 self.changed = True
431 return
432
433 cmd = 'rmfcmap'
434 cmdopts = {}
435 if self.force:
436 cmdopts['force'] = self.force
437 self.restapi.svc_run_command(cmd, cmdopts, cmdargs=[self.name])
438
439 def rename_temp_to_target(self, temp_name):
440 if self.module.check_mode:
441 self.changed = True
442 return
443
444 cmd = 'chvdisk'
445 cmdopts = {}
446 cmdopts['name'] = self.target
447 self.log("Rename %s to %s", cmd, cmdopts)
448 self.restapi.svc_run_command(cmd, cmdopts, cmdargs=[temp_name])
449
450 def fcmap_probe(self, data):
451 props = {}
452 props_not_supported = []
453 if self.source:
454 if data["source_vdisk_name"] != self.source:
455 props_not_supported.append("source")
456 if self.target:
457 if data["target_vdisk_name"] != self.target:
458 props_not_supported.append("target")
459 if self.copytype:
460 if (self.copytype == "snapshot" and data['autodelete'] == "on") or (self.copytype == "clone" and data["autodelete"] != "on"):
461 props_not_supported.append("copytype")
462 if self.grainsize:
463 if data['grain_size'] != self.grainsize:
464 props_not_supported.append("grainsize")
465 if props_not_supported:
466 self.module.fail_json(msg="Update not supported for parameter: " + ", ".join(props_not_supported))
467 self.log("Probe which properties need to be updated...")
468 if data['group_name'] and self.noconsistgrp:
469 props['consistgrp'] = 0
470 if not self.noconsistgrp:
471 if self.consistgrp:
472 if self.consistgrp != data['group_name']:
473 props['consistgrp'] = self.consistgrp
474 if self.copyrate and self.copyrate != int(data['copy_rate']):
475 props['copyrate'] = self.copyrate
476 if self.cleanrate and self.cleanrate != int(data['clean_rate']):
477 props['cleanrate'] = self.cleanrate
478 return props
479
480 def fcmap_update(self, modify):
481 if self.module.check_mode:
482 self.changed = True
483 return
484
485 if modify:
486 self.log("updating fcmap with properties %s", modify)
487 cmd = 'chfcmap'
488 cmdopts = {}
489 for prop in modify:
490 cmdopts[prop] = modify[prop]
491 cmdargs = [self.name]
492 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
493
494 # for validating parameter while renaming a volume
495 def parameter_handling_while_renaming(self):
496 parameters = {
497 "copytype": self.copytype,
498 "copyrate": self.copyrate,
499 "cleanrate": self.cleanrate,
500 "source": self.source,
501 "target": self.target,
502 "grainsize": self.grainsize,
503 "mdiskgrp": self.mdiskgrp,
504 "consistgrp": self.consistgrp
505 }
506 parameters_exists = [parameter for parameter, value in parameters.items() if value]
507 if parameters_exists:
508 self.module.fail_json(msg="Parameters {0} not supported while renaming a mapping.".format(parameters_exists))
509
510 def flashcopy_rename(self):
511 msg = None
512 self.parameter_handling_while_renaming()
513 mdata = self.mdata_exists(self.name)
514 old_mdata = self.mdata_exists(self.old_name)
515 if not old_mdata and not mdata:
516 self.module.fail_json(msg="mapping [{0}] does not exists.".format(self.old_name))
517 elif old_mdata and mdata:
518 self.module.fail_json(msg="mapping with name [{0}] already exists.".format(self.name))
519 elif not old_mdata and mdata:
520 msg = "mdisk [{0}] already renamed.".format(self.name)
521 elif old_mdata and not mdata:
522 # when check_mode is enabled
523 if self.module.check_mode:
524 self.changed = True
525 return
526 self.restapi.svc_run_command('chfcmap', {'name': self.name}, [self.old_name])
527 self.changed = True
528 msg = "mapping [{0}] has been successfully rename to [{1}].".format(self.old_name, self.name)
529 return msg
530
531 def apply(self):
532 msg = None
533 modify = []
534 temp = None
535 if self.state == 'present' and self.old_name:
536 msg = self.flashcopy_rename()
537 self.module.exit_json(msg=msg, changed=self.changed)
538 elif self.state == 'absent' and self.old_name:
539 self.module.fail_json(msg="Rename functionality is not supported when 'state' is absent.")
540 else:
541 mdata, sdata, tdata, temp = self.gather_data()
542 if mdata:
543 if self.state == "present":
544 modify = self.fcmap_probe(mdata)
545 if modify:
546 self.changed = True
547 else:
548 msg = "mapping [%s] already exists" % self.name
549 elif self.state == "absent":
550 self.changed = True
551 else:
552 if self.state == "present":
553 if None in [self.source]:
554 self.module.fail_json(msg="Required while creating FlashCopy mapping: 'source'")
555 if not sdata:
556 self.module.fail_json(msg="The source volume [%s] doesn't exist." % self.source)
557
558 if tdata:
559 if sdata[0]["capacity"] == tdata[0]["capacity"]:
560 self.fcmap_create(self.target)
561 msg = "mapping [%s] has been created" % self.name
562 self.module.exit_json(msg=msg, changed=self.changed)
563 elif sdata[0]["capacity"] != tdata[0]["capacity"]:
564 self.module.fail_json(msg="source and target must be of same size")
565 if sdata and not tdata:
566 self.changed = True
567 elif self.state == "absent":
568 msg = "mapping [%s] does not exist" % self.name
569
570 if self.changed:
571 if self.state == "present" and not modify:
572 if None in [self.source, self.target, self.copytype]:
573 self.module.fail_json(msg="Required while creating FlashCopy mapping: 'source', 'target' and 'copytype'")
574 temp_target = "%s_temp_%s" % (self.target, time.time())
575 if len(temp) == 0:
576 self.target_create(temp_target, sdata[0])
577 self.fcmap_create(temp_target)
578 self.rename_temp_to_target(temp_target)
579 msg = "mapping [%s] has been created" % self.name
580 elif len(temp) == 1:
581 self.fcmap_create(temp[0]["name"])
582 self.rename_temp_to_target(temp[0]["name"])
583 msg = "mapping [%s] has been created" % self.name
584 elif len(temp) > 1:
585 self.module.fail_json(msg="Multiple %s_temp_* volumes exists" % self.target)
586 elif self.state == "present" and modify:
587 self.fcmap_update(modify)
588 msg = "mapping [%s] has been modified" % self.name
589 elif self.state == "absent":
590 self.fcmap_delete()
591 msg = "mapping [%s] has been deleted" % self.name
592
593 else:
594 self.log("exiting with no changes")
595 if self.state == 'absent':
596 msg = "mapping [%s] does not exist." % self.name
597 else:
598 msg = "mapping [%s] already exists." % self.name
599
600 if self.module.check_mode:
601 msg = 'skipping changes due to check mode.'
602
603 self.module.exit_json(msg=msg, changed=self.changed)
604
605
606 def main():
607 v = IBMSVCFlashcopy()
608 try:
609 v.apply()
610 except Exception as e:
611 v.log("Exception in apply(): \n%s", format_exc())
612 v.module.fail_json(msg="Module failed. Error [%s]." % to_native(e))
613
614
615 if __name__ == '__main__':
616 main()