#    (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
#    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.

from neutron_lib import constants as n_const
from oslo_log import log as logging
from sqlalchemy import or_

from neutron.callbacks import events
from neutron.callbacks import registry
from neutron.callbacks import resources
from neutron.common import constants as const
from neutron.common import utils as n_utils

from neutron.db import agentschedulers_db
from neutron.db import l3_agentschedulers_db as l3agent_sch_db
from neutron.db import models_v2
from neutron.extensions import portbindings
from neutron import manager
from neutron.plugins.common import constants as service_constants
from neutron.plugins.ml2 import db as ml2_db
from neutron.plugins.ml2 import models as ml2_models

LOG = logging.getLogger(__name__)


class L3_DVRsch_db_mixin(l3agent_sch_db.L3AgentSchedulerDbMixin):
    """Mixin class for L3 DVR scheduler.

    DVR currently supports the following use cases:

     - East/West (E/W) traffic between VMs: this is handled in a
       distributed manner across Compute Nodes without a centralized element.
       This includes E/W traffic between VMs on the same Compute Node.
     - North/South traffic for Floating IPs (FIP N/S): this is supported on the
       distributed routers on Compute Nodes without any centralized element.
     - North/South traffic for SNAT (SNAT N/S): this is supported via a
       centralized element that handles the SNAT traffic.

    To support these use cases,  DVR routers rely on an L3 agent that runs on a
    central node (also known as Network Node or Service Node),  as well as, L3
    agents that run individually on each Compute Node of an OpenStack cloud.

    Each L3 agent creates namespaces to route traffic according to the use
    cases outlined above.  The mechanism adopted for creating and managing
    these namespaces is via (Router,  Agent) binding and Scheduling in general.

    The main difference between distributed routers and centralized ones is
    that in the distributed case,  multiple bindings will exist,  one for each
    of the agents participating in the routed topology for the specific router.

    These bindings are created in the following circumstances:

    - A subnet is added to a router via router-interface-add, and that subnet
      has running VM's deployed in it.  A binding will be created between the
      router and any L3 agent whose Compute Node is hosting the VM(s).
    - An external gateway is set to a router via router-gateway-set.  A binding
      will be created between the router and the L3 agent running centrally
      on the Network Node.

    Therefore,  any time a router operation occurs (create, update or delete),
    scheduling will determine whether the router needs to be associated to an
    L3 agent, just like a regular centralized router, with the difference that,
    in the distributed case,  the bindings required are established based on
    the state of the router and the Compute Nodes.
    """

    def dvr_handle_new_service_port(self, context, port, dest_host=None):
        """Handle new dvr service port creation.

        When a new dvr service port is created, this function will
        schedule a dvr router to new compute node if needed and notify
        l3 agent on that node.
        The 'dest_host' will provide the destinaton host of the port in
        case of service port migration.
        """
        port_host = dest_host or port[portbindings.HOST_ID]
        l3_agent_on_host = (self.get_l3_agents(
            context, filters={'host': [port_host]}) or [None])[0]
        if not l3_agent_on_host:
            return

        if dest_host:
            # Make sure we create the floatingip agent gateway port
            # for the destination node if fip is associated with this
            # fixed port
            l3plugin = manager.NeutronManager.get_service_plugins().get(
                service_constants.L3_ROUTER_NAT)
            (
                l3plugin.
                check_for_fip_and_create_agent_gw_port_on_host_if_not_exists(
                    context, port, dest_host))

        subnet_ids = [ip['subnet_id'] for ip in port['fixed_ips']]
        router_ids = self.get_dvr_routers_by_subnet_ids(context, subnet_ids)
        if router_ids:
            LOG.debug('DVR: Handle new service port, host %(host)s, '
                      'router ids %(router_ids)s',
                {'host': port_host, 'router_ids': router_ids})
            self.l3_rpc_notifier.routers_updated_on_host(
                context, router_ids, port_host)

    def get_dvr_routers_by_subnet_ids(self, context, subnet_ids):
        """Gets the dvr routers on vmport subnets."""
        if not subnet_ids:
            return set()

        router_ids = set()
        filter_sub = {'fixed_ips': {'subnet_id': subnet_ids},
                      'device_owner':
                      [n_const.DEVICE_OWNER_DVR_INTERFACE]}
        subnet_ports = self._core_plugin.get_ports(
            context, filters=filter_sub)
        for subnet_port in subnet_ports:
            router_ids.add(subnet_port['device_id'])
        return router_ids

    def get_subnet_ids_on_router(self, context, router_id):
        """Return subnet IDs for interfaces attached to the given router."""
        subnet_ids = set()
        filter_rtr = {'device_id': [router_id]}
        int_ports = self._core_plugin.get_ports(context, filters=filter_rtr)
        for int_port in int_ports:
            int_ips = int_port['fixed_ips']
            if int_ips:
                int_subnet = int_ips[0]['subnet_id']
                subnet_ids.add(int_subnet)
            else:
                LOG.debug('DVR: Could not find a subnet id '