diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go index 1f0fece56a..bf9e1c5299 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go @@ -354,48 +354,99 @@ func TestChunkRound_RetryKeepsTheSlot(t *testing.T) { } } +// waitFor waits for ch, failing t after a bound. +func waitFor(t *testing.T, ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(10 * time.Second): + t.Fatalf("timed out waiting for %s", what) + } +} + +// releaser closes a channel once; registered as cleanup before any worker +// that waits on it starts, so a failing test never strands that worker. +func releaser(t *testing.T) (ch chan struct{}, release func()) { + ch = make(chan struct{}) + var once sync.Once + release = func() { once.Do(func() { close(ch) }) } + t.Cleanup(release) + return ch, release +} + // A reservation waiting on the filer ends with the caller's context when it // follows it; one that ignores it is still joined (Put does not return // before it), and its late successful reply never starts an upload. func TestChunkRound_ReserveFollowsTheCaller(t *testing.T) { - b := newRangeFake() - hold := make(chan struct{}) - b.reserveHook = func(ctx context.Context, _ int) error { - select { - case <-hold: - return nil - case <-ctx.Done(): - return ctx.Err() + t.Run("cooperative", func(t *testing.T) { + b := newRangeFake() + hold, _ := releaser(t) + entered := make(chan struct{}) + b.reserveHook = func(ctx context.Context, _ int) error { + close(entered) + select { + case <-hold: + return nil + case <-ctx.Done(): + return ctx.Err() + } } - } - r := roundRemote(t, b) - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - if err := r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")); !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("held reservation: %v", err) - } - close(hold) - - b2 := newRangeFake() - hold2 := make(chan struct{}) - b2.reserveHook = func(context.Context, int) error { <-hold2; return nil } // ignores ctx - r2 := roundRemote(t, b2) - ctx2, cancel2 := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel2() - done := make(chan error, 1) - go func() { done <- r2.BeginPutRound(1, 4096).Put(ctx2, 0, roundKey(0), []byte("x")) }() - select { - case err := <-done: - t.Fatalf("Put returned (%v) while its reservation call was still running", err) - case <-time.After(200 * time.Millisecond): - } - close(hold2) // the late reply is a success - if err := <-done; !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("late reply after the caller gave up: %v", err) - } - if puts := b2.putList(); len(puts) != 0 { - t.Fatalf("uploads %v after the caller gave up", puts) - } + r := roundRemote(t, b) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { done <- r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) }() + waitFor(t, entered, "the reservation call") + cancel() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled reservation: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("Put did not end with its context") + } + }) + t.Run("uncooperative", func(t *testing.T) { + b := newRangeFake() + hold, release := releaser(t) + entered := make(chan struct{}) + b.reserveHook = func(context.Context, int) error { close(entered); <-hold; return nil } // ignores ctx + r := roundRemote(t, b) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { done <- r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) }() + t.Cleanup(func() { // joins the worker whatever happens below + release() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Error("Put never returned") + } + }) + waitFor(t, entered, "the reservation call") + cancel() + select { + case err := <-done: + done <- err + t.Fatalf("Put returned (%v) while its admitted reservation call was still running", err) + case <-time.After(200 * time.Millisecond): + } + release() // the late reply is a success + select { + case err := <-done: + done <- err + if !errors.Is(err, context.Canceled) { + t.Fatalf("late reply after the caller gave up: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("Put did not return after its reservation call did") + } + if puts := b.putList(); len(puts) != 0 { + t.Fatalf("uploads %v after the caller gave up", puts) + } + }) } // A replacement reply that arrives after a lower slot retired the group's @@ -407,33 +458,58 @@ func TestChunkRound_StaleReplacementIsDiscarded(t *testing.T) { rd := r.BeginPutRound(4, 4096).(*putRound) g := rd.groups[0] second := make(chan struct{}) - release := make(chan struct{}) - b.reserveHook = func(_ context.Context, call int) error { + var secondOnce sync.Once + release, releaseAll := releaser(t) + b.reserveHook = func(ctx context.Context, call int) error { if call == 2 { - close(second) - <-release + secondOnce.Do(func() { close(second) }) + select { + case <-release: + case <-ctx.Done(): + return ctx.Err() + } } return nil } slot0Sent := make(chan struct{}) - b.putHook = func(_ context.Context, fid string) (bool, error) { + b.putHook = func(ctx context.Context, fid string) (bool, error) { switch fid { case "1,0a0b0c0d0e_1": // slot 1: refused at once return false, errRangeRefused case "1,0a0b0c0d0e": // slot 0: sent, refused once the replacement is in flight close(slot0Sent) - <-second + select { + case <-second: + case <-ctx.Done(): + return false, ctx.Err() + } return false, errRangeRefused } return true, nil } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() errs := make(chan error, 2) + started := 0 + t.Cleanup(func() { // release and join every worker started + releaseAll() + cancel() + for k := 0; k < started; k++ { + select { + case <-errs: + case <-time.After(10 * time.Second): + t.Error("a round worker never returned") + return + } + } + }) + started++ go func() { errs <- rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))) }() - <-slot0Sent + waitFor(t, slot0Sent, "slot 0's upload") + started++ go func() { errs <- rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))) }() - <-second + waitFor(t, second, "the replacement reservation") + deadline := time.Now().Add(10 * time.Second) for { // slot 0's refusal retires the rest of the group meanwhile g.mu.Lock() v := g.ver @@ -441,12 +517,20 @@ func TestChunkRound_StaleReplacementIsDiscarded(t *testing.T) { if v == 2 { break } + if time.Now().After(deadline) { + t.Fatalf("group version %d; slot 0's refusal never retired the range", v) + } time.Sleep(time.Millisecond) } - close(release) - for k := 0; k < 2; k++ { - if err := <-errs; err != nil { - t.Fatal(err) + releaseAll() + for ; started > 0; started-- { + select { + case err := <-errs: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("a round worker did not finish") } } got := b.reserveCounts() diff --git a/seaweed-block/core/frontend/chunkstore/swfs_batch.go b/seaweed-block/core/frontend/chunkstore/swfs_batch.go index cb33513e33..5f0b18c891 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs_batch.go +++ b/seaweed-block/core/frontend/chunkstore/swfs_batch.go @@ -18,6 +18,7 @@ import ( "math" "net" "net/http" + "net/url" "strconv" "strings" "time" @@ -127,18 +128,28 @@ func validBaseFid(fid string, count int) error { return nil } -// validHostPort checks a volume server location: host:port, no scheme or path. +// validHostPort checks a volume server location: a plain host:port HTTP +// authority ([v6]:port included), with no scheme, path, user, escape, +// space or control byte, so the range's uploads can be addressed at all. func validHostPort(loc string) error { + for _, c := range loc { + if c <= ' ' || c == 0x7f || strings.ContainsRune("/?#@\\", c) { + return fmt.Errorf("chunkstore: assign location %q: not a plain host:port", loc) + } + } host, port, err := net.SplitHostPort(loc) if err != nil { return fmt.Errorf("chunkstore: assign location %q: %v", loc, err) } - if host == "" || strings.ContainsAny(host, "/ ?#@") { - return fmt.Errorf("chunkstore: assign location %q: bad host", loc) + if host == "" { + return fmt.Errorf("chunkstore: assign location %q: no host", loc) } if p, err := strconv.ParseUint(port, 10, 16); err != nil || p == 0 { return fmt.Errorf("chunkstore: assign location %q: bad port", loc) } + if u, err := url.Parse("http://" + loc + "/"); err != nil || u.Host != loc { + return fmt.Errorf("chunkstore: assign location %q: not an HTTP authority", loc) + } return nil } diff --git a/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go b/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go index 7bad01ed29..fa0572a17d 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go +++ b/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go @@ -154,6 +154,13 @@ func TestSWFSRange_ReserveValidates(t *testing.T) { {"location with a bad port", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1:x"}}, false, 0}, {"location with port 0", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1:0"}}, false, 0}, {"location with a path", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a/b:1"}}, false, 0}, + {"location with a tab", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1\t:1"}}, false, 0}, + {"location with a newline", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a\nb:1"}}, false, 0}, + {"location with a bad escape", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a%zz:1"}}, false, 0}, + {"location with an escape", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a%41:1"}}, false, 0}, + {"location with a space", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a b:1"}}, false, 0}, + {"location with a user", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "u@a:1"}}, false, 0}, + {"bracketed IPv6 location", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "[::1]:8080"}}, true, 4}, {"widest key", 4, &filerpb.AssignVolumeResponse{FileId: "3,0123456789abcdef0a0b0c0d", Count: 4, Location: loc}, true, 4}, {"key of 17 digits (leading zero)", 4, &filerpb.AssignVolumeResponse{FileId: "3,00123456789abcdef0a0b0c0d", Count: 4, Location: loc}, false, 0}, {"key wider than 64 bits", 4, &filerpb.AssignVolumeResponse{FileId: "3,10123456789abcdef0a0b0c0d", Count: 4, Location: loc}, false, 0}, @@ -185,6 +192,20 @@ func TestSWFSRange_ReserveValidates(t *testing.T) { t.Fatalf("reserve %d: offset %d gave %q", n, n, fid) } } + // A rejected location leaves nothing to upload to: a round over it makes + // no upload at all. + vol := newBatchVolume(t) + bad := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 2, Location: &filerpb.Location{Url: vol.host() + "\t"}}}) + rr, err := NewChunkRemote(newFakeFiler(), bad, "/swblock/vols/v1") + if err != nil { + t.Fatal(err) + } + if err := rr.BeginPutRound(2, 4096).Put(context.Background(), 0, "k00000", []byte("x")); err == nil { + t.Fatal("round over a malformed location stored an object") + } + if uploads, _, _ := vol.snapshot(); len(uploads) != 0 { + t.Fatalf("uploads %v after a malformed location", uploads) + } s := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 1, Location: loc}}) for _, n := range []int{0, -1, maxRangeCount + 1} { if _, err := s.reserve(context.Background(), n, 4096); err == nil { diff --git a/seaweed-block/core/storage/chunk_put_round_test.go b/seaweed-block/core/storage/chunk_put_round_test.go index e9bbf7d5e3..bb1aaeb862 100644 --- a/seaweed-block/core/storage/chunk_put_round_test.go +++ b/seaweed-block/core/storage/chunk_put_round_test.go @@ -148,19 +148,27 @@ func TestChunkCut_FinalUploadIsNotRetried(t *testing.T) { } // heldRound blocks every round Put until released; cooperative Puts also -// end with their context. It records the bytes of every attempt. +// end with their context. It records the bytes of every attempt, and closes +// cancelled when an outstanding Put's context ends. type heldRound struct { *fakeChunkRemote cooperative bool entered chan struct{} + cancelled chan struct{} release chan struct{} once sync.Once + cancelOnce sync.Once mu sync.Mutex sent [][]byte transient int // the first transient attempts fail after being recorded mutate func() } +func newHeldRound(cooperative bool) *heldRound { + return &heldRound{fakeChunkRemote: newFakeChunkRemote(), cooperative: cooperative, + entered: make(chan struct{}), cancelled: make(chan struct{}), release: make(chan struct{})} +} + func (h *heldRound) BeginPutRound(n, objSize int) ChunkPutRound { return heldRoundPut{h} } type heldRoundPut struct{ h *heldRound } @@ -179,6 +187,13 @@ func (p heldRoundPut) Put(ctx context.Context, i int, key string, data []byte) e if attempt <= h.transient { return errors.New("transient upload failure") } + go func() { // witness: the outstanding call's context ended + select { + case <-ctx.Done(): + h.cancelOnce.Do(func() { close(h.cancelled) }) + case <-h.release: + } + }() if h.cooperative { select { case <-h.release: @@ -191,54 +206,101 @@ func (p heldRoundPut) Put(ctx context.Context, i int, key string, data []byte) e return h.fakeChunkRemote.Put(ctx, key, data) } -// While a round's upload call is held, guest writes go on; Close cancels a -// cooperative call and joins it; an uncooperative call is still joined: -// Close does not return before it does. +// waitDone waits for ch, failing t after a bound. +func waitDone(t *testing.T, ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(10 * time.Second): + t.Fatalf("timed out waiting for %s", what) + } +} + +// While a round's upload call is held, guest writes and flushes go on; +// Close cancels the call's context, then joins it: a cooperative call ends +// and Close returns; an uncooperative one is still joined, and Close does +// not return before it does. func TestChunkCut_HeldRoundCallIsJoined(t *testing.T) { for _, cooperative := range []bool{true, false} { t.Run(fmt.Sprintf("cooperative=%v", cooperative), func(t *testing.T) { s, _ := newChunkTestStore(t) - h := &heldRound{fakeChunkRemote: newFakeChunkRemote(), cooperative: cooperative, entered: make(chan struct{}), release: make(chan struct{})} + h := newHeldRound(cooperative) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(h.release) }) } layer := mustAttach(t, s, h, ctConfig(1)) w := newWriteLog() w.write(t, s, 2, 0x22) cutDone := make(chan error, 1) - go func() { _, err := layer.Cut(context.Background()); cutDone <- err }() - select { - case <-h.entered: - case <-time.After(10 * time.Second): - t.Fatal("the cut never reached its upload") - } - wrote := make(chan struct{}) - go func() { w.write(t, s, 7, 0x77); close(wrote) }() - select { - case <-wrote: - case <-time.After(5 * time.Second): - t.Fatal("a guest write waited on the held upload call") - } closeDone := make(chan error, 1) + closeStarted := false + t.Cleanup(func() { // release, then join every worker started + release() + for _, c := range []struct { + ch chan error + started bool + }{{cutDone, true}, {closeDone, closeStarted}} { + if !c.started { + continue + } + select { + case <-c.ch: + case <-time.After(10 * time.Second): + t.Error("a worker never returned") + } + } + }) + go func() { _, err := layer.Cut(context.Background()); cutDone <- err }() + waitDone(t, h.entered, "the cut's upload call") + + guest := make(chan error, 1) + go func() { + if _, err := s.Write(7, makeBlock(ctBlockSize, 0x77)); err != nil { + guest <- err + return + } + _, err := s.Sync() + guest <- err + }() + select { + case err := <-guest: + if err != nil { + t.Fatalf("guest write/flush during the held upload: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("a guest write or flush waited on the held upload call") + } + + closeStarted = true go func() { closeDone <- layer.Close() }() + // Close has cancelled the layer's calls: it is past cancel, at its join. + waitDone(t, h.cancelled, "Close cancelling the held call") if !cooperative { select { - case <-closeDone: + case err := <-closeDone: + closeDone <- err t.Fatal("Close returned while an uncooperative upload call was still running") case <-time.After(300 * time.Millisecond): } - close(h.release) + release() } select { - case <-closeDone: + case err := <-closeDone: + closeDone <- err + if err != nil { + t.Fatalf("Close: %v", err) + } case <-time.After(10 * time.Second): t.Fatal("Close did not return") } select { - case <-cutDone: - case <-time.After(5 * time.Second): + case err := <-cutDone: + cutDone <- err + if err == nil { + t.Fatal("the cut succeeded across Close") + } + case <-time.After(10 * time.Second): t.Fatal("the cut did not end with Close") } - if cooperative { - close(h.release) - } }) } } @@ -247,7 +309,8 @@ func TestChunkCut_HeldRoundCallIsJoined(t *testing.T) { // newer write to the same block. func TestChunkCut_RetrySendsTheCapturedBytes(t *testing.T) { s, _ := newChunkTestStore(t) - h := &heldRound{fakeChunkRemote: newFakeChunkRemote(), cooperative: true, entered: make(chan struct{}), release: make(chan struct{}), transient: 1} + h := newHeldRound(true) + h.transient = 1 close(h.release) w := newWriteLog() h.mutate = func() { w.write(t, s, 2, 0x99) } // the guest overwrites the block mid-upload