sftp: copy only the stored bytes on a non-truncating open

A size set by a truncate that grows a file stores nothing, but opening
the file for writing without O_TRUNC copied its whole logical size into
the temp file as zeros. Copy up to the last stored byte and extend the
temp file to the size, which leaves the rest sparse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chris LuandClaude Opus 5.5 committed 2026-12-03 23:48:25 -08:00
1 parent f796077361
commit 8c45dc42a9
4 files changed
+66 -27

No files matched your search

+10 -9
View File
@@ -160,19 +160,21 @@ func TestCopyExistingContentIgnoresStaleRemoteSize(t *testing.T) {
}
}
// A file whose size is all holes still keeps its zeros.
// A size set past the stored bytes stores nothing, so there is nothing to
// copy: the caller keeps that hole sparse.
func TestCopyExistingContentAllHoles(t *testing.T) {
entries := map[string]*filer_pb.Entry{
"/home/holes.bin": chunkedEntry(10),
"/home/holes.bin": chunkedEntry(1 << 40),
"/home/grown.txt": {Attributes: &filer_pb.FuseAttributes{FileSize: 1 << 40}, Content: []byte("x")},
}
fs := newCopyTestServer(t, "", entries)
var dst bytes.Buffer
if _, err := fs.copyExistingContent("/home/holes.bin", &dst); err != nil {
t.Fatalf("all-holes file: %v", err)
if _, err := fs.copyExistingContent("/home/holes.bin", &dst); err != nil || dst.Len() != 0 {
t.Fatalf("all-holes file: err=%v written=%d, want nothing", err, dst.Len())
}
if dst.Len() != 10 || !bytes.Equal(dst.Bytes(), make([]byte, 10)) {
t.Fatalf("wrote %d bytes, want 10 zeros", dst.Len())
if _, err := fs.copyExistingContent("/home/grown.txt", &dst); err != nil || dst.String() != "x" {
t.Fatalf("grown inline file: err=%v written=%d, want only %q", err, dst.Len(), "x")
}
}
@@ -216,9 +218,8 @@ func TestCopyExistingContentTrailingGap(t *testing.T) {
if _, err := fs.copyExistingContent("/home/trailing.bin", &dst); err != nil {
t.Fatalf("copyExistingContent: %v", err)
}
want := append(append([]byte{}, chunkA...), make([]byte, 40)...)
if !bytes.Equal(dst.Bytes(), want) {
t.Fatalf("copied %d bytes, want %d with a zero-filled tail", dst.Len(), len(want))
if !bytes.Equal(dst.Bytes(), chunkA) {
t.Fatalf("copied %d bytes, want the %d stored ones", dst.Len(), len(chunkA))
}
}
+2 -1
View File
@@ -13,6 +13,7 @@ import (
"regexp"
"strings"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"golang.org/x/crypto/ssh"
@@ -168,7 +169,7 @@ func (fs *SftpServer) fileHash(ctx context.Context, kind, userPath string) (stri
return hex.EncodeToString(entry.Attributes.Md5), nil
}
h := newHash(kind)
if err := fs.writeContent(ctx, absPath, entry, ctxWriter{ctx, h}); err != nil {
if err := fs.writeContent(ctx, absPath, entry, int64(filer.FileSize(entry)), ctxWriter{ctx, h}); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
+26 -17
View File
@@ -201,10 +201,15 @@ func (fs *SftpServer) newFileWriter(r *sftp.Request) (io.WriterAt, error) {
return nil, err
}
}
// Without O_TRUNC the client writes into the existing file, so start from its current bytes.
// Without O_TRUNC the client writes into the existing file, so start from
// its current bytes. Past the stored ones it is a hole, kept sparse.
var existing *filer_pb.Entry
if !flags.Trunc && !exclusive {
if existing, err = fs.copyExistingContent(absPath, tmpFile); err != nil {
existing, err = fs.copyExistingContent(absPath, tmpFile)
if err == nil && existing != nil {
err = tmpFile.Truncate(int64(filer.FileSize(existing)))
}
if err != nil {
tmpFile.Close()
os.Remove(tmpFile.Name())
return nil, err
@@ -280,8 +285,8 @@ func (fs *SftpServer) checkWritable(absPath string) (*filer_pb.Entry, error) {
return entry, fs.checkEntryProtected(absPath, entry)
}
// copyExistingContent writes the file's content to dst and returns the entry
// it copied, or nil when there is no file.
// copyExistingContent writes the file's content up to its last stored byte
// to dst and returns the entry it copied, or nil when there is no file.
func (fs *SftpServer) copyExistingContent(absPath string, dst io.Writer) (*filer_pb.Entry, error) {
entry, err := fs.getEntry(absPath)
if err == os.ErrNotExist {
@@ -293,34 +298,38 @@ func (fs *SftpServer) copyExistingContent(absPath string, dst io.Writer) (*filer
if entry.IsDirectory {
return nil, nil
}
return entry, fs.writeContent(context.Background(), absPath, entry, dst)
return entry, fs.writeContent(context.Background(), absPath, entry, storedSize(entry), dst)
}
// writeContent writes the file's whole logical content to dst: inline bytes,
// then chunks, with zeros for the gaps and tail no chunk stores.
func (fs *SftpServer) writeContent(ctx context.Context, absPath string, entry *filer_pb.Entry, dst io.Writer) error {
size := int64(filer.FileSize(entry))
// storedSize is where the file's last stored byte ends. A size set past it,
// as a truncate that grows the file does, stores nothing.
func storedSize(entry *filer_pb.Entry) int64 {
stored := filer.TotalSize(entry.GetChunks())
if len(entry.Content) > 0 {
stored = uint64(len(entry.Content))
}
return int64(min(stored, filer.FileSize(entry)))
}
// writeContent writes the first size bytes of the file's logical content to
// dst: inline bytes, then chunks, with zeros for the gaps no chunk stores.
func (fs *SftpServer) writeContent(ctx context.Context, absPath string, entry *filer_pb.Entry, size int64, dst io.Writer) error {
remote := entry.GetRemoteEntry()
if len(entry.Content) == 0 && len(entry.GetChunks()) == 0 {
if remote != nil && remote.RemoteSize > 0 {
return fmt.Errorf("existing content of %s is not readable", absPath)
}
if size == 0 {
return nil
}
return writeZeros(dst, size)
}
if size == 0 {
return nil
}
if len(entry.Content) > 0 {
if _, err := dst.Write(entry.Content); err != nil {
content := entry.Content[:min(int64(len(entry.Content)), size)]
if _, err := dst.Write(content); err != nil {
return err
}
if remaining := size - int64(len(entry.Content)); remaining > 0 {
return writeZeros(dst, remaining)
}
return nil
return writeZeros(dst, size-int64(len(content)))
}
streamFn, err := filer.PrepareStreamContentWithThrottler(ctx, lookupFileIdFn(filer.LookupFn(fs)), filer.JwtForVolumeServer, entry.GetChunks(), 0, size, 0)
if err != nil {
+28
View File
@@ -164,6 +164,34 @@ func TestReadWriteOpenUploadsOnlyChanges(t *testing.T) {
}
}
// A truncate can grow a file to any size without storing anything. Opening it
// for writing must not turn that size into zeros on the server's disk.
func TestReadWriteOpenGrownFile(t *testing.T) {
rw := newRWTest(t, PermAll)
const size = 1 << 40
rw.fake.mu.Lock()
rw.fake.entries["/buckets/b/grown.txt"] = &filer_pb.Entry{Name: "grown.txt", Content: []byte("x"), Attributes: &filer_pb.FuseAttributes{FileSize: size, FileMode: 0o644}}
rw.fake.mu.Unlock()
f, err := rw.client.OpenFile("/b/grown.txt", os.O_RDWR)
if err != nil {
t.Fatalf("open read-write: %v", err)
}
buf := make([]byte, 2)
if n, err := f.ReadAt(buf, 0); n != 2 || string(buf) != "x\x00" {
t.Fatalf("read at 0 = %q (err=%v), want %q", buf[:n], err, "x\x00")
}
if n, err := f.ReadAt(buf, size-2); n != 2 || string(buf) != "\x00\x00" {
t.Fatalf("read at the end = %q (err=%v), want two zeros", buf[:n], err)
}
if err := f.Close(); err != nil {
t.Fatalf("close: %v", err)
}
if got := rw.uploads(); len(got) != 0 {
t.Fatalf("uploaded %d times on close, want none", len(got))
}
}
// Without read permission a read-write open still writes, as a write-only
// open would, but reads only what the handle itself wrote.
func TestReadWriteOpenWithoutReadPermission(t *testing.T) {