mirror of
https://github.com/ansible-collections/community.general.git
synced 2024-09-14 20:13:21 +02:00
New Module: Allow for copy of Luns (#52285)
* Revert "changes to clusteR" This reverts commit 33ee1b71e4bc8435fb315762a871f8c4cb6c5f80. * add lun copy * Revert "Revert "changes to clusteR"" This reverts commit 8e56b999e6cf6a65de339e516f7134a6b6b39cba.
This commit is contained in:
parent
d63794741f
commit
fde2e2d195
2 changed files with 343 additions and 0 deletions
184
lib/ansible/modules/storage/netapp/na_ontap_lun_copy.py
Normal file
184
lib/ansible/modules/storage/netapp/na_ontap_lun_copy.py
Normal file
|
@ -0,0 +1,184 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
# (c) 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
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
|
||||
module: na_ontap_lun_copy
|
||||
|
||||
short_description: NetApp ONTAP copy LUNs
|
||||
extends_documentation_fragment:
|
||||
- netapp.na_ontap
|
||||
version_added: '2.8'
|
||||
author: NetApp Ansible Team (@carchi8py) <ng-ansibleteam@netapp.com>
|
||||
|
||||
description:
|
||||
- Copy LUNs on NetApp ONTAP.
|
||||
|
||||
options:
|
||||
|
||||
state:
|
||||
description:
|
||||
- Whether the specified LUN should exist or not.
|
||||
choices: ['present']
|
||||
default: present
|
||||
|
||||
destination_vserver:
|
||||
description:
|
||||
- the name of the Vserver that will host the new LUN.
|
||||
required: true
|
||||
|
||||
destination_path:
|
||||
description:
|
||||
- Specifies the full path to the new LUN.
|
||||
required: true
|
||||
|
||||
source_path:
|
||||
description:
|
||||
- Specifies the full path to the source LUN.
|
||||
required: true
|
||||
|
||||
source_vserver:
|
||||
description:
|
||||
- Specifies the name of the vserver hosting the LUN to be copied.
|
||||
|
||||
'''
|
||||
EXAMPLES = """
|
||||
- name: Copy LUN
|
||||
na_ontap_lun:
|
||||
na_ontap_lun_copy:
|
||||
destination_vserver: ansible
|
||||
destination_path: /vol/test/test_copy_dest_dest_new
|
||||
source_path: /vol/test/test_copy_1
|
||||
source_vserver: ansible
|
||||
hostname: "{{ netapp_hostname }}"
|
||||
username: "{{ netapp_username }}"
|
||||
password: "{{ netapp_password }}"
|
||||
"""
|
||||
|
||||
RETURN = """
|
||||
|
||||
"""
|
||||
|
||||
import traceback
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
from ansible.module_utils._text import to_native
|
||||
from ansible.module_utils.netapp_module import NetAppModule
|
||||
import ansible.module_utils.netapp as netapp_utils
|
||||
|
||||
|
||||
HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
|
||||
|
||||
|
||||
class NetAppOntapLUNCopy(object):
|
||||
|
||||
def __init__(self):
|
||||
self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
|
||||
self.argument_spec.update(dict(
|
||||
state=dict(required=False, choices=['present'], default='present'),
|
||||
destination_vserver=dict(required=True, type='str'),
|
||||
destination_path=dict(required=True, type='str'),
|
||||
source_path=dict(required=True, type='str'),
|
||||
source_vserver=dict(required=False, type='str'),
|
||||
|
||||
))
|
||||
|
||||
self.module = AnsibleModule(
|
||||
argument_spec=self.argument_spec,
|
||||
supports_check_mode=True
|
||||
)
|
||||
|
||||
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")
|
||||
else:
|
||||
self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['destination_vserver'])
|
||||
|
||||
def get_lun(self):
|
||||
"""
|
||||
Check if the LUN exis
|
||||
|
||||
:return: true is it exists, false otherwise
|
||||
:rtype: bool
|
||||
"""
|
||||
|
||||
return_value = False
|
||||
lun_info = netapp_utils.zapi.NaElement('lun-get-iter')
|
||||
query_details = netapp_utils.zapi.NaElement('lun-info')
|
||||
|
||||
query_details.add_new_child('path', self.parameters['destination_path'])
|
||||
query_details.add_new_child('vserver', self.parameters['destination_vserver'])
|
||||
|
||||
query = netapp_utils.zapi.NaElement('query')
|
||||
query.add_child_elem(query_details)
|
||||
|
||||
lun_info.add_child_elem(query)
|
||||
try:
|
||||
result = self.server.invoke_successfully(lun_info, True)
|
||||
|
||||
except netapp_utils.zapi.NaApiError as e:
|
||||
self.module.fail_json(msg="Error getting lun info %s for verver %s: %s" %
|
||||
(self.parameters['destination_path'], self.parameters['destination_vserver'], to_native(e)),
|
||||
exception=traceback.format_exc())
|
||||
|
||||
if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1:
|
||||
return_value = True
|
||||
return return_value
|
||||
|
||||
def copy_lun(self):
|
||||
"""
|
||||
Copy LUN with requested path and vserver
|
||||
"""
|
||||
lun_copy = netapp_utils.zapi.NaElement.create_node_with_children(
|
||||
'lun-copy-start', **{'source-vserver': self.parameters['source_vserver']})
|
||||
|
||||
path_obj = netapp_utils.zapi.NaElement('paths')
|
||||
pair = netapp_utils.zapi.NaElement('lun-path-pair')
|
||||
pair.add_new_child('destination-path', self.parameters['destination_path'])
|
||||
pair.add_new_child('source-path', self.parameters['source_path'])
|
||||
path_obj.add_child_elem(pair)
|
||||
lun_copy.add_child_elem(path_obj)
|
||||
|
||||
try:
|
||||
self.server.invoke_successfully(lun_copy, enable_tunneling=True)
|
||||
except netapp_utils.zapi.NaApiError as e:
|
||||
self.module.fail_json(msg="Error copying lun from %s to vserver %s: %s" %
|
||||
(self.parameters['source_vserver'], self.parameters['destination_vserver'], to_native(e)),
|
||||
exception=traceback.format_exc())
|
||||
|
||||
def apply(self):
|
||||
|
||||
netapp_utils.ems_log_event("na_ontap_lun_copy", self.server)
|
||||
if self.get_lun(): # lun already exists at destination
|
||||
changed = False
|
||||
else:
|
||||
changed = True
|
||||
if self.module.check_mode:
|
||||
pass
|
||||
else:
|
||||
# need to copy lun
|
||||
if self.parameters['state'] == 'present':
|
||||
self.copy_lun()
|
||||
|
||||
self.module.exit_json(changed=changed)
|
||||
|
||||
|
||||
def main():
|
||||
v = NetAppOntapLUNCopy()
|
||||
v.apply()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
159
test/units/modules/storage/netapp/test_na_ontap_lun_copy.py
Normal file
159
test/units/modules/storage/netapp/test_na_ontap_lun_copy.py
Normal file
|
@ -0,0 +1,159 @@
|
|||
# (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_lun_copy \
|
||||
import NetAppOntapLUNCopy as my_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, parm1=None):
|
||||
''' save arguments '''
|
||||
self.type = kind
|
||||
self.parm1 = parm1
|
||||
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 == 'destination_vserver':
|
||||
xml = self.build_lun_info(self.parm1)
|
||||
self.xml_out = xml
|
||||
return xml
|
||||
|
||||
@staticmethod
|
||||
def build_lun_info(data):
|
||||
''' build xml data for lun-info '''
|
||||
xml = netapp_utils.zapi.NaElement('xml')
|
||||
attributes = {
|
||||
'num-records': 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.mock_lun_copy = {
|
||||
'source_vserver': 'ansible',
|
||||
'destination_path': '/vol/test/test_copy_dest_dest_new_reviewd_new',
|
||||
'source_path': '/vol/test/test_copy_1',
|
||||
'destination_vserver': 'ansible',
|
||||
'state': 'present'
|
||||
}
|
||||
|
||||
def mock_args(self):
|
||||
|
||||
return {
|
||||
'source_vserver': self.mock_lun_copy['source_vserver'],
|
||||
'destination_path': self.mock_lun_copy['destination_path'],
|
||||
'source_path': self.mock_lun_copy['source_path'],
|
||||
'destination_vserver': self.mock_lun_copy['destination_vserver'],
|
||||
'state': self.mock_lun_copy['state'],
|
||||
'hostname': 'hostname',
|
||||
'username': 'username',
|
||||
'password': 'password',
|
||||
}
|
||||
# self.server = MockONTAPConnection()
|
||||
|
||||
def get_lun_copy_mock_object(self, kind=None):
|
||||
"""
|
||||
Helper method to return an na_ontap_lun_copy object
|
||||
:param kind: passes this param to MockONTAPConnection()
|
||||
:return: na_ontap_interface object
|
||||
"""
|
||||
lun_copy_obj = my_module()
|
||||
lun_copy_obj.autosupport_log = Mock(return_value=None)
|
||||
if kind is None:
|
||||
lun_copy_obj.server = MockONTAPConnection()
|
||||
else:
|
||||
lun_copy_obj.server = MockONTAPConnection(kind=kind)
|
||||
return lun_copy_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({})
|
||||
my_module()
|
||||
print('Info: %s' % exc.value.args[0]['msg'])
|
||||
|
||||
def test_create_error_missing_param(self):
|
||||
''' Test if create throws an error if required param 'destination_vserver' is not specified'''
|
||||
data = self.mock_args()
|
||||
del data['destination_vserver']
|
||||
set_module_args(data)
|
||||
with pytest.raises(AnsibleFailJson) as exc:
|
||||
self.get_lun_copy_mock_object('lun_copy').copy_lun()
|
||||
msg = 'Error: Missing one or more required parameters for copying lun: ' \
|
||||
'destination_path, source_path, destination_path'
|
||||
expected = sorted(','.split(msg))
|
||||
received = sorted(','.split(exc.value.args[0]['msg']))
|
||||
assert expected == received
|
||||
|
||||
def test_successful_copy(self):
|
||||
''' Test successful create '''
|
||||
# data = self.mock_args()
|
||||
set_module_args(self.mock_args())
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_lun_copy_mock_object().apply()
|
||||
assert exc.value.args[0]['changed']
|
||||
|
||||
def test_copy_idempotency(self):
|
||||
''' Test create idempotency '''
|
||||
set_module_args(self.mock_args())
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_lun_copy_mock_object('destination_vserver').apply()
|
||||
assert not exc.value.args[0]['changed']
|
Loading…
Reference in a new issue