Python oslo_utils.fileutils.delete_if_exists() Examples

The following are 11 code examples of oslo_utils.fileutils.delete_if_exists(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oslo_utils.fileutils , or try the search function .
Example #1
Source File: rbd.py    From os-brick with Apache License 2.0 6 votes vote down vote up
def disconnect_volume(self, connection_properties, device_info,
                          force=False, ignore_errors=False):
        """Disconnect a volume.

        :param connection_properties: The dictionary that describes all
                                      of the target volume attributes.
        :type connection_properties: dict
        :param device_info: historical difference, but same as connection_props
        :type device_info: dict
        """
        do_local_attach = connection_properties.get('do_local_attach',
                                                    self.do_local_attach)
        if do_local_attach:
            root_device = self._find_root_device(connection_properties)
            if root_device:
                cmd = ['rbd', 'unmap', root_device]
                cmd += self._get_rbd_args(connection_properties)
                self._execute(*cmd, root_helper=self._root_helper,
                              run_as_root=True)
        else:
            if device_info:
                rbd_handle = device_info.get('path', None)
                if rbd_handle is not None:
                    fileutils.delete_if_exists(rbd_handle.rbd_conf)
                    rbd_handle.close() 
Example #2
Source File: pathutils.py    From compute-hyperv with Apache License 2.0 5 votes vote down vote up
def check_instance_shared_storage_cleanup(self, data):
        fileutils.delete_if_exists(data["filename"]) 
Example #3
Source File: vmops.py    From compute-hyperv with Apache License 2.0 5 votes vote down vote up
def unrescue_instance(self, instance):
        self.power_off(instance)

        root_vhd_path = self._pathutils.lookup_root_vhd_path(instance.name)
        rescue_vhd_path = self._pathutils.lookup_root_vhd_path(instance.name,
                                                               rescue=True)

        if (instance.vm_state == vm_states.RESCUED and
                not (rescue_vhd_path and root_vhd_path)):
            err_msg = _('Missing instance root and/or rescue image. '
                        'The instance cannot be unrescued.')
            raise exception.InstanceNotRescuable(reason=err_msg,
                                                 instance_id=instance.uuid)

        vm_gen = self._vmutils.get_vm_generation(instance.name)
        controller_type = VM_GENERATIONS_CONTROLLER_TYPES[vm_gen]

        self._vmutils.detach_vm_disk(instance.name, root_vhd_path,
                                     is_physical=False)
        if rescue_vhd_path:
            self._vmutils.detach_vm_disk(instance.name, rescue_vhd_path,
                                         is_physical=False)
            fileutils.delete_if_exists(rescue_vhd_path)
        self._attach_drive(instance.name, root_vhd_path, 0,
                           self._ROOT_DISK_CTRL_ADDR, controller_type)

        self._detach_config_drive(instance.name, rescue=True, delete=True)

        # Reattach the configdrive, if exists and not already attached.
        configdrive_path = self._pathutils.lookup_configdrive_path(
            instance.name)
        if configdrive_path and not self._vmutils.is_disk_attached(
                configdrive_path, is_physical=False):
            self.attach_config_drive(instance, configdrive_path, vm_gen)

        self.power_on(instance) 
Example #4
Source File: rbd.py    From os-brick with Apache License 2.0 5 votes vote down vote up
def _get_rbd_handle(self, connection_properties):
        try:
            user = connection_properties['auth_username']
            pool, volume = connection_properties['name'].split('/')
            cluster_name = connection_properties['cluster_name']
            monitor_ips = connection_properties['hosts']
            monitor_ports = connection_properties['ports']
            keyring = connection_properties.get('keyring')
        except (KeyError, ValueError):
            msg = _("Connect volume failed, malformed connection properties.")
            raise exception.BrickException(msg=msg)

        conf = self._create_ceph_conf(monitor_ips, monitor_ports,
                                      str(cluster_name), user,
                                      keyring)
        try:
            rbd_client = linuxrbd.RBDClient(user, pool, conffile=conf,
                                            rbd_cluster_name=str(cluster_name))
            rbd_volume = linuxrbd.RBDVolume(rbd_client, volume)
            rbd_handle = linuxrbd.RBDVolumeIOWrapper(
                linuxrbd.RBDImageMetadata(rbd_volume, pool, user, conf))
        except Exception:
            fileutils.delete_if_exists(conf)
            raise

        return rbd_handle 
Example #5
Source File: pathutils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def temporary_file(self, suffix=None, *args, **kwargs):
        """Creates a random, temporary, closed file, returning the file's

        path. It's different from tempfile.NamedTemporaryFile which returns
        an open file descriptor.
        """

        tmp_file_path = None
        try:
            tmp_file_path = self.create_temporary_file(suffix, *args, **kwargs)
            yield tmp_file_path
        finally:
            if tmp_file_path:
                fileutils.delete_if_exists(tmp_file_path) 
Example #6
Source File: file_system.py    From qinling with Apache License 2.0 5 votes vote down vote up
def store(self, project_id, function, data, md5sum=None):
        """Store the function package data to local file system.

        :param project_id: Project ID.
        :param function: Function ID.
        :param data: Package file content.
        :param md5sum: The MD5 provided by the user.
        :return: A tuple (if the package is updated, MD5 value of the package)
        """
        LOG.debug(
            'Store package, function: %s, project: %s', function, project_id
        )

        project_path = os.path.join(self.base_path, project_id)
        fileutils.ensure_tree(project_path)

        # Check md5
        md5_actual = common.md5(content=data)
        if md5sum and md5_actual != md5sum:
            raise exc.InputException("Package md5 mismatch.")

        func_zip = os.path.join(
            project_path,
            PACKAGE_NAME_TEMPLATE % (function, md5_actual)
        )
        if os.path.exists(func_zip):
            return False, md5_actual

        # Save package
        new_func_zip = os.path.join(project_path, '%s.zip.new' % function)
        with open(new_func_zip, 'wb') as fd:
            fd.write(data)

        if not zipfile.is_zipfile(new_func_zip):
            fileutils.delete_if_exists(new_func_zip)
            raise exc.InputException("Package is not a valid ZIP package.")

        os.rename(new_func_zip, func_zip)

        return True, md5_actual 
Example #7
Source File: test_fileutils.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def test_file_present(self):
        tmpfile = tempfile.mktemp()

        open(tmpfile, 'w')
        fileutils.delete_if_exists(tmpfile)
        self.assertFalse(os.path.exists(tmpfile)) 
Example #8
Source File: test_fileutils.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def test_file_absent(self):
        tmpfile = tempfile.mktemp()

        fileutils.delete_if_exists(tmpfile)
        self.assertFalse(os.path.exists(tmpfile)) 
Example #9
Source File: test_fileutils.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def test_dir_present(self):
        tmpdir = tempfile.mktemp()
        os.mkdir(tmpdir)

        fileutils.delete_if_exists(tmpdir, remove=os.rmdir)
        self.assertFalse(os.path.exists(tmpdir)) 
Example #10
Source File: test_fileutils.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def test_file_error(self):
        def errm(path):
            raise OSError(errno.EINVAL, '')

        tmpfile = tempfile.mktemp()

        open(tmpfile, 'w')
        self.assertRaises(OSError, fileutils.delete_if_exists, tmpfile, errm)
        os.unlink(tmpfile) 
Example #11
Source File: test_fileutils.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def test_remove_dir(self):
        tmpdir = tempfile.mktemp()
        os.mkdir(tmpdir)

        try:
            with fileutils.remove_path_on_error(
                    tmpdir,
                    lambda path: fileutils.delete_if_exists(path, os.rmdir)):
                raise Exception
        except Exception:
            self.assertFalse(os.path.exists(tmpdir))