Debian Codegraph @

ansible_collections/netapp_eseries/santricity/plugins/modules/na_santricity_iscsi_interface.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_iscsi_interface
12 short_description: NetApp E-Series manage iSCSI interface configuration
13 description:
14 - Configure settings of an E-Series iSCSI interface
15 author:
16 - Michael Price (@lmprice)
17 - Nathan Swartz (@swartzn)
18 - Vu Tran (@VuTran007)
19 extends_documentation_fragment:
20 - netapp_eseries.santricity.santricity.santricity_doc
21 options:
22 controller:
23 description:
24 - The controller that owns the port you want to configure.
25 - Controller names are presented alphabetically, with the first controller as A,
26 the second as B, and so on.
27 - Current hardware models have either 1 or 2 available controllers, but that is not a guaranteed hard
28 limitation and could change in the future.
29 type: str
30 required: true
31 choices:
32 - A
33 - B
34 port:
35 description:
36 - The controller iSCSI baseboard or HIC port to modify.
37 - Determine the port by counting, starting from one, the controller's iSCSI ports left to right. Count the
38 baseboard and then the HIC ports.
39 type: int
40 required: true
41 state:
42 description:
43 - When enabled, the provided configuration will be utilized.
44 - When disabled, the IPv4 configuration will be cleared and IPv4 connectivity disabled.
45 type: str
46 choices:
47 - enabled
48 - disabled
49 default: enabled
50 address:
51 description:
52 - The IPv4 address to assign to the interface.
53 - Should be specified in xx.xx.xx.xx form.
54 - Mutually exclusive with I(config_method=dhcp)
55 type: str
56 required: false
57 subnet_mask:
58 description:
59 - The subnet mask to utilize for the interface.
60 - Should be specified in xx.xx.xx.xx form.
61 - Mutually exclusive with I(config_method=dhcp)
62 type: str
63 gateway:
64 description:
65 - The IPv4 gateway address to utilize for the interface.
66 - Should be specified in xx.xx.xx.xx form.
67 - Mutually exclusive with I(config_method=dhcp)
68 type: str
69 required: false
70 config_method:
71 description:
72 - The configuration method type to use for this interface.
73 - dhcp is mutually exclusive with I(address), I(subnet_mask), and I(gateway).
74 type: str
75 choices:
76 - dhcp
77 - static
78 default: dhcp
79 required: false
80 mtu:
81 description:
82 - The maximum transmission units (MTU), in bytes.
83 - This allows you to configure a larger value for the MTU, in order to enable jumbo frames
84 (any value > 1500).
85 - Generally, it is necessary to have your host, switches, and other components not only support jumbo
86 frames, but also have it configured properly. Therefore, unless you know what you're doing, it's best to
87 leave this at the default.
88 type: int
89 default: 1500
90 required: false
91 aliases:
92 - max_frame_size
93 speed:
94 description:
95 - The option will change the interface port speed.
96 - Only supported speeds will be accepted and must be in the form [0-9]+[gm] (i.e. 25g)
97 - Down interfaces will report as Unknown speed until they are set to an accepted network speed.
98 - Do not use this option when the port's speed is automatically configured as it will fail. See System
99 Manager for the port's capability.
100 type: str
101 required: false
102 notes:
103 - Check mode is supported.
104 - The interface settings are applied synchronously, but changes to the interface itself (receiving a new IP address
105 via dhcp, etc), can take seconds or minutes longer to take effect.
106 - This module will not be useful/usable on an E-Series system without any iSCSI interfaces.
107 - This module requires a Web Services API version of >= 1.3.
108 """
109
110 EXAMPLES = """
111 - name: Configure the first port on the A controller with a static IPv4 address
112 na_santricity_iscsi_interface:
113 ssid: "1"
114 api_url: "https://192.168.1.100:8443/devmgr/v2"
115 api_username: "admin"
116 api_password: "adminpass"
117 validate_certs: true
118 port: "1"
119 controller: "A"
120 config_method: static
121 address: "192.168.1.100"
122 subnet_mask: "255.255.255.0"
123 gateway: "192.168.1.1"
124 speed: "25g"
125
126 - name: Disable ipv4 connectivity for the second port on the B controller
127 na_santricity_iscsi_interface:
128 ssid: "1"
129 api_url: "https://192.168.1.100:8443/devmgr/v2"
130 api_username: "admin"
131 api_password: "adminpass"
132 validate_certs: true
133 port: "2"
134 controller: "B"
135 state: disabled
136
137 - name: Enable jumbo frames for the first 4 ports on controller A
138 na_santricity_iscsi_interface:
139 ssid: "1"
140 api_url: "https://192.168.1.100:8443/devmgr/v2"
141 api_username: "admin"
142 api_password: "adminpass"
143 validate_certs: true
144 port: "{{ item }}"
145 controller: "A"
146 state: enabled
147 mtu: 9000
148 config_method: dhcp
149 loop:
150 - 1
151 - 2
152 - 3
153 - 4
154 """
155
156 RETURN = """
157 msg:
158 description: Success message
159 returned: on success
160 type: str
161 sample: The interface settings have been updated.
162 """
163 import re
164
165 from ansible_collections.netapp_eseries.santricity.plugins.module_utils.santricity import NetAppESeriesModule
166 from ansible.module_utils._text import to_native
167
168
169 def strip_interface_speed(speed):
170 """Converts symbol interface speeds to a more common notation. Example: 'speed10gig' -> '10g'"""
171 if isinstance(speed, list):
172 result = [re.match(r"speed[0-9]{1,3}[gm]", sp) for sp in speed]
173 result = [sp.group().replace("speed", "") if result else "unknown" for sp in result if sp]
174 result = ["auto" if re.match(r"auto", sp) else sp for sp in result]
175 else:
176 result = re.match(r"speed[0-9]{1,3}[gm]", speed)
177 result = result.group().replace("speed", "") if result else "unknown"
178 result = "auto" if re.match(r"auto", result.lower()) else result
179 return result
180
181
182 class NetAppESeriesIscsiInterface(NetAppESeriesModule):
183 def __init__(self):
184 ansible_options = dict(controller=dict(type="str", required=True, choices=["A", "B"]),
185 port=dict(type="int", required=True),
186 state=dict(type="str", required=False, default="enabled", choices=["enabled", "disabled"]),
187 address=dict(type="str", required=False),
188 subnet_mask=dict(type="str", required=False),
189 gateway=dict(type="str", required=False),
190 config_method=dict(type="str", required=False, default="dhcp", choices=["dhcp", "static"]),
191 mtu=dict(type="int", default=1500, required=False, aliases=["max_frame_size"]),
192 speed=dict(type="str", required=False))
193
194 required_if = [["config_method", "static", ["address", "subnet_mask"]]]
195 super(NetAppESeriesIscsiInterface, self).__init__(ansible_options=ansible_options,
196 web_services_version="02.00.0000.0000",
197 required_if=required_if,
198 supports_check_mode=True)
199
200 args = self.module.params
201 self.controller = args["controller"]
202 self.port = args["port"]
203 self.mtu = args["mtu"]
204 self.state = args["state"]
205 self.address = args["address"]
206 self.subnet_mask = args["subnet_mask"]
207 self.gateway = args["gateway"]
208 self.config_method = args["config_method"]
209 self.speed = args["speed"]
210
211 self.check_mode = self.module.check_mode
212 self.post_body = dict()
213 self.controllers = list()
214 self.get_target_interface_cache = None
215
216 if self.mtu < 1500 or self.mtu > 9000:
217 self.module.fail_json(msg="The provided mtu is invalid, it must be > 1500 and < 9000 bytes.")
218
219 if self.config_method == "dhcp" and any([self.address, self.subnet_mask, self.gateway]):
220 self.module.fail_json(msg="A config_method of dhcp is mutually exclusive with the address,"
221 " subnet_mask, and gateway options.")
222
223 # A relatively primitive regex to validate that the input is formatted like a valid ip address
224 address_regex = re.compile(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
225
226 if self.address and not address_regex.match(self.address):
227 self.module.fail_json(msg="An invalid ip address was provided for address.")
228
229 if self.subnet_mask and not address_regex.match(self.subnet_mask):
230 self.module.fail_json(msg="An invalid ip address was provided for subnet_mask.")
231
232 if self.gateway and not address_regex.match(self.gateway):
233 self.module.fail_json(msg="An invalid ip address was provided for gateway.")
234
235 self.get_host_board_id_cache = None
236
237 @property
238 def interfaces(self):
239 ifaces = list()
240 try:
241 rc, ifaces = self.request("storage-systems/%s/graph/xpath-filter?query=/controller/hostInterfaces" % self.ssid)
242 except Exception as err:
243 self.module.fail_json(msg="Failed to retrieve defined host interfaces. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
244
245 # Filter out non-iSCSI interfaces
246 iscsi_interfaces = []
247 for iface in [iface for iface in ifaces if iface["interfaceType"] == "iscsi"]:
248 if iface["iscsi"]["interfaceData"]["type"] == "ethernet":
249 iscsi_interfaces.append(iface)
250
251 return iscsi_interfaces
252
253 def get_host_board_id(self, iface_ref):
254 if self.get_host_board_id_cache is None:
255 try:
256 rc, iface_board_map_list = self.request("storage-systems/%s/graph/xpath-filter?query=/ioInterfaceHicMap" % self.ssid)
257 except Exception as err:
258 self.module.fail_json(msg="Failed to retrieve IO interface HIC mappings! Array Id [%s]."
259 " Error [%s]." % (self.ssid, to_native(err)))
260
261 self.get_host_board_id_cache = dict()
262 for iface_board_map in iface_board_map_list:
263 self.get_host_board_id_cache.update({iface_board_map["interfaceRef"]: iface_board_map["hostBoardRef"]})
264
265 return self.get_host_board_id_cache[iface_ref]
266
267 def get_controllers(self):
268 """Retrieve a mapping of controller labels to their references
269 {
270 "A": "070000000000000000000001",
271 "B": "070000000000000000000002",
272 }
273 :return: the controllers defined on the system
274 """
275 controllers = list()
276 try:
277 rc, controllers = self.request("storage-systems/%s/graph/xpath-filter?query=/controller/id" % self.ssid)
278 except Exception as err:
279 self.module.fail_json(msg="Failed to retrieve controller list! Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
280
281 controllers.sort()
282
283 controllers_dict = {}
284 i = ord("A")
285 for controller in controllers:
286 label = chr(i)
287 controllers_dict[label] = controller
288 i += 1
289
290 return controllers_dict
291
292 def get_target_interface(self):
293 """Retrieve the specific controller iSCSI interface."""
294 if self.get_target_interface_cache is None:
295 ifaces = self.interfaces
296
297 controller_ifaces = []
298 for iface in ifaces:
299 if self.controllers[self.controller] == iface["iscsi"]["controllerId"]:
300 controller_ifaces.append([iface["iscsi"]["channel"], iface, iface["iscsi"]["interfaceData"]["ethernetData"]["linkStatus"]])
301
302 sorted_controller_ifaces = sorted(controller_ifaces)
303 if self.port < 1 or self.port > len(controller_ifaces):
304 status_msg = ", ".join(["%s (link %s)" % (index + 1, values[2]) for index, values in enumerate(sorted_controller_ifaces)])
305 self.module.fail_json(msg="Invalid controller %s iSCSI port. Available ports: %s, Array Id [%s]."
306 % (self.controller, status_msg, self.ssid))
307
308 self.get_target_interface_cache = sorted_controller_ifaces[self.port - 1][1]
309 return self.get_target_interface_cache
310
311 def make_update_body(self, target_iface):
312 target_iface = target_iface["iscsi"]
313 body = dict(iscsiInterface=target_iface["id"])
314 update_required = False
315
316 if self.state == "enabled":
317 settings = dict()
318 if not target_iface["ipv4Enabled"]:
319 update_required = True
320 settings["ipv4Enabled"] = [True]
321 if self.mtu != target_iface["interfaceData"]["ethernetData"]["maximumFramePayloadSize"]:
322 update_required = True
323 settings["maximumFramePayloadSize"] = [self.mtu]
324 if self.config_method == "static":
325 ipv4Data = target_iface["ipv4Data"]["ipv4AddressData"]
326
327 if ipv4Data["ipv4Address"] != self.address:
328 update_required = True
329 settings["ipv4Address"] = [self.address]
330 if ipv4Data["ipv4SubnetMask"] != self.subnet_mask:
331 update_required = True
332 settings["ipv4SubnetMask"] = [self.subnet_mask]
333 if self.gateway is not None and ipv4Data["ipv4GatewayAddress"] != self.gateway:
334 update_required = True
335 settings["ipv4GatewayAddress"] = [self.gateway]
336
337 if target_iface["ipv4Data"]["ipv4AddressConfigMethod"] != "configStatic":
338 update_required = True
339 settings["ipv4AddressConfigMethod"] = ["configStatic"]
340
341 elif target_iface["ipv4Data"]["ipv4AddressConfigMethod"] != "configDhcp":
342 update_required = True
343 settings.update(dict(ipv4Enabled=[True],
344 ipv4AddressConfigMethod=["configDhcp"]))
345 body["settings"] = settings
346
347 else:
348 if target_iface["ipv4Enabled"]:
349 update_required = True
350 body["settings"] = dict(ipv4Enabled=[False])
351
352 return update_required, body
353
354 def make_update_speed_body(self, target_iface):
355 target_iface = target_iface["iscsi"]
356
357 # Check whether HIC speed should be changed.
358 if self.speed is None:
359 return False, dict()
360 else:
361 if target_iface["interfaceData"]["ethernetData"]["autoconfigSupport"]:
362 self.module.warn("This interface's HIC speed is autoconfigured!")
363 return False, dict()
364
365 target_current_iface_speed = target_iface["interfaceData"]["ethernetData"]["currentInterfaceSpeed"]
366 if self.speed == strip_interface_speed(target_current_iface_speed):
367 return False, dict()
368
369 # Create a dictionary containing supported HIC speeds keyed by simplified value to the complete value
370 # (ie. {"10g": "speed10gig"})
371 supported_speeds = dict()
372 for supported_speed in target_iface["interfaceData"]["ethernetData"]["supportedInterfaceSpeeds"]:
373 supported_speeds.update({strip_interface_speed(supported_speed): supported_speed})
374
375 if self.speed not in supported_speeds:
376 self.module.fail_json(
377 msg="The host interface card (HIC) does not support the provided speed. "
378 "Array Id [%s]. Supported speeds [%s]" % (self.ssid, ", ".join(supported_speeds.keys()))
379 )
380
381 body = {"settings": {"maximumInterfaceSpeed": [supported_speeds[self.speed]]}, "portsRef": {}}
382 hic_ref = self.get_host_board_id(target_iface["id"])
383 if hic_ref == "0000000000000000000000000000000000000000":
384 body.update({"portsRef": {"portRefType": "baseBoard", "baseBoardRef": target_iface["id"], "hicRef": ""}})
385 else:
386 body.update({"portsRef": {"portRefType": "hic", "hicRef": hic_ref, "baseBoardRef": ""}})
387
388 return True, body
389
390 def update(self):
391 self.controllers = self.get_controllers()
392 if self.controller not in self.controllers:
393 self.module.fail_json(msg="The provided controller name is invalid. Valid controllers: %s." % ", ".join(self.controllers.keys()))
394
395 iface_before = self.get_target_interface()
396 update_required, body = self.make_update_body(iface_before)
397 if update_required and not self.check_mode:
398 try:
399 rc, result = self.request("storage-systems/%s/symbol/setIscsiInterfaceProperties" % self.ssid, method="POST", data=body, ignore_errors=True)
400 # We could potentially retry this a few times, but it's probably a rare enough case (unless a playbook
401 # is cancelled mid-flight), that it isn't worth the complexity.
402 if rc == 422 and result["retcode"] in ["busy", "3"]:
403 self.module.fail_json(msg="The interface is currently busy (probably processing a previously "
404 "requested modification request). This operation cannot currently be "
405 "completed. Array Id [%s]. Error [%s]." % (self.ssid, result))
406 # Handle authentication issues, etc.
407 elif rc != 200:
408 self.module.fail_json(msg="Failed to modify the interface! Array Id [%s]. Error [%s]." % (self.ssid, to_native(result)))
409 # This is going to catch cases like a connection failure
410 except Exception as err:
411 self.module.fail_json(msg="Connection failure: we failed to modify the interface! Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
412
413 update_speed_required, speed_body = self.make_update_speed_body(iface_before)
414 if update_speed_required and not self.check_mode:
415 try:
416 rc, result = self.request(
417 "storage-systems/%s/symbol/setHostPortsAttributes?verboseErrorResponse=true" % self.ssid,
418 method="POST",
419 data=speed_body
420 )
421 except Exception as err:
422 self.module.fail_json(msg="Failed to update host interface card speed. Array Id [%s], Body [%s]. "
423 "Error [%s]." % (self.ssid, speed_body, to_native(err)))
424
425 if update_required or update_speed_required:
426 self.module.exit_json(msg="The interface settings have been updated.", changed=True)
427 self.module.exit_json(msg="No changes were required.", changed=False)
428
429
430 def main():
431 iface = NetAppESeriesIscsiInterface()
432 iface.update()
433
434
435 if __name__ == "__main__":
436 main()