Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (C) 2020 IBM CORPORATION
5 # Author(s): Peng Wang <[email protected]>
6 # Sreshtant Bohidar <[email protected]>
7 # Rohit Kumar <[email protected]>
8 # Sudheesh Reddy Satti<[email protected]>
9 # Sandip Gulab Rajbanshi <[email protected]>
10 # Lavanya C R <[email protected]>
11 # Rahul Pawar <[email protected]>
12 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
13
14 from __future__ import absolute_import, division, print_function
15 __metaclass__ = type
16
17 DOCUMENTATION = '''
18 ---
19 module: ibm_svc_host
20 short_description: This module manages hosts on IBM Storage Virtualize family systems
21 version_added: "1.0.0"
22 description:
23 - Ansible interface to manage 'mkhost', 'chhost', and 'rmhost' host commands.
24 options:
25 name:
26 description:
27 - Specifies a name or label for the new host object.
28 required: true
29 type: str
30 state:
31 description:
32 - Creates or updates (C(present)) or removes (C(absent)) a host.
33 choices: [ absent, present ]
34 required: true
35 type: str
36 clustername:
37 description:
38 - The hostname or management IP or Partition IP of the Storage Virtualize system.
39 required: true
40 type: str
41 domain:
42 description:
43 - Domain for the Storage Virtualize system.
44 - Valid when hostname is used for the parameter I(clustername).
45 type: str
46 username:
47 description:
48 - REST API username for the Storage Virtualize system.
49 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
50 type: str
51 password:
52 description:
53 - REST API password for the Storage Virtualize system.
54 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
55 type: str
56 token:
57 description:
58 - The authentication token to verify a user on the Storage Virtualize system.
59 - To generate a token, use the M(ibm.storage_virtualize.ibm_svc_auth) module.
60 type: str
61 version_added: '1.5.0'
62 fcwwpn:
63 description:
64 - List of Initiator WWPNs to be added to the host. The complete list of WWPNs must be provided.
65 - The parameters I(fcwwpn) and I(iscsiname) are mutually exclusive.
66 - Required when I(state=present), to create or modify a Fibre Channel (FC) host.
67 type: str
68 iscsiname:
69 description:
70 - List of Initiator IQNs to be added to the host. IQNs are separated by comma. The complete list of IQNs must be provided.
71 - The parameters I(fcwwpn) and I(iscsiname) are mutually exclusive.
72 - Valid when I(state=present), to create host.
73 type: str
74 iogrp:
75 description:
76 - Specifies a set of one or more input/output (I/O) groups from which the host can access the volumes.
77 Once specified, this parameter cannot be modified.
78 - Valid when I(state=present), to create a host.
79 type: str
80 nqn:
81 description:
82 - List of initiator NQNs to be added to the host. Each NQN is separated by a comma. The complete list of NQNs must be provided.
83 - Required when I(protocol=rdmanvme or tcpnvme), to create.
84 - Valid when I(state=present), to create or modify a host.
85 type: str
86 version_added: '1.12.0'
87 protocol:
88 description:
89 - Specifies the protocol used by the host to communicate with the storage system. Only 'scsi' protocol is supported.
90 - Valid when I(state=present), to create a host.
91 choices: [scsi, rdmanvme, tcpnvme, fcnvme, iscsi, fcscsi]
92 type: str
93 type:
94 description:
95 - Specifies the type of host.
96 - Valid when I(state=present), to create or modify a host.
97 type: str
98 site:
99 description:
100 - Specifies the site name of the host.
101 - Valid when I(state=present), to create or modify a host.
102 - If I(site) is specified as an empty string (""), it is treated as nosite, indicating the removal of the existing site.
103 type: str
104 hostcluster:
105 description:
106 - Specifies the name of the host cluster to which the host object is to be added.
107 A host cluster must exist before a host object can be added to it.
108 - Parameters I(hostcluster) and I(nohostcluster) are mutually exclusive.
109 - Valid when I(state=present), to create or modify a host.
110 type: str
111 version_added: '1.5.0'
112 nohostcluster:
113 description:
114 - If specified as C(True), host object is removed from the host cluster.
115 - Parameters I(hostcluster) and I(nohostcluster) are mutually exclusive.
116 - Valid when I(state=present), to modify an existing host.
117 type: bool
118 version_added: '1.5.0'
119 old_name:
120 description:
121 - Specifies the old name of the host while renaming.
122 - Valid when I(state=present), to rename an existing host.
123 type: str
124 version_added: '1.9.0'
125 portset:
126 description:
127 - Specifies the portset to be associated with the host.
128 - Valid when I(state=present), to create or modify a host.
129 type : str
130 version_added: '1.12.0'
131 partition:
132 description:
133 - Specifies the storage partition to be associated with the host.
134 - Valid when I(state=present), to create or modify a host.
135 - Supported from Storage Virtualize family systems 8.6.1.0 or later.
136 type : str
137 version_added: '2.1.0'
138 nopartition:
139 description:
140 - If specified as C(True), the host object is removed from the storage partition.
141 - Parameters I(partition) and I(nopartition) are mutually exclusive.
142 - Valid when I(state=present), to modify an existing host.
143 - Supported from Storage Virtualize family systems 8.6.1.0 or later.
144 type : bool
145 version_added: '2.1.0'
146 draftpartition:
147 description:
148 - Specifies the name of the draft partition to be assigned to the host.
149 - Valid when I(state=present), to modify a host.
150 - Supported from Storage Virtualize family systems 8.6.3.0 or later.
151 type : str
152 version_added: '2.5.0'
153 nodraftpartition:
154 description:
155 - If specified as C(True), the host object is removed from the draft partition.
156 - Parameters I(draftpartition) and I(nodraftpartition) are mutually exclusive.
157 - Valid when I(state=present), to modify an existing host.
158 - Supported from Storage Virtualize family systems 8.6.3.0 or later.
159 type : bool
160 version_added: '2.5.0'
161 suppressofflinealert:
162 description:
163 - If specified as C(yes), an event will not be generated if host is offline.
164 - Valid when I(state=present), to modify an existing host.
165 - Supported from Storage Virtualize family systems 8.7.2.0 or later.
166 choices: ['yes', 'no']
167 type : str
168 version_added: '2.7.0'
169 log_path:
170 description:
171 - Path of debug log file.
172 type: str
173 validate_certs:
174 description:
175 - Validates certification.
176 default: false
177 type: bool
178 fdminame:
179 description:
180 - Host object to be created from the fdminame. The valid fdminame should be provided for host creation.
181 - The parameters I(fcwwpn) and I(fdminame) are mutually exclusive.
182 - Parameter is mutually exlusive with other parameters saswwpn,fcwwpn,iscsiname and nqn.
183 - Valid when I(state=present), to create host.
184 type: str
185 version_added: '2.7.0'
186 location:
187 description:
188 - Specifies the system ID or system name that is co-located with this host.
189 - If set to blank (""), the host will normally submit I/O operations to the storage partition's preferred system.
190 - Valid when I(state=present), to modify an existing host.
191 - Supported from Storage Virtualize family systems 8.7.0.0 or later.
192 - Creating a host with a location, or changing the location of a host, is only permitted if the host is associated with
193 a storage partition configured for high availability.
194 type : str
195 version_added: '2.7.0'
196 author:
197 - Sreshtant Bohidar (@Sreshtant-Bohidar)
198 - Rohit Kumar (@rohitk-github)
199 - Sandip G. Rajbanshi (@Sandip-Rajbanshi)
200 - Lavanya C R(@Lavanya-C-R1)
201 notes:
202 - This module supports C(check_mode).
203 - scsi option is deprecated from 8.5.0.0. Instead of scsi, use iscsi and fcscsi as the case may be.
204 - This module supports logging in via partition IP.
205 - Parameters not supported when logged in via partition IP are 'site', 'iogrp', 'partition', 'nopartition', 'draftpartition',
206 'site', 'nosite'.
207 '''
208
209 EXAMPLES = '''
210 - name: Define a new iSCSI host
211 ibm.storage_virtualize.ibm_svc_host:
212 clustername: "{{ clustername }}"
213 domain: "{{ domain }}"
214 username: "{{ username }}"
215 password: "{{ password }}"
216 log_path: /tmp/playbook.debug
217 name: iscsi_host0
218 state: present
219 iscsiname: iqn.1994-05.com.redhat:2e358e438b8a
220 iogrp: 0:1:2:3
221 protocol: scsi
222 type: generic
223 site: site-name
224 portset: portset0
225 - name: Add a host to an existing host cluster
226 ibm.storage_virtualize.ibm_svc_host:
227 clustername: "{{ clustername }}"
228 domain: "{{ domain }}"
229 username: "{{ username }}"
230 password: "{{ password }}"
231 log_path: /tmp/playbook.debug
232 name: host0
233 state: present
234 hostcluster: hostcluster0
235 - name: Define a new FC host
236 ibm.storage_virtualize.ibm_svc_host:
237 clustername: "{{ clustername }}"
238 domain: "{{ domain }}"
239 username: "{{ username }}"
240 password: "{{ password }}"
241 log_path: /tmp/playbook.debug
242 name: fc_host0
243 state: present
244 fcwwpn: 100000109B570216:1000001AA0570266
245 iogrp: 0:1:2:3
246 protocol: scsi
247 type: generic
248 site: site-name
249 - name: Rename an existing host
250 ibm.storage_virtualize.ibm_svc_host:
251 clustername: "{{ clustername }}"
252 domain: "{{ domain }}"
253 username: "{{ username }}"
254 password: "{{ password }}"
255 old_name: "old_host_name"
256 name: "new_host_name"
257 state: "present"
258 - name: Create an iSCSI host
259 ibm.storage_virtualize.ibm_svc_host:
260 clustername: "{{ clustername }}"
261 domain: "{{ domain }}"
262 username: "{{ username }}"
263 password: "{{ password }}"
264 log_path: /tmp/playbook.debug
265 name: iscsi_host0
266 iscsiname: iqn.1994-05.com.redhat:2e358e438b8a,iqn.localhost.hostid.7f000001
267 state: present
268 - name: Create a tcpnvme host
269 ibm.storage_virtualize.ibm_svc_host:
270 clustername: "{{ clustername }}"
271 domain: "{{ domain }}"
272 username: "{{ username }}"
273 password: "{{ password }}"
274 log_path: /tmp/playbook.debug
275 name: tcpnvme_host0
276 protocol: tcpnvme
277 nqn: nqn.2014-08.org.nvmexpress:NVMf:uuid:644f51bf-8432-4f59-bb13-5ada20c06397
278 state: present
279 - name: Delete a host
280 ibm.storage_virtualize.ibm_svc_host:
281 clustername: "{{ clustername }}"
282 domain: "{{ domain }}"
283 username: "{{ username }}"
284 password: "{{ password }}"
285 log_path: /tmp/playbook.debug
286 name: host0
287 state: absent
288 - name: Add existing host to draft partition
289 ibm.storage_virtualize.ibm_svc_host:
290 clustername: "{{ clustername }}"
291 domain: "{{ domain }}"
292 username: "{{ username }}"
293 password: "{{ password }}"
294 log_path: /tmp/playbook.debug
295 name: host0
296 state: prersent
297 draftpartition: partition_name
298 - name: Remove a host from a draft partition
299 ibm.storage_virtualize.ibm_svc_host:
300 clustername: "{{ clustername }}"
301 domain: "{{ domain }}"
302 username: "{{ username }}"
303 password: "{{ password }}"
304 log_path: /tmp/playbook.debug
305 name: host0
306 state: present
307 nodraftpartition: 'True'
308 - name: Create a fcnvme host
309 ibm.storage_virtualize.ibm_svc_host:
310 clustername: "{{ clustername }}"
311 domain: "{{ domain }}"
312 username: "{{ username }}"
313 password: "{{ password }}"
314 log_path: /tmp/playbook.debug
315 name: fcnvme_host0
316 protocol: fcnvme
317 nqn: nqn.2014-08.org.nvmexpress:b2071fa4-4356-410f-a4ae-7ebfab5b0e90
318 portset: portset_name
319 state: present
320 - name: Create an fdmi host
321 ibm.storage_virtualize.ibm_svc_host:
322 clustername: "{{ clustername }}"
323 domain: "{{ domain }}"
324 username: "{{ username }}"
325 password: "{{ password }}"
326 log_path: /tmp/playbook.debug
327 name: fdmi_host0
328 fdminame: Ansible-Host-1
329 state: present
330 - name: Create a host with preferred location.
331 ibm.storage_virtualize.ibm_svc_host:
332 clustername: '{{ clustername }}'
333 username: '{{ username }}'
334 password: '{{ password }}'
335 state: present
336 name: host0
337 location: fs9500cl-2
338 partition: ha-partition-0
339 - name: Remove the currently set location from host.
340 ibm.storage_virtualize.ibm_svc_host:
341 clustername: '{{ clustername }}'
342 username: '{{ username }}'
343 password: '{{ password }}'
344 state: present
345 name: host0
346 location: ""
347 - name: Remove the currently set site from host.
348 ibm.storage_virtualize.ibm_svc_host:
349 clustername: '{{ clustername }}'
350 username: '{{ username }}'
351 password: '{{ password }}'
352 state: present
353 name: host0
354 site: ""
355 - name: Create a fcnvme host inside a partition
356 ibm.storage_virtualize.ibm_svc_host:
357 clustername: "{{ clustername }}"
358 domain: "{{ domain }}"
359 username: "{{ username }}"
360 password: "{{ password }}"
361 log_path: /tmp/playbook.debug
362 name: fcnvme_host0
363 protocol: fcnvme
364 nqn: nqn.2014-08.org.nvmexpress:b2071fa4-4356-410f-a4ae-7ebfab5b0e90
365 portset: postset0
366 state: present
367 - name: Create a tcpnvme host inside a partition
368 ibm.storage_virtualize.ibm_svc_host:
369 clustername: "{{ clustername }}"
370 domain: "{{ domain }}"
371 username: "{{ username }}"
372 password: "{{ password }}"
373 log_path: /tmp/playbook.debug
374 name: tcpnvme_host0
375 protocol: tcpnvme
376 nqn: nqn.2014-08.org.nvmexpress:b2071fa4-4356-410f-a4ae-7ebfab5b0e90
377 portset: postset0
378 state: present
379 '''
380
381 RETURN = '''#'''
382
383 from traceback import format_exc
384 from ansible.module_utils.basic import AnsibleModule
385 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import IBMSVCRestApi, svc_argument_spec, get_logger
386 from ansible.module_utils._text import to_native
387
388 CMMVC5737E_MESSAGE = 'CMMVC5737E The parameter {0} has been entered multiple times. Enter the parameter only one time.'
389
390
391 class IBMSVChost(object):
392 def __init__(self):
393 argument_spec = svc_argument_spec()
394
395 argument_spec.update(
396 dict(
397 name=dict(type='str', required=True),
398 state=dict(type='str', required=True, choices=['absent',
399 'present']),
400 fcwwpn=dict(type='str', required=False),
401 iscsiname=dict(type='str', required=False),
402 iogrp=dict(type='str', required=False),
403 protocol=dict(type='str', required=False, choices=['scsi',
404 'rdmanvme',
405 'tcpnvme',
406 'fcnvme',
407 'fcscsi',
408 'iscsi']),
409 type=dict(type='str'),
410 site=dict(type='str'),
411 hostcluster=dict(type='str'),
412 nohostcluster=dict(type='bool'),
413 old_name=dict(type='str', required=False),
414 nqn=dict(type='str', required=False),
415 portset=dict(type='str', required=False),
416 partition=dict(type='str', required=False),
417 nopartition=dict(type='bool', required=False),
418 draftpartition=dict(type='str', required=False),
419 nodraftpartition=dict(type='bool', required=False),
420 fdminame=dict(type='str', required=False),
421 suppressofflinealert=dict(type='str', required=False, choices=['yes', 'no']),
422 location=dict(type='str')
423 )
424 )
425
426 self.module = AnsibleModule(argument_spec=argument_spec,
427 supports_check_mode=True)
428
429 # logging setup
430 log_path = self.module.params['log_path']
431 log = get_logger(self.__class__.__name__, log_path)
432 self.log = log.info
433
434 # Required
435 self.name = self.module.params['name']
436 self.state = self.module.params['state']
437
438 # Optional
439 self.fcwwpn = self.module.params.get('fcwwpn', '')
440 self.iscsiname = self.module.params.get('iscsiname', '')
441 self.iogrp = self.module.params.get('iogrp', '')
442 self.protocol = self.module.params.get('protocol', '')
443 self.type = self.module.params.get('type', '')
444 self.site = self.module.params.get('site', '')
445 self.hostcluster = self.module.params.get('hostcluster', '')
446 self.nohostcluster = self.module.params.get('nohostcluster', '')
447 self.old_name = self.module.params.get('old_name', '')
448 self.nqn = self.module.params.get('nqn', '')
449 self.portset = self.module.params.get('portset', '')
450 self.partition = self.module.params.get('partition', '')
451 self.nopartition = self.module.params.get('nopartition', '')
452 self.draftpartition = self.module.params.get('draftpartition', '')
453 self.nodraftpartition = self.module.params.get('nodraftpartition', '')
454 self.fdminame = self.module.params.get('fdminame', '')
455 self.suppressofflinealert = self.module.params.get('suppressofflinealert', '')
456 self.location = self.module.params.get('location', '')
457
458 # internal variable
459 self.changed = False
460
461 # Handling duplicate fcwwpn
462 if self.fcwwpn:
463 dup_fcwwpn = self.duplicate_checker(self.fcwwpn.split(':'))
464 if dup_fcwwpn:
465 self.module.fail_json(msg=CMMVC5737E_MESSAGE.format(dup_fcwwpn))
466
467 # Handling duplicate iscsiname
468 if self.iscsiname:
469 dup_iscsiname = self.duplicate_checker(self.iscsiname.split(','))
470 if dup_iscsiname:
471 self.module.fail_json(msg=CMMVC5737E_MESSAGE.format(dup_iscsiname))
472
473 # Handling duplicate nqn
474 if self.nqn:
475 dup_nqn = self.duplicate_checker(self.nqn.split(','))
476 if dup_nqn:
477 self.module.fail_json(msg=CMMVC5737E_MESSAGE.format(dup_nqn))
478
479 # Handling for missing mandatory parameter name
480 if not self.name:
481 self.module.fail_json(msg='Missing mandatory parameter: name')
482 # Handling for parameter protocol
483 if self.protocol:
484 if self.protocol not in ('scsi', 'rdmanvme', 'tcpnvme', 'fcnvme', 'iscsi', 'fcscsi'):
485 self.module.fail_json(msg="[{0}] is not supported for iscsiname. only 'scsi', 'rdmanvme', 'tcpnvme', and 'fcnvme' "
486 "protocols are supported.".format(self.protocol))
487
488 self.restapi = IBMSVCRestApi(
489 module=self.module,
490 clustername=self.module.params['clustername'],
491 domain=self.module.params['domain'],
492 username=self.module.params['username'],
493 password=self.module.params['password'],
494 validate_certs=self.module.params['validate_certs'],
495 log_path=log_path,
496 token=self.module.params['token']
497 )
498
499 def basic_checks(self):
500 if self.state == 'present':
501 mutually_exclusive = (
502 ('hostcluster', 'nohostcluster'),
503 ('partition', 'nopartition'),
504 ('draftpartition', 'nodraftpartition'),
505 ('draftpartition', 'partition'),
506 )
507 for param1, param2 in mutually_exclusive:
508 if getattr(self, param1) and getattr(self, param2):
509 self.module.fail_json(msg='Mutually exclusive parameters: {0}, {1}'.format(param1, param2))
510
511 if self.nqn and not self.protocol:
512 self.module.fail_json(msg='Parameter [nqn] can only be entered when [protocol] has been entered.')
513
514 if self.state == 'absent':
515 fields = [f for f in ['protocol', 'portset', 'nqn', 'type', 'partition', 'nopartition', 'draftpartition', 'nodraftpartition',
516 'suppressofflinealert', 'location', 'fdminame', 'iscsiname', 'fcwwpn', 'iogrp', 'site'] if getattr(self, f)]
517
518 if any(fields):
519 self.module.fail_json(msg='Parameters {0} not supported while deleting a host'.format(', '.join(fields)))
520
521 def parameter_handling_while_renaming(self):
522 # for validating parameter while renaming a host
523 parameters = {
524 "fcwwpn": self.fcwwpn,
525 "iscsiname": self.iscsiname,
526 "iogrp": self.iogrp,
527 "protocol": self.protocol,
528 "type": self.type,
529 "site": self.site,
530 "hostcluster": self.hostcluster,
531 "nohostcluster": self.nohostcluster,
532 "partition": self.partition,
533 "nopartition": self.nopartition,
534 "fdminame": self.fdminame,
535 "suppressofflinealert": self.suppressofflinealert
536 }
537 parameters_exists = [parameter for parameter, value in parameters.items() if value]
538 if parameters_exists:
539 self.module.fail_json(msg="Parameters {0} not supported while renaming a host.".format(parameters_exists))
540
541 def duplicate_checker(self, items):
542 unique_items = set(items)
543 if len(items) != len(unique_items):
544 return [element for element in unique_items if items.count(element) > 1]
545 else:
546 return []
547
548 def get_existing_host(self, host_name):
549 merged_result = {}
550
551 data = self.restapi.svc_obj_info(cmd='lshost', cmdopts=None, cmdargs=['-gui', host_name])
552
553 if isinstance(data, list):
554 for d in data:
555 merged_result.update(d)
556 else:
557 merged_result = data
558
559 return merged_result
560
561 def validate_iogrp(self):
562 all_iogrps = self.restapi.svc_obj_info(cmd='lsiogrp', cmdopts=None, cmdargs=None)
563 all_iogrps_map = {iog['name']: iog['id'] for iog in all_iogrps if iog['name'] != 'recovery_io_grp'}
564
565 valid_names = set(all_iogrps_map.keys())
566 valid_ids = set(all_iogrps_map.values())
567
568 input_iogrps = self.iogrp.split(":")
569 parsed_input_iogrp = set()
570
571 for iogrp in input_iogrps:
572 if iogrp.isdigit():
573 if iogrp not in valid_ids:
574 self.module.fail_json(msg=f"The value [{iogrp}] is not a valid IO group id")
575 parsed_input_iogrp.add(iogrp)
576 else:
577 if iogrp not in valid_names:
578 self.module.fail_json(msg=f"The value [{iogrp}] is not a valid IO group name")
579 parsed_input_iogrp.add(all_iogrps_map[iogrp])
580
581 if len(parsed_input_iogrp) != len(input_iogrps):
582 self.module.fail_json(msg='Duplicate iogrp detected.')
583
584 self.input_iogrps_id = parsed_input_iogrp
585
586 # TBD: Implement a more generic way to check for properties to modify.
587 def host_probe(self, data):
588 props = []
589
590 if self.hostcluster and (self.hostcluster != data['host_cluster_name']):
591 if data['host_cluster_name'] != '':
592 self.module.fail_json(msg="Host already belongs to hostcluster [%s]" % data['host_cluster_name'])
593 else:
594 props += ['hostcluster']
595
596 # TBD: The parameter is fcwwpn but the view has fcwwpn label.
597 if self.type:
598 if self.type != data['type']:
599 props += ['type']
600
601 if self.fcwwpn:
602 self.existing_fcwwpn = [node["WWPN"] for node in data['nodes'] if "WWPN" in node]
603 self.input_fcwwpn = self.fcwwpn.upper().split(":")
604 if set(self.existing_fcwwpn).symmetric_difference(set(self.input_fcwwpn)):
605 props += ['fcwwpn']
606
607 if self.iscsiname:
608 self.existing_iscsiname = [node["iscsi_name"] for node in data['nodes'] if "iscsi_name" in node]
609 self.input_iscsiname = self.iscsiname.split(",")
610 if set(self.existing_iscsiname).symmetric_difference(set(self.input_iscsiname)):
611 props += ['iscsiname']
612
613 if self.fdminame:
614 lsfabric_data = self.restapi.svc_obj_info(cmd='lsfabric', cmdopts={'host': self.name}, cmdargs=None)
615 if self.fdminame != lsfabric_data[0]['fdmi_host_name']:
616 self.module.fail_json(msg="Host already exist, Parameter fdminame is not supported for updation.")
617
618 if self.iogrp:
619 self.validate_iogrp()
620 existing_host_iogrps = self.restapi.svc_obj_info(cmd='lshostiogrp', cmdopts=None, cmdargs=[self.name])
621 existing_host_iogrps_id = set({node["id"] for node in existing_host_iogrps})
622
623 if self.input_iogrps_id.symmetric_difference(existing_host_iogrps_id): # Symmetric difference finds elements that are in either set but not both.
624 iogrps_to_add = self.input_iogrps_id.difference(existing_host_iogrps_id) # IO_Grps in input but not in existing
625 iogrps_to_remove = existing_host_iogrps_id.difference(self.input_iogrps_id) # IO_Grps in existing but not in input
626
627 self.iogrps_to_add = list(iogrps_to_add) if iogrps_to_add else None
628 self.iogrps_to_remove = list(iogrps_to_remove) if iogrps_to_remove else None
629
630 if iogrps_to_add or iogrps_to_remove:
631 props += ['iogrp']
632
633 if self.nqn:
634 self.existing_nqn = [node["nqn"] for node in data['nodes'] if "nqn" in node]
635 self.input_nqn = self.nqn.split(",")
636 if set(self.existing_nqn).symmetric_difference(set(self.input_nqn)):
637 props += ['nqn']
638
639 if self.site is not None:
640 if self.site != "" and self.site != data['site_name'] and self.site != data['site_id']:
641 props.append('site')
642 elif self.site == "" and data['site_name'] != "":
643 self.nosite = True
644 props.append('nosite')
645
646 if self.nohostcluster:
647 if data['host_cluster_name'] != '':
648 props += ['nohostcluster']
649
650 if self.portset:
651 if self.portset != data['portset_name']:
652 props += ['portset']
653
654 if self.partition and self.partition != data['partition_name']:
655 if data['partition_name'] != '':
656 self.module.fail_json(msg="Host already belongs to partition [%s]" % data['partition_name'])
657 else:
658 props += ['partition']
659
660 if self.nopartition:
661 if data['partition_name'] != '':
662 props += ['nopartition']
663
664 if self.draftpartition:
665 if self.draftpartition == data['draft_partition_name']:
666 self.log("Host [%s] is already associated with draft partition [%s].", self.name, self.draftpartition)
667 elif self.draftpartition == data['partition_name']:
668 self.log("Host [%s] is already associated with partition [%s].", self.name, self.draftpartition)
669 else:
670 props += ['draftpartition']
671
672 if self.nodraftpartition:
673 if data['draft_partition_name'] != '':
674 props += ['nodraftpartition']
675
676 if self.suppressofflinealert:
677 if data['offline_alert_suppressed'] != self.suppressofflinealert:
678 props += ['suppressofflinealert']
679
680 if self.location is not None:
681 if self.location != "" and self.location != data['location_system_name'] and self.location != data['location_system_id']:
682 props += ["location"]
683 elif self.location == "" and data['location_system_name'] != "":
684 self.nolocation = True
685 props += ['nolocation']
686
687 self.log("host_probe props='%s'", props)
688 return props
689
690 def host_create(self):
691 if (not self.fcwwpn) and (not self.iscsiname) and (not self.nqn) and (not self.fdminame):
692 self.module.fail_json(msg="One of fcwwpn, iscsiname, nqn or fdminame must be provided to create a new host.")
693
694 if (self.fcwwpn and self.iscsiname) or (self.nqn and self.iscsiname) or (
695 self.fcwwpn and self.nqn) or (self.fcwwpn and self.fdminame) or (
696 self.iscsiname and self.fdminame) or (self.nqn and self.fdminame):
697 self.module.fail_json(msg="You have to pass only one parameter among fcwwpn, nqn, iscsiname and fdminame to the module.")
698
699 if self.draftpartition:
700 self.module.fail_json(msg='[draftpartition] is not a supported parameter while creating host')
701 elif self.nodraftpartition:
702 self.module.fail_json(msg='[nodraftpartition] is not a supported parameter while creating host')
703 if self.location and not self.partition:
704 self.module.fail_json(msg='Parameter [location] can only be entered when [partition] has been entered.')
705 if self.module.check_mode:
706 self.changed = True
707 return
708
709 self.log("creating host '%s'", self.name)
710
711 # Make command
712 cmd = 'mkhost'
713 cmdopts = {'name': self.name, 'force': True}
714
715 for field in ['fcwwpn', 'iscsiname', 'nqn', 'fdminame']:
716 value = getattr(self, field, None)
717 if value is not None:
718 cmdopts[field] = value
719 break # only one of these can be set
720
721 if self.iogrp:
722 self.validate_iogrp()
723
724 cmdopts['protocol'] = self.protocol if self.protocol else 'scsi'
725 for field in ['iogrp', 'type', 'site', 'portset', 'partition', 'location']:
726 value = getattr(self, field, None)
727 if value is not None:
728 cmdopts[field] = value
729
730 self.log("Command options for creating host: '%s'", cmdopts)
731
732 # Run command
733 result = self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
734 self.log("create host result '%s'", result)
735
736 if result and 'message' in result:
737 self.changed = True
738 self.log("create host result message '%s'", (result['message']))
739 else:
740 self.module.fail_json(
741 msg="Failed to create host [%s]" % self.name)
742
743 def host_fcwwpn_update(self):
744 to_be_removed = ':'.join(list(set(self.existing_fcwwpn) - set(self.input_fcwwpn)))
745 if to_be_removed:
746 self.restapi.svc_run_command(
747 'rmhostport',
748 {'fcwwpn': to_be_removed, 'force': True},
749 [self.name]
750 )
751 self.log('%s removed from %s', to_be_removed, self.name)
752 to_be_added = ':'.join(list(set(self.input_fcwwpn) - set(self.existing_fcwwpn)))
753 if to_be_added:
754 self.restapi.svc_run_command(
755 'addhostport',
756 {'fcwwpn': to_be_added, 'force': True},
757 [self.name]
758 )
759 self.log('%s added to %s', to_be_added, self.name)
760
761 def host_iscsiname_update(self):
762 to_be_removed = ','.join(list(set(self.existing_iscsiname) - set(self.input_iscsiname)))
763 if to_be_removed:
764 self.restapi.svc_run_command(
765 'rmhostport',
766 {'iscsiname': to_be_removed, 'force': True},
767 [self.name]
768 )
769 self.log('%s removed from %s', to_be_removed, self.name)
770 to_be_added = ','.join(list(set(self.input_iscsiname) - set(self.existing_iscsiname)))
771 if to_be_added:
772 self.restapi.svc_run_command(
773 'addhostport',
774 {'iscsiname': to_be_added, 'force': True},
775 [self.name]
776 )
777 self.log('%s added to %s', to_be_added, self.name)
778
779 def host_iogrp_update(self):
780 if self.iogrps_to_add is not None:
781 self.restapi.svc_run_command(
782 'addhostiogrp',
783 {'iogrp': ':'.join(self.iogrps_to_add)},
784 [self.name]
785 )
786 if self.iogrps_to_remove is not None:
787 self.restapi.svc_run_command(
788 'rmhostiogrp',
789 {'iogrp': ':'.join(self.iogrps_to_remove)},
790 [self.name]
791 )
792
793 def host_nqn_update(self):
794 to_be_removed = ','.join(list(set(self.existing_nqn) - set(self.input_nqn)))
795 if to_be_removed:
796 self.restapi.svc_run_command(
797 'rmhostport',
798 {'nqn': to_be_removed, 'force': True},
799 [self.name]
800 )
801 self.log('%s removed from %s', to_be_removed, self.name)
802 to_be_added = ','.join(list(set(self.input_nqn) - set(self.existing_nqn)))
803 if to_be_added:
804 self.restapi.svc_run_command(
805 'addhostport',
806 {'nqn': to_be_added, 'force': True},
807 [self.name]
808 )
809 self.log('%s added to %s', to_be_added, self.name)
810
811 def host_update(self, modify, host_data):
812 # update the host
813 self.log("updating host '%s'", self.name)
814 if 'hostcluster' in modify:
815 self.addhostcluster()
816 modify.remove('hostcluster')
817 elif 'nohostcluster' in modify:
818 self.removehostcluster(host_data)
819 modify.remove('nohostcluster')
820
821 cmd = 'chhost'
822 cmdopts = {}
823 if 'fcwwpn' in modify:
824 self.host_fcwwpn_update()
825 self.changed = True
826 self.log("fcwwpn of %s updated", self.name)
827 modify.remove('fcwwpn')
828 if 'iscsiname' in modify:
829 self.host_iscsiname_update()
830 self.changed = True
831 self.log("iscsiname of %s updated", self.name)
832 modify.remove('iscsiname')
833 if 'iogrp' in modify:
834 self.host_iogrp_update()
835 self.changed = True
836 self.log("io_grp of %s updated", self.name)
837 modify.remove('iogrp')
838 if 'nqn' in modify:
839 self.host_nqn_update()
840 self.changed = True
841 self.log("nqn of %s updated", self.name)
842 modify.remove('nqn')
843
844 for param in modify:
845 cmdopts[param] = getattr(self, param)
846
847 if cmdopts:
848 cmdargs = [self.name]
849 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
850 # Any error will have been raised in svc_run_command
851 # chhost does not output anything when successful.
852 self.changed = True
853 self.log("type of %s updated", self.name)
854
855 def host_delete(self):
856 if self.module.check_mode:
857 self.changed = True
858 return
859
860 self.log("deleting host '%s'", self.name)
861
862 cmd = 'rmhost'
863 cmdopts = {}
864 cmdargs = [self.name]
865
866 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
867
868 # Any error will have been raised in svc_run_command
869 # chhost does not output anything when successful.
870 self.changed = True
871
872 def get_existing_hostcluster(self):
873 self.log("get_existing_hostcluster %s", self.hostcluster)
874
875 data = self.restapi.svc_obj_info(cmd='lshostcluster', cmdopts=None,
876 cmdargs=[self.hostcluster])
877
878 return data
879
880 def addhostcluster(self):
881 if self.module.check_mode:
882 self.changed = True
883 return
884
885 self.log("Adding host '%s' in hostcluster %s", self.name, self.hostcluster)
886
887 cmd = 'addhostclustermember'
888 cmdopts = {}
889 cmdargs = [self.hostcluster]
890
891 cmdopts['host'] = self.name
892
893 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
894
895 # Any error will have been raised in svc_run_command
896 # chhost does not output anything when successful.
897 self.changed = True
898
899 def removehostcluster(self, data):
900 if self.module.check_mode:
901 self.changed = True
902 return
903
904 self.log("removing host '%s' from hostcluster %s", self.name, data['host_cluster_name'])
905
906 hostcluster_name = data['host_cluster_name']
907
908 cmd = 'rmhostclustermember'
909 cmdopts = {}
910 cmdargs = [hostcluster_name]
911
912 cmdopts['host'] = self.name
913 cmdopts['keepmappings'] = True
914
915 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
916
917 # Any error will have been raised in svc_run_command
918 # chhost does not output anything when successful.
919 self.changed = True
920
921 # function for renaming an existing host with a new name
922 def host_rename(self, host_data):
923 msg = ''
924 self.parameter_handling_while_renaming()
925 old_host_data = self.get_existing_host(self.old_name)
926 if not old_host_data and not host_data:
927 self.module.fail_json(msg="Host [{0}] does not exists.".format(self.old_name))
928 elif old_host_data and host_data:
929 self.module.fail_json(msg="Host [{0}] already exists.".format(self.name))
930 elif not old_host_data and host_data:
931 msg = "Host with name [{0}] already exists.".format(self.name)
932 elif old_host_data and not host_data:
933 # when check_mode is enabled
934 if self.module.check_mode:
935 self.changed = True
936 return
937 self.restapi.svc_run_command('chhost', {'name': self.name}, [self.old_name])
938 self.changed = True
939 msg = "Host [{0}] has been successfully rename to [{1}].".format(self.old_name, self.name)
940 return msg
941
942 def apply(self):
943 changed = False
944 msg = None
945 modify = []
946
947 self.basic_checks()
948
949 host_data = self.get_existing_host(self.name)
950
951 if self.state == 'present' and self.old_name:
952 msg = self.host_rename(host_data)
953 elif self.state == 'absent' and self.old_name:
954 self.module.fail_json(msg="Rename functionality is not supported when 'state' is absent.")
955 else:
956 if host_data:
957 if self.state == 'absent':
958 self.log("CHANGED: host exists, but requested state is 'absent'")
959 changed = True
960 elif self.state == 'present':
961 # This is where we detect if chhost should be called
962 modify = self.host_probe(host_data)
963 if modify:
964 changed = True
965 else:
966 if self.state == 'present':
967 self.log("CHANGED: host does not exist, but requested state is 'present'")
968 changed = True
969
970 if changed:
971 if self.state == 'present':
972 if self.hostcluster:
973 hc_data = self.get_existing_hostcluster()
974 if hc_data is None:
975 self.module.fail_json(msg="Host cluster must already exist before its usage in this module")
976 elif not host_data and hc_data:
977 self.host_create()
978 self.addhostcluster()
979 msg = "host %s has been created and added to hostcluster." % self.name
980 elif not host_data:
981 self.host_create()
982 msg = "host %s has been created." % self.name
983 if host_data and modify:
984 # This is where we would modify
985 self.host_update(modify, host_data)
986 msg = "host [%s] has been modified." % self.name
987 elif self.state == 'absent':
988 self.host_delete()
989 msg = "host [%s] has been deleted." % self.name
990 else:
991 self.log("exiting with no changes")
992 if self.state == 'absent':
993 msg = "host [%s] did not exist." % self.name
994 else:
995 msg = "host [%s] already exists." % self.name
996 if self.module.check_mode:
997 msg = 'skipping changes due to check mode'
998
999 self.module.exit_json(msg=msg, changed=self.changed)
1000
1001
1002 def main():
1003 v = IBMSVChost()
1004 try:
1005 v.apply()
1006 except Exception as e:
1007 v.log("Exception in apply(): \n%s", format_exc())
1008 v.module.fail_json(msg="Module failed. Error [%s]." % to_native(e))
1009
1010
1011 if __name__ == '__main__':
1012 main()