mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
chunkstore, storage: batch-assign review fold
Discard a reservation reply that lost a race with a retirement; keep a slot's fid while an upload to it is unresolved and read it back before giving it up; send under the token's deadline; make a rejected token and used-up replacements final through storage; count every reservation attempt; validate key width, offset overflow and location. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7c4d08199f
commit
d0fc061a77
7 files changed
+749
-95
No files matched your search
@@ -7,18 +7,25 @@ package chunkstore
|
||||
// objects still spread over up to G volumes, and a round with no upload
|
||||
// makes none.
|
||||
//
|
||||
// A slot is frozen once reserved: retrying object i sends the same fid. A
|
||||
// group's ranges change only for slots no upload has stored yet:
|
||||
// A slot is frozen once an upload was sent for it: until that upload is
|
||||
// resolved (stored and bound, or definitely not stored), every retry uses
|
||||
// the same fid, whatever happens to the group's ranges. Ranges change only
|
||||
// for slots with no upload outstanding:
|
||||
// - a short grant is topped up by a reservation for the remaining slots;
|
||||
// - a refusal before append (read-only or full volume) moves this and the
|
||||
// later slots of the group to a fresh range, at most roundMaxReplacements
|
||||
// times per group;
|
||||
// - a range whose token is past its stated expiry is never sent to; its
|
||||
// unsent slots get a fresh range under the same bound.
|
||||
// A rejected token (401) is terminal. Extra reservations are counted apart
|
||||
// from the initial ones (AssignCounts).
|
||||
// - a range whose token is past its stated expiry (less a skew) is never
|
||||
// sent to: an upload is sent under that deadline, and a slot frozen on
|
||||
// an expired range is resolved by reading its fid back first (the exact
|
||||
// bytes: bind it; definitely absent: a fresh range takes it).
|
||||
// A rejected token (401) and used-up replacements end the object for good
|
||||
// (storage.ErrChunkPutFinal). A reservation reply that arrives after the
|
||||
// group's ranges changed is discarded (its ids stay unused). AssignCounts
|
||||
// counts every reservation attempt, by reason, failed ones included.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -35,26 +42,32 @@ const (
|
||||
roundMaxReplacements = 3
|
||||
)
|
||||
|
||||
// AssignCounts counts the reservations this remote's upload rounds made.
|
||||
// AssignCounts counts the reservation attempts this remote's upload rounds
|
||||
// made. Each attempt is counted once, by why it was made, whether or not it
|
||||
// succeeded; Failed counts the ones that returned no usable range.
|
||||
type AssignCounts struct {
|
||||
Initial int64 // the first reservation of each group
|
||||
Initial int64 // the first attempt of each group
|
||||
Short int64 // top-ups after a short grant
|
||||
Capacity int64 // replacements after a refusal before append
|
||||
Expired int64 // replacements of ranges whose token expired before use
|
||||
Retry int64 // attempts after a failed, lost or discarded reply
|
||||
Failed int64 // attempts that returned an error or were discarded
|
||||
}
|
||||
|
||||
// Extra is every reservation beyond the initial ones.
|
||||
func (a AssignCounts) Extra() int64 { return a.Short + a.Capacity + a.Expired }
|
||||
// Extra is every attempt beyond the initial ones.
|
||||
func (a AssignCounts) Extra() int64 { return a.Short + a.Capacity + a.Expired + a.Retry }
|
||||
|
||||
type assignCounters struct{ initial, short, capacity, expired atomic.Int64 }
|
||||
type assignCounters struct{ initial, short, capacity, expired, retry, failed atomic.Int64 }
|
||||
|
||||
// AssignCounts reports the reservations made so far.
|
||||
// AssignCounts reports the reservation attempts made so far.
|
||||
func (r *ChunkRemote) AssignCounts() AssignCounts {
|
||||
return AssignCounts{
|
||||
Initial: r.assigns.initial.Load(),
|
||||
Short: r.assigns.short.Load(),
|
||||
Capacity: r.assigns.capacity.Load(),
|
||||
Expired: r.assigns.expired.Load(),
|
||||
Retry: r.assigns.retry.Load(),
|
||||
Failed: r.assigns.failed.Load(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +84,7 @@ func (r *ChunkRemote) BeginPutRound(n, objSize int) storage.ChunkPutRound {
|
||||
rd := &putRound{r: r, rb: rb, n: n, size: uint64(max(objSize, 0)), groups: make([]*roundGroup, g)}
|
||||
for j := range rd.groups {
|
||||
// Group j holds objects j, j+g, j+2g, ...
|
||||
rd.groups[j] = &roundGroup{slots: (n - j + g - 1) / g}
|
||||
rd.groups[j] = &roundGroup{slots: (n - j + g - 1) / g, pins: map[int]slotPin{}, owners: map[int]chan struct{}{}}
|
||||
}
|
||||
return rd
|
||||
}
|
||||
@@ -90,17 +103,6 @@ type putRound struct {
|
||||
groups []*roundGroup
|
||||
}
|
||||
|
||||
// roundGroup's ranges cover its slots [0, end) as consecutive spans.
|
||||
type roundGroup struct {
|
||||
slots int
|
||||
|
||||
mu sync.Mutex
|
||||
spans []roundSpan
|
||||
reserving chan struct{} // non-nil while a reservation is in flight
|
||||
replacements int
|
||||
next reserveReason // what the next reservation is for
|
||||
}
|
||||
|
||||
type reserveReason int
|
||||
|
||||
const (
|
||||
@@ -108,13 +110,36 @@ const (
|
||||
reserveShort
|
||||
reserveCapacity
|
||||
reserveExpired
|
||||
reserveRetry
|
||||
)
|
||||
|
||||
// roundGroup's ranges cover its slots [0, end) as consecutive spans.
|
||||
type roundGroup struct {
|
||||
slots int
|
||||
|
||||
mu sync.Mutex
|
||||
spans []roundSpan
|
||||
ver int // bumped by every change to spans other than an append
|
||||
reserving chan struct{} // non-nil while a reservation is in flight
|
||||
replacements int
|
||||
next reserveReason // why the next reservation is made
|
||||
pins map[int]slotPin
|
||||
owners map[int]chan struct{} // slot -> held by one Put at a time
|
||||
}
|
||||
|
||||
type roundSpan struct {
|
||||
from int
|
||||
rng blobRange
|
||||
}
|
||||
|
||||
// slotPin freezes a slot on the fid an upload was sent to; stored records
|
||||
// that the upload succeeded (only its binding is outstanding).
|
||||
type slotPin struct {
|
||||
rng blobRange
|
||||
off int
|
||||
stored bool
|
||||
}
|
||||
|
||||
func (g *roundGroup) end() int {
|
||||
if len(g.spans) == 0 {
|
||||
return 0
|
||||
@@ -133,9 +158,54 @@ func (g *roundGroup) lookup(s int) (blobRange, int, bool) {
|
||||
return blobRange{}, 0, false
|
||||
}
|
||||
|
||||
// own makes the caller the only Put working on slot s until release.
|
||||
func (g *roundGroup) own(ctx context.Context, s int) (release func(), err error) {
|
||||
for {
|
||||
g.mu.Lock()
|
||||
held, busy := g.owners[s]
|
||||
if !busy {
|
||||
done := make(chan struct{})
|
||||
g.owners[s] = done
|
||||
g.mu.Unlock()
|
||||
return func() {
|
||||
g.mu.Lock()
|
||||
delete(g.owners, s)
|
||||
g.mu.Unlock()
|
||||
close(done)
|
||||
}, nil
|
||||
}
|
||||
g.mu.Unlock()
|
||||
select {
|
||||
case <-held:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (g *roundGroup) pin(s int, p slotPin) {
|
||||
g.mu.Lock()
|
||||
g.pins[s] = p
|
||||
g.mu.Unlock()
|
||||
}
|
||||
|
||||
func (g *roundGroup) unpin(s int) {
|
||||
g.mu.Lock()
|
||||
delete(g.pins, s)
|
||||
g.mu.Unlock()
|
||||
}
|
||||
|
||||
func (g *roundGroup) pinned(s int) (slotPin, bool) {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
p, ok := g.pins[s]
|
||||
return p, ok
|
||||
}
|
||||
|
||||
// retire drops slots s and later of the span using rng, so they take a fresh
|
||||
// range; it reports false once the group's replacements are used up. A span
|
||||
// already replaced (by a concurrent upload) is left as is.
|
||||
// range (slots with an upload outstanding keep their pinned fid); it reports
|
||||
// false once the group's replacements are used up. A span already replaced
|
||||
// (by a concurrent upload) is left as is.
|
||||
func (g *roundGroup) retire(rng blobRange, s int, why reserveReason) bool {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
@@ -148,6 +218,7 @@ func (g *roundGroup) retire(rng blobRange, s int, why reserveReason) bool {
|
||||
}
|
||||
g.replacements++
|
||||
g.next = why
|
||||
g.ver++
|
||||
if s <= sp.from {
|
||||
g.spans = g.spans[:k]
|
||||
} else {
|
||||
@@ -159,9 +230,25 @@ func (g *roundGroup) retire(rng blobRange, s int, why reserveReason) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (rd *putRound) count(why reserveReason) {
|
||||
switch why {
|
||||
case reserveInitial:
|
||||
rd.r.assigns.initial.Add(1)
|
||||
case reserveShort:
|
||||
rd.r.assigns.short.Add(1)
|
||||
case reserveCapacity:
|
||||
rd.r.assigns.capacity.Add(1)
|
||||
case reserveExpired:
|
||||
rd.r.assigns.expired.Add(1)
|
||||
case reserveRetry:
|
||||
rd.r.assigns.retry.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
// slot returns slot s's range and offset, reserving the group's remaining
|
||||
// slots when s is not covered yet. Concurrent callers share one reservation;
|
||||
// waiting follows ctx, and a reply after ctx ends is not used.
|
||||
// waiting follows ctx. A reply after ctx ends, or after the group's ranges
|
||||
// changed while it was in flight, is not used.
|
||||
func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange, int, error) {
|
||||
for {
|
||||
g.mu.Lock()
|
||||
@@ -178,12 +265,12 @@ func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange,
|
||||
return blobRange{}, 0, ctx.Err()
|
||||
}
|
||||
}
|
||||
from := g.end()
|
||||
why := g.next
|
||||
from, ver, why := g.end(), g.ver, g.next
|
||||
done := make(chan struct{})
|
||||
g.reserving = done
|
||||
g.mu.Unlock()
|
||||
|
||||
rd.count(why)
|
||||
rng, err := rd.rb.reserve(ctx, g.slots-from, rd.size)
|
||||
if err == nil {
|
||||
err = ctx.Err()
|
||||
@@ -191,19 +278,18 @@ func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange,
|
||||
g.mu.Lock()
|
||||
g.reserving = nil
|
||||
close(done)
|
||||
if err == nil {
|
||||
switch {
|
||||
case err != nil:
|
||||
rd.r.assigns.failed.Add(1)
|
||||
g.next = reserveRetry
|
||||
case g.ver != ver || g.end() != from:
|
||||
// The ranges changed while this reply was in flight: its ids
|
||||
// stay unused, and the uncovered slots are reserved again.
|
||||
rd.r.assigns.failed.Add(1)
|
||||
g.next = reserveRetry
|
||||
default:
|
||||
g.spans = append(g.spans, roundSpan{from: from, rng: rng})
|
||||
g.next = reserveShort // only a short grant leaves slots uncovered now
|
||||
switch why {
|
||||
case reserveInitial:
|
||||
rd.r.assigns.initial.Add(1)
|
||||
case reserveShort:
|
||||
rd.r.assigns.short.Add(1)
|
||||
case reserveCapacity:
|
||||
rd.r.assigns.capacity.Add(1)
|
||||
case reserveExpired:
|
||||
rd.r.assigns.expired.Add(1)
|
||||
}
|
||||
}
|
||||
g.mu.Unlock()
|
||||
if err != nil {
|
||||
@@ -212,6 +298,9 @@ func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange,
|
||||
}
|
||||
}
|
||||
|
||||
// final marks an outcome no retry can change.
|
||||
func final(err error) error { return errors.Join(storage.ErrChunkPutFinal, err) }
|
||||
|
||||
// Put stores object i under key in its group's range and binds key to it.
|
||||
func (rd *putRound) Put(ctx context.Context, i int, key string, data []byte) error {
|
||||
if i < 0 || i >= rd.n {
|
||||
@@ -226,35 +315,77 @@ func (rd *putRound) Put(ctx context.Context, i int, key string, data []byte) err
|
||||
}
|
||||
g := rd.groups[i%len(rd.groups)]
|
||||
s := i / len(rd.groups)
|
||||
release, err := g.own(ctx, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rng, off, err := rd.slot(ctx, g, s)
|
||||
p, frozen := g.pinned(s)
|
||||
if !frozen {
|
||||
rng, off, err := rd.slot(ctx, g, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p = slotPin{rng: rng, off: off}
|
||||
}
|
||||
fid, err := p.rng.fid(p.off)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if dl, ok := rng.sendDeadline(); ok && !time.Now().Before(dl) {
|
||||
// Never sent: the unsent slots take a fresh range.
|
||||
if !g.retire(rng, s, reserveExpired) {
|
||||
return fmt.Errorf("chunkstore: round object %d: token expired before upload, replacements used up", i)
|
||||
if p.stored {
|
||||
if err := rd.r.bindKey(ctx, key, name, fid, data, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
g.unpin(s)
|
||||
return nil
|
||||
}
|
||||
dl, hasDL := p.rng.sendDeadline()
|
||||
if hasDL && !time.Now().Before(dl) {
|
||||
if frozen {
|
||||
// An earlier upload to fid is unresolved: read it back
|
||||
// before giving the fid up.
|
||||
got, perr := rd.rb.probe(ctx, p.rng, p.off)
|
||||
switch {
|
||||
case perr == nil && bytes.Equal(got, data):
|
||||
g.pin(s, slotPin{rng: p.rng, off: p.off, stored: true})
|
||||
continue
|
||||
case perr == nil:
|
||||
return final(fmt.Errorf("chunkstore: round object %d: %s holds other bytes", i, fid))
|
||||
case !errors.Is(perr, errBlobAbsent):
|
||||
return fmt.Errorf("chunkstore: round object %d: earlier upload to %s unresolved: %w", i, fid, perr)
|
||||
}
|
||||
g.unpin(s)
|
||||
}
|
||||
if !g.retire(p.rng, s, reserveExpired) {
|
||||
return final(fmt.Errorf("chunkstore: round object %d: token expired before upload, replacements used up", i))
|
||||
}
|
||||
continue
|
||||
}
|
||||
fid, err := rng.fid(off)
|
||||
if err != nil {
|
||||
return err
|
||||
pctx, cancel := ctx, context.CancelFunc(func() {})
|
||||
if hasDL {
|
||||
pctx, cancel = context.WithDeadline(ctx, dl)
|
||||
}
|
||||
err = rd.rb.putRange(ctx, rng, off, data)
|
||||
if errors.Is(err, errRangeRefused) {
|
||||
if !g.retire(rng, s, reserveCapacity) {
|
||||
return fmt.Errorf("chunkstore: round object %d: %w (replacements used up)", i, err)
|
||||
g.pin(s, p) // sent: frozen until resolved
|
||||
err = rd.rb.putRange(pctx, p.rng, p.off, data)
|
||||
cancel()
|
||||
switch {
|
||||
case err == nil:
|
||||
g.pin(s, slotPin{rng: p.rng, off: p.off, stored: true})
|
||||
continue
|
||||
case errors.Is(err, errRangeRefused):
|
||||
g.unpin(s) // definitely not stored
|
||||
if !g.retire(p.rng, s, reserveCapacity) {
|
||||
return final(fmt.Errorf("chunkstore: round object %d: %w (replacements used up)", i, err))
|
||||
}
|
||||
continue
|
||||
case errors.Is(err, errRangeAuth):
|
||||
g.unpin(s) // definitely not stored
|
||||
return final(err)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return rd.r.bindKey(ctx, key, name, fid, data, "")
|
||||
return err // outcome unknown: the slot stays frozen on fid
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -21,28 +22,31 @@ type rangeFake struct {
|
||||
reserves []int // requested counts, in order
|
||||
grant func(requested int) int
|
||||
auth func() string
|
||||
refuse func(fid string) error // non-nil: the put fails with it
|
||||
puts []string
|
||||
putAuth map[string]string
|
||||
inflight int
|
||||
peak int
|
||||
hold chan struct{} // non-nil: reserve waits for it (or ctx)
|
||||
refuse func(fid string) error // non-nil: the put fails with it (nothing stored)
|
||||
// reserveHook, when set, runs before each reserve (call counts from 1);
|
||||
// an error fails the reserve. It decides itself whether to follow ctx.
|
||||
reserveHook func(ctx context.Context, call int) error
|
||||
// putHook, when set, decides each put: store the bytes or not, and the
|
||||
// error to return (a stored put with an error is a lost reply).
|
||||
putHook func(ctx context.Context, fid string) (store bool, err error)
|
||||
puts []string
|
||||
putAuth map[string]string
|
||||
putDL map[string]time.Time // deadline of the context each put was sent under
|
||||
}
|
||||
|
||||
func newRangeFake() *rangeFake {
|
||||
return &rangeFake{fakeBlobs: newFakeBlobs(), nextVid: 1, putAuth: map[string]string{}}
|
||||
return &rangeFake{fakeBlobs: newFakeBlobs(), nextVid: 1, putAuth: map[string]string{}, putDL: map[string]time.Time{}}
|
||||
}
|
||||
|
||||
func (b *rangeFake) reserve(ctx context.Context, n int, _ uint64) (blobRange, error) {
|
||||
b.mu.Lock()
|
||||
b.reserves = append(b.reserves, n)
|
||||
hold := b.hold
|
||||
call := len(b.reserves)
|
||||
hook := b.reserveHook
|
||||
b.mu.Unlock()
|
||||
if hold != nil {
|
||||
select {
|
||||
case <-hold:
|
||||
case <-ctx.Done():
|
||||
return blobRange{}, ctx.Err()
|
||||
if hook != nil {
|
||||
if err := hook(ctx, call); err != nil {
|
||||
return blobRange{}, err
|
||||
}
|
||||
}
|
||||
b.mu.Lock()
|
||||
@@ -57,7 +61,7 @@ func (b *rangeFake) reserve(ctx context.Context, n int, _ uint64) (blobRange, er
|
||||
}
|
||||
vid := b.nextVid
|
||||
b.nextVid++
|
||||
return blobRange{base: fmt.Sprintf("%d,0a0b0c0d0e", vid), count: count, url: "fake", auth: auth}, nil
|
||||
return blobRange{base: fmt.Sprintf("%d,0a0b0c0d0e", vid), count: count, url: "fake:1", auth: auth}, nil
|
||||
}
|
||||
|
||||
func (b *rangeFake) putRange(ctx context.Context, r blobRange, i int, data []byte) error {
|
||||
@@ -68,17 +72,46 @@ func (b *rangeFake) putRange(ctx context.Context, r blobRange, i int, data []byt
|
||||
b.mu.Lock()
|
||||
b.puts = append(b.puts, fid)
|
||||
b.putAuth[fid] = r.auth
|
||||
refuse := b.refuse
|
||||
if dl, ok := ctx.Deadline(); ok {
|
||||
b.putDL[fid] = dl
|
||||
}
|
||||
refuse, hook := b.refuse, b.putHook
|
||||
b.mu.Unlock()
|
||||
store, perr := true, error(nil)
|
||||
if refuse != nil {
|
||||
if err := refuse(fid); err != nil {
|
||||
return err
|
||||
store, perr = false, err
|
||||
}
|
||||
}
|
||||
if hook != nil {
|
||||
store, perr = hook(ctx, fid)
|
||||
}
|
||||
if store {
|
||||
b.fakeBlobs.mu.Lock()
|
||||
b.fakeBlobs.data[fid] = append([]byte(nil), data...)
|
||||
b.fakeBlobs.mu.Unlock()
|
||||
}
|
||||
return perr
|
||||
}
|
||||
|
||||
func (b *rangeFake) probe(_ context.Context, r blobRange, i int) ([]byte, error) {
|
||||
fid, err := r.fid(i)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.fakeBlobs.mu.Lock()
|
||||
b.fakeBlobs.data[fid] = append([]byte(nil), data...)
|
||||
b.fakeBlobs.mu.Unlock()
|
||||
return nil
|
||||
defer b.fakeBlobs.mu.Unlock()
|
||||
d, ok := b.fakeBlobs.data[fid]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w %s", errBlobAbsent, fid)
|
||||
}
|
||||
return append([]byte(nil), d...), nil
|
||||
}
|
||||
|
||||
func (b *rangeFake) putList() []string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return append([]string(nil), b.puts...)
|
||||
}
|
||||
|
||||
func (b *rangeFake) reserveCounts() []int {
|
||||
@@ -321,23 +354,275 @@ func TestChunkRound_RetryKeepsTheSlot(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A reservation waiting on the filer ends with the caller's context, and a
|
||||
// reply that arrives after it never starts an upload.
|
||||
// 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()
|
||||
b.hold = make(chan struct{})
|
||||
hold := make(chan struct{})
|
||||
b.reserveHook = func(ctx context.Context, _ int) error {
|
||||
select {
|
||||
case <-hold:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
rd := r.BeginPutRound(1, 4096)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); !errors.Is(err, context.DeadlineExceeded) {
|
||||
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(b.hold)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// A replacement reply that arrives after a lower slot retired the group's
|
||||
// ranges is discarded: the group is reserved again from its first uncovered
|
||||
// slot, so no slot is left uncovered (and no zero-id reservation is asked).
|
||||
func TestChunkRound_StaleReplacementIsDiscarded(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
r := roundRemote(t, b)
|
||||
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 {
|
||||
if call == 2 {
|
||||
close(second)
|
||||
<-release
|
||||
}
|
||||
return nil
|
||||
}
|
||||
slot0Sent := make(chan struct{})
|
||||
b.putHook = func(_ 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
|
||||
return false, errRangeRefused
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
errs := make(chan error, 2)
|
||||
go func() { errs <- rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))) }()
|
||||
<-slot0Sent
|
||||
go func() { errs <- rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))) }()
|
||||
<-second
|
||||
for { // slot 0's refusal retires the rest of the group meanwhile
|
||||
g.mu.Lock()
|
||||
v := g.ver
|
||||
g.mu.Unlock()
|
||||
if v == 2 {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
close(release)
|
||||
for k := 0; k < 2; k++ {
|
||||
if err := <-errs; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got := b.reserveCounts()
|
||||
for _, n := range got {
|
||||
if n <= 0 {
|
||||
t.Fatalf("reservations %v: asked for %d ids", got, n)
|
||||
}
|
||||
}
|
||||
if len(got) != 3 || got[0] != 4 || got[1] != 3 || got[2] != 4 {
|
||||
t.Fatalf("reservations %v; want [4 3 4] (the stale [1,4) reply discarded)", got)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
if fid := r.fids[roundKey(i)]; !strings.HasPrefix(fid, "3,") {
|
||||
t.Fatalf("slot %d bound to %s; want the fresh range", i, fid)
|
||||
}
|
||||
}
|
||||
if a := r.AssignCounts(); a.Initial != 1 || a.Capacity != 1 || a.Retry != 1 || a.Failed != 1 {
|
||||
t.Fatalf("assign counts %+v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// A lost reservation reply is counted: the retry is an extra attempt.
|
||||
func TestChunkRound_LostReservationReplyIsCounted(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
b.reserveHook = func(_ context.Context, call int) error {
|
||||
if call == 1 {
|
||||
return errors.New("lost assign reply")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
rd := r.BeginPutRound(1, 4096)
|
||||
ctx := context.Background()
|
||||
if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); err == nil {
|
||||
t.Fatal("lost reply reported success")
|
||||
}
|
||||
if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a := r.AssignCounts(); a.Initial != 1 || a.Retry != 1 || a.Failed != 1 || a.Extra() != 1 {
|
||||
t.Fatalf("assign counts %+v; want 1 initial + 1 retry, 1 failed", a)
|
||||
}
|
||||
}
|
||||
|
||||
// An upload whose reply was lost keeps its fid: a retry after the group's
|
||||
// lower slot retired the range, or after the token expired, does not move
|
||||
// it. Past expiry the fid is read back: the exact bytes are bound there,
|
||||
// definitely absent bytes go to a fresh range.
|
||||
func TestChunkRound_AmbiguousUploadKeepsItsFid(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
t.Run("lower slot retires the range", func(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
lost := true
|
||||
b.putHook = func(_ context.Context, fid string) (bool, error) {
|
||||
switch {
|
||||
case fid == "1,0a0b0c0d0e_1" && lost:
|
||||
lost = false
|
||||
return false, errors.New("connection reset") // outcome unknown to the client
|
||||
case fid == "1,0a0b0c0d0e":
|
||||
return false, errRangeRefused
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
rd := r.BeginPutRound(2, 4096)
|
||||
if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err == nil {
|
||||
t.Fatal("lost reply reported success")
|
||||
}
|
||||
if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fid := r.fids[roundKey(1)]; fid != "1,0a0b0c0d0e_1" {
|
||||
t.Fatalf("retried slot bound to %s; want its first fid", fid)
|
||||
}
|
||||
if fid := r.fids[roundKey(0)]; !strings.HasPrefix(fid, "2,") {
|
||||
t.Fatalf("refused slot bound to %s; want the fresh range", fid)
|
||||
}
|
||||
})
|
||||
for _, stored := range []bool{true, false} {
|
||||
t.Run(fmt.Sprintf("token expires, stored=%v", stored), func(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
calls := 0
|
||||
b.auth = func() string {
|
||||
calls++
|
||||
if calls == 1 { // expires (less skew) about a second from now
|
||||
return jwtWithExp(time.Now().Add(jwtSendSkew + time.Second).Unix())
|
||||
}
|
||||
return jwtWithExp(time.Now().Add(time.Hour).Unix())
|
||||
}
|
||||
lost := true
|
||||
b.putHook = func(context.Context, string) (bool, error) {
|
||||
if lost {
|
||||
lost = false
|
||||
return stored, errors.New("reply lost")
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
rd := r.BeginPutRound(1, 4096)
|
||||
if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err == nil {
|
||||
t.Fatal("lost reply reported success")
|
||||
}
|
||||
b.mu.Lock()
|
||||
first := b.putAuth["1,0a0b0c0d0e"]
|
||||
b.mu.Unlock()
|
||||
dl, _ := (blobRange{auth: first}).sendDeadline()
|
||||
time.Sleep(time.Until(dl) + 10*time.Millisecond)
|
||||
if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fid, puts := r.fids[roundKey(0)], b.putList()
|
||||
if stored {
|
||||
if fid != "1,0a0b0c0d0e" || len(puts) != 1 {
|
||||
t.Fatalf("stored upload: bound %s after uploads %v; want its first fid, no resend", fid, puts)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(fid, "2,") || len(puts) != 2 {
|
||||
t.Fatalf("absent upload: bound %s after uploads %v; want a fresh range", fid, puts)
|
||||
}
|
||||
if a := r.AssignCounts(); a.Initial != 1 || a.Expired != 1 {
|
||||
t.Fatalf("assign counts %+v", a)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An upload is sent under its token's send deadline: a queued upload ends
|
||||
// there, not at the caller's later deadline.
|
||||
func TestChunkRound_UploadCarriesTheTokenDeadline(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
b.auth = func() string { return jwtWithExp(time.Now().Add(jwtSendSkew + time.Second).Unix()) }
|
||||
b.putHook = func(ctx context.Context, _ string) (bool, error) {
|
||||
<-ctx.Done() // queued until its context ends
|
||||
return false, ctx.Err()
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
err := r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x"))
|
||||
if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 10*time.Second {
|
||||
t.Fatalf("queued upload: %v after %v; want it ended at the token's deadline", err, time.Since(start))
|
||||
}
|
||||
b.mu.Lock()
|
||||
n := len(b.puts)
|
||||
b.mu.Unlock()
|
||||
if n != 0 {
|
||||
t.Fatalf("%d uploads after the caller gave up", n)
|
||||
defer b.mu.Unlock()
|
||||
for f, a := range b.putAuth {
|
||||
dl, _ := (blobRange{auth: a}).sendDeadline()
|
||||
if !b.putDL[f].Equal(dl) {
|
||||
t.Fatalf("upload to %s sent under deadline %v; want the token's %v", f, b.putDL[f], dl)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A rejected token and used-up replacements are final for the caller; a
|
||||
// transient failure is not.
|
||||
func TestChunkRound_FinalOutcomes(t *testing.T) {
|
||||
put := func(b *rangeFake) error {
|
||||
return roundRemote(t, b).BeginPutRound(1, 4096).Put(context.Background(), 0, roundKey(0), []byte("x"))
|
||||
}
|
||||
b := newRangeFake()
|
||||
b.refuse = func(string) error { return errRangeAuth }
|
||||
if err := put(b); !errors.Is(err, storage.ErrChunkPutFinal) {
|
||||
t.Fatalf("401: %v; want final", err)
|
||||
}
|
||||
b2 := newRangeFake()
|
||||
b2.refuse = func(string) error { return errRangeRefused }
|
||||
if err := put(b2); !errors.Is(err, storage.ErrChunkPutFinal) {
|
||||
t.Fatalf("replacements used up: %v; want final", err)
|
||||
}
|
||||
b3 := newRangeFake()
|
||||
b3.refuse = func(string) error { return errors.New("connection reset") }
|
||||
if err := put(b3); err == nil || errors.Is(err, storage.ErrChunkPutFinal) {
|
||||
t.Fatalf("transient failure: %v; want retryable", err)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -37,6 +39,9 @@ var (
|
||||
errRangeRefused = errors.New("chunkstore: volume refused the write before append")
|
||||
// errRangeAuth: the volume rejected the upload's token. Terminal.
|
||||
errRangeAuth = errors.New("chunkstore: volume rejected the upload token")
|
||||
// errBlobAbsent: the volume server holding a range has no needle at
|
||||
// the probed fid.
|
||||
errBlobAbsent = errors.New("chunkstore: no needle at fid")
|
||||
)
|
||||
|
||||
// blobRange is one batch reservation: count ids starting at base, on the
|
||||
@@ -86,13 +91,17 @@ func (r blobRange) sendDeadline() (time.Time, bool) {
|
||||
type rangeBlobs interface {
|
||||
reserve(ctx context.Context, n int, objSize uint64) (blobRange, error)
|
||||
putRange(ctx context.Context, r blobRange, i int, data []byte) error
|
||||
// probe reads offset i back from the range's volume server:
|
||||
// errBlobAbsent when that server definitely has no such needle.
|
||||
probe(ctx context.Context, r blobRange, i int) ([]byte, error)
|
||||
}
|
||||
|
||||
var _ rangeBlobs = (*SWFS)(nil)
|
||||
|
||||
// validBaseFid checks "<vid>,<key><cookie>": a decimal volume id, then hex
|
||||
// with at least a cookie's 8 digits after a key, and no offset suffix.
|
||||
func validBaseFid(fid string) error {
|
||||
// validBaseFid checks "<vid>,<key><cookie>" for a range of count ids: a
|
||||
// 32-bit decimal volume id, a 64-bit hex needle key (1 to 16 digits) and an
|
||||
// 8-digit hex cookie, no offset suffix, and room for key + count - 1.
|
||||
func validBaseFid(fid string, count int) error {
|
||||
vid, kc, ok := strings.Cut(fid, ",")
|
||||
if !ok || vid == "" {
|
||||
return fmt.Errorf("chunkstore: assign fid %q has no volume id", fid)
|
||||
@@ -100,14 +109,36 @@ func validBaseFid(fid string) error {
|
||||
if _, err := strconv.ParseUint(vid, 10, 32); err != nil {
|
||||
return fmt.Errorf("chunkstore: assign fid %q: volume id: %v", fid, err)
|
||||
}
|
||||
if len(kc) <= 8 {
|
||||
return fmt.Errorf("chunkstore: assign fid %q: no key before the cookie", fid)
|
||||
if len(kc) <= 8 || len(kc) > 16+8 {
|
||||
return fmt.Errorf("chunkstore: assign fid %q: want a 1..16 digit key and an 8 digit cookie", fid)
|
||||
}
|
||||
for _, c := range kc {
|
||||
if !strings.ContainsRune("0123456789abcdefABCDEF", c) {
|
||||
return fmt.Errorf("chunkstore: assign fid %q: not a plain hex key and cookie", fid)
|
||||
}
|
||||
}
|
||||
key, err := strconv.ParseUint(kc[:len(kc)-8], 16, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("chunkstore: assign fid %q: key: %v", fid, err)
|
||||
}
|
||||
if count > 0 && key > math.MaxUint64-uint64(count-1) {
|
||||
return fmt.Errorf("chunkstore: assign fid %q: key + %d overflows", fid, count-1)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validHostPort checks a volume server location: host:port, no scheme or path.
|
||||
func validHostPort(loc string) error {
|
||||
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 p, err := strconv.ParseUint(port, 10, 16); err != nil || p == 0 {
|
||||
return fmt.Errorf("chunkstore: assign location %q: bad port", loc)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -131,16 +162,16 @@ func (c *SWFS) reserve(ctx context.Context, n int, objSize uint64) (blobRange, e
|
||||
if ar.GetError() != "" {
|
||||
return blobRange{}, fmt.Errorf("chunkstore: assign %d: %s", n, ar.GetError())
|
||||
}
|
||||
if ar.GetLocation().GetUrl() == "" {
|
||||
return blobRange{}, fmt.Errorf("chunkstore: assign %d returned no location", n)
|
||||
}
|
||||
if err := validBaseFid(ar.GetFileId()); err != nil {
|
||||
if err := validHostPort(ar.GetLocation().GetUrl()); err != nil {
|
||||
return blobRange{}, err
|
||||
}
|
||||
count := int(ar.GetCount())
|
||||
if count <= 0 || count > n {
|
||||
return blobRange{}, fmt.Errorf("chunkstore: assign %d returned %d ids", n, count)
|
||||
}
|
||||
if err := validBaseFid(ar.GetFileId(), count); err != nil {
|
||||
return blobRange{}, err
|
||||
}
|
||||
return blobRange{base: ar.FileId, count: count, url: ar.Location.Url, auth: ar.GetAuth(), fsync: ar.GetFsync()}, nil
|
||||
}
|
||||
|
||||
@@ -155,6 +186,30 @@ func (c *SWFS) putRange(ctx context.Context, r blobRange, i int, data []byte) er
|
||||
return c.upload(ctx, r.url, fid, r.auth, r.fsync, data)
|
||||
}
|
||||
|
||||
// probe GETs offset i from the range's own volume server.
|
||||
func (c *SWFS) probe(ctx context.Context, r blobRange, i int) ([]byte, error) {
|
||||
fid, err := r.fid(i)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+r.url+"/"+fid, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("chunkstore: probe %s: %w", fid, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK:
|
||||
return io.ReadAll(resp.Body)
|
||||
case http.StatusNotFound:
|
||||
return nil, fmt.Errorf("%w %s", errBlobAbsent, fid)
|
||||
}
|
||||
return nil, fmt.Errorf("chunkstore: probe %s: http %d", fid, resp.StatusCode)
|
||||
}
|
||||
|
||||
// upload POSTs data raw to fid on the volume server at host.
|
||||
func (c *SWFS) upload(ctx context.Context, host, fid, auth string, fsync bool, data []byte) error {
|
||||
u := "http://" + host + "/" + fid
|
||||
|
||||
@@ -149,6 +149,17 @@ func TestSWFSRange_ReserveValidates(t *testing.T) {
|
||||
{"non-hex key", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0dzz", Count: 4, Location: loc}, false, 0},
|
||||
{"key too short for a cookie", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d", Count: 4, Location: loc}, false, 0},
|
||||
{"assign error", 4, &filerpb.AssignVolumeResponse{Error: "no free volumes"}, false, 0},
|
||||
{"location with a scheme", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "http://127.0.0.1:1"}}, false, 0},
|
||||
{"location without a port", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1"}}, false, 0},
|
||||
{"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},
|
||||
{"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},
|
||||
{"last offset fits", 2, &filerpb.AssignVolumeResponse{FileId: "3,fffffffffffffffe0a0b0c0d", Count: 2, Location: loc}, true, 2},
|
||||
{"last offset overflows the key", 3, &filerpb.AssignVolumeResponse{FileId: "3,fffffffffffffffe0a0b0c0d", Count: 3, Location: loc}, false, 0},
|
||||
{"volume id wider than 32 bits", 4, &filerpb.AssignVolumeResponse{FileId: "4294967296,0a0b0c0d0e", Count: 4, Location: loc}, false, 0},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
s := startFakeFiler(t, &fakeFilerGRPC{assignResp: c.resp})
|
||||
@@ -161,6 +172,19 @@ func TestSWFSRange_ReserveValidates(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, n := range []int{1, 256, 4096} {
|
||||
s := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: int32(n), Location: loc}})
|
||||
r, err := s.reserve(context.Background(), n, 4096)
|
||||
if err != nil || r.count != n {
|
||||
t.Fatalf("reserve %d: %+v %v", n, r, err)
|
||||
}
|
||||
if _, err := r.fid(n - 1); err != nil {
|
||||
t.Fatalf("reserve %d: last offset: %v", n, err)
|
||||
}
|
||||
if fid, err := r.fid(n); err == nil {
|
||||
t.Fatalf("reserve %d: offset %d gave %q", n, n, fid)
|
||||
}
|
||||
}
|
||||
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 {
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
package storage
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// ErrChunkPutFinal marks a Put failure no retry can change (for example a
|
||||
// rejected token): the caller stops retrying the object.
|
||||
var ErrChunkPutFinal = errors.New("storage: chunk upload refused for good")
|
||||
|
||||
// ChunkPutRounds is an optional ChunkRemote capability: the objects of one
|
||||
// upload round share remote reservations (batch assign) instead of taking
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -119,3 +121,150 @@ func TestChunkCut_FailedRoundPublishesNothing(t *testing.T) {
|
||||
t.Fatalf("installed %d HEADs after a failed upload", len(heads))
|
||||
}
|
||||
}
|
||||
|
||||
// A final upload outcome is not retried: the object is sent once, its
|
||||
// binding is checked, and the cut fails at once.
|
||||
func TestChunkCut_FinalUploadIsNotRetried(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
f := &roundChunkRemote{fakeChunkRemote: newFakeChunkRemote()}
|
||||
f.fail = func(int, int, int) error { return errors.Join(ErrChunkPutFinal, errors.New("token rejected")) }
|
||||
layer := mustAttach(t, s, f, ctConfig(1))
|
||||
w := newWriteLog()
|
||||
w.write(t, s, 2, 0x22)
|
||||
start := time.Now()
|
||||
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, ErrChunkPutFinal) {
|
||||
t.Fatalf("cut with a final upload refusal: %v", err)
|
||||
}
|
||||
if took := time.Since(start); took > 5*time.Second {
|
||||
t.Fatalf("cut took %v: the final refusal was retried", took)
|
||||
}
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for k, n := range f.tries {
|
||||
if n != 1 {
|
||||
t.Fatalf("object %v sent %d times; want once", k, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// heldRound blocks every round Put until released; cooperative Puts also
|
||||
// end with their context. It records the bytes of every attempt.
|
||||
type heldRound struct {
|
||||
*fakeChunkRemote
|
||||
cooperative bool
|
||||
entered chan struct{}
|
||||
release chan struct{}
|
||||
once sync.Once
|
||||
mu sync.Mutex
|
||||
sent [][]byte
|
||||
transient int // the first transient attempts fail after being recorded
|
||||
mutate func()
|
||||
}
|
||||
|
||||
func (h *heldRound) BeginPutRound(n, objSize int) ChunkPutRound { return heldRoundPut{h} }
|
||||
|
||||
type heldRoundPut struct{ h *heldRound }
|
||||
|
||||
func (p heldRoundPut) Put(ctx context.Context, i int, key string, data []byte) error {
|
||||
h := p.h
|
||||
h.mu.Lock()
|
||||
h.sent = append(h.sent, append([]byte(nil), data...))
|
||||
attempt := len(h.sent)
|
||||
mutate := h.mutate
|
||||
h.mu.Unlock()
|
||||
h.once.Do(func() { close(h.entered) })
|
||||
if mutate != nil && attempt == 1 {
|
||||
mutate()
|
||||
}
|
||||
if attempt <= h.transient {
|
||||
return errors.New("transient upload failure")
|
||||
}
|
||||
if h.cooperative {
|
||||
select {
|
||||
case <-h.release:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
} else {
|
||||
<-h.release
|
||||
}
|
||||
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.
|
||||
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{})}
|
||||
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)
|
||||
go func() { closeDone <- layer.Close() }()
|
||||
if !cooperative {
|
||||
select {
|
||||
case <-closeDone:
|
||||
t.Fatal("Close returned while an uncooperative upload call was still running")
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
close(h.release)
|
||||
}
|
||||
select {
|
||||
case <-closeDone:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("Close did not return")
|
||||
}
|
||||
select {
|
||||
case <-cutDone:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the cut did not end with Close")
|
||||
}
|
||||
if cooperative {
|
||||
close(h.release)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A retried upload sends the bytes captured for the cut, not the guest's
|
||||
// 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}
|
||||
close(h.release)
|
||||
w := newWriteLog()
|
||||
h.mutate = func() { w.write(t, s, 2, 0x99) } // the guest overwrites the block mid-upload
|
||||
layer := mustAttach(t, s, h, ctConfig(1))
|
||||
w.write(t, s, 2, 0x22)
|
||||
if _, err := layer.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.sent) != 2 {
|
||||
t.Fatalf("%d upload attempts; want the failed one and its retry", len(h.sent))
|
||||
}
|
||||
if !bytes.Equal(h.sent[0], h.sent[1]) {
|
||||
t.Fatal("the retry sent different bytes than the first attempt")
|
||||
}
|
||||
if bytes.Contains(h.sent[1], makeBlock(ctBlockSize, 0x99)) {
|
||||
t.Fatal("the retry sent the guest's newer write")
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,9 @@ func (l *chunkLayerImpl) putCapturedWith(ctx context.Context, key string, data [
|
||||
}
|
||||
return errChunkKeyExists
|
||||
}
|
||||
if errors.Is(err, ErrChunkPutFinal) {
|
||||
return err
|
||||
}
|
||||
timer := time.NewTimer(backoff)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
|
||||
Reference in new issue
Block a user