mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-10-13 17:48:29 +02:00
* filer: skip replayed peer events older than the local entry Replay deleted and re-inserted every received event unconditionally, so a restarted filer that rewound its subscription offset re-applied stale peer writes over newer local state (values reverted, deleted entries came back and pointed at already-vacuumed chunks). Compare the event's TsNs against the local entry's Mtime and skip per-path, so a move event can still remove its source while keeping a newer destination. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: add replay last-writer-wins regression tests Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: stop peer subscriptions and flush offsets on shutdown Filer.Shutdown closed the store while subscription goroutines were still mid-stream; their deferred offset save was never guaranteed to run, so a restart rewound each peer's stream back to the last periodic flush and replayed stale events. MetaAggregator.Shutdown now closes every peer's stop channel and waits for the loops so the saved offset covers what was replayed, and the reconnect sleep is interruptible by the stop channel. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: test that shutdown stops and waits for peer loops Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: order replay by persisted per-path commit timestamps Review feedback found the mtime comparison still lets stale replay win: a local delete removes the entry it would have been compared against, an entry mtime is client-controllable, and the check ran unlocked so a local write could land between it and the store mutation. - Record the event timestamp per mutated path in the store KV on every emitted mutation, plus a delete record for sources of deletes and renames. The record survives the entry, so a replayed create older than a local delete no longer resurrects it; ancestor delete records cover children swept without per-child events. - Replay compares the event timestamp against that record under the same per-path entry locks local RPC mutations hold, falling back to entry mtime only for entries written before records existed. Lookup errors now abort the event instead of being treated as an absent entry. - MetaAggregator.Shutdown marks the aggregator stopped under peerChansLock so a master update cannot start a subscription that outlives the wait, and waits for the loops without the five-second cap now that every blocking stage — signature RPC, bootstrap traversal, retry sleeps, and per-event processing — cancels on the stop channel. * filer: pin peer offset at failed replay, fix commit-record context and key size A replayed event that exhausted its retries (or was interrupted by shutdown) was still followed by advancing the peer watermark, so the persisted offset skipped the unapplied event forever. replicateMetadataChange now reports the outcome: errPeerSubscriptionStopped aborts the subscription so the deferred save keeps the last completed event, and an exhausted retry records a barrier the persisted offset and reconnect resume point cannot pass while the stream keeps flowing. Commit records also failed on two fronts: NotifyUpdateEvent runs after CommitTransaction with the same context, so SQL stores wrote MpTs/MpDl through an already-committed *sql.Tx; and metaPathKey embedded the whole path, overflowing the 766-char name column SQL KV stores use, which the KvPut fallback update then silently dropped. The writes now use a fresh context and a sha256-hashed fixed-size key. * filer: lock HTTP delete handler and replay against ancestor paths The HTTP DeleteHandler called DeleteEntryMetaAndData without the shared entry lock, so a peer replay could still interleave with a local delete and its commit record. It now holds the same lock the gRPC DeleteEntry handler does. Replay also locked only the exact event paths, but its ordering check consults ancestor delete records: a local recursive delete holds only the ancestor's lock, so a stale child create could check before the tombstone landed and then reinsert. lockReplayPaths now locks every ancestor of both event paths in one lexicographic order — parents sort before children, as the rename handler's two-path order already does — while never locking the root, which cannot be deleted and would serialize all replays. * filer: record replay commit before the replacement insert If the same-path update DeleteEntry succeeded but InsertEntry failed, the path sat deleted with no commit record until the retry arrived, and a stale peer create could resurrect it in the gap. The commit record now lands immediately after the delete — without a delete record, since an update is not a delete — and again after the successful insert. * filer: lock replay ancestors shared, not exclusive Exclusive locks on every ancestor serialized all replays under a shared parent — unrelated objects in the same bucket could no longer apply in parallel. Ancestors only need to exclude an exclusive holder (a local delete or rename of the ancestor), so they now take shared locks; a path the event changes stays exclusive even when it is also the other path's ancestor. * filer: order peer bootstrap on the sender's commit timestamp traversePeerMetadata compared localCommitTsNs — a commit-clock value — against the entry's mtime, which a client can set freely: a peer change committed recently with an old mtime was skipped, and a stale entry mtime-stamped in the future overwrote a newer local commit. TraverseBfsMetadataResponse now carries the sender's per-path commit timestamp (recorded MpTs record, entry mtime as the unrecorded fallback). The bootstrap applies an entry only when its commit is newer than the local one and records the applied timestamp, so replayed events order against it — closing the gap between bootstrap content and the event stream. A peer without the field sends 0 and keeps the mtime fallback, preserving rolling-upgrade behavior. * filer: keep failed commit records pending until they land notePathChange ran after the mutation committed and only logged a KvPut failure: a delete whose MpTs/MpDl record never landed left no tombstone, so a stale replayed create could resurrect the path while the store was unreachable. Failed records now stay in metaTsPending and a repair pass retries them until they land. localCommitTsNs, deletedAfterTsNs and CommitTsNs consult the pending record, so ordering holds in the window between the committed mutation and the durable record. A per-path flag bounds the repair to one goroutine, and respawns cover merges landing between its last pass and the flag release. * filer: keep only unwritten work in the pending commit record The pending record merged every obligation into one timestamp and flag, and a later successful write left it untouched: a repair pass could then write an older timestamp over a newer one, and a merged delete inherited the newer change's time, which the ancestor check reads as a newer delete. The record now holds a change and a delete timestamp of its own, both discharged under the record's lock alongside the store writes that cover them, so a repair writes only what is still owed. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: fail traversal on a commit-record read error CommitTsNs answered a store read failure with the entry mtime, a value clients can set arbitrarily far ahead; a peer bootstrapping on it would record the minted time and reject real updates below it. The lookup now returns the error so the traversal restarts instead. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
362 lines
12 KiB
Go
362 lines
12 KiB
Go
package weed_server
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/operation"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/security"
|
|
"github.com/seaweedfs/seaweedfs/weed/stats"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
"github.com/seaweedfs/seaweedfs/weed/util/constants"
|
|
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
|
)
|
|
|
|
var (
|
|
OS_UID = uint32(os.Getuid())
|
|
OS_GID = uint32(os.Getgid())
|
|
|
|
// ErrReadOnly is filer_pb.ErrReadOnly so errors.Is matches on either side
|
|
// of the gRPC boundary.
|
|
ErrReadOnly = filer_pb.ErrReadOnly
|
|
)
|
|
|
|
type FilerPostResult struct {
|
|
Name string `json:"name,omitempty"`
|
|
Size int64 `json:"size,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
}
|
|
|
|
func (fs *FilerServer) assignNewFileInfo(ctx context.Context, so *operation.StorageOption, expectedDataSize uint64) (fileId, urlLocation string, auth security.EncodedJwt, err error) {
|
|
|
|
stats.FilerHandlerCounter.WithLabelValues(stats.ChunkAssign).Inc()
|
|
start := time.Now()
|
|
defer func() {
|
|
stats.FilerRequestHistogram.WithLabelValues(stats.ChunkAssign).Observe(time.Since(start).Seconds())
|
|
}()
|
|
|
|
ar, altRequest := so.ToAssignRequests(1)
|
|
ar.ExpectedDataSize = expectedDataSize
|
|
if altRequest != nil {
|
|
altRequest.ExpectedDataSize = expectedDataSize
|
|
}
|
|
|
|
// Use a context that ignores cancellation from the request context
|
|
assignCtx := context.WithoutCancel(ctx)
|
|
|
|
assignResult, ae := operation.Assign(assignCtx, fs.filer.GetMaster, fs.grpcDialOption, ar, altRequest)
|
|
if ae != nil {
|
|
glog.ErrorfCtx(ctx, "failing to assign a file id: %v", ae)
|
|
err = ae
|
|
return
|
|
}
|
|
fileId = assignResult.Fid
|
|
assignUrl := assignResult.Url
|
|
// Prefer same data center
|
|
if fs.option.DataCenter != "" {
|
|
for _, repl := range assignResult.Replicas {
|
|
if repl.DataCenter == fs.option.DataCenter {
|
|
assignUrl = repl.Url
|
|
break
|
|
}
|
|
}
|
|
}
|
|
urlLocation = "http://" + assignUrl + "/" + assignResult.Fid
|
|
if so.Fsync {
|
|
urlLocation += "?fsync=true"
|
|
}
|
|
auth = assignResult.Auth
|
|
return
|
|
}
|
|
|
|
func (fs *FilerServer) PostHandler(w http.ResponseWriter, r *http.Request, contentLength int64) {
|
|
ctx := r.Context()
|
|
|
|
// Match storage rules on the decoded path the entry is written to. The raw
|
|
// request-target is percent-encoded on the wire, so a rule on "/只读/" would
|
|
// never see "/%E5%8F%AA%E8%AF%BB/".
|
|
destination := r.URL.Path
|
|
headerDestination := r.Header.Get(s3_constants.SeaweedStorageDestinationHeader)
|
|
if headerDestination != "" {
|
|
destination = headerDestination
|
|
}
|
|
|
|
// The destination header picks storage rules for a logical destination, but
|
|
// the entry is written at r.URL.Path. Enforce the read-only/quota rule on the
|
|
// actual write path too, so the header cannot route a write into a read-only
|
|
// location.
|
|
if headerDestination != "" && fs.filer.FilerConf.MatchStorageRule(r.URL.Path).ReadOnly {
|
|
writeJsonError(w, r, http.StatusInsufficientStorage, ErrReadOnly)
|
|
return
|
|
}
|
|
|
|
query := r.URL.Query()
|
|
so, err := fs.detectStorageOption0(ctx, destination,
|
|
query.Get("collection"),
|
|
query.Get("replication"),
|
|
query.Get("ttl"),
|
|
query.Get("disk"),
|
|
query.Get("fsync"),
|
|
query.Get("dataCenter"),
|
|
query.Get("rack"),
|
|
query.Get("dataNode"),
|
|
query.Get("saveInside"),
|
|
)
|
|
if err != nil {
|
|
if errors.Is(err, ErrReadOnly) {
|
|
writeJsonError(w, r, http.StatusInsufficientStorage, err)
|
|
} else {
|
|
glog.V(1).InfolnCtx(ctx, "post", r.RequestURI, ":", err.Error())
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
}
|
|
return
|
|
}
|
|
|
|
if util.FullPath(r.URL.Path).IsLongerFileName(so.MaxFileNameLength) {
|
|
glog.V(1).InfolnCtx(ctx, "post", r.RequestURI, ": ", "entry name too long")
|
|
w.WriteHeader(http.StatusRequestURITooLong)
|
|
return
|
|
}
|
|
|
|
// When DiskType is empty,use filer's -disk
|
|
if so.DiskType == "" {
|
|
so.DiskType = fs.option.DiskType
|
|
}
|
|
|
|
if strings.HasPrefix(r.URL.Path, "/etc") {
|
|
so.SaveInside = true
|
|
}
|
|
|
|
if query.Has("mv.from") {
|
|
fs.move(ctx, w, r, so)
|
|
} else if query.Has("cp.from") {
|
|
fs.copy(ctx, w, r, so)
|
|
} else {
|
|
fs.autoChunk(ctx, w, r, contentLength, so)
|
|
}
|
|
|
|
util_http.CloseRequest(r)
|
|
|
|
}
|
|
|
|
func (fs *FilerServer) move(ctx context.Context, w http.ResponseWriter, r *http.Request, so *operation.StorageOption) {
|
|
src := r.URL.Query().Get("mv.from")
|
|
dst := r.URL.Path
|
|
|
|
glog.V(2).InfofCtx(ctx, "FilerServer.move %v to %v", src, dst)
|
|
|
|
var err error
|
|
if src, err = clearName(src); err != nil {
|
|
writeJsonError(w, r, http.StatusBadRequest, err)
|
|
return
|
|
}
|
|
if dst, err = clearName(dst); err != nil {
|
|
writeJsonError(w, r, http.StatusBadRequest, err)
|
|
return
|
|
}
|
|
src = strings.TrimRight(src, "/")
|
|
if src == "" {
|
|
err = fmt.Errorf("invalid source '/'")
|
|
writeJsonError(w, r, http.StatusBadRequest, err)
|
|
return
|
|
}
|
|
|
|
srcPath := util.FullPath(src)
|
|
dstPath := util.FullPath(dst)
|
|
if dstPath.IsLongerFileName(so.MaxFileNameLength) {
|
|
err = fmt.Errorf("dst name to long")
|
|
writeJsonError(w, r, http.StatusBadRequest, err)
|
|
return
|
|
}
|
|
srcEntry, err := fs.filer.FindEntry(ctx, srcPath)
|
|
if err != nil {
|
|
err = fmt.Errorf("failed to get src entry '%s', err: %s", src, err)
|
|
writeJsonError(w, r, http.StatusBadRequest, err)
|
|
return
|
|
}
|
|
|
|
wormEnforced, err := fs.wormEnforcedForEntry(ctx, src)
|
|
if err != nil {
|
|
writeJsonError(w, r, http.StatusInternalServerError, err)
|
|
return
|
|
} else if wormEnforced {
|
|
// you cannot move a worm file or directory
|
|
err = fmt.Errorf("cannot move write-once entry from '%s' to '%s': %s", src, dst, constants.ErrMsgOperationNotPermitted)
|
|
writeJsonError(w, r, http.StatusForbidden, err)
|
|
return
|
|
}
|
|
|
|
oldDir, oldName := srcPath.DirAndName()
|
|
newDir, newName := dstPath.DirAndName()
|
|
newName = util.Nvl(newName, oldName)
|
|
|
|
dstEntry, err := fs.filer.FindEntry(ctx, util.FullPath(strings.TrimRight(dst, "/")))
|
|
if err != nil && err != filer_pb.ErrNotFound {
|
|
err = fmt.Errorf("failed to get dst entry '%s', err: %s", dst, err)
|
|
writeJsonError(w, r, http.StatusInternalServerError, err)
|
|
return
|
|
}
|
|
if err == nil && !dstEntry.IsDirectory() && srcEntry.IsDirectory() {
|
|
err = fmt.Errorf("move: cannot overwrite non-directory '%s' with directory '%s'", dst, src)
|
|
writeJsonError(w, r, http.StatusBadRequest, err)
|
|
return
|
|
}
|
|
|
|
_, err = fs.AtomicRenameEntry(ctx, &filer_pb.AtomicRenameEntryRequest{
|
|
OldDirectory: oldDir,
|
|
OldName: oldName,
|
|
NewDirectory: newDir,
|
|
NewName: newName,
|
|
})
|
|
if err != nil {
|
|
err = fmt.Errorf("failed to move entry from '%s' to '%s', err: %s", src, dst, err)
|
|
writeJsonError(w, r, http.StatusBadRequest, err)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
// curl -X DELETE http://localhost:8888/path/to
|
|
// curl -X DELETE http://localhost:8888/path/to?recursive=true
|
|
// curl -X DELETE http://localhost:8888/path/to?recursive=true&ignoreRecursiveError=true
|
|
// curl -X DELETE http://localhost:8888/path/to?recursive=true&skipChunkDeletion=true
|
|
func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
|
|
isRecursive := r.FormValue("recursive") == "true"
|
|
if !isRecursive && fs.option.recursiveDelete {
|
|
if r.FormValue("recursive") != "false" {
|
|
isRecursive = true
|
|
}
|
|
}
|
|
ignoreRecursiveError := r.FormValue("ignoreRecursiveError") == "true"
|
|
skipChunkDeletion := r.FormValue("skipChunkDeletion") == "true"
|
|
|
|
objectPath := r.URL.Path
|
|
if len(r.URL.Path) > 1 && strings.HasSuffix(objectPath, "/") {
|
|
objectPath = objectPath[0 : len(objectPath)-1]
|
|
}
|
|
|
|
wormEnforced, err := fs.wormEnforcedForEntry(context.TODO(), objectPath)
|
|
if err != nil {
|
|
writeJsonError(w, r, http.StatusInternalServerError, err)
|
|
return
|
|
} else if wormEnforced {
|
|
writeJsonError(w, r, http.StatusForbidden, errors.New(constants.ErrMsgOperationNotPermitted))
|
|
return
|
|
}
|
|
|
|
// The delete and the commit record it emits must serialize with peer
|
|
// replay of this path, same as the gRPC DeleteEntry handler.
|
|
fullPath := util.FullPath(objectPath)
|
|
if fs.entryLockTable != nil {
|
|
pathLock := fs.entryLockTable.AcquireLock("DeleteHandler", fullPath, util.ExclusiveLock)
|
|
defer fs.entryLockTable.ReleaseLock(fullPath, pathLock)
|
|
}
|
|
|
|
err = fs.filer.DeleteEntryMetaAndData(context.Background(), fullPath, isRecursive, ignoreRecursiveError, !skipChunkDeletion, false, nil, 0)
|
|
if err != nil && err != filer_pb.ErrNotFound {
|
|
glog.V(1).Infoln("deleting", objectPath, ":", err.Error())
|
|
writeJsonError(w, r, http.StatusInternalServerError, err)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (fs *FilerServer) detectStorageOption(ctx context.Context, requestURI, qCollection, qReplication string, ttlSeconds int32, diskType, dataCenter, rack, dataNode string) (*operation.StorageOption, error) {
|
|
|
|
rule := fs.filer.FilerConf.MatchStorageRule(requestURI)
|
|
|
|
if rule.ReadOnly {
|
|
// Name the read-only prefix so the caller knows which path is locked and why.
|
|
// MatchStorageRule leaves LocationPrefix empty when several rules merge; fall back to the request path.
|
|
prefix := rule.LocationPrefix
|
|
if prefix == "" {
|
|
prefix = requestURI
|
|
}
|
|
return nil, fmt.Errorf("%w: %s (e.g. bucket over quota)", ErrReadOnly, prefix)
|
|
}
|
|
|
|
// Use local variable instead of mutating shared rule
|
|
maxFileNameLength := rule.MaxFileNameLength
|
|
if maxFileNameLength == 0 {
|
|
maxFileNameLength = fs.filer.MaxFilenameLength
|
|
}
|
|
|
|
// required by buckets folder
|
|
bucketDefaultCollection := ""
|
|
if strings.HasPrefix(requestURI, fs.filer.DirBucketsPath+"/") {
|
|
bucketDefaultCollection = fs.filer.DetectBucket(util.FullPath(requestURI))
|
|
}
|
|
|
|
if ttlSeconds == 0 {
|
|
ttl, err := needle.ReadTTL(rule.GetTtl())
|
|
if err != nil {
|
|
glog.ErrorfCtx(ctx, "fail to parse %s ttl setting %s: %v", rule.LocationPrefix, rule.Ttl, err)
|
|
}
|
|
ttlSeconds = int32(ttl.Minutes()) * 60
|
|
}
|
|
|
|
collection := util.Nvl(qCollection, rule.Collection, bucketDefaultCollection, fs.option.Collection)
|
|
|
|
// A placement overlay steers a bound collection's new volumes onto a tier.
|
|
// It sits between the explicit request and the filer.conf rule: it overrides
|
|
// the rule but yields to a value the caller asked for outright. Only a
|
|
// steered collection contributes values; an unsteered one clears them so it
|
|
// falls straight through to the rule.
|
|
overlayDisk, overlayReplication, overlayDataCenter, overlaySteered := fs.filer.ResolvePlacement(collection)
|
|
if !overlaySteered {
|
|
overlayDisk, overlayReplication, overlayDataCenter = "", "", ""
|
|
} else {
|
|
glog.V(4).InfofCtx(ctx, "placement overlay steers collection %s: disk=%q replication=%q dataCenter=%q",
|
|
collection, overlayDisk, overlayReplication, overlayDataCenter)
|
|
}
|
|
|
|
return &operation.StorageOption{
|
|
Replication: util.Nvl(qReplication, overlayReplication, rule.Replication, fs.option.DefaultReplication),
|
|
Collection: collection,
|
|
DataCenter: util.Nvl(dataCenter, overlayDataCenter, rule.DataCenter, fs.option.DataCenter),
|
|
Rack: util.Nvl(rack, rule.Rack, fs.option.Rack),
|
|
DataNode: util.Nvl(dataNode, rule.DataNode, fs.option.DataNode),
|
|
TtlSeconds: ttlSeconds,
|
|
DiskType: util.Nvl(diskType, overlayDisk, rule.DiskType),
|
|
Fsync: rule.Fsync,
|
|
VolumeGrowthCount: rule.VolumeGrowthCount,
|
|
MaxFileNameLength: maxFileNameLength,
|
|
}, nil
|
|
}
|
|
|
|
func (fs *FilerServer) detectStorageOption0(ctx context.Context, requestURI, qCollection, qReplication string, qTtl string, diskType string, fsync string, dataCenter, rack, dataNode, saveInside string) (*operation.StorageOption, error) {
|
|
|
|
ttl, err := needle.ReadTTL(qTtl)
|
|
if err != nil {
|
|
glog.ErrorfCtx(ctx, "fail to parse ttl %s: %v", qTtl, err)
|
|
}
|
|
|
|
so, err := fs.detectStorageOption(ctx, requestURI, qCollection, qReplication, int32(ttl.Minutes())*60, diskType, dataCenter, rack, dataNode)
|
|
if so != nil {
|
|
if fsync == "false" {
|
|
so.Fsync = false
|
|
} else if fsync == "true" {
|
|
so.Fsync = true
|
|
}
|
|
if saveInside == "true" {
|
|
so.SaveInside = true
|
|
} else {
|
|
so.SaveInside = false
|
|
}
|
|
}
|
|
|
|
return so, err
|
|
}
|