mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-10-26 06:50:45 +01:00
* filer: enable per-path commit records only when a peer has its own store Since seaweedfs#11698 every metadata change writes a per-path commit record into the filer store (an MpTs key, plus an MpDl key on deletes), and the records stay after the path is deleted. They order the events a filer replays from peer filers that keep their own store, since replay only runs when peerSignature != f.Signature. Filers that all share one store (one Redis, MySQL, TiKV, ...) never replay each other's events, so the records are never read, yet each change still costs one or two extra store writes and the key count grows with every path ever changed — unbounded growth for in-memory stores. This turns the records off by default and latches them on the first time a peer reports a different store signature — no option needed. The latch is persisted in the store (MpRep) so it survives restarts and converges filers sharing a store even before they discover the peer themselves. While off, a filer keeps an MpOff marker so enabling later bumps the records' generation (MpGen, folded into each record key) past the unrecorded window: a record older than a change made while off cannot let an older replayed peer event win. Ordering for unrecorded changes falls back to the entry's mtime, the same as entries written before the records existed. Supersedes the manual option approach in seaweedfs#12060. * filer: keep delete tombstones while records off, harden enable path Review on the first commit: - A delete committed while the records were off left no entry and no usable tombstone: after enabling, an older replayed create could resurrect the path. Deletes and rename sources are now always recorded under the generation-0 MpDl key — they are never fenced by a generation bump, and they cannot go stale because every delete is recorded. Creates/updates still write nothing while off. - bumpPathCommitGen could regress MpGen under concurrent bumpers on a shared store. It now loops: each pass writes only a generation higher than any it has seen, so concurrent bumps converge upward. - doSubscribeToOneFiler proceeded into replay when enablePathCommitRecords failed, running the whole session without ordering. It now aborts the subscribe so the reconnect retries with the records on. * filer: bind pending commit-record repairs to their generation A failed MpTs write kept in metaTsPending could land after a shared-store generation bump, writing a pre-bump timestamp as a current-generation record and overriding newer unrecorded state. Each pending change record now carries the generation it failed under: repairs write it only while that generation is current, and ordering reads ignore it otherwise. Pending delete records need no binding — MpDl keys are never fenced. * filer: never move the local records' generation backward The converge loop in bumpPathCommitGen seeded from zero and both it and syncPathCommitGen stored unconditionally: a stale writer could leave the stored generation below what this filer already adopted, and the next sync or bump then walked the local value back — orphaning records it wrote under the higher generation. The bump now seeds from the local generation and every store only moves it forward. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: name a records generation after the off marker it consumes Two filers consuming the same off marker each counted one past the stored generation, so the second could store N+2 after the first stored N+1 and write records under a key the other could not read until the next check. The bump now takes the marker's own timestamp — filers racing on one marker land on one value — a marker older than the stored generation is cleaned as a leftover, and a stored value that already passed the bump is adopted instead of counted past. A newly enabling filer whose marker was already consumed names its own off window with the current time, so its unrecorded period is still fenced. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: tell a fresh off marker from one the generation already consumed A marker whose timestamp reads at or below the stored generation was dropped as leftover, but a new off period can also read that old — the off filer's clock lagging, or a host clock moving back — and dropping it kept records from before that period live, so stale replay could win. The stored generation now names the marker it was bumped for: a marker the store still shows is consumed unless it is that one, however old it reads, and only the consumed marker itself is cleared without a bump. The generation trails in the value, so a whole-slice read still yields it on stores written before the pair was stored. Enabling fences the filer's own off window with the current time instead of a marker a sharer may already have consumed. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: cover racing off-marker consumers settling on one generation * filer: adopt the stored generation, not the consumed marker it names A filer syncing with no off marker present read the value's first field — the consumed marker's timestamp — so a restart after a lagging-clock off period under-counted the generation and kept records the bump dropped. * filer: re-check the off marker before consuming it A sync whose marker read ran behind a later off period's consume cycle still bumped for its stale read: the stored generation already covered a different marker, so the bump overwrote the consumed name, counted the generation past records a newer consumption meant to keep, and cleared whatever marker was live by then. Each pass now re-reads the marker and only bumps or clears while it is still the one the pass saw. * filer: keep a failed generation read from resetting the records' generation The final generation read ignored errors and then stored whatever gen held — possibly zero — so a transient store failure could hide records the current generation wrote. Unexpected read errors now return before the local generation changes. Also cover a sync whose marker read runs behind another consumer's delete: it must adopt the stored generation, not bump for the stale read. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: fail a bump that cannot verify the stored generation A generation read that failed mid-bump was treated as absent: the write could land below a generation a racing bumper had stored, or re-store a marker that bumper had already consumed. Read failures now abort the pass like every other store error on the path. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: cover generation reads that fail instead of returning a value Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: carry the commit timestamp on the entry itself The per-path MpTs record only exists because a commit timestamp had nowhere else to live. Stamping commit_ts_ns on the entry before its store write - and reusing that stamp as the emitted event's TsNs - makes the entry its own commit record: replay and bootstrap traversal order on it with zero extra writes for creates and updates. Deletes still need a durable key since a removed entry cannot carry a timestamp, so MpDl tombstones stay (one write per delete, growth bounded by delete history). Entries predating the field fall back to mtime, matching what peers and old records already assume. This replaces the MpTs/MpOff/MpGen/MpRep machinery entirely: shared- store filers write nothing extra, and dedicated-store replication keeps last-writer-wins ordering plus tombstone coverage for deletes and ancestor drops. * filer: keep a directory update replay from tombstoning its subtree A same-path update wrote a delete record before the delete-and-reinsert, so a directory metadata change read as a subtree delete: a later peer event for a child older than the update was then skipped even though nobody deleted the children, leaving files missing on this filer. Only file updates take the tombstone now — the re-inserted directory entry's own commit stamp orders the path itself. * filer: order unstamped entries by their recorded commit before mtime Entries written before stamping existed have no CommitTsNs, so the ordering check fell back to the client-settable mtime and dropped the MpTs record those versions wrote: an entry committed at event time 300 with mtime 100 lost to a delayed peer event at 200 after upgrade. Read the legacy record for unstamped entries in localCommitTsNs, CommitTsNs, and the traverse stamp (which also stopped falling back to mtime, regressing entry_ts_ns to 0). * filer: release queued rename event stamps when the rename fails Each moved entry carried an in-flight stamp its queued event would adopt at emit time. When the move succeeded but a later child move or the commit failed, the handler rolled back without emitting the queued events or releasing their stamps, pinning the delivered and flushed watermarks below the aborted rename forever. Release every queued stamp on both failure exits in both rename handlers. * filer: apply a directory update replay with an in-place upsert Deleting the stored entry before inserting its replacement left a window where the directory had no entry and no ordering record — a tombstone cannot stand in for it without reading as a subtree delete that suppresses the children's own records. A stale peer event accepted in that gap could replay an older update or delete and sweep the directory's children. Upsert the replacement instead: the entry keeps its recorded commit order across the whole update, and a directory has no chunks or hard links for a delete to release. * filer: update an existing directory entry on replay instead of upserting InsertEntry is not an upsert on SQL stores configured without upsert support — PostgreSQL with enableUpsert=false issues a plain INSERT and its duplicate-key error does not match the MySQL-only fallback, so a replay updating a present directory failed on every retry. Pick UpdateEntry when the entry exists and InsertEntry when it is absent; UpdateEntry touches no row that is not there. * filer: detect a shared-store delete racing a replayed directory update UpdateEntry reports success even when the row was deleted between the find and the update — the UPDATE changes zero rows and the replayed change is dropped while the subscription offset advances. Re-read the entry after the update and retry the write, re-checking the recorded commit order each pass so a newer peer change wins instead of being resurrected over. * filer: declare commit_ts_ns in field-number order Field 6 sits between extended and hard_link_id; the declaration now reads in the same order. Wire format unchanged. Also syncs the Java client's checked-in copy of filer.proto, which the pb Makefile copies on gen. * filer: option to skip delete tombstones entirely filer.options.deleteTombstones=false stops writing MpDl records on deletes - a single filer or shared-store cluster never replays peer events, so the tombstones are dead weight. The tradeoff is explicit: if a dedicated-store peer does replicate, a stale event can resurrect a deleted path. * filer: drop delete tombstones entirely Deletes no longer write MpDl records, and the pending-repair machinery they needed is gone with them: per-mutation metadata overhead is now zero for every store topology. Ordering information lives only on the entry itself via commit_ts_ns. The accepted tradeoff: a dedicated-store peer replaying an event older than a delete can resurrect the path, and a kept directory no longer fences stale child creates. Recorded tombstones and MpTs records left by older builds are still read, so upgrades keep the protections they already have. * filer: stop reading legacy per-path records too Drops the MpTs/MpDl read path along with the writes: meta_path_ts.go keeps only the entry-field readers (CommitTsNs, EntryCommitTsNs, localCommitTsNs). Entries written before stamping existed fall back to mtime, and tombstones or commit records older builds left behind no longer fence replayed events. * filer: trim commit timestamp comments --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
444 lines
16 KiB
Go
444 lines
16 KiB
Go
package weed_server
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/filer"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/operation"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/remote_storage"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_objectlock"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
"google.golang.org/protobuf/proto"
|
|
)
|
|
|
|
func (fs *FilerServer) CacheRemoteObjectToLocalCluster(ctx context.Context, req *filer_pb.CacheRemoteObjectToLocalClusterRequest) (*filer_pb.CacheRemoteObjectToLocalClusterResponse, error) {
|
|
// Use singleflight to deduplicate concurrent caching requests for the same object.
|
|
// This benefits all clients: S3 API, filer HTTP, Hadoop, etc.
|
|
cacheKey := req.Directory + "/" + req.Name
|
|
|
|
// Detach from caller ctx: on failure the error path deletes every chunk
|
|
// already written, so cancelling mid-download loses all progress. For
|
|
// blobs large enough that the download outlasts the caller's timeout
|
|
// the retry loop never converges.
|
|
bgCtx := context.WithoutCancel(ctx)
|
|
|
|
// DoChan (vs Do) so the caller can bail out on ctx.Done() while the
|
|
// singleflight goroutine keeps caching on bgCtx; otherwise this handler
|
|
// goroutine stays blocked for the full download after the client is gone.
|
|
ch := fs.remoteCacheGroup.DoChan(cacheKey, func() (interface{}, error) {
|
|
return fs.doCacheRemoteObjectToLocalCluster(bgCtx, req)
|
|
})
|
|
|
|
select {
|
|
case <-ctx.Done():
|
|
// Caller gave up; the detached cache keeps running and a later
|
|
// request will find the entry cached (or join the same singleflight).
|
|
return nil, ctx.Err()
|
|
case res := <-ch:
|
|
if res.Shared {
|
|
glog.V(2).Infof("CacheRemoteObjectToLocalCluster: shared result for %s", cacheKey)
|
|
}
|
|
if res.Err != nil {
|
|
return nil, cacheRemoteObjectError(res.Err)
|
|
}
|
|
if res.Val == nil {
|
|
return nil, fmt.Errorf("unexpected nil result from singleflight")
|
|
}
|
|
resp, ok := res.Val.(*filer_pb.CacheRemoteObjectToLocalClusterResponse)
|
|
if !ok {
|
|
return nil, fmt.Errorf("unexpected result type from singleflight")
|
|
}
|
|
return resp, nil
|
|
}
|
|
}
|
|
|
|
// doCacheRemoteObjectToLocalCluster performs the actual caching operation.
|
|
// This is called from singleflight, so only one instance runs per object.
|
|
func (fs *FilerServer) doCacheRemoteObjectToLocalCluster(ctx context.Context, req *filer_pb.CacheRemoteObjectToLocalClusterRequest) (*filer_pb.CacheRemoteObjectToLocalClusterResponse, error) {
|
|
lockPath := util.JoinPath(req.Directory, req.Name)
|
|
entry, logTsNs, err := fs.fencedFindEntry(ctx, lockPath)
|
|
|
|
if err == filer_pb.ErrNotFound {
|
|
return nil, err
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("find entry %s/%s: %v", req.Directory, req.Name, err)
|
|
}
|
|
|
|
resp := &filer_pb.CacheRemoteObjectToLocalClusterResponse{LogTsNs: logTsNs, LogSignature: fs.filer.Signature}
|
|
|
|
// Early return if not a remote-only object or already cached
|
|
if entry.Remote == nil || entry.Remote.RemoteSize == 0 {
|
|
resp.Entry = entry.ToProtoEntry()
|
|
return resp, nil
|
|
}
|
|
if len(entry.GetChunks()) > 0 {
|
|
// Already has local chunks - already cached
|
|
glog.V(2).Infof("CacheRemoteObjectToLocalCluster: %s/%s already cached (%d chunks)", req.Directory, req.Name, len(entry.GetChunks()))
|
|
resp.Entry = entry.ToProtoEntry()
|
|
return resp, nil
|
|
}
|
|
|
|
glog.V(1).Infof("CacheRemoteObjectToLocalCluster: caching %s/%s (remote size: %d)", req.Directory, req.Name, entry.Remote.RemoteSize)
|
|
|
|
readDir, readName := fs.filer.RemoteReadPath(entry, req.Directory, req.Name)
|
|
storageConf, remoteLocation, err := fs.resolveMountedRemote(ctx, readDir, readName)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// detect storage option
|
|
so, err := fs.detectStorageOption(ctx, req.Directory, "", "", 0, "", "", "", "")
|
|
if err != nil {
|
|
return resp, err
|
|
}
|
|
assignRequest, altRequest := so.ToAssignRequests(1)
|
|
|
|
// adaptive chunk size: target ~32 chunks per file to balance
|
|
// per-chunk overhead (volume assign, gRPC, needle write) against parallelism
|
|
chunkSize := int64(5 * 1024 * 1024) // 5MB floor
|
|
maxChunkSize := int64(fs.option.MaxMB) * 1024 * 1024
|
|
if maxChunkSize < chunkSize {
|
|
maxChunkSize = chunkSize
|
|
}
|
|
targetChunks := int64(32)
|
|
if entry.Remote.RemoteSize/targetChunks > chunkSize {
|
|
chunkSize = entry.Remote.RemoteSize / targetChunks
|
|
if chunkSize > maxChunkSize {
|
|
chunkSize = maxChunkSize
|
|
}
|
|
}
|
|
// final safety check: ensure no more than 1000 chunks
|
|
if (entry.Remote.RemoteSize+chunkSize-1)/chunkSize > 1000 {
|
|
chunkSize = (entry.Remote.RemoteSize + 999) / 1000
|
|
}
|
|
|
|
// Now that chunkSize is known, hint it to the master so per-chunk
|
|
// assigns don't fall back to the 1 MB default estimate. Slightly over-
|
|
// estimates for the final partial chunk (< chunkSize) by design.
|
|
assignRequest.ExpectedDataSize = uint64(chunkSize)
|
|
if altRequest != nil {
|
|
altRequest.ExpectedDataSize = uint64(chunkSize)
|
|
}
|
|
|
|
var chunks []*filer_pb.FileChunk
|
|
var chunksMu sync.Mutex
|
|
var fetchAndWriteErr error
|
|
var wg sync.WaitGroup
|
|
|
|
chunkConcurrency := int(req.ChunkConcurrency)
|
|
if chunkConcurrency <= 0 {
|
|
chunkConcurrency = 8
|
|
} else if chunkConcurrency > 1024 {
|
|
glog.V(0).Infof("capping chunkConcurrency from %d to 1024", chunkConcurrency)
|
|
chunkConcurrency = 1024
|
|
}
|
|
downloadConcurrency := req.DownloadConcurrency
|
|
if downloadConcurrency > 1024 {
|
|
glog.V(0).Infof("capping downloadConcurrency from %d to 1024", downloadConcurrency)
|
|
downloadConcurrency = 1024
|
|
}
|
|
|
|
limitedConcurrentExecutor := util.NewLimitedConcurrentExecutor(chunkConcurrency)
|
|
for offset := int64(0); offset < entry.Remote.RemoteSize; offset += chunkSize {
|
|
localOffset := offset
|
|
|
|
wg.Add(1)
|
|
limitedConcurrentExecutor.Execute(func() {
|
|
defer wg.Done()
|
|
size := chunkSize
|
|
if localOffset+chunkSize > entry.Remote.RemoteSize {
|
|
size = entry.Remote.RemoteSize - localOffset
|
|
}
|
|
|
|
// assign one volume server
|
|
assignResult, err := operation.Assign(ctx, fs.filer.GetMaster, fs.grpcDialOption, assignRequest, altRequest)
|
|
if err != nil {
|
|
chunksMu.Lock()
|
|
if fetchAndWriteErr == nil {
|
|
fetchAndWriteErr = err
|
|
}
|
|
chunksMu.Unlock()
|
|
return
|
|
}
|
|
if assignResult.Error != "" {
|
|
chunksMu.Lock()
|
|
if fetchAndWriteErr == nil {
|
|
fetchAndWriteErr = fmt.Errorf("assign: %v", assignResult.Error)
|
|
}
|
|
chunksMu.Unlock()
|
|
return
|
|
}
|
|
fileId, parseErr := needle.ParseFileIdFromString(assignResult.Fid)
|
|
if parseErr != nil {
|
|
chunksMu.Lock()
|
|
if fetchAndWriteErr == nil {
|
|
fetchAndWriteErr = fmt.Errorf("unrecognized file id %s: %v", assignResult.Fid, parseErr)
|
|
}
|
|
chunksMu.Unlock()
|
|
return
|
|
}
|
|
|
|
var replicas []*volume_server_pb.FetchAndWriteNeedleRequest_Replica
|
|
for _, r := range assignResult.Replicas {
|
|
replicas = append(replicas, &volume_server_pb.FetchAndWriteNeedleRequest_Replica{
|
|
Url: r.Url,
|
|
PublicUrl: r.PublicUrl,
|
|
GrpcPort: int32(r.GrpcPort),
|
|
})
|
|
}
|
|
|
|
// tell filer to tell volume server to download into needles
|
|
assignedServerAddress := pb.NewServerAddressWithGrpcPort(assignResult.Url, assignResult.GrpcPort)
|
|
var etag string
|
|
err = operation.WithVolumeServerClient(false, assignedServerAddress, fs.grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
|
resp, fetchErr := volumeServerClient.FetchAndWriteNeedle(context.Background(), &volume_server_pb.FetchAndWriteNeedleRequest{
|
|
VolumeId: uint32(fileId.VolumeId),
|
|
NeedleId: uint64(fileId.Key),
|
|
Cookie: uint32(fileId.Cookie),
|
|
Offset: localOffset,
|
|
Size: size,
|
|
Replicas: replicas,
|
|
Auth: string(assignResult.Auth),
|
|
DownloadConcurrency: downloadConcurrency,
|
|
RemoteConf: storageConf,
|
|
RemoteLocation: remoteLocation,
|
|
})
|
|
if fetchErr != nil {
|
|
return fetchAndWriteError(assignResult.Url, remoteLocation.Path, fetchErr)
|
|
}
|
|
etag = resp.ETag
|
|
return nil
|
|
})
|
|
|
|
if err != nil {
|
|
chunksMu.Lock()
|
|
if fetchAndWriteErr == nil {
|
|
fetchAndWriteErr = err
|
|
}
|
|
chunksMu.Unlock()
|
|
return
|
|
}
|
|
|
|
chunk := &filer_pb.FileChunk{
|
|
FileId: assignResult.Fid,
|
|
Offset: localOffset,
|
|
Size: uint64(size),
|
|
ModifiedTsNs: time.Now().UnixNano(),
|
|
ETag: etag,
|
|
Fid: &filer_pb.FileId{
|
|
VolumeId: uint32(fileId.VolumeId),
|
|
FileKey: uint64(fileId.Key),
|
|
Cookie: uint32(fileId.Cookie),
|
|
},
|
|
}
|
|
chunksMu.Lock()
|
|
chunks = append(chunks, chunk)
|
|
chunksMu.Unlock()
|
|
})
|
|
}
|
|
|
|
wg.Wait()
|
|
|
|
chunksMu.Lock()
|
|
err = fetchAndWriteErr
|
|
// Sort chunks by offset to maintain file order
|
|
sort.Slice(chunks, func(i, j int) bool {
|
|
return chunks[i].Offset < chunks[j].Offset
|
|
})
|
|
chunksMu.Unlock()
|
|
if err != nil {
|
|
// Clean up any chunks that were successfully written before the error.
|
|
// Without this, partial downloads leave orphaned needles in volume servers
|
|
// that accumulate across retry cycles and cannot be reclaimed by vacuum.
|
|
if len(chunks) > 0 {
|
|
fs.filer.DeleteUncommittedChunks(ctx, chunks)
|
|
}
|
|
if fs.option.RemoteCacheEvictThreshold > 0 && isRemoteCacheCapacityError(err) {
|
|
fileIds := make([]string, 0, len(chunks))
|
|
for _, chunk := range chunks {
|
|
fileIds = append(fileIds, chunk.GetFileIdString())
|
|
}
|
|
fs.notePendingRemoteCacheVids(fileIds)
|
|
go fs.reclaimRemoteCacheSpace(fs.evictCtx(), entry.Remote.RemoteSize, nil)
|
|
}
|
|
fs.pruneEntryMissingFromRemote(ctx, lockPath, entry, err)
|
|
return nil, err
|
|
}
|
|
|
|
// Commit under the mutation path lock so a fenced lookup cannot land
|
|
// between the store update and its notification, handing out
|
|
// under-versioned state. Re-read under it: the entry may have changed
|
|
// during the unlocked download, and the stale base would clobber it.
|
|
commitLock := fs.entryLockTable.AcquireLock("CacheRemoteObjectToLocalCluster", lockPath, util.ExclusiveLock)
|
|
defer fs.entryLockTable.ReleaseLock(lockPath, commitLock)
|
|
|
|
commitLogTsNs := time.Now().UnixNano()
|
|
current, err := fs.filer.FindEntry(ctx, lockPath)
|
|
if err != nil {
|
|
fs.filer.DeleteUncommittedChunks(ctx, chunks)
|
|
if err == filer_pb.ErrNotFound {
|
|
// Deleted while the download ran; keep the sentinel so callers
|
|
// still surface a 404 rather than a generic failure.
|
|
return nil, err
|
|
}
|
|
return nil, fmt.Errorf("find entry %s before commit: %v", lockPath, err)
|
|
}
|
|
if !filer.EqualEntry(current, entry) {
|
|
// Changed during the download: that writer supersedes the cached
|
|
// content. Return the current state, fenced at this read.
|
|
fs.filer.DeleteUncommittedChunks(ctx, chunks)
|
|
resp.Entry = current.ToProtoEntry()
|
|
resp.LogTsNs = commitLogTsNs
|
|
resp.LogSignature = fs.filer.Signature
|
|
return resp, nil
|
|
}
|
|
|
|
garbage := entry.GetChunks()
|
|
|
|
newEntry := entry.ShallowClone()
|
|
newEntry.Chunks = chunks
|
|
newEntry.Remote = proto.Clone(entry.Remote).(*filer_pb.RemoteEntry)
|
|
newEntry.Remote.LastLocalSyncTsNs = time.Now().UnixNano()
|
|
|
|
// this skips meta data log events
|
|
|
|
fs.filer.StampEntryCommitTsNs(newEntry)
|
|
if err := fs.filer.Store.UpdateEntry(context.Background(), newEntry); err != nil {
|
|
fs.filer.ReleaseEntryCommitTsNs(newEntry.CommitTsNs)
|
|
fs.filer.DeleteUncommittedChunks(ctx, chunks)
|
|
return nil, err
|
|
}
|
|
fs.filer.DeleteChunks(ctx, entry.FullPath, garbage)
|
|
|
|
ctx, eventSink := filer.WithMetadataEventSink(ctx)
|
|
fs.filer.NotifyUpdateEvent(ctx, entry, newEntry, true, false, nil)
|
|
|
|
resp.Entry = newEntry.ToProtoEntry()
|
|
resp.MetadataEvent = eventSink.Last()
|
|
resp.LogTsNs = commitLogTsNs
|
|
resp.LogSignature = fs.filer.Signature
|
|
|
|
return resp, nil
|
|
|
|
}
|
|
|
|
// resolveMountedRemote reads /etc/remote fresh (so conf changes need no restart)
|
|
// and maps dir/name to its remote storage conf and remote location.
|
|
func (fs *FilerServer) resolveMountedRemote(ctx context.Context, dir, name string) (*remote_pb.RemoteConf, *remote_pb.RemoteStorageLocation, error) {
|
|
mappingEntry, err := fs.filer.FindEntry(ctx, util.JoinPath(filer.DirectoryEtcRemote, filer.REMOTE_STORAGE_MOUNT_FILE))
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
mappings, err := filer.UnmarshalRemoteStorageMappings(mappingEntry.Content)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
localMountedDir, remoteStorageMountedLocation, err := filer.FindMountedRemoteMapping(mappings, dir)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
storageConfEntry, err := fs.filer.FindEntry(ctx, util.JoinPath(filer.DirectoryEtcRemote, remoteStorageMountedLocation.Name+filer.REMOTE_STORAGE_CONF_SUFFIX))
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
storageConf := &remote_pb.RemoteConf{}
|
|
if unMarshalErr := proto.Unmarshal(storageConfEntry.Content, storageConf); unMarshalErr != nil {
|
|
return nil, nil, fmt.Errorf("unmarshal remote storage conf %s/%s: %v", filer.DirectoryEtcRemote, remoteStorageMountedLocation.Name+filer.REMOTE_STORAGE_CONF_SUFFIX, unMarshalErr)
|
|
}
|
|
|
|
remoteLocation := filer.MapFullPathToRemoteStorageLocation(util.FullPath(localMountedDir), remoteStorageMountedLocation, util.FullPath(dir).Child(name))
|
|
return storageConf, remoteLocation, nil
|
|
}
|
|
|
|
// fetchAndWriteError restores the remote's not-found sentinel from the volume
|
|
// server's answer, so it is told apart from failures worth retrying.
|
|
func fetchAndWriteError(volumeServer, path string, err error) error {
|
|
if st, ok := status.FromError(err); ok && st.Code() == codes.NotFound && strings.Contains(st.Message(), remote_storage.ErrRemoteObjectNotFound.Error()) {
|
|
return fmt.Errorf("volume server %s fetchAndWrite %s: %w", volumeServer, path, remote_storage.ErrRemoteObjectNotFound)
|
|
}
|
|
return fmt.Errorf("volume server %s fetchAndWrite %s: %v", volumeServer, path, err)
|
|
}
|
|
|
|
// cacheRemoteObjectError makes the not-found sentinels canonical: they would
|
|
// cross gRPC as codes.Unknown, and remote callers classify a vanished entry or
|
|
// remote object by codes.NotFound.
|
|
func cacheRemoteObjectError(err error) error {
|
|
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, remote_storage.ErrRemoteObjectNotFound) {
|
|
return status.Error(codes.NotFound, err.Error())
|
|
}
|
|
return err
|
|
}
|
|
|
|
// pruneEntryMissingFromRemote converges the filer on the remote once the remote
|
|
// confirms the object is gone. It removes the entry only while it is still the
|
|
// one the failed fetch read: any write since then owns the path. The check and
|
|
// delete run as an object transaction so they land on the path's write owner,
|
|
// under the lock the S3 object writes take.
|
|
func (fs *FilerServer) pruneEntryMissingFromRemote(ctx context.Context, p util.FullPath, fetched *filer.Entry, fetchErr error) bool {
|
|
if !errors.Is(fetchErr, remote_storage.ErrRemoteObjectNotFound) || !isPrunableRemoteEntry(fetched) {
|
|
return false
|
|
}
|
|
dir, name := p.DirAndName()
|
|
resp, err := fs.ObjectTransaction(ctx, &filer_pb.ObjectTransactionRequest{
|
|
LockKey: string(p),
|
|
RouteKey: entryRouteKey(p),
|
|
Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{{
|
|
Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL,
|
|
ExpectedEntry: fetched.ToProtoEntry(),
|
|
}}},
|
|
Mutations: []*filer_pb.ObjectMutation{{
|
|
Type: filer_pb.ObjectMutation_DELETE,
|
|
Directory: dir,
|
|
Name: name,
|
|
KeepRemoteObject: true,
|
|
}},
|
|
})
|
|
if err != nil {
|
|
glog.WarningfCtx(ctx, "prune %s missing from remote: %v", p, err)
|
|
return false
|
|
}
|
|
if resp.Error != "" {
|
|
if resp.ErrorCode != filer_pb.FilerError_PRECONDITION_FAILED {
|
|
glog.WarningfCtx(ctx, "prune %s missing from remote: %s", p, resp.Error)
|
|
}
|
|
return false
|
|
}
|
|
glog.V(0).InfofCtx(ctx, "pruned %s: its remote object no longer exists", p)
|
|
return true
|
|
}
|
|
|
|
// isPrunableRemoteEntry admits only a file whose content lives solely on the
|
|
// remote. Version entries are left alone because their parent's latest-version
|
|
// pointer would dangle, and locked objects because pruning would bypass the
|
|
// lock.
|
|
func isPrunableRemoteEntry(entry *filer.Entry) bool {
|
|
if entry == nil || entry.IsDirectory() || !entry.IsInRemoteOnly() {
|
|
return false
|
|
}
|
|
if len(entry.Content) > 0 || len(entry.HardLinkId) > 0 {
|
|
return false
|
|
}
|
|
if dir, _ := entry.FullPath.DirAndName(); strings.HasSuffix(dir, s3_constants.VersionsFolder) {
|
|
return false
|
|
}
|
|
return !s3_objectlock.EntryHasActiveLock(entry.ToProtoEntry(), time.Now())
|
|
}
|