Merge #317 (4.3 batch assign) into train 5

This commit is contained in:
pingqiu committed 2026-11-20 19:27:27 -08:00
commit 0a3e9d345a
13 files changed
+2200 -41

No files matched your search

@@ -90,6 +90,8 @@ type ChunkRemote struct {
mu sync.Mutex
fids map[string]string // key -> fid; key entries are write-once
assigns assignCounters // reservations made by upload rounds
}
// NewChunkRemote returns the remote for the volume rooted at root, an
@@ -150,26 +152,42 @@ func (r *ChunkRemote) Put(ctx context.Context, key string, data []byte) error {
}
func (r *ChunkRemote) putObject(ctx context.Context, key string, data []byte, object string) error {
if err := storage.ValidChunkKey(key); err != nil {
return fmt.Errorf("%w: %v", ErrInvalidKey, err)
}
if strings.HasPrefix(key, "@") {
return fmt.Errorf("%w: %q is owner-qualified; a volume writes only its own keys", ErrInvalidKey, key)
}
name, err := keyName(key)
name, err := r.ownKeyName(key)
if err != nil {
return err
}
r.mu.Lock()
_, known := r.fids[key]
r.mu.Unlock()
if known {
if r.knownKey(key) {
return storage.ErrChunkKeyExists
}
fid, err := r.b.Put(ctx, data)
if err != nil {
return err
}
return r.bindKey(ctx, key, name, fid, data, object)
}
// ownKeyName checks that key is one of this volume's own keys and returns
// its binding's entry name.
func (r *ChunkRemote) ownKeyName(key string) (string, error) {
if err := storage.ValidChunkKey(key); err != nil {
return "", fmt.Errorf("%w: %v", ErrInvalidKey, err)
}
if strings.HasPrefix(key, "@") {
return "", fmt.Errorf("%w: %q is owner-qualified; a volume writes only its own keys", ErrInvalidKey, key)
}
return keyName(key)
}
// knownKey reports whether key is already bound (as far as this remote saw).
func (r *ChunkRemote) knownKey(key string) bool {
r.mu.Lock()
defer r.mu.Unlock()
_, known := r.fids[key]
return known
}
// bindKey binds key to the stored needle fid with an exclusive create.
func (r *ChunkRemote) bindKey(ctx context.Context, key, name, fid string, data []byte, object string) error {
now := time.Now().Unix()
e := &filerpb.Entry{
Name: name,
@@ -68,6 +68,13 @@ func waitTCP(t *testing.T, addr string, d time.Duration) {
}
func startWeed(t *testing.T) *weedCluster {
t.Helper()
return startWeedWith(t, "")
}
// startWeedWith starts the cluster with security (the contents of a
// security.toml in its working directory; "" for none).
func startWeedWith(t *testing.T, security string) *weedCluster {
t.Helper()
weed := os.Getenv("CHUNKSTORE_WEED")
if weed == "" {
@@ -112,6 +119,11 @@ func startWeed(t *testing.T) *weedCluster {
t.Fatal(err)
}
}
if security != "" {
if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte(security), 0o600); err != nil {
t.Fatal(err)
}
}
run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000")
waitTCP(t, c.master, 20*time.Second)
run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, "-max=32")
@@ -0,0 +1,391 @@
package chunkstore
// Upload rounds over batch assign. The n objects of one round are split into
// G = min(8, ceil(n/64)) groups (object i goes to group i % G, as slot i / G),
// and each group takes one reservation for all its slots, made when its
// first object is uploaded. So a round costs G assigns instead of n, its
// objects still spread over up to G volumes, and a round with no upload
// makes none.
//
// 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 (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"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
const (
roundGroupSize = 64
roundMaxGroups = 8
roundMaxReplacements = 3
)
// 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 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 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, retry, failed atomic.Int64 }
// 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(),
}
}
var _ storage.ChunkPutRounds = (*ChunkRemote)(nil)
// BeginPutRound starts a round of n objects of objSize bytes. Without batch
// support in the blob store, the round is one Put per object.
func (r *ChunkRemote) BeginPutRound(n, objSize int) storage.ChunkPutRound {
rb, ok := r.b.(rangeBlobs)
if !ok || n <= 0 {
return plainRound{r}
}
g := min(roundMaxGroups, (n+roundGroupSize-1)/roundGroupSize)
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, pins: map[int]slotPin{}, owners: map[int]chan struct{}{}}
}
return rd
}
type plainRound struct{ r *ChunkRemote }
func (p plainRound) Put(ctx context.Context, _ int, key string, data []byte) error {
return p.r.Put(ctx, key, data)
}
type putRound struct {
r *ChunkRemote
rb rangeBlobs
n int
size uint64
groups []*roundGroup
}
type reserveReason int
const (
reserveInitial reserveReason = iota
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
}
last := g.spans[len(g.spans)-1]
return last.from + last.rng.count
}
// lookup returns the range and offset of slot s, if reserved. g.mu held.
func (g *roundGroup) lookup(s int) (blobRange, int, bool) {
for _, sp := range g.spans {
if s >= sp.from && s < sp.from+sp.rng.count {
return sp.rng, s - sp.from, true
}
}
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 (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()
for k, sp := range g.spans {
if sp.rng.base != rng.base {
continue
}
if g.replacements >= roundMaxReplacements {
return false
}
g.replacements++
g.next = why
g.ver++
if s <= sp.from {
g.spans = g.spans[:k]
} else {
g.spans[k].rng.count = s - sp.from
g.spans = g.spans[:k+1]
}
return true
}
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. 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()
if rng, off, ok := g.lookup(s); ok {
g.mu.Unlock()
return rng, off, nil
}
if wait := g.reserving; wait != nil {
g.mu.Unlock()
select {
case <-wait:
continue
case <-ctx.Done():
return blobRange{}, 0, ctx.Err()
}
}
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()
}
g.mu.Lock()
g.reserving = nil
close(done)
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
}
g.mu.Unlock()
if err != nil {
return blobRange{}, 0, err
}
}
}
// 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 {
return fmt.Errorf("chunkstore: round object %d outside a round of %d", i, rd.n)
}
name, err := rd.r.ownKeyName(key)
if err != nil {
return err
}
if rd.r.knownKey(key) {
return storage.ErrChunkKeyExists
}
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
}
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 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
}
pctx, cancel := ctx, context.CancelFunc(func() {})
if hasDL {
pctx, cancel = context.WithDeadline(ctx, dl)
}
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)
}
return err // outcome unknown: the slot stays frozen on fid
}
}
@@ -0,0 +1,726 @@
package chunkstore
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// rangeFake is a blob store with batch reservations: each reserve hands out
// a new volume id; puts are recorded by fid. Hooks shape the replies.
type rangeFake struct {
*fakeBlobs
mu sync.Mutex
nextVid int
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 (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{}, 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)
call := len(b.reserves)
hook := b.reserveHook
b.mu.Unlock()
if hook != nil {
if err := hook(ctx, call); err != nil {
return blobRange{}, err
}
}
b.mu.Lock()
defer b.mu.Unlock()
count := n
if b.grant != nil {
count = b.grant(n)
}
auth := ""
if b.auth != nil {
auth = b.auth()
}
vid := b.nextVid
b.nextVid++
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 {
fid, err := r.fid(i)
if err != nil {
return err
}
b.mu.Lock()
b.puts = append(b.puts, fid)
b.putAuth[fid] = r.auth
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 {
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()
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 {
b.mu.Lock()
defer b.mu.Unlock()
return append([]int(nil), b.reserves...)
}
func roundRemote(t *testing.T, b *rangeFake) *ChunkRemote {
t.Helper()
r, err := NewChunkRemote(newFakeFiler(), b, "/swblock/vols/v1")
if err != nil {
t.Fatal(err)
}
return r
}
func roundKey(i int) string { return fmt.Sprintf("k%05d", i) }
// putAll runs one round of n objects with w concurrent workers.
func putAll(t *testing.T, r *ChunkRemote, n, w int) error {
t.Helper()
rd := r.BeginPutRound(n, 4096)
var mu sync.Mutex
next := 0
var first error
var wg sync.WaitGroup
for j := 0; j < w; j++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
mu.Lock()
i := next
next++
mu.Unlock()
if i >= n {
return
}
if err := rd.Put(context.Background(), i, roundKey(i), []byte(roundKey(i))); err != nil {
mu.Lock()
if first == nil {
first = err
}
mu.Unlock()
}
}
}()
}
wg.Wait()
return first
}
func checkBound(t *testing.T, r *ChunkRemote, n int) {
t.Helper()
for i := 0; i < n; i++ {
got, err := r.Get(context.Background(), roundKey(i))
if err != nil || !bytes.Equal(got, []byte(roundKey(i))) {
t.Fatalf("key %d: %q %v", i, got, err)
}
}
}
// D objects take G = min(8, ceil(D/64)) reservations, balanced across the
// groups; D = 0 makes none. Every key is bound to its own fid.
func TestChunkRound_GroupsPerRound(t *testing.T) {
for _, c := range []struct{ d, g int }{{0, 0}, {1, 1}, {64, 1}, {65, 2}, {512, 8}, {513, 8}, {1000, 8}} {
t.Run(fmt.Sprint(c.d), func(t *testing.T) {
b := newRangeFake()
r := roundRemote(t, b)
if err := putAll(t, r, c.d, 16); err != nil {
t.Fatal(err)
}
got := b.reserveCounts()
if len(got) != c.g {
t.Fatalf("%d reservations %v for %d objects, want %d", len(got), got, c.d, c.g)
}
total, lo, hi := 0, c.d, 0
for _, n := range got {
total += n
lo, hi = min(lo, n), max(hi, n)
}
if total != c.d || (c.g > 0 && hi-lo > 1) {
t.Fatalf("reservations %v: want %d ids balanced within one", got, c.d)
}
checkBound(t, r, c.d)
seen := map[string]bool{}
for i := 0; i < c.d; i++ {
fid := r.fids[roundKey(i)]
if seen[fid] {
t.Fatalf("fid %s bound twice", fid)
}
seen[fid] = true
}
if a := r.AssignCounts(); a.Initial != int64(c.g) || a.Extra() != 0 {
t.Fatalf("assign counts %+v, want %d initial, no extras", a, c.g)
}
})
}
}
// A short grant is topped up by a reservation for the remainder, counted as
// an extra, not an initial assign.
func TestChunkRound_ShortGrantReservesRemainder(t *testing.T) {
b := newRangeFake()
first := true
b.grant = func(n int) int {
if first {
first = false
return n / 2
}
return n
}
r := roundRemote(t, b)
if err := putAll(t, r, 10, 4); err != nil {
t.Fatal(err)
}
if got := b.reserveCounts(); len(got) != 2 || got[0] != 10 || got[1] != 5 {
t.Fatalf("reservations %v, want [10 5]", got)
}
checkBound(t, r, 10)
if a := r.AssignCounts(); a.Initial != 1 || a.Short != 1 || a.Extra() != 1 {
t.Fatalf("assign counts %+v", a)
}
}
// A definite capacity refusal leaves objects already stored on the old range
// alone and moves the rest of the group to a fresh range; a volume that keeps
// refusing ends the round after a bounded number of replacements.
func TestChunkRound_CapacityRefusalReplacesRemainder(t *testing.T) {
b := newRangeFake()
b.refuse = func(fid string) error {
// The first volume is full from its third id on.
if fid == "1,0a0b0c0d0e_2" || fid == "1,0a0b0c0d0e_3" {
return errRangeRefused
}
return nil
}
r := roundRemote(t, b)
if err := putAll(t, r, 6, 1); err != nil {
t.Fatal(err)
}
checkBound(t, r, 6)
if r.fids[roundKey(0)] != "1,0a0b0c0d0e" || r.fids[roundKey(1)] != "1,0a0b0c0d0e_1" {
t.Fatalf("committed prefix moved: %s %s", r.fids[roundKey(0)], r.fids[roundKey(1)])
}
if got := b.reserveCounts(); len(got) != 2 || got[1] != 4 {
t.Fatalf("reservations %v, want a fresh range for the remaining 4", got)
}
if a := r.AssignCounts(); a.Initial != 1 || a.Capacity != 1 {
t.Fatalf("assign counts %+v", a)
}
b2 := newRangeFake()
b2.refuse = func(string) error { return errRangeRefused }
r2 := roundRemote(t, b2)
err := putAll(t, r2, 3, 1)
if !errors.Is(err, errRangeRefused) {
t.Fatalf("always-full volumes: %v; want the refusal after bounded replacements", err)
}
if got := b2.reserveCounts(); len(got) != 1+roundMaxReplacements {
t.Fatalf("%d reservations %v; want 1 + %d replacements, then stop", len(got), got, roundMaxReplacements)
}
}
// An expired token is never sent: the remainder gets a fresh range. A 401 is
// terminal: no replacement.
func TestChunkRound_TokenExpiryAndAuth(t *testing.T) {
b := newRangeFake()
calls := 0
b.auth = func() string {
calls++
if calls == 1 {
return jwtWithExp(time.Now().Add(-time.Minute).Unix())
}
return jwtWithExp(time.Now().Add(time.Hour).Unix())
}
r := roundRemote(t, b)
if err := putAll(t, r, 3, 1); err != nil {
t.Fatal(err)
}
checkBound(t, r, 3)
b.mu.Lock()
for fid, a := range b.putAuth {
if exp, ok := (blobRange{auth: a}).sendDeadline(); !ok || exp.Before(time.Now()) {
t.Fatalf("upload to %s sent with an expired token", fid)
}
}
b.mu.Unlock()
if a := r.AssignCounts(); a.Initial != 1 || a.Expired != 1 {
t.Fatalf("assign counts %+v", a)
}
b2 := newRangeFake()
b2.refuse = func(string) error { return errRangeAuth }
r2 := roundRemote(t, b2)
if err := putAll(t, r2, 2, 1); !errors.Is(err, errRangeAuth) {
t.Fatalf("401: %v", err)
}
if got := b2.reserveCounts(); len(got) != 1 {
t.Fatalf("reservations %v after a 401; want no replacement", got)
}
}
// A transient failure leaves the slot frozen: the retry sends the same fid.
func TestChunkRound_RetryKeepsTheSlot(t *testing.T) {
b := newRangeFake()
failed := false
b.refuse = func(fid string) error {
if fid == "1,0a0b0c0d0e_1" && !failed {
failed = true
return errors.New("connection reset")
}
return nil
}
r := roundRemote(t, b)
rd := r.BeginPutRound(2, 4096)
ctx := context.Background()
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("transient failure reported success")
}
if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err != nil {
t.Fatal(err)
}
b.mu.Lock()
puts := append([]string(nil), b.puts...)
b.mu.Unlock()
if len(puts) != 3 || puts[1] != "1,0a0b0c0d0e_1" || puts[2] != "1,0a0b0c0d0e_1" {
t.Fatalf("uploads %v; want the retry on the same fid", puts)
}
if got := b.reserveCounts(); len(got) != 1 {
t.Fatalf("reservations %v; a transient failure takes no new range", got)
}
// A bound key is never rebound.
if err := rd.Put(ctx, 1, roundKey(1), []byte("other")); !errors.Is(err, storage.ErrChunkKeyExists) {
t.Fatalf("rebinding a key: %v", err)
}
}
// 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) {
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.WithCancel(context.Background())
defer cancel()
done := make(chan error, 1)
joined := false
t.Cleanup(func() { // ends and joins the worker whatever happens below
cancel()
if joined {
return
}
select {
case <-done:
case <-time.After(10 * time.Second):
t.Error("Put never returned")
}
})
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:
joined = true
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
// 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{})
var secondOnce sync.Once
release, releaseAll := releaser(t)
b.reserveHook = func(ctx context.Context, call int) error {
if call == 2 {
secondOnce.Do(func() { close(second) })
select {
case <-release:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
slot0Sent := make(chan struct{})
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)
select {
case <-second:
case <-ctx.Done():
return false, ctx.Err()
}
return false, errRangeRefused
}
return true, nil
}
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 ; started > 0; started-- {
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))) }()
waitFor(t, slot0Sent, "slot 0's upload")
started++
go func() { errs <- rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))) }()
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
g.mu.Unlock()
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)
}
releaseAll()
for started > 0 {
select {
case err := <-errs:
started-- // joined, before any Fatal: cleanup must not wait for it again
if err != nil {
t.Fatal(err)
}
case <-time.After(10 * time.Second):
t.Fatal("a round worker did not finish")
}
}
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()
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)
}
}
+1 -27
View File
@@ -1,9 +1,7 @@
package chunkstore
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
@@ -219,33 +217,9 @@ func (c *SWFS) Put(ctx context.Context, data []byte) (string, error) {
if ar.GetFileId() == "" || ar.GetLocation().GetUrl() == "" {
return "", fmt.Errorf("chunkstore: assign returned no fid/location")
}
u := "http://" + ar.Location.Url + "/" + ar.FileId
if ar.GetFsync() {
u += "?fsync=true"
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(data))
if err != nil {
if err := c.upload(ctx, ar.Location.Url, ar.FileId, ar.GetAuth(), ar.GetFsync(), data); err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/octet-stream")
if ar.GetAuth() != "" {
req.Header.Set("Authorization", "BEARER "+ar.Auth)
}
resp, err := c.http.Do(req)
if err != nil {
return "", fmt.Errorf("chunkstore: upload %s: %w", ar.FileId, err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if resp.StatusCode/100 != 2 {
return "", fmt.Errorf("chunkstore: upload %s: http %d: %s", ar.FileId, resp.StatusCode, strings.TrimSpace(string(body)))
}
var ur struct {
Error string `json:"error"`
}
if json.Unmarshal(body, &ur) == nil && ur.Error != "" {
return "", fmt.Errorf("chunkstore: upload %s: %s", ar.FileId, ur.Error)
}
return ar.FileId, nil
}
@@ -0,0 +1,262 @@
package chunkstore
// Batch assign: one AssignVolume(Count = n) reserves n consecutive needle ids
// on one volume. They are addressed in SeaweedFS's native form: offset 0 is
// the base fid, offset i is "<base>_<i>". The volume server adds i to the
// needle key and checks the assign's token against the base fid, so every
// offset carries the base's token and shares its cookie. Never write such an
// id as a different fid (key+i): that one has no token.
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
)
const (
// maxRangeCount bounds one reservation.
maxRangeCount = 1 << 16
// jwtSendSkew: an upload is not sent within this much of its token's
// stated expiry.
jwtSendSkew = 2 * time.Second
)
var (
// errRangeRefused: the volume refused the write before appending it
// (read-only or full). Nothing was stored; a fresh range may take it.
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
// volume server at url, with the assign's token and fsync policy.
type blobRange struct {
base string
count int
url string
auth string
fsync bool
}
// fid returns the native id of offset i.
func (r blobRange) fid(i int) (string, error) {
if i < 0 || i >= r.count {
return "", fmt.Errorf("chunkstore: offset %d outside a range of %d ids", i, r.count)
}
if i == 0 {
return r.base, nil
}
return r.base + "_" + strconv.Itoa(i), nil
}
// sendDeadline is the last time an upload with this range's token may be
// sent: the token's stated expiry less jwtSendSkew. The claim is read, not
// verified: it only ever stops an upload, it never authorizes one. A token
// without a readable expiry gives no deadline.
func (r blobRange) sendDeadline() (time.Time, bool) {
parts := strings.Split(r.auth, ".")
if len(parts) != 3 {
return time.Time{}, false
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return time.Time{}, false
}
var claims struct {
Exp *int64 `json:"exp"`
}
if json.Unmarshal(payload, &claims) != nil || claims.Exp == nil {
return time.Time{}, false
}
return time.Unix(*claims.Exp, 0).Add(-jwtSendSkew), true
}
// rangeBlobs is the optional batch capability of a blob store.
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>" 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)
}
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 || 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: 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 == "" {
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
}
// reserve asks for n ids of objSize bytes each (the master counts
// ExpectedDataSize per id). A shorter valid grant is returned as is; the
// caller reserves the rest.
func (c *SWFS) reserve(ctx context.Context, n int, objSize uint64) (blobRange, error) {
if n <= 0 || n > maxRangeCount {
return blobRange{}, fmt.Errorf("chunkstore: reserve %d ids: want 1..%d", n, maxRangeCount)
}
ar, err := c.fc.AssignVolume(ctx, &filerpb.AssignVolumeRequest{
Count: int32(n),
Collection: c.cfg.Collection,
Replication: c.cfg.Replication,
Path: c.cfg.AssignPath,
ExpectedDataSize: objSize,
})
if err != nil {
return blobRange{}, fmt.Errorf("chunkstore: assign %d: %w", n, err)
}
if ar.GetError() != "" {
return blobRange{}, fmt.Errorf("chunkstore: assign %d: %s", n, ar.GetError())
}
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
}
// putRange uploads data as offset i of r. A refusal before append is
// errRangeRefused, a rejected token errRangeAuth; any other failure is
// returned as is (the caller retries the same offset).
func (c *SWFS) putRange(ctx context.Context, r blobRange, i int, data []byte) error {
fid, err := r.fid(i)
if err != nil {
return err
}
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
if fsync {
u += "?fsync=true"
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(data))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/octet-stream")
if auth != "" {
req.Header.Set("Authorization", "BEARER "+auth)
}
resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("chunkstore: upload %s: %w", fid, err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if resp.StatusCode/100 != 2 {
err := fmt.Errorf("chunkstore: upload %s: http %d: %s", fid, resp.StatusCode, strings.TrimSpace(string(body)))
switch {
case resp.StatusCode == http.StatusUnauthorized:
return errors.Join(errRangeAuth, err)
case resp.StatusCode == http.StatusConflict,
resp.Header.Get("X-Seaweed-Write-Outcome") == "refused-before-append":
return errors.Join(errRangeRefused, err)
}
return err
}
var ur struct {
Error string `json:"error"`
}
if json.Unmarshal(body, &ur) == nil && ur.Error != "" {
return fmt.Errorf("chunkstore: upload %s: %s", fid, ur.Error)
}
return nil
}
@@ -0,0 +1,108 @@
//go:build chunkstore_integration
package chunkstore
import (
"bytes"
"context"
"errors"
"fmt"
"strconv"
"strings"
"testing"
"time"
)
const jwtSecurity = `[jwt.signing]
key = "batch-assign-integration"
expires_after_seconds = 60
`
// arithmeticFid is the fid key+i with the base's cookie: a different needle
// id, which the base's token does not cover.
func arithmeticFid(t *testing.T, base string, i int) string {
t.Helper()
vid, kc, _ := strings.Cut(base, ",")
key, err := strconv.ParseUint(kc[:len(kc)-8], 16, 64)
if err != nil {
t.Fatal(err)
}
return fmt.Sprintf("%s,%x%s", vid, key+uint64(i), kc[len(kc)-8:])
}
// With JWT on, every offset of a reservation is written with the base's
// token in the native "<base>_<i>" form and reads back as itself; the same
// token on the arithmetic fid key+i is refused.
func TestIntegrationBatch_JWTNativeOffsets(t *testing.T) {
c := startWeedWith(t, jwtSecurity)
cl := c.client(t, "/swblock/vols/v1")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
const n = 5
r, err := cl.reserve(ctx, n, 4096)
if err != nil {
t.Fatal(err)
}
if r.auth == "" {
t.Fatal("assign with JWT on returned no token")
}
if r.count != n {
t.Fatalf("reserved %d of %d", r.count, n)
}
data := func(i int) []byte { return bytes.Repeat([]byte(fmt.Sprintf("offset-%d|", i)), 400) }
for _, i := range []int{0, 2, n - 1} { // first, middle, last
if err := cl.putRange(ctx, r, i, data(i)); err != nil {
t.Fatalf("offset %d: %v", i, err)
}
}
for _, i := range []int{0, 2, n - 1} {
fid, _ := r.fid(i)
got, err := cl.Get(ctx, fid)
if err != nil || !bytes.Equal(got, data(i)) {
t.Fatalf("offset %d (%s) read back %d bytes, %v", i, fid, len(got), err)
}
}
arith := arithmeticFid(t, r.base, 1)
err = cl.upload(ctx, r.url, arith, r.auth, r.fsync, data(1))
if !errors.Is(err, errRangeAuth) {
t.Fatalf("upload to the arithmetic fid %s with the base token: %v; want a rejected token", arith, err)
}
}
// A round of more than one group writes through real assigns, binds every
// key, and reads every key back; it takes one assign per group.
func TestIntegrationBatch_RoundBindsAndReadsBack(t *testing.T) {
c := startWeedWith(t, jwtSecurity)
cl := c.client(t, "/swblock/vols/v1")
r, err := NewChunkRemote(cl, cl, "/swblock/vols/v1")
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
const n = 130 // three groups
rd := r.BeginPutRound(n, 4096)
for i := 0; i < n; i++ {
if err := rd.Put(ctx, i, roundKey(i), []byte(roundKey(i))); err != nil {
t.Fatalf("object %d: %v", i, err)
}
}
for i := 0; i < n; i++ {
got, err := r.Get(ctx, roundKey(i))
if err != nil || !bytes.Equal(got, []byte(roundKey(i))) {
t.Fatalf("key %d read back %q, %v", i, got, err)
}
}
if a := r.AssignCounts(); a.Initial != 3 || a.Extra() != 0 {
t.Fatalf("assign counts %+v; want 3 initial", a)
}
suffixed := 0
for i := 0; i < n; i++ {
if strings.Contains(r.fids[roundKey(i)], "_") {
suffixed++
}
}
if suffixed != n-3 {
t.Fatalf("%d of %d bindings use an offset fid; want all but the 3 bases", suffixed, n)
}
}
@@ -0,0 +1,285 @@
package chunkstore
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
)
// batchVolume is a volume server that records every upload by its path (the
// fid as sent), with the Authorization header and query.
type batchVolume struct {
mu sync.Mutex
stored map[string][]byte
auth map[string]string
query map[string]string
refuse func(fid string) (status int, header string) // non-zero status: refuse
srv *httptest.Server
uploads []string
}
func newBatchVolume(t *testing.T) *batchVolume {
v := &batchVolume{stored: map[string][]byte{}, auth: map[string]string{}, query: map[string]string{}}
v.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fid := strings.TrimPrefix(r.URL.Path, "/")
b, _ := io.ReadAll(r.Body)
v.mu.Lock()
defer v.mu.Unlock()
if r.Method != http.MethodPost {
if d, ok := v.stored[fid]; ok {
_, _ = w.Write(d)
return
}
w.WriteHeader(http.StatusNotFound)
return
}
v.uploads = append(v.uploads, fid)
if v.refuse != nil {
if st, h := v.refuse(fid); st != 0 {
if h != "" {
w.Header().Set("X-Seaweed-Write-Outcome", h)
}
w.WriteHeader(st)
_, _ = w.Write([]byte(`{"error":"refused"}`))
return
}
}
v.stored[fid] = b
v.auth[fid] = r.Header.Get("Authorization")
v.query[fid] = r.URL.RawQuery
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"size":1}`))
}))
t.Cleanup(v.srv.Close)
return v
}
func (v *batchVolume) host() string { return strings.TrimPrefix(v.srv.URL, "http://") }
func (v *batchVolume) snapshot() (uploads []string, stored map[string][]byte, auth map[string]string) {
v.mu.Lock()
defer v.mu.Unlock()
stored, auth = map[string][]byte{}, map[string]string{}
for k, d := range v.stored {
stored[k] = d
}
for k, a := range v.auth {
auth[k] = a
}
return append([]string(nil), v.uploads...), stored, auth
}
// One reservation of n ids is addressed in SeaweedFS's native form: offset 0
// is the base fid, offset i is "<base>_<i>"; every offset carries the base's
// token and the assign's fsync policy.
func TestSWFSRange_NativeOffsetFids(t *testing.T) {
vol := newBatchVolume(t)
f := &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "7,01abcdef12", Count: 3, Auth: "tok", Fsync: true, Location: &filerpb.Location{Url: vol.host()}}}
c := startFakeFiler(t, f)
ctx := context.Background()
r, err := c.reserve(ctx, 3, 4096)
if err != nil {
t.Fatal(err)
}
if f.lastAssign.Count != 3 || f.lastAssign.ExpectedDataSize != 4096 || f.lastAssign.Collection != "swblock" || f.lastAssign.Path != "/swblock/vols/v1" {
t.Fatalf("assign request %+v; want count 3 and the per-object expected size", f.lastAssign)
}
want := []string{"7,01abcdef12", "7,01abcdef12_1", "7,01abcdef12_2"}
for i, w := range want {
fid, err := r.fid(i)
if err != nil || fid != w {
t.Fatalf("offset %d: fid %q %v, want %q", i, fid, err, w)
}
if err := c.putRange(ctx, r, i, []byte(fmt.Sprintf("obj%d", i))); err != nil {
t.Fatalf("offset %d: %v", i, err)
}
}
_, stored, auth := vol.snapshot()
vol.mu.Lock()
query := vol.query
vol.mu.Unlock()
for i, w := range want {
if !bytes.Equal(stored[w], []byte(fmt.Sprintf("obj%d", i))) {
t.Fatalf("offset %d stored %q at %s", i, stored[w], w)
}
if auth[w] != "BEARER tok" {
t.Fatalf("offset %d authorization %q; want the base token", i, auth[w])
}
if q := query[w]; q != "fsync=true" {
t.Fatalf("offset %d query %q; want the assign's fsync policy", i, q)
}
}
for _, i := range []int{-1, 3, 4} {
if fid, err := r.fid(i); err == nil {
t.Fatalf("offset %d outside a range of 3 gave fid %q", i, fid)
}
}
}
// A reservation reply is checked before any id in it is used.
func TestSWFSRange_ReserveValidates(t *testing.T) {
loc := &filerpb.Location{Url: "127.0.0.1:1"}
for _, c := range []struct {
name string
n int
resp *filerpb.AssignVolumeResponse
ok bool
want int
}{
{"full grant", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: loc}, true, 4},
{"short grant", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 2, Location: loc}, true, 2},
{"zero count", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 0, Location: loc}, false, 0},
{"more than asked", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 5, Location: loc}, false, 0},
{"no location", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4}, false, 0},
{"no fid", 4, &filerpb.AssignVolumeResponse{Count: 4, Location: loc}, false, 0},
{"fid with a suffix", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e_1", Count: 4, Location: loc}, false, 0},
{"fid without a comma", 4, &filerpb.AssignVolumeResponse{FileId: "30a0b0c0d0e", Count: 4, Location: loc}, false, 0},
{"non-numeric volume", 4, &filerpb.AssignVolumeResponse{FileId: "x,0a0b0c0d0e", Count: 4, Location: loc}, false, 0},
{"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},
{"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},
{"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})
r, err := s.reserve(context.Background(), c.n, 4096)
if c.ok != (err == nil) {
t.Fatalf("reserve: %+v %v; want ok=%v", r, err, c.ok)
}
if c.ok && r.count != c.want {
t.Fatalf("count %d, want %d", r.count, c.want)
}
})
}
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)
}
}
// 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 {
t.Fatalf("reserve of %d ids accepted", n)
}
}
}
// A read-only volume (409, or a write refused before append) is a definite
// refusal: nothing was appended, so a fresh range may take the object. A 401
// is terminal. Anything else is not classified (the caller retries the same
// slot).
func TestSWFSRange_PutClassifiesRefusals(t *testing.T) {
vol := newBatchVolume(t)
f := &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "7,01abcdef12", Count: 4, Location: &filerpb.Location{Url: vol.host()}}}
c := startFakeFiler(t, f)
ctx := context.Background()
r, err := c.reserve(ctx, 4, 4096)
if err != nil {
t.Fatal(err)
}
vol.mu.Lock()
vol.refuse = func(fid string) (int, string) {
switch fid {
case "7,01abcdef12":
return http.StatusConflict, ""
case "7,01abcdef12_1":
return http.StatusInternalServerError, "refused-before-append"
case "7,01abcdef12_2":
return http.StatusUnauthorized, ""
case "7,01abcdef12_3":
return http.StatusInternalServerError, ""
}
return 0, ""
}
vol.mu.Unlock()
for i, want := range []error{errRangeRefused, errRangeRefused, errRangeAuth, nil} {
err := c.putRange(ctx, r, i, []byte("x"))
if err == nil {
t.Fatalf("offset %d: refused upload reported success", i)
}
for _, e := range []error{errRangeRefused, errRangeAuth} {
if errors.Is(err, e) != (e == want) {
t.Fatalf("offset %d: %v; classified as %v=%v, want %v", i, err, e, errors.Is(err, e), want)
}
}
}
}
// jwtWithExp returns an unsigned token whose payload names exp (unix seconds).
func jwtWithExp(exp int64) string {
enc := base64.RawURLEncoding
return enc.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`)) + "." +
enc.EncodeToString([]byte(fmt.Sprintf(`{"exp":%d,"fid":"7,01abcdef12"}`, exp))) + ".sig"
}
// The send deadline of a range is its token's stated expiry less a skew; a
// token with no readable expiry gives no deadline.
func TestSWFSRange_TokenSendDeadline(t *testing.T) {
now := time.Unix(1700000000, 0)
for _, c := range []struct {
name string
auth string
ok bool
want time.Time
}{
{"no token", "", false, time.Time{}},
{"opaque token", "tok", false, time.Time{}},
{"no exp claim", base64.RawURLEncoding.EncodeToString([]byte(`{}`)) + "." + base64.RawURLEncoding.EncodeToString([]byte(`{"fid":"x"}`)) + ".s", false, time.Time{}},
{"exp", jwtWithExp(now.Unix() + 10), true, now.Add(10*time.Second - jwtSendSkew)},
} {
got, ok := blobRange{auth: c.auth}.sendDeadline()
if ok != c.ok || !got.Equal(c.want) {
t.Errorf("%s: deadline %v %v, want %v %v", c.name, got, ok, c.want, c.ok)
}
}
}
@@ -51,6 +51,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
var once sync.Once
var intent string
var intentErr error
put := l.beginPutRound(len(batch))
err := l.uploadBatch(ctx, len(batch), func(ctx context.Context, i int) error {
c, err := read(ctx, batch[i])
if err != nil {
@@ -69,7 +70,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
return fmt.Errorf("storage: capture intent: %w: %w", errChunkRemoteUnavailable, intentErr)
}
c.intent = intent
if err := l.putCaptured(ctx, c.key, c.data); err != nil {
if err := l.putCapturedWith(ctx, c.key, c.data, func(ctx context.Context) error { return put(ctx, i, c.key, c.data) }); err != nil {
return fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err))
}
}
+2 -1
View File
@@ -1010,9 +1010,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
st.PublishPrepareNs += time.Since(prepareStart).Nanoseconds()
payloadStart := time.Now()
put := l.beginPutRound(len(uploads))
if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error {
u := uploads[i]
return l.putCaptured(ctx, u.key, u.c.data)
return l.putCapturedWith(ctx, u.key, u.c.data, func(ctx context.Context) error { return put(ctx, i, u.key, u.c.data) })
}); err != nil {
l.abortCut(all)
dropCapturedIntents(ctx, intents)
@@ -0,0 +1,37 @@
package storage
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
// one each. The round belongs to the cut or staging round that begins it and
// ends with it; it starts no goroutine of its own, so joining the round's
// workers joins every call it made.
type ChunkPutRounds interface {
BeginPutRound(n, objSize int) ChunkPutRound
}
// ChunkPutRound stores object i (0 <= i < n) of its round under key, with
// Put's rules: a bound key is never rebound (ErrChunkKeyExists). A failed Put
// may be retried with the same i and bytes.
type ChunkPutRound interface {
Put(ctx context.Context, i int, key string, data []byte) error
}
// beginPutRound returns the put for a round of n objects: the remote's
// round when it has one, otherwise one Put per object.
func (l *chunkLayerImpl) beginPutRound(n int) func(ctx context.Context, i int, key string, data []byte) error {
if rounds, ok := l.remote.(ChunkPutRounds); ok && n > 0 {
return rounds.BeginPutRound(n, int(uint64(l.blockSize)*l.chunkBlocks)).Put
}
return func(ctx context.Context, _ int, key string, data []byte) error {
return l.remote.Put(ctx, key, data)
}
}
@@ -0,0 +1,335 @@
package storage
import (
"bytes"
"context"
"errors"
"fmt"
"sync"
"testing"
"time"
)
// roundChunkRemote adds upload rounds to the fake remote and records them.
type roundChunkRemote struct {
*fakeChunkRemote
mu sync.Mutex
rounds []int // n of each round begun
puts [][2]int // {round, i} of each round Put
keys []string // key of each round Put
fail func(round, i int, attempt int) error
tries map[[2]int]int
}
type recordedRound struct {
r *roundChunkRemote
id int
}
func (r *roundChunkRemote) BeginPutRound(n, objSize int) ChunkPutRound {
r.mu.Lock()
defer r.mu.Unlock()
r.rounds = append(r.rounds, n)
return recordedRound{r: r, id: len(r.rounds) - 1}
}
func (rr recordedRound) Put(ctx context.Context, i int, key string, data []byte) error {
r := rr.r
r.mu.Lock()
r.puts = append(r.puts, [2]int{rr.id, i})
r.keys = append(r.keys, key)
if r.tries == nil {
r.tries = map[[2]int]int{}
}
r.tries[[2]int{rr.id, i}]++
attempt := r.tries[[2]int{rr.id, i}]
fail := r.fail
r.mu.Unlock()
if fail != nil {
if err := fail(rr.id, i, attempt); err != nil {
return err
}
}
return r.fakeChunkRemote.Put(ctx, key, data)
}
// A cut uploads its changed chunks through one round of the remote, one
// object index per chunk (the round may be sized for more candidates than
// end up changed); a cut with nothing to upload begins none. A retried
// upload keeps its index.
func TestChunkCut_UploadsThroughOneRound(t *testing.T) {
s, _ := newChunkTestStore(t)
f := &roundChunkRemote{fakeChunkRemote: newFakeChunkRemote()}
f.fail = func(round, i, attempt int) error {
if i == 0 && attempt == 1 {
return errors.New("transient upload failure")
}
return nil
}
layer := mustAttach(t, s, f, ctConfig(1))
w := newWriteLog()
w.write(t, s, 2, 0x22)
w.write(t, s, 9, 0x29)
if _, err := layer.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
f.mu.Lock()
rounds, puts := append([]int(nil), f.rounds...), append([][2]int(nil), f.puts...)
f.mu.Unlock()
if len(rounds) != 1 || rounds[0] < 1 {
t.Fatalf("rounds %v; want one round for the cut", rounds)
}
seen := map[int]int{}
for _, p := range puts {
if p[0] != 0 || p[1] < 0 || p[1] >= rounds[0] {
t.Fatalf("round put %v outside round 0 of %d", p, rounds[0])
}
seen[p[1]]++
}
if seen[0] != 2 {
t.Fatalf("object 0 sent %d times; want the failed attempt and its retry on the same index", seen[0])
}
if len(seen) != 2 {
t.Fatalf("round of %d used indexes %v; want one per changed chunk (2)", rounds[0], seen)
}
if _, err := layer.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
f.mu.Lock()
n := len(f.rounds)
f.mu.Unlock()
if n != 1 {
t.Fatalf("a cut with nothing to upload began a round (%d rounds)", n)
}
}
// A round that cannot store an object fails the cut: no HEAD names it.
func TestChunkCut_FailedRoundPublishesNothing(t *testing.T) {
s, _ := newChunkTestStore(t)
f := &roundChunkRemote{fakeChunkRemote: newFakeChunkRemote()}
f.fail = func(int, int, int) error { return ErrChunkKeyExists }
layer := mustAttach(t, s, f, ctConfig(1))
w := newWriteLog()
w.write(t, s, 2, 0x22)
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
if _, err := layer.Cut(ctx); err == nil {
t.Fatal("cut with a refused upload succeeded")
}
if heads := f.installedHeads(); len(heads) != 0 {
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, 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 }
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")
}
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:
case <-ctx.Done():
return ctx.Err()
}
} else {
<-h.release
}
return h.fakeChunkRemote.Put(ctx, key, data)
}
// 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 := 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)
closeDone := make(chan error, 1)
guest := make(chan error, 1)
closeStarted, guestStarted := false, false
t.Cleanup(func() { // release, then join every worker started and not yet joined
release()
for _, c := range []struct {
ch chan error
started bool
}{{cutDone, true}, {closeDone, closeStarted}, {guest, guestStarted}} {
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")
guestStarted = true
go func() {
if _, err := s.Write(7, makeBlock(ctBlockSize, 0x77)); err != nil {
guest <- err
return
}
_, err := s.Sync()
guest <- err
}()
select {
case err := <-guest:
guestStarted = false // joined
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 err := <-closeDone:
closeDone <- err
t.Fatal("Close returned while an uncooperative upload call was still running")
case <-time.After(300 * time.Millisecond):
}
release()
}
select {
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 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")
}
})
}
}
// 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 := 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
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")
}
}
+10 -1
View File
@@ -14,6 +14,12 @@ import (
// Keep the point and frozen buffer through transient failures until the cut
// context ends (deadline, Close or window abort), never a fresh point.
func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byte) error {
return l.putCapturedWith(ctx, key, data, func(ctx context.Context) error { return l.remote.Put(ctx, key, data) })
}
// putCapturedWith is putCaptured over put, one object's slot in an upload
// round: every retry sends through the same put.
func (l *chunkLayerImpl) putCapturedWith(ctx context.Context, key string, data []byte, put func(context.Context) error) error {
// The per-object retry deadline also bounds a contextless cut. It retains
// the same point and buffer through a remote outage, never re-reads live data.
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
@@ -24,7 +30,7 @@ func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byt
if err := ctx.Err(); err != nil {
return errors.Join(lastErr, err)
}
err := l.remote.Put(ctx, key, data)
err := put(ctx)
if err == nil {
return nil
}
@@ -37,6 +43,9 @@ func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byt
}
return errChunkKeyExists
}
if errors.Is(err, ErrChunkPutFinal) {
return err
}
timer := time.NewTimer(backoff)
select {
case <-ctx.Done():