<commit_before># 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 baremetal_network_provisioning.common import constants
from baremetal_network_provisioning.db import bm_nw_provision_db as db
from baremetal_network_provisioning.drivers import discovery_driver
from baremetal_network_provisioning.ml2 import network_provisioning_api as api

import webob.exc as wexc

from neutron.api.v2 import base
from neutron.common import constants as n_const
from neutron import context as neutron_context
from neutron.i18n import _LE
from neutron.i18n import _LI
from neutron.i18n import _LW
from neutron.plugins.ml2.common import exceptions as ml2_exc

from oslo_config import cfg
from oslo_log import log as logging
from oslo_service import loopingcall
from oslo_utils import importutils

LOG = logging.getLogger(__name__)
hp_opts = [
    cfg.IntOpt('snmp_retries',
               default=5,
               help=_("Number of retries to be done")),
    cfg.IntOpt('snmp_timeout',
               default=3,
               help=_("Timeout in seconds to wait for SNMP request"
                      "completion.")),
    cfg.BoolOpt('bnp_sync_enable',
                default=False,
                help=_("Enable sync between neutron and "
                       "switch databases.")),
    cfg.FloatOpt('bnp_sync_interval',
                 default=300,
                 help=_("Interval at which polling thread sync "
                        "databases."))]
cfg.CONF.register_opts(hp_opts, "default")


class HPSNMPProvisioningDriver(api.NetworkProvisioningApi):
    """Back-end mechanism driver implementation for bare

    metal provisioning.
    """

    def __init__(self):
        """initialize the snmp driver."""
        self.conf = cfg.CONF
        self.bnp_sync_enable = self.conf.default.bnp_sync_enable
        self.bnp_sync_interval = float(
            self.conf.default.get('bnp_sync_interval'))
        # TODO(selva) need to check how we can load dynamically
        drvr = 'baremetal_network_provisioning.drivers.snmp_driver.SNMPDriver'
        self.context = neutron_context.get_admin_context()
        self._load_drivers(drvr)
        if self.bnp_sync_enable:
            self.start_snmp_polling()
        else:
            LOG.info(_LI("BNP SNMP polling is disabled"))

    def monitor_port_status(self):
        """Sync switch database periodically."""
        self.context = neutron_context.get_admin_context()
        portmaps = db.get_all_bnp_swport_mappings(self.context)
        for portmap in portmaps:
            swport = db.get_bnp_phys_switch_port_by_id(
                self.context, portmap['switch_port_id'])
            old_status = swport['port_status']
            switch = db.get_bnp_phys_switch(self.context,
                                            portmap['switch_id'])
            try:
                snmp_drv = discovery_driver.SNMPDiscoveryDriver(switch)
                port_status = snmp_drv.get_port_status(swport['ifindex'])
            except Exception as e:
                LOG.error(_LE("BNP SNMP polling exception: %s."), e)
                if old_status != 'UNKNOWN':
                    LOG.info(_LI("BNP SNMP polling: Update port status to "
                                 "UNKNOWN."))
                    db.update_bnp_phys_swport_status(
                        self.context, swport['switch_id'],
                        swport['interface_name'], 'UNKNOWN')
                    db.set_port_status(self.context,
                                       portmap['neutron_port_id'],
                                       n_const.PORT_STATUS_ERROR)
            else:
                new_status = constants.PORT_STATUS.get(str(port_status))
                LOG.debug("BNP SNMP polling: new port status %s", new_status)
                if new_status != old_status:
                    LOG.info(_LI('BNP SNMP polling: Update port status to %s'),
                             new_status)
                    db.update_bnp_phys_swport_status(
                        self.context, swport['switch_id'],
                        swport['interface_name'], new_status)
                    if new_status == 'UP':
                        db.set_port_status(self.context,
                                           portmap['neutron_port_id'],
                                           n_const.PORT_STATUS_ACTIVE)
                    else:
                        db.set_port_status(self.context,
                                           portmap['neutron_port_id'],
                                           n_const.PORT_STATUS_DOWN)

    def start_snmp_polling(self):
        """Spawn a thread to poll the switch db."""
        try:
            if self.bnp_sync_interval < 0:
                LOG.warning(_LW("Disabling BNP SNMP polling because its"
                                " interval is negative"))
            else:
                poll_thread = loopingcall.FixedIntervalLoopingCall(
                    self.monitor_port_status)
                poll_thread.start(interval=self.bnp_sync_interval)
                LOG.debug("Successfully started BNP SNMP polling thread with "
                          "interval %s", self.bnp_sync_interval)
        except Exception as e:
            LOG.error(_LE("Can't start BNP SNMP polling: %s"), e)

    def create_port(self, port):
        """create_port ."""
        LOG.info(_LI('create_port called from back-end mechanism driver'))
        self._create_port(port)

    def bind_port_to_segment(self, port):
        """bind_port_to_segment ."""
        LOG.info(_LI('bind_port_to_segment called from back-end mech driver'))
        switchports = port['port']['switchports']
        for switchport in switchports:
            switch_id = switchport['switch_id']
            bnp_switch = db.get_bnp_phys_switch_by_mac(self.context,
                                                       switch_id)
            port_name = switchport['port_id']
            if not bnp_switch:
                self._raise_ml2_error(wexc.HTTPNotFound, 'create_port')
            phys_port = db.get_bnp_phys_port(self.context,
                                             bnp_switch.id,
                                             port_name)
            if not phys_port:
                self._raise_ml2_error(wexc.HTTPNotFound, 'create_port')
            port_maps = db.get_all_bnp_swport_mappings(self.context)
            for port_map in port_maps:
                if phys_port.id == port_map.switch_port_id:
                    self._raise_ml2_error(wexc.HTTPConflict, 'create_port')
            switchport['ifindex'] = phys_port.ifindex
        credentials_dict = port.get('port')
        cred_dict = self._get_credentials_dict(bnp_switch, 'create_port')<commit_msg>Fix for VNETEE-413 Cleaning port failed.<commit_after># 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 baremetal_network_provisioning.common import constants
from baremetal_network_provisioning.db import bm_nw_provision_db as db
from baremetal_network_provisioning.drivers import discovery_driver
from baremetal_network_provisioning.ml2 import network_provisioning_api as api

import webob.exc as wexc

from neutron.api.v2 import base
from neutron.common import constants as n_const
from neutron import context as neutron_context
from neutron.i18n import _LE
from neutron.i18n import _LI
from neutron.i18n import _LW
from neutron.plugins.ml2.common import exceptions as ml2_exc

from oslo_config import cfg
from oslo_log import log as logging
from oslo_service import loopingcall
from oslo_utils import importutils

LOG = logging.getLogger(__name__)
hp_opts = [
    cfg.IntOpt('snmp_retries',
               default=5,
               help=_("Number of retries to be done")),
    cfg.IntOpt('snmp_timeout',
               default=3,
               help=_("Timeout in seconds to wait for SNMP request"
                      "completion.")),
    cfg.BoolOpt('bnp_sync_enable',
                default=False,
                help=_("Enable sync between neutron and "
                       "switch databases.")),
    cfg.FloatOpt('bnp_sync_interval',
                 default=300,
                 help=_("Interval at which polling thread sync "
                        "databases."))]
cfg.CONF.register_opts(hp_opts, "default")


class HPSNMPProvisioningDriver(api.NetworkProvisioningApi):
    """Back-end mechanism driver implementation for bare

    metal provisioning.
    """

    def __init__(self):
        """initialize the snmp driver."""
        self.conf = cfg.CONF
        self.bnp_sync_enable = self.conf.default.bnp_sync_enable
        self.bnp_sync_interval = float(
            self.conf.default.get('bnp_sync_interval'))
        # TODO(selva) need to check how we can load dynamically
        drvr = 'baremetal_network_provisioning.drivers.snmp_driver.SNMPDriver'
        self.context = neutron_context.get_admin_context()
        self._load_drivers(drvr)
        if self.bnp_sync_enable:
            self.start_snmp_polling()
        else:
            LOG.info(_LI("BNP SNMP polling is disabled"))

    def monitor_port_status(self):
        """Sync switch database periodically."""
        self.context = neutron_context.get_admin_context()
        portmaps = db.get_all_bnp_swport_mappings(self.context)
        for portmap in portmaps:
            swport = db.get_bnp_phys_switch_port_by_id(
                self.context, portmap['switch_port_id'])
            old_status = swport['port_status']
            switch = db.get_bnp_phys_switch(self.context,
                                            portmap['switch_id'])
            try:
                snmp_drv = discovery_driver.SNMPDiscoveryDriver(switch)
                port_status = snmp_drv.get_port_status(swport['ifindex'])
            except Exception as e:
                LOG.error(_LE("BNP SNMP polling exception: %s."), e)
                if old_status != 'UNKNOWN':
                    LOG.info(_LI("BNP SNMP polling: Update port status to "
                                 "UNKNOWN."))
                    db.update_bnp_phys_swport_status(
                        self.context, swport['switch_id'],
                        swport['interface_name'], 'UNKNOWN')
                    db.set_port_status(self.context,
                                       portmap['neutron_port_id'],
                                       n_const.PORT_STATUS_ERROR)
            else:
                new_status = constants.PORT_STATUS.get(str(port_status))
                LOG.debug("BNP SNMP polling: new port status %s", new_status)
                if new_status != old_status:
                    LOG.info(_LI('BNP SNMP polling: Update port status to %s'),
                             new_status)
                    db.update_bnp_phys_swport_status(
                        self.context, swport['switch_id'],
                        swport['interface_name'], new_status)
                    if new_status == 'UP':
                        db.set_port_status(self.context,
                                           portmap['neutron_port_id'],
                                           n_const.PORT_STATUS_ACTIVE)
                    else:
                        db.set_port_status(self.context,
                                           portmap['neutron_port_id'],
                                           n_const.PORT_STATUS_DOWN)

    def start_snmp_polling(self):
        """Spawn a thread to poll the switch db."""
        try:
            if self.bnp_sync_interval < 0:
                LOG.warning(_LW("Disabling BNP SNMP polling because its"
                                " interval is negative"))
            else:
                poll_thread = loopingcall.FixedIntervalLoopingCall(
                    self.monitor_port_status)
                poll_thread.start(interval=self.bnp_sync_interval)
                LOG.debug("Successfully started BNP SNMP polling thread with "
                          "interval %s", self.bnp_sync_interval)
        except Exception as e:
            LOG.error(_LE("Can't start BNP SNMP polling: %s"), e)

    def create_port(self, port):
        """create_port ."""
        LOG.info(_LI('create_port called from back-end mechanism driver'))
        self._create_port(port)

    def bind_port_to_segment(self, port):
        """bind_port_to_segment ."""
        LOG.info(_LI('bind_port_to_segment called from back-end mech driver'))
        switchports = port['port']['switchports']
        for switchport in switchports:
            switch_id = switchport['switch_id']
            bnp_switch = db.get_bnp_phys_switch_by_mac(self.context,
                                                       switch_id)
            port_name = switchport['port_id']
            if not bnp_switch:
                self._raise_ml2_error(wexc.HTTPNotFound, 'create_port')
            phys_port = db.get_bnp_phys_port(self.context,
                                             bnp_switch.id,
                                             port_name)
            if not phys_port:
                self._raise_ml2_error(wexc.HTTPNotFound, 'create_port')
            # port_maps = db.get_all_bnp_swport_mappings(self.context)
            # for port_map in port_maps:
            #    if phys_port.id == port_map.switch_port_id:
            #        self._raise_ml2_error(wexc.HTTPConflict, 'create_port')
            switchport['ifindex'] = phys_port.ifindex
        credentials_dict = port.get('port')
        cred_dict = self._get_credentials_dict(bnp_switch, 'create_port')
{'fraction_non_alphanumeric': 0.07951196106655699, 'fraction_numerical': 0.003907053259304956, 'mean_word_length': 1.9391619661563255, 'pattern_counts': {'":': 0, '<': 5, '<?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': 40, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5397628', 'n_tokens_mistral': 4011, 'n_tokens_neox': 3842, 'n_words': 920}