Exemplo n.º 1
0
 def _get_data_from_binding_profile(self, context, port):
     if df_const.DF_PORT_BINDING_PROFILE not in port or not attr.is_attr_set(port[df_const.DF_PORT_BINDING_PROFILE]):
         return None, None
     parent_name = port[df_const.DF_PORT_BINDING_PROFILE].get("parent_name")
     tag = port[df_const.DF_PORT_BINDING_PROFILE].get("tag")
     if not any((parent_name, tag)):
         # An empty profile is fine.
         return None, None
     if not all((parent_name, tag)):
         # If one is set, they both must be set.
         msg = _("Invalid binding:profile. parent_name and tag are " "both required.")
         raise n_exc.InvalidInput(error_message=msg)
     if not isinstance(parent_name, six.string_types):
         msg = _('Invalid binding:profile. parent_name "%s" must be ' "a string.") % parent_name
         raise n_exc.InvalidInput(error_message=msg)
     try:
         tag = int(tag)
         if tag < 0 or tag > 4095:
             raise ValueError
     except ValueError:
         msg = _('Invalid binding:profile. tag "%s" must be ' "an int between 1 and 4096, inclusive.") % tag
         raise n_exc.InvalidInput(error_message=msg)
     # Make sure we can successfully look up the port indicated by
     # parent_name.  Just let it raise the right exception if there is a
     # problem.
     self.get_port(context, parent_name)
     return parent_name, tag
Exemplo n.º 2
0
 def _get_data_from_binding_profile(self, context, port):
     if (ovn_const.OVN_PORT_BINDING_PROFILE not in port or
             not attr.is_attr_set(
                 port[ovn_const.OVN_PORT_BINDING_PROFILE])):
         return None, None
     parent_name = (
         port[ovn_const.OVN_PORT_BINDING_PROFILE].get('parent_name'))
     tag = port[ovn_const.OVN_PORT_BINDING_PROFILE].get('tag')
     if not any((parent_name, tag)):
         # An empty profile is fine.
         return None, None
     if not all((parent_name, tag)):
         # If one is set, they both must be set.
         msg = _('Invalid binding:profile. parent_name and tag are '
                 'both required.')
         raise n_exc.InvalidInput(error_message=msg)
     if not isinstance(parent_name, six.string_types):
         msg = _('Invalid binding:profile. parent_name "%s" must be '
                 'a string.') % parent_name
         raise n_exc.InvalidInput(error_message=msg)
     try:
         tag = int(tag)
         if tag < 0 or tag > 4095:
             raise ValueError
     except ValueError:
         # The tag range is defined by ovn-nb.ovsschema.
         # https://github.com/openvswitch/ovs/blob/ovn/ovn/ovn-nb.ovsschema
         msg = _('Invalid binding:profile. tag "%s" must be '
                 'an int between 1 and 4096, inclusive.') % tag
         raise n_exc.InvalidInput(error_message=msg)
     # Make sure we can successfully look up the port indicated by
     # parent_name.  Just let it raise the right exception if there is a
     # problem.
     self.get_port(context, parent_name)
     return parent_name, tag
Exemplo n.º 3
0
    def update_network_precommit(self, context):
        if context.original['name'] != context.current['name']:
            nsx_switch_ids = nsx_utils.get_nsx_switch_ids(
               context._plugin_context.session,
               self.cluster,
               context.current['id']
            )

            if not nsx_switch_ids or len(nsx_switch_ids) < 1:
                 LOG.warn(_("Unable to find NSX mappings for neutron "
                             "network:%s"), context.original['id'])

            try:
                switchlib.update_lswitch(
                    self.cluster,
                    lswitch_ids[0],
                    context.current['name']
                )
            except api_exc.NsxApiException as e:
                 LOG.warn(_("Logical switch update on NSX backend failed. "
                            "Neutron network id:%(net_id)s; "
                            "NSX lswitch id:%(lswitch_id)s;"
                            "Error:%(error)s"),
                            {'net_id': context.current['id'],
                             'lswitch_id': lswitch_ids[0],
                             'error': e})
    def _nsx_delete_port(self, context, port_data):
        # FIXME(salvatore-orlando): On the NSX platform we do not really have
        # external networks. So deleting regular ports from external networks
        # does not make sense. However we cannot raise as this would break
        # unit tests.

        # NOTE(rods): reporting mark's comment on havana version of this patch.
        # Akanda does want ports for external networks so this method is
        # basically same with external check removed

        # ---------------------------------------------------------------------
        # Original code:
        # if self._network_is_external(context, port_data['network_id']):
        #     LOG.info(_("NSX plugin does not support regular VIF ports on "
        #                "external networks. Port %s will be down."),
        #              port_data['network_id'])
        #     return
        # ---------------------------------------------------------------------

        nsx_switch_id, nsx_port_id = nsx_utils.get_nsx_switch_and_port_id(
            context.session, self.cluster, port_data['id'])
        if not nsx_port_id:
            LOG.debug(_("Port '%s' was already deleted on NSX platform"), id)
            return
        # TODO(bgh): if this is a bridged network and the lswitch we just got
        # back will have zero ports after the delete we should garbage collect
        # the lswitch.
        try:
            switchlib.delete_port(self.cluster, nsx_switch_id, nsx_port_id)
            LOG.debug(_("_nsx_delete_port completed for port %(port_id)s "
                        "on network %(net_id)s"),
                      {'port_id': port_data['id'],
                       'net_id': port_data['network_id']})
        except n_exc.NotFound:
            LOG.warning(_("Port %s not found in NSX"), port_data['id'])
Exemplo n.º 5
0
 def _get_data_from_binding_profile(self, context, port):
     if (df_const.DF_PORT_BINDING_PROFILE not in port or
             not attr.is_attr_set(
                 port[df_const.DF_PORT_BINDING_PROFILE])):
         return None, None
     parent_name = (
         port[df_const.DF_PORT_BINDING_PROFILE].get('parent_name'))
     tag = port[df_const.DF_PORT_BINDING_PROFILE].get('tag')
     if not any((parent_name, tag)):
         # An empty profile is fine.
         return None, None
     if not all((parent_name, tag)):
         # If one is set, they both must be set.
         msg = _('Invalid binding:profile. parent_name and tag are '
                 'both required.')
         raise n_exc.InvalidInput(error_message=msg)
     if not isinstance(parent_name, six.string_types):
         msg = _('Invalid binding:profile. parent_name "%s" must be '
                 'a string.') % parent_name
         raise n_exc.InvalidInput(error_message=msg)
     try:
         tag = int(tag)
         if tag < 0 or tag > 4095:
             raise ValueError
     except ValueError:
         msg = _('Invalid binding:profile. tag "%s" must be '
                 'an int between 1 and 4096, inclusive.') % tag
         raise n_exc.InvalidInput(error_message=msg)
     # Make sure we can successfully look up the port indicated by
     # parent_name.  Just let it raise the right exception if there is a
     # problem.
     self.get_port(context, parent_name)
     return parent_name, tag
Exemplo n.º 6
0
 def _validate_binding_profile(self, context):
     # Validate binding:profile if it exists in precommit so that we can
     # fail port creation if the contents are invalid.
     port = context.current
     if ovn_const.OVN_PORT_BINDING_PROFILE not in port:
         return
     parent_name = (
         port[ovn_const.OVN_PORT_BINDING_PROFILE].get('parent_name'))
     tag = port[ovn_const.OVN_PORT_BINDING_PROFILE].get('tag')
     if not any((parent_name, tag)):
         # An empty profile is fine.
         return
     if not all((parent_name, tag)):
         # If one is set, they both must be set.
         msg = _('Invalid binding:profile. parent_name and tag are '
                 'both required.')
         raise n_exc.InvalidInput(error_message=msg)
     if not isinstance(parent_name, six.string_types):
         msg = _('Invalid binding:profile. parent_name "%s" must be '
                 'a string.') % parent_name
         raise n_exc.InvalidInput(error_message=msg)
     if not isinstance(tag, int) or tag < 0 or tag > 4095:
         # The tag range is defined by ovn-nb.ovsschema.
         # https://github.com/openvswitch/ovs/blob/ovn/ovn/ovn-nb.ovsschema
         msg = _('Invalid binding:profile. tag "%s" must be '
                 'an int between 1 and 4096, inclusive.') % tag
         raise n_exc.InvalidInput(error_message=msg)
     # Make sure we can successfully look up the port indicated by
     # parent_name.  Just let it raise the right exception if there is a
     # problem.
     context._plugin.get_port(context._plugin_context, parent_name)
Exemplo n.º 7
0
 def _wait_for_load_balancer_status(cls,
                                    load_balancer_id,
                                    provisioning_status='ACTIVE',
                                    operating_status='ONLINE',
                                    delete=False):
     interval_time = 1
     timeout = 600
     end_time = time.time() + timeout
     lb = {}
     while time.time() < end_time:
         try:
             lb = cls.load_balancers_client.get_load_balancer(
                 load_balancer_id)
             if not lb:
                 # loadbalancer not found
                 if delete:
                     break
                 else:
                     raise Exception(
                         _("loadbalancer {lb_id} not"
                           " found").format(lb_id=load_balancer_id))
             if (lb.get('provisioning_status') == provisioning_status
                     and lb.get('operating_status') == operating_status):
                 break
             time.sleep(interval_time)
         except exceptions.NotFound as e:
             # if wait is for delete operation do break
             if delete:
                 break
             else:
                 # raise original exception
                 raise e
     else:
         if delete:
             raise exceptions.TimeoutException(
                 _("Waited for load balancer {lb_id} to be deleted for "
                   "{timeout} seconds but can still observe that it "
                   "exists.").format(lb_id=load_balancer_id,
                                     timeout=timeout))
         else:
             raise exceptions.TimeoutException(
                 _("Wait for load balancer ran for {timeout} seconds and "
                   "did not observe {lb_id} reach {provisioning_status} "
                   "provisioning status and {operating_status} "
                   "operating status.").format(
                       timeout=timeout,
                       lb_id=load_balancer_id,
                       provisioning_status=provisioning_status,
                       operating_status=operating_status))
     return lb
Exemplo n.º 8
0
def allocate_edge_vnic_with_tunnel_index(session, edge_id, network_id):
    """Allocate an avaliable edge vnic with tunnel index to network."""

    # TODO(berlin): temporary solution to let metadata and dhcp use
    # different vnics
    net_list = get_nsxv_internal_network(
        session, constants.InternalEdgePurposes.INTER_EDGE_PURPOSE)
    metadata_net_id = net_list[0]['network_id'] if net_list else None

    with session.begin(subtransactions=True):
        query = session.query(nsxv_models.NsxvEdgeVnicBinding)
        query = query.filter(
            nsxv_models.NsxvEdgeVnicBinding.edge_id == edge_id,
            nsxv_models.NsxvEdgeVnicBinding.network_id == expr.null())
        if metadata_net_id:
            vnic_binding = get_edge_vnic_binding(
                session, edge_id, metadata_net_id)
            if vnic_binding:
                vnic_index = vnic_binding.vnic_index
                query = query.filter(
                    nsxv_models.NsxvEdgeVnicBinding.vnic_index != vnic_index)

        binding = query.first()
        if not binding:
            msg = (_("Failed to allocate one available vnic on edge_id: "
                     ":%(edge_id)s to network_id: %(network_id)s") %
                   {'edge_id': edge_id, 'network_id': network_id})
            LOG.exception(msg)
            raise nsx_exc.NsxPluginException(err_msg=msg)
        binding['network_id'] = network_id
        session.add(binding)
        session.flush()
    return binding
Exemplo n.º 9
0
    def create_network_precommit(self, context):
        """Add a network to NSX

        This method does not handle provider networks correctly and
        is out-of-scope for now.
        """
        net_data = context.current

        if net_data['admin_state_up'] is False:
             LOG.warning(_("Network with admin_state_up=False are not yet "
                           "supported by this plugin. Ignoring setting for "
                           "network %s"), net_data.get('name', '<unknown>'))

        transport_zone_config = self._convert_to_transport_zones(net_data)

        nsx_switch = switchlib.create_lswitch(
            self.cluster,
            net_data['id'],
            net_data['tenant_id'],
            net_data.get('name'),
            transport_zone_config,
            shared=bool(net_data.get('shared'))
        )

        nsx_db.add_neutron_nsx_network_mapping(
           context._plugin_context.session,
           net_data['id'],
           nsx_switch['uuid']
        )
Exemplo n.º 10
0
    def update_port_postcommit(self, context):
        try:
            dvs = self._lookup_dvs_for_context(context.network)
        except exceptions.NotSupportedNetworkType as e:
            LOG.info(
                _LI("Port %(id)s not updated. Reason: %(reason)s") % {"id": context.current["id"], "reason": e.message}
            )
        except exceptions.NoDVSForPhysicalNetwork:
            raise exceptions.InvalidSystemState(
                details=_(
                    "Port %(port_id)s belong to VMWare VM, but there is no " "mapping from network %(net_id)s to DVS."
                )
                % {"port_id": context.current["id"], "net_id": context.network.current["id"]}
            )
        else:
            self._update_admin_state_up(dvs, context)

            force = context.original["status"] == n_const.PORT_STATUS_DOWN
            # self._update_security_groups(dvs, context, force=force)
            if (
                context.current["binding:vif_type"] == "unbound"
                and context.current["status"] == n_const.PORT_STATUS_DOWN
            ):
                context._plugin.update_port_status(
                    context._plugin_context, context.current["id"], n_const.PORT_STATUS_ACTIVE
                )
Exemplo n.º 11
0
class DragonflowException(Exception):
    """Base Dragonflow Exception.

    To correctly use this class, inherit from it and define
    a 'message' property. That message will get printf'd
    with the keyword arguments provided to the constructor.
    """
    message = _("An unknown exception occurred.")

    def __init__(self, **kwargs):
        try:
            super(DragonflowException, self).__init__(self.message % kwargs)
            self.msg = self.message % kwargs
        except Exception:
            with excutils.save_and_reraise_exception() as ctxt:
                if not self.use_fatal_exceptions():
                    ctxt.reraise = False
                    # at least get the core message out if something happened
                    super(DragonflowException, self).__init__(self.message)

    if six.PY2:
        def __unicode__(self):
            return unicode(self.msg)

    def __str__(self):
        return self.msg

    def use_fatal_exceptions(self):
        return False
Exemplo n.º 12
0
 def delete_lswitch(self, lswitch_name=None, ext_id=None, if_exists=True):
     if (lswitch_name is not None):
         return cmd.DelLSwitchCommand(self, lswitch_name, if_exists)
     else:
         raise RuntimeError(
             _("Currently only supports delete "
               "by lswitch-name"))
Exemplo n.º 13
0
 def delete_lport(self, lport_name=None, lswitch=None,
                  ext_id=None, if_exists=True):
     if (lport_name is not None):
         return cmd.DelLogicalPortCommand(self, lport_name,
                                          lswitch, if_exists)
     else:
         raise RuntimeError(_("Currently only supports "
                              "delete by lport-name"))
Exemplo n.º 14
0
 def _restore_firewall_action(self, action):
     if action == VSE_FWAAS_ALLOW:
         return FWAAS_ALLOW
     elif action == VSE_FWAAS_DENY:
         return FWAAS_DENY
     else:
         msg = _("Invalid action value %s in " "a vshield firewall rule") % action
         raise vcns_exc.VcnsBadRequest(resource="firewall_rule", msg=msg)
Exemplo n.º 15
0
 def insert_rule(self, context, rule_info, edge_id, fwr):
     if rule_info.get("insert_before"):
         self._add_rule_above(context, rule_info["insert_before"], edge_id, fwr)
     elif rule_info.get("insert_after"):
         self._add_rule_below(context, rule_info["insert_after"], edge_id, fwr)
     else:
         msg = _("Can't execute insert rule operation " "without reference rule_id")
         raise vcns_exc.VcnsBadRequest(resource="firewall_rule", msg=msg)
Exemplo n.º 16
0
 def _convert_firewall_action(self, action):
     if action == FWAAS_ALLOW:
         return VSE_FWAAS_ALLOW
     elif action == FWAAS_DENY:
         return VSE_FWAAS_DENY
     else:
         msg = _("Invalid action value %s in a firewall rule") % action
         raise vcns_exc.VcnsBadRequest(resource='firewall_rule', msg=msg)
Exemplo n.º 17
0
    def create_floatingip(self, context, floatingip):
        LOG.debug('create_floatingip %s', (floatingip,))
        fip = floatingip['floatingip']
        tenant_id = self._get_tenant_id_for_create(context, fip)
        fip_id = uuidutils.generate_uuid()

        f_net_id = fip['floating_network_id']
        if not self._core_plugin._network_is_external(context, f_net_id):
            msg = _("Network %s is not a valid external network") % f_net_id
            raise q_exc.BadRequest(resource='floatingip', msg=msg)

        # NOTE(dhellmann): Custom
        #
        # FIXME(dhellmann): This should probably verify that the subnet
        # being used is on the network the user requested.
        ip_to_use = self._allocate_floatingip_from_configured_subnets(context)

        with context.session.begin(subtransactions=True):
            # This external port is never exposed to the tenant.
            # it is used purely for internal system and admin use when
            # managing floating IPs.
            external_port = self._core_plugin.create_port(context.elevated(), {
                'port':
                {'tenant_id': '',  # tenant intentionally not set
                 'network_id': f_net_id,
                 'mac_address': attributes.ATTR_NOT_SPECIFIED,
                 # NOTE(dhellmann): Custom
                 'fixed_ips': [ip_to_use],
                 'admin_state_up': True,
                 'device_id': fip_id,
                 'device_owner': DEVICE_OWNER_FLOATINGIP,
                 'name': ''}})
            # Ensure IP addresses are allocated on external port
            if not external_port['fixed_ips']:
                raise q_exc.ExternalIpAddressExhausted(net_id=f_net_id)

            floating_fixed_ip = external_port['fixed_ips'][0]
            floating_ip_address = floating_fixed_ip['ip_address']
            floatingip_db = FloatingIP(
                id=fip_id,
                tenant_id=tenant_id,
                floating_network_id=fip['floating_network_id'],
                floating_ip_address=floating_ip_address,
                floating_port_id=external_port['id'])
            fip['tenant_id'] = tenant_id
            # Update association with internal port
            # and define external IP address
            self._update_fip_assoc(context, fip,
                                   floatingip_db, external_port)
            context.session.add(floatingip_db)

        router_id = floatingip_db['router_id']
        if router_id:
            self.l3_rpc_notifier.routers_updated(
                context, [router_id],
                'create_floatingip')
        return self._make_floatingip_dict(floatingip_db)
Exemplo n.º 18
0
 def _create_load_balancer(cls, wait=True, **lb_kwargs):
     try:
         lb = cls.load_balancers_client.create_load_balancer(**lb_kwargs)
         if wait:
             cls._wait_for_load_balancer_status(lb.get('id'))
     except Exception:
         raise Exception(_("Failed to create load balancer..."))
     cls._lbs_to_delete.append(lb.get('id'))
     return lb
Exemplo n.º 19
0
 def _create_load_balancer(cls, wait=True, **lb_kwargs):
     try:
         lb = cls.load_balancers_client.create_load_balancer(**lb_kwargs)
         if wait:
             cls._wait_for_load_balancer_status(lb.get('id'))
     except Exception:
         raise Exception(_("Failed to create load balancer..."))
     cls._lbs_to_delete.append(lb.get('id'))
     return lb
Exemplo n.º 20
0
def get_nsxv_edge_firewallrule_binding_by_vseid(
        session, edge_id, rule_vseid):
    with session.begin(subtransactions=True):
        try:
            return (session.query(nsxv_models.NsxvEdgeFirewallRuleBinding).
                    filter_by(edge_id=edge_id, rule_vseid=rule_vseid).one())
        except exc.NoResultFound:
            msg = _("Rule Resource binding not found!")
            raise nsx_exc.NsxPluginException(err_msg=msg)
Exemplo n.º 21
0
    def run_idl(self, txn):
        try:
            port = idlutils.row_by_value(self.api.idl, 'Logical_Port',
                                         'name', self.lport)
        except idlutils.RowNotFound:
            msg = _("Logical Port %s does not exist") % self.lport
            raise RuntimeError(msg)
        try:
            lrouter_port = idlutils.row_by_value(self.api.idl,
                                                 'Logical_Router_Port',
                                                 'name', self.lport)
        except idlutils.RowNotFound:
            msg = _("Logical Router Port %s does not exist") % self.lport
            raise RuntimeError(msg)

        options = {'router-port': str(lrouter_port.uuid)}
        setattr(port, 'options', options)
        setattr(port, 'type', 'router')
Exemplo n.º 22
0
 def _get_tenant_id_for_create(self, context, resource):
     if context.is_admin and 'tenant_id' in resource:
         tenant_id = resource['tenant_id']
     elif ('tenant_id' in resource
           and resource['tenant_id'] != context.tenant_id):
         reason = _('Cannot create resource for another tenant')
         raise n_exc.AdminRequired(reason=reason)
     else:
         tenant_id = context.tenant_id
     return tenant_id
 def remove_port_filter(self, port):
     LOG.debug("OFW Removing device (%s) filter: %s", port['device'],
               port)
     if not self._filtered_ports.get(port['device']):
         LOG.info(_('Attempted to remove port filter which is not '
                    'filtered %r'), port)
         return
     self._remove_flows(port)
     self._filtered_ports.pop(port['device'])
     self._filtered_in_ports.pop(port['device'])
Exemplo n.º 24
0
 def load(self, *args, **kwargs):
     for app in self.apps_list:
         app_class_name = self.apps_location_prefix + "." + app
         try:
             app_class = importutils.import_class(app_class_name)
             app = app_class(*args, **kwargs)
             self.apps.append(app)
         except ImportError as e:
             LOG.exception(_LE("Error loading application by class, %s"), e)
             raise ImportError(_("Application class not found."))
Exemplo n.º 25
0
 def _wait_for_load_balancer_status(cls, load_balancer_id,
                                    provisioning_status='ACTIVE',
                                    operating_status='ONLINE',
                                    delete=False):
     interval_time = 10
     timeout = 300
     end_time = time.time() + timeout
     lb = {}
     while time.time() < end_time:
         try:
             lb = cls.load_balancers_client.get_load_balancer(
                 load_balancer_id)
             if not lb:
                     # loadbalancer not found
                 if delete:
                     break
                 else:
                     raise Exception(
                         _("loadbalancer {lb_id} not"
                           " found").format(
                               lb_id=load_balancer_id))
             if (lb.get('provisioning_status') == provisioning_status and
                     lb.get('operating_status') == operating_status):
                 break
             time.sleep(interval_time)
         except exceptions.NotFound as e:
             # if wait is for delete operation do break
             if delete:
                 break
             else:
                 # raise original exception
                 raise e
     else:
         raise Exception(
             _("Wait for load balancer ran for {timeout} seconds and did "
               "not observe {lb_id} reach {provisioning_status} "
               "provisioning status and {operating_status} "
               "operating status.").format(
                   timeout=timeout,
                   lb_id=load_balancer_id,
                   provisioning_status=provisioning_status,
                   operating_status=operating_status))
     return lb
Exemplo n.º 26
0
    def run_idl(self, txn):
        try:
            port = idlutils.row_by_value(self.api.idl, 'Logical_Port', 'name',
                                         self.lport)
        except idlutils.RowNotFound:
            msg = _("Logical Port %s does not exist") % self.lport
            LOG.error(msg)
            raise RuntimeError(msg)

        for col, val in self.columns.items():
            setattr(port, col, val)
Exemplo n.º 27
0
    def run_idl(self, txn):
        try:
            port = idlutils.row_by_value(self.api.idl, 'Logical_Port',
                                         'name', self.lport)
        except idlutils.RowNotFound:
            msg = _("Logical Port %s does not exist") % self.lport
            LOG.error(msg)
            raise RuntimeError(msg)

        for col, val in self.columns.items():
            setattr(port, col, val)
Exemplo n.º 28
0
    def run_idl(self, txn):
        try:
            lswitch = idlutils.row_by_value(self.api.idl, 'Logical_Switch',
                                            'name', self.name)
        except idlutils.RowNotFound:
            if self.if_exists:
                return
            msg = _("Logical Switch %s does not exist") % self.name
            raise RuntimeError(msg)

        self.api._tables['Logical_Switch'].rows[lswitch.uuid].delete()
Exemplo n.º 29
0
 def delete_port_postcommit(self, context):
     try:
         dvs = self._lookup_dvs_for_context(context.network)
     except exceptions.NoDVSForPhysicalNetwork:
         raise exceptions.InvalidSystemState(details=_(
             'Port %(port_id)s belong to VMWare VM, but there is no '
             'mapping from network %(net_id)s to DVS.') % {
                 'port_id': context.current['id'],
                 'net_id': context.network.current['id']})
     self._update_security_groups(dvs, context, force=True)
     dvs.release_port(context.current)
Exemplo n.º 30
0
    def run_idl(self, txn):
        try:
            lport = idlutils.row_by_value(self.api.idl, 'Logical_Port',
                                          'name', self.lport)
        except idlutils.RowNotFound:
            if self.if_exists:
                return
            msg = _("Port %s does not exist") % self.lport
            LOG.error(msg)
            raise RuntimeError(msg)

        self.api._tables['Logical_Port'].rows[lport.uuid].delete()
Exemplo n.º 31
0
    def run_idl(self, txn):
        try:
            lrouter_port = idlutils.row_by_value(self.api.idl,
                                                 'Logical_Router_Port',
                                                 'name', self.name)
        except idlutils.RowNotFound:
            if self.if_exists:
                return
            msg = _("Logical Router Port %s does not exist") % self.name
            raise RuntimeError(msg)
        try:
            lrouter = idlutils.row_by_value(self.api.idl, 'Logical_Router',
                                            'name', self.lrouter)
        except idlutils.RowNotFound:
            msg = _("Logical Router %s does not exist") % self.lrouter
            raise RuntimeError(msg)

        lrouter_ports = getattr(lrouter, 'ports', [])
        if (lrouter_port in lrouter_ports):
            lrouter_ports.remove(lrouter_port)
            setattr(lrouter, 'ports', lrouter_ports)
Exemplo n.º 32
0
 def delete_lport(self,
                  lport_name=None,
                  lswitch=None,
                  ext_id=None,
                  if_exists=True):
     if (lport_name is not None):
         return cmd.DelLogicalPortCommand(self, lport_name, lswitch,
                                          if_exists)
     else:
         raise RuntimeError(
             _("Currently only supports "
               "delete by lport-name"))
Exemplo n.º 33
0
    def run_idl(self, txn):
        try:
            lrouter = idlutils.row_by_value(self.api.idl, 'Logical_Router',
                                            'name', self.name)
        except idlutils.RowNotFound:
            if self.if_exists:
                return
            msg = _("Logical Router %s does not exist") % self.name
            LOG.error(msg)
            raise RuntimeError(msg)

        self.api._tables['Logical_Router'].rows[lrouter.uuid].delete()
Exemplo n.º 34
0
    def run_idl(self, txn):
        try:
            lswitch = idlutils.row_by_value(self.api.idl, 'Logical_Switch',
                                            'name', self.name)
        except idlutils.RowNotFound:
            if self.if_exists:
                return
            msg = _("Logical Switch %s does not exist") % self.name
            LOG.error(msg)
            raise RuntimeError(msg)

        self.api._tables['Logical_Switch'].rows[lswitch.uuid].delete()
Exemplo n.º 35
0
 def update_port_postcommit(self, current, original, segment):
     try:
         dvs = self._lookup_dvs_for_context(segment)
         if current['id'] in self.booked_ports:
             self.added_ports.add(current['id'])
             self.booked_ports.discard(current['id'])
     except exceptions.NoDVSForPhysicalNetwork:
         raise exceptions.InvalidSystemState(details=_(
             'Port %(port_id)s belong to VMWare VM, but there is '
             'no mapping from network to DVS.') % {'port_id': current['id']}
         )
     else:
         self._update_admin_state_up(dvs, original, current)
Exemplo n.º 36
0
    def run_idl(self, txn):
        try:
            lswitch = idlutils.row_by_value(self.api.idl, 'Logical_Switch',
                                            'name', self.name)

        except idlutils.RowNotFound:
            if self.if_exists:
                return
            msg = _("Logical Switch %s does not exist") % self.name
            raise RuntimeError(msg)

        external_ids = getattr(lswitch, 'external_ids', {})
        external_ids[self.field] = self.value
        lswitch.external_ids = external_ids
Exemplo n.º 37
0
 def remove_port_filter(self, port):
     LOG.debug("OFW Removing device (%s) filter: %s", port['device'], port)
     if not self._filtered_ports.get(port['device']):
         LOG.info(
             _('Attempted to remove port filter which is not '
               'filtered %r'), port)
         return
     vif_port = self._int_br_not_deferred.get_vif_port_by_id(port['device'])
     if not vif_port:
         LOG.info(
             _LW("Port %(port_id)s not present in bridge. Skip"
                 "applying rules for this port"), {'port_id': port})
     self._remove_flows(port, vif_port)
     self._filtered_ports.pop(port['device'])
Exemplo n.º 38
0
    def run_idl(self, txn):
        try:
            lrouter = idlutils.row_by_value(self.api.idl, 'Logical_Router',
                                            'name', self.name, None)
        except idlutils.RowNotFound:
            if self.if_exists:
                return
            msg = _("Logical Router %s does not exist") % self.name
            raise RuntimeError(msg)

        if lrouter:
            for col, val in self.columns.items():
                setattr(lrouter, col, val)
            return
Exemplo n.º 39
0
    def run_idl(self, txn):
        try:
            lswitch = idlutils.row_by_value(self.api.idl, 'Logical_Switch',
                                            'name', self.lswitch_name)
        except idlutils.RowNotFound:
            msg = _("Logical Switch %s does not exist") % self.lswitch_name
            LOG.error(msg)
            raise RuntimeError(msg)

        row = txn.insert(self.api._tables['ACL'])
        row.lswitch = lswitch
        row.priority = self.priority
        row.match = self.match
        row.action = self.action
        row.external_ids = self.ext_ids_dict
Exemplo n.º 40
0
    def load(self):
        app_mgr = AppManager.get_instance()
        self.open_flow_app = app_mgr.instantiate(OFPHandler, None, None)
        self.open_flow_app.start()

        for app in self.apps_list:
            app_class_name = self.apps_location_prefix + "." + app
            try:
                app_class = importutils.import_class(app_class_name)
                app = app_mgr.instantiate(app_class, None, **self.params)
                app.start()
                self.apps.append(app)
            except ImportError as e:
                LOG.exception(_LE("Error loading application by class, %s"), e)
                raise ImportError(_("Application class not found."))
 def remove_port_filter(self, port):
     LOG.debug("OFW Removing device (%s) filter: %s", port['device'],
               port)
     if not self._filtered_ports.get(port['device']):
         LOG.info(_('Attempted to remove port filter which is not '
                    'filtered %r'), port)
         return
     vif_port = self._int_br_not_deferred.get_vif_port_by_id(
         port['device'])
     if not vif_port:
         LOG.info(_LW("Port %(port_id)s not present in bridge. Skip"
                      "applying rules for this port"),
                  {'port_id': port})
     self._remove_flows(port, vif_port)
     self._filtered_ports.pop(port['device'])
Exemplo n.º 42
0
    def load(self):
        app_mgr = AppManager.get_instance()
        self.open_flow_app = app_mgr.instantiate(OFPHandler, None, None)
        self.open_flow_app.start()

        for app in self.apps_list:
            app_class_name = self.apps_location_prefix + "." + app
            try:
                app_class = importutils.import_class(app_class_name)
                app = app_mgr.instantiate(app_class, None, **self.params)
                app.start()
                self.apps.append(app)
            except ImportError as e:
                LOG.exception(_LE("Error loading application by class, %s"), e)
                raise ImportError(_("Application class not found."))
Exemplo n.º 43
0
 def delete_port_postcommit(self, current, original, segment):
     try:
         dvs = self._lookup_dvs_for_context(segment)
     except exceptions.NoDVSForPhysicalNetwork:
         raise exceptions.InvalidSystemState(details=_(
             'Port %(port_id)s belong to VMWare VM, but there is '
             'no mapping from network to DVS.') % {'port_id': current['id']}
         )
     else:
         if sg_rpc.is_firewall_enabled():
             key = current.get(
                 'binding:vif_details', {}).get('dvs_port_key')
             if key:
                 dvs.remove_block(key)
         else:
             dvs.release_port(current)
Exemplo n.º 44
0
 def delete_port_postcommit(self, current, original, segment, sg_info):
     try:
         dvs = self._lookup_dvs_for_context(segment)
     except exceptions.NotSupportedNetworkType as e:
         LOG.info(
             _LI('Port %(id)s not deleted. Reason: %(reason)s') % {
                 'id': current['id'],
                 'reason': e.message
             })
     except exceptions.NoDVSForPhysicalNetwork:
         raise exceptions.InvalidSystemState(
             details=_('Port %(port_id)s belong to VMWare VM, but there is '
                       'no mapping from network to DVS.') %
             {'port_id': current['id']})
     else:
         # TODO SlOPS: update security groups on girect call
         dvs.release_port(current)
Exemplo n.º 45
0
    def run_idl(self, txn):
        try:
            lport = idlutils.row_by_value(self.api.idl, 'Logical_Port', 'name',
                                          self.lport)
            lswitch = idlutils.row_by_value(self.api.idl, 'Logical_Switch',
                                            'name', self.lswitch)
            ports = getattr(lswitch, 'ports', [])
        except idlutils.RowNotFound:
            if self.if_exists:
                return
            msg = _("Port %s does not exist") % self.lport
            LOG.error(msg)
            raise RuntimeError(msg)

        ports.remove(lport)
        lswitch.verify('ports')
        setattr(lswitch, 'ports', ports)
        self.api._tables['Logical_Port'].rows[lport.uuid].delete()
Exemplo n.º 46
0
    def update_port_filter(self, port):
        LOG.debug("OFW Updating device (%s) filter: %s", port['device'], port)
        if port['device'] not in self._filtered_ports:
            LOG.info(
                _('Attempted to update port filter which is not '
                  'filtered %s'), port['device'])
            return

        old_port = self._filtered_ports[port['device']]
        vif_port = self._int_br_not_deferred.get_vif_port_by_id(port['device'])
        if not vif_port:
            LOG.info(
                _LW("Port %(port_id)s not present in bridge. Skip"
                    "applying rules for this port"), {'port_id': port})
        port['vinfo'] = self._vif_port_info(vif_port.port_name)
        self._filtered_ports[port['device']] = port
        self._remove_flows(old_port, vif_port)
        self._add_base_flows(port, vif_port)
        self.known_in_port_for_device[port['device']] = vif_port.ofport
Exemplo n.º 47
0
 def update_port_postcommit(self, current, original, segment, sg_info):
     try:
         dvs = self._lookup_dvs_for_context(segment)
         if current['id'] in self.booked_ports:
             self.added_ports.add(current['id'])
             self.booked_ports.discard(current['id'])
     except exceptions.NotSupportedNetworkType as e:
         LOG.info(
             _LI('Port %(id)s not updated. Reason: %(reason)s') % {
                 'id': current['id'],
                 'reason': e.message
             })
     except exceptions.NoDVSForPhysicalNetwork:
         raise exceptions.InvalidSystemState(
             details=_('Port %(port_id)s belong to VMWare VM, but there is '
                       'no mapping from network to DVS.') %
             {'port_id': current['id']})
     else:
         self._update_admin_state_up(dvs, original, current)
Exemplo n.º 48
0
def create_agent_config_map(config):
    """Create a map of agent config parameters.

    :param config: an instance of cfg.CONF
    :returns: a map of agent configuration parameters
    """
    try:
        bridge_mappings = utils.parse_mappings(config.ML2_VMWARE.network_maps)
    except ValueError as e:
        raise ValueError(_("Parsing network_maps failed: %s.") % e)

    kwargs = dict(
        vsphere_hostname=config.ML2_VMWARE.vsphere_hostname,
        vsphere_login=config.ML2_VMWARE.vsphere_login,
        vsphere_password=config.ML2_VMWARE.vsphere_password,
        bridge_mappings=bridge_mappings,
        polling_interval=config.AGENT.polling_interval,
        quitting_rpc_timeout=config.AGENT.quitting_rpc_timeout,
    )
    return kwargs
Exemplo n.º 49
0
    def run_idl(self, txn):
        try:

            lrouter = idlutils.row_by_value(self.api.idl, 'Logical_Router',
                                            'name', self.lrouter)
            lswitch = idlutils.row_by_value(self.api.idl, 'Logical_Switch',
                                            'name', self.lswitch)
            lrouter_ports = getattr(lrouter, 'ports', [])

            lrouter_port = idlutils.row_by_value(self.api.idl,
                                                 'Logical_Router_Port', 'name',
                                                 self.name)
        except idlutils.RowNotFound:
            if self.if_exists:
                return
            msg = _("Logical Router Port %s does not exist") % self.name
            LOG.error(msg)
            raise RuntimeError(msg)

        lrouter_ports.remove(lrouter_port)
        setattr(lrouter, 'ports', lrouter_ports)
        setattr(lswitch, 'router_port', [])
Exemplo n.º 50
0
 def _ip_version_from_address(ip_string):
     ipv4_pattern = \
         "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}" \
         "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
     ipv6_pattern = "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"
     ipv6_pattern_hexcompressed = \
         "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]" \
         "{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$"
     ipv6_pattern_hex4dec = \
         "^((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]" \
         "\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\z"
     ipv6_pattern_hex4deccompressed = \
         "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]" \
         "{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]" \
         "\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$"
     if re.search(ipv4_pattern, ip_string):
         return constants.IPv4
     if re.search(ipv6_pattern, ip_string) or \
             re.search(ipv6_pattern_hexcompressed, ip_string) or \
             re.search(ipv6_pattern_hex4dec, ip_string) or \
             re.search(ipv6_pattern_hex4deccompressed, ip_string):
         return constants.IPv6
     raise ValueError(_('Illegal IP string address'))
Exemplo n.º 51
0
    def run_idl(self, txn):
        try:
            lswitch = idlutils.row_by_value(self.api.idl, 'Logical_Switch',
                                            'name', self.lswitch)
            ports = getattr(lswitch, 'ports', [])
        except idlutils.RowNotFound:
            msg = _("Logical Switch %s does not exist") % self.lswitch
            LOG.error(msg)
            raise RuntimeError(msg)
        if self.may_exist:
            port = idlutils.row_by_value(self.api.idl, 'Logical_Port', 'name',
                                         self.lport, None)
            if port:
                return

        port = txn.insert(self.api._tables['Logical_Port'])
        port.name = self.lport
        for col, val in self.columns.items():
            setattr(port, col, val)
        # add the newly created port to exiting lswitch
        ports.append(port.uuid)
        setattr(lswitch, 'ports', ports)
        lswitch.verify('ports')
Exemplo n.º 52
0
class VMNotFound(ResourceNotFound):
    message = _('Virtual machine not found')
Exemplo n.º 53
0
class DVSNotFound(ResourceNotFound):
    message = _('Distributed Virtual Switch %(dvs_name)s not found')
Exemplo n.º 54
0
class ResourceInUse(VMWareDVSException):
    message = _('The resource %(resource)s is in use')
Exemplo n.º 55
0
class PortGroupNotFound(ResourceNotFound):
    message = _('Port Group %(pg_name)s not found')
Exemplo n.º 56
0
class PortNotFound(ResourceNotFound):
    message = _('Port %(id)s not found')
Exemplo n.º 57
0
class UnboundPortNotFound(ResourceNotFound):
    message = _('Unbound port not found')
Exemplo n.º 58
0
class HypervisorNotFound(ResourceNotFound):
    message = _('Hypervisor not found')
Exemplo n.º 59
0
class NoDVSForPhysicalNetwork(VMWareDVSException):
    message = _('No dvs mapped for physical network: %(physical_network)s')