diff --git a/weed/mount/chunk_proofs.go b/weed/mount/chunk_proofs.go new file mode 100644 index 0000000000..3a594fdd37 --- /dev/null +++ b/weed/mount/chunk_proofs.go @@ -0,0 +1,271 @@ +package mount + +import ( + "context" + "fmt" + "sync" + "time" + + "google.golang.org/grpc" + + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" +) + +var ( + // chunkProofLimit bounds the assignment proofs a mount keeps at once, a few + // hundred bytes each. Reaching it means that many uploaded chunks still + // wait for their entry to be stored. + chunkProofLimit = 1 << 16 + // chunkProofWait is how long an upload waits for room to keep its proof + // before it fails. Tests shorten it. + chunkProofWait = time.Minute + // chunkProofExpiryGrace keeps a proof past its expiry for as long as a + // filer's clock leeway may still accept it. + chunkProofExpiryGrace = 5 * time.Minute +) + +// chunkProofs keeps the assignment proofs that a filer returns with +// AssignVolume to a scoped token. Such a filer stores a chunk it does not +// already hold at that path only when the request carries the chunk's proof +// in chunk_auth, so every proof is kept from the upload until a filer has +// acknowledged an entry that names the chunk. A failed or timed out commit +// may or may not have been stored, so it releases nothing: the retry still +// carries the proof, and a proof for a chunk the filer already holds is +// ignored there. +// +// The store is bounded. Once it is full an upload waits, before it is +// assigned a file id, for commits to make room, and fails after +// chunkProofWait instead of evicting a proof a pending commit still needs. +// Only proofs past their expiry are dropped to make room: a filer refuses +// them anyway. +// +// A nil *chunkProofs keeps nothing and attaches nothing: a mount without a +// filer token is never given proofs, and its requests are left as they are. +type chunkProofs struct { + mu sync.Mutex + held map[string]chunkProof // by the file id a chunk names + reserved int // uploads under way that may add a proof + limit int + room chan struct{} // closed and replaced when room may have been made +} + +type chunkProof struct { + auth string + expires time.Time // zero when the proof does not say +} + +func newChunkProofs(limit int) *chunkProofs { + return &chunkProofs{held: make(map[string]chunkProof), limit: limit, room: make(chan struct{})} +} + +// reserve makes room for the proofs of an upload of n file ids before it is +// assigned, waiting up to chunkProofWait for commits to release some. +func (p *chunkProofs) reserve(n int) error { + if p == nil { + return nil + } + if n > p.limit { + return fmt.Errorf("an upload of %d file ids needs more assignment proofs than the %d a mount keeps", n, p.limit) + } + deadline := time.Now().Add(chunkProofWait) + logged := false + p.mu.Lock() + defer p.mu.Unlock() + for len(p.held)+p.reserved+n > p.limit { + if p.dropExpiredLocked() { + continue + } + wait := time.Until(deadline) + if wait <= 0 { + return fmt.Errorf("%d uploaded chunks still wait for their entries to be stored: no room to keep another assignment proof", len(p.held)) + } + if !logged { + logged = true + glog.V(0).Infof("%d uploaded chunks still wait for their entries to be stored: the next upload waits for a commit", len(p.held)) + } + room := p.room + p.mu.Unlock() + timer := time.NewTimer(wait) + select { + case <-room: + case <-timer.C: + } + timer.Stop() + p.mu.Lock() + } + p.reserved += n + return nil +} + +// keep ends the reservation of n file ids made for an upload that stored its +// data under fileId, and keeps the proof the filer returned for them. An +// empty proof keeps nothing: the filer did not ask for one. +func (p *chunkProofs) keep(fileId, auth string, n int) { + if p == nil { + return + } + covered := n + var expires time.Time + if claims, ok := security.AssignProofClaims(security.EncodedJwt(auth)); ok { + if claims.ExpiresAt != nil { + expires = claims.ExpiresAt.Time + } + // A proof covers fileId and fileId_1 up to its count. + if int(claims.Count) < covered { + covered = int(claims.Count) + } + } + p.mu.Lock() + defer p.mu.Unlock() + p.reserved -= n + if auth != "" { + for i := 0; i < covered; i++ { + fid := fileId + if i > 0 { + fid = fmt.Sprintf("%s_%d", fileId, i) + } + p.held[fid] = chunkProof{auth: auth, expires: expires} + } + } + p.signalLocked() +} + +// unreserve ends the reservation of n file ids made for a failed upload. +func (p *chunkProofs) unreserve(n int) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + p.reserved -= n + p.signalLocked() +} + +// attach adds to *auth the proof of each chunk the store holds one for, and +// reports whether there was any. It writes nothing once *auth carries them, +// so a request already handed to a send that is still in flight can be +// attached to again for its retry: the proofs of the chunks a request names +// are kept before the request is built. +func (p *chunkProofs) attach(chunks []*filer_pb.FileChunk, auth *map[string]string) (held bool) { + if p == nil || len(chunks) == 0 { + return false + } + p.mu.Lock() + defer p.mu.Unlock() + if len(p.held) == 0 { + return false + } + for _, chunk := range chunks { + fid := chunk.GetFileIdString() + proof, ok := p.held[fid] + if !ok { + continue + } + held = true + if current, ok := (*auth)[fid]; ok && current == proof.auth { + continue + } + if *auth == nil { + *auth = make(map[string]string) + } + (*auth)[fid] = proof.auth + } + return held +} + +// release drops the proofs of chunks once a filer acknowledged an entry that +// names them: it holds the chunks now and asks for no proof again. +func (p *chunkProofs) release(chunks []*filer_pb.FileChunk) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + released := false + for _, chunk := range chunks { + fid := chunk.GetFileIdString() + if _, ok := p.held[fid]; ok { + delete(p.held, fid) + released = true + } + } + if released { + p.signalLocked() + } +} + +// count reports how many file ids have a proof kept. +func (p *chunkProofs) count() int { + if p == nil { + return 0 + } + p.mu.Lock() + defer p.mu.Unlock() + return len(p.held) +} + +func (p *chunkProofs) dropExpiredLocked() (dropped bool) { + now := time.Now() + for fid, proof := range p.held { + if !proof.expires.IsZero() && now.After(proof.expires.Add(chunkProofExpiryGrace)) { + delete(p.held, fid) + dropped = true + } + } + return dropped +} + +func (p *chunkProofs) signalLocked() { + close(p.room) + p.room = make(chan struct{}) +} + +// requestChunks returns the chunks a filer request stores and the map their +// proofs go in, or nil for a request that stores none. +func requestChunks(req any) ([]*filer_pb.FileChunk, *map[string]string) { + switch r := req.(type) { + case *filer_pb.CreateEntryRequest: + return r.GetEntry().GetChunks(), &r.ChunkAuth + case *filer_pb.UpdateEntryRequest: + return r.GetEntry().GetChunks(), &r.ChunkAuth + case *filer_pb.AppendToEntryRequest: + return r.GetChunks(), &r.ChunkAuth + } + return nil, nil +} + +// stored reports whether reply acknowledges that the filer stored the +// request's entry. A create reports a refused condition in its reply. +func stored(reply any) bool { + if r, ok := reply.(*filer_pb.CreateEntryResponse); ok { + return r.GetError() == "" && r.GetErrorCode() == filer_pb.FilerError_OK + } + return true +} + +// conn attaches the kept proofs to every unary create, update and append the +// mount sends through cc, on each attempt, and releases them once the filer +// acknowledged the request. +func (p *chunkProofs) conn(cc grpc.ClientConnInterface) grpc.ClientConnInterface { + if p == nil { + return cc + } + return &chunkProofConn{ClientConnInterface: cc, proofs: p} +} + +type chunkProofConn struct { + grpc.ClientConnInterface + proofs *chunkProofs +} + +func (c *chunkProofConn) Invoke(ctx context.Context, method string, args, reply any, opts ...grpc.CallOption) error { + chunks, auth := requestChunks(args) + held := auth != nil && c.proofs.attach(chunks, auth) + err := c.ClientConnInterface.Invoke(ctx, method, args, reply, opts...) + if err == nil && held && stored(reply) { + c.proofs.release(chunks) + } + return err +} diff --git a/weed/mount/chunk_proofs_test.go b/weed/mount/chunk_proofs_test.go new file mode 100644 index 0000000000..877df5e11e --- /dev/null +++ b/weed/mount/chunk_proofs_test.go @@ -0,0 +1,763 @@ +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) + } +} diff --git a/weed/mount/weedfs.go b/weed/mount/weedfs.go index 28328f3da9..f2856dbdb4 100644 --- a/weed/mount/weedfs.go +++ b/weed/mount/weedfs.go @@ -164,6 +164,9 @@ type Option struct { type WFS struct { readAuth *ReadAuth + // chunkProofs keeps the assignment proofs of uploaded chunks until their + // entries are stored; nil without a filer token, which gets none. + chunkProofs *chunkProofs // Metadata-only refusal token, detached at final Forget; no live resources retained. writebackContentErrors sync.Map // https://dl.acm.org/doi/fullHtml/10.1145/3310148 @@ -324,6 +327,10 @@ func NewSeaweedFileSystem(option *Option) *WFS { dirIdleEvict: dirIdleEvict, } + if option.FilerTokenSource != nil { + wfs.chunkProofs = newChunkProofs(chunkProofLimit) + } + // With writeback caching, this mount is the single writer. Increase kernel // FUSE cache TTLs so the kernel doesn't re-issue Lookup/GetAttr for every // path component and stat — the local meta cache is authoritative. diff --git a/weed/mount/weedfs_file_sync.go b/weed/mount/weedfs_file_sync.go index 4f72c6dc81..9f7407a2a0 100644 --- a/weed/mount/weedfs_file_sync.go +++ b/weed/mount/weedfs_file_sync.go @@ -377,7 +377,7 @@ func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, n // no chunk deleter here: a failed fold reports the blobs it saved unfolded := chunks - chunks, manifestErr := filer.MaybeManifestize(wfs.saveDataAsChunk(fileFullPath), nil, chunks) + chunks, manifestErr := wfs.maybeManifestize(fileFullPath, chunks) if manifestErr != nil { // not good, but should be ok glog.V(0).Infof("MaybeManifestize: %v", manifestErr) diff --git a/weed/mount/weedfs_filer_token.go b/weed/mount/weedfs_filer_token.go index 3c144e9f94..41659a8ec1 100644 --- a/weed/mount/weedfs_filer_token.go +++ b/weed/mount/weedfs_filer_token.go @@ -76,3 +76,15 @@ func filerTokenExpiry(token security.EncodedJwt) time.Time { } return time.Time{} } + +// filerTokenScoped reports whether the filer scopes the mount's current +// token, as it does one with path grants or a method list. A token that +// cannot be read or decoded counts as scoped. +func (wfs *WFS) filerTokenScoped() bool { + token, err := wfs.option.FilerTokenSource(context.Background()) + if err != nil { + return true + } + claims, ok := security.FilerTokenClaims(token) + return !ok || claims.IsScoped() || len(claims.AllowedMethods) > 0 +} diff --git a/weed/mount/weedfs_metadata_flush.go b/weed/mount/weedfs_metadata_flush.go index b697b439a3..4daa8e22a9 100644 --- a/weed/mount/weedfs_metadata_flush.go +++ b/weed/mount/weedfs_metadata_flush.go @@ -156,7 +156,7 @@ func (wfs *WFS) flushFileMetadata(fh *FileHandle) error { // Try to create manifest chunks for large files // no chunk deleter here: a failed fold reports the blobs it saved unfolded := compactedChunks - compactedChunks, manifestErr := filer.MaybeManifestize(wfs.saveDataAsChunk(fileFullPath), nil, compactedChunks) + compactedChunks, manifestErr := wfs.maybeManifestize(fileFullPath, compactedChunks) if manifestErr != nil { glog.V(0).Infof("flushFileMetadata MaybeManifestize: %v", manifestErr) } diff --git a/weed/mount/weedfs_stream_mutate.go b/weed/mount/weedfs_stream_mutate.go index a5fe00c605..555235834e 100644 --- a/weed/mount/weedfs_stream_mutate.go +++ b/weed/mount/weedfs_stream_mutate.go @@ -102,14 +102,22 @@ func newStreamMutateMux(wfs *WFS) *streamMutateMux { } // CreateEntry sends a CreateEntryRequest over the stream and waits for the response. +// The request carries the assignment proofs of the new chunks it stores, +// released once the filer acknowledged it. func (m *streamMutateMux) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) { + proofs := m.wfs.chunkProofs + held := proofs.attach(req.GetEntry().GetChunks(), &req.ChunkAuth) resp, err := m.doUnary(ctx, &filer_pb.StreamMutateEntryRequest{ Request: &filer_pb.StreamMutateEntryRequest_CreateRequest{CreateRequest: req}, }) if err != nil { return nil, err } - return createEntryFromResponse(resp, req) + cr, err := createEntryFromResponse(resp, req) + if err == nil && held { + proofs.release(req.GetEntry().GetChunks()) + } + return cr, err } // createEntryFromResponse unwraps a create's nested response, mapping its @@ -146,7 +154,10 @@ func createEntryFromResponse(resp *filer_pb.StreamMutateEntryResponse, req *file } // UpdateEntry sends an UpdateEntryRequest over the stream and waits for the response. +// Proofs are attached and released as for CreateEntry. func (m *streamMutateMux) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) { + proofs := m.wfs.chunkProofs + held := proofs.attach(req.GetEntry().GetChunks(), &req.ChunkAuth) resp, err := m.doUnary(ctx, &filer_pb.StreamMutateEntryRequest{ Request: &filer_pb.StreamMutateEntryRequest_UpdateRequest{UpdateRequest: req}, }) @@ -154,6 +165,9 @@ func (m *streamMutateMux) UpdateEntry(ctx context.Context, req *filer_pb.UpdateE return nil, err } if r, ok := resp.Response.(*filer_pb.StreamMutateEntryResponse_UpdateResponse); ok { + if held { + proofs.release(req.GetEntry().GetChunks()) + } return r.UpdateResponse, nil } return nil, fmt.Errorf("unexpected response type %T", resp.Response) diff --git a/weed/mount/weedfs_write.go b/weed/mount/weedfs_write.go index de8282cac8..ff5565020c 100644 --- a/weed/mount/weedfs_write.go +++ b/weed/mount/weedfs_write.go @@ -25,6 +25,18 @@ func (wfs *WFS) shouldCacheUploadedChunk(offset int64) bool { return wfs.chunkCache != nil && (offset == 0 || wfs.peerAnnouncer != nil || wfs.readAuth != nil) } +// maybeManifestize folds a file's chunks into manifests as +// filer.MaybeManifestize does, except on a mount with a scoped filer token: a +// filer serving a scoped token stores no new chunk in an entry that holds +// manifests, so every later write to a folded file would be refused. Such a +// mount keeps chunk lists flat. +func (wfs *WFS) maybeManifestize(fullPath util.FullPath, chunks []*filer_pb.FileChunk) ([]*filer_pb.FileChunk, error) { + if wfs.chunkProofs != nil && wfs.filerTokenScoped() { + return chunks, nil + } + return filer.MaybeManifestize(wfs.saveDataAsChunk(fullPath), nil, chunks) +} + func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFunctionType { // Backstop: FUSE entry points sanitize names before they reach @@ -56,6 +68,12 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun } } + // A filer serving a scoped token stores the chunk only with the + // assignment proof it returns, so make room to keep it first. + if err = wfs.chunkProofs.reserve(1); err != nil { + glog.V(0).Infof("upload data %v: %v", filename, err) + return nil, fmt.Errorf("upload data: %w", err) + } fileId, uploadResult, err, data := uploader.UploadWithRetry( wfs, &filer_pb.AssignVolumeRequest{ @@ -71,13 +89,16 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun ) if err != nil { + wfs.chunkProofs.unreserve(1) glog.V(0).Infof("upload data %v: %v", filename, err) return nil, fmt.Errorf("upload data: %w", err) } if uploadResult.Error != "" { + wfs.chunkProofs.unreserve(1) glog.V(0).Infof("upload failure %v: %v", filename, err) return nil, fmt.Errorf("upload result: %v", uploadResult.Error) } + wfs.chunkProofs.keep(fileId, uploadResult.AssignAuth, 1) // shouldCacheUploadedChunk explains when and why every uploaded // chunk is cached (peer sharing, and read-auth read-after-write). diff --git a/weed/mount/wfs_filer_client.go b/weed/mount/wfs_filer_client.go index ec615eb1d6..5b57fc48ef 100644 --- a/weed/mount/wfs_filer_client.go +++ b/weed/mount/wfs_filer_client.go @@ -155,9 +155,10 @@ func (wfs *WFS) callFiler(ctx context.Context, streamingMode bool, callWait time // newFilerClient authorizes each call through the client with the mount's // filer token source, resolved per attempt so a retry carries a replaced -// token. The cached channel itself carries no identity. +// token. The cached channel itself carries no identity. Creates and updates +// carry the assignment proofs of the new chunks they store. func (wfs *WFS) newFilerClient(conn *grpc.ClientConn) filer_pb.SeaweedFilerClient { - return filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, wfs.option.FilerTokenSource)) + return filer_pb.NewSeaweedFilerClient(wfs.chunkProofs.conn(security.WithFilerClientAuth(conn, wfs.option.FilerTokenSource))) } func (wfs *WFS) AdjustedUrl(location *filer_pb.Location) string { diff --git a/weed/operation/upload_content.go b/weed/operation/upload_content.go index 69f9bcfa1c..c63737141e 100644 --- a/weed/operation/upload_content.go +++ b/weed/operation/upload_content.go @@ -90,6 +90,11 @@ type UploadResult struct { Gzip uint32 `json:"gzip,omitempty"` ContentMd5 string `json:"contentMd5,omitempty"` RetryCount int `json:"-"` + // AssignAuth is the assignment proof a filer returned with the volume + // assignment UploadWithRetry stored the data under, empty when it sent + // none. A filer serving a scoped token stores the chunk in an entry only + // when the request presents this proof in chunk_auth. + AssignAuth string `json:"-"` } func (uploadResult *UploadResult) ToPbFileChunk(fileId string, offset int64, tsNs int64) *filer_pb.FileChunk { @@ -368,7 +373,11 @@ func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assi uploadOption.Md5 = base64.StdEncoding.EncodeToString(util.Md5For(uploadOption.Digest, data)) } + // Each attempt may assign a new file id; only the proof of the one the + // data was finally stored under is returned. + var assignAuth string fileId, uploadResult, err = uploader.uploadWithRetryData(func() (fileId string, host string, auth security.EncodedJwt, fsync bool, err error) { + assignAuth = "" // grpc assign volume if grpcAssignErr := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { assignCtx, assignCancel := context.WithTimeout(context.Background(), assignVolumeTimeout) @@ -383,6 +392,7 @@ func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assi } fileId, auth = resp.FileId, security.EncodedJwt(resp.Auth) + assignAuth = resp.AssignAuth fsync = resp.Fsync loc := resp.Location host = filerClient.AdjustedUrl(loc) @@ -393,6 +403,9 @@ func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assi } return }, uploadOption, data) + if err == nil && uploadResult != nil { + uploadResult.AssignAuth = assignAuth + } return } diff --git a/weed/operation/upload_content_test.go b/weed/operation/upload_content_test.go index 6e6202f183..980da3a269 100644 --- a/weed/operation/upload_content_test.go +++ b/weed/operation/upload_content_test.go @@ -1441,3 +1441,57 @@ func TestIsUploadBackpressure(t *testing.T) { } } } + +// assignSequenceClient answers each AssignVolume with the next response. +type assignSequenceClient struct { + filer_pb.SeaweedFilerClient + responses []*filer_pb.AssignVolumeResponse + calls int +} + +func (c *assignSequenceClient) AssignVolume(context.Context, *filer_pb.AssignVolumeRequest, ...grpc.CallOption) (*filer_pb.AssignVolumeResponse, error) { + resp := c.responses[c.calls] + c.calls++ + return resp, nil +} + +func (c *assignSequenceClient) WithFilerClient(_ bool, fn func(filer_pb.SeaweedFilerClient) error) error { + return fn(c) +} +func (c *assignSequenceClient) AdjustedUrl(loc *filer_pb.Location) string { return loc.GetUrl() } +func (c *assignSequenceClient) GetDataCenter() string { return "" } + +// The result carries the assignment proof of the file id the data was stored +// under, never one of an assignment the upload abandoned. +func TestUploadWithRetryReturnsProofOfFinalAssignment(t *testing.T) { + for _, tc := range []struct { + name string + secondProof string + }{ + {name: "reassigned with a proof", secondProof: "proof-second"}, + {name: "reassigned without a proof", secondProof: ""}, + } { + t.Run(tc.name, func(t *testing.T) { + failed := scriptedHTTPResponse{status: http.StatusInternalServerError, body: `{"error":"volume down"}`} + httpClient := &scriptedHTTPClient{responses: map[string][]scriptedHTTPResponse{ + "http://volume-a/1,first": {failed, failed, failed}, + "http://volume-b/2,second": {{status: http.StatusCreated, body: `{"size":3}`}}, + }} + client := &assignSequenceClient{responses: []*filer_pb.AssignVolumeResponse{ + {FileId: "1,first", Count: 1, Location: &filer_pb.Location{Url: "volume-a"}, AssignAuth: "proof-first"}, + {FileId: "2,second", Count: 1, Location: &filer_pb.Location{Url: "volume-b"}, AssignAuth: tc.secondProof}, + }} + fileID, result, err, _ := newUploader(httpClient).UploadWithRetry(client, + &filer_pb.AssignVolumeRequest{Count: 1, Path: "/dir/file"}, &UploadOption{}, strings.NewReader("abc")) + if err != nil { + t.Fatalf("upload: %v", err) + } + if fileID != "2,second" || client.calls != 2 { + t.Fatalf("file id %s after %d assignments, want 2,second after 2", fileID, client.calls) + } + if result.AssignAuth != tc.secondProof { + t.Fatalf("assignment proof = %q, want %q", result.AssignAuth, tc.secondProof) + } + }) + } +} diff --git a/weed/security/jwt.go b/weed/security/jwt.go index 91946b868c..c76bd3fb4b 100644 --- a/weed/security/jwt.go +++ b/weed/security/jwt.go @@ -315,6 +315,17 @@ func VerifyAssignJwt(filerKey, previousFilerKey SigningKey, token EncodedJwt, fi uint64(requested.Key-base.Key) < uint64(claims.Count) } +// AssignProofClaims decodes an assignment proof's claims without verifying +// it. A client holding a proof uses them to learn when the proof expires and +// how many file ids it covers; only the filer verifies the proof. +func AssignProofClaims(token EncodedJwt) (*SeaweedAssignClaims, bool) { + claims := &SeaweedAssignClaims{} + if _, _, err := jwt.NewParser().ParseUnverified(string(token), claims); err != nil { + return nil, false + } + return claims, true +} + // FilerJwtProvider signs the credential a filer's HTTP API expects. A nil // provider means the process-wide jwt.filer_signing configuration applies. type FilerJwtProvider func(isWrite bool) EncodedJwt