# Copyright 2016 Hewlett Packard Enterprise Development, LP
#
# 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 copy

from keystoneauth1 import loading as ks_loading
import netaddr
from neutron_lib.api.definitions import ip_allocation as ipalloc_apidef
from neutron_lib.api.definitions import l2_adjacency as l2adj_apidef
from neutron_lib.api.definitions import network as net_def
from neutron_lib.api.definitions import port as port_def
from neutron_lib.api.definitions import subnet as subnet_def
from neutron_lib.api import validators
from neutron_lib.callbacks import events
from neutron_lib.callbacks import registry
from neutron_lib.callbacks import resources
from neutron_lib import constants
from neutron_lib.exceptions import placement as placement_exc
from neutron_lib.plugins import directory
from novaclient import client as nova_client
from novaclient import exceptions as nova_exc
from oslo_config import cfg
from oslo_log import log
from oslo_utils import excutils

from neutron._i18n import _
from neutron.db import _resource_extend as resource_extend
from neutron.extensions import segment
from neutron.notifiers import batch_notifier
from neutron.objects import network as net_obj
from neutron.objects import subnet as subnet_obj
from neutron.services.segments import db
from neutron.services.segments import exceptions
from neutron.services.segments import placement_client

LOG = log.getLogger(__name__)

NOVA_API_VERSION = '2.41'
IPV4_RESOURCE_CLASS = 'IPV4_ADDRESS'
SEGMENT_NAME_STUB = 'Neutron segment id %s'
MAX_INVENTORY_UPDATE_RETRIES = 10


@resource_extend.has_resource_extenders
@registry.has_registry_receivers
class Plugin(db.SegmentDbMixin, segment.SegmentPluginBase):

    _instance = None

    supported_extension_aliases = ["segment", "ip_allocation",
                                   l2adj_apidef.ALIAS,
                                   "standard-at
tr-segment",
                                   "subnet-segmentid-writable",
                                   'segments-peer-subnet-host-routes']

    __native_pagination_support = True
    __native_sorting_support = True
    __filter_validation_support = True

    def __init__(self):
        self.nova_updater = NovaSegmentNotifier()
        self.segment_host_routes = SegmentHostRoutes()

    @staticmethod
    @resource_extend.extends([net_def.COLLECTION_NAME])
   
 def _extend_network_dict_binding(network_res, network_db):
        if not directory.get_plugin('segments'):
            return

        # TODO(carl_baldwin) Make this work with service subnets when
        #                    it's a thing.
        is_adjacent = (not network_db.subnets or
                       not network_db.subnets[0].segment_id)
        network_res[l2adj_apidef.L2_ADJACENCY] = is_adjacent

    @staticmethod
    @resource_extend.extends([subnet_def.COLLECTION_NAME])
    def _extend_subnet_dict_binding(subnet_res, subnet_db):
        subnet_res['segment_id'] = subnet_db.get('segment_id')

    @staticmethod
    @resource_extend.extends([port_def.COLLECTION_NAME])
    def _extend_port_dict_binding(port_res, port_db):
        if not directory.get_plugin('segments'):
            return

        value = ipalloc_apidef.IP_ALLOCATION_IMMEDIATE
        if port_db.get('ip_allocation'):
            value = port_db.get('ip_allocation')
        port_res[ipalloc_apidef.IP_ALLOCATION] = value

    @classmethod
    def get_instance(cls):
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    @registry.receives(resources.SEGMENT, [events.BEFORE_DELETE])
    def _prevent_segment_delete_with_subnet_associated(
            self, resource, event, trigger, context, segment,
            for_net_delete=False):
        """Raise exception if there are any subnets associated with segment."""
        if for_net_delete:
            # don't check if this is a part of a network delete operation
            return
        segment_id = segment['id']
        subnets = subnet_obj.Subnet.get_objects(context,
                                                segment_id=segment_id)
        subnet_ids = [s.id for s in subnets]

        if subnet_ids:
            reason = _("The segment is still associated with subnet(s) "
                       "%s") % ", ".join(subnet_ids)
            raise exceptions.SegmentInUse(segment_id=segment_id,
                                          reason=reason)


class Event(object):

    def __init__(self, method, segment_ids, total=None, reserved=None,
                 segment_host_mappings=None, host=None):
        self.method = method
        if isinstance(segment_ids, set):
            self.segment_ids = segment_ids
        else:
            self.segment_id = segment_ids
        self.total = total
        self.reserved = reserved
        self.segment_host_mappings = segment_host_mappings
        self.host = host


@registry.has_registry_receivers
class NovaSegmentNotifier(object):

    def __init__(self):
        self.p_client, self.n_client = self._get_clients()
        self.batch_notifier = batch_notifier.BatchNotifier(
            cfg.CONF.send_events_interval, self._send_notifications)

    def _get_clients(self):
        p_client = placement_client.PlacementAPIClient()

        n_auth = ks_loading.load_auth_from_conf_options(cfg.CONF, 'nova')
        n_session = ks_loading.load_session_from_conf_options(
            cfg.CONF,
            'nova',
            auth=n_auth)
        extensions = [
            ext for ext in nova_client.discover_extensions(NOVA_API_VERSION)
            if ext.name == "server_external_events"]
        n_client = nova_client.Client(
            NOVA_API_VERSION,
            session=n_session,
            region_name=cfg.CONF.nova.region_name,
            endpoint_type=cfg.CONF.nova.endpoint_type,
            extensions=extensions)

        return p_client, n_client

    def _send_notifications(self, batched_events):
        for event in batched_events:
            try:
                event.method(event)
            except placement_exc.PlacementEndpointNotFound:
                LOG.debug('Placement API was not found when trying to '
                          'update routed networks IPv4 inventories')
                return

    def _notify_subnet(self, context, subnet, segment_id):
        total, reserved = self._calculate_inventory_total_and_reserved(subnet)
        if total:
            segment_host_mappings = net_obj.SegmentHostMapping.get_objects(
                context, segment_id=segment_id)
            self.batch_notifier.queue_event(Event(
                self._create_or_update_nova_inventory, segment_id, total=total,
                reserved=reserved,
                segment_host_mappings=segment_host_mappings))

    @registry.receives(resources.SUBNET, [events.AFTER_CREATE])
    def _notify_subnet_created(self, resource, event, trigger, context,
                               subnet, **kwargs):
        segment_id = subnet.get('segment_id')
        if not segment_id or subnet['ip_version'] != constants.IP_VERSION_4:
            return
        self._notify_subnet(context, subnet, segment_id)

    def _create_or_update_nova_inventory(self, event):
        try:
            self._update_nova_inventory(event)
        except placement_exc.PlacementResourceProviderNotFound:
            self._create_nova_inventory(event.segment_id, event.total,
                                        event.reserved,
                                        event.segment_host_mappings)

    def _update_nova_inventory(self, event):
        for count in range(MAX_INVENTORY_UPDATE_RETRIES):
 