#
# Copyright 2015 Nexenta Systems, Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
"""
Unit tests for OpenStack Cinder volume driver
"""

import mock
from oslo_utils import units

from cinder import context
from cinder import db
from cinder import exception
from cinder import test
from cinder.volume import configuration as conf
from cinder.volume.drivers.nexenta import iscsi
from cinder.volume.drivers.nexenta import jsonrpc
from cinder.volume.drivers.nexenta import nfs
from cinder.volume.drivers.nexenta import utils


class TestNexentaISCSIDriver(test.TestCase):
    TEST_VOLUME_NAME = 'volume1'
    TEST_VOLUME_NAME2 = 'volume2'
    TEST_SNAPSHOT_NAME = 'snapshot1'
    TEST_VOLUME_REF = {
        'name': TEST_VOLUME_NAME,
        'size': 1,
        'id': '1',
        'status': 'available'
    }
    TEST_VOLUME_REF2 = {
        'name': TEST_VOLUME_NAME2,
        'size': 1,
        'id': '2',
        'status': 'in-use'
    }
    TEST_SNAPSHOT_REF = {
        'name': TEST_SNAPSHOT_NAME,
        'volume_name': TEST_VOLUME_NAME,
    }

    def __init__(self, method):
        super(TestNexentaISCSIDriver, self).__init__(method)

    def setUp(self):
        super(TestNexentaISCSIDriver, self).setUp()
        self.cfg = mock.Mock(spec=conf.Configuration)
        self.ctxt = context.get_admin_context()
        self.cfg.nexenta_dataset_description = ''
        self.cfg.nexenta_host = '1.1.1.1'
        self.cfg.nexenta_user = 'admin'
        self.cfg.nexenta_password = 'nexenta'
        self.cfg.nexenta_volume = 'cinder'
        self.cfg.nexenta_rest_port = 2000
        self.cfg.nexenta_rest_protocol = 'http'
        self.cfg.nexenta_iscsi_target_portal_port = 3260
        self.cfg.nexenta_target_prefix = 'iqn:'
        self.cfg.nexenta_target_group_prefix = 'cinder/'
        self.cfg.nexenta_blocksize = '8K'
        self.cfg.nexenta_sparse = True
        self.cfg.nexenta_dataset_compression = 'on'
        self.cfg.nexenta_dataset_dedup = 'off'
        self.cfg.nexenta_rrmgr_compression = 1
        self.cfg.nexenta_rrmgr_tcp_buf_size = 1024
        self.cfg.nexenta_rrmgr_connections = 2
        self.cfg.reserved_percentage = 20
        self.nms_mock = mock.Mock()
        for mod in ['volume', 'zvol', 'iscsitarget', 'appliance',
                    'stmf', 'scsidisk', 'snapshot']:
            setattr(self.nms_mock, mod, mock.Mock())
        self.stubs.Set(jsonrpc, 'NexentaJSONProxy',
                       lambda *_, **__: self.nms_mock)
        self.drv = iscsi.NexentaISCSIDriver(
            configuration=self.cfg)
        self.drv.db = db
        self.drv.do_setup(self.ctxt)

    def test_check_do_setup(self):
        self.assertEqual('http', self.drv.nms_protocol)

    def test_check_for_setup_error(self):
        self.nms_mock.volume.object_exists.return_value = False
        self.assertRaises(LookupError, self.drv.check_for_setup_error)

    def test_local_path(self):
        self.assertRaises(NotImplementedError, self.drv.local_path, '')

    def test_create_volume(self):
        self.drv.create_volume(self.TEST_VOLUME_REF)
        self.nms_mock.zvol.create.assert_called_with(
            'cinder/%s' % self.TEST_VOLUME_REF['name'], '1G',
            self.cfg.nexenta_blocksize, self.cfg.nexenta_sparse)

    def test_delete_volume(self):
        self.nms_mock.zvol.get_child_props.return_value = (
            {'origin': 'cinder/volume0@snapshot'})
        self.drv.delete_volume(self.TEST_VOLUME_REF)
        self.nms_mock.zvol.get_child_props.assert_called_with(
            'cinder/volume1', 'origin')
        self.nms_mock.zvol.destroy.assert_called_with(
            'cinder/volume1', '')

        self.nms_mock.zvol.get_child_props.assert_called_with(
            'cinder/volume1', 'origin')
        self.nms_mock.zvol.destroy.assert_called_with('cinder/volume1', '')
        self.drv.delete_volume(self.TEST_VOLUME_REF)

        self.nms_mock.zvol.get_child_props.assert_called_with(
            'cinder/volume1', 'origin')
        self.nms_mock.zvol.get_child_props.return_value = (
            {'origin': 'cinder/volume0@cinder-clone-snapshot-1'})
        self.nms_mock.zvol.destroy.assert_called_with('cinder/volume1', '')

        self.drv.delete_volume(self.TEST_VOLUME_REF)
        self.nms_mock.snapshot.destroy.assert_called_with(
            'cinder/volume0@cinder-clone-snapshot-1', '')
        self.nms_mock.volume.object_exists.assert_called_with('cinder/volume0')

    def test_create_cloned_volume(self):
        vol = self.TEST_VOLUME_REF2
        src_vref = self.TEST_VOLUME_REF
        snapshot = {
            'volume_name': src_vref['name'],
            'name': 'cinder-clone-snapshot-%s' % vol['id'],
        }
        self.drv.create_cloned_volume(vol, src_vref)
        self.nms_mock.zvol.create_snapshot.assert_called_with(
            'cinder/%s' % src_vref['name'], snapshot['name'], '')
        self.nms_mock.zvol.clone.assert_called_with(
            'cinder/%s@%s' % (src_vref['name'], snapshot['name']),
            'cinder/%s' % vol['name'])

    def test_migrate_volume(self):
        volume = self.TEST_VOLUME_REF
        host = {
            'capabilities': {
                'vendor_name': 'Nexenta',
                'location_info': 'NexentaISCSIDriver:1.1.1.1:cinder',
                'free_capacity_gb': 1,
                'iscsi_target_portal_port': 3260,
                'nms_url': 'http://admin:password@1.1.1.1:2000'
            }
        }
        snapshot = {
            'volume_name': volume['name'],
            'name': 'cinder-migrate-snapshot-%s' % volume['id'],
        }
        volume_name = 'cinder/%s' % volume['name']

        self.nms_mock.appliance.ssh_list_bindings.return_value = (
            {'0': [True, True, True, '1.1.1.1']})
        self.nms_mock.zvol.get_child_props.return_value = None

        self.drv.migrate_volume(None, volume, host)
        self.nms_mock.zvol.create_snapshot.assert_called_with(
            'cinder/%s' % volume['name'], snapshot['name'], '')

        src = '%(volume)s/%(zvol)s@%(snapshot)s' % {
            'volume': 'cinder',
            'zvol': volume['name'],
            'snapshot': snapshot['name']
        }
        dst = '1.1.1.1:cinder'
        cmd = ' '.join(['rrmgr -s zfs -c 1 -q -e -w 1024 -n 2', src, dst])

        self.nms_mock.appliance.execute.assert_called_with(cmd)

        snapshot_name = 'cinder/%(volume)s@%(snapshot)s' % {
            'volume': volume['name'],
            'snapshot': snapshot['name']
        }
        self.nms_mock.snapshot.destroy.assert_called_with(snapshot_name, '')
        self.nms_mock.zvol.destroy.assert_called_with(volume_name, '')
        self.nms_mock.snapshot.destroy.assert_called_with(
            'cinder/%(volume)s@%(snapshot)s' % {
                'volume': volume['name'],
                'snapshot': snapshot['name']
            }, '')
        self.nms_mock.volume.object_exists.assert_called_with(volume_name)
        self.mox.ReplayAll()

    def test_create_snapshot(self):
        self.drv.create_snapshot(self.TEST_SNAPSHOT_REF)
        self.nms_mock.zvol.create_snapshot.assert_called_with(
            'cinder/volume1', 'snapshot1', '')

    def test_create_volume_from_snapshot(self):
        self.drv.create_volume_from_snapshot(self.TEST_VOLUME_REF2,