Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # (c) 2018, NetApp Inc.
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
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_host
17 short_description: NetApp E-Series manage eseries hosts
18 description: Create, update, remove hosts on NetApp E-series storage arrays
19 version_added: '2.2.0'
20 author:
21 - Kevin Hulquest (@hulquest)
22 - Nathan Swartz (@ndswartz)
23 extends_documentation_fragment:
24 - netapp_eseries.santricity.santricity.netapp.eseries
25 options:
26 name:
27 description:
28 - If the host doesn't yet exist, the label/name to assign at creation time.
29 - If the hosts already exists, this will be used to uniquely identify the host to make any required changes
30 required: True
31 type: str
32 aliases:
33 - label
34 state:
35 description:
36 - Set to absent to remove an existing host
37 - Set to present to modify or create a new host definition
38 choices:
39 - absent
40 - present
41 default: present
42 type: str
43 version_added: "2.7.0"
44 host_type:
45 description:
46 - This is the type of host to be mapped
47 - Required when C(state=present)
48 - Either one of the following names can be specified, Linux DM-MP, VMWare, Windows, Windows Clustered, or a
49 host type index which can be found in M(netapp_eseries.santricity.netapp_e_facts)
50 type: str
51 aliases:
52 - host_type_index
53 ports:
54 description:
55 - A list of host ports you wish to associate with the host.
56 - Host ports are uniquely identified by their WWN or IQN. Their assignments to a particular host are
57 uniquely identified by a label and these must be unique.
58 required: False
59 type: list
60 elements: dict
61 suboptions:
62 type:
63 description:
64 - The interface type of the port to define.
65 - Acceptable choices depend on the capabilities of the target hardware/software platform.
66 required: true
67 choices:
68 - iscsi
69 - sas
70 - fc
71 - ib
72 - nvmeof
73 - ethernet
74 label:
75 description:
76 - A unique label to assign to this port assignment.
77 required: true
78 port:
79 description:
80 - The WWN or IQN of the hostPort to assign to this port definition.
81 required: true
82 force_port:
83 description:
84 - Allow ports that are already assigned to be re-assigned to your current host
85 required: false
86 type: bool
87 default: false
88 version_added: "2.7.0"
89 group:
90 description:
91 - The unique identifier of the host-group you want the host to be a member of; this is used for clustering.
92 required: False
93 type: str
94 aliases:
95 - cluster
96 log_path:
97 description:
98 - A local path to a file to be used for debug logging
99 required: False
100 type: str
101 version_added: "2.7.0"
102 """
103
104 EXAMPLES = """
105 - name: Define or update an existing host named 'Host1'
106 netapp_e_host:
107 ssid: "1"
108 api_url: "10.113.1.101:8443"
109 api_username: admin
110 api_password: myPassword
111 name: "Host1"
112 state: present
113 host_type_index: Linux DM-MP
114 ports:
115 - type: 'iscsi'
116 label: 'PORT_1'
117 port: 'iqn.1996-04.de.suse:01:56f86f9bd1fe'
118 - type: 'fc'
119 label: 'FC_1'
120 port: '10:00:FF:7C:FF:FF:FF:01'
121 - type: 'fc'
122 label: 'FC_2'
123 port: '10:00:FF:7C:FF:FF:FF:00'
124
125 - name: Ensure a host named 'Host2' doesn't exist
126 netapp_e_host:
127 ssid: "1"
128 api_url: "10.113.1.101:8443"
129 api_username: admin
130 api_password: myPassword
131 name: "Host2"
132 state: absent
133 """
134
135 RETURN = """
136 msg:
137 description:
138 - A user-readable description of the actions performed.
139 returned: on success
140 type: str
141 sample: The host has been created.
142 id:
143 description:
144 - the unique identifier of the host on the E-Series storage-system
145 returned: on success when state=present
146 type: str
147 sample: 00000000600A098000AAC0C3003004700AD86A52
148 version_added: "2.6.0"
149
150 ssid:
151 description:
152 - the unique identifier of the E-Series storage-system with the current api
153 returned: on success
154 type: str
155 sample: 1
156 version_added: "2.6.0"
157
158 api_url:
159 description:
160 - the url of the API that this request was processed by
161 returned: on success
162 type: str
163 sample: https://webservices.example.com:8443
164 version_added: "2.6.0"
165 """
166 import json
167 import logging
168 import re
169 from pprint import pformat
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 Host(object):
182 HOST_TYPE_INDEXES = {"linux dm-mp": 28, "vmware": 10, "windows": 1, "windows clustered": 8}
183
184 def __init__(self):
185 argument_spec = eseries_host_argument_spec()
186 argument_spec.update(dict(
187 state=dict(type='str', default='present', choices=['absent', 'present']),
188 group=dict(type='str', required=False, aliases=['cluster']),
189 ports=dict(type='list', elements="dict", required=False),
190 force_port=dict(type='bool', required=False, default=False),
191 name=dict(type='str', required=True, aliases=['label']),
192 host_type=dict(type='str', aliases=['host_type_index']),
193 log_path=dict(type='str', required=False),
194 ))
195
196 self.module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
197 self.check_mode = self.module.check_mode
198 args = self.module.params
199 self.group = args['group']
200 self.ports = args['ports']
201 self.force_port = args['force_port']
202 self.name = args['name']
203 self.state = args['state']
204 self.ssid = args['ssid']
205 self.url = args['api_url']
206 self.user = args['api_username']
207 self.pwd = args['api_password']
208 self.certs = args['validate_certs']
209
210 self.post_body = dict()
211 self.all_hosts = list()
212 self.host_obj = dict()
213 self.newPorts = list()
214 self.portsForUpdate = list()
215 self.portsForRemoval = list()
216
217 # Update host type with the corresponding index
218 host_type = args['host_type_index']
219 if host_type:
220 host_type = host_type.lower()
221 if host_type in [key.lower() for key in list(self.HOST_TYPE_INDEXES.keys())]:
222 self.host_type_index = self.HOST_TYPE_INDEXES[host_type]
223 elif host_type.isdigit():
224 self.host_type_index = int(args['host_type_index'])
225 else:
226 self.module.fail_json(msg="host_type must be either a host type name or host type index found integer"
227 " the documentation.")
228
229 # logging setup
230 self._logger = logging.getLogger(self.__class__.__name__)
231 if args['log_path']:
232 logging.basicConfig(
233 level=logging.DEBUG, filename=args['log_path'], filemode='w',
234 format='%(relativeCreated)dms %(levelname)s %(module)s.%(funcName)s:%(lineno)d\n %(message)s')
235
236 if not self.url.endswith('/'):
237 self.url += '/'
238
239 # Ensure when state==present then host_type_index is defined
240 if self.state == "present" and self.host_type_index is None:
241 self.module.fail_json(msg="Host_type_index is required when state=='present'. Array Id: [%s]" % self.ssid)
242
243 # Fix port representation if they are provided with colons
244 if self.ports is not None:
245 for port in self.ports:
246 port['label'] = port['label'].lower()
247 port['type'] = port['type'].lower()
248 port['port'] = port['port'].lower()
249
250 # Determine whether address is 16-byte WWPN and, if so, remove
251 if re.match(r'^(0x)?[0-9a-f]{16}$', port['port'].replace(':', '')):
252 port['port'] = port['port'].replace(':', '').replace('0x', '')
253
254 def valid_host_type(self):
255 host_types = None
256 try:
257 (rc, host_types) = request(self.url + 'storage-systems/%s/host-types' % self.ssid, url_password=self.pwd,
258 url_username=self.user, validate_certs=self.certs, headers=HEADERS)
259 except Exception as err:
260 self.module.fail_json(
261 msg="Failed to get host types. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
262
263 try:
264 match = list(filter(lambda host_type: host_type['index'] == self.host_type_index, host_types))[0]
265 return True
266 except IndexError:
267 self.module.fail_json(msg="There is no host type with index %s" % self.host_type_index)
268
269 def assigned_host_ports(self, apply_unassigning=False):
270 """Determine if the hostPorts requested have already been assigned and return list of required used ports."""
271 used_host_ports = {}
272 for host in self.all_hosts:
273 if host['label'] != self.name:
274 for host_port in host['hostSidePorts']:
275 for port in self.ports:
276 if port['port'] == host_port["address"] or port['label'] == host_port['label']:
277 if not self.force_port:
278 self.module.fail_json(msg="There are no host ports available OR there are not enough"
279 " unassigned host ports")
280 else:
281 # Determine port reference
282 port_ref = [port["hostPortRef"] for port in host["ports"]
283 if port["hostPortName"] == host_port["address"]]
284 port_ref.extend([port["initiatorRef"] for port in host["initiators"]
285 if port["nodeName"]["iscsiNodeName"] == host_port["address"]])
286
287 # Create dictionary of hosts containing list of port references
288 if host["hostRef"] not in used_host_ports.keys():
289 used_host_ports.update({host["hostRef"]: port_ref})
290 else:
291 used_host_ports[host["hostRef"]].extend(port_ref)
292 else:
293 for host_port in host['hostSidePorts']:
294 for port in self.ports:
295 if ((host_port['label'] == port['label'] and host_port['address'] != port['port']) or
296 (host_port['label'] != port['label'] and host_port['address'] == port['port'])):
297 if not self.force_port:
298 self.module.fail_json(msg="There are no host ports available OR there are not enough"
299 " unassigned host ports")
300 else:
301 # Determine port reference
302 port_ref = [port["hostPortRef"] for port in host["ports"]
303 if port["hostPortName"] == host_port["address"]]
304 port_ref.extend([port["initiatorRef"] for port in host["initiators"]
305 if port["nodeName"]["iscsiNodeName"] == host_port["address"]])
306
307 # Create dictionary of hosts containing list of port references
308 if host["hostRef"] not in used_host_ports.keys():
309 used_host_ports.update({host["hostRef"]: port_ref})
310 else:
311 used_host_ports[host["hostRef"]].extend(port_ref)
312
313 # Unassign assigned ports
314 if apply_unassigning:
315 for host_ref in used_host_ports.keys():
316 try:
317 rc, resp = request(self.url + 'storage-systems/%s/hosts/%s' % (self.ssid, host_ref),
318 url_username=self.user, url_password=self.pwd, headers=HEADERS,
319 validate_certs=self.certs, method='POST',
320 data=json.dumps({"portsToRemove": used_host_ports[host_ref]}))
321 except Exception as err:
322 self.module.fail_json(msg="Failed to unassign host port. Host Id [%s]. Array Id [%s]. Ports [%s]."
323 " Error [%s]." % (self.host_obj['id'], self.ssid,
324 used_host_ports[host_ref], to_native(err)))
325
326 return used_host_ports
327
328 def group_id(self):
329 if self.group:
330 try:
331 (rc, all_groups) = request(self.url + 'storage-systems/%s/host-groups' % self.ssid,
332 url_password=self.pwd,
333 url_username=self.user, validate_certs=self.certs, headers=HEADERS)
334 except Exception as err:
335 self.module.fail_json(
336 msg="Failed to get host groups. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
337
338 try:
339 group_obj = list(filter(lambda group: group['name'] == self.group, all_groups))[0]
340 return group_obj['id']
341 except IndexError:
342 self.module.fail_json(msg="No group with the name: %s exists" % self.group)
343 else:
344 # Return the value equivalent of no group
345 return "0000000000000000000000000000000000000000"
346
347 def host_exists(self):
348 """Determine if the requested host exists
349 As a side effect, set the full list of defined hosts in 'all_hosts', and the target host in 'host_obj'.
350 """
351 match = False
352 all_hosts = list()
353
354 try:
355 (rc, all_hosts) = request(self.url + 'storage-systems/%s/hosts' % self.ssid, url_password=self.pwd,
356 url_username=self.user, validate_certs=self.certs, headers=HEADERS)
357 except Exception as err:
358 self.module.fail_json(
359 msg="Failed to determine host existence. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
360
361 # Augment the host objects
362 for host in all_hosts:
363 for port in host['hostSidePorts']:
364 port['type'] = port['type'].lower()
365 port['address'] = port['address'].lower()
366 port['label'] = port['label'].lower()
367
368 # Augment hostSidePorts with their ID (this is an omission in the API)
369 ports = dict((port['label'], port['id']) for port in host['ports'])
370 ports.update((port['label'], port['id']) for port in host['initiators'])
371
372 for host_side_port in host['hostSidePorts']:
373 if host_side_port['label'] in ports:
374 host_side_port['id'] = ports[host_side_port['label']]
375
376 if host['label'] == self.name:
377 self.host_obj = host
378 match = True
379
380 self.all_hosts = all_hosts
381 return match
382
383 def needs_update(self):
384 """Determine whether we need to update the Host object
385 As a side effect, we will set the ports that we need to update (portsForUpdate), and the ports we need to add
386 (newPorts), on self.
387 """
388 changed = False
389 if (self.host_obj["clusterRef"].lower() != self.group_id().lower() or
390 self.host_obj["hostTypeIndex"] != self.host_type_index):
391 self._logger.info("Either hostType or the clusterRef doesn't match, an update is required.")
392 changed = True
393 current_host_ports = dict((port["id"], {"type": port["type"], "port": port["address"], "label": port["label"]})
394 for port in self.host_obj["hostSidePorts"])
395
396 if self.ports:
397 for port in self.ports:
398 for current_host_port_id in current_host_ports.keys():
399 if port == current_host_ports[current_host_port_id]:
400 current_host_ports.pop(current_host_port_id)
401 break
402 elif port["port"] == current_host_ports[current_host_port_id]["port"]:
403 if self.port_on_diff_host(port) and not self.force_port:
404 self.module.fail_json(msg="The port you specified [%s] is associated with a different host."
405 " Specify force_port as True or try a different port spec" % port)
406
407 if (port["label"] != current_host_ports[current_host_port_id]["label"] or
408 port["type"] != current_host_ports[current_host_port_id]["type"]):
409 current_host_ports.pop(current_host_port_id)
410 self.portsForUpdate.append({"portRef": current_host_port_id, "port": port["port"],
411 "label": port["label"], "hostRef": self.host_obj["hostRef"]})
412 break
413 else:
414 self.newPorts.append(port)
415
416 self.portsForRemoval = list(current_host_ports.keys())
417 changed = any([self.newPorts, self.portsForUpdate, self.portsForRemoval, changed])
418
419 return changed
420
421 def port_on_diff_host(self, arg_port):
422 """ Checks to see if a passed in port arg is present on a different host """
423 for host in self.all_hosts:
424 # Only check 'other' hosts
425 if host['name'] != self.name:
426 for port in host['hostSidePorts']:
427 # Check if the port label is found in the port dict list of each host
428 if arg_port['label'] == port['label'] or arg_port['port'] == port['address']:
429 self.other_host = host
430 return True
431 return False
432
433 def update_host(self):
434 self._logger.info("Beginning the update for host=%s.", self.name)
435
436 if self.ports:
437
438 # Remove ports that need reassigning from their current host.
439 self.assigned_host_ports(apply_unassigning=True)
440
441 self.post_body["portsToUpdate"] = self.portsForUpdate
442 self.post_body["ports"] = self.newPorts
443 self._logger.info("Requested ports: %s", pformat(self.ports))
444 else:
445 self._logger.info("No host ports were defined.")
446
447 if self.group:
448 self.post_body['groupId'] = self.group_id()
449
450 self.post_body['hostType'] = dict(index=self.host_type_index)
451
452 api = self.url + 'storage-systems/%s/hosts/%s' % (self.ssid, self.host_obj['id'])
453 self._logger.info("POST => url=%s, body=%s.", api, pformat(self.post_body))
454
455 if not self.check_mode:
456 try:
457 (rc, self.host_obj) = request(api, url_username=self.user, url_password=self.pwd, headers=HEADERS,
458 validate_certs=self.certs, method='POST', data=json.dumps(self.post_body))
459 except Exception as err:
460 self.module.fail_json(
461 msg="Failed to update host. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
462
463 payload = self.build_success_payload(self.host_obj)
464 self.module.exit_json(changed=True, **payload)
465
466 def create_host(self):
467 self._logger.info("Creating host definition.")
468
469 # Remove ports that need reassigning from their current host.
470 self.assigned_host_ports(apply_unassigning=True)
471
472 # needs_reassignment = False
473 post_body = dict(
474 name=self.name,
475 hostType=dict(index=self.host_type_index),
476 groupId=self.group_id(),
477 )
478
479 if self.ports:
480 post_body.update(ports=self.ports)
481
482 api = self.url + "storage-systems/%s/hosts" % self.ssid
483 self._logger.info('POST => url=%s, body=%s', api, pformat(post_body))
484
485 if not self.check_mode:
486 if not self.host_exists():
487 try:
488 (rc, self.host_obj) = request(api, method='POST', url_username=self.user, url_password=self.pwd, validate_certs=self.certs,
489 data=json.dumps(post_body), headers=HEADERS)
490 except Exception as err:
491 self.module.fail_json(
492 msg="Failed to create host. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
493 else:
494 payload = self.build_success_payload(self.host_obj)
495 self.module.exit_json(changed=False, msg="Host already exists. Id [%s]. Host [%s]." % (self.ssid, self.name), **payload)
496
497 payload = self.build_success_payload(self.host_obj)
498 self.module.exit_json(changed=True, msg='Host created.', **payload)
499
500 def remove_host(self):
501 try:
502 (rc, resp) = request(self.url + "storage-systems/%s/hosts/%s" % (self.ssid, self.host_obj['id']),
503 method='DELETE',
504 url_username=self.user, url_password=self.pwd, validate_certs=self.certs)
505 except Exception as err:
506 self.module.fail_json(
507 msg="Failed to remove host. Host[%s]. Array Id [%s]. Error [%s]." % (self.host_obj['id'],
508 self.ssid,
509 to_native(err)))
510
511 def build_success_payload(self, host=None):
512 keys = ['id']
513 if host is not None:
514 result = dict((key, host[key]) for key in keys)
515 else:
516 result = dict()
517 result['ssid'] = self.ssid
518 result['api_url'] = self.url
519 return result
520
521 def apply(self):
522 if self.state == 'present':
523 if self.host_exists():
524 if self.needs_update() and self.valid_host_type():
525 self.update_host()
526 else:
527 payload = self.build_success_payload(self.host_obj)
528 self.module.exit_json(changed=False, msg="Host already present; no changes required.", **payload)
529 elif self.valid_host_type():
530 self.create_host()
531 else:
532 payload = self.build_success_payload()
533 if self.host_exists():
534 self.remove_host()
535 self.module.exit_json(changed=True, msg="Host removed.", **payload)
536 else:
537 self.module.exit_json(changed=False, msg="Host already absent.", **payload)
538
539
540 def main():
541 host = Host()
542 host.apply()
543
544
545 if __name__ == '__main__':
546 main()