Debian Codegraph @

ansible_collections/ibm/storage_virtualize/plugins/modules/ibm_svc_manage_volume.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 # Rahul Pawar <[email protected]>
7 # Sumit Kumar Gupta <[email protected]>
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 = r'''
14 ---
15 module: ibm_svc_manage_volume
16 short_description: This module manages standard volumes on IBM Storage Virtualize family systems
17 description:
18 - Ansible interface to manage 'mkvolume', 'rmvolume', and 'chvdisk' volume commands.
19 version_added: "1.6.0"
20 options:
21 name:
22 description:
23 - Specifies the name to assign to the new volume or name/UID to manage an existing volume.
24 required: true
25 type: str
26 state:
27 description:
28 - Creates or updates (C(present)) or removes (C(absent)) a volume.
29 choices: [ absent, present ]
30 required: true
31 type: str
32 clustername:
33 description:
34 - The hostname or management IP or Partition IP of the Storage Virtualize system.
35 required: true
36 type: str
37 domain:
38 description:
39 - Domain for the Storage Virtualize system.
40 - Valid when hostname is used for the parameter I(clustername).
41 type: str
42 username:
43 description:
44 - REST API username for the Storage Virtualize system.
45 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
46 type: str
47 password:
48 description:
49 - REST API password for the Storage Virtualize system.
50 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
51 type: str
52 token:
53 description:
54 - The authentication token to verify a user on the Storage Virtualize system.
55 - To generate a token, use the ibm_svc_auth module.
56 type: str
57 pool:
58 description:
59 - Specifies the name of the storage pool to use while creating the volume.
60 - This parameter is required when I(state=present), to create a volume.
61 type: str
62 size:
63 description:
64 - Defines the size of the volume. This parameter can also be used to resize an existing volume.
65 - Required when I(state=present), to create or modify a volume.
66 type: str
67 warning:
68 description:
69 - Raises a warning when the used disk capacity on the thin-provisioned copy first exceeds the specified threshold.
70 - The value is specified as a percentage of the total capacity of the thin-provisioned volume, hence it must be between 0 and 100.
71 - When not specified, the default value is 80%.
72 - Valid when I(state=present), to create or modify a thin-provisioned or compressed volume.
73 type: int
74 version_added: '2.7.0'
75 unit:
76 description:
77 - Specifies the data units to use with the capacity that is specified by the 'size' parameter.
78 - I(size) is required when using I(unit).
79 type: str
80 choices: [ b, kb, mb, gb, tb, pb ]
81 iogrp:
82 description:
83 - Specifies the list of I/O group names. Group names in the list must be separated by using a comma.
84 - While creating a new volume, the first I/O group in the list is added as both cached & access I/O group,
85 while remaining I/O groups are added as access I/O groups.
86 - This parameter supports update functionality.
87 - Valid when I(state=present), to create or modify a volume.
88 type: str
89 thin:
90 description:
91 - Specifies that a thin-provisioned volume is to be created.
92 - Parameters 'thin' and 'compressed' are mutually exclusive.
93 - Valid when I(state=present), to create a thin-provisioned volume.
94 type: bool
95 type:
96 description:
97 - Specifies the type of volume to create. Volume can be thinclone or clone type.
98 - Valid when I(state=present), to create a thinclone or clone volume.
99 - Supported from Storage Virtualize family systems from 8.6.2.0 or later.
100 - Also used to convert a thinclone volume to clone. type = clone should be specified.
101 choices: [thinclone, clone]
102 type: str
103 fromsourcevolume:
104 description:
105 - Specifies the volume name/UID in the snapshot used to pre-populate clone or thinclone volume.
106 - Valid when I(state=present), to create a thinclone or clone volume.
107 - Supported from Storage Virtualize family systems from 8.6.2.0 or later.
108 type: str
109 compressed:
110 description:
111 - Specifies that a compressed volume is to be created.
112 - Parameters 'compressed' and 'thin' are mutually exclusive.
113 - Valid when I(state=present), to create a compressed volume.
114 type: bool
115 buffersize:
116 description:
117 - Specifies the pool capacity that the volume will reserve as a buffer for thin-provisioned and compressed volumes.
118 - Parameter 'thin' or 'compressed' must be specified to use this parameter.
119 - The default buffer size is 2%.
120 - I(thin) or I(compressed) is required when using I(buffersize).
121 - Valid when I(state=present), to create a volume.
122 type: str
123 deduplicated:
124 description:
125 - Specifies that a deduplicated volume is to be created.
126 - Required when I(state=present), to create a deduplicated volume.
127 type: bool
128 volumegroup:
129 description:
130 - Specifies the name of the volumegroup to which the volume is to be added.
131 - Parameters 'volumegroup' and 'novolumegroup' are mutually exclusive.
132 - Valid when I(state=present), to create or modify a volume.
133 type: str
134 novolumegroup:
135 description:
136 - If specified `True`, the volume is removed from its associated volumegroup.
137 - Parameters 'novolumegroup' and 'volumegroup' are mutually exclusive.
138 - Valid when I(state=present), to modify a volume.
139 type: bool
140 unmap:
141 description:
142 - Removes specified objects associated with the volume which is to be deleted.
143 - Valid when I(state=absent), to delete a volume.
144 type: list
145 elements: str
146 choices: [ host_mappings, remotecopy_relationships, flashcopy_mappings ]
147 version_added: 2.7.0
148 old_name:
149 description:
150 - Specifies the old name/UID of the volume during renaming.
151 - Valid when I(state=present), to rename an existing volume.
152 type: str
153 version_added: '1.9.0'
154 enable_cloud_snapshot:
155 description:
156 - Specify to enable or disable cloud snapshot.
157 - Valid when I(state=present), to modify an existing volume.
158 type: bool
159 version_added: '1.11.0'
160 cloud_account_name:
161 description:
162 - Specifies the name of the cloud account name.
163 - Valid when I(enable_cloud_snapshot=true).
164 type: str
165 version_added: '1.11.0'
166 allow_hs:
167 description:
168 - If specified `True`, manages the hyperswap volume by ignoring the volume type validation.
169 - Valid when I(state=present), to modify an existing volume.
170 type: bool
171 default: false
172 version_added: '2.0.0'
173 validate_certs:
174 description:
175 - Validates certification.
176 default: false
177 type: bool
178 log_path:
179 description:
180 - Path of debug log file.
181 type: str
182 grainsize:
183 description:
184 - Sets the grain size for a thin-provisioned volume.
185 choices: [32, 64, 128, 256]
186 type: int
187 version_added: '3.0.0'
188 preferrednode:
189 description:
190 - Specifies the preferred node name that is used to access the volume.
191 - When not specified, the system selects the preferred node automatically.
192 type: str
193 version_added: '3.2.0'
194 cache:
195 description:
196 - Specifies the caching options for the volume.
197 - When not specified, the default value is 'readwrite'.
198 type: str
199 choices: [readwrite, readonly, none]
200 version_added: '3.2.0'
201 autoexpand:
202 description:
203 - Specifies whether thin-provisioned volume copies automatically expand their real capacities.
204 - If specified as off, works as `noautoexpand`.
205 type: str
206 choices: ['on', 'off']
207 version_added: '3.2.0'
208 author:
209 - Sreshtant Bohidar(@Sreshtant-Bohidar)
210 - Rahul Pawar(@rahul-p)
211 - Sumit Kumar Gupta(@sumitguptaibm)
212 notes:
213 - This module supports C(check_mode).
214 - For unmap parameter, the option remotecopy_relationships has been deprecated from 8.7.1.0 onwards.
215 - CMMVC9855E The command failed because one of more of the specified volumes does not exist.
216 This error occurs when the user-provided volume(s) do not exist.
217 - This module supports logging in via partition IP.
218 - To create a clone or thinclone of a Volume, please refer to ibm_sv_manage_clone module.
219 '''
220
221 EXAMPLES = r'''
222 - name: Create a volume
223 ibm.storage_virtualize.ibm_svc_manage_volume:
224 clustername: "{{ clustername }}"
225 domain: "{{ domain }}"
226 username: "{{ username }}"
227 password: "{{ password }}"
228 log_path: "{{ log_path }}"
229 name: "volume_name"
230 state: "present"
231 pool: "pool_name"
232 size: "1"
233 unit: "gb"
234 iogrp: "io_grp0, io_grp1"
235 volumegroup: "test_volumegroup"
236 - name: Create a thin-provisioned volume
237 ibm.storage_virtualize.ibm_svc_manage_volume:
238 clustername: "{{ clustername }}"
239 domain: "{{ domain }}"
240 username: "{{ username }}"
241 password: "{{ password }}"
242 log_path: "{{ log_path }}"
243 name: "volume_name"
244 state: "present"
245 pool: "pool_name"
246 size: "1"
247 unit: "gb"
248 iogrp: "io_grp0, io_grp1"
249 thin: true
250 buffersize: 10%
251 - name: Create a compressed volume
252 ibm.storage_virtualize.ibm_svc_manage_volume:
253 clustername: "{{ clustername }}"
254 domain: "{{ domain }}"
255 username: "{{ username }}"
256 password: "{{ password }}"
257 log_path: "{{ log_path }}"
258 name: "volume_name"
259 state: "present"
260 pool: "pool_name"
261 size: "1"
262 unit: "gb"
263 iogrp: "io_grp0, io_grp1"
264 compressed: true
265 buffersize: 10%
266 - name: Creating a volume with iogrp- io_grp0
267 ibm.storage_virtualize.ibm_svc_manage_volume:
268 clustername: "{{ clustername }}"
269 domain: "{{ domain }}"
270 username: "{{ username }}"
271 password: "{{ password }}"
272 log_path: "{{ log_path }}"
273 name: "volume_name"
274 state: "present"
275 pool: "pool_name"
276 size: "1"
277 unit: "gb"
278 iogrp: "io_grp0"
279 - name: Create thinclone volume from volume vol1
280 ibm.storage_virtualize.ibm_svc_manage_volume:
281 clustername: "{{ clustername }}"
282 domain: "{{ domain }}"
283 username: "{{ username }}"
284 password: "{{ password }}"
285 name: "vol1_thinclone"
286 fromsourcevolume: "vol1"
287 state: "present"
288 pool: "pool0"
289 type: "thinclone"
290 - name: Create clone volume from volume vol1
291 ibm.storage_virtualize.ibm_svc_manage_volume:
292 clustername: "{{ clustername }}"
293 domain: "{{ domain }}"
294 username: "{{ username }}"
295 password: "{{ password }}"
296 name: "vol1_clone"
297 fromsourcevolume: "vol1"
298 state: "present"
299 pool: "pool0"
300 type: "clone"
301 - name: Adding a new iogrp- io_grp1
302 ibm.storage_virtualize.ibm_svc_manage_volume:
303 clustername: "{{ clustername }}"
304 domain: "{{ domain }}"
305 username: "{{ username }}"
306 password: "{{ password }}"
307 log_path: "{{ log_path }}"
308 name: "volume_name"
309 state: "present"
310 pool: "pool_name"
311 iogrp: "io_grp0, io_grp1"
312 - name: Rename an existing volume
313 ibm.storage_virtualize.ibm_svc_manage_volume:
314 clustername: "{{ clustername }}"
315 domain: "{{ domain }}"
316 username: "{{ username }}"
317 password: "{{ password }}"
318 old_name: "volume_name"
319 name: "new_volume_name"
320 state: "present"
321 - name: Convert a thinclone volume to clone
322 ibm.storage_virtualize.ibm_svc_manage_volume:
323 clustername: "{{ clustername }}"
324 domain: "{{ domain }}"
325 username: "{{ username }}"
326 password: "{{ password }}"
327 name: "vol0-0"
328 type: "clone"
329 log_path: "{{ log_path }}"
330 state: "present"
331 - name: Convert list of thinclone volumes to clone
332 ibm.storage_virtualize.ibm_svc_manage_volume:
333 clustername: "{{ clustername }}"
334 domain: "{{ domain }}"
335 username: "{{ username }}"
336 password: "{{ password }}"
337 name: "vol0:vol1:vol2"
338 type: "clone"
339 log_path: "{{ log_path }}"
340 state: "present"
341 - name: Update size of volume
342 ibm.storage_virtualize.ibm_svc_manage_volume:
343 clustername: "{{ clustername }}"
344 domain: "{{ domain }}"
345 username: "{{ username }}"
346 password: "{{ password }}"
347 name: "volume_name"
348 size: "2"
349 unit: "gb"
350 state: "present"
351 - name: Update volumegroup of volume
352 ibm.storage_virtualize.ibm_svc_manage_volume:
353 clustername: "{{ clustername }}"
354 domain: "{{ domain }}"
355 username: "{{ username }}"
356 password: "{{ password }}"
357 name: "volume_name"
358 volumegroup: "vg1"
359 state: "present"
360 - name: Enable cloud backup in an existing volume
361 ibm.storage_virtualize.ibm_svc_manage_volume:
362 clustername: "{{ clustername }}"
363 domain: "{{ domain }}"
364 username: "{{ username }}"
365 password: "{{ password }}"
366 name: "volume_name"
367 enable_cloud_snapshot: true
368 cloud_account_name: "aws_acc"
369 state: "present"
370 - name: Delete a volume
371 ibm.storage_virtualize.ibm_svc_manage_volume:
372 clustername: "{{ clustername }}"
373 domain: "{{ domain }}"
374 username: "{{ username }}"
375 password: "{{ password }}"
376 log_path: "{{ log_path }}"
377 name: "new_volume_name"
378 state: "absent"
379 - name: Delete a volume and remove associated host mappings, remote copy relationships, and flashcopy mappings
380 ibm.storage_virtualize.ibm_svc_manage_volume:
381 clustername: "{{ clustername }}"
382 domain: "{{ domain }}"
383 username: "{{ username }}"
384 password: "{{ password }}"
385 log_path: "{{ log_path }}"
386 name: "new_volume_name"
387 state: "absent"
388 unmap: ['host_mappings', 'remotecopy_relationships', 'flashcopy_mappings']
389 - name: Create a thin volume with grainsize
390 ibm.storage_virtualize.ibm_svc_manage_volume:
391 clustername: "{{ clustername }}"
392 domain: "{{ domain }}"
393 username: "{{ username }}"
394 password: "{{ password }}"
395 log_path: "{{ log_path }}"
396 name: "volume_name"
397 state: "present"
398 pool: "pool_name"
399 size: "1"
400 unit: "gb"
401 thin: true
402 grainsize: 32
403 '''
404
405 RETURN = '''#'''
406
407 from traceback import format_exc
408 from ansible.module_utils.basic import AnsibleModule
409 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import (
410 IBMSVCRestApi,
411 svc_argument_spec,
412 get_logger,
413 strtobool,
414 is_feature_supported
415 )
416 from ansible.module_utils._text import to_native
417 import random
418 import re
419
420
421 class IBMSVCvolume(object):
422 def __init__(self):
423 argument_spec = svc_argument_spec()
424
425 argument_spec.update(
426 dict(
427 name=dict(type='str', required=True),
428 state=dict(type='str', required=True, choices=['absent', 'present']),
429 pool=dict(type='str', required=False),
430 size=dict(type='str', required=False),
431 warning=dict(type='int', required=False),
432 unit=dict(type='str', choices=['b', 'kb', 'mb', 'gb', 'tb', 'pb']),
433 buffersize=dict(type='str', required=False),
434 iogrp=dict(type='str', required=False),
435 volumegroup=dict(type='str', required=False),
436 novolumegroup=dict(type='bool', required=False),
437 unmap=dict(type='list', elements='str', required=False, choices=['host_mappings',
438 'remotecopy_relationships',
439 'flashcopy_mappings']),
440 thin=dict(type='bool', required=False),
441 compressed=dict(type='bool', required=False),
442 deduplicated=dict(type='bool', required=False),
443 old_name=dict(type='str', required=False),
444 enable_cloud_snapshot=dict(type='bool'),
445 cloud_account_name=dict(type='str'),
446 type=dict(type='str', required=False, choices=['clone', 'thinclone']),
447 fromsourcevolume=dict(type='str', required=False),
448 allow_hs=dict(type='bool', default=False),
449 grainsize=dict(type='int', required=False, choices=[32, 64, 128, 256]),
450 preferrednode=dict(type='str', required=False),
451 cache=dict(type='str', required=False, choices=['readwrite', 'readonly', 'none']),
452 autoexpand=dict(type='str', required=False, choices=['on', 'off'])
453 )
454 )
455
456 self.module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
457
458 # logging setup
459 log_path = self.module.params['log_path']
460 log = get_logger(self.__class__.__name__, log_path)
461 self.log = log.info
462
463 # Required Parameters
464 self.name = self.module.params['name']
465 self.state = self.module.params['state']
466
467 # Optional Parameters
468 self.pool = self.module.params['pool']
469 self.size = self.module.params['size']
470 self.warning = self.module.params['warning']
471 self.unit = self.module.params['unit']
472 self.iogrp = self.module.params['iogrp']
473 self.buffersize = self.module.params['buffersize']
474 self.volumegroup = self.module.params['volumegroup']
475 self.novolumegroup = self.module.params['novolumegroup']
476 self.thin = self.module.params['thin']
477 self.compressed = self.module.params['compressed']
478 self.deduplicated = self.module.params['deduplicated']
479 self.old_name = self.module.params['old_name']
480 self.enable_cloud_snapshot = self.module.params['enable_cloud_snapshot']
481 self.cloud_account_name = self.module.params['cloud_account_name']
482 self.allow_hs = self.module.params['allow_hs']
483 self.type = self.module.params['type']
484 self.fromsourcevolume = self.module.params['fromsourcevolume']
485 self.unmap = self.module.params['unmap']
486 self.grainsize = self.module.params['grainsize']
487 self.preferrednode = self.module.params['preferrednode']
488 self.cache = self.module.params['cache']
489 self.autoexpand = self.module.params['autoexpand']
490
491 # internal variable
492 self.changed = False
493
494 self.restapi = IBMSVCRestApi(
495 module=self.module,
496 clustername=self.module.params['clustername'],
497 domain=self.module.params['domain'],
498 username=self.module.params['username'],
499 password=self.module.params['password'],
500 validate_certs=self.module.params['validate_certs'],
501 log_path=log_path,
502 token=self.module.params['token']
503 )
504
505 # assemble iogrp
506 def assemble_iogrp(self):
507 if self.iogrp:
508 input_iogrps = [item.strip() for item in self.iogrp.split(',') if item]
509 self.len_input_iogrps = len(input_iogrps)
510 if self.len_input_iogrps != len(set(input_iogrps)):
511 self.module.fail_json(msg='Duplicate iogrp detected.')
512
513 self.active_iogrp = [item['name'] for item in self.restapi.svc_obj_info('lsiogrp', None, None) if int(item['node_count']) > 0]
514
515 valid_iogrp = []
516 invalid_iogrp = []
517 for item in input_iogrps:
518 if item not in self.active_iogrp:
519 invalid_iogrp.append(item)
520 else:
521 valid_iogrp.append(item)
522 if invalid_iogrp:
523 self.module.fail_json(msg='Empty or non-existing iogrp detected: {0}'.format(invalid_iogrp))
524
525 self.iogrp = valid_iogrp
526
527 # Validate mandatory parameters of the module
528 def mandatory_parameter_validation(self):
529 missing = [item[0] for item in [('name', self.name), ('state', self.state)] if not item[1]]
530 if missing:
531 self.module.fail_json(msg='Missing mandatory parameter: [{0}]'.format(', '.join(missing)))
532 if self.volumegroup and self.novolumegroup:
533 self.module.fail_json(msg='Mutually exclusive parameters detected: [volumegroup] and [novolumegroup]')
534 if self.thin and self.compressed:
535 self.module.fail_json(msg='Mutually exclusive parameters detected: [thin] and [compressed]')
536 if self.state == 'present' and self.unmap is not None:
537 self.module.fail_json(msg='Parameter [unmap] cannot be specified when creating or updating a volume.')
538 if self.unit and not self.size:
539 self.module.fail_json(msg='Parameter [unit] is invalid without [size]')
540
541 # for validating parameter while removing an existing volume
542 def volume_deletion_parameter_validation(self):
543 invalids = ('pool', 'size', 'iogrp', 'buffersize', 'volumegroup', 'novolumegroup',
544 'thin', 'compressed', 'deduplicated', 'old_name', 'enable_cloud_snapshot',
545 'cloud_account_name', 'allow_hs', 'type', 'fromsourcevolume', 'warning', 'grainsize', 'preferrednode', 'cache', 'autoexpand')
546
547 invalid_params = ', '.join((param for param in invalids if getattr(self, param)))
548
549 if invalid_params:
550 self.module.fail_json(
551 msg='Following parameter(s) are invalid while deletion of volume: {0}'.format(invalid_params)
552 )
553
554 # for validating parameter while creating a volume
555 def volume_creation_parameter_validation(self):
556 if self.enable_cloud_snapshot in {True, False}:
557 self.module.fail_json(msg='Following parameter not applicable for creation: enable_cloud_snapshot')
558
559 if self.cloud_account_name:
560 self.module.fail_json(msg='Following parameter not applicable for creation: cloud_account_name')
561
562 if self.old_name:
563 self.module.fail_json(msg='Parameter [old_name] is not supported during volume creation.')
564
565 if (self.type and not self.fromsourcevolume) or (self.fromsourcevolume and not self.type):
566 self.module.fail_json(msg='Parameters [type] and [fromsourcevolume] parameters must be used together')
567
568 if (self.warning) and not self.thin and not self.compressed:
569 self.module.fail_json(msg='Parameter [warning] is invalid without [thin] or [compressed]')
570
571 if self.grainsize and not self.thin:
572 self.module.fail_json(msg='Parameter [grainsize] is invalid without [thin]')
573
574 if self.deduplicated and not (self.thin or self.compressed):
575 self.module.fail_json(msg='Parameter [deduplicated] is invalid without [thin] or [compressed]')
576
577 if self.preferrednode and (not self.iogrp or self.len_input_iogrps != 1):
578 self.module.fail_json(msg='Parameter [preferrednode] is only valid with a single iogrp.')
579
580 if self.autoexpand and (not self.thin and not self.compressed):
581 self.module.fail_json(msg='Parameter [autoexpand] is invalid without [thin]')
582
583 missing = []
584 if self.type:
585 if not self.pool:
586 missing = ['pool']
587 if self.size:
588 self.module.fail_json(msg='Parameter [size] is invalid while creating clone or thinclone')
589 else:
590 missing = [item[0] for item in [('pool', self.pool), ('size', self.size)] if not item[1]]
591
592 if missing:
593 self.module.fail_json(msg='Missing required parameter(s) while creating: [{0}]'.format(', '.join(missing)))
594
595 def chvolume_supported(self):
596 system_info = self.restapi.svc_obj_info(cmd='lssystem', cmdopts=None, cmdargs=None)
597 code_build_version = system_info['code_level']
598 match = re.match(r'^([\d\.]+)', code_build_version)
599 code_level = match.group(1) if match else None
600 return is_feature_supported('chvolume', code_level)
601
602 # for validating parameter while renaming a volume
603 def parameter_handling_while_renaming(self):
604 if not self.old_name:
605 self.module.fail_json(msg="Parameter is required while renaming: old_name")
606 parameters = {
607 "pool": self.pool,
608 "size": self.size,
609 "iogrp": self.iogrp,
610 "buffersize": self.buffersize,
611 "volumegroup": self.volumegroup,
612 "novolumegroup": self.novolumegroup,
613 "thin": self.thin,
614 "compressed": self.compressed,
615 "deduplicated": self.deduplicated,
616 "type": self.type,
617 "fromsourcevolume": self.fromsourcevolume,
618 "warning": self.warning,
619 "grainsize": self.grainsize,
620 "preferrednode": self.preferrednode,
621 "cache": self.cache,
622 "autoexpand": self.autoexpand
623 }
624 parameters_exists = [parameter for parameter, value in parameters.items() if value]
625 if parameters_exists:
626 self.module.fail_json(msg="Parameters {0} not supported while renaming a volume.".format(parameters_exists))
627
628 # for validating if volume type is supported or not
629 def validate_volume_type(self, data):
630 unsupported_volume = False
631
632 # The value many indicates that the volume has more than one copy
633 if data[0]['type'] == "many":
634 unsupported_volume = True
635 if not unsupported_volume:
636 relationship_name = data[0]['RC_name']
637 if relationship_name:
638 rel_data = self.restapi.svc_obj_info(cmd='lsrcrelationship', cmdopts=None, cmdargs=[relationship_name])
639 if rel_data['copy_type'] == "activeactive" and not self.allow_hs:
640 unsupported_volume = True
641 if unsupported_volume:
642 self.module.fail_json(msg="The module cannot be used for managing Mirrored volume.")
643
644 # function to get existing volume data
645 def get_existing_volume(self, volume_name):
646 return self.restapi.svc_obj_info(
647 'lsvdisk', {'bytes': True}, [volume_name]
648 )
649
650 def get_all_target_volumes(self, criteria=None):
651 # This function does following:
652 # 1. It fetches a set of volumes from SVC in all_vols_set
653 # 2. It converts self.name into a provided_vols_set
654 # 3. It gets common volumes set from both that meet the criteria
655 # 4. If any user-provide volume(s) do not exist on the cluster, returns error
656 # 5. It sets a new attribute self.target_vols_list_str which is a string formed
657 # by joining colon-separated list of common volumes.
658
659 all_vols_set = set()
660 self.target_vols_list_str = ''
661
662 if self.module.check_mode:
663 self.changed = True
664 return
665
666 cmdopts = {}
667 if criteria:
668 cmdopts['filtervalue'] = criteria
669 data = self.restapi.svc_obj_info('lsvdisk', cmdopts, None)
670 if data:
671 for item in data:
672 all_vols_set.add(item['name'])
673
674 user_provided_vols_set = set(self.name.split(':'))
675 invalid_vols_list = list(user_provided_vols_set.difference(all_vols_set))
676 if invalid_vols_list:
677 self.module.fail_json(msg="CMMVC9855E The command failed because one or more of"
678 " the specified volumes does not exist.")
679
680 target_vols_list = []
681 if data:
682 for item in data:
683 if item['name'] in user_provided_vols_set and item['volume_type'] == "thinclone":
684 target_vols_list.append(item['name'])
685 self.target_vols_list_str = ':'.join(target_vols_list)
686 self.log("Volume(s) that need to be converted from thinclone to clone: [%s].", self.target_vols_list_str)
687
688 return
689
690 # function to get list of associated iogrp to a volume
691 def get_existing_iogrp(self):
692 response = []
693 data = self.restapi.svc_obj_info(
694 'lsvdiskaccess', None, [self.name]
695 )
696 if data:
697 for item in data:
698 response.append(item['IO_group_name'])
699 return response
700
701 # function to create a transient (short-lived) snapshot
702 # return value: snapshot_id
703 def create_transient_snapshot(self):
704 # Required parameters
705 snapshot_cmd = 'addsnapshot'
706 snapshot_opts = {}
707 snapshot_name = 'snapshot_' + ''.join(random.choices('0123456789', k=10))
708
709 snapshot_opts['name'] = snapshot_name
710
711 # Optional parameters
712 snapshot_opts['pool'] = self.module.params.get('pool', '')
713 snapshot_opts['volumes'] = self.module.params.get('fromsourcevolume', '')
714 snapshot_opts['retentionminutes'] = 5
715
716 addsnapshot_output = self.restapi.svc_run_command(snapshot_cmd, snapshot_opts, cmdargs=None, timeout=10)
717 snapshot_id = addsnapshot_output['id']
718
719 return snapshot_id
720
721 # function to create a new volume
722 def create_volume(self):
723 self.volume_creation_parameter_validation()
724 if self.module.check_mode:
725 self.changed = True
726 return
727 cmd = 'mkvolume'
728 cmdopts = {}
729 if self.pool:
730 cmdopts['pool'] = self.pool
731 if self.size:
732 cmdopts['size'] = self.size
733 if self.unit:
734 cmdopts['unit'] = self.unit
735 if self.iogrp:
736 cmdopts['iogrp'] = self.iogrp[0]
737 if self.volumegroup:
738 cmdopts['volumegroup'] = self.volumegroup
739 if self.thin:
740 cmdopts['thin'] = self.thin
741 if self.compressed:
742 cmdopts['compressed'] = self.compressed
743 if self.deduplicated:
744 cmdopts['deduplicated'] = self.deduplicated
745 if self.buffersize:
746 cmdopts['buffersize'] = self.buffersize
747 if self.name:
748 cmdopts['name'] = self.name
749 if self.warning:
750 cmdopts['warning'] = str(self.warning) + '%'
751 if self.preferrednode:
752 cmdopts['preferrednode'] = self.preferrednode
753 if self.cache:
754 cmdopts['cache'] = self.cache
755 if self.autoexpand == 'off':
756 cmdopts['noautoexpand'] = True
757 if self.type:
758 cmdopts['type'] = self.type
759 snapshot_id = self.create_transient_snapshot()
760 cmdopts['fromsnapshotid'] = snapshot_id
761 if self.fromsourcevolume:
762 cmdopts['fromsourcevolume'] = self.fromsourcevolume
763 if self.grainsize:
764 cmdopts['grainsize'] = self.grainsize
765
766 result = self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
767 if result and 'message' in result:
768 self.changed = True
769 self.log("create volume result message %s", result['message'])
770 else:
771 self.module.fail_json(
772 msg="Failed to create volume [%s]" % self.name)
773
774 # function to remove an existing volume
775 def remove_volume(self):
776 self.volume_deletion_parameter_validation()
777 cmdopts = {}
778 if self.module.check_mode:
779 self.changed = True
780 return
781 name_params_map = {
782 'host_mappings': 'removehostmappings',
783 'remotecopy_relationships': 'removercrelationships',
784 'flashcopy_mappings': 'removefcmaps'
785 }
786 if self.unmap:
787 for name in self.unmap:
788 cmdopts[name_params_map[name]] = True
789
790 self.restapi.svc_run_command(
791 'rmvolume', cmdopts, [self.name]
792 )
793 self.changed = True
794
795 # function that data in other units to b
796 def convert_to_bytes(self):
797 return int(self.size) * (1024 ** (['b', 'kb', 'mb', 'gb', 'tb', 'pb'].index((self.unit).lower())))
798
799 # function to probe an existing volume
800 def probe_volume(self, data):
801 props = {}
802
803 # check for changes in iogrp
804 if self.iogrp:
805 input_iogrp = set(self.iogrp)
806 existing_iogrp = set(self.get_existing_iogrp())
807 if input_iogrp ^ existing_iogrp:
808 iogrp_to_add = input_iogrp - existing_iogrp
809 iogrp_to_remove = existing_iogrp - input_iogrp
810 if iogrp_to_add:
811 props['iogrp'] = {
812 'add': list(iogrp_to_add)
813 }
814 if iogrp_to_remove:
815 props['iogrp'] = {
816 'remove': list(iogrp_to_remove)
817 }
818 # check for changes in volume size for non-HA volumes
819 # Even if we need to use chvolume, it is ok to calculate
820 # because these are local calculations, and won't have any
821 # effect if chvolume is to be used. Refer to update_volume()
822 # for 'updating size of a volume'
823
824 if self.size:
825 input_size = self.convert_to_bytes()
826 existing_size = int(data[0]['capacity'])
827 if input_size != existing_size:
828 action = 'expand' if input_size > existing_size else 'shrink'
829 props['size'] = {action: abs(input_size - existing_size)}
830
831 if self.warning:
832 # Check for standard or compressed volume
833 if (data[0]['capacity'] != data[1]['real_capacity']) or (data[1]['compressed_copy'] == 'yes'):
834 if (int(data[1]['warning']) != (self.warning)):
835 props['warning'] = str(self.warning) + '%'
836 else:
837 self.module.fail_json(msg='Parameter [warning] is applicable only for thin-provisioned and compressed volumes.')
838
839 # check for changes in volumegroup
840 if self.volumegroup:
841 if self.volumegroup != data[0]['volume_group_name']:
842 props['volumegroup'] = {
843 'name': self.volumegroup,
844 }
845
846 # check for presence of novolumegroup
847 if self.novolumegroup:
848 if data[0]['volume_group_name']:
849 props['novolumegroup'] = {
850 'status': True
851 }
852
853 # check for change in thin, compressed and deduplicated
854 for attr, field in (('thin', 'se_copy'),
855 ('compressed', 'compressed_copy'),
856 ('deduplicated', 'deduplicated_copy')):
857 val = getattr(self, attr)
858 if val is not None:
859 current = str(data[1].get(field)).lower() == 'yes'
860 if bool(val) != current:
861 props[attr] = {'status': True}
862
863 # check for change in pool
864 if self.pool:
865 if self.pool != data[0]['mdisk_grp_name']:
866 props['pool'] = {
867 'status': True
868 }
869 # Check for change in cloud backup
870 if self.enable_cloud_snapshot is True:
871 if not strtobool(data[0].get('cloud_backup_enabled')):
872 props['cloud_backup'] = {'status': True}
873 elif self.enable_cloud_snapshot is False:
874 if strtobool(data[0].get('cloud_backup_enabled')):
875 props['cloud_backup'] = {'status': True}
876
877 if self.cloud_account_name:
878 if self.cloud_account_name != data[0].get('cloud_account_name'):
879 props['cloud_backup'] = {'status': True}
880
881 # Check for change in fromsourcevolume
882 if self.fromsourcevolume:
883 if self.fromsourcevolume != data[0].get('source_volume_name'):
884 props['fromsourcevolume'] = {'status': True}
885
886 # Check for change in type
887 if self.type:
888 if self.type != data[0].get('volume_type'):
889 props['type'] = {'status': True}
890
891 if self.grainsize:
892 if self.grainsize != int(data[1].get('grainsize') or 0):
893 props['grainsize'] = {'status': True}
894
895 if self.preferrednode and self.preferrednode != data[0].get('preferred_node_name'):
896 props['preferrednode'] = self.preferrednode
897
898 if self.cache and self.cache != data[0].get('cache'):
899 props['cache'] = self.cache
900
901 if self.autoexpand and self.autoexpand != data[1].get('autoexpand'):
902 props['autoexpand'] = self.autoexpand
903
904 self.log("Properties to be changed: %s", props)
905 return props
906
907 # function to expand an existing volume size
908 def expand_volume(self, expand_size):
909 self.restapi.svc_run_command(
910 'expandvdisksize',
911 {'size': expand_size, 'unit': 'b'},
912 [self.name]
913 )
914 self.changed = True
915
916 # function to shrink an existing volume size
917 def shrink_volume(self, shrink_size):
918 self.restapi.svc_run_command(
919 'shrinkvdisksize',
920 {'size': shrink_size, 'unit': 'b'},
921 [self.name]
922 )
923 self.changed = True
924
925 # add iogrp
926 def add_iogrp(self, list_of_iogrp):
927 self.restapi.svc_run_command(
928 'addvdiskaccess',
929 {'iogrp': ':'.join(list_of_iogrp)},
930 [self.name]
931 )
932 self.changed = True
933
934 # remove iogrp
935 def remove_iogrp(self, list_of_iogrp):
936 self.restapi.svc_run_command(
937 'rmvdiskaccess',
938 {'iogrp': ':'.join(list_of_iogrp)},
939 [self.name]
940 )
941 self.changed = True
942
943 def update_cloud_backup(self):
944 cmdopts = {}
945
946 if self.enable_cloud_snapshot is True:
947 cmdopts['backup'] = 'cloud'
948 cmdopts['enable'] = True
949
950 if self.enable_cloud_snapshot is False:
951 cmdopts['backup'] = 'cloud'
952 cmdopts['disable'] = True
953
954 if self.cloud_account_name:
955 cmdopts['account'] = self.cloud_account_name
956
957 self.restapi.svc_run_command(
958 'chvdisk',
959 cmdopts,
960 [self.name]
961 )
962 self.changed = True
963
964 def convert_to_clone(self):
965 # when check_mode is enabled
966 if self.module.check_mode:
967 self.msg = 'Skipping changes due to check mode.'
968 self.changed = True
969 return
970
971 cmdopts = {}
972 # For a list of volumes, target_volumes_list_str will be set by get_all_target_volumes()
973 if hasattr(self, 'target_vols_list_str') and self.target_vols_list_str != '':
974 cmdopts['volumes'] = self.target_vols_list_str
975 else:
976 cmdopts['volumes'] = self.name
977 cmdargs = None
978 self.restapi.svc_run_command('converttoclone', cmdopts, cmdargs)
979 self.msg = "Volume(s) [{0}] converted to clone.".format(self.name)
980 self.changed = True
981 return
982
983 # function to update an existing volume
984 def update_volume(self, modify):
985 # raise error for unsupported parameter(s)
986 unsupported_parameters = ['pool', 'thin', 'compressed', 'deduplicated', 'fromsourcevolume', 'grainsize', 'preferrednode']
987 unsupported_exists = [param for param in unsupported_parameters if param in modify]
988 if unsupported_exists:
989 self.module.fail_json(msg=f"Update not supported for parameter(s): {', '.join(unsupported_exists)}")
990
991 invalid_together = ['warning', 'cloud_backup', 'volumegroup', 'novolumegroup', 'size', 'cache', 'autoexpand']
992 mutually_exclusive_params = [param for param in invalid_together if param in modify]
993
994 # If any 2 conflicting parameters are passed, return error
995 if len(mutually_exclusive_params) > 1:
996 self.module.fail_json(msg=f"Parameters are mutually exclusive: {', '.join(mutually_exclusive_params)}")
997
998 # when check_mode is enabled
999 if self.module.check_mode:
1000 self.changed = True
1001 return
1002
1003 # updating iogrps of a volume
1004 if 'iogrp' in modify:
1005 if 'add' in modify['iogrp']:
1006 self.add_iogrp(modify['iogrp']['add'])
1007 if 'remove' in modify['iogrp']:
1008 self.remove_iogrp(modify['iogrp']['remove'])
1009
1010 if 'cloud_backup' in modify:
1011 self.update_cloud_backup()
1012
1013 cmd = 'chvdisk'
1014
1015 cmdopts = {}
1016 if 'volumegroup' in modify:
1017 cmdopts['volumegroup'] = modify['volumegroup']['name']
1018 if self.chvolume_supported():
1019 cmd = 'chvolume'
1020 if 'novolumegroup' in modify:
1021 cmdopts['novolumegroup'] = modify['novolumegroup']['status']
1022 if self.chvolume_supported():
1023 cmd = 'chvolume'
1024 if 'warning' in modify:
1025 cmdopts['warning'] = modify['warning']
1026
1027 # updating size of a volume
1028 if 'size' in modify:
1029 if 'shrink' in modify['size']:
1030 self.shrink_volume(modify['size']['shrink'])
1031 else:
1032 if self.chvolume_supported():
1033 cmd = 'chvolume'
1034 cmdopts['size'] = self.size
1035 if self.unit:
1036 cmdopts['unit'] = self.unit
1037 else:
1038 self.expand_volume(modify['size']['expand'])
1039
1040 if 'cache' in modify:
1041 cmdopts['cache'] = modify['cache']
1042 if 'autoexpand' in modify:
1043 cmdopts['autoexpand'] = modify['autoexpand']
1044
1045 if cmdopts:
1046 self.restapi.svc_run_command(
1047 cmd,
1048 cmdopts,
1049 [self.name]
1050 )
1051 self.changed = True
1052
1053 # function for renaming an existing volume with a new name
1054 def volume_rename(self, volume_data):
1055 msg = None
1056 self.parameter_handling_while_renaming()
1057 old_volume_data = self.get_existing_volume(self.old_name)
1058 if not old_volume_data and not volume_data:
1059 self.module.fail_json(msg="Volume [{0}] does not exists.".format(self.old_name))
1060 elif old_volume_data and volume_data:
1061 if old_volume_data[0].get('vdisk_UID') == volume_data[0].get('vdisk_UID'):
1062 msg = "Volume [{0}] already renamed.".format(self.name)
1063 else:
1064 self.module.fail_json(msg="Volume [{0}] already exists.".format(self.name))
1065 elif not old_volume_data and volume_data:
1066 msg = "Volume with name [{0}] already exists.".format(self.name)
1067 elif old_volume_data and not volume_data:
1068 # when check_mode is enabled
1069 if self.module.check_mode:
1070 self.changed = True
1071 return
1072
1073 cmd = 'chvolume' if self.chvolume_supported() else 'chvdisk'
1074 self.restapi.svc_run_command(cmd, {'name': self.name}, [self.old_name])
1075 self.changed = True
1076 msg = "Volume [{0}] has been successfully renamed to [{1}]".format(self.old_name, self.name)
1077 return msg
1078
1079 def apply(self):
1080 changed, msg, modify = False, None, {}
1081 self.mandatory_parameter_validation()
1082
1083 if ':' in self.name and self.type == 'clone' and self.state == 'present':
1084 # Special handling for list of volumes
1085 # Only applicable for converting thinclone volumes list to clone
1086 self.get_all_target_volumes()
1087 # self.target_vols_list_str will be set after calling get_all_target_volumes()
1088 if self.target_vols_list_str != '':
1089 self.convert_to_clone()
1090 self.module.exit_json(msg=self.msg, changed=self.changed)
1091 else:
1092 self.msg = "Volume(s) [{0}] are not thinclone!!".format(self.name)
1093 self.module.exit_json(msg=self.msg, changed=self.changed)
1094 else:
1095 volume_data = self.get_existing_volume(self.name)
1096
1097 if volume_data and self.type == 'clone' and not self.fromsourcevolume:
1098 # If an existing volume was passed along with type=clone
1099 # but not fromsourcevolume, user wants to convert thinclone to clone
1100 if volume_data[0].get('volume_type') == 'thinclone':
1101 # If volume is thinclone, convert it to clone.
1102 self.convert_to_clone()
1103 self.module.exit_json(msg=self.msg, changed=self.changed)
1104 else:
1105 # If volume is not thinclone, just return message.
1106 # This is for cases, where it was either already done
1107 # the last time it was run, or was never a thinclone.
1108 self.module.exit_json(msg='Volume {0} is not a thinclone.'.format(self.name), changed=self.changed)
1109
1110 if self.state == "present" and self.old_name:
1111 if self.name == self.old_name:
1112 self.module.exit_json(msg="Volume's name is same as old name.", changed=self.changed)
1113 else:
1114 msg = self.volume_rename(volume_data)
1115 elif self.state == "absent" and self.old_name:
1116 self.module.fail_json(msg="Rename functionality is not supported when 'state' is absent.")
1117 else:
1118 if self.state == 'present':
1119 self.assemble_iogrp()
1120 if volume_data:
1121 self.validate_volume_type(volume_data)
1122 if self.state == 'absent':
1123 changed = True
1124 elif self.state == 'present':
1125 if self.type or self.fromsourcevolume:
1126 # Both type and fromsourcevolume needed together
1127 self.volume_creation_parameter_validation()
1128 if ((volume_data[0].get('source_volume_name') and not self.fromsourcevolume) or
1129 (volume_data[0].get('volume_type') and not self.type)):
1130 changed = True
1131
1132 modify = self.probe_volume(volume_data)
1133 if modify:
1134 changed = True
1135 else:
1136 if self.state == 'present':
1137 changed = True
1138 if changed:
1139 if self.state == 'present':
1140 if not volume_data:
1141 self.create_volume()
1142 if isinstance(self.iogrp, list):
1143 if len(self.iogrp) > 1:
1144 self.add_iogrp(self.iogrp[1:])
1145 msg = 'volume [%s] has been created' % self.name
1146 else:
1147 if modify:
1148 self.update_volume(modify)
1149 msg = 'volume [%s] has been modified' % self.name
1150 elif self.state == 'absent':
1151 self.remove_volume()
1152 msg = 'volume [%s] has been deleted.' % self.name
1153 else:
1154 if self.state == 'absent':
1155 msg = "volume [%s] did not exist." % self.name
1156 else:
1157 msg = "volume [%s] already exists." % self.name
1158 if self.module.check_mode:
1159 msg = 'Skipping changes due to check mode.'
1160 self.log('skipping changes due to check mode.')
1161 self.module.exit_json(msg=msg, changed=self.changed)
1162
1163
1164 def main():
1165 v = IBMSVCvolume()
1166 try:
1167 v.apply()
1168 except Exception as e:
1169 v.log("Exception in apply(): \n%s", format_exc())
1170 v.module.fail_json(msg="Module failed. Error [%s]." % to_native(e))
1171
1172
1173 if __name__ == '__main__':
1174 main()