def _create_dir_object(self, dir_path, metadata=None): """ Create a directory object at the specified path. No check is made to see if the directory object already exists, that is left to the caller (this avoids a potentially duplicate stat() system call). The "dir_path" must be relative to its container, self._container_path. The "metadata" object is an optional set of metadata to apply to the newly created directory object. If not present, no initial metadata is applied. The algorithm used is as follows: 1. An attempt is made to create the directory, assuming the parent directory already exists * Directory creation races are detected, returning success in those cases 2. If the directory creation fails because some part of the path to the directory does not exist, then a search back up the path is performed to find the first existing ancestor directory, and then the missing parents are successively created, finally creating the target directory """ full_path = os.path.join(self._container_path, dir_path) cur_path = full_path stack = [] while True: md = None if cur_path != full_path else metadata ret, newmd = make_directory(cur_path, self._uid, self._gid, md) if ret: break # Some path of the parent did not exist, so loop around and # create that, pushing this parent on the stack. if os.path.sep not in cur_path: raise DiskFileError("DiskFile._create_dir_object(): failed to" " create directory path while exhausting" " path elements to create: %s" % full_path) cur_path, child = cur_path.rsplit(os.path.sep, 1) assert child stack.append(child) child = stack.pop() if stack else None while child: cur_path = os.path.join(cur_path, child) md = None if cur_path != full_path else metadata ret, newmd = make_directory(cur_path, self._uid, self._gid, md) if not ret: raise DiskFileError("DiskFile._create_dir_object(): failed to" " create directory path to target, %s," " on subpath: %s" % (full_path, cur_path)) child = stack.pop() if stack else None return True, newmd
def get_data_file_size(self): """ Returns the os.path.getsize for the file. Raises an exception if this file does not match the Content-Length stored in the metadata. Or if self.data_file does not exist. :returns: file size as an int :raises DiskFileError: on file size mismatch. :raises DiskFileNotExist: on file not existing (including deleted) """ try: file_size = 0 if self.data_file: file_size = self.threadpool.run_in_thread( getsize, self.data_file) if 'Content-Length' in self.metadata: metadata_size = int(self.metadata['Content-Length']) if file_size != metadata_size: raise DiskFileError( 'Content-Length of %s does not match file size ' 'of %s' % (metadata_size, file_size)) return file_size except OSError, err: if err.errno != errno.ENOENT: raise
def write(self, obj, offset, data): try: return self._ioctx.write(obj, data, offset) except self._fs.RADOS.NoSpace: raise DiskFileNoSpace() except Exception: raise DiskFileError()
def get_data_file_size(self): """ Returns the Original-Content-Length stored in metadata, whi is length of not crypted file. Also check if os.path.getsize does not match the Content-Length stored in the metadata. Or il self.data_file does not exist. :returns: file size as an int :raises DiskFileError: on file size mismatch. :raises DiskFileNotExist: on file not existing (including deleted) """ try: file_size = 0 if self.data_file: file_size = os.path.getsize(self.data_file) if 'Content-Length' in self.metadata: metadata_size = int(self.metadata['Content-Length']) if file_size != metadata_size: raise DiskFileError( 'Content-Length of %s does not match file size ' 'of %s' % (metadata_size, file_size)) original_file_size = \ int(self.metadata['Original-Content-Length']) if original_file_size: return original_file_size else: return file_size except OSError, err: if err.errno != errno.ENOENT: raise
def _get_ondisk_file(self): """ Do the work to figure out if the data directory exists, and if so, determine the on-disk files to use. :returns: a tuple of data, meta and ts (tombstone) files, in one of three states: * all three are None data directory does not exist, or there are no files in that directory * ts_file is not None, data_file is None, meta_file is None object is considered deleted * data_file is not None, ts_file is None object exists, and optionally has fast-POST metadata """ data_file = meta_file = ts_file = None try: files = sorted(os.listdir(self._datadir), reverse=True) except OSError as err: if err.errno != errno.ENOENT: raise DiskFileError() # The data directory does not exist, so the object cannot exist. else: for afile in files: assert ts_file is None, "On-disk file search loop" \ " continuing after tombstone, %s, encountered" % ts_file assert data_file is None, "On-disk file search loop" \ " continuing after data file, %s, encountered" % data_file if afile.endswith('.ts'): meta_file = None ts_file = join(self._datadir, afile) break if afile.endswith('.meta') and not meta_file: meta_file = join(self._datadir, afile) # NOTE: this does not exit this loop, since a fast-POST # operation just updates metadata, writing one or more # .meta files, the data file will have an older timestamp, # so we keep looking. continue if afile.endswith('.data'): data_file = join(self._datadir, afile) break assert ((data_file is None and meta_file is None and ts_file is None) or (ts_file is not None and data_file is None and meta_file is None) or (data_file is not None and ts_file is None)), \ "On-disk file search algorithm contract is broken: data_file:" \ " %s, meta_file: %s, ts_file: %s" % (data_file, meta_file, ts_file) return data_file, meta_file, ts_file
def _get_data_file_size(self): # ensure file is opened metadata = self.get_metadata() try: file_size = 0 if self.data_file: file_size = self.threadpool.run_in_thread( getsize, self.data_file) if 'Content-Length' in metadata: metadata_size = int(metadata['Content-Length']) if file_size != metadata_size: raise DiskFileError( 'Content-Length of %s does not match file size ' 'of %s' % (metadata_size, file_size)) return file_size except OSError as err: if err.errno != errno.ENOENT: raise raise DiskFileNotExist('Data File does not exist.')
def reconstruct_fa(self, job, node, datafile_metadata): """ Reconstructs a fragment archive - this method is called from ssync after a remote node responds that is missing this object - the local diskfile is opened to provide metadata - but to reconstruct the missing fragment archive we must connect to multiple object servers. :param job: job from ssync_sender :param node: node that we're rebuilding to :param datafile_metadata: the datafile metadata to attach to the rebuilt fragment archive :returns: a DiskFile like class for use by ssync :raises DiskFileError: if the fragment archive cannot be reconstructed """ part_nodes = job['policy'].object_ring.get_part_nodes(job['partition']) part_nodes.remove(node) # the fragment index we need to reconstruct is the position index # of the node we're rebuilding to within the primary part list fi_to_rebuild = node['index'] # KISS send out connection requests to all nodes, see what sticks headers = self.headers.copy() headers['X-Backend-Storage-Policy-Index'] = int(job['policy']) pile = GreenAsyncPile(len(part_nodes)) path = datafile_metadata['name'] for node in part_nodes: pile.spawn(self._get_response, node, job['partition'], path, headers, job['policy']) responses = [] etag = None for resp in pile: if not resp: continue resp.headers = HeaderKeyDict(resp.getheaders()) if str(fi_to_rebuild) == \ resp.headers.get('X-Object-Sysmeta-Ec-Frag-Index'): continue if resp.headers.get('X-Object-Sysmeta-Ec-Frag-Index') in set( r.headers.get('X-Object-Sysmeta-Ec-Frag-Index') for r in responses): continue responses.append(resp) etag = sorted( responses, reverse=True, key=lambda r: Timestamp(r.headers.get('X-Backend-Timestamp')) )[0].headers.get('X-Object-Sysmeta-Ec-Etag') responses = [ r for r in responses if r.headers.get('X-Object-Sysmeta-Ec-Etag') == etag ] if len(responses) >= job['policy'].ec_ndata: break else: self.logger.error('Unable to get enough responses (%s/%s) ' 'to reconstruct %s with ETag %s' % (len(responses), job['policy'].ec_ndata, self._full_path(node, job['partition'], datafile_metadata['name'], job['policy']), etag)) raise DiskFileError('Unable to reconstruct EC archive') rebuilt_fragment_iter = self.make_rebuilt_fragment_iter( responses[:job['policy'].ec_ndata], path, job['policy'], fi_to_rebuild) return RebuildingECDiskFileStream(datafile_metadata, fi_to_rebuild, rebuilt_fragment_iter)
def reconstruct_fa(self, job, node, datafile_metadata): """ Reconstructs a fragment archive - this method is called from ssync after a remote node responds that is missing this object - the local diskfile is opened to provide metadata - but to reconstruct the missing fragment archive we must connect to multiple object servers. :param job: job from ssync_sender :param node: node that we're rebuilding to :param datafile_metadata: the datafile metadata to attach to the rebuilt fragment archive :returns: a DiskFile like class for use by ssync :raises DiskFileError: if the fragment archive cannot be reconstructed """ part_nodes = job['policy'].object_ring.get_part_nodes(job['partition']) part_nodes.remove(node) # the fragment index we need to reconstruct is the position index # of the node we're rebuilding to within the primary part list fi_to_rebuild = job['policy'].get_backend_index(node['index']) # KISS send out connection requests to all nodes, see what sticks. # Use fragment preferences header to tell other nodes that we want # fragments at the same timestamp as our fragment, and that they don't # need to be durable. headers = self.headers.copy() headers['X-Backend-Storage-Policy-Index'] = int(job['policy']) frag_prefs = [{ 'timestamp': datafile_metadata['X-Timestamp'], 'exclude': [] }] headers['X-Backend-Fragment-Preferences'] = json.dumps(frag_prefs) pile = GreenAsyncPile(len(part_nodes)) path = datafile_metadata['name'] for _node in part_nodes: pile.spawn(self._get_response, _node, job['partition'], path, headers, job['policy']) buckets = defaultdict(dict) etag_buckets = {} error_resp_count = 0 for resp in pile: if not resp: error_resp_count += 1 continue resp.headers = HeaderKeyDict(resp.getheaders()) frag_index = resp.headers.get('X-Object-Sysmeta-Ec-Frag-Index') try: resp_frag_index = int(frag_index) except (TypeError, ValueError): # The successful response should include valid X-Object- # Sysmeta-Ec-Frag-Index but for safety, catching the case # either missing X-Object-Sysmeta-Ec-Frag-Index or invalid # frag index to reconstruct and dump warning log for that self.logger.warning( 'Invalid resp from %s ' '(invalid X-Object-Sysmeta-Ec-Frag-Index: %r)', resp.full_path, frag_index) continue if fi_to_rebuild == resp_frag_index: # TODO: With duplicated EC frags it's not unreasonable to find # the very fragment we're trying to rebuild exists on another # primary node. In this case we should stream it directly from # the remote node to our target instead of rebuild. But # instead we ignore it. self.logger.debug( 'Found existing frag #%s at %s while rebuilding to %s', fi_to_rebuild, resp.full_path, _full_path(node, job['partition'], datafile_metadata['name'], job['policy'])) continue timestamp = resp.headers.get('X-Backend-Timestamp') if not timestamp: self.logger.warning( 'Invalid resp from %s, frag index %s ' '(missing X-Backend-Timestamp)', resp.full_path, resp_frag_index) continue timestamp = Timestamp(timestamp) etag = resp.headers.get('X-Object-Sysmeta-Ec-Etag') if not etag: self.logger.warning( 'Invalid resp from %s, frag index %s ' '(missing Etag)', resp.full_path, resp_frag_index) continue if etag != etag_buckets.setdefault(timestamp, etag): self.logger.error( 'Mixed Etag (%s, %s) for %s frag#%s', etag, etag_buckets[timestamp], _full_path(node, job['partition'], datafile_metadata['name'], job['policy']), fi_to_rebuild) continue if resp_frag_index not in buckets[timestamp]: buckets[timestamp][resp_frag_index] = resp if len(buckets[timestamp]) >= job['policy'].ec_ndata: responses = buckets[timestamp].values() self.logger.debug( 'Reconstruct frag #%s with frag indexes %s' % (fi_to_rebuild, list(buckets[timestamp]))) break else: for timestamp, resp in sorted(buckets.items()): etag = etag_buckets[timestamp] self.logger.error( 'Unable to get enough responses (%s/%s) ' 'to reconstruct %s frag#%s with ETag %s' % (len(resp), job['policy'].ec_ndata, _full_path(node, job['partition'], datafile_metadata['name'], job['policy']), fi_to_rebuild, etag)) if error_resp_count: self.logger.error( 'Unable to get enough responses (%s error responses) ' 'to reconstruct %s frag#%s' % (error_resp_count, _full_path(node, job['partition'], datafile_metadata['name'], job['policy']), fi_to_rebuild)) raise DiskFileError('Unable to reconstruct EC archive') rebuilt_fragment_iter = self.make_rebuilt_fragment_iter( responses[:job['policy'].ec_ndata], path, job['policy'], fi_to_rebuild) return RebuildingECDiskFileStream(datafile_metadata, fi_to_rebuild, rebuilt_fragment_iter)
def create(self, size=None): """ 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 size: optional initial size of file to explicitly allocate on disk :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: os.makedirs(self._container_path) except OSError as err: if err.errno != errno.EEXIST: raise data_file = os.path.join(self._put_datadir, self._obj) # Assume the full directory path exists to the file already, and # construct the proper name for the temporary file. attempts = 1 while True: # To know more about why following temp file naming convention is # used, please read this GlusterFS doc: # https://github.com/gluster/glusterfs/blob/master/doc/features/dht.md#rename-optimizations # noqa tmpfile = '.' + self._obj + '.' + uuid4().hex tmppath = os.path.join(self._put_datadir, tmpfile) try: fd = do_open(tmppath, os.O_WRONLY | os.O_CREAT | os.O_EXCL | O_CLOEXEC) 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 raise DiskFileNoSpace() if gerr.errno == errno.ENOTDIR: raise AlreadyExistsAsFile('do_open(): failed on %s,' ' path or part of a' ' path is not a directory' % (tmppath)) if gerr.errno not in (errno.ENOENT, errno.EEXIST, errno.EIO): # FIXME: Other cases we should handle? 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: # Retry with a different random number. attempts += 1 elif gerr.errno == errno.EIO: # FIXME: Possible FUSE issue or race condition, let's # sleep on it and retry the operation. _random_sleep() logging.warn( "DiskFile.mkstemp(): %s ... retrying in" " 0.1 secs", gerr) attempts += 1 elif not self._obj_path: # No directory hierarchy and the create failed telling us # the container or volume directory does not exist. This # could be a FUSE issue or some race condition, so let's # sleep a bit and retry. _random_sleep() logging.warn( "DiskFile.mkstemp(): %s ... retrying in" " 0.1 secs", gerr) attempts += 1 elif attempts > 1: # Got ENOENT after previously making the path. This could # also be a FUSE issue or some race condition, nap and # retry. _random_sleep() logging.warn("DiskFile.mkstemp(): %s ... retrying in" " 0.1 secs" % gerr) attempts += 1 else: # It looks like the path to the object does not already # exist; don't count this as an attempt, though, since # we perform the open() system call optimistically. self._create_dir_object(self._obj_path) else: break dw = None try: # Ensure it is properly owned before we make it available. do_fchown(fd, self._uid, self._gid) # NOTE: we do not perform the fallocate() call at all. We ignore # it completely since at the time of this writing FUSE does not # support it. dw = DiskFileWriter(fd, tmppath, self) yield dw finally: dw.close() if dw._tmppath: do_unlink(dw._tmppath)
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
def _finalize_put(self, metadata): # Write out metadata before fsync() to ensure it is also forced to # disk. write_metadata(self._fd, metadata) # We call fsync() before calling drop_cache() to lower the # amount of redundant work the drop cache code will perform on # the pages (now that after fsync the pages will be all # clean). do_fsync(self._fd) # From the Department of the Redundancy Department, make sure # we call drop_cache() after fsync() to avoid redundant work # (pages all clean). do_fadvise64(self._fd, self._last_sync, self._upload_size) # At this point we know that the object's full directory path # exists, so we can just rename it directly without using Swift's # swift.common.utils.renamer(), which makes the directory path and # adds extra stat() calls. df = self._disk_file attempts = 1 while True: try: do_rename(self._tmppath, df._data_file) except OSError as err: if err.errno in (errno.ENOENT, errno.EIO) \ and attempts < MAX_RENAME_ATTEMPTS: # FIXME: Why either of these two error conditions is # happening is unknown at this point. This might be a # FUSE issue of some sort or a possible race # condition. So let's sleep on it, and double check # the environment after a good nap. _random_sleep() # Tease out why this error occurred. The man page for # rename reads: # "The link named by tmppath does not exist; or, a # directory component in data_file does not exist; # or, tmppath or data_file is an empty string." assert len(self._tmppath) > 0 and len(df._data_file) > 0 tpstats = do_stat(self._tmppath) tfstats = do_fstat(self._fd) assert tfstats if not tpstats or tfstats.st_ino != tpstats.st_ino: # Temporary file name conflict raise DiskFileError( 'DiskFile.put(): temporary file, %s, was' ' already renamed (targeted for %s)' % (self._tmppath, df._data_file)) else: # Data file target name now has a bad path! dfstats = do_stat(df._put_datadir) if not dfstats: raise DiskFileError( 'DiskFile.put(): path to object, %s, no' ' longer exists (targeted for %s)' % (df._put_datadir, df._data_file)) else: is_dir = stat.S_ISDIR(dfstats.st_mode) if not is_dir: raise DiskFileError( 'DiskFile.put(): path to object, %s,' ' no longer a directory (targeted for' ' %s)' % (self._put_datadir, df._data_file)) else: # Let's retry since everything looks okay logging.warn( "DiskFile.put(): rename('%s','%s')" " initially failed (%s) but a" " stat('%s') following that succeeded:" " %r" % (self._tmppath, df._data_file, str(err), df._put_datadir, dfstats)) attempts += 1 continue else: raise SwiftOnFileSystemOSError( err.errno, "%s, rename('%s', '%s')" % (err.strerror, self._tmppath, df._data_file)) else: # Success! break # Close here so the calling context does not have to perform this # in a thread. self.close()
def create(self, size=None): """ 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 size: optional initial size of file to explicitly allocate on disk :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: os.makedirs(self._container_path) except OSError as err: if err.errno != errno.EEXIST: raise data_file = os.path.join(self._put_datadir, self._obj) # Assume the full directory path exists to the file already, and # construct the proper name for the temporary file. fd = None attempts = 1 while True: # To know more about why following temp file naming convention is # used, please read this GlusterFS doc: # https://github.com/gluster/glusterfs/blob/master/doc/features/dht.md#rename-optimizations # noqa tmpfile = '.' + self._obj + '.' + uuid4().hex tmppath = os.path.join(self._put_datadir, tmpfile) try: fd = do_open(tmppath, os.O_WRONLY | os.O_CREAT | os.O_EXCL | O_CLOEXEC) 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 raise DiskFileNoSpace() if gerr.errno == errno.ENOTDIR: raise AlreadyExistsAsFile('do_open(): failed on %s,' ' path or part of a' ' path is not a directory' % (tmppath)) if gerr.errno not in (errno.ENOENT, errno.EEXIST, errno.EIO): # FIXME: Other cases we should handle? raise if attempts >= MAX_OPEN_ATTEMPTS: # We failed after N attempts to create the temporary # file. raise DiskFileError( 'DiskFile.create(): 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: # Retry with a different random number. attempts += 1 elif gerr.errno == errno.EIO: # FIXME: Possible FUSE issue or race condition, let's # sleep on it and retry the operation. _random_sleep() logging.warn( "DiskFile.create(): %s ... retrying in" " 0.1 secs", gerr) attempts += 1 elif not self._obj_path: # ENOENT # No directory hierarchy and the create failed telling us # the container or volume directory does not exist. This # could be a FUSE issue or some race condition, so let's # sleep a bit and retry. # Handle race: # This can be the issue when memcache has cached that the # container exists. If someone removes the container dir # from filesystem, it's not reflected in memcache. So # swift reports that the container exists and this code # tries to create a file in a directory that does not # exist. However, it's wrong to create the container here. _random_sleep() logging.warn( "DiskFile.create(): %s ... retrying in" " 0.1 secs", gerr) attempts += 1 if attempts > 2: # Ideally we would want to return 404 indicating that # the container itself does not exist. Can't be done # though as the caller won't catch DiskFileNotExist. # We raise an exception with a meaningful name for # correctness. logging.warn("Container dir %s does not exist", self._container_path) raise DiskFileContainerDoesNotExist elif attempts > 1: # Got ENOENT after previously making the path. This could # also be a FUSE issue or some race condition, nap and # retry. _random_sleep() logging.warn("DiskFile.create(): %s ... retrying in" " 0.1 secs" % gerr) attempts += 1 else: # It looks like the path to the object does not already # exist; don't count this as an attempt, though, since # we perform the open() system call optimistically. self._create_dir_object(self._obj_path) else: break dw = None try: if size is not None and size > 0: try: fallocate(fd, size) except OSError as err: if err.errno in (errno.ENOSPC, errno.EDQUOT): raise DiskFileNoSpace() raise # Ensure it is properly owned before we make it available. if not ((self._uid == DEFAULT_UID) and (self._gid == DEFAULT_GID)): # If both UID and GID is -1 (default values), it has no effect. # So don't do a fchown. # Further, at the time of this writing, UID and GID information # is not passed to DiskFile. do_fchown(fd, self._uid, self._gid) dw = DiskFileWriter(fd, tmppath, self) # It's now the responsibility of DiskFileWriter to close this fd. fd = None yield dw finally: if dw: dw.close() if dw._tmppath: do_unlink(dw._tmppath)