Files
seaweedfs/weed/mount/chunk_proofs_test.go
T
394e9d247e mount: keep assignment proofs until the filer stores their chunks (#13186)
* operation: return the assignment proof of an upload

A filer serving a scoped token returns an assignment proof with
AssignVolume and stores a new chunk in an entry only when the request
presents that proof in chunk_auth. UploadWithRetry dropped it, so a
client had no way to commit the chunks it uploaded.

UploadResult.AssignAuth now carries the proof of the assignment the data
was finally stored under. A proof from an assignment the upload abandoned
after a failed attempt is never returned. The field is not serialized and
stays empty when the filer sends none, so existing callers are unchanged.

* mount: keep assignment proofs until the filer stores their chunks

A mount with a scoped filer token was refused whenever it wrote new
chunks: the filer asks for the assignment proof of every chunk the stored
entry does not hold, and the mount never kept it.

The mount now keeps the proof of every chunk it uploads and attaches the
proofs of the chunks a request names to each create, update and append
it sends, over the mutation stream and over unary calls, on every
attempt. A proof is released only once a filer acknowledged an entry that
names the chunk, or a manifest that holds it. A failed, refused or timed
out commit releases nothing, since it may have been stored: the retry
still carries the proof, and a filer ignores proofs for chunks it holds.
Proofs are stateless, so a commit retried on another filer of the cluster
is accepted there.

The store is bounded. When it is full an upload waits for commits to make
room before it is assigned a file id, and fails after a minute instead of
evicting a proof a pending commit still needs. Only proofs well past their
expiry, which a filer refuses anyway, are dropped to make room.

Without a filer token the mount keeps no store: its requests and chunk
lists are as before. A token without path grants is given no proofs, so
nothing is attached either.

* mount: keep chunk lists flat with a filer token file

A filer serving a scoped token stores no new chunk in an entry that holds
manifests, so once a mount folded a file's small chunks into a manifest,
every later write to that file was refused. A mount with a filer token now
keeps chunk lists flat; mounts without one fold as before.

* mount: test the unscoped-token path with a signed token

GenJwtForFilerScope returns an empty token when it is given no path
grants, so both cases of TestUnscopedMountRequestsCarryNoProofs ran a
tokenless mount. Sign an unscoped filer token instead and check that it
is not empty, so the test covers a mount holding a token the filer issues
no proofs for.

* mount: fold chunk lists unless the filer scopes the mount's token

A mount with -filer.tokenFile kept every chunk list flat, also when the
token is an unscoped one the filer issues no proofs for. Such a mount
stopped folding chunks into manifests, so its small-chunk runs were never
folded and, on FoundationDB, a file past about 1000 chunks no longer fit
its entry. Keep lists flat only while the current token has path grants
or a method list, which the filer scopes; fold as before otherwise.

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-30 18:18:29 -08:00

764 lines
28 KiB
Go

package mount
import (
"context"
"fmt"
"io"
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/go-fuse/v2/fuse"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"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"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
)
var proofTestKey = security.SigningKey("chunk-proof-test-signing-key")
// proofCluster is what the filers of one cluster share: their entries and the
// file ids they assign.
type proofCluster struct {
mu sync.Mutex
entries map[string]*filer_pb.Entry
received []proofRequest
assigned atomic.Uint64
}
type proofRequest struct {
via string // "unary" or "stream"
chunk []*filer_pb.FileChunk
auth map[string]string
}
func newProofCluster() *proofCluster {
return &proofCluster{entries: make(map[string]*filer_pb.Entry)}
}
func (c *proofCluster) entry(path string) *filer_pb.Entry {
c.mu.Lock()
defer c.mu.Unlock()
return c.entries[path]
}
func (c *proofCluster) put(path string, entry *filer_pb.Entry) {
c.mu.Lock()
defer c.mu.Unlock()
c.entries[path] = entry
}
func (c *proofCluster) requests() []proofRequest {
c.mu.Lock()
defer c.mu.Unlock()
return append([]proofRequest(nil), c.received...)
}
// proofFiler applies a scoped filer's rule for new chunks with the real
// assignment proof primitives. AssignVolume to a scoped token returns a proof
// bound to the token's id; a create, update or append naming a chunk the
// stored entry lacks is refused unless chunk_auth holds a valid proof for it,
// and chunks cannot be added to an entry that holds manifests. A token
// without path grants gets no proof and is not checked. Filers sharing a
// cluster accept each other's proofs, as they share the signing key.
type proofFiler struct {
fakeFilerServer
cluster *proofCluster
volume string
assigns atomic.Int32
failCommits atomic.Int32 // commits answered Unavailable before storing
holdCommits atomic.Int32 // commits held until the caller gives up
}
func newProofFiler(t *testing.T, cluster *proofCluster, volume string) (*proofFiler, pb.ServerAddress) {
f := &proofFiler{cluster: cluster, volume: volume}
return f, listenFiler(t, f)
}
func proofHolder(ctx context.Context) (string, bool) {
md, _ := metadata.FromIncomingContext(ctx)
token, ok := strings.CutPrefix(joinAuthorization(md), "Bearer ")
if !ok {
return "", false
}
claims, ok := security.FilerTokenClaims(security.EncodedJwt(token))
if !ok || !claims.IsScoped() {
return "", false
}
return claims.ID, true
}
func (f *proofFiler) AssignVolume(ctx context.Context, req *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
f.assigns.Add(1)
fid := needle.NewFileId(3, f.cluster.assigned.Add(1), 0x637037d6).String()
resp := &filer_pb.AssignVolumeResponse{
FileId: fid,
Count: req.GetCount(),
Location: &filer_pb.Location{Url: f.volume, PublicUrl: f.volume},
}
if holder, scoped := proofHolder(ctx); scoped {
resp.AssignAuth = string(security.GenJwtForAssign(proofTestKey, time.Hour, fid, holder, req.GetCount(), ""))
}
return resp, nil
}
// commit checks a request the way a scoped filer does and stores entry at
// path. appended chunks are added to the stored entry instead.
func (f *proofFiler) commit(ctx context.Context, via, method, path string, entry *filer_pb.Entry, appended []*filer_pb.FileChunk, auth map[string]string) error {
requested := entry.GetChunks()
if appended != nil {
requested = appended
}
f.cluster.mu.Lock()
defer f.cluster.mu.Unlock()
f.cluster.received = append(f.cluster.received, proofRequest{via: via, chunk: requested, auth: auth})
if f.failCommits.Load() > 0 {
f.failCommits.Add(-1)
return status.Error(codes.Unavailable, "filer restarting")
}
if f.holdCommits.Load() > 0 {
f.holdCommits.Add(-1)
f.cluster.mu.Unlock()
<-ctx.Done()
f.cluster.mu.Lock()
return ctx.Err()
}
stored := f.cluster.entries[path]
if holder, scoped := proofHolder(ctx); scoped {
known := make(map[string]bool)
for _, chunk := range stored.GetChunks() {
if chunk.GetIsChunkManifest() && len(requested) > 0 {
return status.Errorf(codes.PermissionDenied, "filer: %s: chunks cannot be written to an entry containing manifests", method)
}
known[chunk.GetFileIdString()] = true
}
for _, chunk := range requested {
fid := chunk.GetFileIdString()
if !known[fid] && !security.VerifyAssignJwt(proofTestKey, nil, security.EncodedJwt(auth[fid]), fid, holder, 0, "") {
return status.Errorf(codes.PermissionDenied, "filer: %s: %s %s", method, filer_pb.ChunkProofRefused, fid)
}
}
}
if appended != nil {
next := proto.Clone(stored).(*filer_pb.Entry)
next.Chunks = append(next.Chunks, appended...)
entry = next
}
f.cluster.entries[path] = proto.Clone(entry).(*filer_pb.Entry)
return nil
}
func (f *proofFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
if err := f.commit(ctx, "unary", "CreateEntry", string(util.NewFullPath(req.Directory, req.Entry.Name)), req.Entry, nil, req.ChunkAuth); err != nil {
return nil, err
}
return f.fakeFilerServer.CreateEntry(ctx, req)
}
func (f *proofFiler) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
if err := f.commit(ctx, "unary", "UpdateEntry", string(util.NewFullPath(req.Directory, req.Entry.Name)), req.Entry, nil, req.ChunkAuth); err != nil {
return nil, err
}
return f.fakeFilerServer.UpdateEntry(ctx, req)
}
func (f *proofFiler) AppendToEntry(ctx context.Context, req *filer_pb.AppendToEntryRequest) (*filer_pb.AppendToEntryResponse, error) {
if err := f.commit(ctx, "unary", "AppendToEntry", string(util.NewFullPath(req.Directory, req.EntryName)), nil, req.Chunks, req.ChunkAuth); err != nil {
return nil, err
}
return &filer_pb.AppendToEntryResponse{}, nil
}
// StreamMutateEntry answers a refusal in the response, with EACCES, as the
// scoped filer's stream check does.
func (f *proofFiler) StreamMutateEntry(stream filer_pb.SeaweedFiler_StreamMutateEntryServer) error {
for {
req, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
out := &filer_pb.StreamMutateEntryResponse{RequestId: req.RequestId, IsLast: true}
switch r := req.Request.(type) {
case *filer_pb.StreamMutateEntryRequest_CreateRequest:
c := r.CreateRequest
err = f.commit(stream.Context(), "stream", "CreateEntry", string(util.NewFullPath(c.Directory, c.Entry.Name)), c.Entry, nil, c.ChunkAuth)
out.Response = &filer_pb.StreamMutateEntryResponse_CreateResponse{CreateResponse: &filer_pb.CreateEntryResponse{}}
case *filer_pb.StreamMutateEntryRequest_UpdateRequest:
u := r.UpdateRequest
err = f.commit(stream.Context(), "stream", "UpdateEntry", string(util.NewFullPath(u.Directory, u.Entry.Name)), u.Entry, nil, u.ChunkAuth)
out.Response = &filer_pb.StreamMutateEntryResponse_UpdateResponse{UpdateResponse: &filer_pb.UpdateEntryResponse{}}
default:
err = fmt.Errorf("unexpected request %T", req.Request)
}
if err != nil {
out.Response = nil
out.Error, out.Errno = err.Error(), int32(syscall.EACCES)
}
if err := stream.Send(out); err != nil {
return err
}
}
}
// newProofMount is a mount writing through filers (in walk order) with token,
// which also keeps assignment proofs unless token is empty. Chunks go straight
// to the volume stub the filers assign.
func newProofMount(t *testing.T, token security.EncodedJwt, filers ...pb.ServerAddress) *WFS {
t.Helper()
wfs := newInvalidateTestWFS(t)
wfs.filerCallTimeout = 5 * time.Second
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
wfs.option.FilerAddresses = filers
atomic.StoreInt32(&wfs.option.filerIndex, 0)
wfs.option.VolumeServerAccess = "direct"
wfs.filerClient = wdclient.NewFilerClient(filers, wfs.option.GrpcDialOption, "")
if token != "" {
wfs.option.FilerTokenSource = func(context.Context) (security.EncodedJwt, error) { return token, nil }
wfs.chunkProofs = newChunkProofs(chunkProofLimit)
}
return wfs
}
func scopedMountToken() security.EncodedJwt {
return security.GenJwtForFilerScope(proofTestKey, time.Hour, "mount-1", []string{"/dir"}, nil)
}
// openDirtyFile opens /dir/file holding stored, which the cluster stores too,
// with data written after it and not uploaded yet.
func openDirtyFile(t *testing.T, wfs *WFS, cluster *proofCluster, stored ...*filer_pb.FileChunk) *FileHandle {
t.Helper()
data := []byte("data written by a scoped mount")
offset := int64(filer.TotalSize(stored))
entry := &filer_pb.Entry{
Name: "file",
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(offset) + uint64(len(data)), FileMode: 0100644},
Chunks: stored,
}
if len(stored) > 0 {
cluster.put("/dir/file", proto.Clone(entry).(*filer_pb.Entry))
}
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 0, 0)
t.Cleanup(func() { wfs.ReleaseHandle(fh.fh) })
if _, err := fh.dirtyPages.AddPage(offset, data, true, time.Now().UnixNano()); err != nil {
t.Fatalf("AddPage: %v", err)
}
fh.dirtyMetadata = true
return fh
}
func flushFile(wfs *WFS, fh *FileHandle) fuse.Status {
return wfs.Flush(nil, &fuse.FlushIn{InHeader: fuse.InHeader{NodeId: fh.inode}, Fh: uint64(fh.fh)})
}
// newChunks returns the chunks of req the cluster had not stored before it.
func newChunks(req proofRequest, before map[string]bool) []string {
var fids []string
for _, chunk := range req.chunk {
if !before[chunk.GetFileIdString()] {
fids = append(fids, chunk.GetFileIdString())
}
}
return fids
}
// checkCarriesProofs asserts auth holds a valid proof for every one of fids
// and nothing else.
func checkCarriesProofs(t *testing.T, auth map[string]string, fids ...string) {
t.Helper()
if len(auth) != len(fids) {
t.Fatalf("chunk_auth names %d chunks, want exactly %v: %v", len(auth), fids, auth)
}
for _, fid := range fids {
if !security.VerifyAssignJwt(proofTestKey, nil, security.EncodedJwt(auth[fid]), fid, "mount-1", 0, "") {
t.Fatalf("chunk_auth carries no valid proof for %s", fid)
}
}
}
// A scoped mount's flush stores its new chunk only with the chunk's proof,
// and the proof is dropped once the filer acknowledged it. Without the proofs
// (the mount before it kept them) the filer refuses the same flush.
func TestScopedMountFlushCommitsNewChunkWithItsProof(t *testing.T) {
for _, keep := range []bool{true, false} {
t.Run(fmt.Sprintf("keeps proofs %v", keep), func(t *testing.T) {
cluster := newProofCluster()
_, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, scopedMountToken(), addr)
if !keep {
wfs.chunkProofs = nil
}
fh := openDirtyFile(t, wfs, cluster)
status := flushFile(wfs, fh)
if !keep {
if status == fuse.OK || cluster.entry("/dir/file") != nil {
t.Fatalf("Flush = %v without proofs, want the filer to refuse it", status)
}
return
}
if status != fuse.OK {
t.Fatalf("Flush = %v, want OK", status)
}
stored := cluster.entry("/dir/file")
if len(stored.GetChunks()) != 1 {
t.Fatalf("stored chunks = %v, want the uploaded chunk", stored.GetChunks())
}
requests := cluster.requests()
if len(requests) != 1 {
t.Fatalf("filer received %d commits, want 1", len(requests))
}
checkCarriesProofs(t, requests[0].auth, stored.Chunks[0].GetFileIdString())
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept after the commit was acknowledged, want 0", n)
}
})
}
}
// A commit that failed may still have been stored, so it releases nothing:
// the retry, on the same filer or another one of the cluster, carries the
// proof the first filer issued.
func TestScopedMountRetriedCommitCarriesProof(t *testing.T) {
for _, tc := range []struct {
name string
filers int
failing int32 // commits the first filer fails
}{
{name: "same filer", filers: 1, failing: 1},
{name: "assigned on one filer, stored by another", filers: 2, failing: 1 << 20},
} {
t.Run(tc.name, func(t *testing.T) {
cluster := newProofCluster()
volume := newVolumeStub(t)
first, addr := newProofFiler(t, cluster, volume)
first.failCommits.Store(tc.failing)
addrs := []pb.ServerAddress{addr}
var second *proofFiler
if tc.filers == 2 {
var addr2 pb.ServerAddress
second, addr2 = newProofFiler(t, cluster, volume)
addrs = append(addrs, addr2)
}
wfs := newProofMount(t, scopedMountToken(), addrs...)
fh := openDirtyFile(t, wfs, cluster)
if status := flushFile(wfs, fh); status != fuse.OK {
t.Fatalf("Flush = %v, want OK", status)
}
stored := cluster.entry("/dir/file")
if len(stored.GetChunks()) != 1 {
t.Fatalf("stored chunks = %v, want the uploaded chunk", stored.GetChunks())
}
fid := stored.Chunks[0].GetFileIdString()
requests := cluster.requests()
if len(requests) != 2 {
t.Fatalf("filers received %d commits, want the failed one and its retry", len(requests))
}
for _, req := range requests {
checkCarriesProofs(t, req.auth, fid)
}
if first.assigns.Load() != 1 {
t.Fatalf("first filer assigned %d file ids, want 1", first.assigns.Load())
}
if second != nil && second.assigns.Load() != 0 {
t.Fatalf("second filer assigned %d file ids, want none: the proof is from the first", second.assigns.Load())
}
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept after the commit was acknowledged, want 0", n)
}
})
}
}
// A commit that timed out is not known to have failed: the proof stays, and
// the next flush stores the chunk with it.
func TestScopedMountKeepsProofAfterTimedOutCommit(t *testing.T) {
saved := metadataFlushTimeout
metadataFlushTimeout = 300 * time.Millisecond
t.Cleanup(func() { metadataFlushTimeout = saved })
cluster := newProofCluster()
fake, addr := newProofFiler(t, cluster, newVolumeStub(t))
fake.holdCommits.Store(1)
wfs := newProofMount(t, scopedMountToken(), addr)
fh := openDirtyFile(t, wfs, cluster)
if status := flushFile(wfs, fh); status == fuse.OK {
t.Fatal("Flush = OK against a filer that never answered the commit")
}
if n := wfs.chunkProofs.count(); n != 1 {
t.Fatalf("%d proofs kept after a timed out commit, want the chunk's", n)
}
if status := flushFile(wfs, fh); status != fuse.OK {
t.Fatalf("second Flush = %v, want OK", status)
}
stored := cluster.entry("/dir/file")
if len(stored.GetChunks()) != 1 {
t.Fatalf("stored chunks = %v, want the uploaded chunk", stored.GetChunks())
}
requests := cluster.requests()
checkCarriesProofs(t, requests[len(requests)-1].auth, stored.Chunks[0].GetFileIdString())
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept after the commit was acknowledged, want 0", n)
}
}
// Creates and updates carry the proofs of the chunks the filer does not hold
// yet, over the mutation stream and over unary calls alike.
func TestScopedMountCreateAndUpdateCarryProofs(t *testing.T) {
for _, via := range []string{"unary", "stream"} {
t.Run(via, func(t *testing.T) {
cluster := newProofCluster()
_, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, scopedMountToken(), addr)
if via == "stream" {
wfs.streamMutate = newStreamMutateMux(wfs)
t.Cleanup(wfs.streamMutate.Close)
}
save := wfs.saveDataAsChunk("/dir/f")
upload := func(offset int64) *filer_pb.FileChunk {
chunk, err := save(strings.NewReader("chunk"), "f", offset, time.Now().UnixNano(), 0)
if err != nil {
t.Fatalf("upload: %v", err)
}
return chunk
}
first := upload(0)
if _, err := wfs.streamCreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
Directory: "/dir",
Entry: &filer_pb.Entry{Name: "f", Chunks: []*filer_pb.FileChunk{first}},
}); err != nil {
t.Fatalf("create: %v", err)
}
second := upload(5)
if _, err := wfs.streamUpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
Directory: "/dir",
Entry: &filer_pb.Entry{Name: "f", Chunks: []*filer_pb.FileChunk{first, second}},
}); err != nil {
t.Fatalf("update: %v", err)
}
requests := cluster.requests()
if len(requests) != 2 {
t.Fatalf("filer received %d commits, want 2", len(requests))
}
for _, req := range requests {
if req.via != via {
t.Fatalf("commit went %s, want %s", req.via, via)
}
}
checkCarriesProofs(t, requests[0].auth, first.GetFileIdString())
// The update only adds the second chunk: the first one is stored.
checkCarriesProofs(t, requests[1].auth, second.GetFileIdString())
if got := len(cluster.entry("/dir/f").GetChunks()); got != 2 {
t.Fatalf("stored chunks = %d, want 2", got)
}
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept after the commits were acknowledged, want 0", n)
}
})
}
}
// A refused update releases nothing: the chunk's proof is kept for a later
// commit, here an append.
func TestScopedMountRefusedCommitKeepsProof(t *testing.T) {
cluster := newProofCluster()
_, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, scopedMountToken(), addr)
chunk, err := wfs.saveDataAsChunk("/dir/f")(strings.NewReader("chunk"), "f", 0, time.Now().UnixNano(), 0)
if err != nil {
t.Fatalf("upload: %v", err)
}
cluster.put("/dir/f", &filer_pb.Entry{Name: "f", Chunks: []*filer_pb.FileChunk{{FileId: "4,01637037d6", IsChunkManifest: true}}})
_, err = wfs.streamUpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
Directory: "/dir",
Entry: &filer_pb.Entry{Name: "f", Chunks: []*filer_pb.FileChunk{chunk}},
})
if status.Code(err) != codes.PermissionDenied {
t.Fatalf("update onto an entry of manifests = %v, want the filer's refusal", err)
}
if n := wfs.chunkProofs.count(); n != 1 {
t.Fatalf("%d proofs kept after a refused commit, want the chunk's", n)
}
cluster.put("/dir/f", &filer_pb.Entry{Name: "f"})
if err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
_, err := client.AppendToEntry(context.Background(), &filer_pb.AppendToEntryRequest{Directory: "/dir", EntryName: "f", Chunks: []*filer_pb.FileChunk{chunk}})
return err
}); err != nil {
t.Fatalf("append: %v", err)
}
requests := cluster.requests()
checkCarriesProofs(t, requests[len(requests)-1].auth, chunk.GetFileIdString())
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept after the append was acknowledged, want 0", n)
}
}
// A filer serving a scoped token stores no new chunk in an entry that holds
// manifests, so a mount with a token keeps the chunk list flat where an
// unscoped mount would fold it: the flush that completes a batch of small
// chunks commits them as they are, and the file stays writable.
func TestScopedMountKeepsChunkListsFlat(t *testing.T) {
cluster := newProofCluster()
fake, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, scopedMountToken(), addr)
// One chunk short of a batch: the chunk this flush uploads completes it.
stored := storedSmallChunks(filer.SmallChunkManifestBatch - 1)
fh := openDirtyFile(t, wfs, cluster, stored...)
if status := flushFile(wfs, fh); status != fuse.OK {
t.Fatalf("Flush = %v, want OK", status)
}
if got := fake.assigns.Load(); got != 1 {
t.Fatalf("AssignVolume calls = %d, want only the data chunk", got)
}
committed := cluster.entry("/dir/file").GetChunks()
if len(committed) != filer.SmallChunkManifestBatch {
t.Fatalf("stored %d chunks, want the %d small chunks unfolded", len(committed), filer.SmallChunkManifestBatch)
}
for _, chunk := range committed {
if chunk.GetIsChunkManifest() {
t.Fatalf("stored a manifest %s; a scoped filer refuses later writes to such an entry", chunk.GetFileIdString())
}
}
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept after the commit was acknowledged, want 0", n)
}
}
// A mount whose token the filer does not scope folds chunk lists as a mount
// without a token does.
func TestUnscopedTokenMountFoldsChunkLists(t *testing.T) {
cluster := newProofCluster()
fake, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, security.GenJwtForFilerAdmin(proofTestKey, 3600), addr)
stored := storedSmallChunks(filer.SmallChunkManifestBatch - 1)
fh := openDirtyFile(t, wfs, cluster, stored...)
if status := flushFile(wfs, fh); status != fuse.OK {
t.Fatalf("Flush = %v, want OK", status)
}
if got := fake.assigns.Load(); got != 2 {
t.Fatalf("AssignVolume calls = %d, want the data chunk and its manifest", got)
}
manifests := 0
for _, chunk := range cluster.entry("/dir/file").GetChunks() {
if chunk.GetIsChunkManifest() {
manifests++
}
}
if manifests != 1 {
t.Fatalf("stored %d manifests, want the %d small chunks folded into one", manifests, filer.SmallChunkManifestBatch)
}
}
// Without a scoped token the filer issues no proofs, and a flush sends the
// same chunks and no chunk_auth, whether or not the mount has a token.
func TestUnscopedMountRequestsCarryNoProofs(t *testing.T) {
var lists [][]string
// A filer token with no path grants is unscoped: it has full access.
unscoped := security.GenJwtForFilerAdmin(proofTestKey, 3600)
if unscoped == "" {
t.Fatal("no unscoped filer token was signed")
}
for _, token := range []security.EncodedJwt{"", unscoped} {
cluster := newProofCluster()
_, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, token, addr)
if (token == "") != (wfs.chunkProofs == nil) {
t.Fatal("a mount keeps proofs only with a filer token")
}
fh := openDirtyFile(t, wfs, cluster)
if status := flushFile(wfs, fh); status != fuse.OK {
t.Fatalf("Flush = %v, want OK", status)
}
requests := cluster.requests()
if len(requests) != 1 || requests[0].auth != nil {
t.Fatalf("commits = %+v, want one without chunk_auth", requests)
}
var list []string
for _, chunk := range requests[0].chunk {
list = append(list, fmt.Sprintf("%s@%d+%d", chunk.GetFileIdString(), chunk.Offset, chunk.Size))
}
lists = append(lists, list)
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept without a scoped token", n)
}
}
if fmt.Sprint(lists[0]) != fmt.Sprint(lists[1]) {
t.Fatalf("chunk lists differ with and without a token: %v vs %v", lists[0], lists[1])
}
}
// One proof covers each file id of a multi-count assignment, and each is
// released on its own.
func TestChunkProofsCoverEveryIdOfAnAssignment(t *testing.T) {
const fid = "3,01637037d6"
proof := string(security.GenJwtForAssign(proofTestKey, time.Hour, fid, "mount-1", 3, ""))
p := newChunkProofs(8)
if err := p.reserve(3); err != nil {
t.Fatal(err)
}
p.keep(fid, proof, 3)
chunks := []*filer_pb.FileChunk{{FileId: fid + "_2"}, {FileId: fid}, {FileId: "3,02637037d6"}}
var auth map[string]string
if !p.attach(chunks, &auth) {
t.Fatal("attach found no proofs")
}
checkCarriesProofs(t, auth, fid, fid+"_2")
p.release(chunks[1:2])
auth = nil
p.attach([]*filer_pb.FileChunk{{FileId: fid}, {FileId: fid + "_1"}}, &auth)
checkCarriesProofs(t, auth, fid+"_1")
if n := p.count(); n != 2 {
t.Fatalf("proofs kept = %d, want 2", n)
}
// A proof covers no more ids than its count, whatever the upload asked.
q := newChunkProofs(8)
if err := q.reserve(2); err != nil {
t.Fatal(err)
}
q.keep(fid, string(security.GenJwtForAssign(proofTestKey, time.Hour, fid, "mount-1", 1, "")), 2)
if n := q.count(); n != 1 || q.reserved != 0 {
t.Fatalf("proofs kept = %d, reserved = %d, want 1 and 0", n, q.reserved)
}
}
func expiredProof(t *testing.T, fid string, expired time.Duration) string {
t.Helper()
collection := ""
claims := security.SeaweedAssignClaims{Fid: fid, Count: 1, Collection: &collection, RegisteredClaims: jwt.RegisteredClaims{
ID: "mount-1", ExpiresAt: jwt.NewNumericDate(time.Now().Add(-expired)),
}}
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(security.AssignSigningKey(proofTestKey)))
if err != nil {
t.Fatal(err)
}
return signed
}
// A full store holds an upload back until a commit makes room, and fails it
// when none does instead of dropping a proof a commit still needs. Only
// proofs past their expiry make room by themselves.
func TestChunkProofsFullStoreWaitsThenFails(t *testing.T) {
saved := chunkProofWait
chunkProofWait = 300 * time.Millisecond
t.Cleanup(func() { chunkProofWait = saved })
proof := func(fid string) string {
return string(security.GenJwtForAssign(proofTestKey, time.Hour, fid, "mount-1", 1, ""))
}
held := []*filer_pb.FileChunk{{FileId: "3,01637037d6"}, {FileId: "3,02637037d6"}}
t.Run("a commit makes room", func(t *testing.T) {
p := newChunkProofs(2)
for _, chunk := range held {
if err := p.reserve(1); err != nil {
t.Fatal(err)
}
p.keep(chunk.FileId, proof(chunk.FileId), 1)
}
done := make(chan error, 1)
go func() { done <- p.reserve(1) }()
select {
case err := <-done:
t.Fatalf("reserve on a full store returned %v before any commit", err)
case <-time.After(50 * time.Millisecond):
}
p.release(held[:1])
if err := <-done; err != nil {
t.Fatalf("reserve after a commit made room: %v", err)
}
})
t.Run("nothing makes room", func(t *testing.T) {
p := newChunkProofs(2)
for _, chunk := range held {
if err := p.reserve(1); err != nil {
t.Fatal(err)
}
p.keep(chunk.FileId, proof(chunk.FileId), 1)
}
start := time.Now()
if err := p.reserve(1); err == nil {
t.Fatal("reserve succeeded on a store no commit drained")
}
if elapsed := time.Since(start); elapsed < chunkProofWait {
t.Fatalf("reserve failed after %v, want it to wait %v", elapsed, chunkProofWait)
}
var auth map[string]string
p.attach(held, &auth)
checkCarriesProofs(t, auth, held[0].FileId, held[1].FileId)
})
t.Run("expired proofs make room", func(t *testing.T) {
p := newChunkProofs(2)
for _, tc := range []struct {
fid string
expired time.Duration
}{{held[0].FileId, chunkProofExpiryGrace + time.Minute}, {held[1].FileId, chunkProofExpiryGrace - time.Minute}} {
if err := p.reserve(1); err != nil {
t.Fatal(err)
}
p.keep(tc.fid, expiredProof(t, tc.fid, tc.expired), 1)
}
if err := p.reserve(1); err != nil {
t.Fatalf("reserve with a proof past its expiry: %v", err)
}
var auth map[string]string
p.attach(held, &auth)
if _, ok := auth[held[0].FileId]; ok || len(auth) != 1 {
t.Fatalf("kept proofs = %v, want only the one still within its grace", auth)
}
})
}
// An upload the store has no room for fails before it is assigned a file id,
// so no data is stored that no commit could name.
func TestScopedMountUploadFailsWhenProofsAreFull(t *testing.T) {
saved := chunkProofWait
chunkProofWait = 100 * time.Millisecond
t.Cleanup(func() { chunkProofWait = saved })
cluster := newProofCluster()
fake, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, scopedMountToken(), addr)
wfs.chunkProofs = newChunkProofs(1)
save := wfs.saveDataAsChunk("/dir/f")
if _, err := save(strings.NewReader("one"), "f", 0, time.Now().UnixNano(), 0); err != nil {
t.Fatalf("first upload: %v", err)
}
if _, err := save(strings.NewReader("two"), "f", 3, time.Now().UnixNano(), 0); err == nil {
t.Fatal("upload succeeded with no room to keep its proof")
}
if got := fake.assigns.Load(); got != 1 {
t.Fatalf("AssignVolume calls = %d, want only the first upload's", got)
}
if wfs.chunkProofs.reserved != 0 {
t.Fatalf("reserved = %d after the uploads ended, want 0", wfs.chunkProofs.reserved)
}
}