mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-10-19 12:34:29 +02:00
* filer: free shared chunks when a folder delete drops the last hard link doBatchDeleteFolderMetaAndData skipped chunk collection for every hard-linked child, relying on maybeDeleteHardLinks to retire the shared inode record. When the delete removes the last link the record is gone and nobody else will ever free those chunks. After the link callback runs, check whether the record survived; if it did not, queue the entry's chunks for deletion. * filer: free orphaned hard-link chunks in the replayed delete sweep The subtree sweep on a replayed directory delete skipped every hard-linked child, so a link that was the inode's last owner leaked its shared chunks. Check the inode record after the store delete; when it is gone, queue the child's chunks like any other swept entry. * filer: mirror remote-object cleanup in the replayed delete sweep Children a lagging peer alone still holds under a replayed directory delete were dropped with plain store deletes: their remote objects leaked and lazy remote fetches could resurrect them. The sweep now records event-stamped tombstones and deletes swept non-directory children through maybeDeleteFromRemoteIfUnchanged, which carries the same stat guard the write-back daemon's processDeleteEvent applies plus a modification-time check — a delayed replay cannot erase an object another writer replaced, even a same-size one. A failed remote delete fails the replay so the event is retried instead of orphaning the object. The directory's own tombstone comes from the event pipeline at the event timestamp and covers the subtree. Metadata-only deletes and cross-cluster events keep the origin's semantics. * filerstore: return real errors from KvGet on MongoDB, ArangoDB, Elastic These stores mapped every lookup failure to ErrKvNotFound, so a database error looked identical to a missing key: hard-link records could appear gone while links still owned their chunks, and path timestamp reads could treat committed state as absent. Return the underlying error and keep ErrKvNotFound for genuinely missing keys. * filer: bind remote-object deletes to the observed object version A guarded stat-then-delete still lets a replacement landing between the two requests go down with the deleted object. Add an optional conditional-delete operation to remote storage clients — S3 If-Match on the live ETag, GCS generation match, Azure IfMatch — and use it everywhere a delete is guarded by a stored stamp: the write-back daemon's delete, rename-source, and pending-rename paths, and the replayed-delete sweep. Backends without it keep the guarded stat-then-delete. * filer: restamp the remote entry after a metadata-only remote update Changing Content-Encoding rewrites the object in place on S3 and advances its LastModified, while the recorded stamp keeps the old mtime. A version-checked delete would then mistake the object for a replacement and keep it forever. Re-stat after UpdateFileMetadata so the saved stamp describes the live object. * filer: mirror the remote-delete ownership checks in the replayed sweep The sweep deleted swept children's remote objects on the listing's snapshot alone. Two gaps: a remote-only entry that took the path since — one a commit record may not cover, such as a lazy fetch materialized from the remote — reads the object as its only copy, and an entry removed while its rename copy was pending leaves the object at the source key orphaned. The per-child delete now runs under the child's entry lock with the commit-time check repeated, keeps a remote-only entry that holds the path, and releases the pending rename's source under the same ownership and stamp conditions the write-back daemon's releasePendingSource applies. * remote.sync: restamp only the object the metadata update touched The live stat after UpdateFileMetadata was saved unconditionally, so a replacement written between the update and the stat stamped the entry with an object it never described — and a later delete would then pass the freshness guard on the replacement's data. The restamp now requires the live object to still match the stored stamp on size and ETag; a different object keeps the old stamp, which the delete guard reads as replaced and keeps. * filer: skip unbudgeted reader-cache test on 32-bit TestReaderCacheUnboundedWithoutBudget proves the reader cache has no implicit memory budget by keeping 96 concurrent 4 MiB downloads in flight (>256 MiB). On linux/386 the weed/filer test binary already runs near the 4 GiB address-space limit, so the burst reliably crashes it with "out of memory" mid-suite. * filer: bail out of a swept child lock instead of waiting on it Replay already holds the event's path locks when the sweep reaches a descendant. A local rename can hold that descendant while waiting on one of the replayed paths, so blocking on the child lock deadlocks both. The sweep now tries the lock and reports ErrLockContended — transient, so the replication retry replays the event once the local write settles. * remote: report the stamp a metadata update produced A metadata write can rewrite the object it touches — S3 changes Content-Encoding through an in-place copy, which can mint a new ETag — so restamping from a fresh stat can reject the very object the update produced, or describe a replacement that landed in between. UpdateFileMetadata now returns the RemoteEntry of the object it wrote (S3 from the copy result, GCS from the update attributes, Azure from a post-update stat); nil means the object was untouched and callers keep the stored stamp. * remote: restamp Azure from the metadata write's own etag
287 lines
7.6 KiB
Go
287 lines
7.6 KiB
Go
package util
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"net"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
var RetryWaitTime = 6 * time.Second
|
|
|
|
// ErrLockContended marks a lock acquisition abandoned instead of waited on —
|
|
// the caller already holds other locks and cannot queue without inverting
|
|
// their order. The holder's write settles the contested state, so callers
|
|
// treat it as transient and retry.
|
|
var ErrLockContended = errors.New("a local write holds the entry lock")
|
|
|
|
// transientErrorMessages are substrings of failures that a later attempt is
|
|
// likely to get past: connection resets, timeouts, and the throttling or
|
|
// overload replies S3 and gRPC hand back. Cloud SDKs bury the underlying net
|
|
// error in an opaque wrapper with no Unwrap, so the message is often all
|
|
// that is left to match on. Compared case-insensitively, so entries are lower
|
|
// case: the same condition reaches different layers capitalized differently
|
|
// (a volume server relays its idle timeout as "I/O timeout" inside JSON).
|
|
var transientErrorMessages = []string{
|
|
"transport",
|
|
"connection reset",
|
|
"connection refused",
|
|
"broken pipe",
|
|
"unexpected eof",
|
|
"i/o timeout",
|
|
"tls handshake timeout",
|
|
"no such host",
|
|
"no route to host",
|
|
"network is unreachable",
|
|
"client.timeout",
|
|
"requesterror",
|
|
"requesttimeout",
|
|
"slowdown",
|
|
"throttling",
|
|
"ratelimitexceeded",
|
|
"rate limit",
|
|
"too many requests",
|
|
"internalerror",
|
|
"resourceexhausted",
|
|
"unavailable",
|
|
}
|
|
|
|
// IsTransientErrorMessage reports whether an error message describes a network
|
|
// or service condition worth retrying. Callers holding an error should use
|
|
// IsTransientError; this is for paths that only carry the text, such as the
|
|
// per-file status strings in a batch delete response.
|
|
func IsTransientErrorMessage(msg string) bool {
|
|
lower := strings.ToLower(msg)
|
|
for _, transient := range transientErrorMessages {
|
|
if strings.Contains(lower, transient) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// ServerStatus returns the status a gRPC server sent, when the error chain
|
|
// still carries one. Unlike status.FromError it keeps the server's own message
|
|
// instead of the whole wrapped string: callers routinely format a path the
|
|
// client chose into their wrapper, so a classifier that matches substrings has
|
|
// to read what the server said and not what the caller added around it.
|
|
func ServerStatus(err error) (*status.Status, bool) {
|
|
var carrier interface{ GRPCStatus() *status.Status }
|
|
if !errors.As(err, &carrier) {
|
|
return nil, false
|
|
}
|
|
st := carrier.GRPCStatus()
|
|
return st, st != nil
|
|
}
|
|
|
|
// IsTransientError reports whether err is a network or service condition worth
|
|
// retrying. A cancelled or expired context never is: the caller is already gone.
|
|
func IsTransientError(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
|
return false
|
|
}
|
|
if errors.Is(err, ErrLockContended) {
|
|
return true
|
|
}
|
|
if errors.Is(err, io.ErrUnexpectedEOF) ||
|
|
errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.ECONNABORTED) ||
|
|
errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.EPIPE) ||
|
|
errors.Is(err, syscall.ETIMEDOUT) {
|
|
return true
|
|
}
|
|
var netErr net.Error
|
|
if errors.As(err, &netErr) && netErr.Timeout() {
|
|
return true
|
|
}
|
|
if st, ok := ServerStatus(err); ok {
|
|
if st.Code() == codes.Canceled {
|
|
return strings.Contains(st.Message(), "the client connection is closing")
|
|
}
|
|
return st.Code() == codes.Unavailable || st.Code() == codes.ResourceExhausted ||
|
|
IsTransientErrorMessage(st.Message())
|
|
}
|
|
return IsTransientErrorMessage(err.Error())
|
|
}
|
|
|
|
func Retry(name string, job func() error) (err error) {
|
|
waitTime := time.Second
|
|
hasErr := false
|
|
for waitTime < RetryWaitTime {
|
|
err = job()
|
|
if err == nil {
|
|
if hasErr {
|
|
glog.V(0).Infof("retry %s successfully", name)
|
|
}
|
|
waitTime = time.Second
|
|
break
|
|
}
|
|
if IsTransientError(err) {
|
|
hasErr = true
|
|
glog.V(0).Infof("retry %s: err: %v", name, err)
|
|
} else {
|
|
break
|
|
}
|
|
time.Sleep(waitTime)
|
|
waitTime += waitTime / 2
|
|
}
|
|
return err
|
|
}
|
|
|
|
func MultiRetry(name string, errList []string, job func() error) (err error) {
|
|
waitTime := time.Second
|
|
hasErr := false
|
|
for waitTime < RetryWaitTime {
|
|
err = job()
|
|
if err == nil {
|
|
if hasErr {
|
|
glog.V(0).Infof("retry %s successfully", name)
|
|
}
|
|
waitTime = time.Second
|
|
break
|
|
}
|
|
if containErr(err.Error(), errList) {
|
|
hasErr = true
|
|
glog.V(0).Infof("retry %s: err: %v", name, err)
|
|
} else {
|
|
break
|
|
}
|
|
time.Sleep(waitTime)
|
|
waitTime += waitTime / 2
|
|
}
|
|
return err
|
|
}
|
|
|
|
// RetryOnError retries job with the same bounded backoff as MultiRetry, but
|
|
// decides retriability with a predicate instead of an error-substring list.
|
|
func RetryOnError(name string, shouldRetry func(error) bool, job func() error) (err error) {
|
|
waitTime := time.Second
|
|
hasErr := false
|
|
for waitTime < RetryWaitTime {
|
|
err = job()
|
|
if err == nil {
|
|
if hasErr {
|
|
glog.V(0).Infof("retry %s successfully", name)
|
|
}
|
|
break
|
|
}
|
|
if shouldRetry(err) {
|
|
hasErr = true
|
|
glog.V(0).Infof("retry %s: err: %v", name, err)
|
|
} else {
|
|
break
|
|
}
|
|
time.Sleep(waitTime)
|
|
waitTime += waitTime / 2
|
|
}
|
|
return err
|
|
}
|
|
|
|
// RetryUntil retries until the job returns no error or onErrFn returns false
|
|
func RetryUntil(name string, job func() error, onErrFn func(err error) (shouldContinue bool)) error {
|
|
waitTime := time.Second
|
|
for {
|
|
err := job()
|
|
if err == nil {
|
|
waitTime = time.Second
|
|
return nil
|
|
}
|
|
if onErrFn(err) {
|
|
if strings.Contains(err.Error(), "transport") || strings.Contains(err.Error(), "ResourceExhausted") || strings.Contains(err.Error(), "Unavailable") {
|
|
glog.V(0).Infof("retry %s: err: %v", name, err)
|
|
}
|
|
time.Sleep(waitTime)
|
|
if waitTime < RetryWaitTime {
|
|
waitTime += waitTime / 2
|
|
}
|
|
continue
|
|
} else {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
// RetryWithBackoff retries an operation on codes.Unavailable errors with exponential
|
|
// backoff, respecting context cancellation and a maximum retry duration.
|
|
// Returns nil on success, ctx.Err() on context cancellation, or the last error
|
|
// when maxDuration is exceeded or a non-retriable error occurs.
|
|
func RetryWithBackoff(ctx context.Context, name string, maxDuration time.Duration, shouldRetry func(error) bool, operation func() error) error {
|
|
waitTime := time.Second
|
|
maxWaitTime := RetryWaitTime
|
|
deadline := time.Now().Add(maxDuration)
|
|
var lastErr error
|
|
for {
|
|
if ctx.Err() != nil {
|
|
return ctx.Err()
|
|
}
|
|
if time.Until(deadline) <= 0 {
|
|
if lastErr != nil {
|
|
glog.V(0).Infof("retry %s: giving up after %v: %v", name, maxDuration, lastErr)
|
|
return lastErr
|
|
}
|
|
}
|
|
err := operation()
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
lastErr = err
|
|
if !shouldRetry(err) {
|
|
return err
|
|
}
|
|
remaining := time.Until(deadline)
|
|
if remaining <= 0 {
|
|
glog.V(0).Infof("retry %s: giving up after %v: %v", name, maxDuration, err)
|
|
return err
|
|
}
|
|
sleepTime := waitTime
|
|
if sleepTime > maxWaitTime {
|
|
sleepTime = maxWaitTime
|
|
}
|
|
if sleepTime > remaining {
|
|
sleepTime = remaining
|
|
}
|
|
glog.V(1).Infof("retry %s: retrying in %v: %v", name, sleepTime, err)
|
|
timer := time.NewTimer(sleepTime)
|
|
select {
|
|
case <-ctx.Done():
|
|
if !timer.Stop() {
|
|
<-timer.C
|
|
}
|
|
return ctx.Err()
|
|
case <-timer.C:
|
|
}
|
|
waitTime += waitTime / 2
|
|
if waitTime > maxWaitTime {
|
|
waitTime = maxWaitTime
|
|
}
|
|
}
|
|
}
|
|
|
|
// Nvl return the first non-empty string
|
|
func Nvl(values ...string) string {
|
|
for _, s := range values {
|
|
if s != "" {
|
|
return s
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func containErr(err string, errList []string) bool {
|
|
for _, e := range errList {
|
|
if strings.Contains(err, e) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|