Files
seaweedfs/weed/server/filer_grpc_server_posix_lock.go
T
760f88e294 filer: bind scoped POSIX locks to the verified token id (#13047)
* filer/posixlock: key lock owners and leases by principal

A lock's owner becomes (Principal, Sid, Owner). The principal is server-side
state, empty for unscoped callers, so owners with equal client-chosen sid and
owner under different principals conflict and never match on unlock, release,
reassertion or coalescing. The session index and leases key on
(Principal, Sid).

Scoped sessions are leased per key from their first acquisition: the lease
ends at the earlier of TTL after the last acquisition or renewal on that key
and Lease.NotAfter. Expired scoped locks are dropped before any operation on
their key as well as by ReapExpired. Unscoped sessions keep their current
whole-session lease, started by the first keepalive.

The handler passes the unscoped session for now, so behaviour is unchanged.
NewManagerWithClock lets tests drive lease boundaries.

* filer: bind scoped POSIX locks to the verified token id

PosixLock trusted the client-supplied sid. GET_LK reports a conflicting
lock's sid and owner, so a scoped caller with a write grant on the same path
could reuse them to unlock or release another holder's lock, keep it alive,
or replace it through a KEEP_ALIVE reassertion. A tokenless request with the
same identity could do the same.

A request admitted for a scoped token now acts for that token's verified jti,
derived in posixLockAuthority from the interceptor's authority. It controls
only the locks it took, whatever sid or owner it names. Its lease on each key
ends at the earlier of the 15s TTL after its last acquisition or renewal and
the token's expiry plus the clock leeway. Each renewal passes admission for
its key, so a narrower token cannot extend keys outside its grant. Tokenless
and unscoped calls keep the unscoped namespace and behaviour, and can no
longer match a scoped lock. Scoped TRY_LOCK and reassertion ranges must be
well-formed read or write ranges, checked before any state changes.

GET_LK, the protobuf and forwarding are unchanged; the principal is never
returned or logged. A renewed token with a new jti is a new owner: the old
locks expire and are reacquired.

* filer/posixlock: release an expired session once, however many ranges it holds

* posix locks: report a lock lost on re-assertion to the mount

A mount whose lease lapsed, for example when its scoped token expired or
was replaced by one with a new id, kept re-asserting locks that another
session had since taken. The filer logged the loss but returned success,
and the mount discarded the reply, so nothing on the mount side showed it.

KEEP_ALIVE now returns the first conflicting lock in the existing
has_conflict and conflict fields, which older mounts ignore. The mount
warns once per key when it learns of a loss and forgets it once a
re-assertion succeeds or the key is no longer held. Writes are not fenced.

* filer/posixlock: drop every expired session's ranges in one pass

* filer/posixlock: renew a scoped session's same-grant leases together

Scoped leases expire per key and a keepalive renewed only the key it named.
A mount renews its keys one keepalive at a time, so with many keys and slow
keepalives a round could outlast the 15s lease and a healthy mount lost
locks; unscoped sessions never had this problem because any keepalive
renews the whole session.

Each scoped lease now records a fingerprint of the verified grants it was
acquired or re-asserted under: a SHA-256 over the sorted, deduplicated
(access level, path) entries. A keepalive, bare or re-assertion, extends
every live lease of the same session (principal and sid) held under the
same fingerprint, each to the request's lease (the earlier of the TTL and
the token's expiry plus leeway). Leases taken under other grants, such as
a narrower token reusing the jti, are still renewed only by name, and a
lease that already ended is not revived before the sweep drops it. No
extra filer lookups; unscoped sessions are unchanged.

* filer/posixlock: bound same-grant renewal and refuse ended-lease grants

A scoped keepalive scanned every key of its session to renew those held
under the same grant, so a mount renewing N keys one by one did N^2 lease
visits per round under the manager's mutex. The scan now runs at most once
per quarter lease TTL per grant; every key under the grant still ends no
earlier than three quarters of a TTL after the latest renewal, and the named
key is always renewed in full.

TryLock now refuses a scoped grant whose lease has already ended, such as a
request admitted just before its token expired that then waited on the
manager, instead of granting a lock the next operation would drop. The filer
returns Unauthenticated, which the mount reports as EIO.

* filer/posixlock: skip same-grant scans by deadline floor, not by time

The scan throttle remembered when a grant was last renewed, not how long
that renewal made its keys last. A replacement token with the same id and
grants but a later expiry could then renew one key while the others kept
ending at the old token's expiry.

Each session now keeps, per grant, the deadline the last scan gave every
live key under it, lowered whenever a key is leased for less. A renewal
skips the scan only while that floor already reaches the earlier of its
own deadline and three quarters of a TTL from now, so a mount renewing
keys one by one still costs linear work.

A keepalive from a session holding no leases records nothing, and a
session's floors go with its last lease, so lock-less keepalives with
changing session ids no longer accumulate state the sweeper never sees.

* filer/posixlock: never move a scoped lease's deadline earlier

Renew, a re-assertion, a same-grant scan and a re-lock all set the key's
deadline to the request's own bound. A request under the old token of a
principal that already renews under a replacement (same id and grants,
later expiry) can land after the replacement's renewal, for example one
of the 32 concurrent keepalives in flight when the mount switched
credentials. It then cut the key back to the old token's expiry, and the
lock was dropped before the next round although the replacement had
renewed it. Keep the later of the current and the requested deadline:
every deadline still comes from an admitted request of the same
principal, so a lease never outlives the latest of its tokens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer/posixlock: keep each session's index and leases in one map

bySession, lastSeen, leases and floors were four maps keyed by Session that
had to be created and pruned together. They become one sessions map whose
sessionState holds the session's keys (with each key's lease), its last
keepalive and its grant floors, so a session's state is dropped in one place.
The release loop shared by ReapExpired and ReleaseSession becomes releaseOn.

ReleaseSession now also forgets an unscoped session's last keepalive, so a
session it released is not reported again by the next sweep.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:58:42 -08:00

323 lines
12 KiB
Go

package weed_server
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"slices"
"strconv"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer/posixlock"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
// posixLockSessionTTL is how long a mount's lease survives without a
// keepalive before its locks are reaped; posixLockSweepInterval is how often
// each filer checks. The mount renews well within the TTL.
posixLockSessionTTL = 15 * time.Second
posixLockSweepInterval = 5 * time.Second
// posixCoolingProbeTimeout bounds the dual-read probe to the prior owner so a
// slow peer can't stall a non-blocking lock call during the cooling window.
posixCoolingProbeTimeout = 2 * time.Second
// posixLockWarmup is how long after a (re)start the owner defers would-be
// grants while mounts re-assert their held locks, so it does not double-grant
// a lock its fresh, still-empty state has not yet rebuilt. Must exceed the
// mount keepalive interval and stay below the TTL.
posixLockWarmup = 10 * time.Second
)
// startPosixLockSweeper periodically reaps the locks of leased sessions (mounts)
// that stopped sending keepalives. Sessions that never renew are never reaped, so
// this is inert until mounts run with -posixLock.
func (fs *FilerServer) startPosixLockSweeper() {
fs.posixLockReadyAt.Store(time.Now().UnixNano())
fs.posixLockSweeperStop = make(chan struct{})
go func() {
ticker := time.NewTicker(posixLockSweepInterval)
defer ticker.Stop()
for {
select {
case <-fs.posixLockSweeperStop:
return
case <-ticker.C:
if reaped := fs.posixLocks.ReapExpired(posixLockSessionTTL); len(reaped) > 0 {
glog.V(2).Infof("posix lock: reaped %d expired session(s): %v", len(reaped), reaped)
}
}
}
}()
}
// PosixLock applies one advisory lock operation against the in-memory lock table
// of the inode's owner filer. The owner is resolved from req.Key on the same
// ring the gateway and DLM use; a non-owner filer forwards the request one hop
// (is_moved bounds it), so the owner's table stays the single authority even when
// the caller's ring view is stale. Blocking (SetLkw) is the caller's job — this
// is strictly non-blocking try/release/query.
func (fs *FilerServer) PosixLock(ctx context.Context, req *filer_pb.PosixLockRequest) (*filer_pb.PosixLockResponse, error) {
if req.Key == "" {
return &filer_pb.PosixLockResponse{}, fmt.Errorf("key is required")
}
if req.Lock == nil {
return &filer_pb.PosixLockResponse{}, fmt.Errorf("lock is required")
}
if fs.filer.Dlm != nil {
if owner := fs.filer.Dlm.LockRing.GetPrimary(req.Key); owner != "" && owner != fs.option.Host {
if !req.IsMoved && scopeKeepOnly(ctx) {
return &filer_pb.PosixLockResponse{}, status.Error(codes.PermissionDenied, "scoped PosixLock cannot be forwarded")
}
if err := fs.checkMovedMarker(ctx, req.IsMoved, owner); err != nil {
return &filer_pb.PosixLockResponse{}, err
}
if !req.IsMoved {
forwarded := &filer_pb.PosixLockRequest{
Key: req.Key,
IsMoved: true,
Op: req.Op,
Lock: req.Lock,
Locks: req.Locks,
}
glog.V(4).InfofCtx(ctx, "PosixLock %s op=%v: forwarding to owner %s", req.Key, req.Op, owner)
var resp *filer_pb.PosixLockResponse
err := pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
var e error
resp, e = client.PosixLock(withCallerAuthContext(ctx), forwarded)
return e
})
if err != nil {
return &filer_pb.PosixLockResponse{}, err
}
return resp, nil
}
}
}
principal, lease := posixLockAuthority(ctx)
if principal != "" {
if err := checkScopedPosixLockRanges(req); err != nil {
return &filer_pb.PosixLockResponse{}, err
}
}
lk := posixRangeFromPb(req.Lock)
lk.Principal = principal
session := lk.Session()
resp := &filer_pb.PosixLockResponse{}
switch req.Op {
case filer_pb.PosixLockOp_TRY_LOCK:
// A fresh owner's state may be incomplete (post-restart warm-up, or a ring
// change whose previous owner can't be reached): report a known conflict,
// else defer the grant so the client retries rather than risk a
// double-grant. A deferred grant becomes EAGAIN for non-blocking SetLk and
// a retry for the blocking SetLkw poll — never a spurious grant.
if !req.CoolingProbe {
if c, deferGrant := fs.posixCoolingOrWarmup(ctx, req.Key, lk); c != nil {
resp.HasConflict = true
resp.Conflict = c
break
} else if deferGrant {
break
}
}
if c, granted, err := fs.posixLocks.TryLock(req.Key, lk, lease); err != nil {
// The token expired while the request waited: a grant would end at once.
return &filer_pb.PosixLockResponse{}, status.Error(codes.Unauthenticated, err.Error())
} else if granted {
resp.Granted = true
} else {
resp.HasConflict = true
resp.Conflict = posixRangeToPb(c)
}
case filer_pb.PosixLockOp_UNLOCK:
fs.posixLocks.Unlock(req.Key, lk)
case filer_pb.PosixLockOp_GET_LK:
// A query is best-effort: report a known conflict but never defer.
if !req.CoolingProbe {
if c, _ := fs.posixCoolingOrWarmup(ctx, req.Key, lk); c != nil {
resp.HasConflict = true
resp.Conflict = c
break
}
}
if c, found := fs.posixLocks.GetLk(req.Key, lk); found {
resp.HasConflict = true
resp.Conflict = posixRangeToPb(c)
}
case filer_pb.PosixLockOp_RELEASE_POSIX_OWNER:
fs.posixLocks.ReleasePosixOwner(req.Key, session, lk.Owner)
case filer_pb.PosixLockOp_RELEASE_FLOCK_OWNER:
fs.posixLocks.ReleaseFlockOwner(req.Key, session, lk.Owner)
case filer_pb.PosixLockOp_KEEP_ALIVE:
// A re-assertion carries the mount's held locks on this key so the owner
// can rebuild its in-memory state after an ownership change or restart; a
// bare keepalive just renews the lease. A lock another session now holds
// is reported back as a conflict, so the mount learns it lost it.
if len(req.Locks) > 0 {
held := make([]posixlock.Range, 0, len(req.Locks))
for _, l := range req.Locks {
held = append(held, posixRangeFromPb(l))
}
if conflicts := fs.posixLocks.Reassert(req.Key, session, held, lease); len(conflicts) > 0 {
glog.Warningf("posix reassert %s sid %d: %d lock(s) lost to another session", req.Key, lk.Sid, len(conflicts))
resp.HasConflict = true
resp.Conflict = posixRangeToPb(conflicts[0])
}
} else {
fs.posixLocks.Renew(req.Key, session, lease)
}
default:
return &filer_pb.PosixLockResponse{}, fmt.Errorf("unknown posix lock op %v", req.Op)
}
return resp, nil
}
// posixLockAuthority derives who a PosixLock request acts for. A request the
// scope interceptor admitted for a scoped token acts for that token's verified
// id (jti): it controls only the locks it took, whatever sid or owner it names,
// and each of its leases ends no later than the token's expiry plus the
// verifier's clock leeway. Its leases are held under a fingerprint of its
// grants, so one keepalive renews every lock the session took under the same
// grants, but not those a token reusing the id took under other grants. Any other
// request, tokenless or carrying an unscoped token, acts in the unscoped
// namespace, which never matches a scoped lock.
func posixLockAuthority(ctx context.Context) (principal string, lease posixlock.Lease) {
authority, _ := ctx.Value(scopeWriteAuthorityKey{}).(*scopeWriteAuthority)
if authority == nil || authority.sc == nil {
return "", posixlock.Lease{}
}
sc := authority.sc
return sc.id, posixlock.Lease{TTL: posixLockSessionTTL, NotAfter: sc.exp.Add(sc.leeway), Grant: scopeGrantFingerprint(sc.grants)}
}
// scopeGrantFingerprint digests a token's verified grants, independent of
// their order or repetition. Tokens with equal fingerprints may lock exactly
// the same keys, which is what lets a keepalive under one renew the locks
// taken under the other.
func scopeGrantFingerprint(grants []scopeGrant) string {
entries := make([]string, 0, len(grants))
for _, g := range grants {
// Quoting keeps every entry on one line, so the joined list is unambiguous.
entries = append(entries, strconv.FormatBool(g.readWrite)+" "+strconv.Quote(g.path))
}
slices.Sort(entries)
sum := sha256.Sum256([]byte(strings.Join(slices.Compact(entries), "\n")))
return hex.EncodeToString(sum[:])
}
// checkScopedPosixLockRanges refuses a scoped request whose lock, or any
// re-asserted lock, is not a well-formed read or write range, before any state
// changes.
func checkScopedPosixLockRanges(req *filer_pb.PosixLockRequest) error {
valid := func(l *filer_pb.PosixLockRange) bool {
return (l.GetType() == posixlock.Read || l.GetType() == posixlock.Write) && l.GetStart() <= l.GetEnd()
}
if req.Op == filer_pb.PosixLockOp_TRY_LOCK && !valid(req.Lock) {
return status.Error(codes.InvalidArgument, "malformed lock range")
}
if req.Op == filer_pb.PosixLockOp_KEEP_ALIVE {
for _, l := range req.Locks {
if !valid(l) {
return status.Error(codes.InvalidArgument, "malformed re-asserted lock range")
}
}
}
return nil
}
// posixWarmingUp reports whether this filer is still within posixLockWarmup of
// when it began serving POSIX locks. The zero readyAt (e.g. in tests) is never
// warming up.
func (fs *FilerServer) posixWarmingUp() bool {
readyAt := fs.posixLockReadyAt.Load()
return readyAt != 0 && time.Since(time.Unix(0, readyAt)) < posixLockWarmup
}
// posixCoolingOrWarmup decides whether a fresh owner can trust its local state
// for key before granting. It returns a known blocking lock (conflict != nil),
// or asks the caller to defer the grant (deferGrant) when the state may be
// incomplete and no conflict can be confirmed. It returns (nil, false) when the
// owner is authoritative and should consult its local table.
//
// - Warm-up: just after a (re)start the owner is still rebuilding from
// re-assertions, so only a locally-visible conflict is trustworthy; a
// would-be grant is deferred.
// - Ring change (cooling window): the previous owner may still hold a lock this
// owner hasn't rebuilt. Ask it (marked cooling_probe so it answers locally
// without recursing), under a short deadline so a slow peer can't stall the
// non-blocking lock path. If it is unreachable — typically because it
// crashed, which caused the change — we cannot confirm, so we defer rather
// than risk a double-grant; re-assertion rebuilds this owner before the
// window ends.
func (fs *FilerServer) posixCoolingOrWarmup(ctx context.Context, key string, lk posixlock.Range) (conflict *filer_pb.PosixLockRange, deferGrant bool) {
if fs.posixWarmingUp() {
if c, found := fs.posixLocks.GetLk(key, lk); found {
return posixRangeToPb(c), false
}
return nil, true
}
if fs.filer.Dlm == nil {
return nil, false
}
prior := fs.filer.Dlm.LockRing.PriorOwner(key)
if prior == "" || prior == fs.option.Host {
return nil, false
}
probeCtx, cancel := context.WithTimeout(ctx, posixCoolingProbeTimeout)
defer cancel()
var resp *filer_pb.PosixLockResponse
err := pb.WithFilerClient(false, 0, prior, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
var e error
resp, e = client.PosixLock(fs.peerContext(probeCtx), &filer_pb.PosixLockRequest{
Key: key,
IsMoved: true,
CoolingProbe: true,
Op: filer_pb.PosixLockOp_GET_LK,
Lock: posixRangeToPb(lk),
})
return e
})
if err != nil {
// Cannot confirm — defer rather than risk a double-grant (the prior owner
// likely crashed; re-assertion rebuilds this owner before the window ends).
glog.V(2).InfofCtx(ctx, "posix cooling probe %s -> %s: %v (deferring)", key, prior, err)
return nil, true
}
if resp.GetHasConflict() {
return resp.GetConflict(), false
}
return nil, false
}
func posixRangeFromPb(l *filer_pb.PosixLockRange) posixlock.Range {
return posixlock.Range{
Start: l.GetStart(),
End: l.GetEnd(),
Type: l.GetType(),
Sid: l.GetSid(),
Owner: l.GetOwner(),
Pid: l.GetPid(),
IsFlock: l.GetIsFlock(),
}
}
func posixRangeToPb(r posixlock.Range) *filer_pb.PosixLockRange {
return &filer_pb.PosixLockRange{
Start: r.Start,
End: r.End,
Type: r.Type,
Sid: r.Sid,
Owner: r.Owner,
Pid: r.Pid,
IsFlock: r.IsFlock,
}
}