Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (C) 2022 IBM CORPORATION
5 # Author(s): Sanjaikumaar M <[email protected]>
6 # Sumit Kumar Gupta <[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_sv_manage_snapshot
16 short_description: This module manages snapshots (PiT image of a volume) on IBM Storage Virtualize family systems
17 version_added: '1.9.0'
18 description:
19 - In this implementation, a snapshot is a mutually consistent image of the volumes
20 in a volume group or a list of independent volume(s).
21 - This Ansible module provides the interface to manage snapshots through 'addsnapshot',
22 'chsnapshot' and 'rmsnapshot' Storage Virtualize commands.
23 options:
24 clustername:
25 description:
26 - The hostname or management IP or Partition IP of the Storage Virtualize system.
27 required: true
28 type: str
29 domain:
30 description:
31 - Domain for the Storage Virtualize system.
32 - Valid when hostname is used for the parameter I(clustername).
33 type: str
34 username:
35 description:
36 - REST API username for the Storage Virtualize system.
37 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
38 type: str
39 password:
40 description:
41 - REST API password for the Storage Virtualize system.
42 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
43 type: str
44 token:
45 description:
46 - The authentication token to verify a user on the Storage Virtualize system.
47 - To generate a token, use the M(ibm.storage_virtualize.ibm_svc_auth) module.
48 type: str
49 log_path:
50 description:
51 - Path of debug log file.
52 type: str
53 state:
54 description:
55 - Creates, updates (C(present)), restores from (C(restore)) or deletes (C(absent)) a snapshot.
56 choices: [ present, restore, absent ]
57 required: true
58 type: str
59 name:
60 description:
61 - Specifies the name of a snapshot.
62 type: str
63 old_name:
64 description:
65 - Specifies the old name of a snapshot.
66 - Valid when I(state=present), to rename the existing snapshot.
67 type: str
68 src_volumegroup_name:
69 description:
70 - Specifies the name of the source volume group for which the snapshot is being created.
71 - I(src_volumegroup_name) and I(src_volume_names) are mutually exclusive for creating snapshot.
72 - Required one of I(src_volumegroup_name) or I(src_volume_names) for creation of snapshot.
73 type: str
74 src_volume_names:
75 description:
76 - Specifies the name/UID of the volumes for which the snapshots are to be created.
77 - List of volume names can be specified with the delimiter colon.
78 - Valid when I(state=present), to create a snapshot.
79 type: str
80 snapshot_pool:
81 description:
82 - Specifies the name of child pool within which the snapshot is being created.
83 type: str
84 ignorelegacy:
85 description:
86 - Specifies the addition of the volume snapshots although there are already legacy FlashCopy mappings using the volume as a source.
87 default: false
88 type: bool
89 ownershipgroup:
90 description:
91 - Specifies the name of the ownershipgroup.
92 - Valid when I(state=present), to update an existing snapshot.
93 type: str
94 safeguarded:
95 description:
96 - Flag to create a safeguarded snapshot.
97 - I(safeguarded) and I(retentiondays) are required together.
98 - Supported in SV build 8.5.2.0 or later.
99 type: bool
100 version_added: 1.10.0
101 retentiondays:
102 description:
103 - Specifies the retention period in days.
104 - I(safeguarded) and I(retentiondays) are required together.
105 - Applies, when I(state=present) to create a safeguarded snapshot.
106 type: int
107 version_added: 1.10.0
108 retentionminutes:
109 description:
110 - Specifies the retention period in minutes in range 1 - 1440.
111 - I(retentionminutes) and I(retentiondays) are mutually exclusive.
112 - Applies, when I(state=present) to create a transient snapshot.
113 type: int
114 version_added: 2.3.0
115 validate_certs:
116 description:
117 - Validates certification.
118 default: false
119 type: bool
120 author:
121 - Sanjaikumaar M (@sanjaikumaar)
122 - Sumit Kumar Gupta (@sumitguptaibm)
123 notes:
124 - This module supports C(check_mode).
125 - This module automates the new Snapshot function, implemented by Storage Virtualize, which is using a
126 simplified management model. Any user requiring the flexibility available with legacy
127 FlashCopy can continue to use the existing module M(ibm.storage_virtualize.ibm_svc_manage_flashcopy).
128 - Snapshots created by this Ansible module are not directly accessible from the hosts.
129 To create a new group of host accessible volumes from a snapshot,
130 use M(ibm.storage_virtualize.ibm_svc_manage_volumegroup) module.
131 - In case of restoring local snapshots present before establishing high availability (HA), HA sync will be stopped till the snapshots gets restored.
132 - This module supports logging in via partition IP.
133 '''
134
135 EXAMPLES = '''
136 - name: Create volumegroup snapshot
137 ibm.storage_virtualize.ibm_sv_manage_snapshot:
138 clustername: '{{ clustername }}'
139 username: '{{ username }}'
140 password: '{{ password }}'
141 name: ansible_1
142 src_volumegroup_name: volumegroup1
143 snapshot_pool: Pool0Childpool0
144 state: present
145 - name: Create volumes snapshot
146 ibm.storage_virtualize.ibm_sv_manage_snapshot:
147 clustername: '{{ clustername }}'
148 username: '{{ username }}'
149 password: '{{ password }}'
150 name: ansible_2
151 src_volume_names: vdisk0:vdisk1
152 snapshot_pool: Pool0Childpool0
153 state: present
154 - name: Create safeguarded snapshot
155 ibm.storage_virtualize.ibm_sv_manage_snapshot:
156 clustername: '{{ clustername }}'
157 username: '{{ username }}'
158 password: '{{ password }}'
159 name: ansible_2
160 src_volume_names: vdisk0:vdisk1
161 safeguarded: true
162 retentiondays: 1
163 snapshot_pool: Pool0Childpool0
164 state: present
165 - name: Update snapshot ansible_2
166 ibm.storage_virtualize.ibm_sv_manage_snapshot:
167 clustername: '{{ clustername }}'
168 username: '{{ username }}'
169 password: '{{ password }}'
170 name: ansible_new
171 old_name: ansible_2
172 ownershipgroup: ownershipgroup0
173 state: present
174 - name: Restore all volumes of a volumegroup from a snapshot
175 ibm.storage_virtualize.ibm_sv_manage_snapshot:
176 clustername: '{{ clustername }}'
177 username: '{{ username }}'
178 password: '{{ password }}'
179 name: snapshot0
180 src_volumegroup_name: volumegroup1
181 state: restore
182 - name: Restore subset of volumes of a volumegroup from snapshot
183 ibm.storage_virtualize.ibm_sv_manage_snapshot:
184 clustername: '{{ clustername }}'
185 username: '{{ username }}'
186 password: '{{ password }}'
187 name: snapshot0
188 src_volumegroup_name: volumegroup1
189 src_volume_names: vdisk0:vdisk1
190 state: restore
191 - name: Create transient snapshot
192 ibm.storage_virtualize.ibm_sv_manage_snapshot:
193 clustername: '{{ clustername }}'
194 username: '{{ username }}'
195 password: '{{ password }}'
196 name: snapshot0
197 src_volume_names: vdisk0:vdisk1
198 safeguarded: true
199 retentionminutes: 5
200 snapshot_pool: Pool0Childpool0
201 state: present
202 - name: Delete volumegroup snapshot
203 ibm.storage_virtualize.ibm_sv_manage_snapshot:
204 clustername: '{{ clustername }}'
205 username: '{{ username }}'
206 password: '{{ password }}'
207 name: ansible_1
208 src_volumegroup_name: volumegroup1
209 state: absent
210 - name: Delete volume snapshot
211 ibm.storage_virtualize.ibm_sv_manage_snapshot:
212 clustername: '{{ clustername }}'
213 username: '{{ username }}'
214 password: '{{ password }}'
215 name: ansible_new
216 state: absent
217 '''
218
219 RETURN = '''#'''
220
221 from traceback import format_exc
222 from ansible.module_utils.basic import AnsibleModule
223 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import (
224 IBMSVCRestApi,
225 svc_argument_spec,
226 strtobool,
227 get_logger
228 )
229 from ansible.module_utils._text import to_native
230
231 MIN_SNAPSHOT_RETENTION_MINUTES = 1
232 MAX_SNAPSHOT_RETENTION_MINUTES = 1440
233
234
235 class IBMSVSnapshot:
236
237 def __init__(self):
238 argument_spec = svc_argument_spec()
239 argument_spec.update(
240 dict(
241 state=dict(
242 type='str',
243 required=True,
244 choices=['present', 'restore', 'absent']
245 ),
246 name=dict(
247 type='str',
248 ),
249 old_name=dict(
250 type='str'
251 ),
252 snapshot_pool=dict(
253 type='str',
254 ),
255 src_volumegroup_name=dict(
256 type='str',
257 ),
258 src_volume_names=dict(
259 type='str',
260 ),
261 ignorelegacy=dict(
262 type='bool',
263 default=False
264 ),
265 ownershipgroup=dict(
266 type='str',
267 ),
268 safeguarded=dict(
269 type='bool'
270 ),
271 retentiondays=dict(
272 type='int',
273 ),
274 retentionminutes=dict(
275 type='int'
276 )
277 )
278 )
279
280 self.module = AnsibleModule(argument_spec=argument_spec,
281 supports_check_mode=True)
282
283 # Required parameters
284 self.name = self.module.params['name']
285 self.state = self.module.params['state']
286
287 # Default parameters
288 self.ignorelegacy = self.module.params['ignorelegacy']
289
290 # Optional parameters
291 self.old_name = self.module.params.get('old_name', '')
292 self.ownershipgroup = self.module.params.get('ownershipgroup', '')
293 self.snapshot_pool = self.module.params.get('snapshot_pool', '')
294 self.volumegroup = self.module.params.get('src_volumegroup_name', '')
295 self.volumes = self.module.params.get('src_volume_names', '')
296 self.safeguarded = self.module.params.get('safeguarded', False)
297 self.retentiondays = self.module.params.get('retentiondays')
298 self.retentionminutes = self.module.params.get('retentionminutes')
299
300 self.basic_checks()
301
302 # logging setup
303 self.log_path = self.module.params['log_path']
304 log = get_logger(self.__class__.__name__, self.log_path)
305 self.log = log.info
306
307 # Dynamic variables
308 self.changed = False
309 self.msg = ''
310 self.parentuid = None
311 self.lsvg_data = {}
312 self.lsv_data = {}
313
314 self.restapi = IBMSVCRestApi(
315 module=self.module,
316 clustername=self.module.params['clustername'],
317 domain=self.module.params['domain'],
318 username=self.module.params['username'],
319 password=self.module.params['password'],
320 validate_certs=self.module.params['validate_certs'],
321 log_path=self.log_path,
322 token=self.module.params['token']
323 )
324
325 def basic_checks(self):
326 if not self.name:
327 self.module.fail_json(msg='Missing mandatory parameter: name')
328
329 if not self.state:
330 self.module.fail_json(msg='Missing mandatory parameter: state')
331
332 if self.state == 'present':
333 if self.volumegroup and self.volumes:
334 self.module.fail_json(
335 msg='Mutually exclusive parameters: src_volumegroup_name, src_volume_names'
336 )
337 if self.retentionminutes is not None:
338 if (self.retentionminutes < MIN_SNAPSHOT_RETENTION_MINUTES or
339 self.retentionminutes > MAX_SNAPSHOT_RETENTION_MINUTES):
340 self.module.fail_json(
341 msg='Invalid value for retentionminutes parameter. Valid range 1-1440.'
342 )
343
344 elif self.state == 'restore':
345 # Check mandatory parameter src_volumegroup_name
346 if not self.volumegroup:
347 self.module.fail_json(
348 msg='Missing mandatory parameter src_volumegroup_name'
349 )
350 invalids = ('snapshot_pool', 'ignorelegacy', 'ownershipgroup',
351 'old_name', 'safeguarded', 'retentiondays', 'retentionminutes')
352 invalid_exists = ', '.join((var for var in invalids if getattr(self, var)))
353 if invalid_exists:
354 self.module.fail_json(
355 msg='Invalid parameters for state=restore: {0}'.format(invalid_exists)
356 )
357
358 elif self.state == 'absent':
359 invalids = ('snapshot_pool', 'ignorelegacy', 'ownershipgroup',
360 'old_name', 'safeguarded', 'retentiondays', 'retentionminutes')
361 invalid_exists = ', '.join((var for var in invalids if getattr(self, var)))
362
363 if self.volumes:
364 invalid_exists = 'src_volume_names, {0}'.format(invalid_exists)
365
366 if invalid_exists:
367 self.module.fail_json(
368 msg='Invalid parameters for state=absent: {0}'.format(invalid_exists)
369 )
370 else:
371 self.module.fail_json(msg='State should be one of present,restore or absent')
372
373 def create_validation(self):
374 if self.old_name:
375 self.rename_validation([])
376
377 if not self.volumegroup and not self.volumes:
378 self.module.fail_json(
379 msg='Either src_volumegroup_name or src_volume_names should be passed during snapshot creation.'
380 )
381
382 if self.ownershipgroup:
383 self.module.fail_json(
384 msg='`ownershipgroup` parameter is not supported during snapshot creation'
385 )
386
387 def rename_validation(self, updates):
388 if self.old_name and self.name:
389
390 if self.name == self.old_name:
391 self.module.fail_json(msg='New name and old name should be different.')
392
393 new = self.is_snapshot_exists()
394 existing = self.is_snapshot_exists(old_name=self.old_name)
395
396 if existing:
397 if new:
398 self.module.fail_json(
399 msg='Snapshot ({0}) already exists for the given new name.'.format(self.name)
400 )
401 else:
402 updates.append('name')
403 else:
404 if not new:
405 self.module.fail_json(
406 msg='Snapshot ({0}) does not exists for the given old name.'.format(self.old_name)
407 )
408 else:
409 self.module.exit_json(
410 msg='Snapshot ({0}) already renamed. No modifications done.'.format(self.name)
411 )
412
413 def is_snapshot_exists(self, old_name=None, force=False):
414 old_name = old_name if old_name else self.name
415 if self.volumegroup:
416 data = self.lsvolumegroupsnapshot(old_name=old_name, force=force)
417 self.parentuid = data.get('parent_uid')
418 else:
419 if self.lsv_data.get('snapshot_name') == old_name and not force:
420 return self.lsv_data
421 cmdopts = {
422 "filtervalue": "snapshot_name={0}".format(old_name)
423 }
424 result = self.restapi.svc_obj_info(
425 cmd='lsvolumesnapshot',
426 cmdopts=cmdopts,
427 cmdargs=None
428 )
429 try:
430 data = next(
431 filter(
432 lambda x: x['volume_group_name'] == '',
433 result
434 )
435 )
436 except StopIteration:
437 return {}
438 else:
439 self.lsv_data = data
440 self.parentuid = data.get('parent_uid')
441
442 return data
443
444 def lsvolumegroupsnapshot(self, force=False, old_name=None, parentuid=None):
445 old_name = old_name if old_name else self.name
446 if self.lsvg_data.get('name') == old_name and not force:
447 return self.lsvg_data
448
449 cmdopts = {
450 'snapshot': old_name
451 }
452 if parentuid:
453 cmdopts['parentuid'] = self.parentuid
454 else:
455 cmdopts['volumegroup'] = self.volumegroup
456
457 data = {}
458 result = self.restapi.svc_obj_info(
459 cmd='lsvolumegroupsnapshot',
460 cmdopts=cmdopts,
461 cmdargs=None
462 )
463
464 if isinstance(result, list):
465 for res in result:
466 data = res
467 else:
468 data = result
469
470 self.lsvg_data = data
471
472 return data
473
474 def create_snapshot(self):
475 self.create_validation()
476 if self.module.check_mode:
477 self.changed = True
478 return
479
480 cmd = 'addsnapshot'
481 cmdopts = {
482 'name': self.name
483 }
484
485 if self.snapshot_pool:
486 cmdopts['pool'] = self.snapshot_pool
487 if self.ignorelegacy:
488 cmdopts['ignorelegacy'] = self.ignorelegacy
489 if self.retentiondays:
490 cmdopts['retentiondays'] = self.retentiondays
491 if self.retentionminutes:
492 cmdopts['retentionminutes'] = self.retentionminutes
493 if self.safeguarded:
494 cmdopts['safeguarded'] = self.safeguarded
495
496 if self.volumegroup:
497 cmdopts['volumegroup'] = self.volumegroup
498 else:
499 cmdopts['volumes'] = self.volumes
500
501 self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
502 self.log('Snapshot (%s) created', self.name)
503 self.changed = True
504
505 def restore_from_snapshot(self, snapshot_data):
506 if self.module.check_mode:
507 self.changed = True
508 return
509
510 cmd = 'restorefromsnapshot'
511 cmdopts = {
512 'snapshot': self.name
513 }
514 if self.volumegroup:
515 cmdopts['volumegroup'] = self.volumegroup
516 if self.volumes:
517 if snapshot_data.get("ha_state") == "highly_available":
518 vol_list = self.volumes.split(":")
519 if len(vol_list) > 1:
520 self.module.fail_json(
521 msg="CMMVC1301E The command failed because highly available snapshot restore is"
522 " only permitted on the whole snapshot or specifying a single volume"
523 )
524 cmdopts['volumes'] = self.volumes
525 if snapshot_data.get("ha_state") == "local":
526 cmdopts['resyncrestoredvolumes'] = True
527
528 self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
529 self.changed = True
530
531 def snapshot_probe(self):
532 updates = []
533 self.rename_validation(updates)
534 kwargs = dict((k, getattr(self, k)) for k in ['old_name', 'parentuid'] if getattr(self, k))
535 ls_data = self.lsvolumegroupsnapshot(**kwargs)
536
537 if self.ownershipgroup and ls_data['owner_name'] != self.ownershipgroup:
538 updates.append('ownershipgroup')
539
540 if self.safeguarded in {True, False} and self.safeguarded != strtobool(ls_data.get('safeguarded', 0)):
541 self.module.fail_json(
542 msg='Following parameter not applicable for update operation: safeguarded'
543 )
544
545 self.log('Snapshot probe result: %s', updates)
546 return updates
547
548 def update_snapshot(self, updates):
549 if self.module.check_mode:
550 self.changed = True
551 return
552
553 old_name = self.old_name if self.old_name else self.name
554 cmd = 'chsnapshot'
555 cmdopts = dict((k, getattr(self, k)) for k in updates)
556 cmdopts['snapshot'] = old_name
557
558 if self.volumegroup:
559 cmdopts['volumegroup'] = self.volumegroup
560 else:
561 cmdopts['parentuid'] = self.parentuid
562 self.restapi.svc_run_command(cmd, cmdopts=cmdopts, cmdargs=None)
563 self.changed = True
564
565 def delete_snapshot(self):
566 if self.module.check_mode:
567 self.changed = True
568 return
569
570 cmd = 'rmsnapshot'
571 cmdopts = {
572 'snapshot': self.name
573 }
574
575 if self.volumegroup:
576 cmdopts['volumegroup'] = self.volumegroup
577 else:
578 cmdopts['parentuid'] = self.parentuid
579
580 self.restapi.svc_run_command(cmd, cmdopts=cmdopts, cmdargs=None)
581 self.changed = True
582
583 still_exists = self.is_snapshot_exists(force=True)
584 if still_exists:
585 self.msg = 'Snapshot ({0}) will be in the dependent_delete '\
586 'state until those dependencies are removed'.format(self.name)
587 else:
588 self.msg = 'Snapshot ({0}) deleted.'.format(self.name)
589
590 def apply(self):
591 snapshot_data = self.is_snapshot_exists(old_name=self.old_name)
592 if snapshot_data:
593 if self.state == 'present':
594 modifications = self.snapshot_probe()
595 if any(modifications):
596 if self.retentionminutes is not None:
597 self.module.fail_json(msg='Invalid parameter retentionminutes for update operation')
598 self.update_snapshot(modifications)
599 self.msg = 'Snapshot ({0}) updated.'.format(self.name)
600 else:
601 self.msg = 'Snapshot ({0}) already exists. No modifications done.'.format(self.name)
602 elif self.state == 'restore':
603 self.restore_from_snapshot(snapshot_data)
604 if self.volumes:
605 self.msg = 'Volumes ({0}) of Volumegroup ({1}) restored from Snapshot ({2}).'.\
606 format(self.volumes, self.volumegroup, self.name)
607 else:
608 self.msg = 'Volumegroup ({0}) restored from Snapshot ({1}).'.format(self.volumegroup, self.name)
609 else:
610 self.delete_snapshot()
611 else:
612 if self.state == 'absent':
613 self.msg = 'Snapshot ({0}) does not exist.'.format(self.name)
614 elif self.state == 'restore':
615 self.module.fail_json(
616 msg='Either snapshot ({0}) does not exist, or snapshot ({0}) is not related to the volumegroup ({1}).'.format(self.name, self.volumegroup)
617 )
618 else:
619 self.create_snapshot()
620 self.msg = 'Snapshot ({0}) created.'.format(self.name)
621
622 if self.module.check_mode:
623 self.msg = 'skipping changes due to check mode.'
624
625 self.module.exit_json(
626 changed=self.changed,
627 msg=self.msg
628 )
629
630
631 def main():
632 v = IBMSVSnapshot()
633 try:
634 v.apply()
635 except Exception as e:
636 v.log('Exception in apply(): \n%s', format_exc())
637 v.module.fail_json(msg='Module failed. Error [%s].' % to_native(e))
638
639
640 if __name__ == '__main__':
641 main()