Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2018, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10 ANSIBLE_METADATA = {'metadata_version': '1.1',
11 'status': ['deprecated'],
12 'supported_by': 'community'}
13
14 DOCUMENTATION = """
15 ---
16 module: netapp_e_iscsi_interface
17 short_description: NetApp E-Series manage iSCSI interface configuration
18 description:
19 - Configure settings of an E-Series iSCSI interface
20 version_added: '2.7.0'
21 author: Michael Price (@lmprice)
22 extends_documentation_fragment:
23 - netapp_eseries.santricity.santricity.netapp.eseries
24 options:
25 controller:
26 description:
27 - The controller that owns the port you want to configure.
28 - Controller names are presented alphabetically, with the first controller as A,
29 the second as B, and so on.
30 - Current hardware models have either 1 or 2 available controllers, but that is not a guaranteed hard
31 limitation and could change in the future.
32 required: yes
33 type: str
34 choices:
35 - A
36 - B
37 name:
38 description:
39 - The channel of the port to modify the configuration of.
40 - The list of choices is not necessarily comprehensive. It depends on the number of ports
41 that are available in the system.
42 - The numerical value represents the number of the channel (typically from left to right on the HIC),
43 beginning with a value of 1.
44 required: yes
45 type: int
46 aliases:
47 - channel
48 state:
49 description:
50 - When enabled, the provided configuration will be utilized.
51 - When disabled, the IPv4 configuration will be cleared and IPv4 connectivity disabled.
52 choices:
53 - enabled
54 - disabled
55 default: enabled
56 type: str
57 address:
58 description:
59 - The IPv4 address to assign to the interface.
60 - Should be specified in xx.xx.xx.xx form.
61 - Mutually exclusive with I(config_method=dhcp)
62 type: str
63 subnet_mask:
64 description:
65 - The subnet mask 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 gateway:
70 description:
71 - The IPv4 gateway address to utilize for the interface.
72 - Should be specified in xx.xx.xx.xx form.
73 - Mutually exclusive with I(config_method=dhcp)
74 type: str
75 config_method:
76 description:
77 - The configuration method type to use for this interface.
78 - dhcp is mutually exclusive with I(address), I(subnet_mask), and I(gateway).
79 choices:
80 - dhcp
81 - static
82 default: dhcp
83 type: str
84 mtu:
85 description:
86 - The maximum transmission units (MTU), in bytes.
87 - This allows you to configure a larger value for the MTU, in order to enable jumbo frames
88 (any value > 1500).
89 - Generally, it is necessary to have your host, switches, and other components not only support jumbo
90 frames, but also have it configured properly. Therefore, unless you know what you're doing, it's best to
91 leave this at the default.
92 default: 1500
93 type: int
94 aliases:
95 - max_frame_size
96 log_path:
97 description:
98 - A local path to a file to be used for debug logging
99 type: str
100 required: no
101 notes:
102 - Check mode is supported.
103 - The interface settings are applied synchronously, but changes to the interface itself (receiving a new IP address
104 via dhcp, etc), can take seconds or minutes longer to take effect.
105 - This module will not be useful/usable on an E-Series system without any iSCSI interfaces.
106 - This module requires a Web Services API version of >= 1.3.
107 """
108
109 EXAMPLES = """
110 - name: Configure the first port on the A controller with a static IPv4 address
111 netapp_e_iscsi_interface:
112 name: "1"
113 controller: "A"
114 config_method: static
115 address: "192.168.1.100"
116 subnet_mask: "255.255.255.0"
117 gateway: "192.168.1.1"
118 ssid: "1"
119 api_url: "10.1.1.1:8443"
120 api_username: "admin"
121 api_password: "myPass"
122
123 - name: Disable ipv4 connectivity for the second port on the B controller
124 netapp_e_iscsi_interface:
125 name: "2"
126 controller: "B"
127 state: disabled
128 ssid: "{{ ssid }}"
129 api_url: "{{ netapp_api_url }}"
130 api_username: "{{ netapp_api_username }}"
131 api_password: "{{ netapp_api_password }}"
132
133 - name: Enable jumbo frames for the first 4 ports on controller A
134 netapp_e_iscsi_interface:
135 name: "{{ item | int }}"
136 controller: "A"
137 state: enabled
138 mtu: 9000
139 config_method: dhcp
140 ssid: "{{ ssid }}"
141 api_url: "{{ netapp_api_url }}"
142 api_username: "{{ netapp_api_username }}"
143 api_password: "{{ netapp_api_password }}"
144 loop:
145 - 1
146 - 2
147 - 3
148 - 4
149 """
150
151 RETURN = """
152 msg:
153 description: Success message
154 returned: on success
155 type: str
156 sample: The interface settings have been updated.
157 enabled:
158 description:
159 - Indicates whether IPv4 connectivity has been enabled or disabled.
160 - This does not necessarily indicate connectivity. If dhcp was enabled without a dhcp server, for instance,
161 it is unlikely that the configuration will actually be valid.
162 returned: on success
163 sample: True
164 type: bool
165 """
166 import json
167 import logging
168 from pprint import pformat
169 import re
170
171 from ansible.module_utils.basic import AnsibleModule
172 from ansible_collections.netapp_eseries.santricity.plugins.module_utils.netapp import request, eseries_host_argument_spec
173 from ansible.module_utils._text import to_native
174
175 HEADERS = {
176 "Content-Type": "application/json",
177 "Accept": "application/json",
178 }
179
180
181 class IscsiInterface(object):
182 def __init__(self):
183 argument_spec = eseries_host_argument_spec()
184 argument_spec.update(dict(
185 controller=dict(type='str', required=True, choices=['A', 'B']),
186 name=dict(type='int', required=True, aliases=['channel']),
187 state=dict(type='str', required=False, default='enabled', choices=['enabled', 'disabled']),
188 address=dict(type='str', required=False),
189 subnet_mask=dict(type='str', required=False),
190 gateway=dict(type='str', required=False),
191 config_method=dict(type='str', required=False, default='dhcp', choices=['dhcp', 'static']),
192 mtu=dict(type='int', default=1500, required=False, aliases=['max_frame_size']),
193 log_path=dict(type='str', required=False),
194 ))
195
196 required_if = [
197 ["config_method", "static", ["address", "subnet_mask"]],
198 ]
199
200 self.module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, required_if=required_if, )
201 args = self.module.params
202 self.controller = args['controller']
203 self.name = args['name']
204 self.mtu = args['mtu']
205 self.state = args['state']
206 self.address = args['address']
207 self.subnet_mask = args['subnet_mask']
208 self.gateway = args['gateway']
209 self.config_method = args['config_method']
210
211 self.ssid = args['ssid']
212 self.url = args['api_url']
213 self.creds = dict(url_password=args['api_password'],
214 validate_certs=args['validate_certs'],
215 url_username=args['api_username'], )
216
217 self.check_mode = self.module.check_mode
218 self.post_body = dict()
219 self.controllers = list()
220
221 log_path = args['log_path']
222
223 # logging setup
224 self._logger = logging.getLogger(self.__class__.__name__)
225
226 if log_path:
227 logging.basicConfig(
228 level=logging.DEBUG, filename=log_path, filemode='w',
229 format='%(relativeCreated)dms %(levelname)s %(module)s.%(funcName)s:%(lineno)d\n %(message)s')
230
231 if not self.url.endswith('/'):
232 self.url += '/'
233
234 if self.mtu < 1500 or self.mtu > 9000:
235 self.module.fail_json(msg="The provided mtu is invalid, it must be > 1500 and < 9000 bytes.")
236
237 if self.config_method == 'dhcp' and any([self.address, self.subnet_mask, self.gateway]):
238 self.module.fail_json(msg='A config_method of dhcp is mutually exclusive with the address,'
239 ' subnet_mask, and gateway options.')
240
241 # A relatively primitive regex to validate that the input is formatted like a valid ip address
242 address_regex = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
243
244 if self.address and not address_regex.match(self.address):
245 self.module.fail_json(msg="An invalid ip address was provided for address.")
246
247 if self.subnet_mask and not address_regex.match(self.subnet_mask):
248 self.module.fail_json(msg="An invalid ip address was provided for subnet_mask.")
249
250 if self.gateway and not address_regex.match(self.gateway):
251 self.module.fail_json(msg="An invalid ip address was provided for gateway.")
252
253 @property
254 def interfaces(self):
255 ifaces = list()
256 try:
257 (rc, ifaces) = request(self.url + 'storage-systems/%s/graph/xpath-filter?query=/controller/hostInterfaces'
258 % self.ssid, headers=HEADERS, **self.creds)
259 except Exception as err:
260 self.module.fail_json(
261 msg="Failed to retrieve defined host interfaces. Array Id [%s]. Error [%s]."
262 % (self.ssid, to_native(err)))
263
264 # Filter out non-iSCSI interfaces
265 ifaces = [iface['iscsi'] for iface in ifaces if iface['interfaceType'] == 'iscsi']
266
267 return ifaces
268
269 def get_controllers(self):
270 """Retrieve a mapping of controller labels to their references
271 {
272 'A': '070000000000000000000001',
273 'B': '070000000000000000000002',
274 }
275 :return: the controllers defined on the system
276 """
277 controllers = list()
278 try:
279 (rc, controllers) = request(self.url + 'storage-systems/%s/graph/xpath-filter?query=/controller/id'
280 % self.ssid, headers=HEADERS, **self.creds)
281 except Exception as err:
282 self.module.fail_json(
283 msg="Failed to retrieve controller list! Array Id [%s]. Error [%s]."
284 % (self.ssid, to_native(err)))
285
286 controllers.sort()
287
288 controllers_dict = {}
289 i = ord('A')
290 for controller in controllers:
291 label = chr(i)
292 controllers_dict[label] = controller
293 i += 1
294
295 return controllers_dict
296
297 def fetch_target_interface(self):
298 interfaces = self.interfaces
299
300 for iface in interfaces:
301 if iface['channel'] == self.name and self.controllers[self.controller] == iface['controllerId']:
302 return iface
303
304 channels = sorted(set((str(iface['channel'])) for iface in interfaces
305 if self.controllers[self.controller] == iface['controllerId']))
306
307 self.module.fail_json(msg="The requested channel of %s is not valid. Valid channels include: %s."
308 % (self.name, ", ".join(channels)))
309
310 def make_update_body(self, target_iface):
311 body = dict(iscsiInterface=target_iface['id'])
312 update_required = False
313
314 self._logger.info("Requested state=%s.", self.state)
315 self._logger.info("config_method: current=%s, requested=%s",
316 target_iface['ipv4Data']['ipv4AddressConfigMethod'], self.config_method)
317
318 if self.state == 'enabled':
319 settings = dict()
320 if not target_iface['ipv4Enabled']:
321 update_required = True
322 settings['ipv4Enabled'] = [True]
323 if self.mtu != target_iface['interfaceData']['ethernetData']['maximumFramePayloadSize']:
324 update_required = True
325 settings['maximumFramePayloadSize'] = [self.mtu]
326 if self.config_method == 'static':
327 ipv4Data = target_iface['ipv4Data']['ipv4AddressData']
328
329 if ipv4Data['ipv4Address'] != self.address:
330 update_required = True
331 settings['ipv4Address'] = [self.address]
332 if ipv4Data['ipv4SubnetMask'] != self.subnet_mask:
333 update_required = True
334 settings['ipv4SubnetMask'] = [self.subnet_mask]
335 if self.gateway is not None and ipv4Data['ipv4GatewayAddress'] != self.gateway:
336 update_required = True
337 settings['ipv4GatewayAddress'] = [self.gateway]
338
339 if target_iface['ipv4Data']['ipv4AddressConfigMethod'] != 'configStatic':
340 update_required = True
341 settings['ipv4AddressConfigMethod'] = ['configStatic']
342
343 elif (target_iface['ipv4Data']['ipv4AddressConfigMethod'] != 'configDhcp'):
344 update_required = True
345 settings.update(dict(ipv4Enabled=[True],
346 ipv4AddressConfigMethod=['configDhcp']))
347 body['settings'] = settings
348
349 else:
350 if target_iface['ipv4Enabled']:
351 update_required = True
352 body['settings'] = dict(ipv4Enabled=[False])
353
354 self._logger.info("Update required ?=%s", update_required)
355 self._logger.info("Update body: %s", pformat(body))
356
357 return update_required, body
358
359 def update(self):
360 self.controllers = self.get_controllers()
361 if self.controller not in self.controllers:
362 self.module.fail_json(msg="The provided controller name is invalid. Valid controllers: %s."
363 % ", ".join(self.controllers.keys()))
364
365 iface_before = self.fetch_target_interface()
366 update_required, body = self.make_update_body(iface_before)
367 if update_required and not self.check_mode:
368 try:
369 url = (self.url +
370 'storage-systems/%s/symbol/setIscsiInterfaceProperties' % self.ssid)
371 (rc, result) = request(url, method='POST', data=json.dumps(body), headers=HEADERS, timeout=300,
372 ignore_errors=True, **self.creds)
373 # We could potentially retry this a few times, but it's probably a rare enough case (unless a playbook
374 # is cancelled mid-flight), that it isn't worth the complexity.
375 if rc == 422 and result['retcode'] in ['busy', '3']:
376 self.module.fail_json(
377 msg="The interface is currently busy (probably processing a previously requested modification"
378 " request). This operation cannot currently be completed. Array Id [%s]. Error [%s]."
379 % (self.ssid, result))
380 # Handle authentication issues, etc.
381 elif rc != 200:
382 self.module.fail_json(
383 msg="Failed to modify the interface! Array Id [%s]. Error [%s]."
384 % (self.ssid, to_native(result)))
385 self._logger.debug("Update request completed successfully.")
386 # This is going to catch cases like a connection failure
387 except Exception as err:
388 self.module.fail_json(
389 msg="Connection failure: we failed to modify the interface! Array Id [%s]. Error [%s]."
390 % (self.ssid, to_native(err)))
391
392 iface_after = self.fetch_target_interface()
393
394 self.module.exit_json(msg="The interface settings have been updated.", changed=update_required,
395 enabled=iface_after['ipv4Enabled'])
396
397 def __call__(self, *args, **kwargs):
398 self.update()
399
400
401 def main():
402 iface = IscsiInterface()
403 iface()
404
405
406 if __name__ == '__main__':
407 main()