# Copyright 2013 Nicira, 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.

import sys

from neutronclient.common import exceptions as n_exc
from neutronclient.neutron import v2_0 as neutronv20
from oslo.config import cfg
import six
from webob import exc

from nova.compute import api as compute_api
from nova import exception
from nova.network import neutronv2
from nova.network.security_group import security_group_base
from nova.objects import security_group
from nova.openstack.common import excutils
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
from nova.openstack.common import uuidutils
from nova import utils


CONF = cfg.CONF
LOG = logging.getLogger(__name__)

# NOTE: Neutron client has a max URL length of 8192, so we have
# to limit the number of IDs we include in any single search.  Really
# doesn't seem to be any point in making this a config value.
MAX_SEARCH_IDS = 150


class SecurityGroupAPI(security_group_base.SecurityGroupBase):

    id_is_uuid = True

    def create_security_group(self, context, name, description):
        neutron = neutronv2.get_client(context)
        body = self._make_neutron_security_group_dict(name, description)
        try:
            security_group = neutron.create_security_group(
                body).get('security_group')
        except n_exc.NeutronClientException as e:
            exc_info = sys.exc_info()
            LOG.exception(_("Neutron Error creating security group %s"),
                          name)
            if e.status_code == 401:
                # TODO(arosen) Cannot raise generic response from neutron here
                # as this error code could be related to bad input or over
                # quota
                raise exc.HTTPBadRequest()
            elif e.status_code == 409:
                self.raise_over_quota(unicode(e))
            raise exc_info[0], exc_info[1], exc_info[2]
        return self._convert_to_nova_security_group_format(security_group)

    def update_security_group(self, context, security_group,
                              name, description):
        neutron = neutronv2.get_client(context)
        body = self._make_neutron_security_group_dict(name, description)
        try:
            security_group = neutron.update_security_group(
                security_group['id'], body).get('security_group')
        except n_exc.NeutronClientException as e:
            exc_info = sys.exc_info()
            LOG.exception(_("Neutron Error updating security group %s"),
                          name)
            if e.status_code == 401:
                # TODO(arosen) Cannot raise generic response from neutron here
                # as this error code could be related to bad input or over
                # quota
                raise exc.HTTPBadRequest()
            raise exc_info[0], exc_info[1], exc_info[2]
        return self._convert_to_nova_security_group_format(security_group)

    def _convert_to_nova_security_group_format(self, security_group):
        nova_group = {}
        nova_group['id'] = security_group['id']
        nova_group['description'] = security_group['description']
        nova_group['name'] = security_group['name']
        nova_group['project_id'] = security_group['tenant_id']
        nova_group['rules'] = []
        for rule in security_group.get('security_group_rules', []):
            if rule['direction'] == 'ingress':
                nova_group['rules'].append(
                    self._convert_to_nova_security_group_rule_format(rule))

        return nova_group

    def _convert_to_nova_security_group_rule_format(self, rule):
        nova_rule = {}
        nova_rule['id'] = rule['id']
        nova_rule['parent_group_id'] = rule['security_group_id']
        nova_rule['protocol'] = rule['protocol']
        if (nova_rule['protocol'] and rule.get('port_range_min') is None and
                rule.get('port_range_max') is None):
            if rule['protocol'].upper() in ['TCP', 'UDP']:
                nova_rule['from_port'] = 1
                nova_rule['to_port'] = 65535
            else:
                nova_rule['from_port'] = -1
                nova_rule['to_port'] = -1
        else:
            nova_rule['from_port'] = rule.get('port_range_min')
            nova_rule['to_port'] = rule.get('port_range_max')
        nova_rule['group_id'] = rule['remote_group_id']
        nova_rule['cidr'] = self.parse_cidr(rule.get('remote_ip_prefix'))
        return nova_rule

    def get(self, context, name=None, id=None, map_exception=False):
        neutron = neutronv2.get_client(context)
        try:
            if not id and name:
                id = neutronv20.find_resourceid_by_name_or_id(
                    neutron, 'security_group', name)
            group = neutron.show_security_group(id).get('security_group')
        except n_exc.NeutronClientNoUniqueMatch as e:
            raise exception.NoUniqueMatch(six.text_type(e))
        except n_exc.NeutronClientException as e:
            exc_info = sys.exc_info()
            if e.status_code == 404:
                LOG.debug("Neutron security group %s not found", name)
                self.raise_not_found(unicode(e))
            else:
                LOG.error(_("Neutron Error: %s"), e)
                raise exc_info[0], exc_info[1], exc_info[2]

        return self._convert_to_nova_security_group_format(group)

    def list(self, context, names=None, ids=None, project=None,
             search_opts=None):
        """Returns list of security group rules owned by tenant."""
        neutron = neutronv2.get_client(context)
        search_opts = {}
        if names:
            search_opts['name'] = names
        if ids:
            search_opts['id'] = ids
        if project:
            search_opts['tenant_id'] = project
        try:
            security_groups = neutron.list_security_groups(**search_opts).get(
                'security_groups')
        except n_exc.NeutronClientException:
            with excutils.save_and_reraise_exception():
                LOG.exception(_("Neutron Error getting security groups"))
        converted_rules = []
        for security_group in security_groups:
            converted_rules.append(
                self._convert_to_nova_security_group_format(security_group))
        return converted_rules

    def validate_id(self, id):
        if not uuidutils.is_uuid_like(id):
            msg = _("Security group id should be uuid")
            self.raise_invalid_property(msg)
        return id

    def destroy(self, context, security_group):
        """This function deletes a security group."""

        neutron = neutronv2.get_client(context)
        try:
            neutron.delete_security_group(security_group['id'])
        except n_exc.NeutronClientException as e:
            exc_info = sys.exc_info()
            if e.status_code == 404:
                self.raise_not_found(unicode(e))
            elif e.status_code == 409:
                self.raise_invalid_property(unicode(e))
            else:
                LOG.error(_("Neutron Error: %s"), e)
                raise exc_info[0], exc_info[1], exc_info[2]

    def add_rules(self, context, id, name, vals):
        """Add security group rule(s) to security group.

        Note: the Nova security group API doesn't support adding multiple
        security group rules at once but the EC2 one does. Therefore,
        this function is written to support both. Multiple rules are
        installed to a security group in neutron using bulk support.
        """

        neutron = neutronv2.get_client(context)
        body = self._make_neutron_security_group_rules_list(vals)
        try:
            rules = neutron.create_security_group_rule(
                body).get('security_group_rules')
        except n_exc.NeutronClientException as e:
            exc_info = sys.exc_info()