* filer: add StreamMutateEntry bidi streaming RPC Add a bidirectional streaming RPC that carries all filer mutation types (create, update, delete, rename) over a single ordered stream. This eliminates per-request connection overhead for pipelined operations and guarantees mutation ordering within a stream. The server handler delegates each request to the existing unary handlers (CreateEntry, UpdateEntry, DeleteEntry) and uses a proxy stream adapter for rename operations to reuse StreamRenameEntry logic. The is_last field signals completion for multi-response operations (rename sends multiple events per request; create/update/delete always send exactly one response with is_last=true). * mount: add streaming mutation multiplexer (streamMutateMux) Implement a client-side multiplexer that routes all filer mutation RPCs (create, update, delete, rename) over a single bidirectional gRPC stream. Multiple goroutines submit requests through a send channel; a dedicated sendLoop serializes them on the stream; a recvLoop dispatches responses to waiting callers via per-request channels. Key features: - Lazy stream opening on first use - Automatic reconnection on stream failure - Permanent fallback to unary RPCs if filer returns Unimplemented - Monotonic request_id for response correlation - Multi-response support for rename operations (is_last signaling) The mux is initialized on WFS and closed during unmount cleanup. No call sites use it yet — wiring comes in subsequent commits. * mount: route CreateEntry and UpdateEntry through streaming mux Wire all CreateEntry call sites to use wfs.streamCreateEntry() which routes through the StreamMutateEntry stream when available, falling back to unary RPCs otherwise. Also wire Link's UpdateEntry calls through wfs.streamUpdateEntry(). Updated call sites: - flushMetadataToFiler (file flush after write) - Mkdir (directory creation) - Symlink (symbolic link creation) - createRegularFile non-deferred path (Mknod) - flushFileMetadata (periodic metadata flush) - Link (hard link: update source + create link + rollback) * mount: route UpdateEntry and DeleteEntry through streaming mux Wire remaining mutation call sites through the streaming mux: - saveEntry (Setattr/chmod/chown/utimes) → streamUpdateEntry - Unlink → streamDeleteEntry (replaces RemoveWithResponse) - Rmdir → streamDeleteEntry (replaces RemoveWithResponse) All filer mutations except Rename now go through StreamMutateEntry when the filer supports it, with automatic unary RPC fallback. * mount: route Rename through streaming mux Wire Rename to use streamMutate.Rename() when available, with fallback to the existing StreamRenameEntry unary stream. The streaming mux sends rename as a StreamRenameEntryRequest oneof variant. The server processes it through the existing rename logic and sends multiple StreamRenameEntryResponse events (one per moved entry), with is_last=true on the final response. All filer mutations now go through a single ordered stream. * mount: fix stream mux connection ownership WithGrpcClient(streamingMode=true) closes the gRPC connection when the callback returns, destroying the stream. Own the connection directly via pb.GrpcDial so it stays alive for the stream's lifetime. Close it explicitly in recvLoop on stream failure and in Close on shutdown. * mount: fix rename failure for deferred-create files Three fixes for rename operations over the streaming mux: 1. lookupEntry: fall back to local metadata store when filer returns "not found" for entries in uncached directories. Files created with deferFilerCreate=true exist only in the local leveldb store until flushed; lookupEntry skipped the local store when the parent directory had never been readdir'd, causing rename to fail with ENOENT. 2. Rename: wait for pending async flushes and force synchronous flush of dirty metadata before sending rename to the filer. Covers the writebackCache case where close() defers the flush to a background worker that may not complete before rename fires. 3. StreamMutateEntry: propagate rename errors from server to client. Add error/errno fields to StreamMutateEntryResponse so the mount can map filer errors to correct FUSE status codes instead of silently returning OK. Also fix the existing Rename error handler which could return fuse.OK on unrecognized errors. * mount: fix streaming mux error handling, sendLoop lifecycle, and fallback Address PR review comments: 1. Server: populate top-level Error/Errno on StreamMutateEntryResponse for create/update/delete errors, not just rename. Previously update errors were silently dropped and create/delete errors were only in nested response fields that the client didn't check. 2. Client: check nested error fields in CreateEntry (ErrorCode, Error) and DeleteEntry (Error) responses, matching CreateEntryWithResponse behavior. 3. Fix sendLoop lifecycle: give each stream generation a stopSend channel. recvLoop closes it on error to stop the paired sendLoop. Previously a reconnect left the old sendLoop draining sendCh, breaking ordering. 4. Transparent fallback: stream helpers and doRename fall back to unary RPCs on transport errors (ErrStreamTransport), including the first Unimplemented from ensureStream. Previously the first call failed instead of degrading. 5. Filer rotation in openStream: try all filer addresses on dial failure, matching WithFilerClient behavior. Stop early on Unimplemented. 6. Pass metadata-bearing context to StreamMutateEntry RPC call so sw-client-id header is actually sent. 7. Gate lookupEntry local-cache fallback on open dirty handle or pending async flush to avoid resurrecting deleted/renamed entries. 8. Remove dead code in flushFileMetadata (err=nil followed by if err!=nil). 9. Use string matching for rename error-to-errno mapping in the mount to stay portable across Linux/macOS (numeric errno values differ). * mount: make failAllPending idempotent with delete-before-close Change failAllPending to collect pending entries into a local slice (deleting from the sync.Map first) before closing channels. This prevents double-close panics if called concurrently. Also remove the unused err parameter. * mount: add stream generation tracking and teardownStream Introduce a generation counter on streamMutateMux that increments each time a new stream is created. Requests carry the generation they were enqueued for so sendLoop can reject stale requests after reconnect. Add teardownStream(gen) which is idempotent (only acts when gen matches current generation and stream is non-nil). Both sendLoop and recvLoop call it on error, replacing the inline cleanup in recvLoop. sendLoop now actively triggers teardown on send errors instead of silently exiting. ensureStream waits for the prior generation's recvDone before creating a new stream, ensuring all old pending waiters are failed before reconnect. recvLoop now takes the stream, generation, and recvDone channel as parameters to avoid accessing shared fields without the lock. * mount: harden Close to prevent races with teardownStream Nil out stream, cancel, and grpcConn under the lock so that any concurrent teardownStream call from recvLoop/sendLoop becomes a no-op. Call failAllPending before closing sendCh to unblock waiters promptly. Guard recvDone with a nil check for the case where Close is called before any stream was ever opened. * mount: make errCh receive ctx-aware in doUnary and Rename Replace the blocking <-sendReq.errCh with a select that also observes ctx.Done(). If sendLoop exits via stopSend without consuming a buffered request, the caller now returns ctx.Err() instead of blocking forever. The buffered errCh (capacity 1) ensures late acknowledgements from sendLoop don't block the sender. * mount: fix sendLoop/Close race and recvLoop/teardown pending channel race Three related fixes: 1. Stop closing sendCh in Close(). Closing the shared producer channel races with callers who passed ensureStream() but haven't sent yet, causing send-on-closed-channel panics. sendCh is now left open; ensureStream checks m.closed to reject new callers. 2. Drain buffered sendCh items on shutdown. sendLoop defers drainSendCh() on exit so buffered requests get an ErrStreamTransport on their errCh instead of blocking forever. Close() drains again for any stragglers enqueued between sendLoop's drain and the final shutdown. 3. Move failAllPending from teardownStream into recvLoop's defer. teardownStream (called from sendLoop on send error) was closing pending response channels while recvLoop could be between pending.Load and the channel send — a send-on-closed-channel panic. recvLoop is now the sole closer of pending channels, eliminating the race. Close() waits on recvDone (with cancel() to guarantee Recv unblocks) so pending cleanup always completes. * filer/mount: add debug logging for hardlink lifecycle Add V(0) logging at every point where a HardLinkId is created, stored, read, or deleted to trace orphaned hardlink references. Logging covers: - gRPC server: CreateEntry/UpdateEntry when request carries HardLinkId - FilerStoreWrapper: InsertEntry/UpdateEntry when entry has HardLinkId - handleUpdateToHardLinks: entry path, HardLinkId, counter, chunk count - setHardLink: KvPut with blob size - maybeReadHardLink: V(1) on read attempt and successful decode - DeleteHardLink: counter decrement/deletion events - Mount Link(): when NewHardLinkId is generated and link is created This helps diagnose how a git pack .rev file ended up with a HardLinkId during a clone (no hard links should be involved). * test: add git clone/pull integration test for FUSE mount Shell script that exercises git operations on a SeaweedFS mount: 1. Creates a bare repo on the mount 2. Clones locally, makes 3 commits, pushes to mount 3. Clones from mount bare repo into an on-mount working dir 4. Verifies clone integrity (files, content, commit hashes) 5. Pushes 2 more commits with renames and deletes 6. Checks out an older revision on the mount clone 7. Returns to branch and pulls with real changes 8. Verifies file content, renames, deletes after pull 9. Checks git log integrity and clean status 27 assertions covering file existence, content, commit hashes, file counts, renames, deletes, and git status. Run against any existing mount: bash test-git-on-mount.sh /path/to/mount * test: add git clone/pull FUSE integration test to CI suite Add TestGitOperations to the existing fuse_integration test framework. The test exercises git's full file operation surface on the mount: 1. Creates a bare repo on the mount (acts as remote) 2. Clones locally, makes 3 commits (files, bulk data, renames), pushes 3. Clones from mount bare repo into an on-mount working dir 4. Verifies clone integrity (content, commit hash, file count) 5. Pushes 2 more commits with new files, renames, and deletes 6. Checks out an older revision on the mount clone 7. Returns to branch and pulls with real fast-forward changes 8. Verifies post-pull state: content, renames, deletes, file counts 9. Checks git log integrity (5 commits) and clean status Runs automatically in the existing fuse-integration.yml CI workflow. * mount: fix permission check with uid/gid mapping The permission checks in createRegularFile() and Access() compared the caller's local uid/gid against the entry's filer-side uid/gid without applying the uid/gid mapper. With -map.uid 501:0, a directory created as uid 0 on the filer would not match the local caller uid 501, causing hasAccess() to fall through to "other" permission bits and reject write access (0755 → other has r-x, no w). Fix: map entry uid/gid from filer-space to local-space before the hasAccess() call so both sides are in the same namespace. This fixes rsync -a failing with "Permission denied" on mkstempat when using uid/gid mapping. * mount: fix Mkdir/Symlink returning filer-side uid/gid to kernel Mkdir and Symlink used `defer wfs.mapPbIdFromFilerToLocal(entry)` to restore local uid/gid, but `outputPbEntry` writes the kernel response before the function returns — so the kernel received filer-side uid/gid (e.g., 0:0). macFUSE then caches these and rejects subsequent child operations (mkdir, create) because the caller uid (501) doesn't match the directory owner (0), and "other" bits (0755 → r-x) lack write permission. Fix: replace the defer with an explicit call to mapPbIdFromFilerToLocal before outputPbEntry, so the kernel gets local uid/gid. Also add nil guards for UidGidMapper in Access and createRegularFile to prevent panics in tests that don't configure a mapper. This fixes rsync -a "Permission denied" on mkpathat for nested directories when using uid/gid mapping. * mount: fix Link outputting filer-side uid/gid to kernel, add nil guards Link had the same defer-before-outputPbEntry bug as Mkdir and Symlink: the kernel received filer-side uid/gid because the defer hadn't run yet when outputPbEntry wrote the response. Also add nil guards for UidGidMapper in Access and createRegularFile so tests without a mapper don't panic. Audit of all outputPbEntry/outputFilerEntry call sites: - Mkdir: fixed in prior commit (explicit map before output) - Symlink: fixed in prior commit (explicit map before output) - Link: fixed here (explicit map before output) - Create (existing file): entry from maybeLoadEntry (already mapped) - Create (deferred): entry has local uid/gid (never mapped to filer) - Create (non-deferred): createRegularFile defer runs before return - Mknod: createRegularFile defer runs before return - Lookup: entry from lookupEntry (already mapped) - GetAttr: entry from maybeReadEntry/maybeLoadEntry (already mapped) - readdir: entry from cache (mapIdFromFilerToLocal) or filer (mapped) - saveEntry: no kernel output - flushMetadataToFiler: no kernel output - flushFileMetadata: no kernel output * test: fix git test for same-filesystem FUSE clone When both the bare repo and working clone live on the same FUSE mount, git's local transport uses hardlinks and cross-repo stat calls that fail on FUSE. Fix: - Use --no-local on clone to disable local transport optimizations - Use reset --hard instead of checkout to stay on branch - Use fetch + reset --hard origin/<branch> instead of git pull to avoid local transport stat failures during fetch * adjust logging * test: use plain git clone/pull to exercise real FUSE behavior Remove --no-local and fetch+reset workarounds. The test should use the same git commands users run (clone, reset --hard, pull) so it reveals real FUSE issues rather than hiding them. * test: enable V(1) logging for filer/mount and collect logs on failure - Run filer and mount with -v=1 so hardlink lifecycle logs (V(0): create/delete/insert, V(1): read attempts) are captured - On test failure, automatically dump last 16KB of all process logs (master, volume, filer, mount) to test output - Copy process logs to /tmp/seaweedfs-fuse-logs/ for CI artifact upload - Update CI workflow to upload SeaweedFS process logs alongside test output * mount: clone entry for filer flush to prevent uid/gid race flushMetadataToFiler and flushFileMetadata used entry.GetEntry() which returns the file handle's live proto entry pointer, then mutated it in-place via mapPbIdFromLocalToFiler. During the gRPC call window, a concurrent Lookup (which takes entryLock.RLock but NOT fhLockTable) could observe filer-side uid/gid (e.g., 0:0) on the file handle entry and return it to the kernel. The kernel caches these attributes, so subsequent opens by the local user (uid 501) fail with EACCES. Fix: proto.Clone the entry before mapping uid/gid for the filer request. The file handle's live entry is never mutated, so concurrent Lookup always sees local uid/gid. This fixes the intermittent "Permission denied" on .git/FETCH_HEAD after the first git pull on a mount with uid/gid mapping. * mount: add debug logging for stale lock file investigation Add V(0) logging to trace the HEAD.lock recreation issue: - Create: log when O_EXCL fails (file already exists) with uid/gid/mode - completeAsyncFlush: log resolved path, saved path, dirtyMetadata, isDeleted at entry to trace whether async flush fires after rename - flushMetadataToFiler: log the dir/name/fullpath being flushed This will show whether the async flush is recreating the lock file after git renames HEAD.lock → HEAD. * mount: prevent async flush from recreating renamed .lock files When git renames HEAD.lock → HEAD, the async flush from the prior close() can run AFTER the rename and re-insert HEAD.lock into the meta cache via its CreateEntryRequest response event. The next git pull then sees HEAD.lock and fails with "File exists". Fix: add isRenamed flag on FileHandle, set by Rename before waiting for the pending async flush. The async flush checks this flag and skips the metadata flush for renamed files (same pattern as isDeleted for unlinked files). The data pages still flush normally. The Rename handler flushes deferred metadata synchronously (Case 1) before setting isRenamed, ensuring the entry exists on the filer for the rename to proceed. For already-released handles (Case 2), the entry was created by a prior flush. * mount: also mark renamed inodes via entry.Attributes.Inode fallback When GetInode fails (Forget already removed the inode mapping), the Rename handler couldn't find the pending async flush to set isRenamed. The async flush then recreated the .lock file on the filer. Fix: fall back to oldEntry.Attributes.Inode to find the pending async flush when the inode-to-path mapping is gone. Also extract MarkInodeRenamed into a method on FileHandleToInode for clarity. * mount: skip async metadata flush when saved path no longer maps to inode The isRenamed flag approach failed for refs/remotes/origin/HEAD.lock because neither GetInode nor oldEntry.Attributes.Inode could find the inode (Forget already evicted the mapping, and the entry's stored inode was 0). Add a direct check in completeAsyncFlush: before flushing metadata, verify that the saved path still maps to this inode in the inode-to-path table. If the path was renamed or removed (inode mismatch or not found), skip the metadata flush to avoid recreating a stale entry. This catches all rename cases regardless of whether the Rename handler could set the isRenamed flag. * mount: wait for pending async flush in Unlink before filer delete Unlink was deleting the filer entry first, then marking the draining async-flush handle as deleted. The async flush worker could race between these two operations and recreate the just-unlinked entry on the filer. This caused git's .lock files (e.g. refs/remotes/origin/HEAD.lock) to persist after git pull, breaking subsequent git operations. Move the isDeleted marking and add waitForPendingAsyncFlush() before the filer delete so any in-flight flush completes first. Even if the worker raced past the isDeleted check, the wait ensures it finishes before the filer delete cleans up any recreated entry. * mount: reduce async flush and metadata flush log verbosity Raise completeAsyncFlush entry log, saved-path-mismatch skip log, and flushMetadataToFiler entry log from V(0) to V(3)/V(4). These fire for every file close with writebackCache and are too noisy for normal use. * filer: reduce hardlink debug log verbosity from V(0) to V(4) HardLinkId logs in filerstore_wrapper, filerstore_hardlink, and filer_grpc_server fire on every hardlinked file operation (git pack files use hardlinks extensively) and produce excessive noise. * mount/filer: reduce noisy V(0) logs for link, rmdir, and empty folder check - weedfs_link.go: hardlink creation logs V(0) → V(4) - weedfs_dir_mkrm.go: non-empty folder rmdir error V(0) → V(1) - empty_folder_cleaner.go: "not empty" check log V(0) → V(4) * filer: handle missing hardlink KV as expected, not error A "kv: not found" on hardlink read is normal when the link blob was already cleaned up but a stale entry still references it. Log at V(1) for not-found; keep Error level for actual KV failures. * test: add waitForDir before git pull in FUSE git operations test After git reset --hard, the FUSE mount's metadata cache may need a moment to settle on slow CI. The git pull subprocess (unpack-objects) could fail to stat the working directory. Poll for up to 5s. * Update git_operations_test.go * wait * test: simplify FUSE test framework to use weed mini Replace the 4-process setup (master + volume + filer + mount) with 2 processes: "weed mini" (all-in-one) + "weed mount". This simplifies startup, reduces port allocation, and is faster on CI. * test: fix mini flag -admin → -admin.ui
319 lines
12 KiB
Go
319 lines
12 KiB
Go
package mount
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
"syscall"
|
|
|
|
"github.com/seaweedfs/go-fuse/v2/fs"
|
|
"github.com/seaweedfs/go-fuse/v2/fuse"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
)
|
|
|
|
// doRename tries the streaming mux first, falling back to unary on transport errors.
|
|
func (wfs *WFS) doRename(ctx context.Context, request *filer_pb.StreamRenameEntryRequest, oldPath, newPath util.FullPath) error {
|
|
if wfs.streamMutate != nil && wfs.streamMutate.IsAvailable() {
|
|
err := wfs.streamMutate.Rename(ctx, request, func(resp *filer_pb.StreamRenameEntryResponse) error {
|
|
return wfs.handleRenameResponse(ctx, resp)
|
|
})
|
|
if err == nil || !errors.Is(err, ErrStreamTransport) {
|
|
return err // success or application error
|
|
}
|
|
glog.V(1).Infof("Rename %s => %s: stream failed, falling back to unary: %v", oldPath, newPath, err)
|
|
}
|
|
return wfs.WithFilerClient(true, func(client filer_pb.SeaweedFilerClient) error {
|
|
stream, streamErr := client.StreamRenameEntry(ctx, request)
|
|
if streamErr != nil {
|
|
return fmt.Errorf("dir AtomicRenameEntry %s => %s : %v", oldPath, newPath, streamErr)
|
|
}
|
|
for {
|
|
resp, recvErr := stream.Recv()
|
|
if recvErr != nil {
|
|
if recvErr == io.EOF {
|
|
break
|
|
}
|
|
return fmt.Errorf("dir Rename %s => %s receive: %v", oldPath, newPath, recvErr)
|
|
}
|
|
if err := wfs.handleRenameResponse(ctx, resp); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
/** Rename a file
|
|
*
|
|
* If the target exists it should be atomically replaced. If
|
|
* the target's inode's lookup count is non-zero, the file
|
|
* system is expected to postpone any removal of the inode
|
|
* until the lookup count reaches zero (see description of the
|
|
* forget function).
|
|
*
|
|
* If this request is answered with an error code of ENOSYS, this is
|
|
* treated as a permanent failure with error code EINVAL, i.e. all
|
|
* future bmap requests will fail with EINVAL without being
|
|
* send to the filesystem process.
|
|
*
|
|
* *flags* may be `RENAME_EXCHANGE` or `RENAME_NOREPLACE`. If
|
|
* RENAME_NOREPLACE is specified, the filesystem must not
|
|
* overwrite *newname* if it exists and return an error
|
|
* instead. If `RENAME_EXCHANGE` is specified, the filesystem
|
|
* must atomically exchange the two files, i.e. both must
|
|
* exist and neither may be deleted.
|
|
*
|
|
* Valid replies:
|
|
* fuse_reply_err
|
|
*
|
|
* @param req request handle
|
|
* @param parent inode number of the old parent directory
|
|
* @param name old name
|
|
* @param newparent inode number of the new parent directory
|
|
* @param newname new name
|
|
*/
|
|
/*
|
|
renameat2()
|
|
renameat2() has an additional flags argument. A renameat2() call
|
|
with a zero flags argument is equivalent to renameat().
|
|
|
|
The flags argument is a bit mask consisting of zero or more of
|
|
the following flags:
|
|
|
|
RENAME_EXCHANGE
|
|
Atomically exchange oldpath and newpath. Both pathnames
|
|
must exist but may be of different types (e.g., one could
|
|
be a non-empty directory and the other a symbolic link).
|
|
|
|
RENAME_NOREPLACE
|
|
Don't overwrite newpath of the rename. Return an error if
|
|
newpath already exists.
|
|
|
|
RENAME_NOREPLACE can't be employed together with
|
|
RENAME_EXCHANGE.
|
|
|
|
RENAME_NOREPLACE requires support from the underlying
|
|
filesystem. Support for various filesystems was added as
|
|
follows:
|
|
|
|
* ext4 (Linux 3.15);
|
|
|
|
* btrfs, tmpfs, and cifs (Linux 3.17);
|
|
|
|
* xfs (Linux 4.0);
|
|
|
|
* Support for many other filesystems was added in Linux
|
|
4.9, including ext2, minix, reiserfs, jfs, vfat, and
|
|
bpf.
|
|
|
|
RENAME_WHITEOUT (since Linux 3.18)
|
|
This operation makes sense only for overlay/union
|
|
filesystem implementations.
|
|
|
|
Specifying RENAME_WHITEOUT creates a "whiteout" object at
|
|
the source of the rename at the same time as performing
|
|
the rename. The whole operation is atomic, so that if the
|
|
rename succeeds then the whiteout will also have been
|
|
created.
|
|
|
|
A "whiteout" is an object that has special meaning in
|
|
union/overlay filesystem constructs. In these constructs,
|
|
multiple layers exist and only the top one is ever
|
|
modified. A whiteout on an upper layer will effectively
|
|
hide a matching file in the lower layer, making it appear
|
|
as if the file didn't exist.
|
|
|
|
When a file that exists on the lower layer is renamed, the
|
|
file is first copied up (if not already on the upper
|
|
layer) and then renamed on the upper, read-write layer.
|
|
At the same time, the source file needs to be "whiteouted"
|
|
(so that the version of the source file in the lower layer
|
|
is rendered invisible). The whole operation needs to be
|
|
done atomically.
|
|
|
|
When not part of a union/overlay, the whiteout appears as
|
|
a character device with a {0,0} device number. (Note that
|
|
other union/overlay implementations may employ different
|
|
methods for storing whiteout entries; specifically, BSD
|
|
union mount employs a separate inode type, DT_WHT, which,
|
|
while supported by some filesystems available in Linux,
|
|
such as CODA and XFS, is ignored by the kernel's whiteout
|
|
support code, as of Linux 4.19, at least.)
|
|
|
|
RENAME_WHITEOUT requires the same privileges as creating a
|
|
device node (i.e., the CAP_MKNOD capability).
|
|
|
|
RENAME_WHITEOUT can't be employed together with
|
|
RENAME_EXCHANGE.
|
|
|
|
RENAME_WHITEOUT requires support from the underlying
|
|
filesystem. Among the filesystems that support it are
|
|
tmpfs (since Linux 3.18), ext4 (since Linux 3.18), XFS
|
|
(since Linux 4.1), f2fs (since Linux 4.2), btrfs (since
|
|
Linux 4.7), and ubifs (since Linux 4.9).
|
|
*/
|
|
const (
|
|
RenameEmptyFlag = 0
|
|
RenameNoReplace = 1
|
|
RenameExchange = fs.RENAME_EXCHANGE
|
|
RenameWhiteout = 3
|
|
)
|
|
|
|
func (wfs *WFS) Rename(cancel <-chan struct{}, in *fuse.RenameIn, oldName string, newName string) (code fuse.Status) {
|
|
if wfs.IsOverQuotaWithUncommitted() {
|
|
return fuse.Status(syscall.ENOSPC)
|
|
}
|
|
|
|
if s := checkName(newName); s != fuse.OK {
|
|
return s
|
|
}
|
|
|
|
switch in.Flags {
|
|
case RenameEmptyFlag:
|
|
case RenameNoReplace:
|
|
case RenameExchange:
|
|
case RenameWhiteout:
|
|
return fuse.ENOTSUP
|
|
default:
|
|
return fuse.EINVAL
|
|
}
|
|
|
|
oldDir, code := wfs.inodeToPath.GetPath(in.NodeId)
|
|
if code != fuse.OK {
|
|
return
|
|
}
|
|
oldPath := oldDir.Child(oldName)
|
|
newDir, code := wfs.inodeToPath.GetPath(in.Newdir)
|
|
if code != fuse.OK {
|
|
return
|
|
}
|
|
newPath := newDir.Child(newName)
|
|
|
|
oldEntry, status := wfs.maybeLoadEntry(oldPath)
|
|
if status != fuse.OK {
|
|
return status
|
|
}
|
|
|
|
if wormEnforced, _ := wfs.wormEnforcedForEntry(oldPath, oldEntry); wormEnforced {
|
|
return fuse.EPERM
|
|
}
|
|
|
|
glog.V(4).Infof("dir Rename %s => %s", oldPath, newPath)
|
|
|
|
// Ensure the source file's metadata exists on the filer before renaming.
|
|
// Two cases can leave the entry only in the local cache:
|
|
// 1. deferFilerCreate=true — file handle still open, dirtyMetadata set.
|
|
// 2. writebackCache — close() triggered async flush, handle released.
|
|
// The filer rename will fail with ENOENT unless we flush/wait first.
|
|
if inode, found := wfs.inodeToPath.GetInode(oldPath); found {
|
|
// Case 1: handle still open with deferred metadata — flush synchronously
|
|
// BEFORE any async flush interference.
|
|
if fh, ok := wfs.fhMap.FindFileHandle(inode); ok && fh.dirtyMetadata {
|
|
glog.V(4).Infof("dir Rename %s: flushing deferred metadata before rename", oldPath)
|
|
if flushStatus := wfs.doFlush(fh, oldEntry.Attributes.Uid, oldEntry.Attributes.Gid, false); flushStatus != fuse.OK {
|
|
glog.Warningf("dir Rename %s: flush before rename failed: %v", oldPath, flushStatus)
|
|
return flushStatus
|
|
}
|
|
}
|
|
// Case 2: handle already released, async flush may be in flight.
|
|
// Mark ALL handles for this inode as renamed so the async flush
|
|
// skips old-path metadata creation (which would re-insert the
|
|
// renamed entry into the meta cache after rename events clean it up).
|
|
wfs.fhMap.MarkInodeRenamed(inode)
|
|
wfs.waitForPendingAsyncFlush(inode)
|
|
} else if oldEntry != nil && oldEntry.Attributes != nil && oldEntry.Attributes.Inode != 0 {
|
|
// GetInode failed (Forget already removed the mapping), but the
|
|
// entry's stored inode can still identify pending async flushes.
|
|
inode = oldEntry.Attributes.Inode
|
|
wfs.fhMap.MarkInodeRenamed(inode)
|
|
wfs.waitForPendingAsyncFlush(inode)
|
|
}
|
|
|
|
// update remote filer
|
|
request := &filer_pb.StreamRenameEntryRequest{
|
|
OldDirectory: string(oldDir),
|
|
OldName: oldName,
|
|
NewDirectory: string(newDir),
|
|
NewName: newName,
|
|
Signatures: []int32{wfs.signature},
|
|
}
|
|
|
|
ctx := context.Background()
|
|
err := wfs.doRename(ctx, request, oldPath, newPath)
|
|
if err != nil {
|
|
glog.V(0).Infof("Rename %s => %s: %v", oldPath, newPath, err)
|
|
// Map error strings to FUSE status codes. String matching is used
|
|
// instead of raw errno to stay portable across platforms (errno
|
|
// numeric values differ between Linux and macOS).
|
|
msg := err.Error()
|
|
if strings.Contains(msg, "not found") {
|
|
return fuse.Status(syscall.ENOENT)
|
|
} else if strings.Contains(msg, "not empty") {
|
|
return fuse.Status(syscall.ENOTEMPTY)
|
|
} else if strings.Contains(msg, "not directory") {
|
|
return fuse.ENOTDIR
|
|
}
|
|
return fuse.EIO
|
|
}
|
|
wfs.inodeToPath.TouchDirectory(oldDir)
|
|
wfs.inodeToPath.TouchDirectory(newDir)
|
|
|
|
return fuse.OK
|
|
|
|
}
|
|
|
|
func (wfs *WFS) handleRenameResponse(ctx context.Context, resp *filer_pb.StreamRenameEntryResponse) error {
|
|
// comes from filer StreamRenameEntry, can only be create or delete entry
|
|
|
|
glog.V(4).Infof("dir Rename %+v", resp.EventNotification)
|
|
|
|
if resp.EventNotification.NewEntry != nil {
|
|
if err := wfs.applyLocalMetadataEvent(ctx, metadataEventFromRenameResponse(resp)); err != nil {
|
|
glog.Warningf("rename apply metadata event: %v", err)
|
|
wfs.inodeToPath.InvalidateChildrenCache(util.FullPath(resp.Directory))
|
|
if resp.EventNotification.NewParentPath != "" {
|
|
wfs.inodeToPath.InvalidateChildrenCache(util.FullPath(resp.EventNotification.NewParentPath))
|
|
}
|
|
}
|
|
|
|
oldParent, newParent := util.FullPath(resp.Directory), util.FullPath(resp.EventNotification.NewParentPath)
|
|
oldName, newName := resp.EventNotification.OldEntry.Name, resp.EventNotification.NewEntry.Name
|
|
|
|
oldPath := oldParent.Child(oldName)
|
|
newPath := newParent.Child(newName)
|
|
|
|
sourceInode, targetInode := wfs.inodeToPath.MovePath(oldPath, newPath)
|
|
if sourceInode != 0 {
|
|
fh, foundFh := wfs.fhMap.FindFileHandle(sourceInode)
|
|
if foundFh {
|
|
if entry := fh.GetEntry(); entry != nil {
|
|
entry.Name = newName
|
|
}
|
|
// Keep the saved handle path current so any flush fallback
|
|
// after Forget uses the post-rename location, not the old one.
|
|
fh.RememberPath(newPath)
|
|
}
|
|
// invalidate attr and data
|
|
// wfs.fuseServer.InodeNotify(sourceInode, 0, -1)
|
|
}
|
|
if targetInode != 0 {
|
|
// invalidate attr and data
|
|
// wfs.fuseServer.InodeNotify(targetInode, 0, -1)
|
|
}
|
|
|
|
} else if resp.EventNotification.OldEntry != nil {
|
|
// without new entry, only old entry name exists. This is the second step to delete old entry
|
|
if err := wfs.applyLocalMetadataEvent(ctx, metadataEventFromRenameResponse(resp)); err != nil {
|
|
glog.Warningf("rename apply delete event: %v", err)
|
|
wfs.inodeToPath.InvalidateChildrenCache(util.FullPath(resp.Directory))
|
|
}
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|