package command import ( "errors" "fmt" "hash/fnv" "io" "regexp" "sort" "sync" "sync/atomic" "time" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" util_http "github.com/seaweedfs/seaweedfs/weed/util/http" ) // errSourceGone marks an upload whose source data no longer exists in this // cluster: a volume server answered 404 for one of the entry's chunks (read // with readDeleted=true, so not even a deleted needle is left), the filer // still holds the entry as the event described it, and that held for // sourceGoneGrace over sourceGoneMinAnswers attempts in a row. Retrying // cannot produce the bytes: the write-back reports the path once and moves // past the event instead of holding the directory's offset on it forever. // A volume lost with its disk (a server restored from a metadata-only // backup) leaves entries like this behind. var errSourceGone = errors.New("source data gone") // A 404 can also come from a volume server that has not loaded the volume // yet, or from a stale location right after a move; neither lasts. Only a // 404 that persists this long, over this many attempts with nothing else in // between, counts as gone. A volume the master cannot locate at all is also // what a volume server that is down looks like, so it never counts. var ( sourceGoneGrace = 5 * time.Minute sourceGoneMinAnswers = 3 ) // sourceGoneRemembered bounds how many paths a process keeps, both those with // sightings in a row and those found gone. const sourceGoneRemembered = 10000 // sourceGoneCount is how many entries this process left unwritten because // their source data was gone. var sourceGoneCount atomic.Int64 // sourceReadRecorder keeps the first error the upload body's reader returned. // Remote clients wrap a body read failure in their own errors (the AWS SDK's // RequestError has no Unwrap), so the write error cannot say whether the // source or the remote failed; the recorder can, and a 404 from the remote // itself never reaches it. type sourceReadRecorder struct { r io.Reader mu sync.Mutex err error } func (s *sourceReadRecorder) Read(p []byte) (int, error) { n, err := s.r.Read(p) s.record(err) return n, err } // sourceReadAtRecorder keeps an io.ReaderAt + io.Seeker body one: an S3 // uploader reads the parts of such a body in place and in parallel, where a // plain io.Reader is copied into a buffer per part. type sourceReadAtRecorder struct { *sourceReadRecorder ra io.ReaderAt sk io.Seeker } func (s *sourceReadAtRecorder) ReadAt(p []byte, off int64) (int, error) { n, err := s.ra.ReadAt(p, off) s.record(err) return n, err } func (s *sourceReadAtRecorder) Seek(offset int64, whence int) (int64, error) { return s.sk.Seek(offset, whence) } // newSourceReadRecorder wraps an upload body, keeping the shape the remote // client sees. func newSourceReadRecorder(r io.Reader) (io.Reader, *sourceReadRecorder) { rec := &sourceReadRecorder{r: r} ra, okAt := r.(io.ReaderAt) sk, okSeek := r.(io.Seeker) if okAt && okSeek { return &sourceReadAtRecorder{sourceReadRecorder: rec, ra: ra, sk: sk}, rec } return rec, rec } func (s *sourceReadRecorder) record(err error) { if err == nil || err == io.EOF { return } s.mu.Lock() if s.err == nil { s.err = err } s.mu.Unlock() } func (s *sourceReadRecorder) readErr() error { if s == nil { return nil } s.mu.Lock() defer s.mu.Unlock() return s.err } // isSourceGone reports whether a read of the entry's own chunks says the data // may be gone: every location of a chunk answered 404 // (util_http.NotFoundEverywhere). Only errors from the source side are passed // here: the upload body's reader or the chunk view resolution. func isSourceGone(sourceErr error) bool { return errors.Is(sourceErr, util_http.ErrNotFound) } var fidInURL = regexp.MustCompile(`/(\d+,[0-9a-fA-F]+)(?:[?:/\s"]|$)`) // goneFid names the chunk the sighting was for, for the log: the file id in // the URL the error carries, else the entry's first chunk and how many more // it has. func goneFid(sourceErr error, entry *filer_pb.Entry) string { if m := fidInURL.FindStringSubmatch(sourceErr.Error()); m != nil { return m[1] } chunks := entry.GetChunks() switch len(chunks) { case 0: return "unknown" case 1: return chunks[0].GetFileIdString() } return fmt.Sprintf("%s and %d more", chunks[0].GetFileIdString(), len(chunks)-1) } // chunkSetKey identifies the content a sighting is about: the entry's chunk // file ids, in any order. The chunk that fails first can differ from one // attempt to the next (an uploader reads parts in parallel), so sightings in // a row are counted per content, not per failing chunk. func chunkSetKey(entry *filer_pb.Entry) string { fids := make([]string, 0, len(entry.GetChunks())) for _, c := range entry.GetChunks() { fids = append(fids, c.GetFileIdString()) } sort.Strings(fids) h := fnv.New64a() for _, f := range fids { h.Write([]byte(f)) h.Write([]byte{0}) } return fmt.Sprintf("%d:%016x", len(fids), h.Sum64()) } type goneSighting struct { key string first time.Time last time.Time answers int } // sourceGoneTracker holds, per path, the sightings seen in a row. Any other // outcome for the path forgets them, so the grace starts again. A path found // gone is remembered with its content key: a later event of the same entry (a // metadata update, a replay) is skipped at once instead of holding the // directory's offset for another grace. type sourceGoneTracker struct { mu sync.Mutex seen map[string]*goneSighting gone map[string]string } func newSourceGoneTracker() *sourceGoneTracker { return &sourceGoneTracker{seen: map[string]*goneSighting{}, gone: map[string]string{}} } var sourceGone = newSourceGoneTracker() // observe records a sighting for path under key (chunkSetKey) and reports // whether it has now held for sourceGoneGrace over sourceGoneMinAnswers // attempts, and whether this call is the one that found it gone (a path // already known gone reports gone, not new). func (t *sourceGoneTracker) observe(path, key string, now time.Time) (gone, isNew bool) { t.mu.Lock() defer t.mu.Unlock() if g, ok := t.gone[path]; ok && g == key { return true, false } s := t.seen[path] if s == nil || s.key != key { if s == nil && len(t.seen) >= sourceGoneRemembered { t.pruneSeen(now) } s = &goneSighting{key: key, first: now} t.seen[path] = s } s.answers++ s.last = now if s.answers >= sourceGoneMinAnswers && now.Sub(s.first) >= sourceGoneGrace { delete(t.seen, path) if len(t.gone) >= sourceGoneRemembered { t.gone = map[string]string{} } t.gone[path] = key return true, true } return false, false } // pruneSeen drops sightings of paths no attempt has reached for longer than // the grace (the entry was deleted, or the subscription moved past it), and // every sighting if the map is still full. Dropping one only restarts that // path's grace. func (t *sourceGoneTracker) pruneSeen(now time.Time) { stale := 2 * sourceGoneGrace for p, s := range t.seen { if now.Sub(s.last) > stale { delete(t.seen, p) } } if len(t.seen) >= sourceGoneRemembered { t.seen = map[string]*goneSighting{} } } // forget drops path's sightings, and its gone mark: the entry was written // back, superseded, or failed some other way. func (t *sourceGoneTracker) forget(path string) { t.mu.Lock() delete(t.seen, path) delete(t.gone, path) t.mu.Unlock() }