# Copyright (c) 2014 EMC Corporation.
# 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.

"""
EMC specific NAS storage driver. This driver is a pluggable driver
that allows specific EMC NAS devices to be plugged-in as the underlying
backend. Use the Manila configuration variable "share_backend_name"
to specify, which backend plugins to use.
"""

from oslo_config import cfg
from oslo_log import log

from manila.share import driver
from manila.share.drivers.emc import plugin_manager as manager

LOG = log.getLogger(__name__)

EMC_NAS_OPTS = [
    cfg.StrOpt('emc_nas_login',
               help='User name for the EMC server.'),
    cfg.StrOpt('emc_nas_password',
               help='Password for the EMC server.'),
    cfg.StrOpt('emc_nas_server',
               help='EMC server hostname or IP address.'),
    cfg.PortOpt('emc_nas_server_port',
                default=8080,
                help='Port number for the EMC server.'),
    cfg.BoolOpt('emc_nas_server_secure',
                default=True,
                help='Use secure connection to server.'),
    cfg.StrOpt('emc_share_backend',
               ignore_case=True,
               choices=['isilon', 'vnx', 'unity'],
               help='Share backend.'),
    cfg.StrOpt('emc_nas_server_container',
               help='Container of share servers.'),
    cfg.ListOpt('emc_nas_pool_names',
                deprecated_name='emc_nas_pool_name',
                help='EMC pool names.'),
    cfg.StrOpt('emc_nas_root_dir',
               help='The root directory where shares will be located.'),
    cfg.StrOpt('emc_nas_server_pool',
               help='Pool to persist the meta-data of NAS server.'),
    cfg.ListOpt('emc_interface_ports',
                help='Comma separated list specifying the ports that can be '
                     'used for share server interfaces. Members of the list '
                     'can be Unix-style glob expressions.'),
]

CONF = cfg.CONF
CONF.register_opts(EMC_NAS_OPTS)


class EMCShareDriver(driver.ShareDriver):
    """EMC specific NAS driver. Allows for NFS and CIFS NAS storage usage."""

    def __init__(self, *args, **kwargs):
        self.configuration = kwargs.get('configuration', None)
        if self.configuration:
            self.configuration.append_config_values(EMC_NAS_OPTS)
            self.backend_name = self.configuration.safe_get(
                'emc_share_backend')
        else:
            self.backend_name = CONF.emc_share_backend
        self.backend_name = self.backend_name or 'EMC_NAS_Storage'
        self.plugin_manager = manager.EMCPluginManager(
            namespace='manila.share.drivers.emc.plugins')
        self.plugin = self.plugin_manager.load_plugin(self.backend_name, LOG)
        super(EMCShareDriver, self).__init__(
            self.plugin.driver_handles_share_servers, *args, **kwargs)

    def create_share(self, context, share, share_server=None):
        """Is called to create share."""
        location = self.plugin.create_share(context, share, share_server)

        return location

    def create_share_from_snapshot(self, context, share, snapshot,
                                   share_server=None):
        """Is called to create share from snapshot."""
        location = self.plugin.create_share_from_snapshot(
            context, share, snapshot, share_server)

        return location

    def extend_share(self, share, new_size, share_server=None):
        """Is called to extend share."""
        self.plugin.extend_share(share, new_size, share_server)

    def create_snapshot(self, context, snapshot, share_server=None):
        """Is called to create snapshot."""
        self.plugin.create_snapshot(context, snapshot, share_server)

    def delete_share(self, context, share, share_server=None):
        """Is called to remove share."""
        self.plugin.delete_share(context, share, share_server)

    def delete_snapshot(self, context, snapshot, share_server=None):
        """Is called to remove snapshot."""
        self.plugin.delete_snapshot(context, snapshot, share_server)

    def ensure_share(self, context, share, share_server=None):
        """Invoked to sure that share is exported."""
        self.plugin.ensure_share(context, share, share_server)

    def allow_access(self, context, share, access, share_server=None):
        """Allow access to the share."""
        self.plugin.allow_access(context, share, access, share_server)

    def deny_access(self, context, share, access, share_server=None):
        """Deny access to the share."""
        self.plugin.deny_access(context, share, access, share_server)

    def check_for_setup_error(self):
        """Check for setup error."""
        self.plugin.check_for_setup_error()

    def do_setup(self, context):
        """Any initialization the share driver does while starting."""
        self.plugin.connect(self, context)

    def _update_share_stats(self):
        """Retrieve stats info from share."""

        backend_name = self.configuration.safe_get(
            'share_backend_name') or "EMC_NAS_Storage"
        data = dict(
            share_backend_name=backend_name,
            vendor_name='EMC',
            storage_protocol='NFS_CIFS')
        self.plugin.update_share_stats(data)
        super(EMCShareDriver, self)._update_share_stats(data)

    def get_network_allocations_number(self):
        """Returns number of network allocations for creating VIFs."""
        return self.plugin.get_network_allocations_number()

    def _setup_server(self, network_info, metadata=None):
        """Set up and configures share server with given network parameters."""
        return self.plugin.setup_server(network_info, metadata)

    def _teardown_server(self, server_details, security_services=None):
        """Teardown share server."""
        return self.plugin.teardown_server(server_details, security_services)
