<commit_before># Copyright 2016 NOKIA
#
#    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 inspect
import netaddr

from oslo_log import log as logging

from neutron._i18n import _
from neutron.services.trunk import constants as t_consts
from neutron_lib.api.definitions import portbindings
from neutron_lib import constants as os_constants
from neutron_lib import context as neutron_context
from neutron_lib.plugins.ml2 import api

from nuage_neutron.plugins.common import base_plugin
from nuage_neutron.plugins.common import constants as nuage_const
from nuage_neutron.plugins.common import exceptions
from nuage_neutron.plugins.common import net_topology_db as ext_db
from nuage_neutron.plugins.common import nuagedb
from nuage_neutron.plugins.common import trunk_db
from nuage_neutron.plugins.common import utils
from nuage_neutron.plugins.common.utils import handle_nuage_api_errorcode
from nuage_neutron.plugins.common.utils import ignore_no_update
from nuage_neutron.plugins.common.utils import ignore_not_found
from nuage_neutron.plugins.sriov import trunk_driver


LOG = logging.getLogger(__name__)


class NuageSriovMechanismDriver(base_plugin.RootNuagePlugin,
                                api.MechanismDriver):
    """Ml2 Mechanism driver interface

    for provisioning sriov instances.
    """

    def initialize(self):
        LOG.debug('Initializing driver')
        self.init_vsd_client()
        self._wrap_vsdclient()
        self.trunk_driver = trunk_driver.NuageTrunkDriver.create(self)
        self.vif_details = {portbindings.CAP_PORT_FILTER: True}
        LOG.debug('Initializing complete')

    def _wrap_vsdclient(self):
        """Wraps nuagecient methods with try-except to ignore certain errors.

        When updating an entity on the VSD and there is nothing to actually
        update because the values don't change, VSD will throw an error. This
        is not needed for neutron so all these exceptions are ignored.

        When VSD responds with a 404, this is sometimes good (for example when
        trying to update an entity). Yet sometimes this is not required to be
        an actual exception. When deleting an entity that does no longer exist
        it is fine for neutron. Also when trying to retrieve something from VSD
        having None returned is easier to work with than RESTProxy exceptions.
        """

        methods = inspect.getmembers(self.vsdclient,
                                     lambda x: inspect.ismethod(x))
        for m in methods:
            wrapped = ignore_no_update(m[1])
            if m[0].startswith('get_') or m[0].startswith('delete_'):
                wrapped = ignore_not_found(wrapped)
            setattr(self.vsdclient, m[0], wrapped)

    @utils.context_log
    def create_network_precommit(self, context):
        db_context = context._plugin_context
        segments = context.current.get('segments')
        if segments:
            bad_segment = next(
                (segment for segment in segments if
                 segment.get('provider:network_type') == t_consts.VLAN and
                 trunk_db.vlan_in_use_by_subport(db_context.session,
                                                 segment)), None)
            if bad_segment:
                raise exceptions.VlanIdInUseBySubport(
                    vlan=bad_segment['provider:segmentation_id'],
                    physnet=bad_segment['provider:physical_network']
                )

    @utils.context_log
    def create_port_precommit(self, context):
        port = context.current
        vnic_type = port.get(portbindings.VNIC_TYPE, "")
        db_context = context._plugin_context
        if vnic_type not in self._supported_vnic_types():
            return
        self._validate_port_request_attributes(context.current)
        subnets = self.core_plugin._get_subnets_by_network(
            db_context,
            port.get('network_id'))
        if len(subnets) != 1:
            if ((len(subnets) != 2 or
                 subnets[0]['ip_version'] ==
                 subnets[1]['ip_version'])):
                raise exceptions.DirectPortSubnetConflict()

    @utils.context_log
    def update_port_precommit(self, context):
        """update_port_precommit."""
        port = context.current
        original = context.original
        if (port.get(portbindings.VNIC_TYPE, "")
                in self._supported_vnic_types()):
            self._validate_port_request_attributes(port, original=original)

    @handle_nuage_api_errorcode
    @utils.context_log
    def update_port_postcommit(self, context):
        """update_port_postcommit."""
        port = context.current
        original = context.original
        if (port.get(portbindings.VNIC_TYPE, "")
                in self._supported_vnic_types()):
            host_added = host_removed = False
            if not original['binding:host_id'] and port['binding:host_id']:
                host_added = True
            elif original['binding:host_id'] and not port['binding:host_id']:
                host_removed = True

            if host_removed:
                self._delete_port(port)
            if host_added:
                port_dict = self._make_port_dict(context)
                if port_dict:
                    self._update_port(port_dict)

    @utils.context_log
    def delete_port_postcommit(self, context):
        """delete_port_postcommit."""
        if (context.current.get(portbindings.VNIC_TYPE, "")
                in self._supported_vnic_types()):
            try:
                self._delete_port(context.current)
            except Exception as e:
                LOG.error("Failed to delete vport from vsd {port id: %s}",
                          context.current['id'])
                raise e

    @utils.context_log
    def bind_port(self, context):
        """bind_port."""
        if context.binding_levels:
            return  # we've already got a top binding

        subnet_mapping = self._validate_port(context._plugin_context,
                                             context.current)
        if not subnet_mapping:
            return

        port_id = context.current['id']
        for segment in context.segments_to_bind:
            if self._check_segment(segment, context):
                if not self._can_bind(context):
                    return<commit_msg>Revert "Move tor port mgmt to postcommit on delete port"<commit_after># Copyright 2016 NOKIA
#
#    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 inspect
import netaddr

from oslo_log import log as logging

from neutron._i18n import _
from neutron.services.trunk import constants as t_consts
from neutron_lib.api.definitions import portbindings
from neutron_lib import constants as os_constants
from neutron_lib import context as neutron_context
from neutron_lib.plugins.ml2 import api

from nuage_neutron.plugins.common import base_plugin
from nuage_neutron.plugins.common import constants as nuage_const
from nuage_neutron.plugins.common import exceptions
from nuage_neutron.plugins.common import net_topology_db as ext_db
from nuage_neutron.plugins.common import nuagedb
from nuage_neutron.plugins.common import trunk_db
from nuage_neutron.plugins.common import utils
from nuage_neutron.plugins.common.utils import handle_nuage_api_errorcode
from nuage_neutron.plugins.common.utils import ignore_no_update
from nuage_neutron.plugins.common.utils import ignore_not_found
from nuage_neutron.plugins.sriov import trunk_driver


LOG = logging.getLogger(__name__)


class NuageSriovMechanismDriver(base_plugin.RootNuagePlugin,
                                api.MechanismDriver):
    """Ml2 Mechanism driver interface

    for provisioning sriov instances.
    """

    def initialize(self):
        LOG.debug('Initializing driver')
        self.init_vsd_client()
        self._wrap_vsdclient()
        self.trunk_driver = trunk_driver.NuageTrunkDriver.create(self)
        self.vif_details = {portbindings.CAP_PORT_FILTER: True}
        LOG.debug('Initializing complete')

    def _wrap_vsdclient(self):
        """Wraps nuagecient methods with try-except to ignore certain errors.

        When updating an entity on the VSD and there is nothing to actually
        update because the values don't change, VSD will throw an error. This
        is not needed for neutron so all these exceptions are ignored.

        When VSD responds with a 404, this is sometimes good (for example when
        trying to update an entity). Yet sometimes this is not required to be
        an actual exception. When deleting an entity that does no longer exist
        it is fine for neutron. Also when trying to retrieve something from VSD
        having None returned is easier to work with than RESTProxy exceptions.
        """

        methods = inspect.getmembers(self.vsdclient,
                                     lambda x: inspect.ismethod(x))
        for m in methods:
            wrapped = ignore_no_update(m[1])
            if m[0].startswith('get_') or m[0].startswith('delete_'):
                wrapped = ignore_not_found(wrapped)
            setattr(self.vsdclient, m[0], wrapped)

    @utils.context_log
    def create_network_precommit(self, context):
        db_context = context._plugin_context
        segments = context.current.get('segments')
        if segments:
            bad_segment = next(
                (segment for segment in segments if
                 segment.get('provider:network_type') == t_consts.VLAN and
                 trunk_db.vlan_in_use_by_subport(db_context.session,
                                                 segment)), None)
            if bad_segment:
                raise exceptions.VlanIdInUseBySubport(
                    vlan=bad_segment['provider:segmentation_id'],
                    physnet=bad_segment['provider:physical_network']
                )

    @utils.context_log
    def create_port_precommit(self, context):
        port = context.current
        vnic_type = port.get(portbindings.VNIC_TYPE, "")
        db_context = context._plugin_context
        if vnic_type not in self._supported_vnic_types():
            return
        self._validate_port_request_attributes(context.current)
        subnets = self.core_plugin._get_subnets_by_network(
            db_context,
            port.get('network_id'))
        if len(subnets) != 1:
            if ((len(subnets) != 2 or
                 subnets[0]['ip_version'] ==
                 subnets[1]['ip_version'])):
                raise exceptions.DirectPortSubnetConflict()

    @utils.context_log
    def update_port_precommit(self, context):
        """update_port_precommit."""
        port = context.current
        original = context.original
        if (port.get(portbindings.VNIC_TYPE, "")
                in self._supported_vnic_types()):
            self._validate_port_request_attributes(port, original=original)

    @handle_nuage_api_errorcode
    @utils.context_log
    def update_port_postcommit(self, context):
        """update_port_postcommit."""
        port = context.current
        original = context.original
        if (port.get(portbindings.VNIC_TYPE, "")
                in self._supported_vnic_types()):
            host_added = host_removed = False
            if not original['binding:host_id'] and port['binding:host_id']:
                host_added = True
            elif original['binding:host_id'] and not port['binding:host_id']:
                host_removed = True

            if host_removed:
                self._delete_port(port)
            if host_added:
                port_dict = self._make_port_dict(context)
                if port_dict:
                    self._update_port(port_dict)

    @utils.context_log
    def delete_port_precommit(self, context):
        """delete_port_precommit."""
        if (context.current.get(portbindings.VNIC_TYPE, "")
                in self._supported_vnic_types()):
            try:
                self._delete_port(context.current)
            except Exception as e:
                LOG.error("Failed to delete vport from vsd {port id: %s}",
                          context.current['id'])
                raise e

    @utils.context_log
    def bind_port(self, context):
        """bind_port."""
        if context.binding_levels:
            return  # we've already got a top binding

        subnet_mapping = self._validate_port(context._plugin_context,
                                             context.current)
        if not subnet_mapping:
            return

        port_id = context.current['id']
        for segment in context.segments_to_bind:
            if self._check_segment(segment, context):
                if not self._can_bind(context):
                    return
{'fraction_non_alphanumeric': 0.07253209545223761, 'fraction_numerical': 0.0033364763908029305, 'mean_word_length': 2.4213399503722086, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5095680', 'n_tokens_mistral': 3772, 'n_tokens_neox': 3645, 'n_words': 1014}