Merging of broadcast domain and Broadcast domain port (#51978)
* Revert "changes to clusteR" This reverts commit 33ee1b71e4bc8435fb315762a871f8c4cb6c5f80. * Add domain ports in to broadcast domain * ansibot fixes * Revert "Revert "changes to clusteR"" This reverts commit 2713c75f31cbf81ef1785d6ab9ea5d0d4db9af60. * Fix author
This commit is contained in:
parent
473596a472
commit
0e77eeb205
2 changed files with 579 additions and 90 deletions
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
# (c) 2018, NetApp, Inc
|
||||
# (c) 2018-2019, NetApp, Inc
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
@ -13,7 +13,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
|
|||
|
||||
DOCUMENTATION = '''
|
||||
module: na_ontap_broadcast_domain
|
||||
short_description: NetApp ONTAP manage broadcast domains..
|
||||
short_description: NetApp ONTAP manage broadcast domains.
|
||||
extends_documentation_fragment:
|
||||
- netapp.na_ontap
|
||||
version_added: '2.6'
|
||||
|
@ -26,52 +26,73 @@ options:
|
|||
- Whether the specified broadcast domain should exist or not.
|
||||
choices: ['present', 'absent']
|
||||
default: present
|
||||
broadcast_domain:
|
||||
name:
|
||||
description:
|
||||
- Specify the broadcast_domain name
|
||||
- Specify the broadcast domain name.
|
||||
required: true
|
||||
aliases:
|
||||
- broadcast_domain
|
||||
from_name:
|
||||
description:
|
||||
- Specify the broadcast domain name to be split into new broadcast domain.
|
||||
version_added: "2.8"
|
||||
mtu:
|
||||
description:
|
||||
- Specify the required mtu for the broadcast domain
|
||||
- Specify the required mtu for the broadcast domain.
|
||||
ipspace:
|
||||
description:
|
||||
- Specify the required ipspace for the broadcast domain.
|
||||
- A domain ipspace can not be modified after the domain has been created
|
||||
- A domain ipspace can not be modified after the domain has been created.
|
||||
ports:
|
||||
description:
|
||||
- Specify the ports associated with this broadcast domain. Should be comma separated
|
||||
|
||||
- Specify the ports associated with this broadcast domain. Should be comma separated.
|
||||
- It represents the expected state of a list of ports at any time.
|
||||
- Add a port if it is specified in expected state but not in current state.
|
||||
- Delete a port if it is specified in current state but not in expected state.
|
||||
- For split action, it represents the ports to be split from current broadcast domain and added to the new broadcast domain.
|
||||
- if all ports are removed or splited from a broadcast domain, the broadcast domain will be deleted automatically.
|
||||
'''
|
||||
|
||||
EXAMPLES = """
|
||||
- name: create broadcast domain
|
||||
na_ontap_broadcast_domain:
|
||||
state=present
|
||||
username={{ netapp_username }}
|
||||
password={{ netapp_password }}
|
||||
hostname={{ netapp_hostname }}
|
||||
broadcast_domain=123kevin
|
||||
mtu=1000
|
||||
ipspace=Default
|
||||
ports=khutton-vsim1:e0d-12,khutton-vsim1:e0d-13
|
||||
- name: delete broadcast domain
|
||||
na_ontap_broadcast_domain:
|
||||
state=absent
|
||||
username={{ netapp_username }}
|
||||
password={{ netapp_password }}
|
||||
hostname={{ netapp_hostname }}
|
||||
broadcast_domain=123kevin
|
||||
mtu=1000
|
||||
ipspace=Default
|
||||
state: present
|
||||
username: "{{ netapp_username }}"
|
||||
password: "{{ netapp_password }}"
|
||||
hostname: "{{ netapp_hostname }}"
|
||||
name: ansible_domain
|
||||
mtu: 1000
|
||||
ipspace: Default
|
||||
ports: ["khutton-vsim1:e0d-12", "khutton-vsim1:e0d-13"]
|
||||
- name: modify broadcast domain
|
||||
na_ontap_broadcast_domain:
|
||||
state=absent
|
||||
username={{ netapp_username }}
|
||||
password={{ netapp_password }}
|
||||
hostname={{ netapp_hostname }}
|
||||
broadcast_domain=123kevin
|
||||
mtu=1100
|
||||
ipspace=Default
|
||||
state: present
|
||||
username: "{{ netapp_username }}"
|
||||
password: "{{ netapp_password }}"
|
||||
hostname: "{{ netapp_hostname }}"
|
||||
name: ansible_domain
|
||||
mtu: 1100
|
||||
ipspace: Default
|
||||
ports: ["khutton-vsim1:e0d-12", "khutton-vsim1:e0d-13"]
|
||||
- name: split broadcast domain
|
||||
na_ontap_broadcast_domain:
|
||||
state: present
|
||||
username: "{{ netapp_username }}"
|
||||
password: "{{ netapp_password }}"
|
||||
hostname: "{{ netapp_hostname }}"
|
||||
from_name: ansible_domain
|
||||
name: new_ansible_domain
|
||||
mtu: 1200
|
||||
ipspace: Default
|
||||
ports: khutton-vsim1:e0d-12
|
||||
- name: delete broadcast domain
|
||||
na_ontap_broadcast_domain:
|
||||
state: absent
|
||||
username: "{{ netapp_username }}"
|
||||
password: "{{ netapp_password }}"
|
||||
hostname: "{{ netapp_hostname }}"
|
||||
name: ansible_domain
|
||||
ipspace: Default
|
||||
"""
|
||||
|
||||
RETURN = """
|
||||
|
@ -83,6 +104,7 @@ import traceback
|
|||
from ansible.module_utils.basic import AnsibleModule
|
||||
from ansible.module_utils._text import to_native
|
||||
import ansible.module_utils.netapp as netapp_utils
|
||||
from ansible.module_utils.netapp_module import NetAppModule
|
||||
|
||||
HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
|
||||
|
||||
|
@ -98,10 +120,11 @@ class NetAppOntapBroadcastDomain(object):
|
|||
self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
|
||||
self.argument_spec.update(dict(
|
||||
state=dict(required=False, choices=['present', 'absent'], default='present'),
|
||||
broadcast_domain=dict(required=True, type='str'),
|
||||
name=dict(required=True, type='str', aliases=["broadcast_domain"]),
|
||||
ipspace=dict(required=False, type='str'),
|
||||
mtu=dict(required=False, type='str'),
|
||||
ports=dict(required=False, type='list'),
|
||||
from_name=dict(required=False, type='str'),
|
||||
))
|
||||
|
||||
self.module = AnsibleModule(
|
||||
|
@ -109,14 +132,8 @@ class NetAppOntapBroadcastDomain(object):
|
|||
supports_check_mode=True
|
||||
)
|
||||
|
||||
parameters = self.module.params
|
||||
|
||||
# set up state variables
|
||||
self.state = parameters['state']
|
||||
self.broadcast_domain = parameters['broadcast_domain']
|
||||
self.ipspace = parameters['ipspace']
|
||||
self.mtu = parameters['mtu']
|
||||
self.ports = parameters['ports']
|
||||
self.na_helper = NetAppModule()
|
||||
self.parameters = self.na_helper.set_parameters(self.module.params)
|
||||
|
||||
if HAS_NETAPP_LIB is False:
|
||||
self.module.fail_json(msg="the python NetApp-Lib module is required")
|
||||
|
@ -124,23 +141,24 @@ class NetAppOntapBroadcastDomain(object):
|
|||
self.server = netapp_utils.setup_na_ontap_zapi(module=self.module)
|
||||
return
|
||||
|
||||
def get_broadcast_domain(self):
|
||||
def get_broadcast_domain(self, broadcast_domain=None):
|
||||
"""
|
||||
Return details about the broadcast domain
|
||||
:param:
|
||||
name : broadcast domain name
|
||||
:param broadcast_domain: specific broadcast domain to get.
|
||||
:return: Details about the broadcas domain. None if not found.
|
||||
:rtype: dict
|
||||
"""
|
||||
if broadcast_domain is None:
|
||||
broadcast_domain = self.parameters['name']
|
||||
domain_get_iter = netapp_utils.zapi.NaElement('net-port-broadcast-domain-get-iter')
|
||||
broadcast_domain_info = netapp_utils.zapi.NaElement('net-port-broadcast-domain-info')
|
||||
broadcast_domain_info.add_new_child('broadcast-domain', self.broadcast_domain)
|
||||
broadcast_domain_info.add_new_child('broadcast-domain', broadcast_domain)
|
||||
query = netapp_utils.zapi.NaElement('query')
|
||||
query.add_child_elem(broadcast_domain_info)
|
||||
domain_get_iter.add_child_elem(query)
|
||||
result = self.server.invoke_successfully(domain_get_iter, True)
|
||||
domain_exists = None
|
||||
# check if job exists
|
||||
# check if broadcast_domain exists
|
||||
if result.get_child_by_name('num-records') and \
|
||||
int(result.get_child_content('num-records')) == 1:
|
||||
domain_info = result.get_child_by_name('attributes-list').\
|
||||
|
@ -148,10 +166,16 @@ class NetAppOntapBroadcastDomain(object):
|
|||
domain_name = domain_info.get_child_content('broadcast-domain')
|
||||
domain_mtu = domain_info.get_child_content('mtu')
|
||||
domain_ipspace = domain_info.get_child_content('ipspace')
|
||||
domain_ports = domain_info.get_child_by_name('ports')
|
||||
if domain_ports is not None:
|
||||
ports = [port.get_child_content('port') for port in domain_ports.get_children()]
|
||||
else:
|
||||
ports = []
|
||||
domain_exists = {
|
||||
'domain-name': domain_name,
|
||||
'mtu': domain_mtu,
|
||||
'ipspace': domain_ipspace
|
||||
'ipspace': domain_ipspace,
|
||||
'ports': ports
|
||||
}
|
||||
return domain_exists
|
||||
|
||||
|
@ -160,35 +184,38 @@ class NetAppOntapBroadcastDomain(object):
|
|||
Creates a new broadcast domain
|
||||
"""
|
||||
domain_obj = netapp_utils.zapi.NaElement('net-port-broadcast-domain-create')
|
||||
domain_obj.add_new_child("broadcast-domain", self.broadcast_domain)
|
||||
if self.ipspace:
|
||||
domain_obj.add_new_child("ipspace", self.ipspace)
|
||||
domain_obj.add_new_child("mtu", self.mtu)
|
||||
if self.ports:
|
||||
domain_obj.add_new_child("broadcast-domain", self.parameters['name'])
|
||||
if self.parameters.get('ipspace'):
|
||||
domain_obj.add_new_child("ipspace", self.parameters['ipspace'])
|
||||
if self.parameters.get('mtu'):
|
||||
domain_obj.add_new_child("mtu", self.parameters['mtu'])
|
||||
if self.parameters.get('ports'):
|
||||
ports_obj = netapp_utils.zapi.NaElement('ports')
|
||||
domain_obj.add_child_elem(ports_obj)
|
||||
for port in self.ports:
|
||||
for port in self.parameters['ports']:
|
||||
ports_obj.add_new_child('net-qualified-port-name', port)
|
||||
try:
|
||||
self.server.invoke_successfully(domain_obj, True)
|
||||
except netapp_utils.zapi.NaApiError as error:
|
||||
self.module.fail_json(msg='Error creating broadcast domain %s: %s' %
|
||||
(self.broadcast_domain, to_native(error)),
|
||||
(self.parameters['name'], to_native(error)),
|
||||
exception=traceback.format_exc())
|
||||
|
||||
def delete_broadcast_domain(self):
|
||||
def delete_broadcast_domain(self, broadcast_domain=None):
|
||||
"""
|
||||
Deletes a broadcast domain
|
||||
"""
|
||||
if broadcast_domain is None:
|
||||
broadcast_domain = self.parameters['name']
|
||||
domain_obj = netapp_utils.zapi.NaElement('net-port-broadcast-domain-destroy')
|
||||
domain_obj.add_new_child("broadcast-domain", self.broadcast_domain)
|
||||
if self.ipspace:
|
||||
domain_obj.add_new_child("ipspace", self.ipspace)
|
||||
domain_obj.add_new_child("broadcast-domain", broadcast_domain)
|
||||
if self.parameters.get('ipspace'):
|
||||
domain_obj.add_new_child("ipspace", self.parameters['ipspace'])
|
||||
try:
|
||||
self.server.invoke_successfully(domain_obj, True)
|
||||
except netapp_utils.zapi.NaApiError as error:
|
||||
self.module.fail_json(msg='Error deleting broadcast domain %s: %s' %
|
||||
(self.broadcast_domain, to_native(error)),
|
||||
(broadcast_domain, to_native(error)),
|
||||
exception=traceback.format_exc())
|
||||
|
||||
def modify_broadcast_domain(self):
|
||||
|
@ -196,51 +223,205 @@ class NetAppOntapBroadcastDomain(object):
|
|||
Modifies ipspace and mtu options of a broadcast domain
|
||||
"""
|
||||
domain_obj = netapp_utils.zapi.NaElement('net-port-broadcast-domain-modify')
|
||||
domain_obj.add_new_child("broadcast-domain", self.broadcast_domain)
|
||||
if self.ipspace:
|
||||
domain_obj.add_new_child("ipspace", self.ipspace)
|
||||
if self.mtu:
|
||||
domain_obj.add_new_child("mtu", self.mtu)
|
||||
domain_obj.add_new_child("broadcast-domain", self.parameters['name'])
|
||||
if self.parameters.get('mtu'):
|
||||
domain_obj.add_new_child("mtu", self.parameters['mtu'])
|
||||
if self.parameters.get('ipspace'):
|
||||
domain_obj.add_new_child("ipspace", self.parameters['ipspace'])
|
||||
try:
|
||||
self.server.invoke_successfully(domain_obj, True)
|
||||
except netapp_utils.zapi.NaApiError as error:
|
||||
self.module.fail_json(msg='Error modifying broadcast domain %s: %s' %
|
||||
(self.broadcast_domain, to_native(error)),
|
||||
(self.parameters['name'], to_native(error)),
|
||||
exception=traceback.format_exc())
|
||||
|
||||
def split_broadcast_domain(self):
|
||||
"""
|
||||
split broadcast domain
|
||||
"""
|
||||
domain_obj = netapp_utils.zapi.NaElement('net-port-broadcast-domain-split')
|
||||
domain_obj.add_new_child("broadcast-domain", self.parameters['from_name'])
|
||||
domain_obj.add_new_child("new-broadcast-domain", self.parameters['name'])
|
||||
if self.parameters.get('ports'):
|
||||
ports_obj = netapp_utils.zapi.NaElement('ports')
|
||||
domain_obj.add_child_elem(ports_obj)
|
||||
for port in self.parameters['ports']:
|
||||
ports_obj.add_new_child('net-qualified-port-name', port)
|
||||
if self.parameters.get('ipspace'):
|
||||
domain_obj.add_new_child("ipspace", self.parameters['ipspace'])
|
||||
try:
|
||||
self.server.invoke_successfully(domain_obj, True)
|
||||
except netapp_utils.zapi.NaApiError as error:
|
||||
self.module.fail_json(msg='Error splitting broadcast domain %s: %s' %
|
||||
(self.parameters['name'], to_native(error)),
|
||||
exception=traceback.format_exc())
|
||||
if len(self.get_broadcast_domain_ports(self.parameters['from_name'])) == 0:
|
||||
self.delete_broadcast_domain(self.parameters['from_name'])
|
||||
|
||||
def modify_redirect(self, modify):
|
||||
"""
|
||||
:param modify: modify attributes.
|
||||
"""
|
||||
for attribute in modify.keys():
|
||||
if attribute == 'mtu':
|
||||
self.modify_broadcast_domain()
|
||||
if attribute == 'ports':
|
||||
self.modify_broadcast_domain_ports()
|
||||
|
||||
def get_modify_attributes(self, current, split):
|
||||
"""
|
||||
:param current: current state.
|
||||
:param split: True or False of split action.
|
||||
:return: list of modified attributes.
|
||||
"""
|
||||
modify = None
|
||||
if self.parameters['state'] == 'present':
|
||||
# split already handled ipspace and ports.
|
||||
if self.parameters.get('from_name'):
|
||||
current = self.get_broadcast_domain(self.parameters['from_name'])
|
||||
if split:
|
||||
modify = self.na_helper.get_modified_attributes(current, self.parameters)
|
||||
if modify.get('ipspace'):
|
||||
del modify['ipspace']
|
||||
if modify.get('ports'):
|
||||
del modify['ports']
|
||||
# ipspace can not be modified.
|
||||
else:
|
||||
modify = self.na_helper.get_modified_attributes(current, self.parameters)
|
||||
if modify.get('ipspace'):
|
||||
self.module.fail_json(msg='A domain ipspace can not be modified after the domain has been created.',
|
||||
exception=traceback.format_exc())
|
||||
return modify
|
||||
|
||||
def modify_broadcast_domain_ports(self):
|
||||
"""
|
||||
compare current and desire ports. Call add or remove ports methods if needed.
|
||||
:return: None.
|
||||
"""
|
||||
current_ports = self.get_broadcast_domain_ports()
|
||||
expect_ports = self.parameters['ports']
|
||||
# if want to remove all ports, simply delete the broadcast domain.
|
||||
if len(expect_ports) == 0:
|
||||
self.delete_broadcast_domain()
|
||||
return
|
||||
ports_to_remove = list(set(current_ports) - set(expect_ports))
|
||||
ports_to_add = list(set(expect_ports) - set(current_ports))
|
||||
|
||||
if len(ports_to_add) > 0:
|
||||
self.add_broadcast_domain_ports(ports_to_add)
|
||||
|
||||
if len(ports_to_remove) > 0:
|
||||
self.delete_broadcast_domain_ports(ports_to_remove)
|
||||
|
||||
def add_broadcast_domain_ports(self, ports):
|
||||
"""
|
||||
Creates new broadcast domain ports
|
||||
"""
|
||||
domain_obj = netapp_utils.zapi.NaElement('net-port-broadcast-domain-add-ports')
|
||||
domain_obj.add_new_child("broadcast-domain", self.parameters['name'])
|
||||
if self.parameters.get('ipspace'):
|
||||
domain_obj.add_new_child("ipspace", self.parameters['ipspace'])
|
||||
if ports:
|
||||
ports_obj = netapp_utils.zapi.NaElement('ports')
|
||||
domain_obj.add_child_elem(ports_obj)
|
||||
for port in ports:
|
||||
ports_obj.add_new_child('net-qualified-port-name', port)
|
||||
try:
|
||||
self.server.invoke_successfully(domain_obj, True)
|
||||
return True
|
||||
except netapp_utils.zapi.NaApiError as error:
|
||||
self.module.fail_json(msg='Error creating port for broadcast domain %s: %s' %
|
||||
(self.parameters['name'], to_native(error)),
|
||||
exception=traceback.format_exc())
|
||||
|
||||
def delete_broadcast_domain_ports(self, ports):
|
||||
"""
|
||||
Deletes broadcast domain ports
|
||||
:param: ports to be deleted.
|
||||
"""
|
||||
domain_obj = netapp_utils.zapi.NaElement('net-port-broadcast-domain-remove-ports')
|
||||
domain_obj.add_new_child("broadcast-domain", self.parameters['name'])
|
||||
if self.parameters.get('ipspace'):
|
||||
domain_obj.add_new_child("ipspace", self.parameters['ipspace'])
|
||||
if ports:
|
||||
ports_obj = netapp_utils.zapi.NaElement('ports')
|
||||
domain_obj.add_child_elem(ports_obj)
|
||||
for port in ports:
|
||||
ports_obj.add_new_child('net-qualified-port-name', port)
|
||||
try:
|
||||
self.server.invoke_successfully(domain_obj, True)
|
||||
return True
|
||||
except netapp_utils.zapi.NaApiError as error:
|
||||
self.module.fail_json(msg='Error deleting port for broadcast domain %s: %s' %
|
||||
(self.parameters['name'], to_native(error)),
|
||||
exception=traceback.format_exc())
|
||||
|
||||
def get_broadcast_domain_ports(self, broadcast_domain=None):
|
||||
"""
|
||||
Return details about the broadcast domain ports.
|
||||
:return: Details about the broadcast domain ports. None if not found.
|
||||
:rtype: list
|
||||
"""
|
||||
if broadcast_domain is None:
|
||||
broadcast_domain = self.parameters['name']
|
||||
domain_get_iter = netapp_utils.zapi.NaElement('net-port-broadcast-domain-get-iter')
|
||||
broadcast_domain_info = netapp_utils.zapi.NaElement('net-port-broadcast-domain-info')
|
||||
broadcast_domain_info.add_new_child('broadcast-domain', broadcast_domain)
|
||||
query = netapp_utils.zapi.NaElement('query')
|
||||
query.add_child_elem(broadcast_domain_info)
|
||||
domain_get_iter.add_child_elem(query)
|
||||
result = self.server.invoke_successfully(domain_get_iter, True)
|
||||
ports = []
|
||||
if result.get_child_by_name('num-records') and \
|
||||
int(result.get_child_content('num-records')) == 1:
|
||||
domain_info = result.get_child_by_name('attributes-list').get_child_by_name('net-port-broadcast-domain-info')
|
||||
domain_ports = domain_info.get_child_by_name('ports')
|
||||
if domain_ports is not None:
|
||||
ports = [port.get_child_content('port') for port in domain_ports.get_children()]
|
||||
return ports
|
||||
|
||||
def apply(self):
|
||||
"""
|
||||
Run Module based on play book
|
||||
"""
|
||||
changed = False
|
||||
broadcast_domain_details = self.get_broadcast_domain()
|
||||
broadcast_domain_exists = False
|
||||
results = netapp_utils.get_cserver(self.server)
|
||||
cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results)
|
||||
netapp_utils.ems_log_event("na_ontap_broadcast_domain", cserver)
|
||||
if broadcast_domain_details:
|
||||
broadcast_domain_exists = True
|
||||
if self.state == 'absent': # delete
|
||||
changed = True
|
||||
elif self.state == 'present': # modify
|
||||
if (self.mtu and self.mtu != broadcast_domain_details['mtu']) or \
|
||||
(self.ipspace and self.ipspace != broadcast_domain_details['ipspace']):
|
||||
changed = True
|
||||
else:
|
||||
if self.state == 'present': # create
|
||||
changed = True
|
||||
if changed:
|
||||
self.asup_log_for_cserver("na_ontap_broadcast_domain")
|
||||
current = self.get_broadcast_domain()
|
||||
cd_action, split = None, None
|
||||
cd_action = self.na_helper.get_cd_action(current, self.parameters)
|
||||
if cd_action == 'create':
|
||||
# either create new domain or split domain.
|
||||
if self.parameters.get('from_name'):
|
||||
split = self.na_helper.is_rename_action(self.get_broadcast_domain(self.parameters['from_name']), current)
|
||||
if split is None:
|
||||
self.module.fail_json(msg='A domain can not be split if it does not exist.',
|
||||
exception=traceback.format_exc())
|
||||
if split:
|
||||
cd_action = None
|
||||
modify = self.get_modify_attributes(current, split)
|
||||
if self.na_helper.changed:
|
||||
if self.module.check_mode:
|
||||
pass
|
||||
else:
|
||||
if self.state == 'present': # execute create
|
||||
if not broadcast_domain_exists:
|
||||
self.create_broadcast_domain()
|
||||
else: # execute modify
|
||||
self.modify_broadcast_domain()
|
||||
elif self.state == 'absent': # execute delete
|
||||
if split:
|
||||
self.split_broadcast_domain()
|
||||
if cd_action == 'create':
|
||||
self.create_broadcast_domain()
|
||||
elif cd_action == 'delete':
|
||||
self.delete_broadcast_domain()
|
||||
self.module.exit_json(changed=changed)
|
||||
elif modify:
|
||||
self.modify_redirect(modify)
|
||||
self.module.exit_json(changed=self.na_helper.changed)
|
||||
|
||||
def asup_log_for_cserver(self, event_name):
|
||||
"""
|
||||
Fetch admin vserver for the given cluster
|
||||
Create and Autosupport log event with the given module name
|
||||
:param event_name: Name of the event log
|
||||
:return: None
|
||||
"""
|
||||
results = netapp_utils.get_cserver(self.server)
|
||||
cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results)
|
||||
netapp_utils.ems_log_event(event_name, cserver)
|
||||
|
||||
|
||||
def main():
|
||||
|
|
|
@ -0,0 +1,308 @@
|
|||
# (c) 2018, NetApp, Inc
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
''' unit test template for ONTAP Ansible module '''
|
||||
|
||||
from __future__ import print_function
|
||||
import json
|
||||
import pytest
|
||||
|
||||
from units.compat import unittest
|
||||
from units.compat.mock import patch, Mock
|
||||
from ansible.module_utils import basic
|
||||
from ansible.module_utils._text import to_bytes
|
||||
import ansible.module_utils.netapp as netapp_utils
|
||||
|
||||
from ansible.modules.storage.netapp.na_ontap_broadcast_domain \
|
||||
import NetAppOntapBroadcastDomain as broadcast_domain_module # module under test
|
||||
|
||||
if not netapp_utils.has_netapp_lib():
|
||||
pytestmark = pytest.mark.skip('skipping as missing required netapp_lib')
|
||||
|
||||
|
||||
def set_module_args(args):
|
||||
"""prepare arguments so that they will be picked up during module creation"""
|
||||
args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
|
||||
basic._ANSIBLE_ARGS = to_bytes(args) # pylint: disable=protected-access
|
||||
|
||||
|
||||
class AnsibleExitJson(Exception):
|
||||
"""Exception class to be raised by module.exit_json and caught by the test case"""
|
||||
pass
|
||||
|
||||
|
||||
class AnsibleFailJson(Exception):
|
||||
"""Exception class to be raised by module.fail_json and caught by the test case"""
|
||||
pass
|
||||
|
||||
|
||||
def exit_json(*args, **kwargs): # pylint: disable=unused-argument
|
||||
"""function to patch over exit_json; package return data into an exception"""
|
||||
if 'changed' not in kwargs:
|
||||
kwargs['changed'] = False
|
||||
raise AnsibleExitJson(kwargs)
|
||||
|
||||
|
||||
def fail_json(*args, **kwargs): # pylint: disable=unused-argument
|
||||
"""function to patch over fail_json; package return data into an exception"""
|
||||
kwargs['failed'] = True
|
||||
raise AnsibleFailJson(kwargs)
|
||||
|
||||
|
||||
class MockONTAPConnection(object):
|
||||
''' mock server connection to ONTAP host '''
|
||||
|
||||
def __init__(self, kind=None, data=None):
|
||||
''' save arguments '''
|
||||
self.type = kind
|
||||
self.params = data
|
||||
self.xml_in = None
|
||||
self.xml_out = None
|
||||
|
||||
def invoke_successfully(self, xml, enable_tunneling): # pylint: disable=unused-argument
|
||||
''' mock invoke_successfully returning xml data '''
|
||||
self.xml_in = xml
|
||||
if self.type == 'broadcast_domain':
|
||||
xml = self.build_broadcast_domain_info(self.params)
|
||||
self.xml_out = xml
|
||||
return xml
|
||||
|
||||
@staticmethod
|
||||
def build_broadcast_domain_info(broadcast_domain_details):
|
||||
''' build xml data for broadcast_domain info '''
|
||||
xml = netapp_utils.zapi.NaElement('xml')
|
||||
attributes = {
|
||||
'num-records': 1,
|
||||
'attributes-list': {
|
||||
'net-port-broadcast-domain-info': {
|
||||
'broadcast-domain': broadcast_domain_details['name'],
|
||||
'ipspace': broadcast_domain_details['ipspace'],
|
||||
'mtu': broadcast_domain_details['mtu'],
|
||||
'ports': {
|
||||
'port-info': {
|
||||
'port': 'test_port_1'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
xml.translate_struct(attributes)
|
||||
return xml
|
||||
|
||||
|
||||
class TestMyModule(unittest.TestCase):
|
||||
''' a group of related Unit Tests '''
|
||||
|
||||
def setUp(self):
|
||||
self.mock_module_helper = patch.multiple(basic.AnsibleModule,
|
||||
exit_json=exit_json,
|
||||
fail_json=fail_json)
|
||||
self.mock_module_helper.start()
|
||||
self.addCleanup(self.mock_module_helper.stop)
|
||||
self.server = MockONTAPConnection()
|
||||
self.mock_broadcast_domain = {
|
||||
'name': 'test_broadcast_domain',
|
||||
'mtu': '1000',
|
||||
'ipspace': 'Default',
|
||||
'ports': 'test_port_1'
|
||||
}
|
||||
|
||||
def mock_args(self):
|
||||
return {
|
||||
'name': self.mock_broadcast_domain['name'],
|
||||
'ipspace': self.mock_broadcast_domain['ipspace'],
|
||||
'mtu': self.mock_broadcast_domain['mtu'],
|
||||
'ports': self.mock_broadcast_domain['ports'],
|
||||
'hostname': 'test',
|
||||
'username': 'test_user',
|
||||
'password': 'test_pass!'
|
||||
}
|
||||
|
||||
def get_broadcast_domain_mock_object(self, kind=None, data=None):
|
||||
"""
|
||||
Helper method to return an na_ontap_volume object
|
||||
:param kind: passes this param to MockONTAPConnection()
|
||||
:param data: passes this param to MockONTAPConnection()
|
||||
:return: na_ontap_volume object
|
||||
"""
|
||||
broadcast_domain_obj = broadcast_domain_module()
|
||||
broadcast_domain_obj.asup_log_for_cserver = Mock(return_value=None)
|
||||
broadcast_domain_obj.cluster = Mock()
|
||||
broadcast_domain_obj.cluster.invoke_successfully = Mock()
|
||||
if kind is None:
|
||||
broadcast_domain_obj.server = MockONTAPConnection()
|
||||
else:
|
||||
if data is None:
|
||||
broadcast_domain_obj.server = MockONTAPConnection(kind='broadcast_domain', data=self.mock_broadcast_domain)
|
||||
else:
|
||||
broadcast_domain_obj.server = MockONTAPConnection(kind='broadcast_domain', data=data)
|
||||
return broadcast_domain_obj
|
||||
|
||||
def test_module_fail_when_required_args_missing(self):
|
||||
''' required arguments are reported as errors '''
|
||||
with pytest.raises(AnsibleFailJson) as exc:
|
||||
set_module_args({})
|
||||
broadcast_domain_module()
|
||||
print('Info: %s' % exc.value.args[0]['msg'])
|
||||
|
||||
def test_get_nonexistent_net_route(self):
|
||||
''' Test if get_broadcast_domain returns None for non-existent broadcast_domain '''
|
||||
set_module_args(self.mock_args())
|
||||
result = self.get_broadcast_domain_mock_object().get_broadcast_domain()
|
||||
assert result is None
|
||||
|
||||
def test_create_error_missing_broadcast_domain(self):
|
||||
''' Test if create throws an error if broadcast_domain is not specified'''
|
||||
data = self.mock_args()
|
||||
del data['name']
|
||||
set_module_args(data)
|
||||
with pytest.raises(AnsibleFailJson) as exc:
|
||||
self.get_broadcast_domain_mock_object('broadcast_domain').create_broadcast_domain()
|
||||
msg = 'missing required arguments: name'
|
||||
assert exc.value.args[0]['msg'] == msg
|
||||
|
||||
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.create_broadcast_domain')
|
||||
def test_successful_create(self, create_broadcast_domain):
|
||||
''' Test successful create '''
|
||||
data = self.mock_args()
|
||||
set_module_args(data)
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_broadcast_domain_mock_object().apply()
|
||||
assert exc.value.args[0]['changed']
|
||||
create_broadcast_domain.assert_called_with()
|
||||
|
||||
def test_create_idempotency(self):
|
||||
''' Test create idempotency '''
|
||||
set_module_args(self.mock_args())
|
||||
obj = self.get_broadcast_domain_mock_object('broadcast_domain')
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
obj.apply()
|
||||
assert not exc.value.args[0]['changed']
|
||||
|
||||
def test_modify_mtu(self):
|
||||
''' Test successful modify mtu '''
|
||||
data = self.mock_args()
|
||||
data['mtu'] = '1200'
|
||||
set_module_args(data)
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_broadcast_domain_mock_object('broadcast_domain').apply()
|
||||
assert exc.value.args[0]['changed']
|
||||
|
||||
def test_modify_ipspace_idempotency(self):
|
||||
''' Test modify ipsapce idempotency'''
|
||||
data = self.mock_args()
|
||||
data['ipspace'] = 'Cluster'
|
||||
set_module_args(data)
|
||||
with pytest.raises(AnsibleFailJson) as exc:
|
||||
self.get_broadcast_domain_mock_object('broadcast_domain').apply()
|
||||
msg = 'A domain ipspace can not be modified after the domain has been created.'
|
||||
assert exc.value.args[0]['msg'] == msg
|
||||
|
||||
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.add_broadcast_domain_ports')
|
||||
def test_add_ports(self, add_broadcast_domain_ports):
|
||||
''' Test successful modify ports '''
|
||||
data = self.mock_args()
|
||||
data['ports'] = 'test_port_1,test_port_2'
|
||||
set_module_args(data)
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_broadcast_domain_mock_object('broadcast_domain').apply()
|
||||
assert exc.value.args[0]['changed']
|
||||
add_broadcast_domain_ports.assert_called_with(['test_port_2'])
|
||||
|
||||
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.delete_broadcast_domain_ports')
|
||||
def test_delete_ports(self, delete_broadcast_domain_ports):
|
||||
''' Test successful modify ports '''
|
||||
data = self.mock_args()
|
||||
data['ports'] = ''
|
||||
set_module_args(data)
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_broadcast_domain_mock_object('broadcast_domain').apply()
|
||||
assert exc.value.args[0]['changed']
|
||||
delete_broadcast_domain_ports.assert_called_with(['test_port_1'])
|
||||
|
||||
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.modify_broadcast_domain')
|
||||
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.split_broadcast_domain')
|
||||
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.get_broadcast_domain')
|
||||
def test_split_broadcast_domain(self, get_broadcast_domain, split_broadcast_domain, modify_broadcast_domain):
|
||||
''' Test successful split broadcast domain '''
|
||||
data = self.mock_args()
|
||||
data['from_name'] = 'test_broadcast_domain'
|
||||
data['name'] = 'test_broadcast_domain_2'
|
||||
data['ports'] = 'test_port_2'
|
||||
set_module_args(data)
|
||||
current = {
|
||||
'name': 'test_broadcast_domain',
|
||||
'mtu': '1000',
|
||||
'ipspace': 'Default',
|
||||
'ports': ['test_port_1,test_port2']
|
||||
}
|
||||
get_broadcast_domain.side_effect = [
|
||||
None,
|
||||
current,
|
||||
current
|
||||
]
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_broadcast_domain_mock_object().apply()
|
||||
assert exc.value.args[0]['changed']
|
||||
modify_broadcast_domain.assert_not_called()
|
||||
split_broadcast_domain.assert_called_with()
|
||||
|
||||
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.delete_broadcast_domain')
|
||||
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.modify_broadcast_domain')
|
||||
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.get_broadcast_domain')
|
||||
def test_split_broadcast_domain_modify_delete(self, get_broadcast_domain, modify_broadcast_domain, delete_broadcast_domain):
|
||||
''' Test successful split broadcast domain '''
|
||||
data = self.mock_args()
|
||||
data['from_name'] = 'test_broadcast_domain'
|
||||
data['name'] = 'test_broadcast_domain_2'
|
||||
data['ports'] = 'test_port_1,test_port_2'
|
||||
data['mtu'] = '1200'
|
||||
set_module_args(data)
|
||||
|
||||
current = {
|
||||
'name': 'test_broadcast_domain',
|
||||
'mtu': '1000',
|
||||
'ipspace': 'Default',
|
||||
'ports': ['test_port_1,test_port2']
|
||||
}
|
||||
get_broadcast_domain.side_effect = [
|
||||
None,
|
||||
current,
|
||||
current
|
||||
]
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_broadcast_domain_mock_object().apply()
|
||||
assert exc.value.args[0]['changed']
|
||||
delete_broadcast_domain.assert_called_with('test_broadcast_domain')
|
||||
modify_broadcast_domain.assert_called_with()
|
||||
|
||||
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.get_broadcast_domain')
|
||||
def test_split_broadcast_domain_not_exist(self, get_broadcast_domain):
|
||||
''' Test successful split broadcast domain '''
|
||||
data = self.mock_args()
|
||||
data['from_name'] = 'test_broadcast_domain'
|
||||
data['name'] = 'test_broadcast_domain_2'
|
||||
data['ports'] = 'test_port_2'
|
||||
set_module_args(data)
|
||||
|
||||
get_broadcast_domain.side_effect = [
|
||||
None,
|
||||
None,
|
||||
]
|
||||
with pytest.raises(AnsibleFailJson) as exc:
|
||||
self.get_broadcast_domain_mock_object().apply()
|
||||
msg = 'A domain can not be split if it does not exist.'
|
||||
assert exc.value.args[0]['msg'], msg
|
||||
|
||||
@patch('ansible.modules.storage.netapp.na_ontap_broadcast_domain.NetAppOntapBroadcastDomain.split_broadcast_domain')
|
||||
def test_split_broadcast_domain_idempotency(self, split_broadcast_domain):
|
||||
''' Test successful split broadcast domain '''
|
||||
data = self.mock_args()
|
||||
data['from_name'] = 'test_broadcast_domain'
|
||||
data['ports'] = 'test_port_1'
|
||||
set_module_args(data)
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_broadcast_domain_mock_object('broadcast_domain').apply()
|
||||
assert exc.value.args[0]['changed'] is False
|
||||
split_broadcast_domain.assert_not_called()
|
Loading…
Reference in a new issue