diff --git a/weed/mount/inline_content.go b/weed/mount/inline_content.go new file mode 100644 index 0000000000..049265dc9a --- /dev/null +++ b/weed/mount/inline_content.go @@ -0,0 +1,83 @@ +package mount + +import ( + "bytes" + "fmt" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" +) + +// A small file the filer keeps inside its entry (-saveToFilerLimit, or +// ?saveInside=true on the upload) has its bytes in the entry's content and no +// chunks. What a mount writes becomes chunks, so the content has to become +// one as well before the first change of the file's data: dropped instead, +// the bytes a write left alone read as zeros from then on. A change of the +// file's size cuts the content, or makes it a chunk for the bytes after it to +// read as zeros. + +// inlineContent returns the bytes of entry's content that are the file's: a +// mount from before this may have cut the file's size and left the content. +func inlineContent(entry *filer_pb.Entry) []byte { + content := entry.GetContent() + if size := entry.GetAttributes().GetFileSize(); uint64(len(content)) > size { + content = content[:size] + } + return content +} + +// bufferInlineContent turns the content of the handle's entry into a write of +// the handle's own, older than one at tsNs, and takes it out of the entry. +// The flush stores it as a chunk with what else the handle wrote. The caller +// holds the handle's lock for writing. +func (fh *FileHandle) bufferInlineContent(entry *filer_pb.Entry, tsNs int64) error { + if len(entry.GetContent()) == 0 { + return nil + } + if content := inlineContent(entry); len(content) > 0 { + buffered, err := fh.dirtyPages.AddPage(0, content, true, tsNs-1) + if err == nil && buffered < int64(len(content)) { + err = fmt.Errorf("buffered %d of %d bytes", buffered, len(content)) + } + if err != nil { + return fmt.Errorf("inline content of %s: %w", fh.FullPath(), err) + } + fh.pageWrites.Add(1) + } + entry.Content = nil + fh.dirtyMetadata, fh.dirtyContent = true, true + return nil +} + +// resizeInlineContent gets entry's content ready for the file's size to +// become size: cut to it, or, when the file grows past the content, stored +// with save in chunks of chunkSize as buffered writes are, for the bytes after +// it to read as zeros. chunked reports that entry has chunks more. +func resizeInlineContent(entry *filer_pb.Entry, size uint64, tsNs int64, chunkSize int64, save filer.SaveDataAsChunkFunctionType) (chunked bool, err error) { + if len(entry.GetContent()) == 0 { + return false, nil + } + content := inlineContent(entry) + if size <= uint64(len(content)) { + if entry.Content = content[:size]; size == 0 { + entry.Content = nil + } + return false, nil + } + var chunks []*filer_pb.FileChunk + for offset := int64(0); offset < int64(len(content)); { + n := int64(len(content)) - offset + if chunkSize > 0 && n > chunkSize { + n = chunkSize + } + chunk, err := save(bytes.NewReader(content[offset:offset+n]), entry.GetName(), offset, tsNs, uint64(n)) + if err != nil { + return false, fmt.Errorf("inline content of %s: %w", entry.GetName(), err) + } + chunks = append(chunks, chunk) + offset += n + } + entry.Chunks = append(entry.Chunks, chunks...) + entry.Content = nil + return len(chunks) > 0, nil +} diff --git a/weed/mount/inline_content_test.go b/weed/mount/inline_content_test.go new file mode 100644 index 0000000000..a04fd2e598 --- /dev/null +++ b/weed/mount/inline_content_test.go @@ -0,0 +1,279 @@ +//go:build !freebsd + +package mount + +import ( + "bytes" + "context" + "errors" + "io" + "sort" + "strings" + "syscall" + "testing" + + "github.com/seaweedfs/go-fuse/v2/fuse" + "google.golang.org/protobuf/proto" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +const inlineTestContent = "0123456789" + +// openInlineFile opens /dir/file, which the filer keeps inside its entry, on a +// mount of a filer that stores what the mount sends it. +func openInlineFile(t *testing.T) (*WFS, uint64, *g6ConditionalPeer) { + t.Helper() + base := &filer_pb.Entry{ + Name: "file", + Content: []byte(inlineTestContent), + Attributes: &filer_pb.FuseAttributes{ + Inode: 42, Uid: 2000, Gid: 20, FileMode: 0644, FileSize: uint64(len(inlineTestContent)), Mtime: 10, + }, + CommitTsNs: 100, + } + peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry), blobs: make(map[string][]byte)} + + w := newInvalidateTestWFS(t) + w.option.CacheDirForWrite = t.TempDir() + w.option.DefaultPermissions = true + w.posixLocks = NewPosixLockTable() + w.option.ConcurrentWriters = 1 + w.concurrentWriters = util.NewLimitedConcurrentExecutor(1) + startFakeFiler(t, w, peer) + w.inodeToPath.Lookup("/dir", 1, true, false, 0, false) + w.inodeToPath.Lookup("/dir/file", 1, false, false, 42, true) + w.inodeToPath.MarkChildrenCached("/dir") + if err := w.metaCache.InsertEntry(context.Background(), filer.FromPbEntry("/dir", proto.Clone(base).(*filer_pb.Entry)), 1); err != nil { + t.Fatal(err) + } + out := &fuse.OpenOut{} + if code := w.Open(nil, &fuse.OpenIn{InHeader: fuse.InHeader{NodeId: 42}, Flags: syscall.O_RDWR}, out); code != fuse.OK { + t.Fatalf("open: %v", code) + } + g6AppendUploader(t, w.GetHandle(FileHandleId(out.Fh)), 100, peer) + return w, out.Fh, peer +} + +// storedInlineFile flushes the handle and returns the file as the filer has +// it then: its content while that is all of it, else its chunks, the later +// over the earlier. +func storedInlineFile(t *testing.T, w *WFS, handle uint64, peer *g6ConditionalPeer) []byte { + t.Helper() + if code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle}); code != fuse.OK { + t.Fatalf("fsync: %v", code) + } + peer.mu.Lock() + defer peer.mu.Unlock() + entry := peer.entry + size := entry.GetAttributes().GetFileSize() + if len(entry.Content) > 0 { + if len(entry.Chunks) > 0 || uint64(len(entry.Content)) != size { + t.Fatalf("stored with %d bytes of content next to %d chunks and a size of %d", len(entry.Content), len(entry.Chunks), size) + } + return entry.Content + } + chunks := append([]*filer_pb.FileChunk(nil), entry.Chunks...) + sort.SliceStable(chunks, func(i, j int) bool { return chunks[i].ModifiedTsNs < chunks[j].ModifiedTsNs }) + stored := make([]byte, size) + for _, c := range chunks { + body, ok := peer.blobs[c.GetFileIdString()] + if !ok || uint64(len(body)) < c.Size || c.Offset < 0 || uint64(c.Offset)+c.Size > size { + t.Fatalf("stored chunk %v of a file of %d bytes has %d bytes behind it", c, size, len(body)) + } + copy(stored[c.Offset:], body[:c.Size]) + } + return stored +} + +func writeInlineFile(t *testing.T, w *WFS, handle, offset uint64, data string) { + t.Helper() + n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle, Offset: offset, Size: uint32(len(data))}, []byte(data)) + if code != fuse.OK || n != uint32(len(data)) { + t.Fatalf("write %q at %d: %d %v", data, offset, n, code) + } +} + +func resizeInlineFile(t *testing.T, w *WFS, size uint64) { + t.Helper() + in := &fuse.SetAttrIn{} + in.NodeId, in.Valid, in.Size = 42, fuse.FATTR_SIZE, size + if code := w.SetAttr(nil, in, &fuse.AttrOut{}); code != fuse.OK { + t.Fatalf("set size %d: %v", size, code) + } +} + +// A write to a file whose bytes are inside its entry used to drop them all: +// the entry is published with the write's chunk and without its content, so +// what the write did not cover read as zeros. +func TestWriteToInlineFileKeepsTheBytesItLeavesAlone(t *testing.T) { + for _, tc := range []struct { + name string + offset uint64 + data string + want string + }{ + {"an append", 10, "XY", "0123456789XY"}, + {"in the middle", 3, "AB", "012AB56789"}, + {"at the start", 0, "Z", "Z123456789"}, + {"past the end", 12, "Q", "0123456789\x00\x00Q"}, + {"all of it", 0, "abcdefghijkl", "abcdefghijkl"}, + } { + t.Run(tc.name, func(t *testing.T) { + w, handle, peer := openInlineFile(t) + writeInlineFile(t, w, handle, tc.offset, tc.data) + + // read back through the handle before anything is stored + buff := make([]byte, len(tc.want)) + if n, err := readDataByFileHandle(buff, w.GetHandle(FileHandleId(handle)), 0); err != nil || string(buff[:n]) != tc.want { + t.Fatalf("the handle reads %q (%v), want %q", buff[:n], err, tc.want) + } + if got := storedInlineFile(t, w, handle, peer); string(got) != tc.want { + t.Fatalf("stored %q, want %q", got, tc.want) + } + }) + } +} + +// Content shorter than the file reads no further than itself, on the mount +// and through the filer, so a file that grows has it stored as a chunk. +func TestFallocateOfInlineFileKeepsItsContent(t *testing.T) { + w, handle, peer := openInlineFile(t) + if code := w.Fallocate(nil, &fuse.FallocateIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle, Offset: 0, Length: 16}); code != fuse.OK { + t.Fatalf("fallocate: %v", code) + } + want := inlineTestContent + "\x00\x00\x00\x00\x00\x00" + if got := storedInlineFile(t, w, handle, peer); string(got) != want { + t.Fatalf("stored %q, want %q", got, want) + } +} + +// A size below the content cuts it. Left as it was, the bytes cut off came +// back when the file grew again. +func TestShrinkingAnInlineFileCutsItsContent(t *testing.T) { + w, handle, peer := openInlineFile(t) + resizeInlineFile(t, w, 4) + if got := storedInlineFile(t, w, handle, peer); string(got) != "0123" { + t.Fatalf("stored %q, want %q", got, "0123") + } + + writeInlineFile(t, w, handle, 8, "W") + if got, want := storedInlineFile(t, w, handle, peer), "0123\x00\x00\x00\x00W"; string(got) != want { + t.Fatalf("stored %q after a write past the cut, want %q", got, want) + } + + resizeInlineFile(t, w, 0) + if got := storedInlineFile(t, w, handle, peer); len(got) != 0 { + t.Fatalf("stored %q after a cut to nothing", got) + } +} + +// The bytes a copy does not reach stay, in a destination kept inside its entry. +func TestCopyFileRangeIntoInlineFileKeepsItsContent(t *testing.T) { + wfs := newCopyRangeTestWFS() + open := func(name, content string) *FileHandle { + path := util.FullPath("/" + name) + inode := wfs.inodeToPath.Lookup(path, 1, false, false, 0, true) + fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{ + Name: name, + Content: []byte(content), + Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: uint64(len(content)), Inode: inode}, + }, 0, 0) + fh.RememberPath(path) + t.Cleanup(fh.dirtyPages.Destroy) + return fh + } + src, dst := open("src", "abcdef"), open("dst", inlineTestContent) + + written, code := wfs.CopyFileRange(nil, &fuse.CopyFileRangeIn{FhIn: uint64(src.fh), FhOut: uint64(dst.fh), OffIn: 1, OffOut: 4, Len: 3}) + if code != fuse.OK || written != 3 { + t.Fatalf("copy: %d %v", written, code) + } + buff := make([]byte, len(inlineTestContent)) + if n, err := readDataByFileHandle(buff, dst, 0); err != nil || string(buff[:n]) != "0123bcd789" { + t.Fatalf("the destination reads %q (%v), want %q", buff[:n], err, "0123bcd789") + } + if content := dst.GetEntry().GetEntry().GetContent(); len(content) != 0 { + t.Fatalf("the destination's entry still has %q inside it", content) + } +} + +func TestResizeInlineContent(t *testing.T) { + entry := func(content string, size uint64) *filer_pb.Entry { + return &filer_pb.Entry{Name: "file", Content: []byte(content), Attributes: &filer_pb.FuseAttributes{FileSize: size}} + } + var saved []string + save := func(r io.Reader, _ string, offset, tsNs int64, expected uint64) (*filer_pb.FileChunk, error) { + body, err := io.ReadAll(r) + if err != nil { + return nil, err + } + if uint64(len(body)) != expected { + t.Fatalf("saving %d bytes announced as %d", len(body), expected) + } + saved = append(saved, string(body)) + return &filer_pb.FileChunk{FileId: "3,01", Offset: offset, Size: uint64(len(body)), ModifiedTsNs: tsNs}, nil + } + for _, tc := range []struct { + name string + entry *filer_pb.Entry + size uint64 + wantContent string + wantSaved []string + }{ + // in chunks of 4 bytes + {"cut", entry(inlineTestContent, 10), 4, "0123", nil}, + {"cut to nothing", entry(inlineTestContent, 10), 0, "", nil}, + {"the same size", entry(inlineTestContent, 10), 10, inlineTestContent, nil}, + {"grown", entry(inlineTestContent, 10), 16, "", []string{"0123", "4567", "89"}}, + // an older mount cut the size and left the content + {"grown after an old cut", entry(inlineTestContent, 4), 16, "", []string{"0123"}}, + {"the size of the content after an old cut", entry(inlineTestContent, 4), 10, "", []string{"0123"}}, + {"grown from nothing", entry(inlineTestContent, 0), 16, "", nil}, + {"no content", entry("", 10), 16, "", nil}, + } { + t.Run(tc.name, func(t *testing.T) { + saved = nil + chunked, err := resizeInlineContent(tc.entry, tc.size, 7, 4, save) + if err != nil { + t.Fatal(err) + } + if string(tc.entry.Content) != tc.wantContent { + t.Fatalf("content %q, want %q", tc.entry.Content, tc.wantContent) + } + if strings.Join(saved, "|") != strings.Join(tc.wantSaved, "|") { + t.Fatalf("saved %q as chunks, want %q", saved, tc.wantSaved) + } + if chunked != (len(tc.wantSaved) > 0) || len(tc.entry.Chunks) != len(tc.wantSaved) { + t.Fatalf("chunked=%v with %d chunks, want %d", chunked, len(tc.entry.Chunks), len(tc.wantSaved)) + } + var offset int64 + for i, chunk := range tc.entry.Chunks { + if chunk.Offset != offset || chunk.ModifiedTsNs != 7 { + t.Fatalf("chunk %d: %v, want it at %d with the time given", i, chunk, offset) + } + offset += int64(chunk.Size) + } + }) + } + + t.Run("not saved", func(t *testing.T) { + e := entry(inlineTestContent, 10) + refused := errors.New("no volume to write to") + var saves int + _, err := resizeInlineContent(e, 16, 7, 4, func(_ io.Reader, _ string, offset int64, _ int64, n uint64) (*filer_pb.FileChunk, error) { + if saves++; saves == 2 { + return nil, refused + } + return &filer_pb.FileChunk{FileId: "3,01", Offset: offset, Size: n}, nil + }) + if !errors.Is(err, refused) { + t.Fatalf("err %v, want the save's", err) + } + if !bytes.Equal(e.Content, []byte(inlineTestContent)) || len(e.Chunks) != 0 { + t.Fatalf("content %q and %d chunks after a save that failed", e.Content, len(e.Chunks)) + } + }) +} diff --git a/weed/mount/weedfs_attr.go b/weed/mount/weedfs_attr.go index b1b7f9eacc..b5ee331a56 100644 --- a/weed/mount/weedfs_attr.go +++ b/weed/mount/weedfs_attr.go @@ -133,6 +133,15 @@ func (wfs *WFS) SetAttr(cancel <-chan struct{}, input *fuse.SetAttrIn, out *fuse // Invalidate the open-mtime cache so the next Open does not set // FOPEN_KEEP_CACHE with stale kernel page cache data. wfs.invalidateOpenMtimeCache(input.NodeId) + // Content inside the entry is cut to the new size, or stored as a + // chunk when the file grows past it. + if chunked, err := resizeInlineContent(entry, size, time.Now().UnixNano(), wfs.option.ChunkSizeLimit, wfs.saveDataAsChunk(path)); err != nil { + glog.Errorf("setattr %v size=%v: %v", path, size, err) + return writeErrorToFuseStatus(err) + } else if chunked && fh != nil { + fh.wfs.readAuth.Track(fh.FullPath(), entry.Chunks) + fh.entryChunkGroup.SetChunks(entry.Chunks) + } oldFileSize := filer.FileSize(entry) if size < oldFileSize { if fh != nil { diff --git a/weed/mount/weedfs_file_copy_range.go b/weed/mount/weedfs_file_copy_range.go index 3bf3e1ac5a..91c1ec9226 100644 --- a/weed/mount/weedfs_file_copy_range.go +++ b/weed/mount/weedfs_file_copy_range.go @@ -135,6 +135,11 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn) // We want to stream the copy operation to avoid allocating massive buffers. nowUnixNano := time.Now().UnixNano() + // The destination's bytes inside its entry, as a write before the copy. + if err := fhOut.bufferInlineContent(fhOut.entry.Entry, nowUnixNano); err != nil { + glog.Errorf("%v", err) + return 0, writeErrorToFuseStatus(err) + } totalCopied := int64(0) buff := wfs.copyBufferPool.Get().([]byte) defer wfs.copyBufferPool.Put(buff) @@ -213,7 +218,6 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn) totalCopied+int64(in.OffOut), int64(fhOut.entry.Attributes.FileSize), )) - fhOut.entry.Content = nil fhOut.dirtyMetadata = true written = uint32(totalCopied) diff --git a/weed/mount/weedfs_file_fallocate.go b/weed/mount/weedfs_file_fallocate.go index 755ca11a30..3ccf86ad83 100644 --- a/weed/mount/weedfs_file_fallocate.go +++ b/weed/mount/weedfs_file_fallocate.go @@ -54,12 +54,18 @@ func (wfs *WFS) Fallocate(cancel <-chan struct{}, in *fuse.FallocateIn) (code fu glog.V(4).Infof("Fallocate %s fh %d grow to %d", fh.FullPath(), fh.fh, newFileSize) + // Content inside the entry reads no further than itself: it becomes a + // write of the handle's, before the file grows past it. + now := time.Now() + if err := fh.bufferInlineContent(entry, now.UnixNano()); err != nil { + glog.Errorf("%v", err) + return writeErrorToFuseStatus(err) + } entry.Attributes.FileSize = newFileSize // The writes that fill the range will not grow the file, so they charge // nothing; the growth is counted here or the quota never sees it. wfs.AddUncommittedBytes(int64(newFileSize - oldFileSize)) - now := time.Now() entry.Attributes.Mtime = now.Unix() entry.Attributes.MtimeNs = int32(now.Nanosecond()) entry.Attributes.Ctime = now.Unix() diff --git a/weed/mount/weedfs_file_write.go b/weed/mount/weedfs_file_write.go index d62edeacfb..6bc3db22fa 100644 --- a/weed/mount/weedfs_file_write.go +++ b/weed/mount/weedfs_file_write.go @@ -68,6 +68,12 @@ func (wfs *WFS) Write(cancel <-chan struct{}, in *fuse.WriteIn, data []byte) (wr return 0, fuse.OK } + // The bytes the filer kept inside the entry, as a write before this one. + if err := fh.bufferInlineContent(entry.Entry, tsNs); err != nil { + glog.Errorf("%v", err) + return 0, writeErrorToFuseStatus(err) + } + // Size and times cover only the bytes buffered, or the next flush // publishes a hole where the data should be. A partly buffered write // is reported as a short write, or as an error to kernel writeback, @@ -90,7 +96,6 @@ func (wfs *WFS) Write(cancel <-chan struct{}, in *fuse.WriteIn, data []byte) (wr } fh.pendingAppend = true } - entry.Content = nil oldFileSize := int64(entry.Attributes.FileSize) newFileSize := max(offset+int64(len(data)), oldFileSize) entry.Attributes.FileSize = uint64(newFileSize)