Beispiel #1
0
def validate_network_mapping_list_without_seg_id_validation(
        network_mapping, check_vlan):
    """Validate network mapping list in connection."""
    if network_mapping.get('segmentation_id'):
        if check_vlan:
            raise exceptions.InvalidInput(
                error_message=_("default segmentation_id should not be"
                                " provided when segmentation_id is assigned"
                                " during l2gateway creation"))
        # This method doen't check segmentation id range.

    if not network_mapping.get('segmentation_id'):
        if check_vlan is False:
            raise exceptions.InvalidInput(
                error_message=_("Segmentation id must be specified in create "
                                "l2gateway connections"))
    network_id = network_mapping.get(l2gw_const.NETWORK_ID)
    if not network_id:
        raise exceptions.InvalidInput(
            error_message=_("A valid network identifier must be specified "
                            "when connecting a network to a network "
                            "gateway. Unable to complete operation"))
    connection_attrs = set(network_mapping.keys())
    if not connection_attrs.issubset(
            l2gw_validators.ALLOWED_CONNECTION_ATTRIBUTES):
        raise exceptions.InvalidInput(
            error_message=(_("Invalid keys found among the ones provided "
                             "in request : %(connection_attrs)s."),
                           connection_attrs))
    return network_id
def validate_network_mapping_list_without_seg_id_validation(network_mapping,
                                                            check_vlan):
    """Validate network mapping list in connection."""
    if network_mapping.get('segmentation_id'):
        if check_vlan:
            raise exceptions.InvalidInput(
                error_message=_("default segmentation_id should not be"
                                " provided when segmentation_id is assigned"
                                " during l2gateway creation"))
        # This method doen't check segmentation id range.

    if not network_mapping.get('segmentation_id'):
        if check_vlan is False:
            raise exceptions.InvalidInput(
                error_message=_("Segmentation id must be specified in create "
                                "l2gateway connections"))
    network_id = network_mapping.get(l2gw_const.NETWORK_ID)
    if not network_id:
        raise exceptions.InvalidInput(
            error_message=_("A valid network identifier must be specified "
                            "when connecting a network to a network "
                            "gateway. Unable to complete operation"))
    connection_attrs = set(network_mapping.keys())
    if not connection_attrs.issubset(l2gw_validators.
                                     ALLOWED_CONNECTION_ATTRIBUTES):
        raise exceptions.InvalidInput(
            error_message=(_("Invalid keys found among the ones provided "
                             "in request : %(connection_attrs)s."),
                           connection_attrs))
    return network_id
    def add_known_arguments(self, parser):
        parser.add_argument(
            '--management-ip',
            dest='management_ip',
            help=_('Management IP to the device. Defaults to None.'))
        parser.add_argument(
            '--management-port',
            dest='management_port',
            help=_('Management port to the device. Defaults to None.'))
        parser.add_argument(
            '--management-protocol',
            dest='management_protocol',
            help=_('Management protocol to manage the device: ovsdb or none. '
                   'If management ip and port are specified, '
                   'defaults to ovsdb. Otherwise to none.'))
        parser.add_argument(
            '--type',
            metavar='<hw_vtep | router_vtep | network_vlan>',
            choices=['hw_vtep', 'router_vtep', 'network_vlan'],
            help=_('Type of the device: hw_vtep, router_vtep or network_vlan. '
                   'Defaults to hw_vtep'))
        parser.add_argument(
            '--resource-id',
            dest='resource_id',
            help=_('Resource UUID or None (for type router_vtep will '
                   'be router UUID and for type network_vlan will be network '
                   'UUID)'))
        add_name_and_tunnel_ips_to_arguments(parser)

        return parser
    def add_known_arguments(self, parser):
        parser.add_argument(
            '--management-ip',
            dest='management_ip',
            help=_('Management IP to the device. Defaults to None.'))
        parser.add_argument(
            '--management-port',
            dest='management_port',
            help=_('Management port to the device. Defaults to None.'))
        parser.add_argument(
            '--management-protocol',
            dest='management_protocol',
            help=_('Management protocol to manage the device: ovsdb or none. '
                   'If management ip and port are specified, '
                   'defaults to ovsdb. Otherwise to none.'))
        parser.add_argument(
            '--type',
            metavar='<hw_vtep | router_vtep | network_vlan>',
            choices=['hw_vtep', 'router_vtep', 'network_vlan'],
            help=_('Type of the device: hw_vtep, router_vtep or network_vlan. '
                   'Defaults to hw_vtep'))
        parser.add_argument(
            '--resource-id',
            dest='resource_id',
            help=_('Resource UUID or None (for type router_vtep will '
                   'be router UUID and for type network_vlan will be network '
                   'UUID)'))
        add_name_and_tunnel_ips_to_arguments(parser)

        return parser
Beispiel #5
0
def validate_gwdevice_list(data, valid_values=None):
    """Validate the list of devices."""

    if not data:
        # Devices must be provided
        msg = _("Cannot create a gateway with an empty device list")
        return msg

    if len(data) > 1:
        # The number of devices must be exactly one
        msg = _("Exactly one device must be specified to create a gateway")
        return msg

    try:
        for device in data:
            err_msg = validators.validate_dict(device, None)
            if err_msg:
                return err_msg

            device_id = device.get('device_id')
            if not device_id:
                msg = _("Cannot create a gateway with an empty device_id")
                return msg

            # Don't accept any interface.  However, when supporting HW VTEPs
            # this must be supported.
            # TODO(RYU): Allow setting segmentation ID in some way
            if device.get('interfaces'):
                msg = _("Interfaces are not allowed in MidoNet L2GW")
                return msg
            device['interfaces'] = []
    except TypeError:
        return (_("%s: provided data are not iterable") %
                validate_gwdevice_list.__name__)
    return None
def validate_gwdevice_list(data, valid_values=None):
    """Validate the list of devices."""

    if not data:
        # Devices must be provided
        msg = _("Cannot create a gateway with an empty device list")
        return msg

    if len(data) > 1:
        # The number of devices must be exactly one
        msg = _("Exactly one device must be specified to create a gateway")
        return msg

    try:
        for device in data:
            err_msg = attributes._validate_dict(device, None)
            if err_msg:
                return err_msg

            device_id = device.get('device_id')
            if not device_id:
                msg = _("Cannot create a gateway with an empty device_id")
                return msg

            # Don't accept any interface.  However, when supporting HW VTEPs
            # this must be supported.
            # TODO(RYU): Allow setting segmentation ID in some way
            if device.get('interfaces'):
                msg = _("Interfaces are not allowed in MidoNet L2GW")
                return msg
            device['interfaces'] = []
    except TypeError:
        return (_("%s: provided data are not iterable") %
                validate_gwdevice_list.__name__)
def is_valid_vxlan_id(seg_id):
    try:
        int_seg_id = int(seg_id)
    except ValueError:
        msg = _("Segmentation id must be a valid integer")
        raise exceptions.InvalidInput(error_message=msg)
    if int_seg_id < 0 or int_seg_id >= constants.MAX_VXLAN_VNI:
        msg = _("Segmentation id is out of range")
        raise exceptions.InvalidInput(error_message=msg)
Beispiel #8
0
def add_common_paramaters_to_arguments(parser):
    parser.add_argument(
        '--enabled',
        metavar='<True | False>',
        choices=['True', 'False'],
        help=_('Enable/disable for the logging. Defaults to False.'))
    parser.add_argument('--description',
                        dest='description',
                        help=_('Description of logging.'))
def add_name_and_tunnel_ips_to_arguments(parser):
    parser.add_argument(
        '--name', dest='name',
        help=_('User defined device name.'))
    parser.add_argument(
        '--tunnel-ip', metavar='TUNNEL_IP',
        action='append', dest='tunnel_ips',
        help=_('IP address on which gateway device originates or '
               'terminates tunnel.'))
Beispiel #10
0
def is_valid_vxlan_id(seg_id):
    try:
        int_seg_id = int(seg_id)
    except ValueError:
        msg = _("Segmentation id must be a valid integer")
        raise exceptions.InvalidInput(error_message=msg)
    if int_seg_id < 0 or int_seg_id >= constants.MAX_VXLAN_VNI:
        msg = _("Segmentation id is out of range")
        raise exceptions.InvalidInput(error_message=msg)
def add_name_and_tunnel_ips_to_arguments(parser):
    parser.add_argument('--name',
                        dest='name',
                        help=_('User defined device name.'))
    parser.add_argument('--tunnel-ip',
                        metavar='TUNNEL_IP',
                        action='append',
                        dest='tunnel_ips',
                        help=_(
                            'IP address on which gateway device originates or '
                            'terminates tunnel.'))
 def add_known_arguments(self, parser):
     super(RemoteMacEntryCreate, self).add_known_arguments(parser)
     parser.add_argument('--mac-address',
                         dest='mac_address',
                         required=True,
                         help=_('Remote MAC address'))
     parser.add_argument('--vtep-address',
                         dest='vtep_address',
                         required=True,
                         help=_('Remote VTEP Tunnel IP'))
     parser.add_argument('--segmentation-id',
                         dest='segmentation_id',
                         required=True,
                         help=_('VNI to be used'))
class ResourceInUseByLoggingResource(nexception.InUse):
    message = _("%(resource_name)s %(resource_id)s %(reason)s")

    def __init__(self, **kwargs):
        if 'reason' not in kwargs:
            kwargs['reason'] = "is in use by logging resource"
        super(ResourceInUseByLoggingResource, self).__init__(**kwargs)
Beispiel #14
0
    def add_known_arguments(self, parser):
        parser.add_argument('name',
                            metavar='NAME',
                            help=_('User defined logging name.'))
        add_common_paramaters_to_arguments(parser)

        return parser
 def get_parser(self, parser):
     parser = super(gw_deviceV20.CreateCommand, self).get_parser(parser)
     parser.add_argument(
         '--mac-address', dest='mac_address',
         required=True,
         help=_('Remote MAC address'))
     parser.add_argument(
         '--vtep-address', dest='vtep_address',
         required=True,
         help=_('Remote VTEP Tunnel IP'))
     parser.add_argument(
         '--segmentation-id', dest='segmentation_id',
         required=True,
         help=_('VNI to be used'))
     self.add_known_arguments(parser)
     return parser
class BgpSpeakerInUse(nexception.InUse):
    message = _("Bgp speaker %(id)s %(reason)s")

    def __init__(self, **kwargs):
        if 'reason' not in kwargs:
            kwargs['reason'] = "is still associated with bgp peers"
        super(BgpSpeakerInUse, self).__init__(**kwargs)
Beispiel #17
0
class GatewayDeviceInUse(nexception.InUse):
    message = _("Gateway device %(id)s %(reason)s")

    def __init__(self, **kwargs):
        if 'reason' not in kwargs:
            kwargs['reason'] = "is in use by l2 gateway"
        super(GatewayDeviceInUse, self).__init__(**kwargs)
Beispiel #18
0
class GatewayDeviceParamDuplicate(nexception.InUse):
    message = _("%(param_name)s %(param_value)s %(reason)s")

    def __init__(self, **kwargs):
        if 'reason' not in kwargs:
            kwargs['reason'] = "is already used"
        super(GatewayDeviceParamDuplicate, self).__init__(**kwargs)
class MidonetBgpPeerInUse(nexception.InUse):
    message = _("bgp peer %(id)s %(reason)s")

    def __init__(self, **kwargs):
        if 'reason' not in kwargs:
            kwargs['reason'] = "is already associated with bgp speaker"
        super(MidonetBgpPeerInUse, self).__init__(**kwargs)
Beispiel #20
0
class DeviceInUseByGatewayDevice(nexception.InUse):
    message = _("device %(resource_id)s (%(resource_type)s) %(reason)s")

    def __init__(self, **kwargs):
        if 'reason' not in kwargs:
            kwargs['reason'] = "is in use by gateway device"
        super(DeviceInUseByGatewayDevice, self).__init__(**kwargs)
Beispiel #21
0
def add_known_arguments(self, parser):
    parser.add_argument(
        '--device',
        metavar='device_id=DEVICE_ID,segmentaion_id=SEGMENTAION_ID',
        action='append',
        dest='devices',
        type=helpers.str2dict,
        help=_('Device id and segmentation id of l2gateway. '
               '--device option can be repeated'))
Beispiel #22
0
def is_midonet_network(context):
    """Checks whether the context is mech driver context for MidoNet driver """

    if isinstance(context, ctx.NetworkContext):
        net = context.current
    elif isinstance(context, ctx.PortContext):
        net = context.network.current
    elif isinstance(context, ctx.SubnetContext):
        net = context.network.current
    else:
        raise ValueError(_("Invalid Mechanism driver context passed in."))

    return net.get(provider_net.NETWORK_TYPE) in const.MIDONET_NET_TYPES
Beispiel #23
0
    def _process_provider_create(self, network):

        net_type = network.get(pnet.NETWORK_TYPE)
        if not validators.is_attr_set(net_type):
            return None

        if net_type == m_const.TYPE_MIDONET:
            return None

        if net_type != m_const.TYPE_UPLINK:
            msg = _('Unsupported network type %(type)s detected '
                    'in a create network request.') % {'type': net_type}
            raise n_exc.InvalidInput(error_message=msg)

        return net_type
    def _process_provider_create(self, network):

        net_type = network.get(pnet.NETWORK_TYPE)
        if not attributes.is_attr_set(net_type):
            return None

        if net_type in _MIDONET_TYPES:
            # NOTE(yamamoto): Accept a few well-known types as
            # the default type.  This is a workaround for Horizon, which
            # currently doesn't have a way to specify MidoNet network types
            # or "no provider network".
            # REVISIT(yamamoto): Clean this up once Horizon is fixed
            if net_type != m_const.TYPE_MIDONET:
                LOG.warning(_LW('Unsupported network type %(type)s detected '
                                'in a create network request.'),
                            {'type': net_type})
            return None

        if net_type != m_const.TYPE_UPLINK:
            msg = _('Unsupported network type %(type)s detected '
                    'in a create network request.') % {'type': net_type}
            raise n_exc.InvalidInput(error_message=msg)

        return net_type
Beispiel #25
0
class MidonetL2GatewayUnavailable(nexception.ServiceUnavailable):
    message = _("Midonet L2 Gateway Service is unavailable "
                "because Gateway Device Management Service is disabled.")
Beispiel #26
0
class RemoteMacEntryNotFound(nexception.NotFound):
    message = _("Remote MAC entry %(id)s does not exist")
Beispiel #27
0
class DuplicateRemoteMacEntry(nexception.InUse):
    message = _("Request contains duplicate remote mac address entry: "
                "mac_address %(mac_address)s.")
Beispiel #28
0
    parser.set_defaults(func=data_show)
    parser = subparsers.add_parser('data-readonly')
    parser.set_defaults(func=data_readonly)
    parser = subparsers.add_parser('data-readwrite')
    parser.set_defaults(func=data_readwrite)
    parser = subparsers.add_parser('data-version-list')
    parser.set_defaults(func=data_version_list)
    parser = subparsers.add_parser('data-version-sync')
    parser.set_defaults(func=data_version_sync)
    parser = subparsers.add_parser('data-version-activate')
    parser.set_defaults(func=data_version_activate)


command_opt = cfg.SubCommandOpt('command',
                                title='Command',
                                help=_('Available commands'),
                                handler=add_command_parsers)

# Override the db management options with our own version
CONF.unregister_opt(n_cli.command_opt)
CONF.register_cli_opt(command_opt)


def get_alembic_config():
    config = alembic_config.Config(os.path.join(os.path.dirname(__file__),
                                                'alembic.ini'))
    config.set_main_option('script_location',
                           'midonet.neutron.db.migration:alembic_migration')
    return config

Beispiel #29
0
class RouterVtepTypeInvalid(nexception.InvalidInput):
    message = _("Gateway device %(type)s must be specified with "
                "resource_id")
Beispiel #30
0
class NetworkVlanTypeInvalid(nexception.InvalidInput):
    message = _("Gateway device %(type)s must be specified with "
                "resource_id")
Beispiel #31
0
class HwVtepTypeInvalid(nexception.InvalidInput):
    message = _("Gateway device %(type)s must be specified with "
                "management_port and management_ip")
Beispiel #32
0
class TunnelIPsRequired(nexception.BadRequest):
    message = _("Unable to complete operation for Gateway Device. "
                "The tunnel ips are required for %(gw_type)s type.")
 def validate_provider_segment(self, segment):
     for key, value in six.iteritems(segment):
         if value and key != api.NETWORK_TYPE:
             msg = _("%s prohibited for uplink provider network") % key
             raise exc.InvalidInput(error_message=msg)
Beispiel #34
0
class TunnelIPsExhausted(nexception.BadRequest):
    message = _("Unable to complete operation for Gateway Device. "
                "The number of tunnel ips exceeds the maximum 1.")
Beispiel #35
0
class GatewayDeviceNotFound(nexception.NotFound):
    message = _("Gateway device %(id)s does not exist")
Beispiel #36
0
class RemoteMacEntryWrongGatewayDevice(nexception.InvalidInput):
    message = _("Remote MAC entry %(id)s does not belong to gateway "
                "device %(gateway_device_id)s")
Beispiel #37
0
class ResourceNotFound(nexception.NotFound):
    message = _("specified resource %(resource_id)s does not exist")
Beispiel #38
0
class OperationRemoteMacEntryNotSupported(nexception.Conflict):
    message = _("Unable to operate remote_mac_entry for gateway device "
                "%(type)s type.")
 def add_known_arguments(self, parser):
     parser.add_argument(
         'gateway_device', metavar='GATEWAY_DEVICE',
         help=_('ID of the gateway device.'))
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from oslo_config import cfg

from midonet.neutron._i18n import _


mido_opts = [
    cfg.StrOpt('midonet_uri', default='http://localhost:8080/midonet-api',
               help=_('MidoNet API server URI.')),
    cfg.StrOpt('username', default='admin',
               help=_('MidoNet admin username.')),
    cfg.StrOpt('password', default='passw0rd',
               secret=True,
               help=_('MidoNet admin password.')),
    cfg.StrOpt('project_id',
               default='77777777-7777-7777-7777-777777777777',
               help=_('ID of the project that MidoNet admin user '
                      'belongs to.')),
    cfg.StrOpt('tunnel_protocol', default='vxlan',
               help=_('Tunnel protocol used by Midonet')),
    cfg.StrOpt('cluster_ip', default='localhost',
               help=_('IP that the cluster service can be reached on')),
    cfg.StrOpt('cluster_port', default='8088',
               help=_('Port that the cluster service can be reached on')),
 def _validate_port_create(self, port):
     if (port.get('device_owner') == n_const.DEVICE_OWNER_ROUTER_GW
             and not port['fixed_ips']):
         msg = (_("No IPs assigned to the gateway port for"
                  " router %s") % port['device_id'])
         raise n_exc.BadRequest(resource='router', msg=msg)
Beispiel #42
0
class MidonetL2GatewayConnectionExists(nexception.InUse):
    message = _("L2 Gateway Connection related to "
                "specified L2 Gateway %(l2_gateway_id)s already exists")
    def create_port(self, context, port):
        LOG.debug("MidonetPluginV2.create_port called: port=%r", port)

        port_data = port['port']
        # REVISIT(yamamoto): this nested transaction is a workaround
        # for bug #1490917.
        with db_api.autonested_transaction(context.session):
            # Set status along admin_state_up if the parameter is specified.
            if port['port'].get('admin_state_up') is not None:
                if not port['port']['admin_state_up']:
                    port['port']['status'] = n_const.PORT_STATUS_DOWN
            # Create a Neutron port
            new_port = super(MidonetPluginV2, self).create_port(context, port)

            # Do not create a gateway port if it has no IP address assigned as
            # MidoNet does not yet handle this case.
            if (new_port.get('device_owner') == n_const.DEVICE_OWNER_ROUTER_GW
                    and not new_port['fixed_ips']):
                msg = (_("No IPs assigned to the gateway port for"
                         " router %s") % port_data['device_id'])
                raise n_exc.BadRequest(resource='router', msg=msg)

            dhcp_opts = port['port'].get(edo_ext.EXTRADHCPOPTS, [])

            # Make sure that the port created is valid
            if "id" not in new_port:
                raise n_exc.BadRequest(resource='port',
                                       msg="Invalid port created")

            # Update fields
            port_data.update(new_port)

            port_psec, has_ip = self._determine_port_security_and_has_ip(
                context, port['port'])
            port['port'][psec.PORTSECURITY] = port_psec
            self._process_port_port_security_create(context,
                                                    port['port'],
                                                    new_port)

            if port_psec is False:
                if self._check_update_has_security_groups(port):
                    raise psec.PortSecurityAndIPRequiredForSecurityGroups()
                if self._check_update_has_allowed_address_pairs(port):
                    raise addr_pair.AddressPairAndPortSecurityRequired()
            else:
                # Bind security groups to the port
                self._ensure_default_security_group_on_port(context, port)

            sg_ids = self._get_security_groups_on_port(context, port)
            self._process_port_create_security_group(context, new_port, sg_ids)

            # Process port bindings
            self._process_portbindings_create_and_update(context, port_data,
                                                         new_port)
            self._process_mido_portbindings_create_and_update(context,
                                                              port_data,
                                                              new_port)

            self._process_port_create_extra_dhcp_opts(context, new_port,
                                                      dhcp_opts)

            new_port[addr_pair.ADDRESS_PAIRS] = (
                self._process_create_allowed_address_pairs(
                    context, new_port,
                    port_data.get(addr_pair.ADDRESS_PAIRS)))

            self.client.create_port_precommit(context, new_port)

        try:
            self.client.create_port_postcommit(new_port)
        except Exception as ex:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE("Failed to create a port %(new_port)s: %(err)s"),
                          {"new_port": new_port, "err": ex})
                try:
                    self.delete_port(context, new_port['id'],
                                     l3_port_check=False)
                except Exception:
                    LOG.exception(_LE("Failed to delete port %s"),
                                  new_port['id'])

        # NOTE(kevinbenton): this extra lookup is necessary to get the
        # latest db model for the extension functions
        port_model = self._get_port(context, new_port['id'])
        self._apply_dict_extend_functions('ports', new_port, port_model)

        LOG.debug("MidonetPluginV2.create_port exiting: port=%r", new_port)
        return new_port