package command import ( "bytes" "errors" "fmt" "io" "testing" "time" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/remote_pb" "github.com/seaweedfs/seaweedfs/weed/util" util_http "github.com/seaweedfs/seaweedfs/weed/util/http" "google.golang.org/protobuf/proto" ) func withSourceGone(t *testing.T, grace time.Duration, minAnswers int) { t.Helper() prevGrace, prevMin, prevWait := sourceGoneGrace, sourceGoneMinAnswers, util.RetryWaitTime sourceGoneGrace, sourceGoneMinAnswers = grace, minAnswers // one pass of the chunk fetch's and the upload's backoff loops util.RetryWaitTime = 1100 * time.Millisecond sourceGone = newSourceGoneTracker() sourceGoneCount.Store(0) t.Cleanup(func() { sourceGoneGrace, sourceGoneMinAnswers, util.RetryWaitTime = prevGrace, prevMin, prevWait sourceGone = newSourceGoneTracker() sourceGoneCount.Store(0) }) } // TestRetriedWriteFileSourceGone: an entry the filer still holds whose chunk // the volume server answers 404 for (a volume lost with its disk) ends in // errSourceGone once the 404 has held, instead of failing its event forever // and holding the directory's offset behind it. The encrypted read path // (GetAuthenticated) must report the 404 as ErrNotFound too: production // cells encrypt volume data. func TestRetriedWriteFileSourceGone(t *testing.T) { const dir = "/buckets/garden--blobs/camera" for _, tc := range []struct { name string chunk *filer_pb.FileChunk }{ {"plain chunk", &filer_pb.FileChunk{FileId: "79,2cb9d2dd0ea2", ETag: "e1", Size: 100}}, {"encrypted chunk", &filer_pb.FileChunk{FileId: "79,2cb9d2dd0ea2", ETag: "e1", Size: 100, CipherKey: make([]byte, 32)}}, } { t.Run(tc.name, func(t *testing.T) { withSourceGone(t, 0, 3) entry := entryWith("snapshot.jpg", nil, tc.chunk) entry.Attributes.FileSize = 100 filerClient, done := servingFilerClient(entry, map[string][]byte{}) // the chunk is gone defer done() dest := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/camera/snapshot.jpg"} for call := 1; call <= 2; call++ { _, err := retriedWriteFile(&captureRemote{}, filerClient, dir, entry, dest) if err == nil || errors.Is(err, errSourceGone) || errors.Is(err, errSuperseded) { t.Fatalf("call %d: err = %v, want the read failure itself while the 404 is young", call, err) } } _, err := retriedWriteFile(&captureRemote{}, filerClient, dir, entry, dest) if !errors.Is(err, errSourceGone) { t.Fatalf("third call: err = %v, want errSourceGone", err) } if got := sourceGoneCount.Load(); got != 1 { t.Errorf("counted %d gone entries, want 1", got) } want := fmt.Sprintf("%s/snapshot.jpg (fid 79,2cb9d2dd0ea2)", dir) if msg := err.Error(); len(msg) < len(want) || msg[:len(want)] != want { t.Errorf("err = %q, want it to start with %q", msg, want) } }) } } // TestRetriedWriteFileRemoteNotFoundIsNeverGone: only the source's own chunk // reads decide. A remote that answers 404 (or anything else) to the upload, // while the chunks read fine, is retried as before: skipping it would drop // data that exists. // TestRetriedWriteFileSourceGoneAcrossChunks: an uploader reads the parts of // a ReaderAt body in parallel, so which lost chunk fails first changes from // one attempt to the next. The sightings are of the same content and must // add up, or a large file missing several chunks holds the offset forever. func TestRetriedWriteFileSourceGoneAcrossChunks(t *testing.T) { withSourceGone(t, 0, 3) entry := entryWith("big.bin", nil, &filer_pb.FileChunk{FileId: "7,01", ETag: "e1", Offset: 0, Size: 4}, &filer_pb.FileChunk{FileId: "8,02", ETag: "e2", Offset: 4, Size: 4}) entry.Attributes.FileSize = 8 filerClient, done := servingFilerClient(entry, map[string][]byte{}) // both chunks lost defer done() dest := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/big.bin"} remote := &partReadingRemote{} for call := 1; call <= 3; call++ { _, err := retriedWriteFile(remote, filerClient, "/buckets/b", entry, dest) if call < 3 && errors.Is(err, errSourceGone) { t.Fatalf("call %d: gone before three sightings", call) } if call == 3 && !errors.Is(err, errSourceGone) { t.Fatalf("call 3: err = %v, want errSourceGone after three sightings of the same entry", err) } } if len(remote.offsets) < 2 || remote.offsets[0] == remote.offsets[1] { t.Fatalf("precondition: the attempts read different parts, got offsets %v", remote.offsets) } } // partReadingRemote reads one 4-byte part of the body per write, the next // part on each call, as parallel part readers do in no fixed order. type partReadingRemote struct { recordingRemote offsets []int64 } func (r *partReadingRemote) WriteFile(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry, reader io.Reader) (*filer_pb.RemoteEntry, error) { ra, ok := reader.(io.ReaderAt) if !ok { return nil, errors.New("body is not a ReaderAt") } off := int64(len(r.offsets)%2) * 4 r.offsets = append(r.offsets, off) if _, err := ra.ReadAt(make([]byte, 4), off); err != nil { return nil, fmt.Errorf("RequestError: send request failed\ncaused by: %v", err) } return r.recordingRemote.WriteFile(loc, entry, reader) } func TestRetriedWriteFileRemoteNotFoundIsNeverGone(t *testing.T) { withSourceGone(t, 0, 1) const dir = "/buckets/ingest" entry := entryWith("lease.json", nil, chunk("3,01", "e1")) filerClient := &stubFilerClient{entry: entryWith(entry.Name, nil, chunk("3,01", "e1"))} dest := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "tier", Path: "/lease.json"} remoteErr := fmt.Errorf("https://s3.example.com/tier/lease.json: 404 Not Found: %w", util_http.ErrNotFound) for call := 1; call <= 3; call++ { _, err := retriedWriteFile(&failingRemote{err: remoteErr}, filerClient, dir, entry, dest) if err == nil || errors.Is(err, errSourceGone) { t.Fatalf("call %d: err = %v, want the remote's failure, never errSourceGone", call, err) } } if got := sourceGoneCount.Load(); got != 0 { t.Errorf("counted %d gone entries, want 0", got) } } // TestSourceGoneTrackerGrace: a sighting counts as gone only after both the // grace and the answer count, for the same chunk, with nothing else in // between; a gone path is then skipped at once until something else happens. func TestSourceGoneTrackerGrace(t *testing.T) { withSourceGone(t, 5*time.Minute, 3) t0 := time.Unix(1_800_000_000, 0) tr := newSourceGoneTracker() observe := func(path, key string, at time.Time) bool { gone, _ := tr.observe(path, key, at) return gone } if observe("/a", "1,01", t0) || observe("/a", "1,01", t0.Add(time.Minute)) || observe("/a", "1,01", t0.Add(2*time.Minute)) { t.Fatal("gone before the grace ended") } if !observe("/a", "1,01", t0.Add(5*time.Minute)) { t.Fatal("not gone after the grace and three answers") } // a later event of the same gone entry is skipped at once if !observe("/a", "1,01", t0.Add(6*time.Minute)) { t.Fatal("a known-gone entry waits for another grace") } // written back or failed otherwise since: the grace starts again tr.forget("/a") if observe("/a", "1,01", t0.Add(7*time.Minute)) { t.Fatal("gone on the first answer after forget") } // an unknown path never matches the empty fid of a chunkless entry if observe("/c", "", t0) { t.Fatal("a first sighting with an empty fid counted as gone") } // many answers inside the grace are not enough for i := 0; i < 10; i++ { if observe("/b", "1,02", t0.Add(time.Duration(i)*time.Second)) { t.Fatalf("answer %d: gone inside the grace", i) } } tr.forget("/b") if observe("/b", "1,02", t0.Add(6*time.Minute)) || observe("/b", "1,02", t0.Add(7*time.Minute)) || observe("/b", "1,02", t0.Add(8*time.Minute)) { t.Fatal("gone without a full grace after forget") } // another chunk of the same path starts again too if observe("/b", "1,03", t0.Add(20*time.Minute)) { t.Fatal("gone on a new chunk's first answer") } } // TestSourceGoneTrackerCountsOnce: a path is new-gone once; replayed events // of it are skipped without another log line or count. func TestSourceGoneTrackerCountsOnce(t *testing.T) { withSourceGone(t, 5*time.Minute, 3) t0 := time.Unix(1_800_000_000, 0) entry := entryWith("x.jpg", nil, chunk("79,01", "e1")) tr := newSourceGoneTracker() key := chunkSetKey(entry) for i, at := range []time.Duration{0, time.Minute, 5 * time.Minute} { gone, isNew := tr.observe("/x", key, t0.Add(at)) if want := i == 2; gone != want || isNew != want { t.Fatalf("answer %d: gone=%v new=%v, want %v %v", i, gone, isNew, want, want) } } if gone, isNew := tr.observe("/x", key, t0.Add(6*time.Minute)); !gone || isNew { t.Errorf("a replay of a gone path: gone=%v new=%v, want gone and not new", gone, isNew) } } // TestIsSourceGone: only a 404 from every location of a chunk is a sighting. func TestIsSourceGone(t *testing.T) { for _, tc := range []struct { err error want bool }{ {fmt.Errorf("http://v:8080/79,2cb9: 404 Not Found: %w", util_http.ErrNotFound), true}, // a volume the master cannot locate: a volume server that is down // looks the same {errors.New("failed to locate 79,2cb9d2dd0ea2"), false}, // a 404 on one replica while another failed otherwise {util_http.NotFoundEverywhere(fmt.Errorf("a: %w", util_http.ErrNotFound), errors.New("b: 503 Service Unavailable")), false}, {errors.New("http://v:8080/79,2cb9: 500 Internal Server Error"), false}, {errors.New("read tcp: connection reset by peer"), false}, {nil, false}, } { if got := isSourceGone(tc.err); got != tc.want { t.Errorf("isSourceGone(%v) = %v, want %v", tc.err, got, tc.want) } } } // TestSourceReadRecorderKeepsReaderAt: the recorder must not hide a // ReaderAt + Seeker body, or an S3 uploader buffers every part in memory. func TestSourceReadRecorderKeepsReaderAt(t *testing.T) { body, rec := newSourceReadRecorder(io.NewSectionReader(goneChunkReaderAt{}, 0, 10)) ra, okAt := body.(io.ReaderAt) _, okSeek := body.(io.Seeker) if !okAt || !okSeek { t.Fatalf("body %T: ReaderAt %v, Seeker %v; want both", body, okAt, okSeek) } if _, err := ra.ReadAt(make([]byte, 4), 0); err == nil { t.Fatal("ReadAt succeeded") } if !errors.Is(rec.readErr(), util_http.ErrNotFound) { t.Errorf("recorded %v, want the ReadAt failure", rec.readErr()) } if _, ok := mustReader(newSourceReadRecorder(bytes.NewBufferString("x"))).(io.ReaderAt); ok { t.Error("a plain reader gained ReadAt") } } type goneChunkReaderAt struct{} func (goneChunkReaderAt) ReadAt([]byte, int64) (int, error) { return 0, fmt.Errorf("http://v:8080/79,2cb9: 404 Not Found: %w", util_http.ErrNotFound) } func mustReader(r io.Reader, _ *sourceReadRecorder) io.Reader { return r } // bodyReadingRemote reads the upload body before recording the write, as a // real remote does; a body read failure fails the write. type bodyReadingRemote struct{ *recordingRemote } func (r bodyReadingRemote) WriteFile(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry, reader io.Reader) (*filer_pb.RemoteEntry, error) { if _, err := io.ReadAll(reader); err != nil { return nil, fmt.Errorf("RequestError: send request failed\ncaused by: %v", err) } return r.recordingRemote.WriteFile(loc, entry, reader) } // TestRenameOfGoneEntryKeepsTheOldKey: a written-back entry renamed after its // local chunks were lost still has its content under the old key. The event // is acknowledged as gone, and the old key is not deleted: it is the only // copy left. With the chunks present, the old key goes once the new one is // written. func TestRenameOfGoneEntryKeepsTheOldKey(t *testing.T) { const mountedDir = "/buckets" mountLoc := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/"} oldKey := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/b/src/photo.jpg"} newKey := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/b/dst/photo.jpg"} event := func(stamped bool) (*filer_pb.Entry, *filer_pb.SubscribeMetadataResponse) { newEntry := entryWith("photo.jpg", nil, &filer_pb.FileChunk{FileId: "79,2cb9d2dd0ea2", ETag: "e1", Size: 4}) newEntry.Attributes.FileSize = 4 var stamp *filer_pb.RemoteEntry if stamped { stamp = &filer_pb.RemoteEntry{StorageName: "bunny", RemoteETag: "etag", RemoteSize: 4, RemoteMtime: 1786096669} } oldEntry := entryWith("photo.jpg", stamp, &filer_pb.FileChunk{FileId: "79,2cb9d2dd0ea2", ETag: "e1", Size: 4}) return newEntry, &filer_pb.SubscribeMetadataResponse{ Directory: "/buckets/b/src", EventNotification: &filer_pb.EventNotification{ OldEntry: oldEntry, NewParentPath: "/buckets/b/dst", NewEntry: newEntry, }, } } t.Run("chunks gone", func(t *testing.T) { withSourceGone(t, 0, 1) newEntry, resp := event(true) filerClient, done := servingFilerClient(newEntry, map[string][]byte{}) defer done() remote := bodyReadingRemote{&recordingRemote{}} if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil { t.Fatalf("err = %v, want nil: the gone entry is acknowledged", err) } if len(remote.deletes) != 0 { t.Errorf("deleted %+v; the old key holds the only copy", remote.deletes) } if len(remote.writes) != 0 { t.Errorf("wrote %+v, want nothing", remote.writes) } if got := sourceGoneCount.Load(); got != 1 { t.Errorf("counted %d gone entries, want 1", got) } }) t.Run("chunks gone, old entry unstamped", func(t *testing.T) { // the upload's stamp was refused by the rename in between: the old // key still holds the only copy withSourceGone(t, 0, 1) newEntry, resp := event(false) filerClient, done := servingFilerClient(newEntry, map[string][]byte{}) defer done() remote := bodyReadingRemote{&recordingRemote{}} if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil { t.Fatalf("err = %v, want nil: the gone entry is acknowledged", err) } if len(remote.deletes) != 0 { t.Errorf("deletes = %+v; the old key holds the only copy", remote.deletes) } }) t.Run("chunks present", func(t *testing.T) { withSourceGone(t, 0, 1) newEntry, resp := event(true) filerClient, done := servingFilerClient(newEntry, map[string][]byte{"79,2cb9d2dd0ea2": []byte("jpeg")}) defer done() remote := bodyReadingRemote{&recordingRemote{}} if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil { t.Fatalf("err = %v", err) } if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], newKey) { t.Errorf("writes = %+v, want the new key", remote.writes) } if len(remote.deletes) != 1 || !proto.Equal(remote.deletes[0], oldKey) { t.Errorf("deletes = %+v, want the old key once the new one is written", remote.deletes) } }) }