Debian Codegraph @

ansible_collections/netapp_eseries/santricity/plugins/modules/na_santricity_host.py

raw
1 #!/usr/bin/python
2
3 # (c) 2024, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 from __future__ import absolute_import, division, print_function
6 __metaclass__ = type
7
8
9 DOCUMENTATION = """
10 ---
11 module: na_santricity_host
12 short_description: NetApp E-Series manage eseries hosts
13 description: Create, update, remove hosts on NetApp E-series storage arrays
14 author:
15 - Kevin Hulquest (@hulquest)
16 - Nathan Swartz (@swartzn)
17 - Vu Tran (@VuTran007)
18 extends_documentation_fragment:
19 - netapp_eseries.santricity.santricity.santricity_doc
20 options:
21 name:
22 description:
23 - If the host doesn't yet exist, the label/name to assign at creation time.
24 - If the hosts already exists, this will be used to uniquely identify the host to make any required changes
25 type: str
26 required: True
27 aliases:
28 - label
29 state:
30 description:
31 - Set to absent to remove an existing host
32 - Set to present to modify or create a new host definition
33 type: str
34 choices:
35 - absent
36 - present
37 default: present
38 host_type:
39 description:
40 - Host type includes operating system and multipath considerations.
41 - If not specified, the default host type will be utilized. Default host type can be set using M(netapp_eseries.santricity.na_santricity_global).
42 - For storage array specific options see M(netapp_eseries.santricity.na_santricity_facts).
43 - All values are case-insensitive.
44 - AIX MPIO - The Advanced Interactive Executive (AIX) OS and the native MPIO driver
45 - AVT 4M - Silicon Graphics, Inc. (SGI) proprietary multipath driver
46 - HP-UX - The HP-UX OS with native multipath driver
47 - Linux ATTO - The Linux OS and the ATTO Technology, Inc. driver (must use ATTO FC HBAs)
48 - Linux DM-MP - The Linux OS and the native DM-MP driver
49 - Linux Pathmanager - The Linux OS and the SGI proprietary multipath driver
50 - Mac - The Mac OS and the ATTO Technology, Inc. driver
51 - ONTAP - FlexArray
52 - Solaris 11 or later - The Solaris 11 or later OS and the native MPxIO driver
53 - Solaris 10 or earlier - The Solaris 10 or earlier OS and the native MPxIO driver
54 - SVC - IBM SAN Volume Controller
55 - VMware - ESXi OS
56 - Windows - Windows Server OS and Windows MPIO with a DSM driver
57 - Windows Clustered - Clustered Windows Server OS and Windows MPIO with a DSM driver
58 - Windows ATTO - Windows OS and the ATTO Technology, Inc. driver
59 type: str
60 required: False
61 aliases:
62 - host_type_index
63 ports:
64 description:
65 - A list of host ports you wish to associate with the host.
66 - Host ports are uniquely identified by their WWN or IQN. Their assignments to a particular host are
67 uniquely identified by a label and these must be unique.
68 type: list
69 elements: dict
70 required: False
71 suboptions:
72 type:
73 description:
74 - The interface type of the port to define.
75 - Acceptable choices depend on the capabilities of the target hardware/software platform.
76 required: true
77 choices:
78 - iscsi
79 - sas
80 - fc
81 - ib
82 - nvmeof
83 label:
84 description:
85 - A unique label to assign to this port assignment.
86 required: true
87 port:
88 description:
89 - The WWN or IQN of the hostPort to assign to this port definition.
90 required: true
91 force_port:
92 description:
93 - Allow ports that are already assigned to be re-assigned to your current host
94 required: false
95 type: bool
96 default: false
97 """
98
99 EXAMPLES = """
100 - name: Define or update an existing host named "Host1"
101 na_santricity_host:
102 ssid: "1"
103 api_url: "https://192.168.1.100:8443/devmgr/v2"
104 api_username: "admin"
105 api_password: "adminpass"
106 validate_certs: true
107 name: "Host1"
108 state: present
109 host_type_index: Linux DM-MP
110 ports:
111 - type: "iscsi"
112 label: "PORT_1"
113 port: "iqn.1996-04.de.suse:01:56f86f9bd1fe"
114 - type: "fc"
115 label: "FC_1"
116 port: "10:00:FF:7C:FF:FF:FF:01"
117 - type: "fc"
118 label: "FC_2"
119 port: "10:00:FF:7C:FF:FF:FF:00"
120
121 - name: Ensure a host named "Host2" doesn"t exist
122 na_santricity_host:
123 ssid: "1"
124 api_url: "https://192.168.1.100:8443/devmgr/v2"
125 api_username: "admin"
126 api_password: "adminpass"
127 validate_certs: true
128 name: "Host2"
129 state: absent
130 """
131
132 RETURN = """
133 msg:
134 description:
135 - A user-readable description of the actions performed.
136 returned: on success
137 type: str
138 sample: The host has been created.
139 id:
140 description:
141 - the unique identifier of the host on the E-Series storage-system
142 returned: on success when state=present
143 type: str
144 sample: 00000000600A098000AAC0C3003004700AD86A52
145 ssid:
146 description:
147 - the unique identifer of the E-Series storage-system with the current api
148 returned: on success
149 type: str
150 sample: 1
151 api_url:
152 description:
153 - the url of the API that this request was proccessed by
154 returned: on success
155 type: str
156 sample: https://webservices.example.com:8443
157 """
158 import re
159
160 from ansible.module_utils._text import to_native
161 from ansible_collections.netapp_eseries.santricity.plugins.module_utils.santricity import NetAppESeriesModule
162
163
164 class NetAppESeriesHost(NetAppESeriesModule):
165 PORT_TYPES = ["iscsi", "sas", "fc", "ib", "nvmeof"]
166
167 def __init__(self):
168 ansible_options = dict(state=dict(type="str", default="present", choices=["absent", "present"]),
169 ports=dict(type="list", elements="dict", required=False),
170 force_port=dict(type="bool", default=False),
171 name=dict(type="str", required=True, aliases=["label"]),
172 host_type=dict(type="str", required=False, aliases=["host_type_index"]))
173
174 super(NetAppESeriesHost, self).__init__(ansible_options=ansible_options,
175 web_services_version="02.00.0000.0000",
176 supports_check_mode=True)
177
178 self.check_mode = self.module.check_mode
179 args = self.module.params
180 self.ports = args["ports"]
181 self.force_port = args["force_port"]
182 self.name = args["name"]
183 self.state = args["state"]
184
185 self.post_body = dict()
186 self.all_hosts = list()
187 self.host_obj = dict()
188 self.new_ports = list()
189 self.ports_for_update = list()
190 self.ports_for_removal = list()
191
192 # Update host type with the corresponding index
193 host_type = args["host_type"]
194 if host_type:
195 host_type = host_type.lower()
196 if host_type in [key.lower() for key in list(self.HOST_TYPE_INDEXES.keys())]:
197 self.host_type_index = self.HOST_TYPE_INDEXES[host_type]
198 elif host_type.isdigit():
199 self.host_type_index = int(args["host_type"])
200 else:
201 self.module.fail_json(msg="host_type must be either a host type name or host type index found integer the documentation.")
202 else:
203 self.host_type_index = None
204
205 if not self.url.endswith("/"):
206 self.url += "/"
207
208 # Fix port representation if they are provided with colons
209 if self.ports is not None:
210 for port in self.ports:
211 port["type"] = port["type"].lower()
212 port["port"] = port["port"].lower()
213
214 if port["type"] not in self.PORT_TYPES:
215 self.module.fail_json(msg="Invalid port type! Port interface type must be one of [%s]." % ", ".join(self.PORT_TYPES))
216
217 # Determine whether address is 16-byte WWPN and, if so, remove
218 if re.match(r"^(0x)?[0-9a-f]{16}$", port["port"].replace(":", "")):
219 port["port"] = port["port"].replace(":", '').replace("0x", "")
220
221 if port["type"] == "ib":
222 port["port"] = "0" * (32 - len(port["port"])) + port["port"]
223
224 @property
225 def default_host_type(self):
226 """Return the default host type index."""
227 try:
228 rc, default_index = self.request("storage-systems/%s/graph/xpath-filter?query=/sa/defaultHostTypeIndex" % self.ssid)
229 return default_index[0]
230 except Exception as error:
231 self.module.fail_json(msg="Failed to retrieve default host type index")
232
233 @property
234 def valid_host_type(self):
235 host_types = None
236 try:
237 rc, host_types = self.request("storage-systems/%s/host-types" % self.ssid)
238 except Exception as err:
239 self.module.fail_json(msg="Failed to get host types. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
240
241 try:
242 match = list(filter(lambda host_type: host_type["index"] == self.host_type_index, host_types))[0]
243 return True
244 except IndexError:
245 self.module.fail_json(msg="There is no host type with index %s" % self.host_type_index)
246
247 def check_port_types(self):
248 """Check to see whether the port interface types are available on storage system."""
249 try:
250 rc, interfaces = self.request("storage-systems/%s/interfaces?channelType=hostside" % self.ssid)
251
252 for port in self.ports:
253 for interface in interfaces:
254
255 # Check for IB iSER
256 if port["type"] == "ib" and "iqn" in port["port"]:
257 if ((interface["ioInterfaceTypeData"]["interfaceType"] == "iscsi" and
258 interface["ioInterfaceTypeData"]["iscsi"]["interfaceData"]["type"] == "infiniband" and
259 interface["ioInterfaceTypeData"]["iscsi"]["interfaceData"]["infinibandData"]["isIser"]) or
260 (interface["ioInterfaceTypeData"]["interfaceType"] == "ib" and
261 interface["ioInterfaceTypeData"]["ib"]["isISERSupported"])):
262 port["type"] = "iscsi"
263 break
264 # Check for NVMe
265 elif (port["type"] == "nvmeof" and "commandProtocolPropertiesList" in interface and
266 "commandProtocolProperties" in interface["commandProtocolPropertiesList"] and
267 interface["commandProtocolPropertiesList"]["commandProtocolProperties"]):
268 if interface["commandProtocolPropertiesList"]["commandProtocolProperties"][0]["commandProtocol"] == "nvme":
269 break
270 # Check SAS, FC, iSCSI
271 elif ((port["type"] == "fc" and interface["ioInterfaceTypeData"]["interfaceType"] == "fibre") or
272 (port["type"] == interface["ioInterfaceTypeData"]["interfaceType"])):
273 break
274 else:
275 # self.module.fail_json(msg="Invalid port type! Type [%s]. Port [%s]." % (port["type"], port["label"]))
276 self.module.warn("Port type not found in hostside interfaces! Type [%s]. Port [%s]." % (port["type"], port["label"]))
277 except Exception as error:
278 # For older versions of web services
279 for port in self.ports:
280 if port["type"] == "ib" and "iqn" in port["port"]:
281 port["type"] = "iscsi"
282 break
283
284 def assigned_host_ports(self, apply_unassigning=False):
285 """Determine if the hostPorts requested have already been assigned and return list of required used ports."""
286 used_host_ports = {}
287 for host in self.all_hosts:
288 if host["label"].lower() != self.name.lower():
289 for host_port in host["hostSidePorts"]:
290
291 # Compare expected ports with those from other hosts definitions.
292 for port in self.ports:
293 if port["port"] == host_port["address"] or port["label"].lower() == host_port["label"].lower():
294 if not self.force_port:
295 self.module.fail_json(msg="Port label or address is already used and force_port option is set to false!")
296 else:
297 # Determine port reference
298 port_ref = [port["hostPortRef"] for port in host["ports"]
299 if port["hostPortName"] == host_port["address"]]
300 port_ref.extend([port["initiatorRef"] for port in host["initiators"]
301 if port["nodeName"]["iscsiNodeName"] == host_port["address"]])
302
303 # Create dictionary of hosts containing list of port references
304 if host["hostRef"] not in used_host_ports.keys():
305 used_host_ports.update({host["hostRef"]: port_ref})
306 else:
307 used_host_ports[host["hostRef"]].extend(port_ref)
308
309 # Unassign assigned ports
310 if apply_unassigning:
311 for host_ref in used_host_ports.keys():
312 try:
313 rc, resp = self.request("storage-systems/%s/hosts/%s" % (self.ssid, host_ref), method="POST",
314 data={"portsToRemove": used_host_ports[host_ref]})
315 except Exception as err:
316 self.module.fail_json(msg="Failed to unassign host port. Host Id [%s]. Array Id [%s]. Ports [%s]. Error [%s]."
317 % (self.host_obj["id"], self.ssid, used_host_ports[host_ref], to_native(err)))
318
319 @property
320 def host_exists(self):
321 """Determine if the requested host exists
322 As a side effect, set the full list of defined hosts in "all_hosts", and the target host in "host_obj".
323 """
324 match = False
325 all_hosts = list()
326
327 try:
328 rc, all_hosts = self.request("storage-systems/%s/hosts" % self.ssid)
329 except Exception as err:
330 self.module.fail_json(msg="Failed to determine host existence. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
331
332 # Augment the host objects
333 for host in all_hosts:
334 for port in host["hostSidePorts"]:
335 port["type"] = port["type"].lower()
336 port["address"] = port["address"].lower()
337
338 # Augment hostSidePorts with their ID (this is an omission in the API)
339 ports = dict((port["label"], port["id"]) for port in host["ports"])
340 ports.update(dict((port["label"], port["id"]) for port in host["initiators"]))
341
342 for host_side_port in host["hostSidePorts"]:
343 if host_side_port["label"] in ports:
344 host_side_port["id"] = ports[host_side_port["label"]]
345
346 if host["label"].lower() == self.name.lower():
347 self.host_obj = host
348 match = True
349
350 self.all_hosts = all_hosts
351 return match
352
353 @property
354 def needs_update(self):
355 """Determine whether we need to update the Host object
356 As a side effect, we will set the ports that we need to update (portsForUpdate), and the ports we need to add
357 (newPorts), on self.
358 """
359 changed = False
360 if self.host_obj["hostTypeIndex"] != self.host_type_index:
361 changed = True
362
363 current_host_ports = dict((port["id"], {"type": port["type"], "port": port["address"], "label": port["label"]})
364 for port in self.host_obj["hostSidePorts"])
365
366 if self.ports:
367 for port in self.ports:
368 for current_host_port_id in current_host_ports.keys():
369 if port == current_host_ports[current_host_port_id]:
370 current_host_ports.pop(current_host_port_id)
371 break
372
373 elif port["port"] == current_host_ports[current_host_port_id]["port"]:
374 if self.port_on_diff_host(port) and not self.force_port:
375 self.module.fail_json(msg="The port you specified [%s] is associated with a different host."
376 " Specify force_port as True or try a different port spec" % port)
377
378 if (port["label"] != current_host_ports[current_host_port_id]["label"] or
379 port["type"] != current_host_ports[current_host_port_id]["type"]):
380 current_host_ports.pop(current_host_port_id)
381 self.ports_for_update.append({"portRef": current_host_port_id, "port": port["port"],
382 "label": port["label"], "hostRef": self.host_obj["hostRef"]})
383 break
384 else:
385 self.new_ports.append(port)
386
387 self.ports_for_removal = list(current_host_ports.keys())
388 changed = any([self.new_ports, self.ports_for_update, self.ports_for_removal, changed])
389 return changed
390
391 def port_on_diff_host(self, arg_port):
392 """ Checks to see if a passed in port arg is present on a different host"""
393 for host in self.all_hosts:
394
395 # Only check "other" hosts
396 if host["name"].lower() != self.name.lower():
397 for port in host["hostSidePorts"]:
398
399 # Check if the port label is found in the port dict list of each host
400 if arg_port["label"].lower() == port["label"].lower() or arg_port["port"].lower() == port["address"].lower():
401 return True
402 return False
403
404 def update_host(self):
405 self.post_body = {"name": self.name, "hostType": {"index": self.host_type_index}}
406
407 # Remove ports that need reassigning from their current host.
408 if self.ports:
409 self.assigned_host_ports(apply_unassigning=True)
410 self.post_body["portsToUpdate"] = self.ports_for_update
411 self.post_body["portsToRemove"] = self.ports_for_removal
412 self.post_body["ports"] = self.new_ports
413
414 if not self.check_mode:
415 try:
416 rc, self.host_obj = self.request("storage-systems/%s/hosts/%s" % (self.ssid, self.host_obj["id"]), method="POST",
417 data=self.post_body, ignore_errors=True)
418 except Exception as err:
419 self.module.fail_json(msg="Failed to update host. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
420
421 self.module.exit_json(changed=True)
422
423 def create_host(self):
424 # Remove ports that need reassigning from their current host.
425 self.assigned_host_ports(apply_unassigning=True)
426
427 # needs_reassignment = False
428 post_body = dict(name=self.name,
429 hostType=dict(index=self.host_type_index))
430
431 if self.ports:
432 post_body.update(ports=self.ports)
433
434 if not self.host_exists:
435 if not self.check_mode:
436 try:
437 rc, self.host_obj = self.request("storage-systems/%s/hosts" % self.ssid, method="POST", data=post_body, ignore_errors=True)
438 except Exception as err:
439 self.module.fail_json(msg="Failed to create host. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
440 else:
441 payload = self.build_success_payload(self.host_obj)
442 self.module.exit_json(changed=False, msg="Host already exists. Id [%s]. Host [%s]." % (self.ssid, self.name), **payload)
443
444 payload = self.build_success_payload(self.host_obj)
445 self.module.exit_json(changed=True, msg="Host created.")
446
447 def remove_host(self):
448 try:
449 rc, resp = self.request("storage-systems/%s/hosts/%s" % (self.ssid, self.host_obj["id"]), method="DELETE")
450 except Exception as err:
451 self.module.fail_json(msg="Failed to remove host. Host[%s]. Array Id [%s]. Error [%s]." % (self.host_obj["id"], self.ssid, to_native(err)))
452
453 def build_success_payload(self, host=None):
454 keys = [] # ["id"]
455
456 if host:
457 result = dict((key, host[key]) for key in keys)
458 else:
459 result = dict()
460 result["ssid"] = self.ssid
461 result["api_url"] = self.url
462 return result
463
464 def apply(self):
465 if self.state == "present":
466 if self.host_type_index is None:
467 self.host_type_index = self.default_host_type
468
469 self.check_port_types()
470 if self.host_exists:
471 if self.needs_update and self.valid_host_type:
472 self.update_host()
473 else:
474 payload = self.build_success_payload(self.host_obj)
475 self.module.exit_json(changed=False, msg="Host already present; no changes required.", **payload)
476 elif self.valid_host_type:
477 self.create_host()
478 else:
479 payload = self.build_success_payload()
480 if self.host_exists:
481 self.remove_host()
482 self.module.exit_json(changed=True, msg="Host removed.", **payload)
483 else:
484 self.module.exit_json(changed=False, msg="Host already absent.", **payload)
485
486
487 def main():
488 host = NetAppESeriesHost()
489 host.apply()
490
491
492 if __name__ == "__main__":
493 main()