package weed_server import ( "context" "errors" "fmt" "net" "os" "strings" "testing" "time" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/storage/needle" "github.com/seaweedfs/seaweedfs/weed/util" ) func TestScopeRetainsDataKeepsOnlyStoredManifests(t *testing.T) { manifest := &filer_pb.FileChunk{FileId: "1,0a0000c0de", Offset: 0, Size: 20, IsChunkManifest: true, ModifiedTsNs: 2} stored := &filer_pb.Entry{Chunks: []*filer_pb.FileChunk{ manifest, {FileId: "3,0300005eed", Offset: 20, Size: 10}, }} nested := &filer_pb.FileChunk{FileId: "1,0b0000c0de", Offset: 10, Size: 10, IsChunkManifest: true} held := []*filer_pb.FileChunk{ {FileId: "3,0100005eed", Offset: 0, Size: 10}, {FileId: "3,0200005eed", Offset: 10, Size: 10}, nested, } reads := 0 readHeld := func(manifests []*filer_pb.FileChunk) ([]*filer_pb.FileChunk, error) { reads++ if len(manifests) != 1 || !scopeSameChunk(manifests[0], manifest) { t.Fatalf("read manifests %v, want the stored one", manifests) } return held, nil } proven := func(fid string) bool { return strings.HasPrefix(fid, "4,") } with := func(chunks ...*filer_pb.FileChunk) *filer_pb.Entry { return &filer_pb.Entry{Chunks: chunks} } kept := proto.Clone(manifest).(*filer_pb.FileChunk) resized := proto.Clone(manifest).(*filer_pb.FileChunk) resized.Size = 30 structured := proto.Clone(manifest).(*filer_pb.FileChunk) filer_pb.BeforeEntrySerialization([]*filer_pb.FileChunk{structured}) newChunk := &filer_pb.FileChunk{FileId: "4,0100005eed", Offset: 30, Size: 10} for _, tc := range []struct { name string requested *filer_pb.Entry admission string // empty when admitted locked string // empty when admitted keeps bool // the request keeps the stored manifest, which is not read }{ {name: "stored manifest kept with a new chunk", requested: with(kept, stored.Chunks[1], newChunk), keeps: true}, {name: "stored manifest kept by structured file id", requested: with(structured), keeps: true}, // A kept manifest's chunks are not read, so listing one of them next // to it needs a proof like any chunk not stored at the target. {name: "held chunk next to the kept manifest", requested: with(kept, held[0]), keeps: true, admission: filer_pb.ChunkProofRefused, locked: filer_pb.ChunkProofRefused}, {name: "held chunks retained flat", requested: with(held[0], held[1], stored.Chunks[1], newChunk)}, // weed mount truncates through a manifest by sending the chunks it // holds, cut at the new size, instead of a shortened manifest. {name: "truncate through the stored manifest", requested: with(held[0], &filer_pb.FileChunk{FileId: held[1].FileId, Offset: 10, Size: 5})}, {name: "manifest not stored", requested: with(&filer_pb.FileChunk{FileId: "4,0200005eed", Size: 20, IsChunkManifest: true}), admission: "only a manifest stored", locked: "only a manifest stored"}, {name: "stored manifest changed", requested: with(resized), admission: "only a manifest stored", locked: "only a manifest stored"}, {name: "nested manifest sent as a manifest", requested: with(nested), admission: "only a manifest stored", locked: "only a manifest stored"}, {name: "stored manifest sent as data", requested: with(&filer_pb.FileChunk{FileId: manifest.FileId, Size: 20}), admission: "cannot be kept as data", locked: "cannot be kept as data"}, {name: "nested manifest sent as data", requested: with(&filer_pb.FileChunk{FileId: nested.FileId, Size: 10}), locked: "cannot be kept as data"}, {name: "alias of a held chunk", requested: with(&filer_pb.FileChunk{FileId: "3,000100005eed", Size: 10}), locked: "chunk identity aliases"}, {name: "unknown chunk without proof", requested: with(&filer_pb.FileChunk{FileId: "3,0900005eed", Size: 10}), locked: filer_pb.ChunkProofRefused}, } { t.Run(tc.name, func(t *testing.T) { reads = 0 for _, check := range []struct { stage string read func([]*filer_pb.FileChunk) ([]*filer_pb.FileChunk, error) want string }{ {stage: "admission", want: tc.admission}, {stage: "locked", read: readHeld, want: tc.locked}, } { err := scopeRetainsData(stored, tc.requested, false, proven, check.read) if check.want == "" && err != nil { t.Fatalf("%s refused: %v", check.stage, err) } if check.want != "" && (err == nil || !strings.Contains(err.Error(), check.want)) { t.Fatalf("%s err=%v, want %q", check.stage, err, check.want) } } if wantReads := map[bool]int{true: 0, false: 1}[tc.keeps]; reads != wantReads { t.Fatalf("read the stored manifest %d times, want %d", reads, wantReads) } }) } reads = 0 if err := scopeRetainsData(stored, &filer_pb.Entry{}, false, proven, readHeld); err != nil || reads != 0 { t.Fatalf("chunkless request err=%v reads=%d, want admitted without reading manifests", err, reads) } // An append drops no stored chunk, so it reads no manifest either. if err := scopeRetainsData(stored, with(newChunk), true, proven, readHeld); err != nil || reads != 0 { t.Fatalf("append err=%v reads=%d, want admitted without reading manifests", err, reads) } failed := errors.New("volume unreachable") unreadable := func([]*filer_pb.FileChunk) ([]*filer_pb.FileChunk, error) { return nil, failed } if err := scopeRetainsData(stored, with(kept, newChunk), false, proven, unreadable); err != nil { t.Fatalf("kept manifest err=%v, want admitted without reading it", err) } err := scopeRetainsData(stored, with(held[0]), false, proven, unreadable) var readErr *scopeManifestReadError if !errors.As(err, &readErr) || !errors.Is(err, failed) { t.Fatalf("unreadable dropped manifest err=%v, want a manifest read error", err) } } // scopeFoldName is the file the scoped fold tests write, n chunks long. const scopeFoldName = "wal.log" // scopeFoldChunks are the chunks of a log appended to n times, as walChunks, // with the canonical file ids an assignment proof names. func scopeFoldChunks(n int) []*filer_pb.FileChunk { chunks := walChunks(n) for i, chunk := range chunks { chunk.FileId = needle.NewFileId(3, uint64(i+1), 0x5eed).String() } return chunks } func scopeFoldEntry(n int) *filer_pb.Entry { entry := walEntry(n) entry.Chunks = scopeFoldChunks(n) return entry } var scopeFoldPath = scopeJoin(aliceWS, scopeFoldName) type scopeFoldServer struct { fs *FilerServer scope *filerGrpcScope volume *reuseManifestVolume store *renameTestStore } // newScopeFoldServer is a filer with a volume that keeps what it is sent, its // own lock ring for appends, and the scope interceptor in front of it. func newScopeFoldServer(t *testing.T) *scopeFoldServer { t.Helper() store := newRenameTestStore() dir := newFileEntry(aliceWS, 2) dir.Attr.Mode = os.ModeDir | 0755 store.entries[aliceWS] = dir fs, volume := newReuseManifestServer(t, store) lis, err := net.Listen("tcp", "127.0.0.1:0") require.NoError(t, err) addr := pb.NewServerAddressWithGrpcPort(lis.Addr().String(), lis.Addr().(*net.TCPAddr).Port) withRing(fs, addr, addr) srv := grpc.NewServer() filer_pb.RegisterSeaweedFilerServer(srv, fs) go srv.Serve(lis) t.Cleanup(srv.Stop) scope := newFilerGrpcScope(scopeConfig{ signingKey: func() security.SigningKey { return security.SigningKey(scopeTestKey) }, }, fs) return &scopeFoldServer{fs: fs, scope: scope, volume: volume, store: store} } // proofs mints an assignment proof for each of chunks. func scopeFoldProofs(t *testing.T, chunks ...*filer_pb.FileChunk) map[string]string { t.Helper() auth := make(map[string]string, len(chunks)) for _, chunk := range chunks { auth[chunk.GetFileIdString()] = scopedChunkProof(t, "retention", chunk.GetFileIdString(), time.Hour) } return auth } // call sends req through the scope interceptor and reports whether it reached // the handler. func (s *scopeFoldServer) call(t *testing.T, req any) (called bool, err error) { t.Helper() method := map[string]string{ "*filer_pb.CreateEntryRequest": "CreateEntry", "*filer_pb.UpdateEntryRequest": "UpdateEntry", "*filer_pb.AppendToEntryRequest": "AppendToEntry", }[fmt.Sprintf("%T", req)] _, err = s.scope.unary(scopedRetentionContext(), req, &grpc.UnaryServerInfo{FullMethod: scopeFilerMethodPrefix + method}, func(ctx context.Context, req any) (any, error) { called = true switch r := req.(type) { case *filer_pb.CreateEntryRequest: resp, err := s.fs.CreateEntry(ctx, r) if err == nil && resp.GetError() != "" { err = errors.New(resp.GetError()) } return resp, err case *filer_pb.UpdateEntryRequest: return s.fs.UpdateEntry(ctx, r) case *filer_pb.AppendToEntryRequest: return s.fs.AppendToEntry(ctx, r) } return nil, fmt.Errorf("unexpected request %T", req) }) return called, err } func (s *scopeFoldServer) stored(t *testing.T) *filer_pb.Entry { t.Helper() entry, err := s.store.FindEntry(context.Background(), util.FullPath(scopeFoldPath)) require.NoError(t, err) return scopedEntrySnapshot(entry) } func (s *scopeFoldServer) deleted() (ids []string) { s.fs.filer.FileIdDeletionQueue.Consume(func(batch []string) { ids = append(ids, batch...) }) return ids } // held reads the chunks the manifests in chunks hold, by file identity. func (s *scopeFoldServer) held(t *testing.T, chunks []*filer_pb.FileChunk) []string { t.Helper() data, _, err := filer.ResolveChunkManifest(context.Background(), s.fs.lookupFileId, chunks, 0, 1<<62, nil, false) require.NoError(t, err) return walChunkIds(data) } // foldScoped stores a scoped create of n chunks, every one with its proof, and // returns the stored entry: the filer folds it like any other commit. func (s *scopeFoldServer) foldScoped(t *testing.T, n int) *filer_pb.Entry { t.Helper() entry := scopeFoldEntry(n) called, err := s.call(t, &filer_pb.CreateEntryRequest{ Directory: aliceWS, Entry: entry, ChunkAuth: scopeFoldProofs(t, entry.Chunks...), SkipCheckParentDirectory: true, }) require.NoError(t, err) require.True(t, called) return s.stored(t) } // A scoped commit past the fold threshold is folded by the filer, so a file a // scoped client writes keeps a chunk list a store with a value size limit can // hold. func TestScopedCommitIsFoldedByTheFiler(t *testing.T) { const n = filer.SmallChunkManifestBatch + 10 s := newScopeFoldServer(t) stored := s.foldScoped(t, n) manifests, flat := filer.SeparateManifestChunks(stored.GetChunks()) require.Len(t, manifests, 1, "the scoped commit was stored flat") require.Len(t, flat, n-filer.SmallChunkManifestBatch) require.Equal(t, 1, s.volume.uploadCount()) require.Equal(t, walChunkIds(scopeFoldChunks(filer.SmallChunkManifestBatch)), s.held(t, manifests)) require.Empty(t, s.deleted()) } // After the filer folded a scoped file, the client's next commit keeps the // stored manifest as stored, or lists its chunks flat again, and adds a new // chunk with its proof. Both keep the stored manifest and delete nothing. func TestScopedCommitKeepsTheStoredManifest(t *testing.T) { const n = filer.SmallChunkManifestBatch + 10 for _, tc := range []struct { name string list func(stored *filer_pb.Entry) []*filer_pb.FileChunk }{ {name: "manifest as stored", list: func(stored *filer_pb.Entry) []*filer_pb.FileChunk { return proto.Clone(stored).(*filer_pb.Entry).Chunks }}, {name: "held chunks flat", list: func(*filer_pb.Entry) []*filer_pb.FileChunk { return scopeFoldChunks(n) }}, } { for _, how := range []string{"update", "create"} { t.Run(tc.name+"/"+how, func(t *testing.T) { s := newScopeFoldServer(t) first := s.foldScoped(t, n) manifests, _ := filer.SeparateManifestChunks(first.GetChunks()) added := scopeFoldChunks(n + 1)[n] entry := scopeFoldEntry(n + 1) entry.Chunks = append(tc.list(first), added) auth := scopeFoldProofs(t, added) var req any = &filer_pb.UpdateEntryRequest{Directory: aliceWS, Entry: entry, ChunkAuth: auth} if how == "create" { req = &filer_pb.CreateEntryRequest{Directory: aliceWS, Entry: entry, ChunkAuth: auth, SkipCheckParentDirectory: true} } called, err := s.call(t, req) require.True(t, called) require.NoError(t, err) stored := s.stored(t) kept, flat := filer.SeparateManifestChunks(stored.GetChunks()) require.Equal(t, walChunkIds(manifests), walChunkIds(kept), "the stored manifest was replaced") require.ElementsMatch(t, walChunkIds(scopeFoldChunks(n + 1)[filer.SmallChunkManifestBatch:]), walChunkIds(flat)) require.Equal(t, 1, s.volume.uploadCount(), "a manifest was written again") require.Empty(t, s.deleted()) }) } } } // clientManifest stores a manifest the filer did not write, over the first // SmallChunkManifestBatch chunks of a file, and returns its chunk. func (s *scopeFoldServer) clientManifest(t *testing.T) *filer_pb.FileChunk { t.Helper() held := scopeFoldChunks(filer.SmallChunkManifestBatch) data, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: held}) require.NoError(t, err) const fid = "1,ff0000c0de" s.volume.mu.Lock() s.volume.blobs[filer.ChunkIdentity(fid)] = data s.volume.mu.Unlock() return &filer_pb.FileChunk{FileId: fid, Offset: 0, Size: uint64(filer.SmallChunkManifestBatch) * 10, IsChunkManifest: true, ModifiedTsNs: int64(filer.SmallChunkManifestBatch)} } // A scoped client may not send a manifest the filer did not store at the // target, even with an assignment proof for it: it could name any chunk. An // unscoped client still may. func TestScopedCommitRefusesManifestsTheFilerDidNotStore(t *testing.T) { const n = filer.SmallChunkManifestBatch + 10 for _, tc := range []struct { name string manifest func(s *scopeFoldServer, stored *filer_pb.Entry) *filer_pb.FileChunk }{ {name: "client manifest", manifest: func(s *scopeFoldServer, _ *filer_pb.Entry) *filer_pb.FileChunk { return s.clientManifest(t) }}, {name: "stored manifest changed", manifest: func(_ *scopeFoldServer, stored *filer_pb.Entry) *filer_pb.FileChunk { manifests, _ := filer.SeparateManifestChunks(stored.GetChunks()) changed := proto.Clone(manifests[0]).(*filer_pb.FileChunk) changed.Size += 10 return changed }}, } { t.Run(tc.name, func(t *testing.T) { s := newScopeFoldServer(t) first := s.foldScoped(t, n) manifest := tc.manifest(s, first) entry := scopeFoldEntry(n) entry.Chunks = append([]*filer_pb.FileChunk{manifest}, scopeFoldChunks(n)[filer.SmallChunkManifestBatch:]...) called, err := s.call(t, &filer_pb.UpdateEntryRequest{Directory: aliceWS, Entry: entry, ChunkAuth: scopeFoldProofs(t, manifest)}) require.Equal(t, codes.PermissionDenied, status.Code(err), "err=%v", err) require.False(t, called, "refused only under the path lock") require.True(t, proto.Equal(first, s.stored(t)), "the stored entry changed") require.Empty(t, s.deleted()) }) } t.Run("unscoped", func(t *testing.T) { s := newScopeFoldServer(t) entry := scopeFoldEntry(n) entry.Chunks = append([]*filer_pb.FileChunk{s.clientManifest(t)}, scopeFoldChunks(n)[filer.SmallChunkManifestBatch:]...) resp, err := s.fs.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{Directory: aliceWS, Entry: entry, SkipCheckParentDirectory: true}) require.NoError(t, err) require.Empty(t, resp.GetError()) require.ElementsMatch(t, walChunkIds(entry.Chunks), walChunkIds(s.stored(t).GetChunks())) }) } // A chunk a stored manifest holds is stored at the target, so a scoped commit // may retain it flat, but not under another spelling of its file id: the // stored manifest's spelling could be deleted while the alias still reads it. func TestScopedCommitRefusesAliasesOfManifestChunks(t *testing.T) { const n = filer.SmallChunkManifestBatch + 10 s := newScopeFoldServer(t) first := s.foldScoped(t, n) entry := scopeFoldEntry(n) original := entry.Chunks[0].FileId alias := strings.Replace(original, ",", ",00", 1) require.Equal(t, filer.ChunkIdentity(original), filer.ChunkIdentity(alias)) entry.Chunks[0].FileId = alias called, err := s.call(t, &filer_pb.UpdateEntryRequest{Directory: aliceWS, Entry: entry, ChunkAuth: scopeFoldProofs(t, entry.Chunks[0])}) require.Equal(t, codes.PermissionDenied, status.Code(err), "err=%v", err) require.Contains(t, err.Error(), "chunk identity aliases") require.True(t, called, "the alias of a held chunk is found under the path lock") require.True(t, proto.Equal(first, s.stored(t)), "the stored entry changed") require.Empty(t, s.deleted()) } // A scoped commit that drops a stored manifest it cannot read is refused, not // checked against the stored chunks alone. One that keeps the manifests does // not read them. func TestScopedCommitFailsClosedOnUnreadableStoredManifest(t *testing.T) { const n = filer.SmallChunkManifestBatch + 10 s := newScopeFoldServer(t) first := s.foldScoped(t, n) s.volume.mu.Lock() clear(s.volume.blobs) s.volume.mu.Unlock() added := scopeFoldChunks(n + 1)[n] flat := scopeFoldEntry(n + 1) called, err := s.call(t, &filer_pb.UpdateEntryRequest{Directory: aliceWS, Entry: flat, ChunkAuth: scopeFoldProofs(t, added)}) require.Equal(t, codes.Unavailable, status.Code(err), "err=%v", err) require.Contains(t, err.Error(), "manifests stored at the target could not be read") require.True(t, called) require.True(t, proto.Equal(first, s.stored(t)), "the stored entry changed") require.Empty(t, s.deleted()) want := append(walChunkIds(first.Chunks), filer.ChunkIdentity(added.GetFileIdString())) kept := scopeFoldEntry(n + 1) kept.Chunks = append(proto.Clone(first).(*filer_pb.Entry).Chunks, added) called, err = s.call(t, &filer_pb.UpdateEntryRequest{Directory: aliceWS, Entry: kept, ChunkAuth: scopeFoldProofs(t, added)}) require.NoError(t, err) require.True(t, called) require.Equal(t, want, walChunkIds(s.stored(t).Chunks)) require.Empty(t, s.deleted()) } // An append keeps every stored chunk, so it may add proven chunks to a file // the filer folded without reading its manifests. Another spelling of a chunk // a stored manifest holds is a new chunk there, and needs its own proof. func TestScopedAppendToFoldedEntry(t *testing.T) { const n = filer.SmallChunkManifestBatch + 10 s := newScopeFoldServer(t) first := s.foldScoped(t, n) added := &filer_pb.FileChunk{FileId: "3,ffff00005eed", Size: 10, ModifiedTsNs: n + 1} called, err := s.call(t, &filer_pb.AppendToEntryRequest{ Directory: aliceWS, EntryName: scopeFoldName, Chunks: []*filer_pb.FileChunk{added}, ChunkAuth: scopeFoldProofs(t, added), }) require.True(t, called) require.NoError(t, err) stored := s.stored(t) require.Equal(t, append(walChunkIds(first.Chunks), filer.ChunkIdentity(added.FileId)), walChunkIds(stored.Chunks)) require.Equal(t, int64(n*10), stored.Chunks[len(stored.Chunks)-1].Offset) alias := &filer_pb.FileChunk{FileId: strings.Replace(scopeFoldChunks(1)[0].FileId, ",", ",00", 1), Size: 10} called, err = s.call(t, &filer_pb.AppendToEntryRequest{ Directory: aliceWS, EntryName: scopeFoldName, Chunks: []*filer_pb.FileChunk{alias}, ChunkAuth: scopeFoldProofs(t, alias), }) require.Equal(t, codes.PermissionDenied, status.Code(err), "err=%v", err) require.Contains(t, err.Error(), filer_pb.ChunkProofRefused) require.False(t, called, "refused at admission") require.True(t, proto.Equal(stored, s.stored(t)), "the stored entry changed") require.Empty(t, s.deleted()) // An append moves its chunks to the end of the file, and a manifest // cannot move without its chunks: even a stored one is refused. var manifest *filer_pb.FileChunk for _, chunk := range stored.Chunks { if chunk.IsChunkManifest { manifest = proto.Clone(chunk).(*filer_pb.FileChunk) break } } require.NotNil(t, manifest) called, err = s.call(t, &filer_pb.AppendToEntryRequest{ Directory: aliceWS, EntryName: scopeFoldName, Chunks: []*filer_pb.FileChunk{manifest}, }) require.Equal(t, codes.PermissionDenied, status.Code(err), "err=%v", err) require.Contains(t, err.Error(), "cannot be appended") require.False(t, called, "refused at admission") require.True(t, proto.Equal(stored, s.stored(t)), "the stored entry changed") require.Empty(t, s.deleted()) }