def test_chown_file_err(self):
     try:
         fs.do_chown(os.path.join('/tmp', str(random.random())),
                     20000, 20000)
     except SwiftOnFileSystemOSError:
         pass
     else:
         self.fail("Expected SwiftOnFileSystemOSError")
 def test_chown_dir(self):
     tmpdir = mkdtemp()
     try:
         subdir = mkdtemp(dir=tmpdir)
         buf = os.stat(subdir)
         if buf.st_uid == 0:
             raise SkipTest
         else:
             try:
                 fs.do_chown(subdir, 20000, 20000)
             except SwiftOnFileSystemOSError as ex:
                 if ex.errno != errno.EPERM:
                     self.fail(
                         "Expected SwiftOnFileSystemOSError(errno=EPERM)")
             else:
                 self.fail("Expected SwiftOnFileSystemOSError")
     finally:
         shutil.rmtree(tmpdir)
 def test_chown_file(self):
     tmpdir = mkdtemp()
     try:
         fd, tmpfile = mkstemp(dir=tmpdir)
         buf = os.stat(tmpfile)
         if buf.st_uid == 0:
             raise SkipTest
         else:
             try:
                 fs.do_chown(tmpfile, 20000, 20000)
             except SwiftOnFileSystemOSError as ex:
                 if ex.errno != errno.EPERM:
                     self.fail(
                         "Expected SwiftOnFileSystemOSError(errno=EPERM")
             else:
                 self.fail("Expected SwiftOnFileSystemOSError")
     finally:
         os.close(fd)
         shutil.rmtree(tmpdir)
Пример #4
0
    def create(self, hpss_hints):
        """
        Context manager to create a file. We create a temporary file first, and
        then return a DiskFileWriter object to encapsulate the state.

        For Gluster, we first optimistically create the temporary file using
        the "rsync-friendly" .NAME.random naming. If we find that some path to
        the file does not exist, we then create that path and then create the
        temporary file again. If we get file name conflict, we'll retry using
        different random suffixes 1,000 times before giving up.

        .. note::

            An implementation is not required to perform on-disk
            preallocations even if the parameter is specified. But if it does
            and it fails, it must raise a `DiskFileNoSpace` exception.

        :param hpss_hints: dict containing HPSS class of service hints
        :raises DiskFileNoSpace: if a size is specified and allocation fails
        :raises AlreadyExistsAsFile: if path or part of a path is not a \
                                     directory
        """
        # Create /account/container directory structure on mount point root
        try:
            self._logger.debug("DiskFile: Creating directories for %s" %
                               self._container_path)
            hpss_utils.makedirs(self._container_path)
        except OSError as err:
            if err.errno != errno.EEXIST:
                raise

        # Create directories to object name, if they don't exist.
        self._logger.debug("DiskFile: creating directories in obj name %s" %
                           self._obj)
        object_dirs = os.path.split(self._obj)[0]
        self._logger.debug("object_dirs: %s" % repr(object_dirs))
        self._logger.debug("data_dir: %s" % self._put_datadir)
        hpss_utils.makedirs(os.path.join(self._put_datadir, object_dirs))

        data_file = os.path.join(self._put_datadir, self._obj)

        # Create the temporary file
        attempts = 1
        while True:
            tmpfile = '.%s.%s.temporary' % (self._obj,
                                            random.randint(0, 65536))
            tmppath = os.path.join(self._put_datadir, tmpfile)
            self._logger.debug("DiskFile: Creating temporary file %s" %
                               tmppath)

            try:
                # TODO: figure out how to create hints struct
                self._logger.debug("DiskFile: creating file")
                fd = do_open(tmppath,
                             hpss.O_WRONLY | hpss.O_CREAT | hpss.O_EXCL)
                self._logger.debug("DiskFile: setting COS")
                if hpss_hints['cos']:
                    hpss_utils.set_cos(tmppath, int(hpss_hints['cos']))

            except SwiftOnFileSystemOSError as gerr:
                if gerr.errno in (errno.ENOSPC, errno.EDQUOT):
                    # Raise DiskFileNoSpace to be handled by upper layers when
                    # there is no space on disk OR when quota is exceeded
                    self._logger.error("DiskFile: no space")
                    raise DiskFileNoSpace()
                if gerr.errno == errno.EACCES:
                    self._logger.error("DiskFile: permission denied")
                    raise DiskFileNoSpace()
                if gerr.errno == errno.ENOTDIR:
                    self._logger.error("DiskFile: not a directory")
                    raise AlreadyExistsAsFile('do_open(): failed on %s,'
                                              '  path or part of a'
                                              ' path is not a directory'
                                              % data_file)

                if gerr.errno not in (errno.ENOENT, errno.EEXIST, errno.EIO):
                    # FIXME: Other cases we should handle?
                    self._logger.error("DiskFile: unknown error %s"
                                       % gerr.errno)
                    raise
                if attempts >= MAX_OPEN_ATTEMPTS:
                    # We failed after N attempts to create the temporary
                    # file.
                    raise DiskFileError('DiskFile.mkstemp(): failed to'
                                        ' successfully create a temporary file'
                                        ' without running into a name conflict'
                                        ' after %d of %d attempts for: %s' % (
                                            attempts, MAX_OPEN_ATTEMPTS,
                                            data_file))
                if gerr.errno == errno.EEXIST:
                    self._logger.debug("DiskFile: file exists already")
                    # Retry with a different random number.
                    attempts += 1
            else:
                break
        dw = None

        self._logger.debug("DiskFile: created file")

        try:
            # Ensure it is properly owned before we make it available.
            do_chown(tmppath, self._uid, self._gid)
            dw = DiskFileWriter(fd, tmppath, self)
            yield dw
        finally:
            if dw:
                dw.close()
                if dw._tmppath:
                    do_unlink(dw._tmppath)
Пример #5
0
def make_directory(full_path, uid, gid, metadata=None):
    """
    Make a directory and change the owner ship as specified, and potentially
    creating the object metadata if requested.
    """
    try:
        do_mkdir(full_path)
    except OSError as err:
        if err.errno == errno.ENOENT:
            # Tell the caller some directory of the parent path does not
            # exist.
            return False, metadata
        elif err.errno == errno.EEXIST:
            # Possible race, in that the caller invoked this method when it
            # had previously determined the file did not exist.
            #
            # FIXME: When we are confident, remove this stat() call as it is
            # not necessary.
            try:
                stats = do_stat(full_path)
            except SwiftOnFileSystemOSError as serr:
                # FIXME: Ideally we'd want to return an appropriate error
                # message and code in the PUT Object REST API response.
                raise DiskFileError("make_directory: mkdir failed"
                                    " because path %s already exists, and"
                                    " a subsequent stat on that same"
                                    " path failed (%s)" % (full_path,
                                                           str(serr)))
            else:
                is_dir = stat.S_ISDIR(stats.st_mode)
                if not is_dir:
                    # FIXME: Ideally we'd want to return an appropriate error
                    # message and code in the PUT Object REST API response.
                    raise AlreadyExistsAsFile("make_directory:"
                                              " mkdir failed on path %s"
                                              " because it already exists"
                                              " but not as a directory"
                                              % (full_path))
            return True, metadata
        elif err.errno == errno.ENOTDIR:
            # FIXME: Ideally we'd want to return an appropriate error
            # message and code in the PUT Object REST API response.
            raise AlreadyExistsAsFile("make_directory:"
                                      " mkdir failed because some "
                                      "part of path %s is not in fact"
                                      " a directory" % (full_path))
        elif err.errno == errno.EIO:
            # Sometimes Fuse will return an EIO error when it does not know
            # how to handle an unexpected, but transient situation. It is
            # possible the directory now exists, stat() it to find out after a
            # short period of time.
            _random_sleep()
            try:
                stats = do_stat(full_path)
            except SwiftOnFileSystemOSError as serr:
                if serr.errno == errno.ENOENT:
                    errmsg = "make_directory: mkdir failed on" \
                             " path %s (EIO), and a subsequent stat on" \
                             " that same path did not find the file." % (
                                 full_path,)
                else:
                    errmsg = "make_directory: mkdir failed on" \
                             " path %s (%s), and a subsequent stat on" \
                             " that same path failed as well (%s)" % (
                                 full_path, str(err), str(serr))
                raise DiskFileError(errmsg)
            else:
                if not stats:
                    errmsg = "make_directory: mkdir failed on" \
                             " path %s (EIO), and a subsequent stat on" \
                             " that same path did not find the file." % (
                                 full_path,)
                    raise DiskFileError(errmsg)
                else:
                    # The directory at least exists now
                    is_dir = stat.S_ISDIR(stats.st_mode)
                    if is_dir:
                        # Dump the stats to the log with the original exception
                        logging.warn("make_directory: mkdir initially"
                                     " failed on path %s (%s) but a stat()"
                                     " following that succeeded: %r" %
                                     (full_path, str(err), stats))
                        # Assume another entity took care of the proper setup.
                        return True, metadata
                    else:
                        raise DiskFileError("make_directory: mkdir"
                                            " initially failed on path %s (%s)"
                                            " but now we see that it exists"
                                            " but is not a directory (%r)" %
                                            (full_path, str(err), stats))
        else:
            # Some other potentially rare exception occurred that does not
            # currently warrant a special log entry to help diagnose.
            raise DiskFileError("make_directory: mkdir failed on"
                                " path %s (%s)" % (full_path, str(err)))
    else:
        if metadata:
            # We were asked to set the initial metadata for this object.
            metadata_orig = get_object_metadata(full_path)
            metadata_orig.update(metadata)
            write_metadata(full_path, metadata_orig)
            metadata = metadata_orig

        # We created it, so we are reponsible for always setting the proper
        # ownership.
        do_chown(full_path, uid, gid)
        return True, metadata