# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nicira Networks, 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.
# @author: Somik Behera, Nicira Networks, Inc.
# @author: Brad Hall, Nicira Networks, Inc.
# @author: Dan Wendlandt, Nicira Networks, Inc.
# @author: Dave Lapsley, Nicira Networks, Inc.
# @author: Aaron Rosen, Nicira Networks, Inc.
# @author: Bob Kukura, Red Hat, Inc.

import logging
import os

from quantum.api.v2 import attributes
from quantum.common import exceptions as q_exc
from quantum.common.utils import find_config_file
from quantum.db import api as db
from quantum.db import db_base_plugin_v2
from quantum.db import models_v2
from quantum.openstack.common import cfg
from quantum.plugins.openvswitch.common import config
from quantum.plugins.openvswitch import ovs_db_v2
from quantum import policy


LOG = logging.getLogger("ovs_quantum_plugin")


class OVSQuantumPluginV2(db_base_plugin_v2.QuantumDbPluginV2):
    """Implement the Quantum abstractions using Open vSwitch.

    Depending on whether tunneling is enabled, either a GRE tunnel or
    a new VLAN is created for each network. An agent is relied upon to
    perform the actual OVS configuration on each host.

    The provider extension is also supported. As discussed in
    https://bugs.launchpad.net/quantum/+bug/1023156, this class could
    be simplified, and filtering on extended attributes could be
    handled, by adding support for extended attributes to the
    QuantumDbPluginV2 base class. When that occurs, this class should
    be updated to take advantage of it.
    """

    supported_extension_aliases = ["provider"]

    def __init__(self, configfile=None):
        self.enable_tunneling = cfg.CONF.OVS.enable_tunneling
        options = {"sql_connection": cfg.CONF.DATABASE.sql_connection}
        options.update({'base': models_v2.model_base.BASEV2})
        sql_max_retries = cfg.CONF.DATABASE.sql_max_retries
        options.update({"sql_max_retries": sql_max_retries})
        reconnect_interval = cfg.CONF.DATABASE.reconnect_interval
        options.update({"reconnect_interval": reconnect_interval})
        db.configure_db(options)

        # update the vlan_id table based on current configuration
        ovs_db_v2.update_vlan_id_pool()

    # TODO(rkukura) Use core mechanism for attribute authorization
    # when available.

    def _check_provider_view_auth(self, context, network):
        return policy.check(context,
                            "extension:provider_network:view",
                            network)

    def _enforce_provider_set_auth(self, context, network):
        return policy.enforce(context,
                              "extension:provider_network:set",
                              network)

    def _extend_network_dict(self, context, network):
        if self._check_provider_view_auth(context, network):
            if not self.enable_tunneling:
                network['provider:vlan_id'] = ovs_db_v2.get_vlan(network['id'])

    def create_network(self, context, network):
        net = super(OVSQuantumPluginV2, self).create_network(context, network)
        try:
            vlan_id = network['network'].get('provider:vlan_id')
            if vlan_id not in (None, attributes.ATTR_NOT_SPECIFIED):
                self._enforce_provider_set_auth(context, net)
                ovs_db_v2.reserve_specific_vlan_id(vlan_id)
            else:
                vlan_id = ovs_db_v2.reserve_vlan_id()
        except Exception:
            super(OVSQuantumPluginV2, self).delete_network(context, net['id'])
            raise

        LOG.debug("Created network: %s" % net['id'])
        ovs_db_v2.add_vlan_binding(vlan_id, str(net['id']))
        self._extend_network_dict(context, net)
        return net

    def update_network(self, context, id, network):
        net = super(OVSQuantumPluginV2, self).update_network(context, id,
                                                             network)
        self._extend_network_dict(context, net)
        return net

    def delete_network(self, context, id):
        vlan_id = ovs_db_v2.get_vlan(id)
        result = super(OVSQuantumPluginV2, self).delete_network(context, id)
        ovs_db_v2.release_vlan_id(vlan_id)
        return result

    def get_network(self, context, id, fields=None, verbose=None):
        net = super(OVSQuantumPluginV2, self).get_network(context, id,
                                                          None, verbose)
        self._extend_network_dict(context, net)
        return self._fields(net, fields)

    def get_networks(self, context, filters=None, fields=None, verbose=None):
        nets = super(OVSQuantumPluginV2, self).get_networks(context, filters,
                                                            None, verbose)
        for net in nets:
            self._extend_network_dict(context, net)
        # TODO(rkukura): Filter on extended attributes.
        return [self._fields(net, fields) for net in nets]
