Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # Copyright (C) 2020 IBM CORPORATION
3 # Author(s): Peng Wang <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = '''
11 ---
12 module: ibm_svc_mdisk
13 short_description: This module manages MDisks on IBM Storage Virtualize family systems
14 description:
15 - Ansible interface to manage 'mkarray' and 'rmmdisk' MDisk commands.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - The MDisk name.
21 required: true
22 type: str
23 state:
24 description:
25 - Creates (C(present)) or removes (C(absent)) the MDisk.
26 choices: [ absent, present ]
27 required: true
28 type: str
29 clustername:
30 description:
31 - The hostname or management IP of the Storage Virtualize system.
32 type: str
33 required: true
34 domain:
35 description:
36 - Domain for the Storage Virtualize system.
37 - Valid when hostname is used for the parameter I(clustername).
38 type: str
39 username:
40 description:
41 - REST API username for the Storage Virtualize system.
42 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
43 type: str
44 password:
45 description:
46 - REST API password 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 token:
50 description:
51 - The authentication token to verify a user on the Storage Virtualize system.
52 - To generate a token, use the ibm_svc_auth module.
53 type: str
54 version_added: '1.5.0'
55 drive:
56 description:
57 - Drive(s) to use as members of the RAID array.
58 - Required when I(state=present), to create an MDisk array.
59 type: str
60 mdiskgrp:
61 description:
62 - The storage pool (mdiskgrp) to which you want to add the MDisk.
63 type: str
64 log_path:
65 description:
66 - Path of debug log file.
67 type: str
68 validate_certs:
69 description:
70 - Validates certification.
71 default: false
72 type: bool
73 level:
74 description:
75 - Specifies the RAID level.
76 - Required when I(state=present), to create an MDisk array.
77 type: str
78 choices: ['raid0', 'raid1', 'raid5', 'raid6', 'raid10']
79 encrypt:
80 description:
81 - Defines use of encryption with the MDisk group.
82 - Applies when I(state=present).
83 type: str
84 default: 'no'
85 choices: ['yes', 'no']
86 driveclass:
87 description:
88 - Specifies the class that is being used to create the array.
89 - Applies when I(state=present).
90 type: str
91 version_added: '2.0.0'
92 drivecount:
93 description:
94 - Specifies the number of the drives.
95 - The value must be a number in the range 2 - 128.
96 - Applies when I(state=present).
97 type: str
98 version_added: '2.0.0'
99 stripewidth:
100 description:
101 - Specifies the width of a single unit of redundancy within a distributed set of drives
102 - The value must be a number in the range 2 - 16.
103 - Applies when I(state=present).
104 type: str
105 version_added: '2.0.0'
106 tier:
107 description:
108 - Specifies the new tier of the MDisk.
109 type: str
110 choices: ['tier0_flash', 'tier1_flash', 'tier_enterprise', 'tier_nearline', 'tier_scm']
111 version_added: '2.7.0'
112 old_name:
113 description:
114 - Specifies the old name of an existing pool.
115 - Applies when I(state=present), to rename the existing pool.
116 type: str
117 version_added: '2.0.0'
118 author:
119 - Peng Wang(@wangpww)
120 notes:
121 - This module supports C(check_mode).
122 '''
123
124 EXAMPLES = '''
125 - name: Create MDisk and name as mdisk20
126 ibm.storage_virtualize.ibm_svc_mdisk:
127 clustername: "{{ clustername }}"
128 domain: "{{ domain }}"
129 username: "{{ username }}"
130 password: "{{ password }}"
131 name: mdisk20
132 state: present
133 level: raid0
134 drive: '5:6'
135 encrypt: 'no'
136 mdiskgrp: pool20
137 - name: Change tier of MDisk to tier1_flash
138 ibm.storage_virtualize.ibm_svc_mdisk:
139 clustername: "{{ clustername }}"
140 domain: "{{ domain }}"
141 username: "{{ username }}"
142 password: "{{ password }}"
143 name: mdisk20
144 state: present
145 mdiskgrp: pool20
146 tier: tier1_flash
147 - name: Delete MDisk named mdisk20
148 ibm.storage_virtualize.ibm_svc_mdisk:
149 clustername: "{{ clustername }}"
150 domain: "{{ domain }}"
151 username: "{{ username }}"
152 password: "{{ password }}"
153 name: mdisk20
154 state: absent
155 mdiskgrp: pool20
156 '''
157
158 RETURN = '''#'''
159
160 from traceback import format_exc
161 from ansible.module_utils.basic import AnsibleModule
162 from ansible.module_utils._text import to_native
163 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import IBMSVCRestApi, svc_argument_spec, get_logger
164
165
166 class IBMSVCmdisk(object):
167 def __init__(self):
168 argument_spec = svc_argument_spec()
169
170 argument_spec.update(
171 dict(
172 name=dict(type='str', required=True),
173 state=dict(type='str', required=True, choices=['absent',
174 'present']),
175 level=dict(type='str', choices=['raid0', 'raid1', 'raid5',
176 'raid6', 'raid10']),
177 drive=dict(type='str', default=None),
178 encrypt=dict(type='str', default='no', choices=['yes', 'no']),
179 mdiskgrp=dict(type='str'),
180 driveclass=dict(type='str'),
181 drivecount=dict(type='str'),
182 stripewidth=dict(type='str'),
183 tier=dict(type='str', choices=['tier0_flash', 'tier1_flash', 'tier_enterprise', 'tier_nearline', 'tier_scm']),
184 old_name=dict(type='str')
185 )
186 )
187
188 mutually_exclusive = []
189 self.module = AnsibleModule(argument_spec=argument_spec,
190 mutually_exclusive=mutually_exclusive,
191 supports_check_mode=True)
192
193 # logging setup
194 log_path = self.module.params['log_path']
195 log = get_logger(self.__class__.__name__, log_path)
196 self.log = log.info
197
198 # Required
199 self.name = self.module.params['name']
200 self.state = self.module.params['state']
201
202 # Optional
203 self.level = self.module.params.get('level', None)
204 self.drive = self.module.params.get('drive', None)
205 self.encrypt = self.module.params.get('encrypt', None)
206 self.mdiskgrp = self.module.params.get('mdiskgrp', None)
207 self.driveclass = self.module.params.get('driveclass', '')
208 self.drivecount = self.module.params.get('drivecount', '')
209 self.stripewidth = self.module.params.get('stripewidth', '')
210 self.tier = self.module.params.get('tier', '')
211 self.old_name = self.module.params.get('old_name', '')
212
213 # internal variable
214 self.changed = False
215
216 self.basic_checks()
217
218 self.restapi = IBMSVCRestApi(
219 module=self.module,
220 clustername=self.module.params['clustername'],
221 domain=self.module.params['domain'],
222 username=self.module.params['username'],
223 password=self.module.params['password'],
224 validate_certs=self.module.params['validate_certs'],
225 log_path=log_path,
226 token=self.module.params['token']
227 )
228
229 def basic_checks(self):
230 # Handling missing mandatory parameters name
231 if not self.name:
232 self.module.fail_json(msg='Missing mandatory parameter: name')
233
234 if self.state == 'present':
235 if self.drive and (self.drivecount or self.driveclass or self.stripewidth):
236 self.module.fail_json(msg="The parameters 'drive' and "
237 "'driveclass, drivecount, stripewidth' are mutually exclusive.")
238 elif self.state == 'absent':
239 if not self.mdiskgrp:
240 self.module.fail_json(msg="Parameter [mdiskgrp] is required when deleting an MDisk.")
241 invalids = ('drive', 'driveclass', 'level', 'drivecount', 'old_name', 'stripewidth', 'tier')
242 invalid_exists = ', '.join((var for var in invalids if getattr(self, var) not in {'', None}))
243
244 if invalid_exists:
245 self.module.fail_json(
246 msg='Following parameters are not applicable while deleting: {0}'.format(invalid_exists))
247
248 def mdisk_exists(self, name):
249 merged_result = {}
250 data = self.restapi.svc_obj_info(
251 cmd='lsmdisk',
252 cmdopts={},
253 cmdargs=['-gui', name]
254 )
255
256 if isinstance(data, list):
257 for d in data:
258 merged_result.update(d)
259 else:
260 merged_result = data
261
262 return merged_result
263
264 def mdisk_rename(self, mdisk_data):
265 msg = None
266 old_mdisk_data = self.mdisk_exists(self.old_name)
267 if not old_mdisk_data and not mdisk_data:
268 self.module.fail_json(msg="mdisk [{0}] does not exists.".format(self.old_name))
269 elif old_mdisk_data and mdisk_data:
270 self.module.fail_json(msg="mdisk with name [{0}] already exists.".format(self.name))
271 elif not old_mdisk_data and mdisk_data:
272 msg = "mdisk [{0}] already renamed.".format(self.name)
273 elif old_mdisk_data and not mdisk_data:
274 # when check_mode is enabled
275 if self.module.check_mode:
276 self.changed = True
277 return
278 self.restapi.svc_run_command('chmdisk', {'name': self.name}, [self.old_name])
279 self.changed = True
280 msg = "mdisk [{0}] has been successfully rename to [{1}].".format(self.old_name, self.name)
281 return msg
282
283 def mdisk_create(self):
284 if self.drive:
285 if self.drivecount or self.driveclass or self.stripewidth:
286 self.module.fail_json(msg="The parameters 'drive' and "
287 "'driveclass, drivecount, stripewidth' are mutually exclusive.")
288 elif self.drivecount and self.driveclass:
289 if self.drivecount and not (2 <= int(self.drivecount) <= 128):
290 self.module.fail_json(msg="You must pass drivecount value in the range 2 - 128 only.")
291
292 if self.stripewidth and not (2 <= int(self.stripewidth) <= 16):
293 self.module.fail_json(msg="You must pass stripewidth value in the range 2 - 16 only.")
294 else:
295 self.module.fail_json(msg="You must pass any one of the following two: "
296 "(1) 'drive' for RAID array "
297 "(2) 'driveclass and drivecount' for DRAID array.")
298
299 if not self.level:
300 self.module.fail_json(msg="You must pass in level to the module.")
301 if not self.mdiskgrp:
302 self.module.fail_json(msg="You must pass in mdiskgrp to the module.")
303
304 if self.module.check_mode:
305 self.changed = True
306 return
307
308 self.log("creating mdisk '%s'", self.name)
309
310 # Make command
311 cmdopts = {}
312 if self.drive:
313 cmd = 'mkarray'
314 cmdopts['drive'] = self.drive
315 elif self.driveclass and self.drivecount:
316 cmd = 'mkdistributedarray'
317 cmdopts['driveclass'] = self.driveclass
318 cmdopts['drivecount'] = self.drivecount
319 cmdopts['allowsuperior'] = True
320 if self.stripewidth:
321 cmdopts['stripewidth'] = self.stripewidth
322
323 if self.encrypt:
324 cmdopts['encrypt'] = self.encrypt
325
326 cmdopts['level'] = self.level
327 cmdopts['strip'] = 256
328 cmdopts['name'] = self.name
329 cmdargs = [self.mdiskgrp]
330 self.log("creating mdisk command=%s opts=%s args=%s",
331 cmd, cmdopts, cmdargs)
332
333 # Run command
334 result = self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
335 self.log("create mdisk result %s", result)
336
337 if 'message' in result:
338 self.changed = True
339 self.log("create mdisk result message %s", result['message'])
340 else:
341 self.module.fail_json(
342 msg="Failed to create mdisk [%s]" % self.name)
343
344 def mdisk_delete(self):
345 if self.module.check_mode:
346 self.changed = True
347 return
348
349 self.log("deleting mdisk '%s'", self.name)
350 cmd = 'rmmdisk'
351 cmdopts = {}
352 cmdopts['mdisk'] = self.name
353 cmdargs = [self.mdiskgrp]
354
355 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
356
357 # Any error will have been raised in svc_run_command
358 # chmkdiskgrp does not output anything when successful.
359 self.changed = True
360
361 def mdisk_update(self, modify):
362 cmd = 'chmdisk'
363 cmdopts = {}
364
365 if 'tier' in modify:
366 cmdopts['tier'] = self.tier
367
368 if cmdopts:
369 cmdargs = [self.name]
370 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
371 # Any error will have been raised in svc_run_command
372 # chhost does not output anything when successful.
373 self.changed = True
374
375 # TBD: Implement a more generic way to check for properties to modify.
376 def mdisk_probe(self, data):
377 props = []
378
379 field_mappings = (
380 ('drivecount', data.get('drive_count')),
381 ('level', data.get('raid_level')),
382 ('encrypt', data.get('encrypt')),
383 ('tier', data.get('tier'))
384 )
385
386 for field, existing_value in field_mappings:
387 new_value = getattr(self, field, None)
388 if new_value is not None and new_value != existing_value:
389 props.append(field)
390
391 self.log("mdisk_probe props='%s'", props)
392 return props
393
394 def apply(self):
395 changed = False
396 msg = None
397 modify = []
398
399 mdisk_data = self.mdisk_exists(self.name)
400 if self.state == 'present' and self.old_name:
401 msg = self.mdisk_rename(mdisk_data)
402 elif self.state == 'absent' and self.old_name:
403 self.module.fail_json(msg="Rename functionality is not supported when 'state' is absent.")
404 else:
405 if mdisk_data:
406 if self.state == 'absent':
407 self.log("CHANGED: mdisk exists, but "
408 "requested state is 'absent'")
409 changed = True
410 elif self.state == 'present':
411 # This is where we detect if chmdisk should be called.
412 modify = self.mdisk_probe(mdisk_data)
413 if modify:
414 changed = True
415
416 else:
417 if self.state == 'present':
418 self.log("CHANGED: mdisk does not exist, "
419 "but requested state is 'present'")
420 changed = True
421
422 if changed:
423 if self.state == 'present':
424 if not mdisk_data:
425 self.mdisk_create()
426 self.changed = True
427 msg = "Mdisk [%s] has been created." % self.name
428 else:
429 # This is where we would modify
430 self.mdisk_update(modify)
431 msg = "Mdisk [%s] has been modified." % self.name
432 self.changed = True
433 elif self.state == 'absent':
434 self.mdisk_delete()
435 msg = "Mdisk [%s] has been deleted." % self.name
436 self.changed = True
437 else:
438 self.log("exiting with no changes")
439 if self.state == 'absent':
440 msg = "Mdisk [%s] did not exist." % self.name
441 else:
442 msg = "Mdisk [%s] already exists. No modifications done" % self.name
443
444 if self.module.check_mode:
445 msg = 'skipping changes due to check mode'
446
447 self.module.exit_json(msg=msg, changed=self.changed)
448
449
450 def main():
451 v = IBMSVCmdisk()
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()