Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (C) 2021 IBM CORPORATION
5 # Author(s): Shilpi Jain <[email protected]>
6 # Sanjaikumaar M <[email protected]>
7 # Sumit Kumar Gupta <[email protected]>
8 # Sandip Gulab Rajbanshi <[email protected]>
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10
11 from __future__ import absolute_import, division, print_function
12 __metaclass__ = type
13
14 DOCUMENTATION = '''
15 ---
16 module: ibm_svc_manage_volumegroup
17 short_description: This module manages volume groups on IBM Storage Virtualize family systems
18 version_added: "1.6.0"
19 description:
20 - Ansible interface to manage 'mkvolumegroup', 'chvolumegroup', and 'rmvolumegroup'
21 commands.
22 options:
23 name:
24 description:
25 - Specifies the name for the volume group.
26 required: true
27 type: str
28 state:
29 description:
30 - Creates or updates (C(present)) or removes (C(absent)) a volume group.
31 choices: [ absent, present ]
32 required: true
33 type: str
34 clustername:
35 description:
36 - The hostname or management IP or Partition IP of the Storage Virtualize system.
37 required: true
38 type: str
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 M(ibm.storage_virtualize.ibm_svc_auth) module.
58 type: str
59 log_path:
60 description:
61 - Path of debug log file.
62 type: str
63 validate_certs:
64 description:
65 - Validates certification.
66 default: false
67 type: bool
68 ownershipgroup:
69 description:
70 - Specifies the name of the ownership group to which the object is being added.
71 - I(ownershipgroup) is mutually exclusive with parameters I(safeguardpolicyname) and I(noownershipgroup).
72 - Applies when I(state=present).
73 type: str
74 noownershipgroup:
75 description:
76 - If specified `True`, the object is removed from the ownership group to which it belongs.
77 - Parameters I(ownershipgroup) and I(noownershipgroup) are mutually exclusive.
78 - Applies when I(state=present) to modify an existing volume group.
79 type: bool
80 safeguardpolicyname:
81 description:
82 - The name of the Safeguarded policy to be assigned to the volume group.
83 - I(safeguardpolicyname) is mutually exclusive with parameters I(nosafeguardpolicy) and I(ownershipgroup).
84 - Applies when I(state=present).
85 type: str
86 nosafeguardpolicy:
87 description:
88 - If specified `True`, removes the Safeguarded policy assigned to the volume group.
89 - Parameters I(safeguardpolicyname) and I(nosafeguardpolicy) are mutually exclusive.
90 - Applies when I(state=present) to modify an existing volume group.
91 type: bool
92 snapshotpolicy:
93 description:
94 - The name of the snapshot policy to be assigned to the volume group.
95 - I(snapshotpolicy) is mutually exclusive with parameters I(nosnapshotpolicy) and I(ownershipgroup).
96 - Applies when I(state=present).
97 type: str
98 version_added: 1.9.0
99 nosnapshotpolicy:
100 description:
101 - If specified `True`, removes the snapshot policy assigned to the volume group.
102 - Parameters I(snapshotpolicy) and I(nosnapshotpolicy) are mutually exclusive.
103 - Applies when I(state=present) to modify an existing volume group.
104 type: bool
105 version_added: 1.9.0
106 snapshotpolicysuspended:
107 description:
108 - Specifies whether to suspend (C(yes)) or resume (C(no)) the snapshot policy on this volume group.
109 - Applies when I(state=present) to modify an existing volume group.
110 choices: [ 'yes', 'no' ]
111 type: str
112 version_added: 1.9.0
113 policystarttime:
114 description:
115 - Specifies the time when the first Safeguarded backup is to be taken.
116 - This parameter can also be associated with snapshot policy.
117 - I(safeguardpolicyname) is required when using I(policystarttime).
118 - The accepted format is YYMMDDHHMM.
119 - Applies when I(state=present).
120 type: str
121 type:
122 description:
123 - Specifies the type of volume group to be created from the snapshot.
124 - Valid during creation of host accessible volume group from an existing snapshot.
125 - Also used to convert a thinclone volumegroup to clone. type = clone should be specified.
126 choices: [ clone, thinclone ]
127 type: str
128 version_added: 1.9.0
129 snapshot:
130 description:
131 - Specifies the name of the snapshot used to prepopulate the new volumes in the new volume group.
132 - Required when creating a host accessible volume group from an existing snapshot.
133 type: str
134 version_added: 1.9.0
135 fromsourcegroup:
136 description:
137 - Specifies the parent volume group of the snapshot. This is used to prepopulate the new volume in the
138 new volume group.
139 - Valid during creation of host accessible volume group from an existing snapshot.
140 type: str
141 version_added: 1.9.0
142 pool:
143 description:
144 - Specifies the pool name where the target volumes are to be created.
145 - Valid during creation of host accessible volume group from an existing snapshot.
146 type: str
147 version_added: 1.9.0
148 iogrp:
149 description:
150 - Specifies the I/O group for new volumes.
151 - Valid during creation of host accessible volume group from an existing snapshot.
152 type: str
153 version_added: 1.9.0
154 safeguarded:
155 description:
156 - If specified, the snapshot policy creates safeguarded snapshots.
157 - Should be specified along with I(snapshotpolicy).
158 - Valid during creation and update of a volume group.
159 - Supported from Storage Virtualize family systems 8.5.2.0 or later.
160 default: false
161 type: bool
162 version_added: 1.10.0
163 ignoreuserfcmaps:
164 description:
165 - Allows user to create snapshots through the scheduler or manually with `addsnapshot`.
166 This can only be used if a volume in the volume group is used as a source of a user legacy
167 FlashCopy mapping.
168 - Valid during creation and update of a volume group.
169 - Supported from Storage Virtualize family systems 8.5.2.0 or later.
170 choices: [ 'yes', 'no' ]
171 type: str
172 version_added: 1.10.0
173 replicationpolicy:
174 description:
175 - Specifies the name of the replication policy to be assigned to the volume group.
176 - Applies when I(state=present).
177 - Supported from Storage Virtualize family systems 8.5.2.1 or later.
178 type: str
179 version_added: 1.10.0
180 noreplicationpolicy:
181 description:
182 - If specified `True`, removes the replication policy assigned to the volume group.
183 - I(noreplicationpolicy) is mutually exclusive with parameters I(replicationpolicy) and I(nodrreplication).
184 - Applies when I(state=present) to modify an existing volume group.
185 - Supported from Storage Virtualize family systems 8.5.2.1 or later.
186 type: bool
187 version_added: 1.10.0
188 old_name:
189 description:
190 - Specifies the old name of the volume group during renaming.
191 - Valid when I(state=present), to rename an existing volume group.
192 type: str
193 version_added: '2.0.0'
194 partition:
195 description:
196 - Specifies the name of the storage partition to be assigned to the volume group.
197 - Applies when I(state=present).
198 - Supported from Storage Virtualize family systems 8.6.1.0 or later.
199 type: str
200 version_added: 2.1.0
201 evictvolumes:
202 description:
203 - If specified `True`, delete the volume group but does not remove volumes.
204 - Applies when I(state=absent) to delete the volume group, keeping associated volumes.
205 - Supported from Storage Virtualize family systems from 8.6.2.0 or later.
206 type: bool
207 version_added: 2.2.0
208 fromsourcevolumes:
209 description:
210 - Specifies colon-separated list of the parent volumes name/UID.
211 - When combined with the type parameter and a snapshot, this allows the user to create a volumegroup with a
212 subset of those volumes whose image is present in a snapshot.
213 - Applies when I(state=present) to create volumegroup clone or thinclone, from subset of volumes of snapshot.
214 - Supported from Storage Virtualize family systems from 8.6.2.0 or later.
215 type: str
216 version_added: 2.3.0
217 draftpartition:
218 description:
219 - Specifies the name of the draft partition to be assigned to the volume group.
220 - Applies when I(state=present).
221 - Supported from Storage Virtualize family systems 8.6.3.0 or later.
222 type: str
223 version_added: 2.5.0
224 nodrreplication:
225 description:
226 - If specified `True`, removes the volume group from the async-dr replication policy.
227 - I(nodrreplication) is mutually exclusive with parameters I(replicationpolicy) and I(noreplicationpolicy).
228 - Applies when I(state=present) to modify an existing volume group.
229 - Supported from Storage Virtualize family systems 8.7.1.0 or later.
230 type: bool
231 version_added: 2.6.0
232
233 author:
234 - Shilpi Jain(@Shilpi-J)
235 - Sanjaikumaar M (@sanjaikumaar)
236 - Sumit Kumar Gupta (@sumitguptaibm)
237 - Sandip G. Rajbanshi (@Sandip-Rajbanshi)
238 notes:
239 - This module supports C(check_mode).
240 - Safeguarded policy and snapshot policy cannot be used at the same time.
241 Therefore, the parameters I(snapshotpolicy) and I(safeguardpolicyname) are mutually exclusive.
242 - This module supports logging in via partition IP.
243 '''
244
245 EXAMPLES = '''
246 - name: Create a new volume group
247 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
248 clustername: "{{ clustername }}"
249 domain: "{{ domain }}"
250 username: "{{ username }}"
251 password: "{{ password }}"
252 log_path: /tmp/playbook.debug
253 name: vg0
254 state: present
255 - name: Delete a volume group
256 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
257 clustername: "{{ clustername }}"
258 domain: "{{ domain }}"
259 username: "{{ username }}"
260 password: "{{ password }}"
261 log_path: /tmp/playbook.debug
262 name: vg0
263 state: absent
264 - name: Update existing volume group to remove ownershipgroup and attach a safeguardpolicy to it
265 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
266 clustername: "{{ clustername }}"
267 domain: "{{ domain }}"
268 username: "{{ username }}"
269 password: "{{ password }}"
270 log_path: /tmp/playbook.debug
271 name: vg0
272 state: present
273 noownershipgroup: true
274 safeguardpolicyname: sg1
275 - name: Update volumegroup with snapshot policy and remove safeguarded policy
276 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
277 clustername: "{{ clustername }}"
278 domain: "{{ domain }}"
279 username: "{{ username }}"
280 password: "{{ password }}"
281 log_path: /tmp/playbook.debug
282 name: vg0
283 nosafeguardpolicy: true
284 snapshotpolicy: sp1
285 state: present
286 - name: Update volumegroup with safeguarded snapshot policy and ignoreuserfcmaps
287 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
288 clustername: "{{ clustername }}"
289 domain: "{{ domain }}"
290 username: "{{ username }}"
291 password: "{{ password }}"
292 log_path: /tmp/playbook.debug
293 name: vg0
294 safeguarded: true
295 snapshotpolicy: sp1
296 ignoreuserfcmaps: 'yes'
297 state: present
298 - name: Suspend snapshot policy in an existing volume group
299 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
300 clustername: "{{ clustername }}"
301 domain: "{{ domain }}"
302 username: "{{ username }}"
303 password: "{{ password }}"
304 log_path: /tmp/playbook.debug
305 name: vg0
306 snapshotpolicysuspended: true
307 state: present
308 - name: Create host accessible volume group from an existing snapshot
309 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
310 clustername: "{{ clustername }}"
311 domain: "{{ domain }}"
312 username: "{{ username }}"
313 password: "{{ password }}"
314 log_path: /tmp/playbook.debug
315 name: host_accessible_vg
316 type: clone
317 snapshot: snapshot0
318 fromsourcegroup: vg0
319 pool: Pool0
320 state: present
321 - name: Create a volumegroup thinclone from a list of volumes
322 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
323 clustername: "{{ clustername }}"
324 domain: "{{ domain }}"
325 username: "{{ username }}"
326 password: "{{ password }}"
327 log_path: /tmp/playbook.debug
328 name: vg0
329 type: thinclone
330 fromsourcevolumes: vol1:vol2
331 pool: Pool0
332 state: present
333 - name: Create a volumegroup clone from a list of volumes
334 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
335 clustername: "{{ clustername }}"
336 domain: "{{ domain }}"
337 username: "{{ username }}"
338 password: "{{ password }}"
339 log_path: /tmp/playbook.debug
340 name: vg0
341 type: clone
342 fromsourcevolumes: vol1:vol2
343 pool: Pool0
344 state: present
345 - name: Convert a thinclone volumegroup to clone
346 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
347 clustername: "{{ clustername }}"
348 domain: "{{ domain }}"
349 username: "{{ username }}"
350 password: "{{ password }}"
351 log_path: /tmp/playbook.debug
352 name: vg0
353 type: clone
354 state: present
355 - name: Delete a volume group, keeping volumes which were associated with volumegroup
356 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
357 clustername: "{{ clustername }}"
358 domain: "{{ domain }}"
359 username: "{{ username }}"
360 password: "{{ password }}"
361 log_path: /tmp/playbook.debug
362 name: vg0
363 state: absent
364 evictvolumes: true
365 - name: Add new or existing volumegroup to a draft partition
366 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
367 clustername: "{{ clustername }}"
368 domain: "{{ domain }}"
369 username: "{{ username }}"
370 password: "{{ password }}"
371 log_path: /tmp/playbook.debug
372 name: vg0
373 state: present
374 draftpartition: partition_name
375 - name: Remove DR replication-policy from volume group
376 ibm.storage_virtualize.ibm_svc_manage_volumegroup:
377 clustername: "{{ clustername }}"
378 domain: "{{ domain }}"
379 username: "{{ username }}"
380 password: "{{ password }}"
381 log_path: /tmp/playbook.debug
382 name: vg0
383 state: absent
384 nodrreplication: true
385 '''
386
387 RETURN = '''#'''
388
389 from traceback import format_exc
390 from ansible.module_utils.basic import AnsibleModule
391 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import \
392 IBMSVCRestApi, svc_argument_spec, get_logger, strtobool
393 from ansible.module_utils._text import to_native
394 import random
395
396
397 class IBMSVCVG(object):
398 def __init__(self):
399 argument_spec = svc_argument_spec()
400
401 argument_spec.update(
402 dict(
403 name=dict(type='str', required=True),
404 state=dict(type='str', required=True, choices=['absent',
405 'present']),
406 ownershipgroup=dict(type='str', required=False),
407 noownershipgroup=dict(type='bool', required=False),
408 safeguardpolicyname=dict(type='str', required=False),
409 nosafeguardpolicy=dict(type='bool', required=False),
410 policystarttime=dict(type='str', required=False),
411 snapshotpolicy=dict(type='str', required=False),
412 nosnapshotpolicy=dict(type='bool', required=False),
413 snapshotpolicysuspended=dict(type='str', choices=['yes', 'no']),
414 type=dict(type='str', choices=['clone', 'thinclone']),
415 snapshot=dict(type='str'),
416 fromsourcegroup=dict(type='str'),
417 fromsourcevolumes=dict(type='str', required=False),
418 pool=dict(type='str'),
419 iogrp=dict(type='str'),
420 safeguarded=dict(type='bool', default=False),
421 ignoreuserfcmaps=dict(type='str', choices=['yes', 'no']),
422 replicationpolicy=dict(type='str'),
423 noreplicationpolicy=dict(type='bool'),
424 old_name=dict(type='str', required=False),
425 partition=dict(type='str'),
426 evictvolumes=dict(type='bool'),
427 draftpartition=dict(type='str'),
428 nodrreplication=dict(type='bool')
429 )
430 )
431
432 self.module = AnsibleModule(argument_spec=argument_spec,
433 supports_check_mode=True)
434
435 # logging setup
436 log_path = self.module.params['log_path']
437 log = get_logger(self.__class__.__name__, log_path)
438 self.log = log.info
439
440 # Required
441 self.name = self.module.params['name']
442 self.state = self.module.params['state']
443
444 # Optional
445 self.ownershipgroup = self.module.params.get('ownershipgroup', '')
446 self.noownershipgroup = self.module.params.get('noownershipgroup', False)
447 self.policystarttime = self.module.params.get('policystarttime', '')
448 self.snapshotpolicy = self.module.params.get('snapshotpolicy', '')
449 self.nosnapshotpolicy = self.module.params.get('nosnapshotpolicy', False)
450 self.snapshotpolicysuspended = self.module.params.get('snapshotpolicysuspended', '')
451 self.type = self.module.params.get('type', '')
452 self.snapshot = self.module.params.get('snapshot', '')
453 self.fromsourcegroup = self.module.params.get('fromsourcegroup', '')
454 self.fromsourcevolumes = self.module.params.get('fromsourcevolumes', '')
455 self.pool = self.module.params.get('pool', '')
456 self.iogrp = self.module.params.get('iogrp', '')
457 self.safeguardpolicyname = self.module.params.get('safeguardpolicyname', '')
458 self.nosafeguardpolicy = self.module.params.get('nosafeguardpolicy', False)
459 self.safeguarded = self.module.params.get('safeguarded', False)
460 self.ignoreuserfcmaps = self.module.params.get('ignoreuserfcmaps', '')
461 self.replicationpolicy = self.module.params.get('replicationpolicy', '')
462 self.noreplicationpolicy = self.module.params.get('noreplicationpolicy', False)
463 self.old_name = self.module.params.get('old_name', '')
464 self.partition = self.module.params.get('partition', '')
465 self.evictvolumes = self.module.params.get('evictvolumes', False)
466 self.draftpartition = self.module.params.get('draftpartition', '')
467 self.nodrreplication = self.module.params.get('nodrreplication', False)
468
469 # Dynamic variable
470 self.parentuid = None
471 self.changed = False
472 self.msg = ''
473
474 self.basic_checks()
475
476 self.restapi = IBMSVCRestApi(
477 module=self.module,
478 clustername=self.module.params['clustername'],
479 domain=self.module.params['domain'],
480 username=self.module.params['username'],
481 password=self.module.params['password'],
482 validate_certs=self.module.params['validate_certs'],
483 log_path=log_path,
484 token=self.module.params['token']
485 )
486
487 def basic_checks(self):
488 changed = False
489 if not self.name:
490 self.module.fail_json(msg='Missing mandatory parameter: name')
491
492 if self.state == 'present':
493 if self.policystarttime:
494 if not self.snapshotpolicy and not self.safeguardpolicyname:
495 self.module.fail_json(
496 msg='Either `snapshotpolicy` or `safeguardpolicyname` should be passed along with `policystarttime`.'
497 )
498 if self.safeguarded:
499 if not self.snapshotpolicy:
500 self.module.fail_json(
501 msg='Parameter `safeguarded` should be passed along with `snapshotpolicy`'
502 )
503 if self.evictvolumes is not None:
504 self.module.fail_json(
505 msg='Parameter `evictvolumes` should be passed only while removing volumegroup'
506 )
507 elif self.state == 'absent':
508 unwanted = ('ownershipgroup', 'noownershipgroup', 'safeguardpolicyname',
509 'nosafeguardpolicy', 'snapshotpolicy', 'nosnapshotpolicy',
510 'policystarttime', 'type', 'fromsourcegroup', 'pool', 'iogrp',
511 'safeguarded', 'ignoreuserfcmaps', 'replicationpolicy',
512 'noreplicationpolicy', 'old_name', 'fromsourcevolumes', 'draftpartition', 'nodrreplication')
513
514 param_exists = ', '.join((param for param in unwanted if getattr(self, param)))
515
516 if param_exists:
517 self.module.fail_json(
518 msg='State=absent but following parameter(s) exist: {0}'.format(param_exists),
519 changed=changed
520 )
521 else:
522 self.module.fail_json(msg='State should be either present or absent')
523
524 def parameter_handling_while_renaming(self):
525 parameters = {
526 "ownershipgroup": self.ownershipgroup,
527 "noownershipgroup": self.noownershipgroup,
528 "replicationpolicy": self.replicationpolicy,
529 "noreplicationpolicy": self.noreplicationpolicy,
530 "safeguardpolicyname": self.safeguardpolicyname,
531 "nosafeguardpolicy": self.nosafeguardpolicy,
532 "snapshotpolicy": self.snapshotpolicy,
533 "nosnapshotpolicy": self.nosnapshotpolicy,
534 "partition": self.partition,
535 "fromsourcevolumes": self.fromsourcevolumes,
536 "nodrreplication": self.nodrreplication
537 }
538 parameters_exists = [parameter for parameter, value in parameters.items() if value]
539 if parameters_exists:
540 self.module.fail_json(msg="Parameters {0} not supported while renaming a volume group.".format(', '.join(parameters_exists)))
541
542 def create_validation(self):
543 mutually_exclusive = (
544 ('ownershipgroup', 'safeguardpolicyname'),
545 ('ownershipgroup', 'snapshotpolicy'),
546 ('ownershipgroup', 'policystarttime'),
547 ('snapshotpolicy', 'safeguardpolicyname'),
548 ('replicationpolicy', 'noreplicationpolicy'),
549 ('draftpartition', 'partition'),
550 ('replicationpolicy', 'nodrreplication'),
551 ('noreplicationpolicy', 'nodrreplication')
552 )
553
554 for param1, param2 in mutually_exclusive:
555 if getattr(self, param1) and getattr(self, param2):
556 self.module.fail_json(
557 msg='Mutually exclusive parameters: {0}, {1}'.format(param1, param2)
558 )
559
560 unsupported = ('nosafeguardpolicy', 'noownershipgroup', 'nosnapshotpolicy',
561 'snapshotpolicysuspended', 'noreplicationpolicy', 'nodrreplication')
562 unsupported_exists = ', '.join((field for field in unsupported if getattr(self, field)))
563
564 if unsupported_exists:
565 self.module.fail_json(
566 msg='Following parameters not supported during creation scenario: {0}'.format(unsupported_exists)
567 )
568
569 def update_validation(self, data):
570 mutually_exclusive = (
571 ('ownershipgroup', 'noownershipgroup'),
572 ('safeguardpolicyname', 'nosafeguardpolicy'),
573 ('ownershipgroup', 'safeguardpolicyname'),
574 ('ownershipgroup', 'snapshotpolicy'),
575 ('ownershipgroup', 'policystarttime'),
576 ('nosafeguardpolicy', 'nosnapshotpolicy'),
577 ('snapshotpolicy', 'nosnapshotpolicy'),
578 ('snapshotpolicy', 'safeguardpolicyname'),
579 ('replicationpolicy', 'nodrreplication'),
580 ('noreplicationpolicy', 'nodrreplication')
581 )
582
583 for param1, param2 in mutually_exclusive:
584 if getattr(self, param1) and getattr(self, param2):
585 self.module.fail_json(
586 msg='Mutually exclusive parameters: {0}, {1}'.format(param1, param2)
587 )
588
589 if self.type:
590 # converttoclone accepts only type=clone, so update validation will include that
591 if self.type == 'clone':
592 invalids_while_converting_to_clone = ('safeguardpolicyname', 'nosafeguardpolicy', 'ownershipgroup',
593 'snapshotpolicy', 'policystarttime', 'nosnapshotpolicy',
594 'replicationpolicy', 'nodrreplication', 'noreplicationpolicy')
595 invalid_params_for_convert_to_clone = ', '.join((param for param in invalids_while_converting_to_clone
596 if getattr(self, param)))
597
598 if invalid_params_for_convert_to_clone:
599 self.module.fail_json(
600 msg='Following parameter(s) are invalid while converting thinclone volumegroup to clone: {0}'
601 .format(invalid_params_for_convert_to_clone)
602 )
603 else:
604 # If type=thinclone (or some invalid value) was passed, return error.
605 self.module.fail_json(
606 msg='type = {0} is invalid for updating volumegroup. Only type = clone is supported.'
607 .format(self.type)
608 )
609
610 unsupported_maps = (
611 ('snapshot', data.get('source_snapshot', '')),
612 ('fromsourcevolumes', data.get('source_volumes_set', '')),
613 ('fromsourcegroup', data.get('source_volume_group_name', '')),
614 ('partition', data.get('partition_name', ''))
615 )
616 unsupported = (
617 fields[0] for fields in unsupported_maps if getattr(self, fields[0]) and getattr(self, fields[0]) != fields[1]
618 )
619 unsupported_exists = ', '.join(unsupported)
620
621 if unsupported_exists:
622 self.module.fail_json(
623 msg='Following parameters not supported during update: {0}'.format(unsupported_exists)
624 )
625
626 def get_existing_vg(self, vg_name):
627 merged_result = {}
628
629 data = self.restapi.svc_obj_info(cmd='lsvolumegroup', cmdopts=None,
630 cmdargs=['-gui', vg_name])
631
632 if isinstance(data, list):
633 for d in data:
634 merged_result.update(d)
635 else:
636 merged_result = data
637
638 if merged_result and ((self.snapshotpolicy and self.policystarttime) or self.snapshotpolicysuspended):
639 # Making new call as snapshot_policy_start_time not available in lsvolumegroup CLI
640 SP_data = self.restapi.svc_obj_info(
641 cmd='lsvolumegroupsnapshotpolicy',
642 cmdopts=None,
643 cmdargs=[self.name]
644 )
645 merged_result['snapshot_policy_start_time'] = SP_data['snapshot_policy_start_time']
646 merged_result['snapshot_policy_suspended'] = SP_data['snapshot_policy_suspended']
647
648 # Make new call as volume list is not present in lsvolumegroup CLI
649 # If existing volumegroup is a thinclone but command params don't contain
650 # [type], that is also considered as an attempt to create/change an already
651 # existing volume. So, it should be recorded to throw error later.
652 is_existing_vg_thinclone = False
653
654 if merged_result and merged_result.get('volume_group_type') == 'thinclone':
655 is_existing_vg_thinclone = True
656 if merged_result and (self.type and self.fromsourcevolumes) or is_existing_vg_thinclone is True:
657 volumes_data = []
658 if self.type == "thinclone" or is_existing_vg_thinclone is True:
659 cmd = 'lsvolumepopulation'
660 cmdopts = {"filtervalue": "volume_group_name={0}".format(self.name)}
661 volumes_data = self.restapi.svc_obj_info(cmd, cmdopts, cmdargs=None)
662 else:
663 # Source volumes for clone volumes needs to be fetched for verification
664 # 1. First get the volumes associated with volumegroup provided
665 associated_volumes_data = []
666 cmd = 'lsvdisk'
667 cmdopts = {"filtervalue": "volume_group_name={0}".format(self.name)}
668 associated_volumes_data = self.restapi.svc_obj_info(cmd, cmdopts, cmdargs=None)
669 vol_names = set()
670 for vol in associated_volumes_data:
671 vol_names.add(vol['name'])
672
673 # 2. Run lsvdisk for each volume provided in command to get source_volume_name
674 for volname in vol_names:
675 cmd = 'lsvdisk' + "/" + volname
676 cmdopts = None
677 cmdargs = None
678 single_vol_data = self.restapi.svc_obj_info(cmd, cmdopts, cmdargs=None)
679 if single_vol_data:
680 volumes_data.append(single_vol_data[0])
681
682 # Make a set from source volumes of all volumes
683 if volumes_data:
684 source_volumes_set = set()
685 source_volumes_pool_set = set()
686 for volume_data in volumes_data:
687 # Add the value of 'source_volume_name' to the merged_result
688 source_volumes_set.add(volume_data['source_volume_name'])
689 merged_result['source_volumes_set'] = source_volumes_set
690 # If pool is provided, verify that pool matches with the one provided in command
691 if self.pool:
692 cmd = 'lsvdisk'
693 cmdopts = {"filtervalue": "parent_mdisk_grp_name={0}".format(self.pool)}
694
695 vdisks_data = self.restapi.svc_obj_info(cmd, cmdopts, cmdargs=None)
696 remaining_vdisks = len(source_volumes_set)
697 for vdisk_data in vdisks_data:
698 if vdisk_data['name'] in source_volumes_set:
699 source_volumes_pool_set.add(vdisk_data['parent_mdisk_grp_name'])
700 remaining_vdisks = remaining_vdisks - 1
701 if remaining_vdisks == 0:
702 break
703
704 merged_result['source_volumes_pool_set'] = source_volumes_pool_set
705
706 return merged_result
707
708 def set_parentuid(self):
709 if self.snapshot and not self.fromsourcegroup:
710 cmdopts = {
711 "filtervalue": "snapshot_name={0}".format(self.snapshot)
712 }
713 data = self.restapi.svc_obj_info(
714 cmd='lsvolumesnapshot',
715 cmdopts=cmdopts,
716 cmdargs=None
717 )
718 try:
719 result = next(
720 filter(
721 lambda obj: obj['volume_group_name'] == '',
722 data
723 )
724 )
725 except StopIteration:
726 self.module.fail_json(
727 msg='Orphan Snapshot ({0}) does not exists for the given name'.format(self.snapshot)
728 )
729 else:
730 self.parentuid = result['parent_uid']
731
732 def vg_probe(self, data):
733 self.update_validation(data)
734 # Mapping the parameters with the existing data for comparision
735 params_mapping = (
736 ('ownershipgroup', data.get('owner_name', '')),
737 ('ignoreuserfcmaps', data.get('ignore_user_flash_copy_maps', '')),
738 ('replicationpolicy', data.get('replication_policy_name', '')),
739 ('noownershipgroup', not bool(data.get('owner_name', ''))),
740 ('nosafeguardpolicy', not bool(data.get('safeguarded_policy_name', ''))),
741 ('nosnapshotpolicy', not bool(data.get('snapshot_policy_name', ''))),
742 ('noreplicationpolicy', not bool(data.get('replication_policy_name', ''))),
743 ('partition', data.get('partition_name', '')),
744 ('draftpartition', data.get('draft_partition_name', '')),
745 ('nodrreplication', not bool(data.get('replication_policy_name', '')))
746 )
747
748 props = dict((k, getattr(self, k)) for k, v in params_mapping if getattr(self, k) and getattr(self, k) != v)
749
750 if self.safeguardpolicyname and self.safeguardpolicyname != data.get('safeguarded_policy_name', ''):
751 props['safeguardedpolicy'] = self.safeguardpolicyname
752 # If policy is changed, existing policystarttime will be erased so adding time without any check
753 if self.policystarttime:
754 props['policystarttime'] = self.policystarttime
755 elif self.safeguardpolicyname:
756 if self.policystarttime and self.policystarttime + '00' != data.get('safeguarded_policy_start_time', ''):
757 props['safeguardedpolicy'] = self.safeguardpolicyname
758 props['policystarttime'] = self.policystarttime
759 elif self.snapshotpolicy and self.snapshotpolicy != data.get('snapshot_policy_name', ''):
760 props['snapshotpolicy'] = self.snapshotpolicy
761 props['safeguarded'] = self.safeguarded
762 if self.policystarttime:
763 props['policystarttime'] = self.policystarttime
764 elif self.snapshotpolicy:
765 if self.policystarttime and self.policystarttime + '00' != data.get('snapshot_policy_start_time', ''):
766 props['snapshotpolicy'] = self.snapshotpolicy
767 props['policystarttime'] = self.policystarttime
768 if self.safeguarded not in ('', None) and self.safeguarded != strtobool(data.get('snapshot_policy_safeguarded', 0)):
769 props['snapshotpolicy'] = self.snapshotpolicy
770 props['safeguarded'] = self.safeguarded
771
772 if self.draftpartition:
773 if "draftpartition" in props and props["draftpartition"] == data.get('partition_name'):
774 props.pop("draftpartition")
775 self.log("Partition [%s] which contains Volumegroup [%s] is already published.", self.draftpartition, self.name)
776 elif self.draftpartition == data.get("draft_partition_name"):
777 self.log("Partition [%s] which contains Volumegroup [%s] is already in draft state.", self.draftpartition, self.name)
778
779 # Adding snapshotpolicysuspended to props
780 if self.snapshotpolicysuspended and self.snapshotpolicysuspended != data.get('snapshot_policy_suspended', ''):
781 props['snapshotpolicysuspended'] = self.snapshotpolicysuspended
782
783 if self.type and self.type != data.get('volume_group_type'):
784 # Handle cases other than '' to clone
785 if not (data.get('volume_group_type') == '' and self.type == 'clone'):
786 props['type'] = self.type
787
788 self.log("volumegroup props = %s", props)
789
790 return props
791
792 def create_transient_snapshot(self):
793 # Required parameters
794 snapshot_cmd = 'addsnapshot'
795 snapshot_opts = {}
796 random_number = ''.join(random.choices('0123456789', k=10))
797 snapshot_name = f"snapshot_{random_number}"
798 snapshot_opts['name'] = snapshot_name
799
800 # Optional parameters
801 snapshot_opts['pool'] = self.module.params.get('pool', '')
802 snapshot_opts['volumes'] = self.module.params.get('fromsourcevolumes', '')
803 snapshot_opts['retentionminutes'] = 5
804
805 self.restapi.svc_run_command(snapshot_cmd, snapshot_opts, cmdargs=None, timeout=10)
806 return snapshot_name
807
808 def vg_create(self):
809 self.create_validation()
810 if self.module.check_mode:
811 self.changed = True
812 return
813
814 self.log("creating volume group '%s'", self.name)
815
816 # Make command
817 cmd = 'mkvolumegroup'
818 cmdopts = {
819 'name': self.name,
820 'safeguarded': self.safeguarded
821 }
822
823 if self.type:
824 optional_params = ('type', 'snapshot', 'pool')
825 cmdopts.update(
826 dict(
827 (param, getattr(self, param)) for param in optional_params if getattr(self, param)
828 )
829 )
830 if self.iogrp:
831 cmdopts['iogroup'] = self.iogrp
832
833 if self.fromsourcevolumes:
834 cmdopts['fromsourcevolumes'] = self.fromsourcevolumes
835 if not self.snapshot:
836 # If thinclone or clone is to be created from volumes, do following:
837 # 1. Create transient snapshot with 5-min retentionminutes
838 # 2. Create a thinclone volumegroup from this snapshot
839 # 3. There is no need to delete snapshot, as it is auto-managed due to retentionminutes
840 try:
841 self.snapshot = self.create_transient_snapshot()
842 cmdopts['snapshot'] = self.snapshot
843 except Exception as e:
844 self.log('Exception in creating transient snapshot: %s', format_exc())
845 self.module.fail_json(msg='Module failed. Error [%s].' % to_native(e))
846 self.set_parentuid()
847 if self.parentuid:
848 cmdopts['fromsourceuid'] = self.parentuid
849 elif self.fromsourcegroup:
850 cmdopts['fromsourcegroup'] = self.fromsourcegroup
851
852 if self.ignoreuserfcmaps:
853 if self.ignoreuserfcmaps == 'yes':
854 cmdopts['ignoreuserfcmaps'] = True
855 else:
856 cmdopts['ignoreuserfcmaps'] = False
857
858 if self.replicationpolicy:
859 cmdopts['replicationpolicy'] = self.replicationpolicy
860
861 if self.partition:
862 cmdopts['partition'] = self.partition
863 elif self.draftpartition:
864 cmdopts['draftpartition'] = self.draftpartition
865 if self.ownershipgroup:
866 cmdopts['ownershipgroup'] = self.ownershipgroup
867 elif self.safeguardpolicyname:
868 cmdopts['safeguardedpolicy'] = self.safeguardpolicyname
869 if self.policystarttime:
870 cmdopts['policystarttime'] = self.policystarttime
871 elif self.snapshotpolicy:
872 cmdopts['snapshotpolicy'] = self.snapshotpolicy
873 if self.policystarttime:
874 cmdopts['policystarttime'] = self.policystarttime
875
876 self.log("creating volumegroup '%s'", cmdopts)
877
878 # Run command
879 result = self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
880 self.log("create volume group result %s", result)
881 # Any error would have been raised in svc_run_command
882 self.changed = True
883
884 def vg_update(self, modify):
885 if 'type' in modify and modify['type'] != "clone":
886 self.module.fail_json(msg='Only type=clone is supported for updating volumegroup.')
887 if self.module.check_mode:
888 self.changed = True
889 return
890
891 # update the volume group
892 self.log("updating volume group '%s' ", self.name)
893 cmdopts = dict()
894 cmdargs = [self.name]
895
896 try:
897 del modify['snapshotpolicysuspended']
898 except KeyError:
899 self.log("snapshotpolicysuspended modification not required!!")
900 else:
901 cmd = 'chvolumegroupsnapshotpolicy'
902 cmdopts = {'snapshotpolicysuspended': self.snapshotpolicysuspended}
903 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
904
905 if modify.get('type') == "clone":
906 # Run converttoclone command
907 cmd = 'converttoclone'
908 cmdopts['volumegroup'] = self.name
909 cmdargs = None
910 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
911 self.log("Volumegroup %s converted from thinclone to clone!!", self.name)
912 else:
913 cmd = 'chvolumegroup'
914 unmaps = ('noownershipgroup', 'nosafeguardpolicy', 'nosnapshotpolicy', 'noreplicationpolicy', 'nodrreplication')
915 for field in unmaps:
916 cmdopts = {}
917 if field == 'nosafeguardpolicy' and field in modify:
918 cmdopts['nosafeguardedpolicy'] = modify.pop('nosafeguardpolicy')
919 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
920 elif field in modify:
921 cmdopts[field] = modify.pop(field)
922 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
923
924 if modify:
925 cmdopts = modify
926 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
927
928 # Any error would have been raised in svc_run_command
929 self.changed = True
930
931 def vg_delete(self):
932 if self.module.check_mode:
933 self.changed = True
934 return
935
936 self.log("deleting volume group '%s'", self.name)
937
938 cmd = 'rmvolumegroup'
939 cmdopts = {}
940 cmdargs = [self.name]
941 if self.evictvolumes is not None:
942 cmdopts['evictvolumes'] = self.evictvolumes
943
944 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
945 # Any error will have been raised in svc_run_command
946 self.changed = True
947
948 def vg_rename(self, vg_data):
949 msg = ''
950 self.parameter_handling_while_renaming()
951 old_vg_data = self.get_existing_vg(self.old_name)
952
953 if not old_vg_data and not vg_data:
954 self.module.fail_json(msg="Volume group with old name {0} doesn't exist.".format(self.old_name))
955 elif old_vg_data and vg_data:
956 self.module.fail_json(msg="Volume group [{0}] already exists.".format(self.name))
957 elif not old_vg_data and vg_data:
958 msg = "Volume group with name [{0}] already exists.".format(self.name)
959 elif old_vg_data and not vg_data:
960 # when check_mode is enabled
961 if self.module.check_mode:
962 self.changed = True
963 return
964 self.restapi.svc_run_command('chvolumegroup', {'name': self.name}, [self.old_name])
965 self.changed = True
966 msg = "Volume group [{0}] has been successfully rename to [{1}].".format(self.old_name, self.name)
967 return msg
968
969 def apply(self):
970 vg_data = self.get_existing_vg(self.name)
971
972 if self.state == 'present' and self.old_name:
973 self.msg = self.vg_rename(vg_data)
974 elif self.state == 'absent' and self.old_name:
975 self.module.fail_json(msg="Rename functionality is not supported when 'state' is absent.")
976 else:
977 if vg_data:
978 if self.state == 'present':
979 is_existing_vg_thinclone = False
980 existing_vg_type = vg_data.get('volume_group_type')
981 if existing_vg_type == 'thinclone':
982 is_existing_vg_thinclone = True
983
984 if self.type and not self.fromsourcevolumes:
985 modify = self.vg_probe(vg_data)
986 if modify:
987 self.vg_update(modify)
988 self.msg = "Volume group [%s] has been modified." % self.name
989 else:
990 self.msg = "No Modifications detected."
991 else:
992 if (self.type and self.fromsourcevolumes) or is_existing_vg_thinclone is True:
993 # Check whether provided source volumes are same as in existing volumegroup
994 volumes_with_existing_vg = None
995 if 'source_volumes_set' in vg_data:
996 volumes_with_existing_vg = vg_data['source_volumes_set']
997 provided_volumes_set = set()
998 if self.fromsourcevolumes:
999 provided_volumes_set = set(self.fromsourcevolumes.split(":"))
1000 if volumes_with_existing_vg or provided_volumes_set:
1001 self.changed = False
1002 if not provided_volumes_set and volumes_with_existing_vg:
1003 self.module.fail_json(
1004 msg="Existing thinclone volumegroup found.",
1005 changed=self.changed
1006 )
1007 if volumes_with_existing_vg != provided_volumes_set:
1008 self.module.fail_json(
1009 msg="Parameter [fromsourcevolumes] is invalid for modifying volumegroup.",
1010 changed=self.changed
1011 )
1012 elif self.pool and vg_data['source_volumes_pool_set'] and (list(vg_data['source_volumes_pool_set'])[0] != self.pool):
1013 self.module.fail_json(
1014 msg="Parameter [pool] is invalid for modifying volumegroup.",
1015 changed=self.changed
1016 )
1017 else:
1018 self.msg = "A volumegroup with name [%s] already exists." % self.name
1019 else:
1020 modify = self.vg_probe(vg_data)
1021 if modify:
1022 self.vg_update(modify)
1023 self.msg = "Volume group [%s] has been modified." % self.name
1024 else:
1025 self.msg = "No Modifications detected, Volume group already exists."
1026 else:
1027 self.vg_delete()
1028 self.msg = "Volume group [%s] has been deleted." % self.name
1029 else:
1030 if self.state == 'absent':
1031 self.msg = "Volume group [%s] does not exist." % self.name
1032 else:
1033 self.vg_create()
1034 self.msg = "Volume group [%s] has been created." % self.name
1035
1036 if self.module.check_mode:
1037 self.msg = 'skipping changes due to check mode.'
1038
1039 self.module.exit_json(msg=self.msg, changed=self.changed)
1040
1041
1042 def main():
1043 v = IBMSVCVG()
1044 try:
1045 v.apply()
1046 except Exception as e:
1047 v.log("Exception in apply(): \n%s", format_exc())
1048 v.module.fail_json(msg="Module failed. Error [%s]." % to_native(e))
1049
1050
1051 if __name__ == '__main__':
1052 main()