diff --git a/weed/mount/page_writer/page_chunk_swapfile.go b/weed/mount/page_writer/page_chunk_swapfile.go index ed490a7f78..e67ff80c8d 100644 --- a/weed/mount/page_writer/page_chunk_swapfile.go +++ b/weed/mount/page_writer/page_chunk_swapfile.go @@ -25,6 +25,9 @@ type SwapFile struct { chunkTrackingLock sync.Mutex activeChunkCount int freeActualChunkList []ActualChunkIndex + // refusedUntil is when, in unix nanoseconds, the file is tried again + // after it refused a chunk or a write; see noteSwapRefused. + refusedUntil atomic.Int64 } type SwapFileChunk struct { @@ -198,6 +201,29 @@ func (sc *SwapFileChunk) LastWriteTsNs() int64 { return sc.lastWriteTsNs.Load() } +// copyWrittenTo reads back what the chunk holds and writes it into dst, each +// written range under its own timestamp. +func (sc *SwapFileChunk) copyWrittenTo(dst *MemChunk) error { + sc.RLock() + defer sc.RUnlock() + chunkStart := int64(sc.logicChunkIndex) * sc.swapfile.chunkSize + slotStart := int64(sc.actualChunkIndex) * sc.swapfile.chunkSize + for t := sc.usage.head.next; t != sc.usage.tail; t = t.next { + data := mem.Allocate(int(t.stopOffset - t.StartOffset)) + n, err := sc.swapfile.file.ReadAt(data, slotStart+t.StartOffset) + if n < len(data) { + mem.Free(data) + if err == nil || err == io.EOF { + err = io.ErrUnexpectedEOF + } + return fmt.Errorf("read swap file in %s [%d,%d) of chunk %d: %w", sc.swapfile.dir, t.StartOffset, t.stopOffset, sc.logicChunkIndex, err) + } + dst.WriteDataAt(data, chunkStart+t.StartOffset, t.TsNs) + mem.Free(data) + } + return nil +} + func (sc *SwapFileChunk) SaveContent(saveFn SaveToStorageFunc) { sc.RLock() defer sc.RUnlock() diff --git a/weed/mount/page_writer/upload_pipeline.go b/weed/mount/page_writer/upload_pipeline.go index 979f9d138d..4ea6466ce5 100644 --- a/weed/mount/page_writer/upload_pipeline.go +++ b/weed/mount/page_writer/upload_pipeline.go @@ -6,6 +6,7 @@ import ( "math" "sync" "sync/atomic" + "time" "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/util" @@ -83,6 +84,28 @@ func NewUploadPipeline(writers *util.LimitedConcurrentExecutor, chunkSize int64, return t } +// swapRefusalBackoff is how long a file keeps chunks bound for its swap file +// in memory after the swap file refused one, before trying it again. +var swapRefusalBackoff = 10 * time.Second + +// swapRefusalLoggedUntil rate-limits the refusal warning across files: they +// all swap to the same cache disk and run out of it together. +var swapRefusalLoggedUntil atomic.Int64 + +// swapRefusedWritableChunks caps the writable chunks a file keeps in memory in +// place of the swap file. Past it the file seals one before creating another. +const swapRefusedWritableChunks = 8 + +// noteSwapRefused starts the file's backoff after its swap file refused a +// chunk or a write. +func noteSwapRefused(sf *SwapFile) { + now := time.Now() + sf.refusedUntil.Store(now.Add(swapRefusalBackoff).UnixNano()) + if previous := swapRefusalLoggedUntil.Swap(now.Add(swapRefusalBackoff).UnixNano()); previous <= now.UnixNano() { + glog.Warningf("swap file in %s refused a write, buffering writes in memory for %v", sf.dir, swapRefusalBackoff) + } +} + func (up *UploadPipeline) SaveDataAt(p []byte, off int64, isSequential bool, tsNs int64) (n int, err error) { up.chunksLock.Lock() @@ -101,70 +124,37 @@ func (up *UploadPipeline) SaveDataAt(p []byte, off int64, isSequential bool, tsN } } - pageChunk, found := up.writableChunks[logicChunkIndex] - if !found { - // Reserve a chunk-sized slot against the global write budget before - // allocating. Reserve may block when volumes are full and sealed - // chunks can't drain, so we must release chunksLock first — the - // uploader goroutines that eventually call Release take chunksLock. - if up.accountant != nil { - up.chunksLock.Unlock() - up.accountant.Reserve(up.ChunkSize) - up.chunksLock.Lock() - // Re-check: another writer on the same file may have created - // the chunk while we were blocked. If so, give the slot back. - if pageChunk, found = up.writableChunks[logicChunkIndex]; found { + // A nil chunk means neither the swap file nor memory can take one: the + // write stores nothing. + for pageChunk := up.writableChunkLocked(logicChunkIndex, isSequential); pageChunk != nil; { + n = pageChunk.WriteDataAt(p, off, tsNs) + if swapChunk, swapped := pageChunk.(*SwapFileChunk); swapped && n < len(p) { + // The swap file refused the write: its disk is full or gone. Carry + // on in memory with what the chunk holds. + noteSwapRefused(up.swapFile) + if memChunk := up.swapChunkToMemoryLocked(swapChunk, logicChunkIndex); memChunk != nil { + pageChunk = memChunk + n = memChunk.WriteDataAt(p, off, tsNs) + } else if up.writableChunks[logicChunkIndex] != pageChunk { + // Sealed by another writer while a seal released the lock: + // write again into the chunk now at the index. + pageChunk = up.writableChunkLocked(logicChunkIndex, isSequential) + continue + } else if swapChunk.WrittenSize() == 0 { + // Created for this write, it holds nothing: drop it rather than + // leave an empty chunk counted against the file's bound, where + // nothing could seal it. + delete(up.writableChunks, logicChunkIndex) + swapChunk.FreeResource() up.accountant.Release(up.ChunkSize) + pageChunk = nil } } + if pageChunk != nil { + up.maybeMoveToSealed(pageChunk, logicChunkIndex) + } + break } - if !found { - if len(up.writableChunks) > up.writableChunkLimit { - // Per-pipeline soft cap. Seal the fullest gap-free chunk; - // gappy chunks must wait so in-flight FUSE writeback can fill - // the gap (issue #9330). If none qualifies, fall through — - // the memChunkCounter ceiling below redirects to swap. - candidateChunkIndex, fullness := LogicChunkIndex(-1), int64(0) - for lci, mc := range up.writableChunks { - if !mc.IsContiguouslyWritten() { - continue - } - if b := mc.WrittenSize(); b > fullness { - candidateChunkIndex = lci - fullness = b - } - } - if candidateChunkIndex >= 0 { - up.moveToSealed(up.writableChunks[candidateChunkIndex], candidateChunkIndex) - } - } - // fmt.Printf("isSequential:%v len(up.writableChunks):%v memChunkCounter:%v", isSequential, len(up.writableChunks), memChunkCounter) - if isSequential && - len(up.writableChunks) < up.writableChunkLimit && - atomic.LoadInt64(&memChunkCounter) < 4*int64(up.writableChunkLimit) { - pageChunk = NewMemChunk(logicChunkIndex, up.ChunkSize) - // fmt.Printf(" create mem chunk %d\n", logicChunkIndex) - } else { - // Check the *SwapFileChunk before it becomes a PageChunk: a nil - // pointer inside the interface would not compare equal to nil. - swapChunk := up.swapFile.NewSwapFileChunk(logicChunkIndex) - // fmt.Printf(" create file chunk %d\n", logicChunkIndex) - if swapChunk == nil { - up.accountant.Release(up.ChunkSize) - return 0, fmt.Errorf("failed to create swap file chunk") - } - pageChunk = swapChunk - } - up.writableChunks[logicChunkIndex] = pageChunk - } - //if _, foundSealed := up.sealedChunks[logicChunkIndex]; foundSealed { - // println("found already sealed chunk", logicChunkIndex) - //} - //if _, foundReading := up.activeReadChunks[logicChunkIndex]; foundReading { - // println("found active read chunk", logicChunkIndex) - //} - n = pageChunk.WriteDataAt(p, off, tsNs) - up.maybeMoveToSealed(pageChunk, logicChunkIndex) if n < len(p) { err = fmt.Errorf("chunk %d stored %d of %d bytes: %w", logicChunkIndex, n, len(p), io.ErrShortWrite) } @@ -172,6 +162,179 @@ func (up *UploadPipeline) SaveDataAt(p []byte, off int64, isSequential bool, tsN return } +// writableChunkLocked returns the writable chunk at logicChunkIndex, creating +// it if there is none, or nil when the swap file is refused and memory cannot +// take the chunk either. Creating it may release and retake chunksLock, to +// wait for write budget or to seal another chunk. +func (up *UploadPipeline) writableChunkLocked(logicChunkIndex LogicChunkIndex, isSequential bool) PageChunk { + if pageChunk, found := up.writableChunks[logicChunkIndex]; found { + return pageChunk + } + // Reserve a chunk-sized slot against the global write budget before + // allocating. Reserve may block when volumes are full and sealed + // chunks can't drain, so we must release chunksLock first — the + // uploader goroutines that eventually call Release take chunksLock. + if up.accountant != nil { + up.chunksLock.Unlock() + up.accountant.Reserve(up.ChunkSize) + up.chunksLock.Lock() + // Re-check: another writer on the same file may have created + // the chunk while we were blocked. If so, give the slot back. + if pageChunk, found := up.writableChunks[logicChunkIndex]; found { + up.accountant.Release(up.ChunkSize) + return pageChunk + } + } + if len(up.writableChunks) > up.writableChunkLimit { + // Per-pipeline soft cap. Seal the fullest gap-free chunk; + // gappy chunks must wait so in-flight FUSE writeback can fill + // the gap (issue #9330). If none qualifies, fall through — + // the memChunkCounter ceiling below redirects to swap. + candidateChunkIndex, fullness := LogicChunkIndex(-1), int64(0) + for lci, mc := range up.writableChunks { + if !mc.IsContiguouslyWritten() { + continue + } + if b := mc.WrittenSize(); b > fullness { + candidateChunkIndex = lci + fullness = b + } + } + if candidateChunkIndex >= 0 { + up.moveToSealed(up.writableChunks[candidateChunkIndex], candidateChunkIndex) + // Sealing released the lock. + if pageChunk, found := up.writableChunks[logicChunkIndex]; found { + up.accountant.Release(up.ChunkSize) + return pageChunk + } + } + } + var pageChunk PageChunk + if isSequential && + len(up.writableChunks) < up.writableChunkLimit && + atomic.LoadInt64(&memChunkCounter) < 4*int64(up.writableChunkLimit) { + pageChunk = NewMemChunk(logicChunkIndex, up.ChunkSize) + } else if swapChunk := up.newSwapFileChunk(logicChunkIndex); swapChunk != nil { + // Checked as a *SwapFileChunk: a nil pointer inside the PageChunk + // interface would not compare equal to nil. + pageChunk = swapChunk + } else { + // The swap file is refused: keep the chunk in memory rather than fail + // the write, within bounds. Sealing waits for an upload slot, so a + // writer that outpaces its uploads slows down instead of filling + // memory. + // + // A file seals one of its chunks before it holds more than + // swapRefusedWritableChunks. Once the memory chunks of all files reach + // the shared ceiling, it seals one of its memory chunks for the new + // one: only those free memory when they upload. With none, the write + // fails as the refused swap file made it fail, rather than memory + // growing with the number of open files. A seal releases the lock, and + // other writers may create chunks meanwhile, so both bounds are checked + // again after each one. + sealedMemory := false + for { + overFile := len(up.writableChunks) >= swapRefusedWritableChunks + overShared := !sealedMemory && up.memChunksAtCeiling() + if !overFile && !overShared { + break + } + if overShared { + if !up.evictOneWritableChunkLocked(isMemChunk) { + up.accountant.Release(up.ChunkSize) + return nil + } + sealedMemory = true + } else if !up.evictOneWritableChunkLocked(nil) { + // Nothing of the file can be sealed: fail the write rather than + // go past the per-file bound. + up.accountant.Release(up.ChunkSize) + return nil + } + if existing, found := up.writableChunks[logicChunkIndex]; found { + up.accountant.Release(up.ChunkSize) + return existing + } + } + pageChunk = NewMemChunk(logicChunkIndex, up.ChunkSize) + } + up.writableChunks[logicChunkIndex] = pageChunk + return pageChunk +} + +// isMemChunk reports a chunk held in memory: sealing one frees memory once it +// has uploaded, sealing a swap chunk frees none. +func isMemChunk(chunk PageChunk) bool { + _, inMemory := chunk.(*MemChunk) + return inMemory +} + +// memChunksAtCeiling reports whether the memory chunks of all files reached +// the shared ceiling, past which the sequential path writes to the swap file. +func (up *UploadPipeline) memChunksAtCeiling() bool { + return atomic.LoadInt64(&memChunkCounter) >= 4*int64(up.writableChunkLimit) +} + +// swapChunkToMemoryLocked moves the writable swap chunk at logicChunkIndex, +// whose swap file refused a write, into a chunk in memory that takes its place +// and its write budget. Each range the swap chunk holds keeps its own +// timestamp, and its swap slot is given back. The index keeps a single chunk: +// a swap chunk sealed beside a new one in memory would upload the bytes the +// refused write had overwritten under that write's timestamp, racing the +// memory chunk's upload for them, and a later seal at the index would hide its +// bytes from readers until it had uploaded. +// +// Like a new chunk, it first seals another chunk of the file while the file +// holds more than swapRefusedWritableChunks, and one of its memory chunks at +// the shared ceiling; a seal releases the lock. It returns nil, leaving the +// swap chunk in place, when the file has no memory chunk to seal at the +// ceiling or the swap file cannot be read back either. +func (up *UploadPipeline) swapChunkToMemoryLocked(swapChunk *SwapFileChunk, logicChunkIndex LogicChunkIndex) *MemChunk { + otherChunk := func(chunk PageChunk) bool { return chunk != PageChunk(swapChunk) } + sealedMemory := false + for { + overFile := len(up.writableChunks) > swapRefusedWritableChunks + overShared := !sealedMemory && up.memChunksAtCeiling() + if !overFile && !overShared { + break + } + if overShared { + if !up.evictOneWritableChunkLocked(isMemChunk) { + return nil + } + sealedMemory = true + } else if !up.evictOneWritableChunkLocked(otherChunk) { + break + } + if current := up.writableChunks[logicChunkIndex]; current != PageChunk(swapChunk) { + memChunk, _ := current.(*MemChunk) + return memChunk + } + } + memChunk := NewMemChunk(logicChunkIndex, up.ChunkSize) + if err := swapChunk.copyWrittenTo(memChunk); err != nil { + glog.Errorf("%s: keep chunk %d in memory: %v", up.filepath, logicChunkIndex, err) + memChunk.FreeResource() + return nil + } + up.writableChunks[logicChunkIndex] = memChunk + swapChunk.FreeResource() + return memChunk +} + +// newSwapFileChunk returns a chunk in the swap file, or nil when the swap file +// refuses it or refused one moments ago. +func (up *UploadPipeline) newSwapFileChunk(logicChunkIndex LogicChunkIndex) *SwapFileChunk { + if time.Now().UnixNano() < up.swapFile.refusedUntil.Load() { + return nil + } + swapChunk := up.swapFile.NewSwapFileChunk(logicChunkIndex) + if swapChunk == nil { + noteSwapRefused(up.swapFile) + } + return swapChunk +} + // MaybeReadDataAt copies the dirty bytes of [off, off+len(p)) the pipeline // holds into p and returns the furthest offset it filled. It fails when dirty // bytes in the range cannot be read back, since the caller would otherwise @@ -298,6 +461,13 @@ func (up *UploadPipeline) moveToSealed(memChunk PageChunk, logicChunkIndex Logic func (up *UploadPipeline) EvictOneWritableChunk() bool { up.chunksLock.Lock() defer up.chunksLock.Unlock() + return up.evictOneWritableChunkLocked(nil) +} + +// evictOneWritableChunkLocked is EvictOneWritableChunk with chunksLock held, +// choosing among the chunks eligible accepts, or among all when it is nil. +// Sealing releases and retakes the lock. +func (up *UploadPipeline) evictOneWritableChunkLocked(eligible func(PageChunk) bool) bool { if len(up.writableChunks) == 0 { return false } @@ -305,6 +475,9 @@ func (up *UploadPipeline) EvictOneWritableChunk() bool { bestIndex := LogicChunkIndex(-1) var bestBytes int64 for lci, wc := range up.writableChunks { + if eligible != nil && !eligible(wc) { + continue + } if !wc.IsContiguouslyWritten() { continue } @@ -318,6 +491,9 @@ func (up *UploadPipeline) EvictOneWritableChunk() bool { oldestTsNs := int64(math.MaxInt64) var fallbackBytes int64 for lci, wc := range up.writableChunks { + if eligible != nil && !eligible(wc) { + continue + } b := wc.WrittenSize() if b == 0 { continue diff --git a/weed/mount/page_writer/upload_pipeline_swap_test.go b/weed/mount/page_writer/upload_pipeline_swap_test.go index d2e98a3a35..d5d9879663 100644 --- a/weed/mount/page_writer/upload_pipeline_swap_test.go +++ b/weed/mount/page_writer/upload_pipeline_swap_test.go @@ -1,21 +1,110 @@ package page_writer import ( + "bytes" "errors" + "fmt" "io" "os" "path/filepath" + "sort" "sync" + "sync/atomic" "testing" "time" "github.com/seaweedfs/seaweedfs/weed/util" ) -// When the swap file cannot be created, SaveDataAt must fail the write -// instead of keeping a nil swap chunk and writing through it, and give back -// the write budget it reserved for the chunk. -func TestSaveDataAtFailsWhenSwapFileCannotBeCreated(t *testing.T) { +// swapRefused reports whether the pipeline's swap file is in its backoff. +func swapRefused(up *UploadPipeline) bool { + return time.Now().UnixNano() < up.swapFile.refusedUntil.Load() +} + +// unusableSwapDir is a swap directory that cannot be created: its parent is a +// file. +func unusableSwapDir(t *testing.T) string { + t.Helper() + notADir := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(notADir, nil, 0600); err != nil { + t.Fatal(err) + } + return filepath.Join(notADir, "swap") +} + +// refuseSwapWrites swaps the pipeline's swap file for a read-only handle on the +// same file: writes fail and reads still work, like a full disk. +func refuseSwapWrites(t *testing.T, up *UploadPipeline) { + t.Helper() + readOnly, err := os.Open(up.swapFile.file.Name()) + if err != nil { + t.Fatal(err) + } + if err := up.swapFile.file.Close(); err != nil { + t.Fatal(err) + } + up.swapFile.file = readOnly +} + +// uploads records what a pipeline uploads and replays it in modification +// order, the order the filer resolves overlapping chunks in. +type uploads struct { + mu sync.Mutex + pieces []upload +} + +type upload struct { + offset int64 + tsNs int64 + data []byte +} + +func (u *uploads) save(reader io.Reader, offset int64, size int64, tsNs int64, cleanupFn func()) { + data, err := io.ReadAll(reader) + if err != nil { + panic(err) + } + u.mu.Lock() + u.pieces = append(u.pieces, upload{offset: offset, tsNs: tsNs, data: data}) + u.mu.Unlock() + cleanupFn() +} + +func (u *uploads) image(size int) []byte { + u.mu.Lock() + pieces := append([]upload(nil), u.pieces...) + u.mu.Unlock() + sort.SliceStable(pieces, func(i, j int) bool { return pieces[i].tsNs < pieces[j].tsNs }) + image := make([]byte, size) + for _, p := range pieces { + copy(image[p.offset:], p.data) + } + return image +} + +// uploadsIn counts the uploads within [start, stop). +func (u *uploads) uploadsIn(start, stop int64) int { + u.mu.Lock() + defer u.mu.Unlock() + n := 0 + for _, p := range u.pieces { + if p.offset >= start && p.offset < stop { + n++ + } + } + return n +} + +func readBack(up *UploadPipeline, off int64, size int) []byte { + p := make([]byte, size) + up.MaybeReadDataAt(p, off, 0) + return p +} + +// When the swap file cannot be created, SaveDataAt used to fail the write. +// It keeps the chunk in memory instead: the data reads back, uploads, and the +// write budget the chunk reserved is given back once it is uploaded. +func TestSaveDataAtKeepsDataInMemoryWhenSwapFileCannotBeCreated(t *testing.T) { for _, tc := range []struct { name string accountant *WriteBufferAccountant @@ -24,19 +113,32 @@ func TestSaveDataAtFailsWhenSwapFileCannotBeCreated(t *testing.T) { {name: "write budget", accountant: NewWriteBufferAccountant(1 << 20)}, } { t.Run(tc.name, func(t *testing.T) { - notADir := filepath.Join(t.TempDir(), "file") - if err := os.WriteFile(notADir, nil, 0600); err != nil { - t.Fatal(err) - } - up := NewUploadPipeline(nil, 1024, nil, 16, filepath.Join(notADir, "swap"), tc.accountant) + saved := &uploads{} + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(4), 1024, saved.save, 16, unusableSwapDir(t), tc.accountant) + defer up.Shutdown() - // A write that is not sequential goes to the swap file. - n, err := up.SaveDataAt([]byte("data"), 0, false, 0) - if err == nil { - t.Fatalf("SaveDataAt = %d, nil; want an error", n) + // A write that is not sequential is bound for the swap file. + if n, err := up.SaveDataAt([]byte("data"), 0, false, 1); err != nil || n != 4 { + t.Fatalf("SaveDataAt = %d, %v; want 4, nil", n, err) } - if _, found := up.writableChunks[0]; found { - t.Error("the failed write left a writable chunk behind") + if _, inMemory := up.writableChunks[0].(*MemChunk); !inMemory { + t.Fatalf("chunk is %T, want a *MemChunk", up.writableChunks[0]) + } + if !swapRefused(up) { + t.Error("the refused swap file did not start the backoff") + } + if got := readBack(up, 0, 4); string(got) != "data" { + t.Errorf("read back %q, want %q", got, "data") + } + up.FlushAll() + if got := saved.image(4); string(got) != "data" { + t.Errorf("uploaded %q, want %q", got, "data") + } + // FlushAll returns once the upload is done; the upload frees the + // chunk, and its budget, right after. + deadline := time.Now().Add(2 * time.Second) + for tc.accountant.Used() != 0 && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) } if used := tc.accountant.Used(); used != 0 { t.Errorf("write budget still holds %d bytes", used) @@ -45,19 +147,230 @@ func TestSaveDataAtFailsWhenSwapFileCannotBeCreated(t *testing.T) { } } -// A swap chunk whose file write fails stores nothing, so SaveDataAt must -// report the short write instead of claiming the bytes. -func TestSaveDataAtReportsFailedSwapWrite(t *testing.T) { - up := NewUploadPipeline(nil, 1024, nil, 16, t.TempDir(), nil) +// A swap chunk whose write fails used to make SaveDataAt report a short write. +// What the chunk holds moves into a chunk in memory, which takes the write, so +// both the earlier and the refused write read back and upload, from one chunk. +func TestSaveDataAtCarriesOnInMemoryWhenTheSwapFileRefusesAWrite(t *testing.T) { + saved := &uploads{} + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(4), 1024, saved.save, 16, t.TempDir(), nil) defer up.Shutdown() - if n, err := up.SaveDataAt([]byte("data"), 0, false, 0); err != nil || n != 4 { + + if n, err := up.SaveDataAt([]byte("data"), 0, false, 1); err != nil || n != 4 { t.Fatalf("first write = %d, %v", n, err) } - if err := up.swapFile.file.Close(); err != nil { + if _, swapped := up.writableChunks[0].(*SwapFileChunk); !swapped { + t.Fatalf("first chunk is %T, want a *SwapFileChunk", up.writableChunks[0]) + } + refuseSwapWrites(t, up) + + if n, err := up.SaveDataAt([]byte("more"), 4, false, 2); err != nil || n != 4 { + t.Fatalf("write the swap file refuses = %d, %v; want 4, nil", n, err) + } + if _, inMemory := up.writableChunks[0].(*MemChunk); !inMemory { + t.Fatalf("chunk after the refusal is %T, want a *MemChunk", up.writableChunks[0]) + } + if got := readBack(up, 0, 8); string(got) != "datamore" { + t.Errorf("read back %q, want %q", got, "datamore") + } + + // Within the backoff a new chunk bound for the swap file stays in memory. + if n, err := up.SaveDataAt([]byte("next"), 3*1024, false, 3); err != nil || n != 4 { + t.Fatalf("write in another chunk = %d, %v", n, err) + } + if _, inMemory := up.writableChunks[3].(*MemChunk); !inMemory { + t.Errorf("chunk within the backoff is %T, want a *MemChunk", up.writableChunks[3]) + } + + up.FlushAll() + image := saved.image(3*1024 + 4) + if got := string(image[:8]); got != "datamore" { + t.Errorf("uploaded %q, want %q", got, "datamore") + } + if n := saved.uploadsIn(0, 1024); n != 1 { + t.Errorf("chunk 0 uploaded in %d pieces, want one", n) + } + if got := string(image[3*1024:]); got != "next" { + t.Errorf("uploaded %q at chunk 3, want %q", got, "next") + } +} + +// Without the swap file a file keeps only a few writable chunks in memory: +// creating one past swapRefusedWritableChunks seals another first. Every +// write still uploads. +func TestSwapRefusedWritesKeepAFewChunksInMemory(t *testing.T) { + saved := &uploads{} + const chunkSize, chunks = 1024, 50 + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(4), chunkSize, saved.save, 16, unusableSwapDir(t), nil) + defer up.Shutdown() + + want := make([]byte, chunks*chunkSize) + for i := 0; i < chunks; i++ { + // Out of order and part of a chunk each: no chunk completes on its own. + index := (i * 7) % chunks + piece := []byte(fmt.Sprintf("%02d", index)) + off := int64(index*chunkSize + 100) + if n, err := up.SaveDataAt(piece, off, false, int64(i+1)); err != nil || n != len(piece) { + t.Fatalf("write %d = %d, %v", i, n, err) + } + copy(want[off:], piece) + up.chunksLock.Lock() + writable := len(up.writableChunks) + up.chunksLock.Unlock() + if writable > swapRefusedWritableChunks { + t.Fatalf("after write %d the file holds %d writable chunks, want at most %d", i, writable, swapRefusedWritableChunks) + } + } + up.FlushAll() + if got := saved.image(len(want)); !bytes.Equal(got, want) { + t.Error("uploaded data differs from what was written") + } +} + +// Within the backoff a refused swap file is not tried again, even once it +// would take writes; after the backoff, chunks bound for it go there again. +func TestSwapRefusalBackoffPasses(t *testing.T) { + saved := swapRefusalBackoff + swapRefusalBackoff = 200 * time.Millisecond + t.Cleanup(func() { swapRefusalBackoff = saved }) + + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(2), 1024, nil, 16, t.TempDir(), nil) + defer up.Shutdown() + if _, err := up.SaveDataAt([]byte("data"), 0, false, 1); err != nil { t.Fatal(err) } - if n, err := up.SaveDataAt([]byte("more"), 4, false, 0); err == nil || n != 0 { - t.Fatalf("write through a closed swap file = %d, %v; want 0 and an error", n, err) + refuseSwapWrites(t, up) + if _, err := up.SaveDataAt([]byte("data"), 1024, false, 2); err != nil { + t.Fatal(err) + } + if !swapRefused(up) { + t.Fatal("the refused write did not start the backoff") + } + + // The disk has room again, but the backoff still holds. + writable, err := os.OpenFile(up.swapFile.file.Name(), os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + up.swapFile.file.Close() + up.swapFile.file = writable + if _, err := up.SaveDataAt([]byte("data"), 2*1024, false, 3); err != nil { + t.Fatal(err) + } + if _, inMemory := up.writableChunks[2].(*MemChunk); !inMemory { + t.Errorf("chunk within the backoff is %T, want a *MemChunk", up.writableChunks[2]) + } + + time.Sleep(250 * time.Millisecond) + if _, err := up.SaveDataAt([]byte("data"), 5*1024, false, 4); err != nil { + t.Fatal(err) + } + if _, swapped := up.writableChunks[5].(*SwapFileChunk); !swapped { + t.Errorf("chunk after the backoff is %T, want a *SwapFileChunk", up.writableChunks[5]) + } +} + +// Writers, readers, the proactive flusher and the write-budget evictor run +// together while every swap write fails. Each writer owns its own chunks, so +// what it wrote is what must upload. +func TestSwapRefusedWritesUnderConcurrentFlushAndReads(t *testing.T) { + saved := swapRefusalBackoff + swapRefusalBackoff = 0 // every new swap-bound chunk tries the swap file and fails + t.Cleanup(func() { swapRefusalBackoff = saved }) + + const chunkSize, writers, chunksPerWriter, rounds = 1024, 4, 12, 6 + uploaded := &uploads{} + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(3), chunkSize, uploaded.save, 16, t.TempDir(), nil) + defer up.Shutdown() + // Open the swap file, then make it refuse writes. + if _, err := up.SaveDataAt([]byte("x"), 0, false, 1); err != nil { + t.Fatal(err) + } + refuseSwapWrites(t, up) + + size := writers * chunksPerWriter * chunkSize + want := make([]byte, size) + want[0] = 'x' + var mu sync.Mutex + var tsNs int64 = 1 + nextTs := func() int64 { + mu.Lock() + defer mu.Unlock() + tsNs++ + return tsNs + } + + stop := make(chan struct{}) + var background sync.WaitGroup + background.Add(3) + go func() { + defer background.Done() + p := make([]byte, chunkSize) + for { + select { + case <-stop: + return + default: + } + up.MaybeReadDataAt(p, int64(len(p)), 0) + } + }() + go func() { + defer background.Done() + for { + select { + case <-stop: + return + default: + } + up.ProactiveFlush(time.Now().UnixNano(), 0, 0, 0, 1, false) + } + }() + go func() { + defer background.Done() + for { + select { + case <-stop: + return + default: + } + up.EvictOneWritableChunk() + time.Sleep(time.Millisecond) + } + }() + + var wg sync.WaitGroup + for w := 0; w < writers; w++ { + wg.Add(1) + go func(w int) { + defer wg.Done() + first := w * chunksPerWriter + for r := 0; r < rounds; r++ { + for c := 0; c < chunksPerWriter; c++ { + index := first + (c*5+r)%chunksPerWriter + off := int64(index*chunkSize + 1 + r*16) + piece := []byte(fmt.Sprintf("w%dr%dc%02d", w, r, index)) + if n, err := up.SaveDataAt(piece, off, r%2 == 0, nextTs()); err != nil || n != len(piece) { + t.Errorf("writer %d: write = %d, %v", w, n, err) + return + } + mu.Lock() + copy(want[off:], piece) + mu.Unlock() + } + } + }(w) + } + wg.Wait() + close(stop) + background.Wait() + up.FlushAll() + + if got := uploaded.image(size); !bytes.Equal(got, want) { + for i := range got { + if got[i] != want[i] { + t.Fatalf("uploaded data differs first at byte %d: got %q, want %q", i, got[i], want[i]) + } + } } } @@ -171,3 +484,472 @@ func waitForBudgetRelease(t *testing.T, accountant *WriteBufferAccountant) { time.Sleep(5 * time.Millisecond) } } + +// A swap chunk whose file refuses a write and cannot be read back either cannot +// move into memory: the write fails as the swap file made it fail, and the +// chunk's upload fails the flush, since the bytes it held are lost. +func TestRefusedSwapChunkThatCannotBeReadBackFailsTheWrite(t *testing.T) { + probe := &swapReadBackProbe{} + accountant := NewWriteBufferAccountant(1 << 20) + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(4), 1024, probe.save, 16, t.TempDir(), accountant) + defer up.Shutdown() + if n, err := up.SaveDataAt([]byte("data"), 0, false, 1); err != nil || n != 4 { + t.Fatalf("first write = %d, %v", n, err) + } + if err := up.swapFile.file.Close(); err != nil { + t.Fatal(err) + } + if n, err := up.SaveDataAt([]byte("more"), 4, false, 2); err == nil || n != 0 { + t.Fatalf("write the swap file refuses and cannot give back = %d, %v; want 0 and an error", n, err) + } + if _, swapped := up.writableChunks[0].(*SwapFileChunk); !swapped { + t.Fatalf("chunk after the failed write is %T, want the *SwapFileChunk still", up.writableChunks[0]) + } + up.FlushAll() + + probe.mu.Lock() + defer probe.mu.Unlock() + if len(probe.errs) != 1 || len(probe.uploaded) != 0 { + t.Errorf("upload read errors = %v, uploaded %v; want one error and nothing uploaded", probe.errs, probe.uploaded) + } + waitForBudgetRelease(t, accountant) +} + +// The swap file takes the first half of an overwrite and refuses the rest, as +// a full copy-on-write disk can: the chunk then holds the new first half and +// the old second half. The data must upload as written whatever order the +// uploads finish in. A swap chunk sealed beside a memory chunk uploaded the old +// half under the overwrite's timestamp, and when it finished last it won the +// tie: equal timestamps resolve to the later chunk. +func TestRefusedPartialOverwriteUploadsTheNewBytes(t *testing.T) { + saved := &uploads{} + firstDone := make(chan struct{}) + var once sync.Once + save := func(reader io.Reader, offset int64, size int64, tsNs int64, cleanupFn func()) { + data, err := io.ReadAll(reader) + if err != nil { + panic(err) + } + if bytes.Contains(data, []byte("LDOL")) { + // Old bytes finish last if anything else is uploading. + select { + case <-firstDone: + case <-time.After(time.Second): + } + } + saved.mu.Lock() + saved.pieces = append(saved.pieces, upload{offset: offset, tsNs: tsNs, data: data}) + saved.mu.Unlock() + once.Do(func() { close(firstDone) }) + cleanupFn() + } + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(4), 1024, save, 16, t.TempDir(), nil) + defer up.Shutdown() + + if _, err := up.SaveDataAt([]byte("OLDOLDOL"), 0, false, 1); err != nil { + t.Fatal(err) + } + // The overwrite: the swap file takes its first half, then refuses it. + if _, err := up.SaveDataAt([]byte("NEW!"), 0, false, 2); err != nil { + t.Fatal(err) + } + refuseSwapWrites(t, up) + if n, err := up.SaveDataAt([]byte("NEW!NEW!"), 0, false, 2); err != nil || n != 8 { + t.Fatalf("overwrite the swap file refuses = %d, %v; want 8, nil", n, err) + } + if got := readBack(up, 0, 8); string(got) != "NEW!NEW!" { + t.Errorf("read back %q, want %q", got, "NEW!NEW!") + } + up.FlushAll() + if got := saved.image(8); string(got) != "NEW!NEW!" { + t.Errorf("uploaded %q, want %q", got, "NEW!NEW!") + } +} + +// The bytes a refused swap chunk held stay readable until they upload, even +// once the index is sealed again. A swap chunk sealed beside a memory chunk was +// replaced in the sealed slot by the memory chunk's seal, and reads of what only +// it held found nothing until its upload finished. +func TestReadsSeeARefusedSwapChunkUntilItUploads(t *testing.T) { + saved := &uploads{} + release := make(chan struct{}) + save := func(reader io.Reader, offset int64, size int64, tsNs int64, cleanupFn func()) { + <-release + saved.save(reader, offset, size, tsNs, cleanupFn) + } + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(4), 1024, save, 16, t.TempDir(), nil) + defer up.Shutdown() + releaseUploads := sync.OnceFunc(func() { close(release) }) + defer releaseUploads() + + if _, err := up.SaveDataAt([]byte("data"), 0, false, 1); err != nil { + t.Fatal(err) + } + refuseSwapWrites(t, up) + if n, err := up.SaveDataAt([]byte("more"), 4, false, 2); err != nil || n != 4 { + t.Fatalf("write the swap file refuses = %d, %v; want 4, nil", n, err) + } + // Nothing has uploaded yet, and the index is sealed again. + if !up.EvictOneWritableChunk() { + t.Fatal("no writable chunk to seal") + } + if got := readBack(up, 0, 8); string(got) != "datamore" { + t.Errorf("read back %q before the uploads finished, want %q", got, "datamore") + } + releaseUploads() + up.FlushAll() + if got := saved.image(8); string(got) != "datamore" { + t.Errorf("uploaded %q, want %q", got, "datamore") + } +} + +// settledMemChunkCount waits for the memory chunks of earlier tests to be +// freed, which their uploads do just after FlushAll returns. +func settledMemChunkCount(t *testing.T) int64 { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + last := atomic.LoadInt64(&memChunkCounter) + for time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + now := atomic.LoadInt64(&memChunkCounter) + if now == last { + return now + } + last = now + } + return last +} + +// Without a swap file, files keep chunks in memory only up to the ceiling all +// files share. Past it a file with a chunk of its own seals that chunk for the +// new one, and a file with none fails the write as the refused swap file did, +// instead of memory growing with the number of open files. +func TestSwapRefusedChunksStayUnderTheSharedMemoryCeiling(t *testing.T) { + const chunkSize = 1024 + base := settledMemChunkCount(t) + limit := int(base/4) + 2 // the ceiling is 4 * limit, at least 8 above base + ceiling := int64(4 * limit) + room := int(ceiling - base) + + var files []*UploadPipeline + defer func() { + for _, up := range files { + up.Shutdown() + } + }() + for i := 0; i < room+3; i++ { + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(4), chunkSize, nil, limit, unusableSwapDir(t), nil) + files = append(files, up) + // Part of a chunk: it does not complete, so nothing seals it. + n, err := up.SaveDataAt([]byte("x"), 100, false, int64(i+1)) + if i < room && (err != nil || n != 1) { + t.Fatalf("file %d of %d below the ceiling: write = %d, %v", i, room, n, err) + } + if i >= room && (err == nil || n != 0) { + t.Fatalf("file %d with nothing to seal past the ceiling: write = %d, %v; want 0 and an error", i, n, err) + } + } + if got := atomic.LoadInt64(&memChunkCounter); got > ceiling { + t.Errorf("%d memory chunks, want at most the ceiling of %d", got, ceiling) + } + // Nor does a swap chunk that refuses a write move into memory past it. + swapped := NewUploadPipeline(util.NewLimitedConcurrentExecutor(4), chunkSize, nil, limit, t.TempDir(), nil) + files = append(files, swapped) + if n, err := swapped.SaveDataAt([]byte("data"), 0, false, 1); err != nil || n != 4 { + t.Fatalf("write to the swap file = %d, %v", n, err) + } + refuseSwapWrites(t, swapped) + before := atomic.LoadInt64(&memChunkCounter) + if n, err := swapped.SaveDataAt([]byte("more"), 4, false, 2); err == nil || n != 0 { + t.Errorf("past the ceiling, a write the swap file refuses = %d, %v; want 0 and an error", n, err) + } + if got := atomic.LoadInt64(&memChunkCounter); got != before { + t.Errorf("memory chunks went from %d to %d past the ceiling", before, got) + } + // That swap chunk is now the file's only chunk. Sealing it would free no + // memory, so a write at another index fails too. + if n, err := swapped.SaveDataAt([]byte("next"), 5*chunkSize, false, 3); err == nil || n != 0 { + t.Errorf("past the ceiling with only a swap chunk to seal: write = %d, %v; want 0 and an error", n, err) + } + if got := atomic.LoadInt64(&memChunkCounter); got != before { + t.Errorf("memory chunks went from %d to %d after sealing a swap chunk", before, got) + } + // A file with a chunk of its own carries on: it seals that one. + if n, err := files[0].SaveDataAt([]byte("y"), 5*chunkSize+100, false, 1000); err != nil || n != 1 { + t.Errorf("past the ceiling, a file with a chunk to seal: write = %d, %v", n, err) + } +} + +// Writers of one file stay within swapRefusedWritableChunks together. A seal +// releases the lock, another writer may create a chunk meanwhile, and the +// count is checked again before a chunk is created. +func TestSwapRefusedWritersShareThePerFileBound(t *testing.T) { + const chunkSize, writers, chunksEach = 1024, 4, 50 + // A high limit keeps the shared ceiling out of the way. + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(2), chunkSize, nil, 64, unusableSwapDir(t), nil) + defer up.Shutdown() + var over atomic.Int32 + var wg sync.WaitGroup + for w := 0; w < writers; w++ { + wg.Add(1) + go func(w int) { + defer wg.Done() + for i := 0; i < chunksEach; i++ { + off := int64(w*chunksEach+i)*chunkSize + 100 + if n, err := up.SaveDataAt([]byte("x"), off, false, int64(w*chunksEach+i+1)); err != nil || n != 1 { + t.Errorf("writer %d: write = %d, %v", w, n, err) + return + } + up.chunksLock.Lock() + if len(up.writableChunks) > swapRefusedWritableChunks { + over.Add(1) + } + up.chunksLock.Unlock() + } + }(w) + } + wg.Wait() + if n := over.Load(); n > 0 { + t.Errorf("the file held more than %d writable chunks %d times", swapRefusedWritableChunks, n) + } +} + +// Both bounds at once. At the shared ceiling a file seals one of its memory +// chunks to make room for a new one, and that seal releases the lock. Here the +// seal waits for the only upload slot while memory frees up and another writer +// brings the file back to swapRefusedWritableChunks. The per-file count must be +// checked again once the seal returns. +func TestSwapRefusedSealForTheCeilingRechecksThePerFileBound(t *testing.T) { + const chunkSize = 1024 + base := settledMemChunkCount(t) + // The ceiling, 4 * limit, leaves room for the file's chunks and two more. + limit := int((base+swapRefusedWritableChunks+2)/4) + 1 + ceiling := int64(4 * limit) + var others []*UploadPipeline + defer func() { + for _, other := range others { + other.Shutdown() + } + }() + for i := int64(0); i < ceiling-base-swapRefusedWritableChunks; i++ { + other := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), chunkSize, nil, limit, unusableSwapDir(t), nil) + others = append(others, other) + if _, err := other.SaveDataAt([]byte("x"), 100, false, 1); err != nil { + t.Fatalf("other file %d: %v", i, err) + } + } + + gate := make(chan struct{}) + openGate := sync.OnceFunc(func() { close(gate) }) + defer openGate() + save := func(reader io.Reader, offset int64, size int64, tsNs int64, cleanupFn func()) { + <-gate + cleanupFn() + } + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), chunkSize, save, limit, unusableSwapDir(t), nil) + defer up.Shutdown() + writable := func() int { + up.chunksLock.Lock() + defer up.chunksLock.Unlock() + return len(up.writableChunks) + } + next := int64(0) + write := func() { + t.Helper() + next++ + if n, err := up.SaveDataAt([]byte("x"), next*chunkSize+100, false, next); err != nil || n != 1 { + t.Fatalf("write %d = %d, %v", next, n, err) + } + } + for writable() < swapRefusedWritableChunks { + write() + } + if got := atomic.LoadInt64(&memChunkCounter); got < ceiling { + t.Fatalf("%d memory chunks, want the ceiling of %d", got, ceiling) + } + // An upload holds the only slot. + if !up.EvictOneWritableChunk() { + t.Fatal("no chunk to seal") + } + // A write at the ceiling seals one more chunk and waits for the slot. + sealing := make(chan error, 1) + go func() { + _, err := up.SaveDataAt([]byte("x"), 1000*chunkSize+100, false, 1000) + sealing <- err + }() + deadline := time.Now().Add(5 * time.Second) + for writable() != swapRefusedWritableChunks-2 { + if time.Now().After(deadline) { + t.Fatalf("the write did not seal a chunk: %d writable", writable()) + } + time.Sleep(time.Millisecond) + } + // Meanwhile memory frees up, and the file is written back to the bound. + for writable() < swapRefusedWritableChunks { + others[len(others)-1].Shutdown() + others = others[:len(others)-1] + write() + } + openGate() + if err := <-sealing; err != nil { + t.Fatalf("the write that sealed for the ceiling: %v", err) + } + if n := writable(); n > swapRefusedWritableChunks { + t.Errorf("the file holds %d writable chunks, want at most %d", n, swapRefusedWritableChunks) + } +} + +// At the shared ceiling, a swap chunk created for a write that the swap file +// then refuses cannot move into memory. It holds nothing, so it is dropped. +// Otherwise empty chunks pile up against the file's bound, and a later write +// finds nothing to seal. +func TestRefusedEmptySwapChunksAreDroppedAtTheCeiling(t *testing.T) { + const chunkSize = 1024 + saved := swapRefusalBackoff + swapRefusalBackoff = 0 // every write tries the swap file again + t.Cleanup(func() { swapRefusalBackoff = saved }) + base := settledMemChunkCount(t) + limit := int(base/4) + 2 + ceiling := int64(4 * limit) + var others []*UploadPipeline + shutdownOthers := func() { + for _, other := range others { + other.Shutdown() + } + others = nil + } + defer shutdownOthers() + for atomic.LoadInt64(&memChunkCounter) < ceiling { + other := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), chunkSize, nil, limit, unusableSwapDir(t), nil) + others = append(others, other) + if _, err := other.SaveDataAt([]byte("x"), 100, false, 1); err != nil { + t.Fatalf("other file %d: %v", len(others), err) + } + } + + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(4), chunkSize, nil, limit, t.TempDir(), nil) + defer up.Shutdown() + if _, err := up.SaveDataAt([]byte("data"), 0, false, 1); err != nil { + t.Fatal(err) + } + refuseSwapWrites(t, up) + for i := 1; i <= swapRefusedWritableChunks; i++ { + if n, err := up.SaveDataAt([]byte("x"), int64(i)*chunkSize, false, int64(i+1)); err == nil || n != 0 { + t.Fatalf("refused write %d at the ceiling = %d, %v; want 0 and an error", i, n, err) + } + } + if n := emptyWritableChunks(up); n != 0 { + t.Fatalf("the refused writes left %d empty writable chunks, want none", n) + } + + // Once memory frees up, the file writes again, within its bound. + shutdownOthers() + for i := 1; i <= 2*swapRefusedWritableChunks; i++ { + if n, err := up.SaveDataAt([]byte("x"), int64(100+i)*chunkSize, false, int64(100+i)); err != nil || n != 1 { + t.Fatalf("write %d after memory freed up = %d, %v", i, n, err) + } + if n := writableCount(up); n > swapRefusedWritableChunks { + t.Fatalf("the file holds %d writable chunks, want at most %d", n, swapRefusedWritableChunks) + } + } +} + +func writableCount(up *UploadPipeline) int { + up.chunksLock.Lock() + defer up.chunksLock.Unlock() + return len(up.writableChunks) +} + +func emptyWritableChunks(up *UploadPipeline) int { + up.chunksLock.Lock() + defer up.chunksLock.Unlock() + n := 0 + for _, chunk := range up.writableChunks { + if chunk.WrittenSize() == 0 { + n++ + } + } + return n +} + +// At the shared ceiling, a file whose swap file refuses a write into its swap +// chunk seals one of its own memory chunks and moves the swap chunk into +// memory, as it does for a new chunk, instead of failing the write. +func TestRefusedSwapChunkAtTheCeilingSealsAMemoryChunkOfItsFile(t *testing.T) { + const chunkSize = 1024 + base := settledMemChunkCount(t) + limit := int(base/4) + 2 + ceiling := int64(4 * limit) + var saved uploads + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(4), chunkSize, saved.save, limit, t.TempDir(), nil) + defer up.Shutdown() + if _, err := up.SaveDataAt([]byte("data"), 0, false, 1); err != nil { + t.Fatal(err) + } + if _, err := up.SaveDataAt([]byte("m"), chunkSize, true, 2); err != nil { + t.Fatal(err) + } + if !isMemChunk(up.writableChunks[1]) { + t.Fatalf("sequential chunk is %T, want a *MemChunk", up.writableChunks[1]) + } + var others []*UploadPipeline + defer func() { + for _, other := range others { + other.Shutdown() + } + }() + for atomic.LoadInt64(&memChunkCounter) < ceiling { + other := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), chunkSize, nil, limit, unusableSwapDir(t), nil) + others = append(others, other) + if _, err := other.SaveDataAt([]byte("x"), 100, false, 1); err != nil { + t.Fatalf("other file %d: %v", len(others), err) + } + } + + refuseSwapWrites(t, up) + if n, err := up.SaveDataAt([]byte("more"), 4, false, 3); err != nil || n != 4 { + t.Fatalf("write the swap file refuses at the ceiling = %d, %v; want 4, nil", n, err) + } + if !isMemChunk(up.writableChunks[0]) { + t.Errorf("chunk 0 is %T, want a *MemChunk", up.writableChunks[0]) + } + up.FlushAll() + want := append([]byte("datamore"), make([]byte, chunkSize-8)...) + want = append(want, 'm') + if got := saved.image(chunkSize + 1); !bytes.Equal(got, want) { + t.Errorf("uploaded %q, want %q", got, want) + } +} + +// A file that filled its swap file with more chunks than it keeps in memory +// seals one of them before a refused swap chunk moves into memory, so it +// stays within swapRefusedWritableChunks. +func TestRefusedSwapChunkMovesWithinThePerFileBound(t *testing.T) { + const chunkSize = 1024 + var saved uploads + // A high limit keeps the per-pipeline cap and the shared ceiling out of the way. + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(4), chunkSize, saved.save, 64, t.TempDir(), nil) + defer up.Shutdown() + for i := 0; i < swapRefusedWritableChunks; i++ { + if _, err := up.SaveDataAt([]byte("x"), int64(i)*chunkSize, false, int64(i+1)); err != nil { + t.Fatal(err) + } + } + refuseSwapWrites(t, up) + off := int64(swapRefusedWritableChunks) * chunkSize + if n, err := up.SaveDataAt([]byte("y"), off, false, 100); err != nil || n != 1 { + t.Fatalf("write the swap file refuses = %d, %v; want 1, nil", n, err) + } + if n := writableCount(up); n > swapRefusedWritableChunks { + t.Errorf("the file holds %d writable chunks, want at most %d", n, swapRefusedWritableChunks) + } + up.FlushAll() + want := make([]byte, off+1) + for i := 0; i < swapRefusedWritableChunks; i++ { + want[int64(i)*chunkSize] = 'x' + } + want[off] = 'y' + if got := saved.image(int(off + 1)); !bytes.Equal(got, want) { + t.Error("uploaded data differs from what was written") + } +} diff --git a/weed/mount/refusing_dirty_pages_test.go b/weed/mount/refusing_dirty_pages_test.go new file mode 100644 index 0000000000..432ecb21c3 --- /dev/null +++ b/weed/mount/refusing_dirty_pages_test.go @@ -0,0 +1,21 @@ +package mount + +import ( + "errors" + + "github.com/seaweedfs/seaweedfs/weed/mount/page_writer" +) + +// refusingDirtyPages buffers the chunks below limit and refuses the pages of +// any later one, the way the dirty pages fail a write they cannot keep. +type refusingDirtyPages struct { + page_writer.DirtyPages + limit int64 +} + +func (r *refusingDirtyPages) AddPage(offset int64, data []byte, isSequential bool, tsNs int64) (int, error) { + if offset >= r.limit { + return 0, errors.New("dirty pages refused the page") + } + return r.DirtyPages.AddPage(offset, data, isSequential, tsNs) +} diff --git a/weed/mount/weedfs_file_copy_range_test.go b/weed/mount/weedfs_file_copy_range_test.go index edaef65cd2..fbed766904 100644 --- a/weed/mount/weedfs_file_copy_range_test.go +++ b/weed/mount/weedfs_file_copy_range_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "errors" - "os" "path/filepath" "runtime" "strings" @@ -419,11 +418,6 @@ func TestStreamingCopyMarksOnlyAcceptedContentDirty(t *testing.T) { func TestStreamingCopyReportsPartlyBufferedCopy(t *testing.T) { wfs := newCopyRangeTestWFS() wfs.option.ConcurrentWriters = 1 - notADir := filepath.Join(t.TempDir(), "file") - if err := os.WriteFile(notADir, nil, 0600); err != nil { - t.Fatal(err) - } - wfs.option.uniqueCacheDirForWrite = filepath.Join(notADir, "swap") srcInode := wfs.inodeToPath.Lookup(util.FullPath("/src.txt"), 1, false, false, 0, true) dstInode := wfs.inodeToPath.Lookup(util.FullPath("/dst.txt"), 1, false, false, 0, true) srcHandle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{ @@ -436,8 +430,10 @@ func TestStreamingCopyReportsPartlyBufferedCopy(t *testing.T) { Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, Inode: dstInode}, }, 0, 0) t.Cleanup(dstHandle.dirtyPages.Destroy) + // Chunks are 1024 bytes: the dirty pages keep the first chunk only. + dstHandle.dirtyPages.randomWriter = &refusingDirtyPages{DirtyPages: dstHandle.dirtyPages.randomWriter, limit: 1024} - // The destination range crosses into a second chunk, which needs the swap file. + // The destination range crosses into the second chunk, which is refused. written, status := wfs.CopyFileRange(make(chan struct{}), &fuse.CopyFileRangeIn{ FhIn: uint64(srcHandle.fh), FhOut: uint64(dstHandle.fh), diff --git a/weed/mount/weedfs_file_write_test.go b/weed/mount/weedfs_file_write_test.go index ccfee8e25c..2ec0fd4d87 100644 --- a/weed/mount/weedfs_file_write_test.go +++ b/weed/mount/weedfs_file_write_test.go @@ -50,7 +50,7 @@ func openSwapWriteHandle(t *testing.T, swapDir string) (*WFS, *FileHandle, *g6Co return w, fh, peer, out } -// A write the swap file cannot buffer fails, and must not grow the file: the +// A write the dirty pages cannot buffer fails, and must not grow the file: the // next flush would publish that size with a hole where its data should be. A // write that buffers only its first chunk is a short write of those bytes, or // an error for kernel writeback, which would drop the rest silently. @@ -60,11 +60,9 @@ func TestFailedWriteDoesNotGrowFile(t *testing.T) { } func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) { - notADir := filepath.Join(t.TempDir(), "file") - if err := os.WriteFile(notADir, nil, 0600); err != nil { - t.Fatal(err) - } - w, fh, peer, out := openSwapWriteHandle(t, filepath.Join(notADir, "swap")) + w, fh, peer, out := openSwapWriteHandle(t, t.TempDir()) + // Chunks are 1024 bytes: the dirty pages keep the first chunk only. + fh.dirtyPages.randomWriter = &refusingDirtyPages{DirtyPages: fh.dirtyPages.randomWriter, limit: 1024} write := func(offset uint64, size int, value byte) (uint32, fuse.Status) { return w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Offset: offset, Size: uint32(size), WriteFlags: writeFlags}, bytes.Repeat([]byte{value}, size)) @@ -72,14 +70,13 @@ func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) { if _, code := write(256, 256, 'A'); code != fuse.OK { t.Fatalf("buffered write: %v", code) } - // The only writable chunk slot is taken, so this write needs the swap file. if _, code := write(4096, 256, 'B'); code == fuse.OK { - t.Fatal("write through an unusable swap directory succeeded") + t.Fatal("a write the dirty pages refused succeeded") } if size := fh.GetEntry().GetEntry().Attributes.FileSize; size != 512 { t.Fatalf("file size after the failed write = %d, want 512", size) } - // The first 24 bytes fit the existing chunk; the next chunk needs the swap file. + // The first 24 bytes fit the first chunk; the dirty pages refuse the next. n, code := write(1000, 48, 'C') if writeFlags == 0 && (code != fuse.OK || n != 24) { t.Fatalf("boundary-crossing write = %d, %v; want a short write of 24", n, code) @@ -104,6 +101,40 @@ func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) { } } +// A write that needs the swap file used to fail when the swap directory could +// not be created, as on a full cache disk. It is buffered in memory instead, +// and the flush stores it. +func TestWriteBuffersInMemoryWhenTheSwapDirectoryIsUnusable(t *testing.T) { + notADir := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(notADir, nil, 0600); err != nil { + t.Fatal(err) + } + w, _, peer, out := openSwapWriteHandle(t, filepath.Join(notADir, "swap")) + + write := func(offset uint64, size int, value byte) (uint32, fuse.Status) { + return w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Offset: offset, Size: uint32(size)}, bytes.Repeat([]byte{value}, size)) + } + if _, code := write(256, 256, 'A'); code != fuse.OK { + t.Fatalf("buffered write: %v", code) + } + // The only writable chunk slot is taken, so this write needs the swap file. + if n, code := write(4096, 256, 'B'); code != fuse.OK || n != 256 { + t.Fatalf("write needing the unusable swap file = %d, %v; want 256, OK", n, code) + } + if code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh}); code != fuse.OK { + t.Fatal(code) + } + + peer.mu.Lock() + defer peer.mu.Unlock() + want := append(bytes.Repeat([]byte{'O'}, 256), bytes.Repeat([]byte{'A'}, 256)...) + want = append(want, make([]byte, 4096-512)...) + want = append(want, bytes.Repeat([]byte{'B'}, 256)...) + if got := g6StoredBytes(t, peer); peer.entry.Attributes.FileSize != 4352 || !bytes.Equal(got, want) { + t.Fatalf("stored size %d, want 4352 with every write", peer.entry.Attributes.FileSize) + } +} + // Writes buffered in the swap file were acknowledged to the application. If the // swap file cannot be read back when they upload, fsync must fail like a failed // chunk upload and the filer must not get an entry that claims those bytes.