# Copyright (c) 2015 OpenStack Foundation
#
#    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 lib_constants
from oslo_log import log as logging

from neutron.agent.l3 import dvr_local_router
from neutron.agent.l3 import dvr_snat_ns
from neutron.agent.l3 import router_info as router
from neutron.agent.linux import ip_lib
from neutron.agent.linux import iptables_manager

LOG = logging.getLogger(__name__)


class DvrEdgeRouter(dvr_local_router.DvrLocalRouter):

    def __init__(self, host, *args, **kwargs):
        super(DvrEdgeRouter, self).__init__(host, *args, **kwargs)
        self.snat_namespace = dvr_snat_ns.SnatNamespace(
            self.router_id, self.agent_conf, self.driver, self.use_ipv6)
        self.snat_iptables_manager = None

    def get_gw_ns_name(self):
        return self.snat_namespace.name

    def external_gateway_added(self, ex_gw_port, interface_name):
        super(DvrEdgeRouter, self).external_gateway_added(
            ex_gw_port, interface_name)
        if self._is_this_snat_host():
            self._create_dvr_gateway(ex_gw_port, interface_name)
            # NOTE: When a router is created without a gateway the routes get
            # added to the router namespace, but if we wanted to populate
            # the same routes to the snat namespace after the gateway port
            # is added, we need to call routes_updated here.
            self.routes_updated([], self.router['routes'])
        elif self.snat_namespace.exists():
            # This is the case where the snat was moved manually or
            # rescheduled to a different agent when the agent was dead.
            LOG.debug("SNAT was moved or rescheduled to a different host "
                      "and does not match with the current host. This is "
                      "a stale namespace %s and will be cleared from the "
                      "current dvr_snat host.", self.snat_namespace.name)
            self.external_gateway_removed(ex_gw_port, interface_name)

    def external_gateway_updated(self, ex_gw_port, interface_name):
        if not self._is_this_snat_host():
            # no centralized SNAT gateway for this node/agent
            LOG.debug("not hosting snat for router: %s", self.router['id'])
            if self.snat_namespace.exists():
                LOG.debug("SNAT was rescheduled to host %s. Clearing snat "
                          "namespace.", self.router.get('gw_port_host'))
                return self.external_gateway_removed(
                    ex_gw_port, interface_name)
            return

        if not self.snat_namespace.exists():
            # SNAT might be rescheduled to this agent; need to process like
            # newly created gateway
            return self.external_gateway_added(ex_gw_port, interface_name)
        else:
            self._external_gateway_added(ex_gw_port,
                                        interface_name,
                                        self.snat_namespace.name,
                                        preserve_ips=[])

    def _external_gateway_removed(self, ex_gw_port, interface_name):
        super(DvrEdgeRouter, self).external_gateway_removed(ex_gw_port,
                                                            interface_name)
        if not self._is_this_snat_host() and not self.snat_namespace.exists():
            # no centralized SNAT gateway for this node/agent
            LOG.debug("not hosting snat for router: %s", self.router['id'])
            return

        self.driver.unplug(interface_name,
                           bridge=self.agent_conf.external_network_bridge,
                           namespace=self.snat_namespace.name,
                           prefix=router.EXTERNAL_DEV_PREFIX)

    def external_gateway_removed(self, ex_gw_port, interface_name):