Esempio n. 1
0
def run_ip_config_cmd(*cmd, **kwargs):
    logger.info("Running %s" % ' '.join(cmd))
    try:
        processutils.execute(*cmd, **kwargs)
    except processutils.ProcessExecutionError:
        logger.error("Failed to execute %s" % ' '.join(cmd))
        raise
Esempio n. 2
0
File: fs.py Progetto: mahak/nova
def unprivileged_resize2fs(image, check_exit_code, size=None):
    if size:
        cmd = ['resize2fs', image, size]
    else:
        cmd = ['resize2fs', image]

    processutils.execute(*cmd, check_exit_code=check_exit_code)
Esempio n. 3
0
File: fs.py Progetto: mahak/nova
def configurable_mkfs(os_type, fs_label, target, run_as_root,
                      default_ephemeral_format, specified_fs=None):
    # Format a file or block device using a user provided command for each
    # os type. If user has not provided any configuration, format type will
    # be used according to a default_ephemeral_format configuration or a
    # system default.
    global _MKFS_COMMAND
    global _DEFAULT_MKFS_COMMAND

    mkfs_command = (_MKFS_COMMAND.get(os_type, _DEFAULT_MKFS_COMMAND) or
                    '') % {'fs_label': fs_label, 'target': target}
    if mkfs_command:
        if run_as_root:
            _inner_configurable_mkfs(os_type, fs_label, target)
        else:
            processutils.execute(*mkfs_command.split())

    else:
        if not specified_fs:
            specified_fs = default_ephemeral_format
            if not specified_fs:
                specified_fs = _DEFAULT_FS_BY_OSTYPE.get(os_type,
                                                         _DEFAULT_FILE_SYSTEM)

        if run_as_root:
            mkfs(specified_fs, target, fs_label)
        else:
            unprivileged_mkfs(specified_fs, target, fs_label)
Esempio n. 4
0
def unprivileged_convert_image(source, dest, in_format, out_format,
                               instances_path):
    # NOTE(mdbooth): qemu-img convert defaults to cache=unsafe, which means
    # that data is not synced to disk at completion. We explicitly use
    # cache=none here to (1) ensure that we don't interfere with other
    # applications using the host's io cache, and (2) ensure that the data is
    # on persistent storage when the command exits. Without (2), a host crash
    # may leave a corrupt image in the image cache, which Nova cannot recover
    # automatically.
    # NOTE(zigo): we cannot use -t none if the instances dir is mounted on a
    # filesystem that doesn't have support for O_DIRECT, which is the case
    # for example with tmpfs. This simply crashes "openstack server create"
    # in environments like live distributions. In such case, the best choice
    # is writethrough, which is power-failure safe, but still faster than
    # writeback.
    if nova.privsep.utils.supports_direct_io(instances_path):
        cache_mode = 'none'
    else:
        cache_mode = 'writethrough'
    cmd = ('qemu-img', 'convert', '-t', cache_mode, '-O', out_format)

    if in_format is not None:
        cmd = cmd + ('-f', in_format)
    cmd = cmd + (source, dest)
    processutils.execute(*cmd)
Esempio n. 5
0
    def run(self, context):
        # TODO(dtantsur): redfish support
        LOG.debug('Probing for IPMI BMC: %s@%s:%s',
                  self.username, self.ip, self.port)

        with tempfile.NamedTemporaryFile(mode='wt') as fp:
            fp.write(self.password or '\0')
            fp.flush()

            try:
                # TODO(dtantsur): try also IPMI v1.5
                processutils.execute('ipmitool', '-I', 'lanplus',
                                     '-H', self.ip, '-L', 'ADMINISTRATOR',
                                     '-p', str(self.port), '-U', self.username,
                                     '-f', fp.name, 'power', 'status',
                                     attempts=self.attempts)
            except processutils.ProcessExecutionError as exc:
                LOG.debug('Probing %(ip)s failed: %(exc)s',
                          {'ip': self.ip, 'exc': exc})
                return None

        LOG.info('Found a BMC on %(ip)s with user %(user)s',
                 {'ip': self.ip, 'user': self.username})
        return {
            'pm_type': self.ipmi_driver,
            'pm_addr': self.ip,
            'pm_user': self.username,
            'pm_password': self.password,
            'pm_port': self.port,
        }
Esempio n. 6
0
    def _apply(self):
        """Apply the current in-memory set of iptables rules.

        This will blow away any rules left over from previous runs of the
        same component of Nova, and replace them with our current set of
        rules. This happens atomically, thanks to iptables-restore.

        """
        s = [('iptables', self.ipv4)]
        if self.use_ipv6:
            s += [('ip6tables', self.ipv6)]

        for cmd, tables in s:
            all_tables, _err = processutils.execute('%s-save' % (cmd,),
                                                    '-c', attempts=5,
                                                    run_as_root=True)
            all_lines = all_tables.split('\n')
            for table_name, table in six.iteritems(tables):
                start, end = self._find_table(all_lines, table_name)
                all_lines[start:end] = self._modify_rules(
                        all_lines[start:end], table, table_name)
                table.dirty = False
            processutils.execute('%s-restore' % (cmd,), '-c',
                                 process_input='\n'.join(all_lines),
                                 attempts=5, run_as_root=True)
Esempio n. 7
0
def if_up_interface(device):
    logger.info("Running /sbin/ifup %s" % device)
    try:
        processutils.execute('/sbin/ifup', device)
    except processutils.ProcessExecutionError:
        logger.error("Failed to ifup  %s" % device)
        raise
Esempio n. 8
0
def generate_key_pair(key_length=2048):
    """Create RSA key pair with specified number of bits in key.

    Returns tuple of private and public keys.
    """
    with tempfiles.tempdir() as tmpdir:
        keyfile = os.path.join(tmpdir, 'tempkey')
        args = [
            'ssh-keygen',
            '-q',  # quiet
            '-N', '',  # w/o passphrase
            '-t', 'rsa',  # create key of rsa type
            '-f', keyfile,  # filename of the key file
            '-C', 'Generated-by-Sahara'  # key comment
        ]
        if key_length is not None:
            args.extend(['-b', key_length])
        processutils.execute(*args)
        if not os.path.exists(keyfile):
            raise ex.SystemError(_("Private key file hasn't been created"))
        private_key = open(keyfile).read()
        public_key_path = keyfile + '.pub'
        if not os.path.exists(public_key_path):
            raise ex.SystemError(_("Public key file hasn't been created"))
        public_key = open(public_key_path).read()

        return private_key, public_key
Esempio n. 9
0
def set_device_macaddr_and_vlan(dev, vf_num, mac_addr, vlan):
    processutils.execute('ip', 'link', 'set', dev,
                         'vf', vf_num,
                         'mac', mac_addr,
                         'vlan', vlan,
                         run_as_root=True,
                         check_exit_code=[0, 2, 254])
    def _test_windows_execute(self, mock_tpool, mock_popen,
                              use_eventlet=False):
        # We want to ensure that if eventlet is used on Windows,
        # 'communicate' calls are wrapped with eventlet.tpool.execute.
        mock_comm = mock_popen.return_value.communicate
        mock_comm.return_value = None
        mock_tpool.execute.return_value = mock_comm.return_value

        fake_pinput = 'fake pinput'.encode('utf-8')

        with mock.patch.object(processutils, 'eventlet_patched',
                               use_eventlet):
            processutils.execute(
                TRUE_UTILITY,
                process_input=fake_pinput,
                check_exit_code=False)

        mock_popen.assert_called_once_with(
            [TRUE_UTILITY],
            stdin=mock.ANY, stdout=mock.ANY,
            stderr=mock.ANY, close_fds=mock.ANY,
            preexec_fn=mock.ANY, shell=mock.ANY,
            cwd=mock.ANY, env=mock.ANY)

        if use_eventlet:
            mock_tpool.execute.assert_called_once_with(
                mock_comm, fake_pinput)
        else:
            mock_comm.assert_called_once_with(fake_pinput)
Esempio n. 11
0
    def _change_config(self, service, old_workers, new_workers):
        pre_reload_parent, pre_reload_children = self._get_heat_api_pids(
            service)
        self.assertEqual(old_workers, len(pre_reload_children))

        # change the config values
        self._set_config_value(service, 'workers', new_workers)
        cmd = "kill -HUP %s" % pre_reload_parent
        processutils.execute(cmd, shell=True)

        # wait till heat-api reloads
        start_time = time.time()
        while time.time() - start_time < self.conf.sighup_timeout:
            post_reload_parent, post_reload_children = self._get_heat_api_pids(
                service)
            intersect = set(post_reload_children) & set(pre_reload_children)
            if (new_workers == len(post_reload_children)
                and pre_reload_parent == post_reload_parent
                    and intersect == set()):
                break
            eventlet.sleep(1)
        self.assertEqual(pre_reload_parent, post_reload_parent)
        self.assertEqual(new_workers, len(post_reload_children))
        # test if all child processes are newly created
        self.assertEqual(set(post_reload_children) & set(pre_reload_children),
                         set())
Esempio n. 12
0
def generate_key_pair(key_length=2048):
    """Create RSA key pair with specified number of bits in key.

    Returns tuple of private and public keys.
    """
    with tempfiles.tempdir() as tmpdir:
        keyfile = os.path.join(tmpdir, "tempkey")
        args = [
            "ssh-keygen",
            "-q",  # quiet
            "-N",
            "",  # w/o passphrase
            "-t",
            "rsa",  # create key of rsa type
            "-f",
            keyfile,  # filename of the key file
            "-C",
            "Generated-by-Sahara",  # key comment
        ]
        if key_length is not None:
            args.extend(["-b", key_length])
        processutils.execute(*args)
        if not os.path.exists(keyfile):
            raise ex.SystemError(_("Private key file hasn't been created"))
        with open(keyfile) as keyfile_fd:
            private_key = keyfile_fd.read()
        public_key_path = keyfile + ".pub"
        if not os.path.exists(public_key_path):
            raise ex.SystemError(_("Public key file hasn't been created"))
        with open(public_key_path) as public_key_path_fd:
            public_key = public_key_path_fd.read()

        return private_key, public_key
Esempio n. 13
0
    def detach(self, client, volume_id):
        # TODO(e0ne): multipath support
        conn_prop = connector.get_connector_properties(utils.get_root_helper(),
                                                       utils.get_my_ip(),
                                                       multipath=False,
                                                       enforce_multipath=False)
        connection = client.volumes.initialize_connection(volume_id, conn_prop)
        nfs_mount_point_base = connection.get('mount_point_base')
        brick_connector = self._brick_get_connector(
            connection['driver_volume_type'],
            nfs_mount_point_base=nfs_mount_point_base)

        # TODO(e0ne): use real device info from params
        device_info = {}
        brick_connector.disconnect_volume(connection['data'], device_info)
        protocol = connection['driver_volume_type']
        protocol = protocol.upper()
        if protocol == 'RBD':
            # TODO(e0ne): move to detach_rbd_volume() function
            # TODO(e0ne): multipath support
            pool, volume = connection['data']['name'].split('/')
            dev_name = '/dev/rbd/{pool}/{volume}'.format(pool=pool,
                                                         volume=volume)
            cmd = ['rbd', 'unmap', dev_name]
            processutils.execute(*cmd,
                                 root_helper=utils.get_root_helper(),
                                 run_as_root=True)
        elif protocol == 'NFS':
            nfs_share = connection['data']['export']
            cmd = ['umount', nfs_share]
            processutils.execute(*cmd, root_helper=utils.get_root_helper(),
                                 run_as_root=True)
        client.volumes.terminate_connection(volume_id, conn_prop)
        client.volumes.detach(volume_id)
Esempio n. 14
0
File: iet.py Progetto: mahak/cinder
def new_auth(tid, type, username, password):
    processutils.execute('ietadm', '--op', 'new',
                         '--tid=%s' % tid,
                         '--user',
                         '--params=%s=%s,Password=%s' % (type,
                                                         username,
                                                         password))
Esempio n. 15
0
def generate_key_pair(key_length=2048):
    """Create RSA key pair with specified number of bits in key.

    Returns tuple of private and public keys.
    """
    with tempfiles.tempdir() as tmpdir:
        keyfile = os.path.join(tmpdir, 'tempkey')
        # The key is generated in the old PEM format, instead of the native
        # format of OpenSSH >=6.5, because paramiko does not support it:
        # https://github.com/paramiko/paramiko/issues/602
        args = [
            'ssh-keygen',
            '-q',  # quiet
            '-N', '',  # w/o passphrase
            '-m', 'PEM',  # old PEM format
            '-t', 'rsa',  # create key of rsa type
            '-f', keyfile,  # filename of the key file
            '-C', 'Generated-by-Sahara'  # key comment
        ]
        if key_length is not None:
            args.extend(['-b', key_length])
        processutils.execute(*args)
        if not os.path.exists(keyfile):
            raise ex.SystemError(_("Private key file hasn't been created"))
        with open(keyfile) as keyfile_fd:
            private_key = keyfile_fd.read()
        public_key_path = keyfile + '.pub'
        if not os.path.exists(public_key_path):
            raise ex.SystemError(_("Public key file hasn't been created"))
        with open(public_key_path) as public_key_path_fd:
            public_key = public_key_path_fd.read()

        return private_key, public_key
Esempio n. 16
0
def unplug_contrail_vif(port_id):
    cmd = (
        'vrouter-port-control',
        '--oper=delete',
        '--uuid=%s' % port_id,
    )
    processutils.execute(*cmd)
def get_host_numa_placement(instance, vcpus):
    """Get placement of instance CPUs on host.

    :param instance: Instance to get placement for.
    :param vcpus: Number of vCPUs on instance.
    """
    out, _ = processutils.execute('ps -eo pid,cmd,args | awk \'/%s/ && '
                                  '!/grep/ {print $1}\'' %
                                  instance['id'], shell=True)
    if not out:
        return

    cgroup, _ = processutils.execute('grep cpuset /proc/%s/cgroup'
                                     % out.strip(), shell=True)
    cgroup = cgroup.split(":")[-1].strip()
    if cgroup.index('emulator'):
        cgroup += '/..'

    placement = []
    for i in range(vcpus):
        cpus, _ = processutils.execute('cgget -n -v -r cpuset.cpus %s'
                                       % (cgroup.replace('\\', '\\\\') +
                                          '/vcpu' + str(i)), shell=True)
        placement.append(cpus.strip())

    return placement
Esempio n. 18
0
    def configure_add(self):
        """
        Configure the Store to use the stored configuration options
        Any store that needs special configuration should implement
        this method. If the store was not able to successfully configure
        itself, it should raise `exceptions.BadStoreConfiguration`
        """

        try:
            chunk_size = self.conf.glance_store.sheepdog_store_chunk_size
            self.chunk_size = chunk_size * units.Mi
            self.READ_CHUNKSIZE = self.chunk_size
            self.WRITE_CHUNKSIZE = self.READ_CHUNKSIZE

            self.addr = self.conf.glance_store.sheepdog_store_address
            self.port = self.conf.glance_store.sheepdog_store_port
        except cfg.ConfigFileValueError as e:
            reason = _("Error in store configuration: %s") % e
            LOG.error(reason)
            raise exceptions.BadStoreConfiguration(store_name="sheepdog", reason=reason)

        try:
            processutils.execute("collie", shell=True)
        except processutils.ProcessExecutionError as exc:
            reason = _("Error in store configuration: %s") % exc
            LOG.error(reason)
            raise exceptions.BadStoreConfiguration(store_name="sheepdog", reason=reason)
Esempio n. 19
0
def set_device_macaddr(dev, mac_addr, port_state=None):
    if port_state:
        processutils.execute('ip', 'link', 'set', dev, 'address', mac_addr,
                             port_state, check_exit_code=[0, 2, 254])
    else:
        processutils.execute('ip', 'link', 'set', dev, 'address', mac_addr,
                             check_exit_code=[0, 2, 254])
Esempio n. 20
0
def copy_image(src, dest, host=None, receive=False,
               on_execute=None, on_completion=None,
               compression=True):
    """Copy a disk image to an existing directory

    :param src: Source image
    :param dest: Destination path
    :param host: Remote host
    :param receive: Reverse the rsync direction
    :param on_execute: Callback method to store pid of process in cache
    :param on_completion: Callback method to remove pid of process from cache
    :param compression: Allows to use rsync operation with or without
                        compression
    """

    if not host:
        # We shell out to cp because that will intelligently copy
        # sparse files.  I.E. holes will not be written to DEST,
        # rather recreated efficiently.  In addition, since
        # coreutils 8.11, holes can be read efficiently too.
        # we add '-r' argument because ploop disks are directories
        processutils.execute('cp', '-r', src, dest)
    else:
        if receive:
            src = "%s:%s" % (utils.safe_ip_format(host), src)
        else:
            dest = "%s:%s" % (utils.safe_ip_format(host), dest)

        remote_filesystem_driver = remotefs.RemoteFilesystem()
        remote_filesystem_driver.copy_file(src, dest,
            on_execute=on_execute, on_completion=on_completion,
            compression=compression)
Esempio n. 21
0
def _s3_decrypt_image(context, encrypted_filename, encrypted_key,
                      encrypted_iv, decrypted_filename):
    encrypted_key = binascii.a2b_hex(encrypted_key)
    encrypted_iv = binascii.a2b_hex(encrypted_iv)
    cert_client = clients.nova_cert(context)
    try:
        key = cert_client.decrypt_text(base64.b64encode(encrypted_key))
    except Exception as exc:
        msg = _('Failed to decrypt private key: %s') % exc
        raise exception.EC2Exception(msg)
    try:
        iv = cert_client.decrypt_text(base64.b64encode(encrypted_iv))
    except Exception as exc:
        msg = _('Failed to decrypt initialization vector: %s') % exc
        raise exception.EC2Exception(msg)

    try:
        processutils.execute('openssl', 'enc',
                             '-d', '-aes-128-cbc',
                             '-in', '%s' % (encrypted_filename,),
                             '-K', '%s' % (key,),
                             '-iv', '%s' % (iv,),
                             '-out', '%s' % (decrypted_filename,))
    except processutils.ProcessExecutionError as exc:
        raise exception.EC2Exception(_('Failed to decrypt image file '
                                       '%(image_file)s: %(err)s') %
                                     {'image_file': encrypted_filename,
                                      'err': exc.stdout})
Esempio n. 22
0
def create_cow_image(backing_file, path, size=None):
    """Create COW image

    Creates a COW image with the given backing file

    :param backing_file: Existing image on which to base the COW image
    :param path: Desired location of the COW image
    """
    base_cmd = ['qemu-img', 'create', '-f', 'qcow2']
    cow_opts = []
    if backing_file:
        cow_opts += ['backing_file=%s' % backing_file]
        base_details = images.qemu_img_info(backing_file)
    else:
        base_details = None
    # Explicitly inherit the value of 'cluster_size' property of a qcow2
    # overlay image from its backing file. This can be useful in cases
    # when people create a base image with a non-default 'cluster_size'
    # value or cases when images were created with very old QEMU
    # versions which had a different default 'cluster_size'.
    if base_details and base_details.cluster_size is not None:
        cow_opts += ['cluster_size=%s' % base_details.cluster_size]
    if size is not None:
        cow_opts += ['size=%s' % size]
    if cow_opts:
        # Format as a comma separated list
        csv_opts = ",".join(cow_opts)
        cow_opts = ['-o', csv_opts]
    cmd = base_cmd + cow_opts + [path]
    processutils.execute(*cmd)
Esempio n. 23
0
def unplug_contrail_vif(port_id, dev_name=None, vnic_type=None, pci_dev=None,
                        vhostuser_socket=None, vhostuser_mode=None):
    """Call the vrouter port control script to unplug a vif

    :param port_id: VIF ID to unplug
    :param dev_name: Name of the TAP/device to unplug
    :param vnic_type: Selector for offload mode (e.g. direct)
    :param pci_dev: Virtual Function to assign for offloading
    :param vhostuser_socket: vhost-user socket path
    :param vhostuser_mode: vhost-user mode (client/server)
    """
    cmd = (
        'vrouter-port-control',
        '--oper=delete',
        '--uuid=%s' % port_id,
    )
    if dev_name:
        cmd += ('--tap_name=%s' % dev_name,)
    if vnic_type:
        cmd += ('--vnic_type=%s' % vnic_type,)
    if pci_dev:
        cmd += ('--pci_dev=%s' % pci_dev,)
    if vhostuser_socket:
        cmd += ('--vhostuser_socket=%s' % vhostuser_socket,)
    if vhostuser_mode is not None:
        cmd += ('--vhostuser_mode=%s' % vhostuser_mode,)
    try:
        env = dict(os.environ)
        env['PATH'] = env['PATH'] + ':/opt/plugin/bin'
        processutils.execute(*cmd, env_variables=env)
    except Exception as e:
        LOG.error(_LE("Unable to execute vrouter-port-control "
                      "%(args)s.  Exception: %(exception)s"),
                  {'args': cmd, 'exception': e})
        raise exception.VrouterPortControlError(args=cmd)
Esempio n. 24
0
    def attach(self, client, volume_id, hostname):
        # TODO(e0ne): use oslo.rootwrap
        # TODO(e0ne): multipath support
        root_helper = 'sudo'
        conn_prop = connector.get_connector_properties(root_helper,
                                                       _get_my_ip(),
                                                       multipath=False,
                                                       enforce_multipath=False)
        connection = client.volumes.initialize_connection(volume_id, conn_prop)

        protocol = connection['driver_volume_type']
        protocol = protocol.upper()
        nfs_mount_point_base = connection.get('mount_point_base')
        brick_connector = self._brick_get_connector(
            protocol, nfs_mount_point_base=nfs_mount_point_base)

        device_info = brick_connector.connect_volume(connection['data'])
        if protocol == 'RBD':
            # TODO(e0ne): move to attach_rbd_volume() function
            # TODO(e0ne): use oslo.rootwrap
            # TODO(e0ne): multipath support
            pool, volume = connection['data']['name'].split('/')
            cmd = ['rbd', 'map', volume, '--pool', pool]
            processutils.execute(*cmd, root_helper='sudo', run_as_root=True)
        client.volumes.attach(volume_id, None, None, host_name=hostname)
        return device_info
Esempio n. 25
0
 def test_decrypt_text(self):
     public_key = os.path.join(os.path.dirname(__file__), 'test_cert.pem')
     private_key = os.path.join(os.path.dirname(__file__),
                                'test_private_key.pem')
     subject = "/C=RU/ST=Moscow/L=Moscow/O=Progmatic/CN=RootCA"
     certificate_file = processutils.execute('openssl',
                                             'req', '-x509', '-new',
                                             '-key', private_key,
                                             '-days', '365',
                                             '-out', public_key,
                                             '-subj', subject)
     text = "some @#!%^* test text"
     process_input = text.encode("ascii") if six.PY3 else text
     enc, _err = processutils.execute('openssl',
                                      'rsautl',
                                      '-certin',
                                      '-encrypt',
                                      '-inkey', public_key,
                                      process_input=process_input,
                                      binary=True)
     self.assertRaises(exception.EC2Exception, image_api._decrypt_text, enc)
     self.configure(x509_root_private_key=private_key)
     dec = image_api._decrypt_text(enc)
     self.assertIsInstance(dec, bytes)
     if six.PY3:
         dec = dec.decode('ascii')
     self.assertEqual(text, dec)
Esempio n. 26
0
def plug_contrail_vif(vif_id, vm_id, net_id, project_id, ip_addr, ip6_addr,
                      vm_name, mac, dev_name, port_type, vif_type=None,
                      vnic_type=None, pci_dev=None, vhostuser_socket=None,
                      vhostuser_mode=None):
    """Call the vrouter port control script to plug a VIF

    :param vif_id: VIF ID to plug
    :param vm_id: Instance ID
    :param net_id: Network ID
    :param project_id: Project ID associated with the instance
    :param ip_addr: IPv4 address to assign to the interface
    :param ip6_addr: IPv6 address to assign to the interface
    :param vm_name: Display name of the instance
    :param mac: MAC address to assign to the interface
    :param dev_name: Name of the TAP/device to plug
    :param port_type: vrouter port type (e.g. NovaVMPort)
    :param vif_type: vrouter VIF type (e.g. VhostUser)
    :param vnic_type: Selector for offload mode (e.g. direct)
    :param pci_dev: Virtual Function to assign for offloading
    :param vhostuser_socket: vhost-user socket path
    :param vhostuser_mode: vhost-user mode (client/server)
    """
    cmd = (
        'vrouter-port-control',
        '--oper=add',
        '--uuid=%s' % vif_id,
        '--instance_uuid=%s' % vm_id,
        '--vn_uuid=%s' % net_id,
        '--vm_project_uuid=%s' % project_id,
        '--ip_address=%s' % ip_addr,
        '--ipv6_address=%s' % ip6_addr,
        '--vm_name=%s' % vm_name,
        '--mac=%s' % mac,
        '--tap_name=%s' % dev_name,
        '--port_type=%s' % port_type,
    )
    if vif_type:
        cmd += ('--vif_type=%s' % vif_type,)
    if vnic_type:
        cmd += ('--vnic_type=%s' % vnic_type,)
    if pci_dev:
        cmd += ('--pci_dev=%s' % pci_dev,)
    if vhostuser_socket:
        cmd += ('--vhostuser_socket=%s' % vhostuser_socket,)
    if vhostuser_mode is not None:
        cmd += ('--vhostuser_mode=%s' % vhostuser_mode,)
    cmd += (
        '--tx_vlan_id=%d' % -1,
        '--rx_vlan_id=%d' % -1,
    )
    try:
        env = dict(os.environ)
        env['PATH'] = env['PATH'] + ':/opt/plugin/bin'
        processutils.execute(*cmd, env_variables=env)
    except Exception as e:
        LOG.error(_LE("Unable to execute vrouter-port-control "
                      "%(args)s.  Exception: %(exception)s"),
                  {'args': cmd, 'exception': e})
        raise exception.VrouterPortControlError(args=cmd)
    def test_relative_path(self):
        prlimit = self.limit_address_space()
        program = sys.executable

        env = dict(os.environ)
        env['PATH'] = os.path.dirname(program)
        args = [os.path.basename(program), '-c', 'pass']
        processutils.execute(*args, prlimit=prlimit, env_variables=env)
Esempio n. 28
0
def run_vrouter_port_control(args):
    try:
        processutils.execute("vrouter-port-control", args)
    except Exception as e:
        LOG.error(_LE("Unable to execute vrouter-port-control " +
                      "%(args)s.  Exception: %(exception)s"),
                  {'args': args, 'exception': e})
        raise exception.VrouterPortControlError(args=args)
Esempio n. 29
0
def block_copy(src_path, dst_path, block_size, num_blocks):
    processutils.execute('dd',
                         'if=%s' % src_path,
                         'of=%s' % dst_path,
                         'bs=%d' % block_size,
                         'count=%d' % num_blocks,
                         'iflag=direct,sync',
                         'oflag=direct,sync')
Esempio n. 30
0
def bind_ip(device, ip, scope_is_link=False):
    if not scope_is_link:
        processutils.execute('ip', 'addr', 'add', str(ip) + '/32',
                             'dev', device, check_exit_code=[0, 2, 254])
    else:
        processutils.execute('ip', 'addr', 'add', str(ip) + '/32',
                             'scope', 'link', 'dev', device,
                             check_exit_code=[0, 2, 254])
Esempio n. 31
0
def ext_journal_disable(device):
    processutils.execute('tune2fs', '-O ^has_journal', device)
Esempio n. 32
0
def lvremove(path):
    processutils.execute('lvremove', '-f', path, attempts=3)
def cleanup_vpmem(devpath):
    daxio_cmd = ['daxio', '-z', '-o', '%s' % devpath]
    processutils.execute(*daxio_cmd)
Esempio n. 34
0
def loopsetup(path):
    return processutils.execute('losetup', '--find', '--show', path)
Esempio n. 35
0
def nbd_connect(device, image):
    return processutils.execute('qemu-nbd', '-c', device, image)
def unprivileged_qb_mount(qb_vol, mnt_base, cfg_file=None):
    """Mount QB volume"""
    mnt_cmd = ['mount.quobyte', '--disable-xattrs', qb_vol, mnt_base]
    if cfg_file:
        mnt_cmd.extend(['-c', cfg_file])
    return processutils.execute(*mnt_cmd)
def get_pmem_namespaces():
    ndctl_cmd = ['ndctl', 'list', '-X']
    nss_info = processutils.execute(*ndctl_cmd)[0]
    return nss_info
Esempio n. 38
0
def vginfo(vg):
    return processutils.execute('vgs', '--noheadings', '--nosuffix',
                                '--separator', '|', '--units', 'b', '-o',
                                'vg_size,vg_free', vg)
Esempio n. 39
0
def execute_root(*cmd, **kwargs):
    return putils.execute(*cmd, shell=False, run_as_root=False, **kwargs)
Esempio n. 40
0
def lvlist(vg):
    return processutils.execute('lvs', '--noheadings', '-o', 'lv_name', vg)
Esempio n. 41
0
def blockdev_size(path):
    return processutils.execute('blockdev', '--getsize64', path)
Esempio n. 42
0
def unprivileged_e2fsck(image, flags='-fp'):
    processutils.execute('e2fsck', flags, image, check_exit_code=[0, 1, 2])
Esempio n. 43
0
def remove_device_maps(device):
    return processutils.execute('kpartx', '-d', device)
Esempio n. 44
0
 def test_check_cwd(self):
     tmpdir = tempfile.mkdtemp()
     out, err = processutils.execute('/usr/bin/env',
                                     'sh', '-c', 'pwd',
                                     cwd=tmpdir)
     self.assertIn(tmpdir, out)
Esempio n. 45
0
def create_device_maps(device):
    return processutils.execute('kpartx', '-a', device)
Esempio n. 46
0
def clear_volume(volume_id):
    lvm = 'vg_os/volume-%s' % volume_id
    out, err = processutils.execute('lvremove', lvm)
    raise Exception(out, err)
Esempio n. 47
0
def nbd_disconnect(device):
    return processutils.execute('qemu-nbd', '-d', device)
Esempio n. 48
0
def execute(*cmd, **kwargs):
    """Convenience wrapper around oslo's execute() function."""
    if 'run_as_root' in kwargs and 'root_helper' not in kwargs:
        kwargs['root_helper'] = _get_root_helper()
    return processutils.execute(*cmd, **kwargs)
Esempio n. 49
0
def loopremove(device):
    return processutils.execute('losetup', '--detach', device, attempts=3)
Esempio n. 50
0
def add_bridge(interface):
    """Add a bridge.

    :param interface: the name of the bridge
    """
    processutils.execute('brctl', 'addbr', interface)
def dmcrypt_delete_volume(target):
    """Deletes a dmcrypt mapping

    :param target: name of the mapped logical device
    """
    processutils.execute('cryptsetup', 'remove', target)
Esempio n. 52
0
def umount(mountpoint):
    processutils.execute('umount', mountpoint, attempts=3, delay_on_retry=True)
Esempio n. 53
0
def ext_journal_enable(device):
    processutils.execute('tune2fs', '-j', device)
Esempio n. 54
0
def lvinfo(path):
    return processutils.execute('lvs', '-o', 'vg_all,lv_all', '--separator',
                                '|', path)
Esempio n. 55
0
def _execute_command(*args):
    return processutils.execute(*args)
def unprivileged_umount(mnt_base):
    """Unmount volume"""
    umnt_cmd = ['umount', mnt_base]
    return processutils.execute(*umnt_cmd)
Esempio n. 57
0
def run_nova_cell_v2_discovery():
    return processutils.execute('/usr/bin/sudo', '/bin/nova-manage', 'cell_v2',
                                'discover_hosts', '--verbose')
Esempio n. 58
0
 def test_check_exit_code_boolean(self):
     processutils.execute('/usr/bin/env', 'false', check_exit_code=False)
     self.assertRaises(processutils.ProcessExecutionError,
                       processutils.execute,
                       '/usr/bin/env', 'false', check_exit_code=True)
Esempio n. 59
0
def blockdev_flush(path):
    return processutils.execute('blockdev', '--flushbufs', path)
def xend_probe():
    processutils.execute('xend', 'status', check_exit_code=True)