Esempio n. 1
0
def check_string_length(value, name=None, min_length=0, max_length=None):
    """Check the length of specified string
    :param value: the value of the string
    :param name: the name of the string
    :param min_length: the min_length of the string
    :param max_length: the max_length of the string
    """
    if not isinstance(value, six.string_types):
        if name is None:
            msg = _("The input is not a string or unicode")
        else:
            msg = _("%s is not a string or unicode") % name
        raise exception.InvalidInput(message=msg)

    if name is None:
        name = value

    if len(value) < min_length:
        msg = _("%(name)s has a minimum character requirement of "
                "%(min_length)s.") % {'name': name, 'min_length': min_length}
        raise exception.InvalidInput(message=msg)

    if max_length and len(value) > max_length:
        msg = _("%(name)s has more than %(max_length)s "
                "characters.") % {'name': name, 'max_length': max_length}
        raise exception.InvalidInput(message=msg)
Esempio n. 2
0
def check_string_length(value, name=None, min_length=0, max_length=None):
    """Check the length of specified string
    :param value: the value of the string
    :param name: the name of the string
    :param min_length: the min_length of the string
    :param max_length: the max_length of the string
    """
    if not isinstance(value, six.string_types):
        if name is None:
            msg = _("The input is not a string or unicode")
        else:
            msg = _("%s is not a string or unicode") % name
        raise exception.InvalidInput(message=msg)

    if name is None:
        name = value

    if len(value) < min_length:
        msg = _("%(name)s has a minimum character requirement of "
                "%(min_length)s.") % {
                    'name': name,
                    'min_length': min_length
                }
        raise exception.InvalidInput(message=msg)

    if max_length and len(value) > max_length:
        msg = _("%(name)s has more than %(max_length)s "
                "characters.") % {
                    'name': name,
                    'max_length': max_length
                }
        raise exception.InvalidInput(message=msg)
Esempio n. 3
0
def get_my_linklocal(interface):
    try:
        if_str = execute('ip', '-f', 'inet6', '-o', 'addr', 'show', interface)
        condition = '\s+inet6\s+([0-9a-f:]+)/\d+\s+scope\s+link'
        links = [re.search(condition, x) for x in if_str[0].split('\n')]
        address = [w.group(1) for w in links if w is not None]
        if address[0] is not None:
            return address[0]
        else:
            msg = _('Link Local address is not found.:%s') % if_str
            raise exception.NovaException(msg)
    except Exception as ex:
        msg = _("Couldn't get Link Local IP of %(interface)s"
                " :%(ex)s") % {'interface': interface, 'ex': ex}
        raise exception.NovaException(msg)
Esempio n. 4
0
    def plug(self, instance_id, vif):
        vif_type = vif['type']

        if vif_type is None:
            raise exception.NovaException(
                _("vif_type parameter must be present "
                  "for this vif_driver implementation"))

        if vif_type == network_model.VIF_TYPE_BRIDGE:
            self.plug_bridge(instance_id, vif)
        elif vif_type == network_model.VIF_TYPE_OVS:
            self.plug_ovs(instance_id, vif)
        else:
            raise exception.NovaException(
                _("Unexpected vif_type=%s") % vif_type)
Esempio n. 5
0
    def spawn(self, context, container, tenant_id, host,
              network_mode=None, network_opts=None):
        # create containers
        args = {
            'hostname': container['hostname'],
            'mem_limit': container['mem_limit'],
            'name': self._encode_utf8(container['name'])
        }
        if network_mode in (None, 'neutron'):
            args['network_disabled'] = True
        image = self.docker.inspect_image(self._encode_utf8(container['image']))
        if not (image and image['ContainerConfig']['Cmd']):
            args['command'] = ['sh']
        if container['command']:
            args['command'] = container['command']
        container_id = self._create_container(container['name'],
                                              container['image'], args)
        if not container_id:
            raise exception.InstanceDeployFailure(
                _('Cannot create container'))
        container['id'] = container_id['id']
        self._start_container(container)
        if network_mode == 'neutron':
            self._start_container(container, network_mode=None)
            nw_info = self.network_api.create_network_resource(
                    context, container, tenant_id, host, **network_opts)
        else:
            self._start_container(container, network_mode=network_mode)

        return container['id']
Esempio n. 6
0
    def __init__(self, message=None, **kwargs):
        self.kwargs = kwargs

        if 'code' not in self.kwargs:
            try:
                self.kwargs['code'] = self.code
            except AttributeError:
                pass

        if not message:
            try:
                message = self.msg_fmt % kwargs

            except Exception:
                exc_info = sys.exc_info()
                # kwargs doesn't match a variable in the message
                # log the issue and the kwargs
                LOG.exception(_('Exception in string format operation'))
                for name, value in kwargs.iteritems():
                    LOG.error("%s: %s" % (name, value))    # noqa

                if CONF.fatal_exception_format_errors:
                    raise exc_info[0], exc_info[1], exc_info[2]
                else:
                    # at least get the core message out if something happened
                    message = self.msg_fmt

        super(EGODockerException, self).__init__(message)
Esempio n. 7
0
def find_fixed_ip_nomask(instance_id, network_info):
    for subnet in network_info['subnets']:
        for ip in subnet['ips']:
            if ip['type'] == 'fixed' and ip['address']:
                return ip['address']
    raise exception.InstanceDeployFailure(_('Cannot find fixed ip'),
                                          instance_id=instance_id)
Esempio n. 8
0
def find_fixed_ip_nomask(instance_id, network_info):
    for subnet in network_info['subnets']:
        for ip in subnet['ips']:
            if ip['type'] == 'fixed' and ip['address']:
                return ip['address']
    raise exception.InstanceDeployFailure(_('Cannot find fixed ip'),
                                          instance_id=instance_id)
Esempio n. 9
0
    def spawn(self,
              context,
              container,
              tenant_id,
              host,
              network_mode=None,
              network_opts=None):
        # create containers
        args = {
            'hostname': container['hostname'],
            'mem_limit': container['mem_limit'],
            'name': self._encode_utf8(container['name'])
        }
        if network_mode in (None, 'neutron'):
            args['network_disabled'] = True
        image = self.docker.inspect_image(self._encode_utf8(
            container['image']))
        if not (image and image['ContainerConfig']['Cmd']):
            args['command'] = ['sh']
        if container['command']:
            args['command'] = container['command']
        container_id = self._create_container(container['name'],
                                              container['image'], args)
        if not container_id:
            raise exception.InstanceDeployFailure(_('Cannot create container'))
        container['id'] = container_id['id']
        self._start_container(container)
        if network_mode == 'neutron':
            self._start_container(container, network_mode=None)
            nw_info = self.network_api.create_network_resource(
                context, container, tenant_id, host, **network_opts)
        else:
            self._start_container(container, network_mode=network_mode)

        return container['id']
Esempio n. 10
0
def parse_server_string(server_str):
    """Parses the given server_string and returns a list of host and port.
    If it's not a combination of host part and port, the port element
    is a null string. If the input is invalid expression, return a null
    list.
    """
    try:
        # First of all, exclude pure IPv6 address (w/o port).
        if netaddr.valid_ipv6(server_str):
            return (server_str, '')

        # Next, check if this is IPv6 address with a port number combination.
        if server_str.find("]:") != -1:
            (address, port) = server_str.replace('[', '', 1).split(']:')
            return (address, port)

        # Third, check if this is a combination of an address and a port
        if server_str.find(':') == -1:
            return (server_str, '')

        # This must be a combination of an address and a port
        (address, port) = server_str.split(':')
        return (address, port)

    except Exception:
        LOG.error(_('Invalid server_string: %s'), server_str)
        return ('', '')
Esempio n. 11
0
def parse_server_string(server_str):
    """Parses the given server_string and returns a list of host and port.
    If it's not a combination of host part and port, the port element
    is a null string. If the input is invalid expression, return a null
    list.
    """
    try:
        # First of all, exclude pure IPv6 address (w/o port).
        if netaddr.valid_ipv6(server_str):
            return (server_str, '')

        # Next, check if this is IPv6 address with a port number combination.
        if server_str.find("]:") != -1:
            (address, port) = server_str.replace('[', '', 1).split(']:')
            return (address, port)

        # Third, check if this is a combination of an address and a port
        if server_str.find(':') == -1:
            return (server_str, '')

        # This must be a combination of an address and a port
        (address, port) = server_str.split(':')
        return (address, port)

    except Exception:
        LOG.error(_('Invalid server_string: %s'), server_str)
        return ('', '')
Esempio n. 12
0
 def _attach_vifs(self, container_name, container, network_info):
     """Plug VIFs into container."""
     container_id = container['id']
     container_pid = container['pid']
     container_info = container['info']
     if not network_info:
         return
     if not container_id:
         return
     netns_path = '/var/run/netns'
     if not os.path.exists(netns_path):
         utils.execute(
                 'mkdir', '-p', netns_path, run_as_root=True)
     
     if not container_pid:
         msg = _('Cannot find any PID under container "{0}"')
         raise RuntimeError(msg.format(container_id))
     netns_path = os.path.join(netns_path, container_id)
     utils.execute(
             'ln', '-sf', '/proc/{0}/ns/net'.format(container_pid),
             '/var/run/netns/{0}'.format(container_id),
             run_as_root=True)
     # input hostname to /etc/hosts
     hostname = container_info['Config'].get('Hostname')
     hosts_path = container_info['HostsPath']
     ip = ''
     for vif in network_info:
         ip = self.vif_driver.attach(container_name, vif, container_id)
         with open(hosts_path, 'a') as file:
             file.write(ip+' '+hostname+'\n')
Esempio n. 13
0
def get_my_ipv4_address():
    """Run ip route/addr commands to figure out the best ipv4
    """
    LOCALHOST = '127.0.0.1'
    try:
        out = execute('ip', '-f', 'inet', '-o', 'route', 'show')

        # Find the default route
        regex_default = ('default\s*via\s*'
                         '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
                         '\s*dev\s*(\w*)\s*')
        default_routes = re.findall(regex_default, out[0])
        if not default_routes:
            return LOCALHOST
        gateway, iface = default_routes[0]

        # Find the right subnet for the gateway/interface for
        # the default route
        route = ('(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})'
                 '\s*dev\s*(\w*)\s*')
        for match in re.finditer(route, out[0]):
            subnet = netaddr.IPNetwork(match.group(1) + "/" + match.group(2))
            if (match.group(3) == iface
                    and netaddr.IPAddress(gateway) in subnet):
                try:
                    return _get_ipv4_address_for_interface(iface)
                except exception.NovaException:
                    pass
    except Exception as ex:
        LOG.error(_("Couldn't get IPv4 : %(ex)s") % {'ex': ex})
    return LOCALHOST
Esempio n. 14
0
    def plug_ovs(self, instance_id, vif):
        if_local_name = 'tap%s' % vif['id'][:11]
        if_remote_name = 'ns%s' % vif['id'][:11]
        bridge = vif['network']['bridge']
        # Device already exists so return.
        if linux_net.device_exists(if_local_name):
            return

        try:
            utils.execute('ip',
                          'link',
                          'add',
                          'name',
                          if_local_name,
                          'type',
                          'veth',
                          'peer',
                          'name',
                          if_remote_name,
                          run_as_root=True)
            linux_net.create_ovs_vif_port(bridge, if_local_name,
                                          network.get_ovs_interfaceid(vif),
                                          vif['address'], instance_id)
            utils.execute('ip',
                          'link',
                          'set',
                          if_local_name,
                          'up',
                          run_as_root=True)
        except Exception:
            LOG.exception("Failed to configure network")
            msg = _('Failed to setup the network, rolling back')
Esempio n. 15
0
def get_my_ipv4_address():
    """Run ip route/addr commands to figure out the best ipv4
    """
    LOCALHOST = '127.0.0.1'
    try:
        out = execute('ip', '-f', 'inet', '-o', 'route', 'show')

        # Find the default route
        regex_default = ('default\s*via\s*'
                         '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
                         '\s*dev\s*(\w*)\s*')
        default_routes = re.findall(regex_default, out[0])
        if not default_routes:
            return LOCALHOST
        gateway, iface = default_routes[0]

        # Find the right subnet for the gateway/interface for
        # the default route
        route = ('(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})'
              '\s*dev\s*(\w*)\s*')
        for match in re.finditer(route, out[0]):
            subnet = netaddr.IPNetwork(match.group(1) + "/" + match.group(2))
            if (match.group(3) == iface and
                    netaddr.IPAddress(gateway) in subnet):
                try:
                    return _get_ipv4_address_for_interface(iface)
                except exception.NovaException:
                    pass
    except Exception as ex:
        LOG.error(_("Couldn't get IPv4 : %(ex)s") % {'ex': ex})
    return LOCALHOST
Esempio n. 16
0
def find_fixed_ip(instance_id, network_info):
    for subnet in network_info['subnets']:
        netmask = subnet['cidr'].split('/')[1]
        for ip in subnet['ips']:
            if ip['type'] == 'fixed' and ip['address']:
                return ip['address'] + "/" + netmask
    raise exception.InstanceDeployFailure(_('Cannot find fixed ip'),
                                          instance_id=instance_id)
Esempio n. 17
0
 def unplug_ovs(self, instance_id, vif):
     """Unplug the VIF by deleting the port from the bridge."""
     try:
         linux_net.delete_ovs_vif_port(vif['network']['bridge'],
                                       vif['devname'])
     except processutils.ProcessExecutionError:
         LOG.exception(_("Failed while unplugging vif"),
                       instance=instance_id)
Esempio n. 18
0
def find_fixed_ip(instance_id, network_info):
    for subnet in network_info['subnets']:
        netmask = subnet['cidr'].split('/')[1]
        for ip in subnet['ips']:
            if ip['type'] == 'fixed' and ip['address']:
                return ip['address'] + "/" + netmask
    raise exception.InstanceDeployFailure(_('Cannot find fixed ip'),
                                          instance_id=instance_id)
Esempio n. 19
0
def convert_version_to_int(version):
    try:
        if isinstance(version, six.string_types):
            version = convert_version_to_tuple(version)
        if isinstance(version, tuple):
            return reduce(lambda x, y: (x * 1000) + y, version)
    except Exception:
        msg = _("Hypervisor version %s is invalid.") % version
        raise exception.NovaException(msg)
Esempio n. 20
0
    def plug_bridge(self, instance_id, vif):
        if_local_name = 'tap%s' % vif['id'][:11]
        if_remote_name = 'ns%s' % vif['id'][:11]
        bridge = vif['network']['bridge']
        gateway = network.find_gateway(instance_id, vif['network'])

        vlan = vif.get('vlan')
        if vlan is not None:
            iface = vif['network'].get_meta('bridge_interface')
            linux_net.LinuxBridgeInterfaceDriver.ensure_vlan_bridge(
                vlan, bridge, iface, net_attrs=vif, mtu=vif.get('mtu'))
            iface = 'vlan%s' % vlan
        else:
            iface = vif['network'].get_meta('bridge_interface')
            LOG.debug('Ensuring bridge for %s - %s' % (iface, bridge))
            linux_net.LinuxBridgeInterfaceDriver.ensure_bridge(bridge,
                                                               iface,
                                                               net_attrs=vif,
                                                               gateway=gateway)

        # Device already exists so return.
        if linux_net.device_exists(if_local_name):
            return

        try:
            utils.execute('ip',
                          'link',
                          'add',
                          'name',
                          if_local_name,
                          'type',
                          'veth',
                          'peer',
                          'name',
                          if_remote_name,
                          run_as_root=True)
            utils.execute('ip',
                          'link',
                          'set',
                          if_local_name,
                          'address',
                          self._fe_random_mac(),
                          run_as_root=True)
            utils.execute('brctl',
                          'addif',
                          bridge,
                          if_local_name,
                          run_as_root=True)
            utils.execute('ip',
                          'link',
                          'set',
                          if_local_name,
                          'up',
                          run_as_root=True)
        except Exception:
            LOG.exception("Failed to configure network")
            msg = _('Failed to setup the network, rolling back')
Esempio n. 21
0
def convert_version_to_int(version):
    try:
        if isinstance(version, six.string_types):
            version = convert_version_to_tuple(version)
        if isinstance(version, tuple):
            return reduce(lambda x, y: (x * 1000) + y, version)
    except Exception:
        msg = _("Hypervisor version %s is invalid.") % version
        raise exception.NovaException(msg)
Esempio n. 22
0
    def allocate(self, context, instance_id, host, tenant_id, **kwargs):
        neutron = neutronv2.get_client(context, admin=True)
        dhcp_opts = kwargs.get('dhcp_options', None)
        zone = kwargs.get('zone')
        net_ids = [kwargs.get('network_id')]
        nets = self._get_available_networks(context, tenant_id, net_ids)
        if not nets:
            LOG.warn(_LW("No network configured!"))
            return network_model.NetworkInfo([])
        security_groups = kwargs.get('security_groups', [])
        security_group_ids = []
        if len(security_groups):
            search_opts = {'tenant_id': tenant_id}
            user_security_groups = neutron.list_security_groups(
                **search_opts).get('security_groups')
        for security_group in security_groups:
            name_match = None
            uuid_match = None
            for user_security_group in user_security_groups:
                if user_security_group['name'] == security_group:
                    if name_match:
                        raise exception.NoUniqueMatch(
                            _("Multiple security groups found matching"
                              " '%s'. Use an ID to be more specific.") %
                               security_group)

                    name_match = user_security_group['id']
                if user_security_group['id'] == security_group:
                    uuid_match = user_security_group['id']

            # If a user names the security group the same as
            # another's security groups uuid, the name takes priority.
            if not name_match and not uuid_match:
                raise exception.SecurityGroupNotFound(
                    security_group_id=security_group)
            elif name_match:
                security_group_ids.append(name_match)
            elif uuid_match:
                security_group_ids.append(uuid_match)
        for net in nets:
            if net['id'] == kwargs.get('network_id'):
                network = net
                break
        if (security_groups and not (
                network['subnets']
                and network.get('port_security_enabled', True))):
            raise exception.SecurityGroupCannotBeApplied()
        port_req_body = {'port': {'device_id': instance_id,
                                  'device_owner': zone,
                                  'binding:host_id': host}}
        created_port = self._create_port(
                neutron, tenant_id, network['id'],
                port_req_body, None, security_group_ids, dhcp_opts)
        nw_info = self._build_network_info_model(context, instance_id, tenant_id,
                                                 networks=[net],
                                                 port_ids=[created_port])
        return network_model.NetworkInfo([vif for vif in nw_info])
Esempio n. 23
0
def get_my_linklocal(interface):
    try:
        if_str = execute('ip', '-f', 'inet6', '-o', 'addr', 'show', interface)
        condition = '\s+inet6\s+([0-9a-f:]+)/\d+\s+scope\s+link'
        links = [re.search(condition, x) for x in if_str[0].split('\n')]
        address = [w.group(1) for w in links if w is not None]
        if address[0] is not None:
            return address[0]
        else:
            msg = _('Link Local address is not found.:%s') % if_str
            raise exception.NovaException(msg)
    except Exception as ex:
        msg = _("Couldn't get Link Local IP of %(interface)s"
                " :%(ex)s") % {
                    'interface': interface,
                    'ex': ex
                }
        raise exception.NovaException(msg)
Esempio n. 24
0
    def __init__(self, user_id, project_id, is_admin=None, read_deleted="no",
                 roles=None, remote_address=None, timestamp=None,
                 request_id=None, auth_token=None, overwrite=True,
                 quota_class=None, user_name=None, project_name=None,
                 service_catalog=None, instance_lock_checked=False, **kwargs):
        """:param read_deleted: 'no' indicates deleted records are hidden,
                'yes' indicates deleted records are visible,
                'only' indicates that *only* deleted records are visible.


           :param overwrite: Set to False to ensure that the greenthread local
                copy of the index is not overwritten.

           :param kwargs: Extra arguments that might be present, but we ignore
                because they possibly came in from older rpc messages.
        """
        if kwargs:
            LOG.warn(_('Arguments dropped when creating context: %s') %
                    str(kwargs))

        self.user_id = user_id
        self.project_id = project_id
        self.roles = roles or []
        self.read_deleted = read_deleted
        self.remote_address = remote_address
        if not timestamp:
            timestamp = timeutils.utcnow()
        if isinstance(timestamp, six.string_types):
            timestamp = timeutils.parse_strtime(timestamp)
        self.timestamp = timestamp
        if not request_id:
            request_id = generate_request_id()
        self.request_id = request_id
        self.auth_token = auth_token

        if service_catalog:
            # Only include required parts of service_catalog
            self.service_catalog = [s for s in service_catalog
                if s.get('type') in ('volume', 'volumev2')]
        else:
            # if list is empty or none
            self.service_catalog = []

        self.instance_lock_checked = instance_lock_checked

        # NOTE(markmc): this attribute is currently only used by the
        # rs_limits turnstile pre-processor.
        # See https://lists.launchpad.net/openstack/msg12200.html
        self.quota_class = quota_class
        self.user_name = user_name
        self.project_name = project_name
        self.is_admin = is_admin
        if self.is_admin is None:
            self.is_admin = False
        if overwrite or not hasattr(local.store, 'context'):
            self.update_store()
Esempio n. 25
0
def _get_ipv4_address_for_interface(iface):
    """Run ip addr show for an interface and grab its ipv4 addresses
    """
    try:
        out = execute('ip', '-f', 'inet', '-o', 'addr', 'show', iface)
        regexp_address = re.compile('inet\s*'
                                    '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
        address = [m.group(1) for m in regexp_address.finditer(out[0])
                   if m.group(1) != '127.0.0.1']
        if address:
            return address[0]
        else:
            msg = _('IPv4 address is not found.: %s') % out[0]
            raise exception.NovaException(msg)
    except Exception as ex:
        msg = _("Couldn't get IPv4 of %(interface)s"
                " : %(ex)s") % {'interface': iface, 'ex': ex}
        LOG.error(msg)
        raise exception.NovaException(msg)
Esempio n. 26
0
def teardown_network(container_id):
    try:
        output, err = utils.execute('ip', '-o', 'netns', 'list')
        for line in output.split('\n'):
            if container_id == line.strip():
                utils.execute('ip', 'netns', 'delete', container_id,
                              run_as_root=True)
                break
    except processutils.ProcessExecutionError:
        LOG.warning(_('Cannot remove network namespace, netns id: %s'),
                    container_id)
Esempio n. 27
0
 def soft_delete(self, container_id):
     if not container_id:
         return
     try:
         self.docker.stop(container_id)
     except errors.APIError as e:
         if 'Unpause the container before stopping' not in e.explanation:
             LOG.warning(_('Cannot stop container'), e, exc_info=True)
             raise
         self.docker.unpause(container_id)
         self.docker.stop(container_id)
Esempio n. 28
0
 def soft_delete(self, container_id):
     if not container_id:
         return
     try:
         self.docker.stop(container_id)
     except errors.APIError as e:
         if 'Unpause the container before stopping' not in e.explanation:
             LOG.warning(_('Cannot stop container'),
                         e, exc_info=True)
             raise
         self.docker.unpause(container_id)
         self.docker.stop(container_id)
Esempio n. 29
0
def tempdir(**kwargs):
    argdict = kwargs.copy()
    if 'dir' not in argdict:
        argdict['dir'] = CONF.tempdir
    tmpdir = tempfile.mkdtemp(**argdict)
    try:
        yield tmpdir
    finally:
        try:
            shutil.rmtree(tmpdir)
        except OSError as e:
            LOG.error(_('Could not remove tmpdir: %s'), e)
Esempio n. 30
0
def tempdir(**kwargs):
    argdict = kwargs.copy()
    if 'dir' not in argdict:
        argdict['dir'] = CONF.tempdir
    tmpdir = tempfile.mkdtemp(**argdict)
    try:
        yield tmpdir
    finally:
        try:
            shutil.rmtree(tmpdir)
        except OSError as e:
            LOG.error(_('Could not remove tmpdir: %s'), e)
Esempio n. 31
0
    def unplug(self, instance_id, vif):
        vif_type = vif['type']

        LOG.debug('vif_type=%(vif_type)s instance=%(instance)s '
                  'vif=%(vif)s', {
                      'vif_type': vif_type,
                      'instance': instance_id,
                      'vif': vif
                  })

        if vif_type is None:
            raise exception.NovaException(
                _("vif_type parameter must be present "
                  "for this vif_driver implementation"))

        if vif_type == network_model.VIF_TYPE_BRIDGE:
            self.unplug_bridge(instance_id, vif)
        elif vif_type == network_model.VIF_TYPE_OVS:
            self.unplug_ovs(instance_id, vif)
        else:
            raise exception.NovaException(
                _("Unexpected vif_type=%s") % vif_type)
Esempio n. 32
0
def validate_integer(value, name, min_value=None, max_value=None):
    """Make sure that value is a valid integer, potentially within range."""
    try:
        value = int(str(value))
    except (ValueError, UnicodeEncodeError):
        msg = _('%(value_name)s must be an integer')
        raise exception.InvalidInput(reason=(msg % {'value_name': name}))

    if min_value is not None:
        if value < min_value:
            msg = _('%(value_name)s must be >= %(min_value)d')
            raise exception.InvalidInput(reason=(msg % {
                'value_name': name,
                'min_value': min_value
            }))
    if max_value is not None:
        if value > max_value:
            msg = _('%(value_name)s must be <= %(max_value)d')
            raise exception.InvalidInput(reason=(msg % {
                'value_name': name,
                'max_value': max_value
            }))
    return value
Esempio n. 33
0
def teardown_network(container_id):
    try:
        output, err = utils.execute('ip', '-o', 'netns', 'list')
        for line in output.split('\n'):
            if container_id == line.strip():
                utils.execute('ip',
                              'netns',
                              'delete',
                              container_id,
                              run_as_root=True)
                break
    except processutils.ProcessExecutionError:
        LOG.warning(_('Cannot remove network namespace, netns id: %s'),
                    container_id)
Esempio n. 34
0
def _get_ipv4_address_for_interface(iface):
    """Run ip addr show for an interface and grab its ipv4 addresses
    """
    try:
        out = execute('ip', '-f', 'inet', '-o', 'addr', 'show', iface)
        regexp_address = re.compile('inet\s*'
                                    '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
        address = [
            m.group(1) for m in regexp_address.finditer(out[0])
            if m.group(1) != '127.0.0.1'
        ]
        if address:
            return address[0]
        else:
            msg = _('IPv4 address is not found.: %s') % out[0]
            raise exception.NovaException(msg)
    except Exception as ex:
        msg = _("Couldn't get IPv4 of %(interface)s"
                " : %(ex)s") % {
                    'interface': iface,
                    'ex': ex
                }
        LOG.error(msg)
        raise exception.NovaException(msg)
Esempio n. 35
0
def validate_integer(value, name, min_value=None, max_value=None):
    """Make sure that value is a valid integer, potentially within range."""
    try:
        value = int(str(value))
    except (ValueError, UnicodeEncodeError):
        msg = _('%(value_name)s must be an integer')
        raise exception.InvalidInput(reason=(
            msg % {'value_name': name}))

    if min_value is not None:
        if value < min_value:
            msg = _('%(value_name)s must be >= %(min_value)d')
            raise exception.InvalidInput(
                reason=(msg % {'value_name': name,
                               'min_value': min_value}))
    if max_value is not None:
        if value > max_value:
            msg = _('%(value_name)s must be <= %(max_value)d')
            raise exception.InvalidInput(
                reason=(
                    msg % {'value_name': name,
                           'max_value': max_value})
            )
    return value
Esempio n. 36
0
def vpn_ping(address, port, timeout=0.05, session_id=None):
    """Sends a vpn negotiation packet and returns the server session.

    Returns False on a failure. Basic packet structure is below.

    Client packet (14 bytes)::

         0 1      8 9  13
        +-+--------+-----+
        |x| cli_id |?????|
        +-+--------+-----+
        x = packet identifier 0x38
        cli_id = 64 bit identifier
        ? = unknown, probably flags/padding

    Server packet (26 bytes)::

         0 1      8 9  13 14    21 2225
        +-+--------+-----+--------+----+
        |x| srv_id |?????| cli_id |????|
        +-+--------+-----+--------+----+
        x = packet identifier 0x40
        cli_id = 64 bit identifier
        ? = unknown, probably flags/padding
        bit 9 was 1 and the rest were 0 in testing

    """
    if session_id is None:
        session_id = random.randint(0, 0xffffffffffffffff)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    data = struct.pack('!BQxxxxx', 0x38, session_id)
    sock.sendto(data, (address, port))
    sock.settimeout(timeout)
    try:
        received = sock.recv(2048)
    except socket.timeout:
        return False
    finally:
        sock.close()
    fmt = '!BQxxxxxQxxxx'
    if len(received) != struct.calcsize(fmt):
        LOG.warn(
            _('Expected to receive %(exp)s bytes, but actually %(act)s') %
            dict(exp=struct.calcsize(fmt), act=len(received)))
        return False
    (identifier, server_sess, client_sess) = struct.unpack(fmt, received)
    if identifier == 0x40 and client_sess == session_id:
        return server_sess
Esempio n. 37
0
    def __init__(self, address=None, type=None, **kwargs):
        super(IP, self).__init__()

        self['address'] = address
        self['type'] = type
        self['version'] = kwargs.pop('version', None)

        self._set_meta(kwargs)

        # determine version from address if not passed in
        if self['address'] and not self['version']:
            try:
                self['version'] = netaddr.IPAddress(self['address']).version
            except netaddr.AddrFormatError:
                msg = _("Invalid IP format %s") % self['address']
                raise exception.InvalidIpAddressError(msg)
Esempio n. 38
0
    def __init__(self, address=None, type=None, **kwargs):
        super(IP, self).__init__()

        self['address'] = address
        self['type'] = type
        self['version'] = kwargs.pop('version', None)

        self._set_meta(kwargs)

        # determine version from address if not passed in
        if self['address'] and not self['version']:
            try:
                self['version'] = netaddr.IPAddress(self['address']).version
            except netaddr.AddrFormatError:
                msg = _("Invalid IP format %s") % self['address']
                raise exception.InvalidIpAddressError(msg)
Esempio n. 39
0
def vpn_ping(address, port, timeout=0.05, session_id=None):
    """Sends a vpn negotiation packet and returns the server session.

    Returns False on a failure. Basic packet structure is below.

    Client packet (14 bytes)::

         0 1      8 9  13
        +-+--------+-----+
        |x| cli_id |?????|
        +-+--------+-----+
        x = packet identifier 0x38
        cli_id = 64 bit identifier
        ? = unknown, probably flags/padding

    Server packet (26 bytes)::

         0 1      8 9  13 14    21 2225
        +-+--------+-----+--------+----+
        |x| srv_id |?????| cli_id |????|
        +-+--------+-----+--------+----+
        x = packet identifier 0x40
        cli_id = 64 bit identifier
        ? = unknown, probably flags/padding
        bit 9 was 1 and the rest were 0 in testing

    """
    if session_id is None:
        session_id = random.randint(0, 0xffffffffffffffff)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    data = struct.pack('!BQxxxxx', 0x38, session_id)
    sock.sendto(data, (address, port))
    sock.settimeout(timeout)
    try:
        received = sock.recv(2048)
    except socket.timeout:
        return False
    finally:
        sock.close()
    fmt = '!BQxxxxxQxxxx'
    if len(received) != struct.calcsize(fmt):
        LOG.warn(_('Expected to receive %(exp)s bytes, but actually %(act)s') %
                 dict(exp=struct.calcsize(fmt), act=len(received)))
        return False
    (identifier, server_sess, client_sess) = struct.unpack(fmt, received)
    if identifier == 0x40 and client_sess == session_id:
        return server_sess
Esempio n. 40
0
class EGODockerException(Exception):
    """Base Nova Exception

    To correctly use this class, inherit from it and define
    a 'msg_fmt' property. That msg_fmt will get printf'd
    with the keyword arguments provided to the constructor.

    """
    msg_fmt = _("An unknown exception occurred.")
    code = 500
    headers = {}
    safe = False

    def __init__(self, message=None, **kwargs):
        self.kwargs = kwargs

        if 'code' not in self.kwargs:
            try:
                self.kwargs['code'] = self.code
            except AttributeError:
                pass

        if not message:
            try:
                message = self.msg_fmt % kwargs

            except Exception:
                exc_info = sys.exc_info()
                # kwargs doesn't match a variable in the message
                # log the issue and the kwargs
                LOG.exception(_('Exception in string format operation'))
                for name, value in kwargs.iteritems():
                    LOG.error("%s: %s" % (name, value))    # noqa

                if CONF.fatal_exception_format_errors:
                    raise exc_info[0], exc_info[1], exc_info[2]
                else:
                    # at least get the core message out if something happened
                    message = self.msg_fmt

        super(EGODockerException, self).__init__(message)

    def format_message(self):
        # NOTE(mrodden): use the first argument to the python Exception object
        # which should be our full EGODockerException message, (see __init__)
        return self.args[0]
Esempio n. 41
0
    def __get_backend(self):
        if not self.__backend:
            if self.__config_group is None:
                backend_name = CONF[self.__pivot]
            else:
                backend_name = CONF[self.__config_group][self.__pivot]
            if backend_name not in self.__backends:
                msg = _('Invalid backend: %s') % backend_name
                raise exception.NovaException(msg)

            backend = self.__backends[backend_name]
            if isinstance(backend, tuple):
                name = backend[0]
                fromlist = backend[1]
            else:
                name = backend
                fromlist = backend

            self.__backend = __import__(name, None, None, fromlist)
        return self.__backend
Esempio n. 42
0
    def __get_backend(self):
        if not self.__backend:
            if self.__config_group is None:
                backend_name = CONF[self.__pivot]
            else:
                backend_name = CONF[self.__config_group][self.__pivot]
            if backend_name not in self.__backends:
                msg = _('Invalid backend: %s') % backend_name
                raise exception.NovaException(msg)

            backend = self.__backends[backend_name]
            if isinstance(backend, tuple):
                name = backend[0]
                fromlist = backend[1]
            else:
                name = backend
                fromlist = backend

            self.__backend = __import__(name, None, None, fromlist)
        return self.__backend
Esempio n. 43
0
def find_gateway(instance_id, network_info):
    for subnet in network_info['subnets']:
        return subnet['gateway']['address']
    raise exception.InstanceDeployFailure(_('Cannot find gateway'),
                                          instance_id=instance_id)
Esempio n. 44
0
def find_gateway(instance_id, network_info):
    for subnet in network_info['subnets']:
        return subnet['gateway']['address']
    raise exception.InstanceDeployFailure(_('Cannot find gateway'),
                                          instance_id=instance_id)
Esempio n. 45
0
 def _set_read_deleted(self, read_deleted):
     if read_deleted not in ('no', 'yes', 'only'):
         raise ValueError(_("read_deleted can only be one of 'no', "
                            "'yes' or 'only', not %r") % read_deleted)
     self._read_deleted = read_deleted
Esempio n. 46
0
    def __init__(self,
                 user_id,
                 project_id,
                 is_admin=None,
                 read_deleted="no",
                 roles=None,
                 remote_address=None,
                 timestamp=None,
                 request_id=None,
                 auth_token=None,
                 overwrite=True,
                 quota_class=None,
                 user_name=None,
                 project_name=None,
                 service_catalog=None,
                 instance_lock_checked=False,
                 **kwargs):
        """:param read_deleted: 'no' indicates deleted records are hidden,
                'yes' indicates deleted records are visible,
                'only' indicates that *only* deleted records are visible.


           :param overwrite: Set to False to ensure that the greenthread local
                copy of the index is not overwritten.

           :param kwargs: Extra arguments that might be present, but we ignore
                because they possibly came in from older rpc messages.
        """
        if kwargs:
            LOG.warn(
                _('Arguments dropped when creating context: %s') % str(kwargs))

        self.user_id = user_id
        self.project_id = project_id
        self.roles = roles or []
        self.read_deleted = read_deleted
        self.remote_address = remote_address
        if not timestamp:
            timestamp = timeutils.utcnow()
        if isinstance(timestamp, six.string_types):
            timestamp = timeutils.parse_strtime(timestamp)
        self.timestamp = timestamp
        if not request_id:
            request_id = generate_request_id()
        self.request_id = request_id
        self.auth_token = auth_token

        if service_catalog:
            # Only include required parts of service_catalog
            self.service_catalog = [
                s for s in service_catalog
                if s.get('type') in ('volume', 'volumev2')
            ]
        else:
            # if list is empty or none
            self.service_catalog = []

        self.instance_lock_checked = instance_lock_checked

        # NOTE(markmc): this attribute is currently only used by the
        # rs_limits turnstile pre-processor.
        # See https://lists.launchpad.net/openstack/msg12200.html
        self.quota_class = quota_class
        self.user_name = user_name
        self.project_name = project_name
        self.is_admin = is_admin
        if self.is_admin is None:
            self.is_admin = False
        if overwrite or not hasattr(local.store, 'context'):
            self.update_store()
Esempio n. 47
0
 def _set_read_deleted(self, read_deleted):
     if read_deleted not in ('no', 'yes', 'only'):
         raise ValueError(
             _("read_deleted can only be one of 'no', "
               "'yes' or 'only', not %r") % read_deleted)
     self._read_deleted = read_deleted
Esempio n. 48
0
def check_isinstance(obj, cls):
    """Checks that obj is of type cls, and lets PyLint infer types."""
    if isinstance(obj, cls):
        return obj
    raise Exception(_('Expected object of type: %s') % (str(cls)))
Esempio n. 49
0
def check_isinstance(obj, cls):
    """Checks that obj is of type cls, and lets PyLint infer types."""
    if isinstance(obj, cls):
        return obj
    raise Exception(_('Expected object of type: %s') % (str(cls)))