def get_error_msg(self, response_list):
        """
        Checks for error in response

        :param:response_list: List of response from device
        :returns:msg - Message will contain error description in case of an
            error, None otherwise.
        """
        msg = None
        for response in response_list:
            if INVALID_INPUT in response:
                msg = _("Ethernet Driver : Create"
                        "network failed: error= Invalid Input")
                LOG.error(msg)
                break
            elif RANGE_ERROR in response_list:
                msg = _("Configuring router interface failed: "
                        "ve out of range error")
                LOG.error(msg)
                break
            elif ERROR in response_list:
                msg = _("Configuring router interface failed: "
                        "vlan not associated to router interface")
                LOG.error(msg)
                break
        return msg
    def create_network_precommit(self, mech_context):
        """Create Network in the mechanism specific database table."""
        if self.is_flat_network(mech_context.network_segments[0]):
            return

        network = mech_context.current
        context = mech_context._plugin_context
        tenant_id = network['tenant_id']
        network_id = network['id']

        segments = mech_context.network_segments
        # currently supports only one segment per network
        segment = segments[0]

        network_type = segment['network_type']
        vlan_id = segment['segmentation_id']
        segment_id = segment['id']

        if network_type not in [p_const.TYPE_VLAN]:
            raise Exception(
                _("Brocade Mechanism: failed to create network, "
                  "only network type vlan is supported"))

        try:
            brocade_db.create_network(context, network_id, vlan_id,
                                      segment_id, network_type, tenant_id)
        except Exception:
            LOG.exception(
                _LE("Brocade Mechanism: failed to create network in db"))
            raise Exception(
                _("Brocade Mechanism: create_network_precommit failed"))
Example #3
0
    def get_error_msg(self, response_list):
        """
        Checks for error in response

        :param:response_list: List of response from device
        :returns:msg - Message will contain error description in case of an
            error, None otherwise.
        """
        msg = None
        for response in response_list:
            if INVALID_INPUT in response:
                msg = _("Ethernet Driver : Create"
                        "network failed: error= Invalid Input")
                LOG.error(msg)
                break
            elif RANGE_ERROR in response_list:
                msg = _("Configuring router interface failed: "
                        "ve out of range error")
                LOG.error(msg)
                break
            elif ERROR in response_list:
                msg = _("Configuring router interface failed: "
                        "vlan not associated to router interface")
                LOG.error(msg)
                break
        return msg
Example #4
0
    def create_network_precommit(self, mech_context):
        """Create Network in the mechanism specific database table."""
        if self.is_flat_network(mech_context.network_segments[0]):
            return

        network = mech_context.current
        context = mech_context._plugin_context
        tenant_id = network['tenant_id']
        network_id = network['id']

        segments = mech_context.network_segments
        # currently supports only one segment per network
        segment = segments[0]

        network_type = segment['network_type']
        vlan_id = segment['segmentation_id']
        segment_id = segment['id']

        if segment['physical_network'] not in self._physical_networks:
            raise Exception(
                _("Brocade Mechanism: failed to create network, "
                  "network cannot be created in the configured "
                  "physical network"))

        if network_type not in [p_const.TYPE_VLAN]:
            raise Exception(
                _("Brocade Mechanism: failed to create network, "
                  "only network type vlan is supported"))

        try:
            brocade_db.create_network(context, network_id, vlan_id, segment_id,
                                      network_type, tenant_id)
        except Exception:
            LOG.exception(
                _LE("Brocade Mechanism: failed to create network in db"))
            raise Exception(
                _("Brocade Mechanism: create_network_precommit failed"))

        LOG.info(
            _LI("create network (precommit): %(network_id)s "
                "of network type = %(network_type)s "
                "with vlan = %(vlan_id)s "
                "for tenant %(tenant_id)s"), {
                    'network_id': network_id,
                    'network_type': network_type,
                    'vlan_id': vlan_id,
                    'tenant_id': tenant_id
                })
Example #5
0
    def delete_network_postcommit(self, mech_context):
        """Delete network.

        This translates to removng portprofile
        from the switch.
        """

        LOG.debug("delete_network_postcommit: called")
        network = mech_context.current
        network_id = network['id']
        vlan_id = network['provider:segmentation_id']
        tenant_id = network['tenant_id']

        try:
            self._driver.delete_network(self._switch['address'],
                                        self._switch['username'],
                                        self._switch['password'], vlan_id)
        except Exception:
            LOG.exception(_LE("Brocade NOS driver: failed to delete network"))
            raise Exception(
                _("Brocade switch exception, "
                  "delete_network_postcommit failed"))

        LOG.info(
            _LI("delete network (postcommit): %(network_id)s"
                " with vlan = %(vlan_id)s"
                " for tenant %(tenant_id)s"), {
                    'network_id': network_id,
                    'vlan_id': vlan_id,
                    'tenant_id': tenant_id
                })
Example #6
0
    def create_port_precommit(self, mech_context):
        """Create logical port on the switch (db update)."""

        LOG.debug("create_port_precommit: called")

        port = mech_context.current
        port_id = port['id']
        network_id = port['network_id']
        tenant_id = port['tenant_id']
        admin_state_up = port['admin_state_up']

        context = mech_context._plugin_context

        network = brocade_db.get_network(context, network_id)
        vlan_id = network['vlan']

        try:
            brocade_db.create_port(context, port_id, network_id, None, vlan_id,
                                   tenant_id, admin_state_up)
        except Exception:
            LOG.exception(
                _LE("Brocade Mechanism: failed to create port"
                    " in db"))
            raise Exception(
                _("Brocade Mechanism: create_port_precommit failed"))
Example #7
0
    def create_network_postcommit(self, mech_context):
        """Create Network on the switch."""

        LOG.debug("create_network_postcommit: called")

        if self.is_flat_network(mech_context.network_segments[0]):
            return

        network = mech_context.current
        # use network_id to get the network attributes
        # ONLY depend on our db for getting back network attributes
        # this is so we can replay postcommit from db
        context = mech_context._plugin_context

        network_id = network['id']
        network = brocade_db.get_network(context, network_id)
        network['network_type']
        network['tenant_id']
        vlan_id = network['vlan']
        segments = mech_context.network_segments
        # currently supports only one segment per network
        segment = segments[0]
        physical_network = segment['physical_network']

        try:
            self._driver.create_network(self._device_dict, physical_network,
                                        vlan_id)
        except Exception:
            LOG.exception(_LE("Brocade NOS driver: failed in create network"))
            brocade_db.delete_network(context, network_id)
            raise Exception(
                _("Brocade Mechanism: create_network_postcommmit failed"))
Example #8
0
    def _get_driver(self, device):
        """
        Gets the driver based on the firmware version of the device.

        :param:device: Contains device name
        :raises: Exception
        """
        driver = self._driver_map.get(device)
        if driver is None:
            driver_factory = importutils.import_object(DRIVER_FACTORY)
            device_info = self._devices.get(device)
            address = device_info.get('address')
            os_type = device_info.get('ostype')
            try:
                driver = driver_factory.get_driver(device_info)
                if driver is not None and os_type in ROUTER_DEVICE_TYPE:
                    self._driver_map.update({device: driver})
            except Exception as e:
                LOG.exception(
                    _LE("BrocadeRouterPlugin:"
                        "_filter_router_devices: Error while getting"
                        " driver : device - %(host)s: %(error)s"), {
                            'host': address,
                            'error': e.args
                        })
                raise Exception(
                    _("BrocadeRouterPlugin:"
                      "_filter_router_devices failed for "
                      "device %(host)s"), {'host': address})
        return driver
    def connect(self, host, username, password):
        """Connect via SSH and initialize the NETCONF session."""

        # Use the persisted NETCONF connection
        if self.mgr and self.mgr.connected:
            return self.mgr

        # check if someone forgot to edit the conf file with real values
        if host == '':
            raise Exception(_("Brocade Switch IP address is not set, "
                              "check config ml2_conf_brocade.ini file"))

        # Open new NETCONF connection
        try:
            self.mgr = manager.connect(host=host, port=SSH_PORT,
                                       username=username, password=password,
                                       unknown_host_cb=nos_unknown_host_cb)

        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.exception(_LE("Connect failed to switch"))

        LOG.debug("Connect success to host %(host)s:%(ssh_port)d",
                  dict(host=host, ssh_port=SSH_PORT))
        return self.mgr
 def _validate_routes_nexthop(self, cidrs, ips, routes, nexthop):
     # lets skip to check connected routes
     # lets keep it FR
     if nexthop in ips:
         raise extraroute.InvalidRoutes(
             routes=routes,
             reason=_('the nexthop is used by router'))
Example #11
0
    def connect(self):
        """
        Connect to the device
        """
        try:
            self.connector = paramiko.SSHClient()
            self.connector.set_missing_host_key_policy(
                paramiko.AutoAddPolicy())
            self.connector.connect(hostname=self.host,
                                   username=self.username,
                                   password=self.password)

            self.channel = self.connector.invoke_shell()
            self.channel.settimeout(TIMEOUT)
            self.channel_data = str()
            self._enter_prompt(False)

        except Exception as e:
            LOG.exception(
                _LE("Connect failed to switch %(host)s with error"
                    " %(error)s"), {
                        'host': self.host,
                        'error': e.args
                    })
            raise Exception(_("Connection Failed"))
    def _create_nos_port(self, context, port, segment):
        hostname, vlan_id, physical_network = self._get_port_info(
            port, segment)
        if not hostname or not vlan_id:
            LOG.info(_LI("hostname or vlan id is empty"))
            return
        for (speed, name) in self._device_dict[(hostname, physical_network)]:
            LOG.debug("_create_nos_port:port %s %s vlan %s",
                      speed, name, str(vlan_id))
            try:
                if not brocade_db.is_vm_exists_on_host(context,
                                                       hostname,
                                                       physical_network,
                                                       vlan_id):
                    address, user, password = self._get_switch_address(hostname)

                    self._driver.configure_trunk_vlan_on_interface(
                                        address,
                                        user,
                                        password,
                                        vlan_id,
                                        name,
                                        speed)
                else:
                    LOG.debug("_create_nos_port:port is already trunked")
            except Exception:
                self._delete_brocade_port(context, port)
                LOG.exception(_LE("Brocade NOS driver:failed to trunk vlan"))
                raise Exception(_("Brocade switch exception:"
                                  " create_port_postcommit failed"))
Example #13
0
    def connect(self, host, username, password):
        """Connect via SSH and initialize the NETCONF session."""

        # Use the persisted NETCONF connection
        if self.mgr and self.mgr.connected:
            return self.mgr

        # check if someone forgot to edit the conf file with real values
        if host == '':
            raise Exception(
                _("Brocade Switch IP address is not set, "
                  "check config ml2_conf_brocade.ini file"))

        # Open new NETCONF connection
        try:
            self.mgr = manager.connect(host=host,
                                       port=SSH_PORT,
                                       username=username,
                                       password=password,
                                       unknown_host_cb=nos_unknown_host_cb,
                                       hostkey_verify=False,
                                       look_for_keys=False)

        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.exception(_LE("Connect failed to switch"))

        LOG.debug("Connect success to host %(host)s:%(ssh_port)d",
                  dict(host=host, ssh_port=SSH_PORT))
        return self.mgr
    def delete_network_precommit(self, mech_context):
        """Delete Network from the plugin specific database table."""

        LOG.debug("delete_network_precommit: called")

        network = mech_context.current
        network_id = network['id']
        vlan_id = network['provider:segmentation_id']
        tenant_id = network['tenant_id']

        context = mech_context._plugin_context

        try:
            brocade_db.delete_network(context, network_id)
        except Exception:
            LOG.exception(
                _LE("Brocade Mechanism: failed to delete network in db"))
            raise Exception(
                _("Brocade Mechanism: delete_network_precommit failed"))

        LOG.info(_LI("delete network (precommit): %(network_id)s"
                     " with vlan = %(vlan_id)s"
                     " for tenant %(tenant_id)s"),
                 {'network_id': network_id,
                  'vlan_id': vlan_id,
                  'tenant_id': tenant_id})
Example #15
0
    def bind_port(self, context):
        port = context.current
        vnic_type = port['binding:vnic_type']

        LOG.debug("Brcd:Attempting to bind port %(port)s with vnic_type "
                  "%(vnic_type)s on network %(network)s",
                  {'port': port['id'], 'vnic_type': vnic_type,
                   'network': context.network.current['id']})

        if baremetal_util.is_baremetal_deploy(port):
            segments = context.segments_to_bind
            LOG.info(_LI("Segments:%s"), segments)
            params = baremetal_util.validate_physical_net_params(context)
            try:
                # TODO(rmadapur): Handle local_link_info portgroups
                for i in params["local_link_information"]:
                    speed, name = i['port_id']
                    vlan_id = segments[0][api.SEGMENTATION_ID]
                    self._driver.configure_native_vlan_on_interface(
                        speed,
                        name, vlan_id)
            except Exception:
                LOG.exception(_LE("Brocade NOS driver:failed to trunk"
                                  " bare metal vlan"))
                raise Exception(_("Brocade switch exception:"
                                  " bind_port failed for baremetal"))
            context.set_binding(segments[0][api.ID],
                                portbindings.VIF_TYPE_OTHER, {},
                                status=n_const.PORT_STATUS_ACTIVE)
    def delete_network_postcommit(self, mech_context):
        """Delete network.

        This translates to removng portprofile
        from the switch.
        """

        LOG.debug("delete_network_postcommit: called")
        network = mech_context.current
        network_id = network['id']
        vlan_id = network['provider:segmentation_id']
        tenant_id = network['tenant_id']

        try:
            self._driver.delete_network(self._switch['address'],
                                        self._switch['username'],
                                        self._switch['password'],
                                        vlan_id)
        except Exception:
            LOG.exception(_LE("Brocade NOS driver: failed to delete network"))
            raise Exception(
                _("Brocade switch exception, "
                  "delete_network_postcommit failed"))

        LOG.info(_LI("delete network (postcommit): %(network_id)s"
                     " with vlan = %(vlan_id)s"
                     " for tenant %(tenant_id)s"),
                 {'network_id': network_id,
                  'vlan_id': vlan_id,
                  'tenant_id': tenant_id})
Example #17
0
    def delete_network_precommit(self, mech_context):
        """Delete Network from the plugin specific database table."""

        LOG.debug("delete_network_precommit: called")

        network = mech_context.current
        network_id = network['id']
        vlan_id = network['provider:segmentation_id']
        tenant_id = network['tenant_id']

        context = mech_context._plugin_context

        try:
            brocade_db.delete_network(context, network_id)
        except Exception:
            LOG.exception(
                _LE("Brocade Mechanism: failed to delete network in db"))
            raise Exception(
                _("Brocade Mechanism: delete_network_precommit failed"))

        LOG.info(
            _LI("delete network (precommit): %(network_id)s"
                " with vlan = %(vlan_id)s"
                " for tenant %(tenant_id)s"), {
                    'network_id': network_id,
                    'vlan_id': vlan_id,
                    'tenant_id': tenant_id
                })
    def _get_driver(self, device):
        """
        Gets the driver based on the firmware version of the device.

        :param:device: Contains device name
        :raises: Exception
        """
        driver = self._driver_map.get(device)
        if driver is None:
            driver_factory = importutils.import_object(DRIVER_FACTORY)
            device_info = self._devices.get(device)
            address = device_info.get('address')
            os_type = device_info.get('ostype')
            try:
                driver = driver_factory.get_driver(device_info)
                if driver is not None and os_type in ROUTER_DEVICE_TYPE:
                    self._driver_map.update({device: driver})
            except Exception as e:
                LOG.exception(_LE("BrocadeRouterPlugin:"
                                  "_filter_router_devices: Error while getting"
                                  " driver : device - %(host)s: %(error)s"),
                              {'host': address, 'error': e.args})
                raise Exception(_("BrocadeRouterPlugin:"
                                  "_filter_router_devices failed for "
                                  "device %(host)s"), {'host': address})
        return driver
    def _delete_nos_port(self, context, port, segment):

        hostname, vlan_id, physical_network =\
            self._get_port_info(port, segment)
        if not hostname or not vlan_id:
            LOG.info(_LI("hostname or vlan id is empty"))
            return
        for (speed, name) in self._device_dict[(hostname, physical_network)]:
            try:
                if brocade_db.is_last_vm_on_host(context,
                                                 hostname,
                                                 physical_network, vlan_id)\
                        and not self._is_dhcp_port(port):
                    address, user, password = self._get_switch_address(hostname)
                    self._driver.deconfigure_trunk_vlan_on_interface(
                                        address,
                                        user,
                                        password,
                                        vlan_id,
                                        name,
                                        speed)
                else:
                    LOG.info(_LI("more vm exist for network on host hence vlan"
                               " is not removed from port"))
            except Exception:
                LOG.exception(
                    _LE("Brocade NOS driver: failed to remove vlan from port"))
                raise Exception(
                    _("Brocade switch exception: delete_port_postcommit"
                      "failed"))
    def create_port_precommit(self, mech_context):
        """Create logical port on the switch (db update)."""

        LOG.debug("create_port_precommit: called")

        port = mech_context.current
        port_id = port['id']
        network_id = port['network_id']
        tenant_id = port['tenant_id']
        admin_state_up = port['admin_state_up']

        context = mech_context._plugin_context

        network = brocade_db.get_network(context, network_id)
        vlan_id = network['vlan']

        try:
            brocade_db.create_port(context, port_id, network_id,
                                   None,
                                   vlan_id, tenant_id, admin_state_up)
        except Exception:
            LOG.exception(_LE("Brocade Mechanism: failed to create port"
                              " in db"))
            raise Exception(
                _("Brocade Mechanism: create_port_precommit failed"))
    def create_network_precommit(self, mech_context):
        """Create Network in the mechanism specific database table."""
        if self.is_flat_network(mech_context.network_segments[0]):
            return

        network = mech_context.current
        context = mech_context._plugin_context
        tenant_id = network['tenant_id']
        network_id = network['id']

        segments = mech_context.network_segments
        # currently supports only one segment per network
        segment = segments[0]

        network_type = segment['network_type']
        vlan_id = segment['segmentation_id']
        segment_id = segment['id']

        if segment['physical_network'] not in self._physical_networks:
            raise Exception(
                _("Brocade Mechanism: failed to create network, "
                  "network cannot be created in the configured "
                  "physical network"))

        if network_type not in [p_const.TYPE_VLAN]:
            raise Exception(
                _("Brocade Mechanism: failed to create network, "
                  "only network type vlan is supported"))

        try:
            brocade_db.create_network(context, network_id, vlan_id,
                                      segment_id, network_type, tenant_id)
        except Exception:
            LOG.exception(
                _LE("Brocade Mechanism: failed to create network in db"))
            raise Exception(
                _("Brocade Mechanism: create_network_precommit failed"))

        LOG.info(_LI("create network (precommit): %(network_id)s "
                     "of network type = %(network_type)s "
                     "with vlan = %(vlan_id)s "
                     "for tenant %(tenant_id)s"),
                 {'network_id': network_id,
                  'network_type': network_type,
                  'vlan_id': vlan_id,
                  'tenant_id': tenant_id})
Example #22
0
class FirewallCountExceeded(n_exception.Conflict):
    """Reference implementation specific exception for firewall count.

    Only one firewall is supported per tenant. When a second
    firewall is tried to be created, this exception will be raised.
    """
    message = _("Exceeded allowed count of firewalls for tenant "
                "%(tenant_id)s. Only one firewall is supported per tenant.")
 def _delete_brocade_port(self, context, port):
     try:
         port_id = port['id']
         brocade_db.delete_port(context, port_id)
     except Exception:
         LOG.exception(_LE("Brocade Mechanism:"
                           " failed to delete port in db"))
         raise Exception(
             _("Brocade Mechanism: delete_port_precommit failed"))
 def _create_brocade_port(self, context, port, segment):
     port_id = port['id']
     network_id = port['network_id']
     tenant_id = port['tenant_id']
     admin_state_up = port['admin_state_up']
     hostname, vlan_id, physical_network = self._get_port_info(
         port, segment)
     try:
         brocade_db.create_port(context, port_id, network_id,
                                physical_network, vlan_id, tenant_id,
                                admin_state_up, hostname)
     except Exception:
         LOG.exception(_LE("Brocade Mechanism: "
                           "failed to create port in db"))
         raise Exception(
             _("Brocade Mechanism: create_port_precommit failed"))
    def delete_port_precommit(self, mech_context):
        """Delete logical port on the switch (db update)."""

        LOG.debug("delete_port_precommit: called")
        port = mech_context.current
        port_id = port['id']

        context = mech_context._plugin_context

        try:
            brocade_db.delete_port(context, port_id)
        except Exception:
            LOG.exception(_LE("Brocade Mechanism: failed to delete port"
                              " in db"))
            raise Exception(
                _("Brocade Mechanism: delete_port_precommit failed"))
Example #26
0
 def delete_port_postcommit(self, mech_context):
     """Dissociate VLAN from baremetal connected
        port.
     """
     LOG.debug(("brocade_baremetal delete_port_postcommit(self: called"))
     port = mech_context.current
     if baremetal_util.is_baremetal_deploy(port):
         params = baremetal_util.validate_physical_net_params(mech_context)
         try:
             # TODO(rmadapur): Handle local_link_info portgroups
             for i in params["local_link_information"]:
                 speed, name = i['port_id']
                 self._driver.remove_native_vlan_from_interface(speed, name)
         except Exception:
             LOG.exception(_LE("Brocade NOS driver:failed to remove native"
                               " vlan from bare metal interface"))
             raise Exception(_("NOS driver:failed to remove native vlan"))
Example #27
0
    def delete_port_precommit(self, mech_context):
        """Delete logical port on the switch (db update)."""

        LOG.debug("delete_port_precommit: called")
        port = mech_context.current
        port_id = port['id']

        context = mech_context._plugin_context

        try:
            brocade_db.delete_port(context, port_id)
        except Exception:
            LOG.exception(
                _LE("Brocade Mechanism: failed to delete port"
                    " in db"))
            raise Exception(
                _("Brocade Mechanism: delete_port_precommit failed"))
 def connect(self):
     """
     Connect to device via Telnet
     """
     try:
         self.connector = telnetlib.Telnet(host=self.host, port=TELNET_PORT)
         self.connector.read_until(LOGIN_USER_TOKEN, MIN_TIMEOUT)
         self.connector.write(self.username + END_OF_LINE)
         self.connector.read_until(LOGIN_PASS_TOKEN, AVG_TIMEOUT)
         self.connector.write(self.password + END_OF_LINE)
         self.response = str()
         self._enter_prompt(False)
     except Exception as e:
         LOG.exception(_LE("Connect failed to switch %(host)s with error"
                           " %(error)s"),
                       {'host': self.host, 'error': e.args})
         raise Exception(_("Connection Failed"))
Example #29
0
    def create_port_postcommit(self, mech_context):
        """Associate the assigned MAC address to the portprofile."""

        LOG.debug("create_port_postcommit: called")
        if self.is_flat_network(mech_context.network.network_segments[0]):
            return

        port = mech_context.current
        port_id = port['id']
        network_id = port['network_id']
        tenant_id = port['tenant_id']

        context = mech_context._plugin_context

        network = brocade_db.get_network(context, network_id)
        if not network:
            LOG.info(_LI("network not populated nothing to be done"))
            return
        vlan_id = network['vlan']

        interface_mac = port['mac_address']

        # convert mac format: xx:xx:xx:xx:xx:xx -> xxxx.xxxx.xxxx
        mac = self.mac_reformat_62to34(interface_mac)
        try:
            self._driver.associate_mac_to_network(self._switch['address'],
                                                  self._switch['username'],
                                                  self._switch['password'],
                                                  vlan_id, mac)
        except Exception:
            LOG.exception(
                _LE("Brocade NOS driver: failed to associate mac %s"),
                interface_mac)
            raise Exception(
                _("Brocade switch exception: create_port_postcommit failed"))

        LOG.info(
            _LI("created port (postcommit): port_id=%(port_id)s"
                " network_id=%(network_id)s tenant_id=%(tenant_id)s"), {
                    'port_id': port_id,
                    'network_id': network_id,
                    'tenant_id': tenant_id
                })
Example #30
0
    def delete_network_postcommit(self, mech_context):
        """Delete network
        from the switch.
        """
        LOG.debug("delete_network_postcommit: called")
        if self.is_flat_network(mech_context.network_segments[0]):
            return

        network = mech_context.current
        network['id']
        vlan_id = network['provider:segmentation_id']
        network['tenant_id']
        try:
            self._driver.delete_network(vlan_id)
        except Exception:
            LOG.exception(_LE("Brocade NOS driver: failed to delete network"))
            raise Exception(
                _("Brocade switch exception, "
                  "delete_network_postcommit failed"))
    def delete_port_postcommit(self, mech_context):
        """Dissociate MAC address from the portprofile."""

        LOG.debug("delete_port_postcommit: called")
        if self.is_flat_network(mech_context.network.network_segments[0]):
            return
        port = mech_context.current
        port_id = port['id']
        network_id = port['network_id']
        tenant_id = port['tenant_id']

        context = mech_context._plugin_context

        network = brocade_db.get_network(context, network_id)
        if not network:
            LOG.info(_LI("network not populated nothing to be done"))
            return
        vlan_id = network['vlan']

        interface_mac = port['mac_address']

        # convert mac format: xx:xx:xx:xx:xx:xx -> xxxx.xxxx.xxxx
        mac = self.mac_reformat_62to34(interface_mac)
        try:
            self._driver.dissociate_mac_from_network(
                self._switch['address'],
                self._switch['username'],
                self._switch['password'],
                vlan_id,
                mac)
        except Exception:
            LOG.exception(
                _LE("Brocade NOS driver: failed to dissociate MAC %s"),
                interface_mac)
            raise Exception(
                _("Brocade switch exception, delete_port_postcommit failed"))

        LOG.info(
            _LI("delete port (postcommit): port_id=%(port_id)s"
                " network_id=%(network_id)s tenant_id=%(tenant_id)s"),
            {'port_id': port_id,
             'network_id': network_id, 'tenant_id': tenant_id})
Example #32
0
 def connect(self):
     """
     Connect to device via Telnet
     """
     try:
         self.connector = telnetlib.Telnet(host=self.host, port=TELNET_PORT)
         self.connector.read_until(LOGIN_USER_TOKEN, MIN_TIMEOUT)
         self.connector.write(self.username + END_OF_LINE)
         self.connector.read_until(LOGIN_PASS_TOKEN, AVG_TIMEOUT)
         self.connector.write(self.password + END_OF_LINE)
         self.response = str()
         self._enter_prompt(False)
     except Exception as e:
         LOG.exception(
             _LE("Connect failed to switch %(host)s with error"
                 " %(error)s"), {
                     'host': self.host,
                     'error': e.args
                 })
         raise Exception(_("Connection Failed"))
    def delete_network_precommit(self, mech_context):
        """Delete Network from the plugin specific database table."""

        LOG.debug("delete_network_precommit: called")
        if self.is_flat_network(mech_context.network_segments[0]):
            return

        network = mech_context.current
        network_id = network['id']
        network['tenant_id']

        context = mech_context._plugin_context

        try:
            brocade_db.delete_network(context, network_id)
        except Exception:
            LOG.exception(
                _LE("Brocade Mechanism: failed to delete network in db"))
            raise Exception(
                _("Brocade Mechanism: delete_network_precommit failed"))
Example #34
0
    def create_network_postcommit(self, mech_context):
        """Create Network as a portprofile on the switch."""

        LOG.debug("create_network_postcommit: called")
        if self.is_flat_network(mech_context.network_segments[0]):
            return

        network = mech_context.current
        # use network_id to get the network attributes
        # ONLY depend on our db for getting back network attributes
        # this is so we can replay postcommit from db
        context = mech_context._plugin_context

        network_id = network['id']
        network = brocade_db.get_network(context, network_id)
        network_type = network.network_type
        tenant_id = network['tenant_id']
        vlan_id = network['vlan']

        try:
            self._driver.create_network(self._switch['address'],
                                        self._switch['username'],
                                        self._switch['password'], vlan_id)
        except Exception:
            LOG.exception(_LE("Brocade NOS driver: failed in create network"))
            brocade_db.delete_network(context, network_id)
            raise Exception(
                _("Brocade Mechanism: create_network_postcommmit failed"))

        LOG.info(
            _LI("created network (postcommit): %(network_id)s"
                " of network type = %(network_type)s"
                " with vlan = %(vlan_id)s"
                " for tenant %(tenant_id)s"), {
                    'network_id': network_id,
                    'network_type': network_type,
                    'vlan_id': vlan_id,
                    'tenant_id': tenant_id
                })
    def create_network_postcommit(self, mech_context):
        """Create Network as a portprofile on the switch."""

        LOG.debug("create_network_postcommit: called")
        if self.is_flat_network(mech_context.network_segments[0]):
            return

        network = mech_context.current
        # use network_id to get the network attributes
        # ONLY depend on our db for getting back network attributes
        # this is so we can replay postcommit from db
        context = mech_context._plugin_context

        network_id = network['id']
        network = brocade_db.get_network(context, network_id)
        network_type = network.network_type
        tenant_id = network['tenant_id']
        vlan_id = network['vlan']

        try:
            self._driver.create_network(self._switch['address'],
                                        self._switch['username'],
                                        self._switch['password'],
                                        vlan_id)
        except Exception:
            LOG.exception(_LE("Brocade NOS driver: failed in create network"))
            brocade_db.delete_network(context, network_id)
            raise Exception(
                _("Brocade Mechanism: create_network_postcommmit failed"))

        LOG.info(_LI("created network (postcommit): %(network_id)s"
                     " of network type = %(network_type)s"
                     " with vlan = %(vlan_id)s"
                     " for tenant %(tenant_id)s"),
                 {'network_id': network_id,
                  'network_type': network_type,
                  'vlan_id': vlan_id,
                  'tenant_id': tenant_id})
Example #36
0
    def configure_vcs(self):
        # configure vcs interfaces based on topology
        if not utils._is_valid_interface(self._device_dict, self._switch,
                                         self._driver):
            sys.exit(0)

        LOG.debug("device dictionary %s", self._device_dict)

        try:
            if utils._is_lacp_enabled():
                LOG.debug("LACP enabled")
                (self._device_dict, self._lacp_ports) =\
                    utils._aggregate_nics_to_support_lacp(self._device_dict,
                                                          self._bond_mappings)
            self._driver.configure_l2_and_trunk_mode_for_interface(
                self._device_dict, self._lacp_ports, self._mtu,
                self._native_vlans)
        except Exception:
            LOG.exception(
                _LE("Brocade Mechanism: failed to put"
                    " interface l2 or tr mode"))
            raise Exception(
                _("Brocade Mechanism: failed to put interface l2 or tr mode"))
    def connect(self):
        """
        Connect to the device
        """
        try:
            self.connector = paramiko.SSHClient()
            self.connector.set_missing_host_key_policy(
                paramiko.AutoAddPolicy())
            self.connector.connect(
                hostname=self.host,
                username=self.username,
                password=self.password)

            self.channel = self.connector.invoke_shell()
            self.channel.settimeout(TIMEOUT)
            self.channel_data = str()
            self._enter_prompt(False)

        except Exception as e:
            LOG.exception(_LE("Connect failed to switch %(host)s with error"
                              " %(error)s"),
                          {'host': self.host, 'error': e.args})
            raise Exception(_("Connection Failed"))
Example #38
0
    def delete_port_postcommit(self, mech_context):
        """Dissociate MAC address from the portprofile."""

        LOG.debug("delete_port_postcommit: called")
        port = mech_context.current
        port_id = port['id']
        network_id = port['network_id']
        tenant_id = port['tenant_id']

        context = mech_context._plugin_context

        network = brocade_db.get_network(context, network_id)
        vlan_id = network['vlan']

        interface_mac = port['mac_address']

        # convert mac format: xx:xx:xx:xx:xx:xx -> xxxx.xxxx.xxxx
        mac = self.mac_reformat_62to34(interface_mac)
        try:
            self._driver.dissociate_mac_from_network(self._switch['address'],
                                                     self._switch['username'],
                                                     self._switch['password'],
                                                     vlan_id, mac)
        except Exception:
            LOG.exception(
                _LE("Brocade NOS driver: failed to dissociate MAC %s"),
                interface_mac)
            raise Exception(
                _("Brocade switch exception, delete_port_postcommit failed"))

        LOG.info(
            _LI("delete port (postcommit): port_id=%(port_id)s"
                " network_id=%(network_id)s tenant_id=%(tenant_id)s"), {
                    'port_id': port_id,
                    'network_id': network_id,
                    'tenant_id': tenant_id
                })
    def create_port_postcommit(self, mech_context):
        """Associate the assigned MAC address to the portprofile."""

        LOG.debug("create_port_postcommit: called")

        port = mech_context.current
        port_id = port['id']
        network_id = port['network_id']
        tenant_id = port['tenant_id']

        context = mech_context._plugin_context

        network = brocade_db.get_network(context, network_id)
        vlan_id = network['vlan']

        interface_mac = port['mac_address']

        # convert mac format: xx:xx:xx:xx:xx:xx -> xxxx.xxxx.xxxx
        mac = self.mac_reformat_62to34(interface_mac)
        try:
            self._driver.associate_mac_to_network(self._switch['address'],
                                                  self._switch['username'],
                                                  self._switch['password'],
                                                  vlan_id,
                                                  mac)
        except Exception:
            LOG.exception(
                _LE("Brocade NOS driver: failed to associate mac %s"),
                interface_mac)
            raise Exception(
                _("Brocade switch exception: create_port_postcommit failed"))

        LOG.info(
            _LI("created port (postcommit): port_id=%(port_id)s"
                " network_id=%(network_id)s tenant_id=%(tenant_id)s"),
            {'port_id': port_id,
             'network_id': network_id, 'tenant_id': tenant_id})
Example #40
0
    def _get_driver(self, device):
        """
        Gets the driver based on the firmware version of the device

        :param:device: A dictionary which contains details of all the devices
            parsed from the configuration template
        :raise: Exception
        """
        driver = self._driver_map.get(device)
        if driver is None:
            driver_factory = importutils.import_object(DRIVER_FACTORY)
            device_info = self._devices.get(device)
            address = device_info.get('address')
            try:
                driver = driver_factory.get_driver(device_info)
            except Exception as e:
                LOG.exception(_LE("BrocadeFiNiMechanism:_get_driver failed for"
                                  "device %(host)s: Error = %(error)s"),
                              {'host': address,
                               'error': e.args})
                raise Exception(_("BrocadeFiNiMechanism: "
                                  "Failed to get driver"))
            self._driver_map.update({device: driver})
        return driver
    def delete_network_postcommit(self, mech_context):
        """Delete network which translates to removng portprofile
        from the switch.
        """
        LOG.debug("delete_network_postcommit: called")
        if self.is_flat_network(mech_context.network_segments[0]):
            return

        network = mech_context.current
        network['id']
        vlan_id = network['provider:segmentation_id']
        network['tenant_id']
        try:
            for hostname, v in self._switch_dict.iteritems():
                sw,user,password = v[0]
                self._driver.delete_network(sw,
                                            user,
                                            password,
                                            vlan_id)
        except Exception:
            LOG.exception(_LE("Brocade NOS driver: failed to delete network"))
            raise Exception(
                _("Brocade switch exception, "
                  "delete_network_postcommit failed"))
    def add_router_interface(self, context, router_id, interface_info):
        """creates svi on NOS device and assigns ip addres to SVI."""
        LOG.debug("BrocadeSVIPlugin.add_router_interface on VDX: "
                  "router_id=%(router_id)s "
                  "interface_info=%(interface_info)r",
                  {'router_id': router_id, 'interface_info': interface_info})

        with context.session.begin(subtransactions=True):

            info = super(BrocadeSVIPlugin, self).add_router_interface(
                context, router_id, interface_info)

            port = db.get_port(context.session, info["port_id"])

            # shutting down neutron port to allow NOS to do Arp/Routing
            port['admin_state_up'] = False
            port['port'] = port
            self._core_plugin.update_port(context, info["port_id"], port)

            interface_info = info
            subnet = self._core_plugin._get_subnet(context,
                                                   interface_info["subnet_id"])
            cidr = subnet["cidr"]
            net_addr, net_len = self.net_addr(cidr)
            gateway_ip = subnet["gateway_ip"]
            network_id = subnet['network_id']
            bnet = brocade_db.get_network(context, network_id)
            vlan_id = bnet['vlan']
            gateway_ip_cidr = gateway_ip + '/' + str(net_len)
            LOG.debug("Allocated cidr %(cidr)s from the pool, "
                      "network_id %(net_id)s "
                      "bnet %(bnet)s "
                      "vlan %(vlan_id)d ", {'cidr': gateway_ip_cidr,
                                            'net_id': network_id,
                                            'bnet': bnet,
                                            'vlan_id': int(vlan_id)})
            port_filters = {'network_id': [network_id],
                            'device_owner': [DEVICE_OWNER_ROUTER_INTF]}
            port_count = self._core_plugin.get_ports_count(context,
                                                           port_filters)
            LOG.info(_LI("BrocadeSVIPlugin.add_router_interface ports_count "
                         "%d"),
                     port_count)

            # port count is checked against 2 since the current port is already
            # added to db
            if port_count == 2:
                # This subnet is already part of some router
                # (this is not supported in this version of brocade svi plugin)
                msg = _("BrocadeSVIPlugin: adding redundant router interface "
                        "is not supported")
                LOG.error(msg)
                raise Exception(msg)

        try:
            switch = self._switch
            self._driver.create_svi(switch['address'],
                                    switch['username'],
                                    switch['password'],
                                    switch['rbridge_id'],
                                    vlan_id,
                                    gateway_ip_cidr,
                                    str(router_id))
        except Exception:
            LOG.error(_LE("Failed to create Brocade resources to add router "
                          "interface. info=%(info)s, router_id=%(router_id)s"),
                      {"info": info, "router_id": router_id})
            with excutils.save_and_reraise_exception():
                with context.session.begin(subtransactions=True):
                    self.remove_router_interface(context, router_id,
                                                 interface_info)
        return info
Example #43
0
                  'af31': 26, 'af32': 28, 'af33': 30,
                  'af41': 38, 'af42': 36, 'af43': 38,
                  'cs1': 8, 'cs2': 16, 'cs3': 24,
                  'cs4': 32, 'cs5': 40, 'cs6': 48,
                  'cs7': 56, 'default': 0, 'ef': 46}

LOG = logging.getLogger(__name__)
OBJ_PREFIX_LEN = 8

DEFAULT_TOPOLOGY = []
DEFAULT_LINK = []
DEFAULT_MTU = []
DEFAULT_NATIVE_VLAN = []
DEFAULT_RBRIDGE_RANGE = []
ML2_BROCADE = [cfg.StrOpt('address', default='',
                          help=_('The address of the host to SSH to')),
               cfg.StrOpt('username', default='admin',
                          help=_('The SSH username to use')),
               cfg.StrOpt('password', default='password', secret=True,
                          help=_('The SSH password to use')),
               cfg.StrOpt('bwc_address', default='',
                          help=_('The address of the BWC to SSH to')),
               cfg.StrOpt('bwc_username', default='admin',
                          help=_('The BWC username to use')),
               cfg.StrOpt('bwc_password', default='password', secret=True,
                          help=_('The SSH password to use')),
               cfg.StrOpt('bwc_api_key', default='password', secret=True,
                          help=_('The api_key')),
               cfg.StrOpt('physical_networks', default='',
                          help=_('Allowed physical networks')),
               cfg.BoolOpt('initialize_vcs', default='True',
Example #44
0
from networking_brocade._i18n import _LI
from neutron.plugins.ml2 import driver_api
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import importutils

from networking_brocade.vdx.ml2driver.nos.db import models as brocade_db

LOG = logging.getLogger(__name__)
MECHANISM_VERSION = 1.0
NOS_DRIVER = 'networking_brocade.vdx.ml2driver.nos.nosdriver.NOSdriver'

ML2_BROCADE = [
    cfg.StrOpt('address',
               default='',
               help=_('The address of the host to SSH to')),
    cfg.StrOpt('username', default='admin', help=_('The SSH username to use')),
    cfg.StrOpt('password',
               default='password',
               secret=True,
               help=_('The SSH password to use')),
    cfg.StrOpt('physical_networks',
               default='',
               help=_('Allowed physical networks')),
    cfg.StrOpt('ostype', default='NOS', help=_('OS Type of the switch')),
    cfg.StrOpt('osversion', default='4.0.0', help=_('OS Version number'))
]

cfg.CONF.register_opts(ML2_BROCADE, "ml2_brocade")

Example #45
0
    def add_router_interface(self, context, router_id, interface_info):
        """creates svi on NOS device and assigns ip addres to SVI"""
        LOG.debug(
            "BrocadeSVIPlugin.add_router_interface called: "
            "router_id=%(router_id)s "
            "interface_info=%(interface_info)r", {
                'router_id': router_id,
                'interface_info': interface_info
            })
        with context.session.begin(subtransactions=True):
            info = super(BrocadeSVIPlugin,
                         self).add_router_interface(context, router_id,
                                                    interface_info)
        try:
            port = self._core_plugin._get_port(context, info["port_id"])
            # shutting  down neutron port to allow NOS to do Arp/Routing
            # Propose to community to allow this to do more gracefully
            port.update({"admin_state_up": False})
            interface_info = info
            subnet = self._core_plugin._get_subnet(context,
                                                   interface_info["subnet_id"])
            cidr = subnet["cidr"]
            net_addr, net_len = self.net_addr(cidr)
            gateway_ip = subnet["gateway_ip"]
            network_id = subnet['network_id']
            tenant_id = subnet['tenant_id']
            bnet = brocade_db.get_network(context, network_id)
            vlan_id = bnet['vlan']
            gateway_ip_cidr = gateway_ip + '/' + str(net_len)
            LOG.debug(
                "Allocated cidr (%s) from the pool, network_id(%s)"
                "bnet (%s) vlan (%d) ", gateway_ip_cidr, network_id, bnet,
                int(vlan_id))
            port_filters = {
                'network_id': [network_id],
                'device_owner': [DEVICE_OWNER_ROUTER_INTF]
            }
            port_count = self._core_plugin.get_ports_count(
                context, port_filters)
            LOG.info(
                _LI("BrocadeSVIPlugin.add_router_interface"
                    " ports_count %d"), port_count)
            # port count is checked against 2 since the
            # current port is already added to db
            if port_count == 2:
                # This subnet is already part of some router is not
                # supported
                # in this version of brocadesvi plugin
                LOG.error(
                    _LE("BrocadeSVIPlugin:adding redundent router"
                        "interface is not supported"))
                raise Exception(
                    _("BrocadeSVIPlugin:adding redundent"
                      "router interface is not supported"))
            # res = self._update_ips_for_port(context, port)
            # gateway_ip = res['ip_address']
            # gateway_ip_cidr  = gateway_ip +'/'+str(net_len)
            brocade_db.create_svi(context, router_id, tenant_id, str(vlan_id),
                                  True, gateway_ip, str(net_len))
            self._invoke_nos_driver_api("create_svi", router_id, vlan_id,
                                        gateway_ip_cidr, context, port)
            self._update_firewall(context, vlan_id, tenant_id)

        except Exception:
            LOG.error(
                _LE("Failed to create Brocade resources to add router "
                    "interface. info=%(info)s, router_id=%(router_id)s"), {
                        "info": info,
                        "router_id": router_id
                    })
            with excutils.save_and_reraise_exception():
                self._invoke_nos_driver_api("delete_svi", router_id, vlan_id,
                                            gateway_ip_cidr)
                with context.session.begin(subtransactions=True):
                    info = super(BrocadeSVIPlugin, self).\
                        remove_router_interface(context,
                                                router_id,
                                                interface_info)

        return info
from networking_brocade.vdx.db import models as brocade_db
from networking_brocade.vdx.ml2driver.nos import nosdriver as driver
from neutron.common import constants as l3_constants
from neutron.plugins.ml2 import db
from neutron.services.l3_router import l3_router_plugin as router
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import excutils


DEVICE_OWNER_ROUTER_INTF = l3_constants.DEVICE_OWNER_ROUTER_INTF
DEVICE_OWNER_ROUTER_GW = l3_constants.DEVICE_OWNER_ROUTER_GW
DEVICE_OWNER_FLOATINGIP = l3_constants.DEVICE_OWNER_FLOATINGIP

ML2_BROCADE = [cfg.StrOpt('address', default='',
                          help=_('The address of the host to SSH to')),
               cfg.StrOpt('username', default='admin',
                          help=_('The SSH username to use')),
               cfg.StrOpt('password', default='password', secret=True,
                          help=_('The SSH password to use')),
               cfg.StrOpt('rbridge_id', default=1,
                          help=_('Rbridge id of provider edge router(s)')),
               ]

cfg.CONF.register_opts(ML2_BROCADE, "ml2_brocade")

LOG = logging.getLogger(__name__)


class BrocadeSVIPlugin(router.L3RouterPlugin):
    """Brocade SVI service Plugin."""
Example #47
0
                  'af21': 18, 'af22': 20, 'af23': 22,
                  'af31': 26, 'af32': 28, 'af33': 30,
                  'af41': 38, 'af42': 36, 'af43': 38,
                  'cs1': 8, 'cs2': 16, 'cs3': 24,
                  'cs4': 32, 'cs5': 40, 'cs6': 48,
                  'cs7': 56, 'default': 0, 'ef': 46}

LOG = logging.getLogger(__name__)
OBJ_PREFIX_LEN = 8

DEFAULT_TOPOLOGY = []
DEFAULT_MTU = []
DEFAULT_NATIVE_VLAN = []
DEFAULT_RBRIDGE_RANGE = []
ML2_BROCADE = [cfg.StrOpt('address', default='',
                          help=_('The address of the host to SSH to')),
               cfg.StrOpt('username', default='admin',
                          help=_('The SSH username to use')),
               cfg.StrOpt('password', default='password', secret=True,
                          help=_('The SSH password to use')),
               cfg.StrOpt('physical_networks', default='',
                          help=_('Allowed physical networks')),
               cfg.BoolOpt('initialize_vcs', default='True',
                           help=_('initialize vcs')),
               cfg.StrOpt('ostype', default='NOS',
                          help=_('OS Type of the switch')),
               # cfg.StrOpt('osversion', default='autodetect',
               #    help=_('OS Version number')),
               cfg.IntOpt('nretries', default=5,
                          help=_(
                              'Number of retries when retieable'
from networking_brocade._i18n import _
from networking_brocade._i18n import _LE
from networking_brocade._i18n import _LI
from neutron.plugins.ml2 import driver_api
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import importutils

from networking_brocade.vdx.ml2driver.nos.db import models as brocade_db

LOG = logging.getLogger(__name__)
MECHANISM_VERSION = 1.0
NOS_DRIVER = 'networking_brocade.vdx.ml2driver.nos.nosdriver.NOSdriver'

ML2_BROCADE = [cfg.StrOpt('address', default='',
                          help=_('The address of the host to SSH to')),
               cfg.StrOpt('username', default='admin',
                          help=_('The SSH username to use')),
               cfg.StrOpt('password', default='password', secret=True,
                          help=_('The SSH password to use')),
               cfg.StrOpt('physical_networks', default='',
                          help=_('Allowed physical networks')),
               cfg.StrOpt('ostype', default='NOS',
                          help=_('OS Type of the switch')),
               cfg.StrOpt('osversion', default='4.0.0',
                          help=_('OS Version number'))
               ]

cfg.CONF.register_opts(ML2_BROCADE, "ml2_brocade")

    def add_router_interface(self, context, router_id, interface_info):
        """creates svi on NOS device and assigns ip addres to SVI"""
        LOG.debug("BrocadeSVIPlugin.add_router_interface called: "
                  "router_id=%(router_id)s "
                  "interface_info=%(interface_info)r",
                  {'router_id': router_id, 'interface_info': interface_info})
        with context.session.begin(subtransactions=True):
            info = super(BrocadeSVIPlugin, self).add_router_interface(
                context, router_id, interface_info)
        try:
            port = self._core_plugin._get_port(context, info["port_id"])
            # shutting  down neutron port to allow NOS to do Arp/Routing
            # Propose to community to allow this to do more gracefully
            port.update({"admin_state_up": False})
            interface_info = info
            subnet = self._core_plugin._get_subnet(context,
                                                   interface_info["subnet_id"])
            cidr = subnet["cidr"]
            net_addr, net_len = self.net_addr(cidr)
            gateway_ip = subnet["gateway_ip"]
            network_id = subnet['network_id']
            tenant_id = subnet['tenant_id']
            bnet = brocade_db.get_network(context, network_id)
            vlan_id = bnet['vlan']
            gateway_ip_cidr = gateway_ip + '/' + str(net_len)
            LOG.debug("Allocated cidr (%s) from the pool, network_id(%s)"
                      "bnet (%s) vlan (%d) ", gateway_ip_cidr, network_id,
                      bnet, int(vlan_id))
            port_filters = {'network_id': [network_id],
                            'device_owner': [DEVICE_OWNER_ROUTER_INTF]}
            port_count = self._core_plugin.get_ports_count(context,
                                                           port_filters)
            LOG.info(_LI("BrocadeSVIPlugin.add_router_interface"
                         " ports_count %d"), port_count)
            # port count is checked against 2 since the
            # current port is already added to db
            if port_count == 2:
                # This subnet is already part of some router is not
                # supported
                # in this version of brocadesvi plugin
                LOG.error(_LE("BrocadeSVIPlugin:adding redundent router"
                              "interface is not supported"))
                raise Exception(_("BrocadeSVIPlugin:adding redundent"
                                  "router interface is not supported"))
            # res = self._update_ips_for_port(context, port)
            # gateway_ip = res['ip_address']
            # gateway_ip_cidr  = gateway_ip +'/'+str(net_len)
            brocade_db.create_svi(context, router_id, tenant_id, str(vlan_id),
                                  True, gateway_ip, str(net_len))
            self._invoke_nos_driver_api("create_svi", router_id, vlan_id,
                                        gateway_ip_cidr, context, port)
            self._update_firewall(context, vlan_id, tenant_id)

        except Exception:
            LOG.error(_LE("Failed to create Brocade resources to add router "
                          "interface. info=%(info)s, router_id=%(router_id)s"),
                      {"info": info, "router_id": router_id})
            with excutils.save_and_reraise_exception():
                self._invoke_nos_driver_api("delete_svi", router_id,
                                            vlan_id, gateway_ip_cidr)
                with context.session.begin(subtransactions=True):
                    info = super(BrocadeSVIPlugin, self).\
                        remove_router_interface(context,
                                                router_id,
                                                interface_info)

        return info
    def add_remove_router_interface(self, context, router_id, interface_info,
                                    is_add):
        """
        Add/Remove router interface on NI device

        :param:context: Contains the network details
        :param:router_id: The router ID
        :param:interface_info: Contains interface details
        :param:is_add: True for add operation, False for remove operation.
        :raises: Exception
        """
        operation = None
        method = None
        if is_add is True:
            method = "add_router_interface"
            operation = "Add"
        else:
            method = "remove_router_interface"
            operation = "Remove"
        info = getattr(super(BrocadeRouterPlugin, self),
                       method)(context, router_id, interface_info)
        interface_info = info
        subnet = self._core_plugin._get_subnet(context.elevated(),
                                               interface_info["subnet_id"])
        vlan_id, gateway_ip_cidr = self._get_network_info(context, subnet)
        for device in self._devices:
            device_info = self._devices.get(device)
            address = device_info.get('address')
            driver = self._get_driver(device)
            LOG.info(_LI("BrocadeRouterPlugin:Before %(op)s l3 "
                         "router to vlan %(vlan_id)s with ip %(gatewayip)s"
                         "on device "
                         "%(host)s"), {'op': operation,
                                       'vlan_id': vlan_id,
                                       'gatewayip': gateway_ip_cidr,
                                       'host': address})
            try:
                if is_add is True:
                    getattr(driver, method)(vlan_id, gateway_ip_cidr)
                else:
                    getattr(driver, method)(vlan_id)
            except Exception as e:
                if is_add:
                    method = "remove_router_interface"
                    info = getattr(super(BrocadeRouterPlugin, self),
                                   method)(context, router_id, interface_info)
                LOG.exception(_LE("BrocadeRouterPlugin: failed to"
                                  " %(op)s l3 router interface for "
                                  "device= %(device)s exception : "
                                  "%(error)s"), {'op': operation,
                                                 'device': address,
                                                 'error': e.args})
                raise Exception(
                    _("BrocadeRouterPlugin: %(op)s router "
                      "interface failed"), {'op': operation})
            LOG.info(_LI("BrocadeRouterPlugin:%(op)sed router "
                         "interface in vlan = %(vlan_id)s with ip address"
                         " %(gatewayip)s on device %(host)s "
                         "successful"), {'op': operation,
                                         'vlan_id': vlan_id,
                                         'gatewayip': gateway_ip_cidr,
                                         'host': address})
        return info