Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (C) 2021 IBM CORPORATION
5 # Author(s): Sandip Gulab Rajbanshi <[email protected]>
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11 DOCUMENTATION = r'''
12 ---
13 module: ibm_sv_manage_clone
14 short_description: This module manages clone and thinclone of volume and volumegroup
15 version_added: '3.2.0'
16 description:
17 - Ansible interface to manage 'mkvolume' and 'mkvolumegroup' clone commands.
18 options:
19 clustername:
20 description:
21 - The hostname, management IP or partition IP of the Storage Virtualize system.
22 required: true
23 type: str
24 domain:
25 description:
26 - Domain for the Storage Virtualize system.
27 - Valid when hostname is used for the parameter I(clustername).
28 type: str
29 username:
30 description:
31 - REST API username for the Storage Virtualize system.
32 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
33 type: str
34 password:
35 description:
36 - REST API password 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 token:
40 description:
41 - The authentication token to verify a user on the Storage Virtualize system.
42 - To generate a token, use the M(ibm.storage_virtualize.ibm_svc_auth) module.
43 type: str
44 log_path:
45 description:
46 - Path of debug log file.
47 type: str
48 state:
49 description:
50 - Creates (C(present)) or removes (C(absent)) the clone object.
51 choices: [ 'absent', 'present' ]
52 required: true
53 type: str
54 name:
55 description:
56 - Specifies a name for the new clone.
57 required: true
58 type: str
59 pool:
60 description:
61 - Specifies the name of the storage pool to use while creating the clone.
62 - The parameters I(pool) is mandatory for clone volumes and optional for clone volume groups while
63 creating clone.
64 type: str
65 iogrp:
66 description:
67 - Specifies the name of the I/O group for the new clone.
68 type: str
69 volumegroup:
70 description:
71 - Specifies the name of the volumegroup to which the clone is to be added.
72 - When logging in via partition IP, the I(volumegroup) parameter is required to create a volume clone.
73 type: str
74 type:
75 description:
76 - Specifies the type of clone to create. Volume can be thinclone or clone type.
77 choices: [ 'clone', 'thinclone' ]
78 type: str
79 fromsourcevolumes:
80 description:
81 - Specifies colon-separated list of the parent volumes name/UID.
82 - The parameters I(fromsourcevolumes) is mandatory for clone volumes and optional for clone volume groups
83 while creating clone.
84 type: str
85 snapshot:
86 description:
87 - Specifies the name of the snapshot that is used to create the clone.
88 - The parameters I(fromsourcevolumes) is mandatory for creating clone.
89 type: str
90 preferrednode:
91 description:
92 - Specifies the preferred node that is used to access the volume.
93 type: str
94 partition:
95 description:
96 - Specifies the name of the storage partition to be assigned to the volume group.
97 type: str
98 ownershipgroup:
99 description:
100 - Specifies the name of the ownership group to which the object is being added.
101 type: str
102 ignoreuserfcmaps:
103 description:
104 - Indicates that snapshots can be created with the scheduler or with the addsnapshot command,
105 if any volumes in the volume group are used as a source volume in legacy FlashCopy mapping.
106 choices: [ 'yes', 'no' ]
107 type: str
108 validate_certs:
109 description:
110 - Validates certification.
111 default: false
112 type: bool
113 author:
114 - Sandip G. Rajbanshi (@Sandip-Rajbanshi)
115 notes:
116 - This module supports C(check_mode).
117 - This module currently only supports the creation of clone volume or volumegroup (C(state=present)).
118 - Support for updating or removing these clone objects may be added in a future release. For updating (converting
119 thinclone to clone) or removing thinclone or clone for volume and volumegroup, use the I(ibm_svc_manage_volume) or
120 I(ibm_svc_manage_volumegroup) modules, respectively.
121 - This module supports log-in via partition-ip.
122 '''
123
124 EXAMPLES = r'''
125 - name: Create a clone of a volume from snapshot
126 ibm.storage_virtualize.ibm_sv_manage_clone:
127 clustername: "{{ clustername }}"
128 domain: "{{ domain }}"
129 username: "{{ username }}"
130 password: "{{ password }}"
131 log_path: "{{ log_path }}"
132 name: "vol1_clone_1"
133 state: "present"
134 pool: "pool1"
135 type: "clone"
136 snapshot: "snapshot1"
137 fromsourcevolumes: "vol1"
138 iogrp: "io_grp0"
139 preferrednode: "node1"
140 volumegroup: "Vg1"
141 - name: Create a clone of a volumegroup from snapshot
142 ibm.storage_virtualize.ibm_sv_manage_clone:
143 clustername: "{{ clustername }}"
144 domain: "{{ domain }}"
145 username: "{{ username }}"
146 password: "{{ password }}"
147 log_path: "{{ log_path }}"
148 name: "vg1_clone_1"
149 state: "present"
150 pool: "pool1"
151 type: "clone"
152 snapshot: "snapshot1"
153 iogrp: "io_grp0"
154 partition: "ptn1"
155 ownershipgroup: "grp1"
156 - name: Create a clone of volume vector from snapshot
157 ibm.storage_virtualize.ibm_sv_manage_clone:
158 clustername: "{{ clustername }}"
159 domain: "{{ domain }}"
160 username: "{{ username }}"
161 password: "{{ password }}"
162 log_path: "{{ log_path }}"
163 name: "vg1_clone_1"
164 state: "present"
165 fromsourcevolumes: "vol1:vol2:vol3"
166 pool: "pool1"
167 type: "clone"
168 snapshot: "snapshot1"
169 iogrp: "io_grp0"
170 partition: "ptn1"
171 ownershipgroup: "grp1"
172 '''
173
174 RETURN = '''#'''
175
176 from traceback import format_exc
177 from ansible.module_utils.basic import AnsibleModule
178 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import (
179 IBMSVCRestApi,
180 svc_argument_spec,
181 get_logger
182 )
183 from ansible.module_utils._text import to_native
184
185
186 class IBMSVClone(object):
187 def __init__(self):
188 argument_spec = svc_argument_spec()
189
190 argument_spec.update(
191 dict(
192 name=dict(type='str', required=True),
193 state=dict(type='str', required=True, choices=['absent', 'present']),
194 pool=dict(type='str', required=False),
195 iogrp=dict(type='str', required=False),
196 volumegroup=dict(type='str', required=False),
197 type=dict(type='str', required=False, choices=['clone', 'thinclone']),
198 fromsourcevolumes=dict(type='str', required=False),
199 log_path=dict(type='str', required=False),
200 snapshot=dict(type='str', required=False),
201 preferrednode=dict(type='str', required=False),
202 partition=dict(type='str', required=False),
203 ownershipgroup=dict(type='str', required=False),
204 ignoreuserfcmaps=dict(type='str', required=False, choices=['yes', 'no'])
205 )
206 )
207
208 self.module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
209
210 # logging setup
211 log_path = self.module.params['log_path']
212 log = get_logger(self.__class__.__name__, log_path)
213 self.log = log.info
214
215 # Required Parameters
216 self.name = self.module.params['name']
217 self.state = self.module.params['state']
218
219 # Optional Parameters
220 self.pool = self.module.params.get('pool', "")
221 self.iogrp = self.module.params.get('iogrp', "")
222 self.volumegroup = self.module.params.get('volumegroup', "")
223 self.type = self.module.params.get('type', "")
224 self.fromsourcevolumes = self.module.params.get('fromsourcevolumes', "")
225 self.fromsourcevolumes_list = self.fromsourcevolumes.split(':') if self.fromsourcevolumes else []
226 self.snapshot = self.module.params.get('snapshot', "")
227 self.preferrednode = self.module.params.get('preferrednode', "")
228 self.partition = self.module.params.get('partition', "")
229 self.ownershipgroup = self.module.params.get('ownershipgroup', "")
230 self.ignoreuserfcmaps = self.module.params.get('ignoreuserfcmaps', "")
231
232 # internal variable
233 self.changed = False
234 self.msg = ""
235 self.OBJECT_TYPE = None
236
237 self.basic_checks()
238
239 self.restapi = IBMSVCRestApi(
240 module=self.module,
241 clustername=self.module.params['clustername'],
242 domain=self.module.params['domain'],
243 username=self.module.params['username'],
244 password=self.module.params['password'],
245 validate_certs=self.module.params['validate_certs'],
246 log_path=log_path,
247 token=self.module.params['token']
248 )
249
250 def basic_checks(self):
251 if len(self.fromsourcevolumes_list) == 1:
252 self.OBJECT_TYPE = 'volume'
253 else:
254 self.OBJECT_TYPE = 'volumegroup'
255 if self.state == 'present':
256 if self.OBJECT_TYPE == 'volume':
257 invalids = ('partition', 'ownershipgroup', 'ignoreuserfcmaps')
258 invalid_exists = ', '.join((var for var in invalids if not getattr(self, var) in {'', None}))
259 if invalid_exists:
260 self.module.fail_json(
261 msg='Volume clone operation does not support the parameter(s): {0}'.format(invalid_exists)
262 )
263 else:
264 invalids = ('volumegroup', 'preferrednode')
265 invalid_exists = ', '.join((var for var in invalids if not getattr(self, var) in {'', None}))
266 if invalid_exists:
267 self.module.fail_json(
268 msg='Volumegroup clone operation does not support the parameter(s): {0}'.format(invalid_exists)
269 )
270 else:
271 self.module.fail_json(
272 msg="Removal of clone is not supported via this module. Please use ibm_svc_manage_volume or"
273 " ibm_svc_manage_volumegroup for removing volume or volumegroup clone/thinclone respectively.")
274
275 def get_existing_clone(self):
276 merged_result = {}
277 cmd = "lsvdisk" if self.OBJECT_TYPE == "volume" else "lsvolumegroup"
278 data = self.restapi.svc_obj_info(cmd, {"bytes": True}, [self.name])
279
280 if isinstance(data, list):
281 for d in data:
282 merged_result.update(d)
283 else:
284 merged_result = data
285 return merged_result
286
287 # Funciton to check whether all volumes inside the volumegroup belonging to the same pool
288 def check_volumes_in_pool(self, vg_name, pool_name):
289 vol_list = self.restapi.svc_obj_info("lsvdisk", {"filtervalue" : "volume_group_name=%s" % vg_name}, [])
290 for vol in vol_list:
291 if self.fromsourcevolumes_list and vol.get("name") not in self.fromsourcevolumes_list:
292 continue
293 if pool_name != vol.get("mdisk_grp_name"):
294 self.log("One or more volumes belonging to volumegroup (%s) are in different pool", vg_name)
295 return False
296 return True
297
298 def get_parent_uid_or_source_grp_from_snapshot(self):
299 parent_uid = None
300 source_grp_name = None
301 if self.OBJECT_TYPE == "volume":
302 snapshot_data = self.restapi.svc_obj_info(
303 'lsvolumesnapshot', {'filtervalue': "snapshot_name=%s" % self.snapshot}, []
304 )
305 if snapshot_data:
306 source_grp_name = snapshot_data[0].get('volume_group_name')
307 parent_uid = snapshot_data[0].get('parent_uid')
308 else:
309 snapshot_data = self.restapi.svc_obj_info(
310 'lsvolumegroupsnapshot', {}, []
311 )
312 for snapshot in snapshot_data:
313 if snapshot.get('name') == self.snapshot:
314 source_grp_name = snapshot.get('volume_group_name')
315 parent_uid = snapshot.get('parent_uid')
316 break
317 if not parent_uid:
318 self.module.fail_json(
319 msg="Snapshot %s does not exist." % self.snapshot
320 )
321 if source_grp_name:
322 return (source_grp_name, None)
323 return (None, parent_uid)
324
325 def create_validation(self):
326 required_params = {
327 "snapshot": self.snapshot,
328 "type": self.type
329 }
330 if self.OBJECT_TYPE == 'volume':
331 required_params["pool"] = self.pool
332
333 missing = [k for k, v in required_params.items() if not v]
334
335 if missing:
336 self.module.fail_json(
337 msg="Following parameters are required while creating clone: {}".format(
338 ", ".join(missing)
339 )
340 )
341
342 def create_clone(self):
343 self.create_validation()
344 cmdopts = {
345 'name': self.name,
346 'type': self.type,
347 'snapshot': self.snapshot,
348 }
349 source_grp_name, parent_uid = self.get_parent_uid_or_source_grp_from_snapshot()
350 if source_grp_name:
351 cmdopts['fromsourcegroup'] = source_grp_name
352 elif parent_uid:
353 cmdopts['fromsourceuid'] = parent_uid
354
355 if self.OBJECT_TYPE == 'volume':
356 cmd = 'mkvolume'
357 cmdopts['fromsourcevolume'] = self.fromsourcevolumes
358 if self.iogrp:
359 cmdopts['iogrp'] = self.iogrp
360 else:
361 cmd = 'mkvolumegroup'
362 if self.fromsourcevolumes:
363 cmdopts['fromsourcevolumes'] = self.fromsourcevolumes
364 if self.iogrp:
365 cmdopts['iogroup'] = self.iogrp
366
367 # Optional fields (add only if defined)
368 optional_fields = {
369 'pool': self.pool,
370 'volumegroup': self.volumegroup,
371 'preferrednode': self.preferrednode,
372 'partition': self.partition,
373 'ownershipgroup': self.ownershipgroup,
374 'ignoreuserfcmaps': self.ignoreuserfcmaps,
375 }
376
377 for key, value in optional_fields.items():
378 if value:
379 cmdopts[key] = value
380
381 # Execute the command
382 self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
383 self.log('Clone (%s) created successfully.', self.name)
384 self.changed = True
385
386 def probe(self, clone_data):
387 params_mapping = (
388 ('ownershipgroup', clone_data.get('owner_name', '')),
389 ('ignoreuserfcmaps', clone_data.get('ignore_user_fc_maps', '')),
390 ('volumegroup', clone_data.get('volumegroup_name', '')),
391 ('iogrp', clone_data.get('IO_group_name', '')),
392 ('partition', clone_data.get('partition_name', '')),
393 ('preferrednode', clone_data.get('preferred_node_name', '')),
394 ('pool', clone_data.get('mdisk_grp_name', '')),
395 ('snapshot', clone_data.get('source_snapshot', '')),
396 )
397
398 props = dict((k, getattr(self, k)) for k, v in params_mapping if getattr(self, k) and getattr(self, k) != v)
399 # Check for type changes if volume is present but type is different
400 if self.OBJECT_TYPE == 'volume':
401 if clone_data.get('source_volume_name') != self.fromsourcevolumes:
402 self.module.fail_json(
403 msg="Specified fromsourcevolumes does not match with existing clone's source volume."
404 )
405 else:
406 if 'pool' in props:
407 # volumegroup's pool cannot be changed after creation
408 if self.check_volumes_in_pool(self.name, self.pool):
409 del props['pool']
410
411 vol_type = clone_data.get('volume_type')
412 vg_type = clone_data.get('volume_group_type')
413 source_type = vol_type if vol_type is not None else vg_type
414
415 # Normalize empty ⇒ treat as "clone"
416 if source_type in ("", None):
417 source_type = "clone"
418
419 # Both conditions assign props['type'] = self.type
420 if (source_type == "clone" and self.type == "thinclone") or \
421 (source_type == "thinclone" and self.type == "clone"):
422 props["type"] = self.type
423 # If source type is clone, source_snapshot is not identifiable
424 if source_type == "clone":
425 if "source_snapshot" in props:
426 del props["source_snapshot"]
427 return props
428
429 def apply(self):
430 clone_data = self.get_existing_clone()
431 if clone_data:
432 self.log("Existing clone data: %s", clone_data)
433 # Volume already exists
434 if self.state == 'present':
435 modifications = self.probe(clone_data)
436 if modifications:
437 self.log("Modifications detected: %s", modifications)
438 self.module.fail_json(
439 msg="Modifications of clone is not supported via this module, Please use ibm_svc_manage_volume or"
440 " ibm_svc_manage_volumegroup for modifying volume or volumegroup clone/thinclone respectively.")
441 else:
442 self.msg = "Clone %s already exists, no modification required." % self.name
443 else:
444 self.create_clone()
445 self.changed = True
446 self.msg = "Clone %s created." % self.name
447 self.module.exit_json(msg=self.msg, changed=self.changed)
448
449
450 def main():
451 v = IBMSVClone()
452 try:
453 v.apply()
454 except Exception as e:
455 v.log("Exception in apply(): \n%s", format_exc())
456 v.module.fail_json(msg="Module failed. Error [%s]." % to_native(e))
457
458
459 if __name__ == '__main__':
460 main()