mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Merge branch 'main' into test/seed-log-duration-regex
This commit is contained in:
commit
8a50adddf7
146 files changed
+10536
-433
No files matched your search
+5
-1
@@ -37,7 +37,11 @@ jobs:
|
||||
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
# The self-hosted runner keeps GOCACHE/GOMODCACHE on its own disk;
|
||||
# uploading them as an Actions cache (~4 GB) in the post step
|
||||
# outlasted the job timeout after every test had passed. Only the
|
||||
# GitHub-hosted (fork PR) runner uses the Actions cache.
|
||||
cache: ${{ runner.environment == 'github-hosted' }}
|
||||
cache-dependency-path: go.sum
|
||||
|
||||
- name: Go version
|
||||
|
||||
@@ -29,13 +29,15 @@ const (
|
||||
)
|
||||
|
||||
type chunkFlags struct {
|
||||
filer string
|
||||
path string
|
||||
collection string
|
||||
replication string
|
||||
captureInterval time.Duration
|
||||
dirtyThreshold int
|
||||
uploadConcurrency int
|
||||
filer string
|
||||
path string
|
||||
collection string
|
||||
replication string
|
||||
captureInterval time.Duration
|
||||
dirtyThreshold int
|
||||
uploadConcurrency int
|
||||
hydrationWorkers int
|
||||
hydrationQueueDepth int
|
||||
// controlEndpoint mounts the /chunk/* routes on the status listener.
|
||||
controlEndpoint bool
|
||||
}
|
||||
@@ -45,7 +47,7 @@ func validateChunkFlags(f flags) error {
|
||||
if f.durableImpl != "walstore-chunk" {
|
||||
if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath ||
|
||||
c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold ||
|
||||
c.uploadConcurrency != 8 || c.controlEndpoint {
|
||||
c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint {
|
||||
return errors.New("--chunk-* flags require --durable-impl=walstore-chunk")
|
||||
}
|
||||
return nil
|
||||
@@ -53,6 +55,9 @@ func validateChunkFlags(f flags) error {
|
||||
if c.controlEndpoint && f.statusAddr == "" {
|
||||
return errors.New("--chunk-control-endpoint requires --status-addr")
|
||||
}
|
||||
if f.replicationAck != "" && f.replicationAck != "best-effort" {
|
||||
return fmt.Errorf("--durable-impl=walstore-chunk is single-replica: --replication-ack=%q needs replica peers (%s)", f.replicationAck, chunkRF1Reason)
|
||||
}
|
||||
if f.durableRoot == "" {
|
||||
return errors.New("--durable-impl=walstore-chunk requires --durable-root")
|
||||
}
|
||||
@@ -68,12 +73,25 @@ func validateChunkFlags(f flags) error {
|
||||
if c.uploadConcurrency < 1 || c.uploadConcurrency > 64 {
|
||||
return errors.New("--chunk-upload-concurrency must be between 1 and 64")
|
||||
}
|
||||
if c.hydrationWorkers < 1 || c.hydrationWorkers > 64 {
|
||||
return errors.New("--chunk-hydration-workers must be between 1 and 64")
|
||||
}
|
||||
if c.hydrationQueueDepth < 1 || c.hydrationQueueDepth > 65536 {
|
||||
return errors.New("--chunk-hydration-queue-depth must be between 1 and 65536")
|
||||
}
|
||||
if c.dirtyThreshold < 0 {
|
||||
return fmt.Errorf("--chunk-dirty-threshold=%d must not be negative", c.dirtyThreshold)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// chunkRF1Reason is why a walstore-chunk volume refuses replication, at start
|
||||
// and on every assignment with replica slots: a chunk cut takes its LSN from the
|
||||
// local WAL head, which no replica is guaranteed to hold, so a published HEAD
|
||||
// could be ahead of every replica. The master's workspace RPCs enforce RF1; this
|
||||
// is the same rule on the volume server, for a direct start.
|
||||
const chunkRF1Reason = "chunk snapshots take the cut LSN from the local WAL, which replicas may not hold; walstore-chunk is RF1 only"
|
||||
|
||||
// chunkWiring is what --durable-impl=walstore-chunk dials once: the
|
||||
// provider's per-volume remotes, the catalog under the same base (VOLUME
|
||||
// entries, snapshots) and the client's closer.
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// A walstore-chunk volume is RF1 only: a chunk cut takes its LSN from the local
|
||||
// WAL head, which replicas may not hold. A direct start must refuse replication
|
||||
// (the master's workspace RPCs already do).
|
||||
func TestChunkVolumeRefusesReplicationAckAtStart(t *testing.T) {
|
||||
base := []string{"--master", "127.0.0.1:1", "--server-id", "node-a", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:9100", "--ctrl-addr", "127.0.0.1:9101"}
|
||||
chunk := append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore-chunk", "--chunk-filer", "127.0.0.1:18888")
|
||||
for _, ack := range []string{"sync-quorum", "sync-all"} {
|
||||
_, err := parseFlags(append(append([]string{}, chunk...), "--replication-ack", ack))
|
||||
if err == nil || !strings.Contains(err.Error(), "single-replica") || !strings.Contains(err.Error(), "RF1 only") {
|
||||
t.Fatalf("walstore-chunk with --replication-ack=%s: %v", ack, err)
|
||||
}
|
||||
}
|
||||
if _, err := parseFlags(append(append([]string{}, chunk...), "--replication-ack", "best-effort")); err != nil {
|
||||
t.Fatalf("walstore-chunk best-effort refused: %v", err)
|
||||
}
|
||||
if _, err := parseFlags(append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore", "--replication-ack", "sync-quorum")); err != nil {
|
||||
t.Fatalf("walstore sync-quorum refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The replication factor arrives with the master's assignment. The host refuses
|
||||
// roles with replica slots (core/host/volume RF1Only, from hostConfig); the
|
||||
// ingress gate refuses them again and opens neither inbound lane (legacy and
|
||||
// dual-lane ports). A primary role without peers (RF1) is admitted.
|
||||
func TestChunkVolumeIngressRefusesReplicaSlots(t *testing.T) {
|
||||
for _, row := range []struct{ impl, mode string }{{"walstore", "legacy"}, {"walstore", "dual-lane"}, {"walstore-chunk", "legacy"}, {"walstore-chunk", "dual-lane"}} {
|
||||
impl, dualLane := row.impl, row.mode == "dual-lane"
|
||||
t.Run(row.impl+"/"+row.mode, func(t *testing.T) {
|
||||
addr, dual := ingressPair(t)
|
||||
f := flags{dataAddr: addr, volumeID: "v1", durableImpl: impl, recoveryMode: row.mode}
|
||||
if got, want := hostConfig(f, nil).RF1Only, map[string]string{"walstore": "", "walstore-chunk": chunkRF1Reason}[impl]; got != want {
|
||||
t.Fatalf("host config RF1Only = %q, want %q", got, want)
|
||||
}
|
||||
r := newReplicationIngress(f, storage.NewBlockStore(4, 4096))
|
||||
defer r.Stop()
|
||||
admitErr := r.AdmitAsReplica(1)
|
||||
if impl == "walstore" {
|
||||
if admitErr != nil || r.listener == nil || (r.dual != nil) != dualLane {
|
||||
t.Fatalf("walstore replica role (%s): %v", row.mode, admitErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if admitErr == nil || !strings.Contains(admitErr.Error(), "refuses a replica role") || !strings.Contains(admitErr.Error(), "RF1 only") {
|
||||
t.Fatalf("replica role admitted: %v", admitErr)
|
||||
}
|
||||
if err := r.FenceAsPrimaryWithPeers(2, true); err == nil || !strings.Contains(err.Error(), "refuses a primary role with replica peers") {
|
||||
t.Fatalf("primary with peers admitted: %v", err)
|
||||
}
|
||||
if err := r.FenceAsPrimary(3); err == nil {
|
||||
t.Fatal("legacy primary fence (peers assumed) admitted")
|
||||
}
|
||||
if r.listener != nil || r.dual != nil {
|
||||
t.Fatal("an inbound listener was created")
|
||||
}
|
||||
for _, a := range []string{addr, dual} {
|
||||
if err := ingressPortReleased(a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := r.FenceAsPrimaryWithPeers(4, false); err != nil {
|
||||
t.Fatalf("RF1 primary refused: %v", err)
|
||||
}
|
||||
if r.listener != nil || r.dual != nil {
|
||||
t.Fatal("the RF1 primary role opened an inbound listener")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestChunkHydrationFlagsAreConfigurable(t *testing.T) {
|
||||
base := append(phase150RequiredBlockvolumeArgs(), "--durable-root=hydration-test", "--durable-impl=walstore-chunk", "--chunk-filer=x:1")
|
||||
f, err := parseFlags(append(base, "--chunk-hydration-workers=3", "--chunk-hydration-queue-depth=17"))
|
||||
if err != nil || f.chunk.hydrationWorkers != 3 || f.chunk.hydrationQueueDepth != 17 {
|
||||
t.Fatalf("hydration limits: %+v err=%v", f.chunk, err)
|
||||
}
|
||||
for _, flag := range []string{"--chunk-hydration-workers=0", "--chunk-hydration-workers=65", "--chunk-hydration-queue-depth=0", "--chunk-hydration-queue-depth=65537"} {
|
||||
if _, err := parseFlags(append(base, flag)); err == nil {
|
||||
t.Fatalf("invalid hydration limit accepted: %s", flag)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -194,7 +194,9 @@ func parseFlags(args []string) (flags, error) {
|
||||
fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)")
|
||||
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: automatic cut once this long has passed since the last successful cut; 0 (default) disables the timer, e.g. 15m as a host-loss safety net")
|
||||
fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)")
|
||||
fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: bound on one cut's barrier copy, in chunks; never triggers a cut; 0 = unbounded")
|
||||
fs.IntVar(&f.chunk.hydrationWorkers, "chunk-hydration-workers", 2, "walstore-chunk: concurrent lazy chunk fetches per volume (1..64)")
|
||||
fs.IntVar(&f.chunk.hydrationQueueDepth, "chunk-hydration-queue-depth", 64, "walstore-chunk: distinct queued/in-flight hydration chunks per volume (1..65536)")
|
||||
fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: number of candidate chunks above which a cut pre-copies (stages) chunks before its barrier, in rounds of this size; copy-before-write copies the rest outside the barrier; never triggers a cut; 0 = no pre-copy")
|
||||
fs.BoolVar(&f.chunk.controlEndpoint, "chunk-control-endpoint", false, "walstore-chunk: expose the /chunk/* control routes (cut, snapshot, snapshots, snapshot/delete, detach) on the status HTTP listener; off by default; loopback-only like the listener")
|
||||
fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)")
|
||||
fs.UintVar(&f.durableBlockSize, "durable-blocksize", 4096, "block size in bytes on first create")
|
||||
@@ -548,19 +550,7 @@ func durableCreateGeometry(f flags) (uint32, int, error) {
|
||||
func run(f flags) int {
|
||||
readyCh := make(chan adapter.AssignmentInfo, 16)
|
||||
|
||||
h, err := volume.New(volume.Config{
|
||||
MasterAddr: f.masterAddr,
|
||||
ServerID: f.serverID,
|
||||
VolumeID: f.volumeID,
|
||||
ReplicaID: f.replicaID,
|
||||
DataAddr: f.dataAddr,
|
||||
CtrlAddr: f.ctrlAddr,
|
||||
HeartbeatInterval: f.hbInterval,
|
||||
RecoverTimeout: f.recoverTimeout,
|
||||
ReadyMarker: readyCh,
|
||||
EnableT1Readiness: f.enableT1Readiness,
|
||||
WorkspaceLease: f.workspaceLease,
|
||||
})
|
||||
h, err := volume.New(hostConfig(f, readyCh))
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "blockvolume:", err)
|
||||
return 1
|
||||
@@ -630,6 +620,8 @@ func run(f flags) int {
|
||||
cfg.ChunkCaptureInterval = f.chunk.captureInterval
|
||||
cfg.ChunkDirtyThreshold = f.chunk.dirtyThreshold
|
||||
cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency
|
||||
cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers
|
||||
cfg.ChunkHydrationQueueDepth = f.chunk.hydrationQueueDepth
|
||||
cfg.ChunkHolder = chunkHolder(f)
|
||||
if chunkErr == nil {
|
||||
cfg.ChunkRemoteFor = chunk.remoteFor
|
||||
@@ -898,8 +890,7 @@ func run(f flags) int {
|
||||
|
||||
// No replication socket exists until a master assignment includes
|
||||
// replica slots. The role gate starts/fences both lanes before admission.
|
||||
replListen = &replicationIngress{addr: f.dataAddr, store: store,
|
||||
volumeID: f.volumeID, floorPath: replicaFloorPath(f), dualLane: f.recoveryMode == "dual-lane"}
|
||||
replListen = newReplicationIngress(f, store)
|
||||
if err := h.SetSelfFence(replListen); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: replica listener role:", err)
|
||||
replListen.Stop()
|
||||
@@ -1460,6 +1451,24 @@ func deriveDualLaneAddr(addr string) (string, error) {
|
||||
|
||||
// replicaFloorPath is where the replica's epoch floor record lives (G1):
|
||||
// beside the volume's durable files, or "" for non-durable memback runs.
|
||||
// hostConfig is the volume host's configuration from the flags.
|
||||
func hostConfig(f flags, readyCh chan<- adapter.AssignmentInfo) volume.Config {
|
||||
return volume.Config{
|
||||
MasterAddr: f.masterAddr,
|
||||
ServerID: f.serverID,
|
||||
VolumeID: f.volumeID,
|
||||
ReplicaID: f.replicaID,
|
||||
DataAddr: f.dataAddr,
|
||||
CtrlAddr: f.ctrlAddr,
|
||||
HeartbeatInterval: f.hbInterval,
|
||||
RecoverTimeout: f.recoverTimeout,
|
||||
ReadyMarker: readyCh,
|
||||
EnableT1Readiness: f.enableT1Readiness,
|
||||
WorkspaceLease: f.workspaceLease,
|
||||
RF1Only: rf1Only(f),
|
||||
}
|
||||
}
|
||||
|
||||
func replicaFloorPath(f flags) string {
|
||||
if f.durableRoot == "" {
|
||||
return ""
|
||||
|
||||
@@ -19,10 +19,33 @@ type replicationIngress struct {
|
||||
addr, volumeID, floorPath string
|
||||
store storage.LogicalStorage
|
||||
dualLane bool
|
||||
listener *transport.ReplicaListener
|
||||
dual net.Listener
|
||||
cancel context.CancelFunc
|
||||
closed bool
|
||||
// rf1Only, when set, refuses every role with replica slots with this reason
|
||||
// (walstore-chunk). The host latches the error: no role is adopted, not Healthy.
|
||||
rf1Only string
|
||||
listener *transport.ReplicaListener
|
||||
dual net.Listener
|
||||
cancel context.CancelFunc
|
||||
closed bool
|
||||
}
|
||||
|
||||
// newReplicationIngress is the volume's ingress from its flags; an RF1-only
|
||||
// volume (walstore-chunk) refuses every role with replica slots.
|
||||
func newReplicationIngress(f flags, store storage.LogicalStorage) *replicationIngress {
|
||||
r := &replicationIngress{addr: f.dataAddr, store: store, volumeID: f.volumeID,
|
||||
floorPath: replicaFloorPath(f), dualLane: f.recoveryMode == "dual-lane"}
|
||||
r.rf1Only = rf1Only(f)
|
||||
return r
|
||||
}
|
||||
|
||||
// rf1Only is the single-replica rule of this volume, "" when replication is
|
||||
// allowed. The host refuses assignments with replica slots (installed at
|
||||
// construction, before any fact is applied or replayed); the ingress gate
|
||||
// refuses the same roles again.
|
||||
func rf1Only(f flags) string {
|
||||
if f.durableImpl == "walstore-chunk" {
|
||||
return chunkRF1Reason
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (r *replicationIngress) FenceAsPrimary(epoch uint64) error {
|
||||
@@ -43,6 +66,9 @@ func (r *replicationIngress) FenceAsPrimaryWithPeers(epoch uint64, hasPeers bool
|
||||
r.stopLocked(true)
|
||||
return nil
|
||||
}
|
||||
if r.rf1Only != "" {
|
||||
return fmt.Errorf("volume %s refuses a primary role with replica peers at epoch %d: %s", r.volumeID, epoch, r.rf1Only)
|
||||
}
|
||||
return r.roleLocked(epoch, true)
|
||||
}
|
||||
func (r *replicationIngress) AdmitAsReplica(epoch uint64) error {
|
||||
@@ -51,6 +77,9 @@ func (r *replicationIngress) AdmitAsReplica(epoch uint64) error {
|
||||
if r.closed {
|
||||
return fmt.Errorf("replication ingress closed")
|
||||
}
|
||||
if r.rf1Only != "" {
|
||||
return fmt.Errorf("volume %s refuses a replica role at epoch %d: %s", r.volumeID, epoch, r.rf1Only)
|
||||
}
|
||||
return r.roleLocked(epoch, false)
|
||||
}
|
||||
func (r *replicationIngress) roleLocked(epoch uint64, primary bool) error {
|
||||
|
||||
@@ -430,3 +430,10 @@ func TestBootstrap_Close_Idempotent(t *testing.T) {
|
||||
t.Fatalf("second Close must be idempotent: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *indexFailingAuthorityStore) PutWorkspaceLostRanges(string, []authority.WorkspaceLostRange) error {
|
||||
return nil
|
||||
}
|
||||
func (s *indexFailingAuthorityStore) LoadWorkspaceLostRanges() (map[string][]authority.WorkspaceLostRange, []error, error) {
|
||||
return nil, nil, nil
|
||||
}
|
||||
@@ -26,15 +26,15 @@ type options struct {
|
||||
calibrate bool
|
||||
persistDemo bool
|
||||
persistDir string
|
||||
authorityStore string
|
||||
s5Bootstrap bool
|
||||
s7RestartSmoke bool
|
||||
authorityStore string
|
||||
s5Bootstrap bool
|
||||
s7RestartSmoke bool
|
||||
}
|
||||
|
||||
type demoResult struct {
|
||||
Demo string `json:"demo"`
|
||||
Pass bool `json:"pass"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Demo string `json:"demo"`
|
||||
Pass bool `json:"pass"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Projection engine.ReplicaProjection `json:"projection"`
|
||||
}
|
||||
|
||||
@@ -221,7 +221,10 @@ func runValidationPass(state *ops.State, volumeID string, pubOpts ...authority.P
|
||||
_, _ = primaryStore.Write(i, data)
|
||||
}
|
||||
_, _ = primaryStore.Sync()
|
||||
blocks := primaryStore.AllBlocks()
|
||||
blocks, err := primaryStore.AllBlocks()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("snapshot primary: %w", err)
|
||||
}
|
||||
_, _, pH := primaryStore.Boundaries()
|
||||
for lba, data := range blocks {
|
||||
_ = replicaStore.ApplyEntry(lba, data, pH)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type manifestFixtureFiler struct {
|
||||
chunkstore.Filer
|
||||
mu sync.Mutex
|
||||
blobs map[string][]byte
|
||||
}
|
||||
|
||||
func newManifestFixtureFiler(f chunkstore.Filer) *manifestFixtureFiler {
|
||||
return &manifestFixtureFiler{Filer: f, blobs: map[string][]byte{}}
|
||||
}
|
||||
|
||||
func (f *manifestFixtureFiler) Put(_ context.Context, b []byte) (string, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
id := fmt.Sprintf("fixture-%d", len(f.blobs))
|
||||
f.blobs[id] = append([]byte(nil), b...)
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (f *manifestFixtureFiler) Get(_ context.Context, id string) ([]byte, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
b, ok := f.blobs[id]
|
||||
if !ok {
|
||||
return nil, chunkstore.ErrNotFound
|
||||
}
|
||||
return append([]byte(nil), b...), nil
|
||||
}
|
||||
|
||||
func prepareFixtureHead(t *testing.T, f *manifestFixtureFiler, h storage.ChunkHead) storage.ChunkHead {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
r, err := chunkstore.NewChunkRemote(f, f, defaultChunkPathCLI+"/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, intents, err := r.PrepareManifest(ctx, storage.ChunkHead{}, h, 8*4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// These fixtures hand the completed cut directly to the catalog; the
|
||||
// snapshot/fork operations establish their own reachability intents.
|
||||
for _, id := range intents {
|
||||
if err := r.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
@@ -41,10 +41,11 @@ func (f *failingFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.E
|
||||
func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ff := &failingFiler{MemFiler: chunkstore.NewMemFiler()}
|
||||
fm := newManifestFixtureFiler(ff)
|
||||
prev := dialChunkFiler
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return ff, func() error { return nil }, nil }
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return fm, func() error { return nil }, nil }
|
||||
t.Cleanup(func() { dialChunkFiler = prev })
|
||||
cat, err := chunkstore.NewCatalog(ff, defaultChunkPathCLI)
|
||||
cat, err := chunkstore.NewCatalog(fm, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -54,6 +55,7 @@ func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) {
|
||||
base := time.Now().Add(-48 * time.Hour)
|
||||
head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive,
|
||||
Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}}
|
||||
head = prepareFixtureHead(t, fm, head)
|
||||
for i := 0; i < 4; i++ {
|
||||
at := base.Add(time.Duration(i) * time.Minute)
|
||||
cat.SetClock(func() time.Time { return at })
|
||||
|
||||
@@ -44,7 +44,7 @@ func TestOpsChunk_SnapshotPinAndExpires(t *testing.T) {
|
||||
// dry-run, apply, and see the accounting follow.
|
||||
func TestOpsChunk_UsageAndRetain(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
mem := chunkstore.NewMemFiler()
|
||||
mem := newManifestFixtureFiler(chunkstore.NewMemFiler())
|
||||
prev := dialChunkFiler
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
|
||||
t.Cleanup(func() { dialChunkFiler = prev })
|
||||
@@ -59,6 +59,7 @@ func TestOpsChunk_UsageAndRetain(t *testing.T) {
|
||||
cat.SetClock(func() time.Time { return old })
|
||||
head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive,
|
||||
Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}}
|
||||
head = prepareFixtureHead(t, mem, head)
|
||||
for i := 0; i < 5; i++ {
|
||||
if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: fmt.Sprintf("s%d", i), RequestID: fmt.Sprintf("r%d", i), Class: chunkstore.SnapshotClassSemantic}, head); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
// either is null when it does not exist (B9 W2 appendix).
|
||||
func TestOpsChunk_Show(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
mem := chunkstore.NewMemFiler()
|
||||
mem := newManifestFixtureFiler(chunkstore.NewMemFiler())
|
||||
prev := dialChunkFiler
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
|
||||
t.Cleanup(func() { dialChunkFiler = prev })
|
||||
@@ -27,6 +27,7 @@ func TestOpsChunk_Show(t *testing.T) {
|
||||
}
|
||||
head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive,
|
||||
Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}}
|
||||
head = prepareFixtureHead(t, mem, head)
|
||||
if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -157,6 +157,15 @@ func TestOpsChunk_FilerCommands(t *testing.T) {
|
||||
}
|
||||
head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 42, State: storage.ChunkHeadActive,
|
||||
Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}}
|
||||
manifestMem := newManifestFixtureFiler(mem)
|
||||
cat, err = chunkstore.NewCatalog(manifestMem, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
|
||||
return manifestMem, func() error { return nil }, nil
|
||||
}
|
||||
head = prepareFixtureHead(t, manifestMem, head)
|
||||
if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ func run(args []string, stdout, stderr io.Writer) int {
|
||||
return ops.VolumeStatusExitInvalid
|
||||
}
|
||||
if len(args) < 2 {
|
||||
fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk")
|
||||
fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume-unheld")
|
||||
usage(stderr)
|
||||
return ops.VolumeStatusExitInvalid
|
||||
}
|
||||
@@ -129,6 +129,8 @@ func run(args []string, stdout, stderr io.Writer) int {
|
||||
return runOpsFrontendPublicationExecutor(args[2:], stdout, stderr)
|
||||
case "chunk":
|
||||
return runOpsChunk(args[2:], stdout, stderr)
|
||||
case "volume-unheld":
|
||||
return runOpsVolumeUnheld(args[2:], stdout, stderr)
|
||||
default:
|
||||
fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1])
|
||||
usage(stderr)
|
||||
@@ -2296,6 +2298,7 @@ func usage(w io.Writer) {
|
||||
fmt.Fprintln(w, " sw-block ops chunk fork --chunk-filer <host:port> [--chunk-path /swblock/chunks] --source <id> --snapshot <name> --target <id> [--request-id <id>] [--label k=v]...")
|
||||
fmt.Fprintln(w, " sw-block ops chunk show --volume <id> --chunk-filer <host:port> [--chunk-path /swblock/chunks]")
|
||||
fmt.Fprintln(w, " sw-block ops chunk gc --chunk-filer <host:port> --master <blockmaster-grpc> [--chunk-path /swblock/chunks] [--apply] [--grace 1h] [--intent-ttl 1h] [--timeout 1m]")
|
||||
fmt.Fprintln(w, " sw-block ops volume-unheld --path <volume-file> (exit 0: no process on this host holds it; local filesystems only)")
|
||||
}
|
||||
|
||||
func emptyCLI(value string) string {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
const volumeUnheldUsage = `usage: sw-block ops volume-unheld --path <volume-file>
|
||||
|
||||
Exit 0 only when no process on THIS host holds the v3 volume file's lock
|
||||
(the lock every v3 owner holds while its store is open; the kernel releases
|
||||
it when the owner process exits). Exit 1: held. Exit 2: unknown (missing
|
||||
file, not a v3 volume, lock error) or bad usage.
|
||||
|
||||
This proof is per host and for local filesystems only. It says nothing about
|
||||
another host, and nothing on a network or shared mount. It does not prove the
|
||||
owner process is dead: host cleanup must require BOTH this command's exit 0
|
||||
AND the host tooling's own check that the recorded owner process is gone.
|
||||
|
||||
The probe holds the lock only for an instant and reserves nothing: it does not
|
||||
keep a new owner out after it returns, and an owner opening the volume at that
|
||||
instant is refused. Run it only when the owner is believed gone.
|
||||
`
|
||||
|
||||
// runOpsVolumeUnheld is `sw-block ops volume-unheld`.
|
||||
func runOpsVolumeUnheld(args []string, stdout, stderr io.Writer) int {
|
||||
fs := flag.NewFlagSet("sw-block ops volume-unheld", flag.ContinueOnError)
|
||||
fs.SetOutput(stderr)
|
||||
fs.Usage = func() { fmt.Fprint(stderr, volumeUnheldUsage) }
|
||||
path := fs.String("path", "", "the volume file")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return ops.VolumeStatusExitInvalid
|
||||
}
|
||||
if *path == "" || fs.NArg() != 0 {
|
||||
fmt.Fprint(stderr, volumeUnheldUsage)
|
||||
return ops.VolumeStatusExitInvalid
|
||||
}
|
||||
switch err := storage.ProbeVolumeUnheld(*path); {
|
||||
case err == nil:
|
||||
fmt.Fprintf(stdout, "unheld: no process on this host holds %s (local proof only; also check the owner process is gone)\n", *path)
|
||||
return ops.VolumeStatusExitOK
|
||||
case errors.Is(err, storage.ErrVolumeHeld):
|
||||
fmt.Fprintf(stdout, "held: a live process on this host holds %s\n", *path)
|
||||
return ops.VolumeStatusExitUnhealthy
|
||||
default:
|
||||
fmt.Fprintf(stderr, "unknown: %v\n", err)
|
||||
return ops.VolumeStatusExitInvalid
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// `sw-block ops volume-unheld` exits 0 only for an unheld v3 volume: 1 while
|
||||
// a store holds it, 2 for unknown (missing, not v3) and bad usage. The
|
||||
// usage states the per-host, local-only limit and the second check.
|
||||
func TestOpsVolumeUnheldExitCodes(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "v.bin")
|
||||
s, err := storage.CreateWALStore(path, 64, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
closed := false
|
||||
t.Cleanup(func() {
|
||||
if !closed {
|
||||
_ = s.Close()
|
||||
}
|
||||
})
|
||||
junk := filepath.Join(t.TempDir(), "junk.bin")
|
||||
if err := os.WriteFile(junk, make([]byte, 64<<10), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runIt := func(args ...string) (int, string, string) {
|
||||
var out, errOut bytes.Buffer
|
||||
code := run(append([]string{"ops", "volume-unheld"}, args...), &out, &errOut)
|
||||
return code, out.String(), errOut.String()
|
||||
}
|
||||
if code, out, _ := runIt("--path", path); code != 1 || !strings.HasPrefix(out, "held:") {
|
||||
t.Fatalf("open store: exit %d %q; want 1 held", code, out)
|
||||
}
|
||||
closed = true
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, out, _ := runIt("--path", path); code != 0 || !strings.HasPrefix(out, "unheld:") {
|
||||
t.Fatalf("closed store: exit %d %q; want 0 unheld", code, out)
|
||||
}
|
||||
for name, args := range map[string][]string{
|
||||
"missing": {"--path", filepath.Join(t.TempDir(), "missing.bin")},
|
||||
"not v3": {"--path", junk},
|
||||
"no path": nil,
|
||||
"extra arg": {"--path", path, "x"},
|
||||
} {
|
||||
if code, out, _ := runIt(args...); code != 2 || strings.HasPrefix(out, "unheld") {
|
||||
t.Fatalf("%s: exit %d %q; want 2", name, code, out)
|
||||
}
|
||||
}
|
||||
_, _, usage := runIt()
|
||||
for _, want := range []string{"per host", "local filesystems only", "network or shared mount", "BOTH", "reserves nothing", "is refused"} {
|
||||
if !strings.Contains(usage, want) {
|
||||
t.Fatalf("usage lacks %q:\n%s", want, usage)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -263,7 +263,10 @@ func TestHandoff_RejoinAfterNewPrimary_DataConsistent(t *testing.T) {
|
||||
waitRecoveredHealthy(t, adapterB, "r1", 3*time.Second)
|
||||
|
||||
// Every LBA that B wrote must match on the replica.
|
||||
allB := primaryB.AllBlocks()
|
||||
allB, snapshotErr := primaryB.AllBlocks()
|
||||
if snapshotErr != nil {
|
||||
t.Fatal(snapshotErr)
|
||||
}
|
||||
for lba, expected := range allB {
|
||||
got, err := replica.Read(lba)
|
||||
if err != nil {
|
||||
|
||||
@@ -158,6 +158,7 @@ type Publisher struct {
|
||||
// Workspace state is serialized with assignment minting under mu. Remote
|
||||
// HEAD reads and subscriber delivery never run under this lock.
|
||||
workspace map[string]*WorkspaceState
|
||||
lostRanges map[string][]WorkspaceLostRange // forced moves' abandoned ranges (side files)
|
||||
workspaceUncertain map[string]bool
|
||||
workspaceNow func() time.Time
|
||||
workspaceTTL time.Duration
|
||||
@@ -234,6 +235,7 @@ func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher {
|
||||
subs: make(map[subKey][]*subscription),
|
||||
writeSeqByVolume: map[string]uint64{},
|
||||
workspace: map[string]*WorkspaceState{},
|
||||
lostRanges: map[string][]WorkspaceLostRange{},
|
||||
workspaceUncertain: map[string]bool{},
|
||||
workspaceNow: time.Now,
|
||||
workspaceTTL: 30 * time.Second,
|
||||
@@ -283,6 +285,12 @@ func (p *Publisher) reloadFromStore() {
|
||||
}
|
||||
}
|
||||
p.loadErrs = append(p.loadErrs, skips...)
|
||||
ranges, lskips, lerr := p.store.LoadWorkspaceLostRanges()
|
||||
if lerr != nil {
|
||||
panic(fmt.Sprintf("authority: lost range load failure: %v", lerr))
|
||||
}
|
||||
p.lostRanges = ranges
|
||||
p.loadErrs = append(p.loadErrs, lskips...)
|
||||
for _, rec := range records {
|
||||
p.refreshLeaseViewLocked(rec.VolumeID)
|
||||
if rec.Workspace != nil {
|
||||
|
||||
@@ -369,3 +369,8 @@ func (f *failingStore) Close() error { return nil }
|
||||
// Silence unused import warning if adapter is not referenced
|
||||
// directly in this file's test bodies.
|
||||
var _ = adapter.AssignmentInfo{}
|
||||
|
||||
func (f *failingStore) PutWorkspaceLostRanges(string, []WorkspaceLostRange) error { return nil }
|
||||
func (f *failingStore) LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error) {
|
||||
return nil, nil, nil
|
||||
}
|
||||
@@ -80,6 +80,16 @@ type AuthorityStore interface {
|
||||
// Publisher.apply).
|
||||
Put(record DurableRecord) error
|
||||
|
||||
// PutWorkspaceLostRanges replaces a volume's forced-move lost ranges
|
||||
// atomically, beside (never inside) its authority record, so the record
|
||||
// stays readable by binaries that predate them. Every store must record
|
||||
// them: a forced move does not issue without its range.
|
||||
PutWorkspaceLostRanges(volumeID string, ranges []WorkspaceLostRange) error
|
||||
|
||||
// LoadWorkspaceLostRanges returns every volume's lost ranges, with
|
||||
// per-file skip errors; only an index-level failure returns err.
|
||||
LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error)
|
||||
|
||||
// Close releases store resources. Idempotent.
|
||||
Close() error
|
||||
}
|
||||
|
||||
@@ -280,12 +280,20 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra
|
||||
if !ok || line.info.Epoch != q.ExpectedEpoch || line.info.ReplicaID != q.ExpectedReplicaID || s == nil || s.Lease == nil {
|
||||
return nil, 0, fmt.Errorf("workspace move: missing or changed authority/lease")
|
||||
}
|
||||
var lostUntil int64
|
||||
if q.Kind == "forced" {
|
||||
now := p.workspaceNow()
|
||||
skew := p.workspaceSkew(s.Lease)
|
||||
if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(p.leaseDeadlineLocked(q.VolumeID).Add(skew)) {
|
||||
deadline := p.leaseDeadlineLocked(q.VolumeID)
|
||||
if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) {
|
||||
return nil, 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed")
|
||||
}
|
||||
// The audit bound only, in wall time: the admission above keeps both
|
||||
// predicates (the deadline's monotonic reading included).
|
||||
lostUntil = time.Unix(0, s.Lease.ExpiresAtNS).Add(skew).UnixNano()
|
||||
if d := deadline.Add(skew).UnixNano(); d > lostUntil {
|
||||
lostUntil = d
|
||||
}
|
||||
}
|
||||
// A restart may resume the identical durable reservation; it never grants
|
||||
// a different request the reserved epoch.
|
||||
@@ -294,6 +302,15 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra
|
||||
if r.Issued || !sameWorkspaceRequest(r, q) {
|
||||
return nil, 0, fmt.Errorf("workspace move reservation differs")
|
||||
}
|
||||
// A forced reservation issues only with the exact range recorded
|
||||
// before it; a missing one (a reservation older than lost ranges,
|
||||
// or a skipped side file) is refused, never recomputed: a new
|
||||
// request records a fresh range.
|
||||
if r.Kind == "forced" {
|
||||
if _, ok := p.lostRangeLocked(q.VolumeID, r.RequestID, r.NewEpoch); !ok {
|
||||
return nil, 0, fmt.Errorf("workspace forced move reservation %s has no recorded lost range; retry with a new request id", r.RequestID)
|
||||
}
|
||||
}
|
||||
s.Moves[idx].Issued = true
|
||||
s.Lease = nil
|
||||
s.Ack = nil
|
||||
@@ -319,6 +336,12 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra
|
||||
}
|
||||
r := WorkspaceMoveRecord{RequestID: q.RequestID, VolumeID: q.VolumeID, OldHost: q.ExpectedHost, NewHost: q.TargetHost, OldReplicaID: q.ExpectedReplicaID, NewReplicaID: q.TargetReplicaID, Kind: q.Kind,
|
||||
OldEpoch: q.ExpectedEpoch, NewEpoch: max + 1, HeadGen: h.Gen, RemoteLSN: h.RemoteLSN, TargetDataAddr: q.TargetDataAddr, TargetCtrlAddr: q.TargetCtrlAddr}
|
||||
if q.Kind == "forced" {
|
||||
lost := WorkspaceLostRange{RequestID: r.RequestID, NewEpoch: r.NewEpoch, OldReplicaID: r.OldReplicaID, OldEpoch: r.OldEpoch, LostAfterLSN: r.RemoteLSN, LostUntilNS: lostUntil}
|
||||
if err := p.recordLostRangeLocked(q.VolumeID, lost); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
}
|
||||
s.Moves = append(s.Moves, r)
|
||||
if err := p.persistWorkspaceLocked(q.VolumeID, s); err != nil {
|
||||
return nil, 0, err
|
||||
|
||||
@@ -616,10 +616,61 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
|
||||
lastEpoch := map[string]uint64{}
|
||||
var extensions atomic.Int64
|
||||
heldEntered, heldRelease := make(chan struct{}), make(chan struct{})
|
||||
var holdOnce, releaseOnce sync.Once
|
||||
releaseHold := func() { releaseOnce.Do(func() { close(heldRelease) }) }
|
||||
var releaseOnce sync.Once
|
||||
// The publisher clock is frozen while the extension write is held (#247
|
||||
// hang): the held write holds p.mu, so every other volume's extender queues
|
||||
// and no horizon can move. With a running clock a late test goroutine could
|
||||
// let horizons expire before each volume got a grant under the hold (the
|
||||
// progress condition never holds), or before the writers run after the
|
||||
// release (a revoke ACK finds the lease expired). This test is about lock
|
||||
// and store ordering, not about lease expiry.
|
||||
// The clock stays frozen after the release until the clean volume's revoke
|
||||
// ACK: the endpoint refreshes, the revocation and the ACK queue on p.mu
|
||||
// behind every volume's extension write (fsync), which on a loaded machine
|
||||
// can outlast the clean volume's grant, and a revoking lease is never
|
||||
// extended (in-time ACK has its own tests). The writer then resumes the
|
||||
// clock from the frozen instant, so it neither jumps over a horizon nor runs
|
||||
// backwards; extensions run in real time alongside the moves and Close.
|
||||
// Now/Freeze/Resume are one transaction each.
|
||||
clock := &leaseTestClock{}
|
||||
releaseHold := func() {
|
||||
releaseOnce.Do(func() { close(heldRelease) })
|
||||
}
|
||||
var classifying atomic.Bool
|
||||
var holding atomic.Bool // set when the extension write is held, before it blocks
|
||||
var holding atomic.Bool // set when the extension write is held, before it blocks
|
||||
var heldVol atomic.Value // string: the volume whose extension write is held
|
||||
var holdTaken atomic.Bool
|
||||
var holdMu sync.Mutex
|
||||
var skippedHolds atomic.Int64 // extension writes not held: some eligible volume lacked headroom
|
||||
var p *Publisher
|
||||
// headroom witnesses, at the frozen instant and from each volume's own
|
||||
// renewal view (the fields RenewWorkspaceLease reads, under the leaf
|
||||
// leaseMu), that a renewal of every eligible volume and of the clean volume
|
||||
// grants positive host validity: lease present and live, durable horizon
|
||||
// minus half the skew after now, and now before the granted deadline. The
|
||||
// frozen clock and the queued extenders keep it so for the whole hold and,
|
||||
// for the clean volume, through its revocation and ACK.
|
||||
var noHeadroom atomic.Value // string: the last volume found without headroom, and why
|
||||
headroom := func() bool {
|
||||
now := clock.Now().UnixNano()
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
for _, i := range append(append([]int{}, eligible...), cleanVol) { // the clean volume is revoked and ACKed frozen
|
||||
lv := p.leaseViews[vol(i)]
|
||||
if lv == nil || !lv.d.bound || !lv.d.leasePresent || lv.d.revoking || lv.d.movePending ||
|
||||
lv.d.uncertain || lv.d.storeless || lv.d.horizon-lv.d.maxSkewNS/2 <= now || now >= lv.deadline.UnixNano() {
|
||||
why := "no view"
|
||||
if lv != nil {
|
||||
why = fmt.Sprintf("bound=%v present=%v revoking=%v pending=%v uncertain=%v validity=%v deadline-now=%v",
|
||||
lv.d.bound, lv.d.leasePresent, lv.d.revoking, lv.d.movePending, lv.d.uncertain,
|
||||
time.Duration(lv.d.horizon-lv.d.maxSkewNS/2-now), time.Duration(lv.deadline.UnixNano()-now))
|
||||
}
|
||||
noHeadroom.Store(vol(i) + ": " + why)
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
hs.setBefore(func(r DurableRecord) error {
|
||||
time.Sleep(5 * time.Millisecond) // a slow store
|
||||
if !classifying.Load() || r.Workspace == nil || r.Workspace.Lease == nil {
|
||||
@@ -636,9 +687,23 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
|
||||
if ext {
|
||||
extensions.Add(1)
|
||||
first := false
|
||||
holdOnce.Do(func() { first = true })
|
||||
if !holdTaken.Load() {
|
||||
holdMu.Lock()
|
||||
if !holdTaken.Load() {
|
||||
clock.Freeze()
|
||||
if headroom() {
|
||||
holdTaken.Store(true)
|
||||
first = true
|
||||
} else {
|
||||
clock.Resume() // try again at a later extension write
|
||||
skippedHolds.Add(1)
|
||||
}
|
||||
}
|
||||
holdMu.Unlock()
|
||||
}
|
||||
if first {
|
||||
holding.Store(true) // before the hold: a renewal started after this saw it
|
||||
heldVol.Store(r.VolumeID) // the volume whose extension write is held
|
||||
holding.Store(true) // before the hold: a renewal started after this saw it
|
||||
close(heldEntered)
|
||||
<-heldRelease
|
||||
}
|
||||
@@ -648,13 +713,17 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
|
||||
// The publisher clock is real time plus an offset. The forced-move volume
|
||||
// is granted at offset -10 s, so by offset 0 its horizon + skew barrier has
|
||||
// passed; the clock only moves forward.
|
||||
var offNS atomic.Int64
|
||||
offNS.Store(int64(-10 * time.Second))
|
||||
p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, func() time.Time { return time.Now().Add(time.Duration(offNS.Load())) }))
|
||||
clock.SetOffset(-10 * time.Second)
|
||||
p = NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, clock.Now))
|
||||
t.Cleanup(p.CloseWorkspaceExtenders)
|
||||
ctx := context.Background()
|
||||
bindAndGrant(t, p, vol(forcedVol), "r") // never renewed again
|
||||
offNS.Store(0)
|
||||
clock.SetOffset(0)
|
||||
// Set-up writes are real store writes (fsync): on a loaded machine binding
|
||||
// the volumes can take longer than a TTL, and the first-bound volume would
|
||||
// expire before its renewer starts (by design it never recovers). The clock
|
||||
// stays frozen through the set-up and resumes just before the renewers.
|
||||
clock.Freeze()
|
||||
for i := 0; i < n; i++ {
|
||||
if i != forcedVol {
|
||||
bindAndGrant(t, p, vol(i), "r")
|
||||
@@ -664,10 +733,14 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
|
||||
st := p.WorkspaceState(vol(i))
|
||||
lastH[vol(i)], lastEpoch[vol(i)] = st.Lease.ExpiresAtNS, st.Lease.Epoch
|
||||
}
|
||||
clock.Resume()
|
||||
classifying.Store(true)
|
||||
|
||||
var grants [n]atomic.Int64
|
||||
var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held
|
||||
var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held
|
||||
var returnedUnderHold [n]atomic.Int64 // calls (any outcome) that started while the extension write was held
|
||||
var refusedUnderHold atomic.Value // string: a refusal of a call started under the hold, before the writers
|
||||
var writersGo atomic.Bool // set before the writers start
|
||||
var maxGrant [n]atomic.Int64
|
||||
var slowest atomic.Int64
|
||||
stop := make(chan struct{})
|
||||
@@ -681,6 +754,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
|
||||
// every worker, and only then let the fixtures close.
|
||||
t.Cleanup(func() {
|
||||
releaseHold()
|
||||
clock.Resume()
|
||||
stopRenewers()
|
||||
settled := make(chan struct{})
|
||||
go func() { wg.Wait(); close(settled) }()
|
||||
@@ -715,11 +789,21 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
|
||||
default:
|
||||
}
|
||||
fresh := holding.Load() // the call starts while the extension write is held
|
||||
beforeWriters := !writersGo.Load()
|
||||
start := time.Now()
|
||||
l, err := p.RenewWorkspaceLease(ctx, vol(i), "r", 1)
|
||||
if d := int64(time.Since(start)); d > slowest.Load() {
|
||||
slowest.Store(d)
|
||||
}
|
||||
if fresh {
|
||||
returnedUnderHold[i].Add(1)
|
||||
// Headroom was witnessed at the frozen instant: until the
|
||||
// writers start, every such renewal must grant (any refusal,
|
||||
// a horizon error included, fails).
|
||||
if beforeWriters && (err != nil || l.Revoking) {
|
||||
refusedUnderHold.CompareAndSwap(nil, fmt.Sprintf("%s: %+v %v", vol(i), l, err))
|
||||
}
|
||||
}
|
||||
if err == nil && !l.Revoking {
|
||||
grants[i].Add(1)
|
||||
if fresh {
|
||||
@@ -735,12 +819,29 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
|
||||
}
|
||||
|
||||
// Handshake 1: the first extension write is held inside the store.
|
||||
<-heldEntered // progress, no timer (#227): renewers keep triggering extensions
|
||||
// Progress handshakes (#227) with a real-time failure exit (never a pass):
|
||||
// the cleanup releases the hold and joins every worker.
|
||||
select {
|
||||
case <-heldEntered: // renewers keep triggering extensions
|
||||
case <-time.After(30 * time.Second):
|
||||
nh, _ := noHeadroom.Load().(string)
|
||||
t.Fatalf("no extension write was held within 30 s (%d extension writes, %d not held for lack of headroom; last: %s)",
|
||||
extensions.Load(), skippedHolds.Load(), nh)
|
||||
}
|
||||
// A late test goroutine (machine load), longer than a horizon (1.5 x TTL):
|
||||
// with the clock frozen under the hold, no volume can lose its lease here.
|
||||
time.Sleep(3500 * time.Millisecond)
|
||||
// Handshake 2: renewals keep succeeding while it is held.
|
||||
// Progress, no timer (#227): every eligible volume gains a grant from a call
|
||||
// that STARTED while the extension write was held (a reply computed before
|
||||
// the hold does not count). Renewals that waited for it would never return.
|
||||
for {
|
||||
// the hold does not count); renewals that waited for it would never return.
|
||||
// The hold was taken only with headroom witnessed for every eligible volume
|
||||
// at the frozen instant, so no refusal is allowed here.
|
||||
held, _ := heldVol.Load().(string)
|
||||
for give := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) {
|
||||
if r, _ := refusedUnderHold.Load().(string); r != "" {
|
||||
t.Fatalf("under the held extension of %s, with headroom witnessed: refused %s", held, r)
|
||||
}
|
||||
all := true
|
||||
for _, i := range eligible {
|
||||
if underHold[i].Load() == 0 {
|
||||
@@ -750,9 +851,15 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
|
||||
if all {
|
||||
break
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
if time.Now().After(give) {
|
||||
t.Fatalf("under the held extension of %s within 30 s: grants %v, returned calls %v", held,
|
||||
underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible))
|
||||
}
|
||||
}
|
||||
t.Logf("under the held extension of %s (%d extension writes not held for lack of headroom): grants %v", held,
|
||||
skippedHolds.Load(), underHoldCounts(&underHold, eligible))
|
||||
// Writers and Close start while the extension write is held.
|
||||
writersGo.Store(true)
|
||||
writersStarted = true
|
||||
go func() {
|
||||
for k := 0; k < 5; k++ {
|
||||
@@ -761,11 +868,16 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
|
||||
return
|
||||
}
|
||||
}
|
||||
// Still frozen since the hold (the refreshes above needed p.mu, which the
|
||||
// held write owned); the clean volume's headroom was witnessed then.
|
||||
if err := p.BeginWorkspaceRevocation(ctx, vol(cleanVol), "r", 1); err != nil {
|
||||
clock.Resume()
|
||||
writersDone <- fmt.Errorf("revocation: %w", err)
|
||||
return
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil {
|
||||
err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7})
|
||||
clock.Resume()
|
||||
if err != nil {
|
||||
writersDone <- fmt.Errorf("ack: %w", err)
|
||||
return
|
||||
}
|
||||
@@ -979,3 +1091,125 @@ func TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite(t *testing.T) {
|
||||
t.Fatal("aborted extender left the single-flight flag set")
|
||||
}
|
||||
}
|
||||
|
||||
// leaseTestClock is a test publisher clock: real time plus an offset, or a
|
||||
// frozen instant. Now, Freeze, Resume and SetOffset are each one transaction
|
||||
// under mu, and Now never returns an earlier time than a previous Now.
|
||||
type leaseTestClock struct {
|
||||
mu sync.Mutex
|
||||
off time.Duration
|
||||
frozen time.Time // zero = running
|
||||
last time.Time
|
||||
}
|
||||
|
||||
func (c *leaseTestClock) Now() time.Time {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
t := c.frozen
|
||||
if t.IsZero() {
|
||||
t = time.Now().Add(c.off)
|
||||
}
|
||||
if t.Before(c.last) {
|
||||
t = c.last
|
||||
}
|
||||
c.last = t
|
||||
return t
|
||||
}
|
||||
|
||||
// Freeze stops the clock at its current reading.
|
||||
func (c *leaseTestClock) Freeze() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.frozen.IsZero() {
|
||||
c.frozen = time.Now().Add(c.off)
|
||||
if c.frozen.Before(c.last) {
|
||||
c.frozen = c.last
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resume restarts a frozen clock from its frozen instant.
|
||||
func (c *leaseTestClock) Resume() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if !c.frozen.IsZero() {
|
||||
c.off = c.frozen.Sub(time.Now())
|
||||
c.frozen = time.Time{}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *leaseTestClock) SetOffset(d time.Duration) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.off = d
|
||||
}
|
||||
|
||||
func underHoldCounts(u *[8]atomic.Int64, eligible []int) []int64 {
|
||||
out := make([]int64, 0, len(eligible))
|
||||
for _, i := range eligible {
|
||||
out = append(out, u[i].Load())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Readers running across freeze/resume transitions never see the test clock
|
||||
// go backwards, and a resume does not jump forward over the frozen interval.
|
||||
func TestLeaseTestClockMonotonicAcrossFreezeResume(t *testing.T) {
|
||||
c := &leaseTestClock{}
|
||||
var stop atomic.Bool
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan string, 8)
|
||||
// Registered before launch: every exit, a Fatal included, stops and joins
|
||||
// the readers (bounded).
|
||||
t.Cleanup(func() {
|
||||
stop.Store(true)
|
||||
joined := make(chan struct{})
|
||||
go func() { wg.Wait(); close(joined) }()
|
||||
select {
|
||||
case <-joined:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Error("clock readers did not settle")
|
||||
}
|
||||
})
|
||||
for r := 0; r < 4; r++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
prev := c.Now()
|
||||
for !stop.Load() {
|
||||
now := c.Now()
|
||||
if now.Before(prev) {
|
||||
select {
|
||||
case errs <- fmt.Sprintf("clock went backwards: %v after %v", now, prev):
|
||||
default:
|
||||
}
|
||||
return
|
||||
}
|
||||
prev = now
|
||||
}
|
||||
}()
|
||||
}
|
||||
for k := 0; k < 50; k++ {
|
||||
c.Freeze()
|
||||
at := c.Now()
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
if got := c.Now(); !got.Equal(at) {
|
||||
t.Fatalf("frozen clock moved: %v -> %v", at, got)
|
||||
}
|
||||
r0 := time.Now()
|
||||
c.Resume()
|
||||
got := c.Now()
|
||||
// After a resume the clock advances by at most the real time since the
|
||||
// resume began (no jump over the frozen interval), and never backwards.
|
||||
if got.Before(at) || got.Sub(at) > time.Since(r0) {
|
||||
t.Fatalf("resume moved the clock by %v (real time since resume %v)", got.Sub(at), time.Since(r0))
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
stop.Store(true)
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for e := range errs {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// WorkspaceLostRange records what a forced move abandoned: the old holder's
|
||||
// writes after LostAfterLSN (the HEAD frontier the move keeps) are lost, and
|
||||
// none of them was acknowledged later than LostUntilNS (master time: the
|
||||
// forced barrier, the lease horizon or restart deadline plus skew). The
|
||||
// lease carries no write frontier, so the upper bound is a time.
|
||||
type WorkspaceLostRange struct {
|
||||
RequestID string
|
||||
NewEpoch uint64
|
||||
OldReplicaID string
|
||||
OldEpoch uint64
|
||||
LostAfterLSN uint64
|
||||
LostUntilNS int64
|
||||
}
|
||||
|
||||
// lostRangeFileExtension does not end in storeFileExtension: authority
|
||||
// loaders, old and new, never read these files.
|
||||
const lostRangeFileExtension = ".lostrange.json"
|
||||
|
||||
type lostRangeEnvelope struct {
|
||||
Version int `json:"v"`
|
||||
VolumeID string `json:"volume"`
|
||||
Ranges []WorkspaceLostRange `json:"ranges"`
|
||||
Checksum string `json:"checksum"`
|
||||
}
|
||||
|
||||
func lostRangeChecksum(volumeID string, ranges []WorkspaceLostRange) string {
|
||||
body, err := json.Marshal(struct {
|
||||
VolumeID string
|
||||
Ranges []WorkspaceLostRange
|
||||
}{volumeID, ranges})
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// PutWorkspaceLostRanges replaces volumeID's lost ranges atomically (temp
|
||||
// file, fsync, rename, directory fsync).
|
||||
func (s *FileAuthorityStore) PutWorkspaceLostRanges(volumeID string, ranges []WorkspaceLostRange) error {
|
||||
if volumeID == "" {
|
||||
return fmt.Errorf("authority_store: lost range with empty VolumeID")
|
||||
}
|
||||
payload, err := json.Marshal(lostRangeEnvelope{Version: 1, VolumeID: volumeID, Ranges: ranges, Checksum: lostRangeChecksum(volumeID, ranges)})
|
||||
if err != nil {
|
||||
return fmt.Errorf("authority_store: encode lost range: %w", err)
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return fmt.Errorf("authority_store: lost range Put on closed store")
|
||||
}
|
||||
final := filepath.Join(s.dir, encodeVolumeIDForFilename(volumeID)+lostRangeFileExtension)
|
||||
temp := final + tempSuffix
|
||||
f, err := os.OpenFile(temp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("authority_store: open lost range temp: %w", err)
|
||||
}
|
||||
_, werr := f.Write(payload)
|
||||
if werr == nil {
|
||||
werr = f.Sync()
|
||||
}
|
||||
if werr == nil {
|
||||
werr = testLostRangeFault("before-rename")
|
||||
}
|
||||
if cerr := f.Close(); werr == nil {
|
||||
werr = cerr
|
||||
}
|
||||
if werr != nil {
|
||||
_ = os.Remove(temp)
|
||||
return fmt.Errorf("authority_store: write lost range temp: %w", werr)
|
||||
}
|
||||
if err := renameWithRetry(temp, final); err != nil {
|
||||
_ = os.Remove(temp)
|
||||
return fmt.Errorf("authority_store: rename lost range: %w", err)
|
||||
}
|
||||
d, err := os.Open(s.dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("authority_store: lost range directory open: %w", err)
|
||||
}
|
||||
serr := d.Sync()
|
||||
if serr == nil {
|
||||
serr = testLostRangeFault("directory-sync")
|
||||
}
|
||||
if cerr := d.Close(); serr == nil {
|
||||
serr = cerr
|
||||
}
|
||||
if serr != nil {
|
||||
return fmt.Errorf("authority_store: lost range directory fsync: %w", serr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadWorkspaceLostRanges returns every volume's lost ranges. A file that
|
||||
// fails its checks is skipped with an error (these are records of loss, not
|
||||
// authority); only an unreadable directory fails the load.
|
||||
func (s *FileAuthorityStore) LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
entries, err := os.ReadDir(s.dir)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("authority_store: readdir: %w", err)
|
||||
}
|
||||
out := map[string][]WorkspaceLostRange{}
|
||||
var skips []error
|
||||
for _, e := range entries {
|
||||
name := e.Name()
|
||||
if e.IsDir() || !strings.HasSuffix(name, lostRangeFileExtension) {
|
||||
continue
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(s.dir, name))
|
||||
if err != nil {
|
||||
skips = append(skips, fmt.Errorf("%s: read: %w", name, err))
|
||||
continue
|
||||
}
|
||||
var env lostRangeEnvelope
|
||||
switch {
|
||||
case json.Unmarshal(raw, &env) != nil:
|
||||
err = errors.New("decode")
|
||||
case env.Version != 1:
|
||||
err = fmt.Errorf("version %d unsupported", env.Version)
|
||||
case env.Checksum != lostRangeChecksum(env.VolumeID, env.Ranges):
|
||||
err = errors.New("checksum mismatch")
|
||||
case encodeVolumeIDForFilename(env.VolumeID)+lostRangeFileExtension != name:
|
||||
err = fmt.Errorf("filename does not match VolumeID %q", env.VolumeID)
|
||||
}
|
||||
if err != nil {
|
||||
skips = append(skips, fmt.Errorf("%s: %w: lost range %v", name, ErrCorruptRecord, err))
|
||||
continue
|
||||
}
|
||||
out[env.VolumeID] = env.Ranges
|
||||
}
|
||||
return out, skips, nil
|
||||
}
|
||||
|
||||
// testLostRangeFaultHook, test-only, fails PutWorkspaceLostRanges at a named
|
||||
// step ("before-rename", "directory-sync") when it returns an error.
|
||||
var testLostRangeFaultHook func(step string) error
|
||||
|
||||
func testLostRangeFault(step string) error {
|
||||
if h := testLostRangeFaultHook; h != nil {
|
||||
return h(step)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// lostRangeLocked returns volume's recorded range for (requestID, newEpoch).
|
||||
// Called under p.mu.
|
||||
func (p *Publisher) lostRangeLocked(volume, requestID string, newEpoch uint64) (WorkspaceLostRange, bool) {
|
||||
for _, e := range p.lostRanges[volume] {
|
||||
if e.RequestID == requestID && e.NewEpoch == newEpoch {
|
||||
return e, true
|
||||
}
|
||||
}
|
||||
return WorkspaceLostRange{}, false
|
||||
}
|
||||
|
||||
// recordLostRangeLocked durably records r for volume before the move record
|
||||
// that issues it is written. An entry whose move never issues is an orphan,
|
||||
// ignored on read. Called under p.mu.
|
||||
func (p *Publisher) recordLostRangeLocked(volume string, r WorkspaceLostRange) error {
|
||||
if p.store == nil {
|
||||
return fmt.Errorf("workspace forced move: no store to record the lost range")
|
||||
}
|
||||
next := make([]WorkspaceLostRange, 0, len(p.lostRanges[volume])+1)
|
||||
for _, e := range p.lostRanges[volume] {
|
||||
if e.RequestID != r.RequestID || e.NewEpoch != r.NewEpoch {
|
||||
next = append(next, e)
|
||||
}
|
||||
}
|
||||
next = append(next, r)
|
||||
if err := p.store.PutWorkspaceLostRanges(volume, next); err != nil {
|
||||
return fmt.Errorf("workspace forced move: record lost range: %w", err)
|
||||
}
|
||||
p.lostRanges[volume] = next
|
||||
return nil
|
||||
}
|
||||
|
||||
// WorkspaceLostRanges returns the lost ranges of volume's issued forced
|
||||
// moves (an entry with no matching issued move is ignored).
|
||||
func (p *Publisher) WorkspaceLostRanges(volume string) []WorkspaceLostRange {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
s := p.workspace[volume]
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
var out []WorkspaceLostRange
|
||||
for _, e := range p.lostRanges[volume] {
|
||||
for _, m := range s.Moves {
|
||||
if m.Issued && m.Kind == "forced" && m.RequestID == e.RequestID && m.NewEpoch == e.NewEpoch {
|
||||
out = append(out, e)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func forcedLostRangeFixture(t *testing.T, store AuthorityStore, restart bool) (p *Publisher, now *time.Time, barrier time.Time) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
at := time.Unix(1000, 0)
|
||||
now = &at
|
||||
clock := func() time.Time { return *now }
|
||||
p = NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(time.Second, clock))
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if restart {
|
||||
*now = now.Add(time.Second)
|
||||
p = NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(time.Second, clock))
|
||||
}
|
||||
lease := p.WorkspaceState("v").Lease
|
||||
if restart && !p.leaseDeadlineLockedForTest("v").After(time.Unix(0, lease.ExpiresAtNS)) {
|
||||
t.Fatal("fixture: the restart deadline is not the later barrier term")
|
||||
}
|
||||
barrier = time.Unix(0, lease.ExpiresAtNS)
|
||||
if d := p.leaseDeadlineLockedForTest("v"); d.After(barrier) {
|
||||
barrier = d
|
||||
}
|
||||
return p, now, barrier.Add(p.workspaceSkew(lease))
|
||||
}
|
||||
|
||||
var forcedLostRangeReq = WorkspaceMoveRequest{RequestID: "f", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1,
|
||||
TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
|
||||
var forcedLostRangeHead = WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42}
|
||||
|
||||
// A forced move records the abandoned range beside its record: the kept HEAD
|
||||
// frontier and the forced barrier (lease horizon, or after a restart the
|
||||
// later restart deadline, plus skew) as the latest master time an old-holder
|
||||
// write can have been acknowledged. A reload returns it; the move record's
|
||||
// own encoding is unchanged, so older binaries still verify and load it.
|
||||
func TestWorkspaceForcedMoveRecordsTheLostRange(t *testing.T) {
|
||||
for _, restart := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "running", true: "after restart"}[restart], func(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
p, now, barrier := forcedLostRangeFixture(t, disk, restart)
|
||||
*now = barrier.Add(-time.Nanosecond)
|
||||
if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err == nil {
|
||||
t.Fatal("forced move admitted before its barrier")
|
||||
}
|
||||
if got := p.WorkspaceLostRanges("v"); len(got) != 0 {
|
||||
t.Fatalf("a refused move recorded a lost range: %+v", got)
|
||||
}
|
||||
*now = barrier.Add(5 * time.Second) // the bound is the barrier, not the time of the move
|
||||
r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := WorkspaceLostRange{RequestID: "f", NewEpoch: r.NewEpoch, OldReplicaID: "old", OldEpoch: 1, LostAfterLSN: 42, LostUntilNS: barrier.UnixNano()}
|
||||
if got := p.WorkspaceLostRanges("v"); len(got) != 1 || got[0] != want {
|
||||
t.Fatalf("lost range %+v; want [%+v]", got, want)
|
||||
}
|
||||
reloaded := NewPublisher(nil, WithStore(disk))
|
||||
if got := reloaded.WorkspaceLostRanges("v"); len(got) != 1 || got[0] != want {
|
||||
t.Fatalf("reloaded lost range %+v; want [%+v]", got, want)
|
||||
}
|
||||
raw, err := json.Marshal(reloaded.WorkspaceState("v").Moves[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(raw), "Lost") {
|
||||
t.Fatalf("the move record's encoding changed: %s", raw)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A clean move abandons nothing and records no lost range.
|
||||
func TestWorkspaceCleanMoveRecordsNoLostRange(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
disk, dir := newTempStore(t)
|
||||
p := NewPublisher(nil, WithStore(disk))
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "v", "old", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := WorkspaceMoveRequest{RequestID: "c", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1,
|
||||
TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"}
|
||||
if _, err := p.MoveWorkspace(ctx, req, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42, Detached: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 0 {
|
||||
t.Fatalf("clean move recorded a lost range: %+v", got)
|
||||
}
|
||||
if m, _ := filepath.Glob(filepath.Join(dir, "*"+lostRangeFileExtension)); len(m) != 0 {
|
||||
t.Fatalf("clean move wrote a lost range file: %v", m)
|
||||
}
|
||||
}
|
||||
|
||||
// lostRangeFaultStore is the file store with injectable failures.
|
||||
type lostRangeFaultStore struct {
|
||||
*FileAuthorityStore
|
||||
failPut, failLostRange bool
|
||||
}
|
||||
|
||||
var errInjected = errors.New("injected store failure")
|
||||
|
||||
func (s *lostRangeFaultStore) Put(r DurableRecord) error {
|
||||
if s.failPut && r.Workspace != nil && len(r.Workspace.Moves) > 0 {
|
||||
return errInjected
|
||||
}
|
||||
return s.FileAuthorityStore.Put(r)
|
||||
}
|
||||
|
||||
func (s *lostRangeFaultStore) PutWorkspaceLostRanges(v string, rs []WorkspaceLostRange) error {
|
||||
if s.failLostRange {
|
||||
return errInjected
|
||||
}
|
||||
return s.FileAuthorityStore.PutWorkspaceLostRanges(v, rs)
|
||||
}
|
||||
|
||||
// The lost range is written before the move record: a failed range write
|
||||
// refuses the move (no epoch issued); a range whose move record then fails
|
||||
// is an orphan, on disk but never reported.
|
||||
func TestWorkspaceForcedMoveLostRangeOrdering(t *testing.T) {
|
||||
t.Run("range write fails", func(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
store := &lostRangeFaultStore{FileAuthorityStore: disk, failLostRange: true}
|
||||
p, now, barrier := forcedLostRangeFixture(t, store, false)
|
||||
*now = barrier.Add(time.Second)
|
||||
if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); !errors.Is(err, errInjected) {
|
||||
t.Fatalf("move with a failed range write: %v; want refused", err)
|
||||
}
|
||||
if line, _ := NewPublisher(nil, WithStore(disk)).VolumeAuthorityLine("v"); line.Epoch != 1 {
|
||||
t.Fatalf("epoch issued without its lost range: %+v", line)
|
||||
}
|
||||
})
|
||||
t.Run("move record fails", func(t *testing.T) {
|
||||
disk, dir := newTempStore(t)
|
||||
store := &lostRangeFaultStore{FileAuthorityStore: disk, failPut: true}
|
||||
p, now, barrier := forcedLostRangeFixture(t, store, false)
|
||||
*now = barrier.Add(time.Second)
|
||||
if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err == nil {
|
||||
t.Fatal("move issued although its record failed")
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "v"+lostRangeFileExtension))
|
||||
if err != nil || !strings.Contains(string(raw), `"RequestID":"f"`) {
|
||||
t.Fatalf("fixture: no orphan range on disk: %v %s", err, raw)
|
||||
}
|
||||
if got := p.WorkspaceLostRanges("v"); len(got) != 0 {
|
||||
t.Fatalf("orphan reported: %+v", got)
|
||||
}
|
||||
if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 0 {
|
||||
t.Fatalf("orphan reported after reload: %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// issueFailStore fails the authority write that would issue a move, leaving
|
||||
// its reservation pending on disk (a crash between reservation and issue).
|
||||
type issueFailStore struct {
|
||||
*FileAuthorityStore
|
||||
failIssue bool
|
||||
}
|
||||
|
||||
func (s *issueFailStore) Put(r DurableRecord) error {
|
||||
if s.failIssue && r.Workspace != nil {
|
||||
for _, m := range r.Workspace.Moves {
|
||||
if m.Issued {
|
||||
return errInjected
|
||||
}
|
||||
}
|
||||
}
|
||||
return s.FileAuthorityStore.Put(r)
|
||||
}
|
||||
|
||||
// A pending forced reservation resumes only with the exact range recorded
|
||||
// before it: after a reload the retry issues it with that range (not one
|
||||
// recomputed at the retry); without it the retry is refused, and a new
|
||||
// request records a fresh range.
|
||||
func TestWorkspaceForcedReservationResumeNeedsItsRange(t *testing.T) {
|
||||
for _, missing := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "range kept", true: "range missing"}[missing], func(t *testing.T) {
|
||||
disk, dir := newTempStore(t)
|
||||
store := &issueFailStore{FileAuthorityStore: disk, failIssue: true}
|
||||
p, now, barrier := forcedLostRangeFixture(t, store, false)
|
||||
*now = barrier.Add(time.Second)
|
||||
if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err == nil {
|
||||
t.Fatal("fixture: the issue write did not fail")
|
||||
}
|
||||
st := NewPublisher(nil, WithStore(disk)).WorkspaceState("v")
|
||||
if st == nil || len(st.Moves) != 1 || st.Moves[0].Issued {
|
||||
t.Fatalf("fixture: no pending reservation on disk: %+v", st)
|
||||
}
|
||||
want := WorkspaceLostRange{RequestID: "f", NewEpoch: st.Moves[0].NewEpoch, OldReplicaID: "old", OldEpoch: 1, LostAfterLSN: 42, LostUntilNS: barrier.UnixNano()}
|
||||
if missing {
|
||||
if err := os.Remove(filepath.Join(dir, "v"+lostRangeFileExtension)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
later := barrier.Add(time.Hour) // a recomputed bound would differ
|
||||
q := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, func() time.Time { return later }))
|
||||
later = later.Add(time.Minute) // past the reload's own restart deadline
|
||||
r, err := q.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead)
|
||||
if missing {
|
||||
if err == nil || !strings.Contains(err.Error(), "no recorded lost range") {
|
||||
t.Fatalf("resume without its range: %v; want refused", err)
|
||||
}
|
||||
if line, _ := q.VolumeAuthorityLine("v"); line.Epoch != 1 {
|
||||
t.Fatalf("epoch issued without a range: %+v", line)
|
||||
}
|
||||
fresh := forcedLostRangeReq
|
||||
fresh.RequestID = "f2"
|
||||
r2, err := q.MoveWorkspace(context.Background(), fresh, forcedLostRangeHead)
|
||||
if err != nil {
|
||||
t.Fatalf("a new request after the refused resume: %v", err)
|
||||
}
|
||||
if got := q.WorkspaceLostRanges("v"); len(got) != 1 || got[0].RequestID != "f2" || got[0].NewEpoch != r2.NewEpoch {
|
||||
t.Fatalf("new request range %+v", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || !r.Issued || r.NewEpoch != want.NewEpoch {
|
||||
t.Fatalf("resume: %+v %v", r, err)
|
||||
}
|
||||
if got := q.WorkspaceLostRanges("v"); len(got) != 1 || got[0] != want {
|
||||
t.Fatalf("resumed range %+v; want the recorded [%+v]", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Failures inside the file store: before the rename nothing is published
|
||||
// and no temp file is left; after the rename (directory sync) the range may
|
||||
// be on disk as an orphan. Either way the move is refused with no epoch, the
|
||||
// orphan is not reported, and a retry issues with exactly one range.
|
||||
func TestWorkspaceLostRangeFileFaults(t *testing.T) {
|
||||
for _, step := range []string{"before-rename", "directory-sync"} {
|
||||
t.Run(step, func(t *testing.T) {
|
||||
disk, dir := newTempStore(t)
|
||||
p, now, barrier := forcedLostRangeFixture(t, disk, false)
|
||||
*now = barrier.Add(time.Second)
|
||||
testLostRangeFaultHook = func(s string) error {
|
||||
if s == step {
|
||||
return errInjected
|
||||
}
|
||||
return nil
|
||||
}
|
||||
t.Cleanup(func() { testLostRangeFaultHook = nil })
|
||||
if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); !errors.Is(err, errInjected) {
|
||||
t.Fatalf("move with a failed range write: %v; want refused", err)
|
||||
}
|
||||
if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 1 {
|
||||
t.Fatalf("epoch issued: %+v", line)
|
||||
}
|
||||
_, statErr := os.Stat(filepath.Join(dir, "v"+lostRangeFileExtension))
|
||||
temps, _ := filepath.Glob(filepath.Join(dir, "*"+lostRangeFileExtension+tempSuffix))
|
||||
if len(temps) != 0 {
|
||||
t.Fatalf("temp file left: %v", temps)
|
||||
}
|
||||
if step == "before-rename" && statErr == nil {
|
||||
t.Fatal("range published although the write failed before the rename")
|
||||
}
|
||||
if step == "directory-sync" && statErr != nil {
|
||||
t.Fatalf("fixture: the rename did not land: %v", statErr)
|
||||
}
|
||||
if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 0 {
|
||||
t.Fatalf("orphan reported: %+v", got)
|
||||
}
|
||||
testLostRangeFaultHook = nil
|
||||
r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead)
|
||||
if err != nil {
|
||||
t.Fatal("retry:", err)
|
||||
}
|
||||
if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 1 || got[0].NewEpoch != r.NewEpoch {
|
||||
t.Fatalf("after the retry: %+v; want one range", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A store wrapper that embeds AuthorityStore forwards the lost ranges: a
|
||||
// forced move through it records its range.
|
||||
func TestWorkspaceLostRangeThroughAStoreWrapper(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
wrapped := &workspaceFailStore{AuthorityStore: disk}
|
||||
p, now, barrier := forcedLostRangeFixture(t, wrapped, false)
|
||||
*now = barrier.Add(time.Second)
|
||||
if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 1 {
|
||||
t.Fatalf("range through a wrapper: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Budget evidence (logged, not asserted): the added critical-section write,
|
||||
// one file of the volume's whole range history plus two fsyncs, for a short
|
||||
// and a long history.
|
||||
func TestWorkspaceLostRangeWriteCost(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
for _, n := range []int{1, 1000} {
|
||||
ranges := make([]WorkspaceLostRange, n)
|
||||
for i := range ranges {
|
||||
ranges[i] = WorkspaceLostRange{RequestID: "request-" + strings.Repeat("x", 24), NewEpoch: uint64(i + 2), OldReplicaID: "r1", OldEpoch: uint64(i + 1), LostAfterLSN: 1 << 40, LostUntilNS: 1 << 60}
|
||||
}
|
||||
var worst time.Duration
|
||||
for i := 0; i < 5; i++ {
|
||||
start := time.Now()
|
||||
if err := disk.PutWorkspaceLostRanges("v", ranges); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d := time.Since(start); d > worst {
|
||||
worst = d
|
||||
}
|
||||
}
|
||||
t.Logf("lost range write: %d entries, worst of 5 = %v", n, worst)
|
||||
}
|
||||
}
|
||||
@@ -67,7 +67,10 @@ func (h *harness) writeBlocks(n uint32) {
|
||||
// and marks the replica's synced frontier at the primary's head. Used
|
||||
// by C1 setup where the replica is already caught up.
|
||||
func (h *harness) mirrorToReplica() {
|
||||
blocks := h.primaryStore.AllBlocks()
|
||||
blocks, err := h.primaryStore.AllBlocks()
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("calibration snapshot: %w", err))
|
||||
}
|
||||
_, _, pH := h.primaryStore.Boundaries()
|
||||
for lba, data := range blocks {
|
||||
_ = h.replicaStore.ApplyEntry(lba, data, pH)
|
||||
@@ -120,7 +123,10 @@ func (h *harness) commandLog() []string {
|
||||
// dataMatches returns true iff every LBA that exists on the primary is
|
||||
// byte-identical on the replica. Used for C2/C3 data-integrity evidence.
|
||||
func (h *harness) dataMatches() bool {
|
||||
primary := h.primaryStore.AllBlocks()
|
||||
primary, err := h.primaryStore.AllBlocks()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for lba, want := range primary {
|
||||
got, err := h.replicaStore.Read(lba)
|
||||
if err != nil {
|
||||
|
||||
@@ -94,7 +94,7 @@ func NewVolumeShowBody(vol string, v *VolumeInfo, h *storage.ChunkHead) VolumeSh
|
||||
if state == "" {
|
||||
state = storage.ChunkHeadActive
|
||||
}
|
||||
body.Head = &HeadShow{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: state, ChunkCount: len(h.Chunks)}
|
||||
body.Head = &HeadShow{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: state, ChunkCount: manifestCount(*h)}
|
||||
if d := h.DetachedBy; d != nil {
|
||||
body.Head.DetachedBy = &DetachedByShow{Holder: d.Holder, Epoch: d.Epoch, Gen: d.Gen}
|
||||
}
|
||||
|
||||
@@ -228,8 +228,9 @@ type SnapshotInfo struct {
|
||||
|
||||
attempt string // the attempt the name resolved to, when read by name
|
||||
|
||||
head storage.ChunkHead
|
||||
geo Geometry
|
||||
head storage.ChunkHead
|
||||
geo Geometry
|
||||
digest string // identity uses the embedded writer version, not today's serializer
|
||||
}
|
||||
|
||||
// Head returns the HEAD the snapshot copied.
|
||||
@@ -673,6 +674,10 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) {
|
||||
if err != nil {
|
||||
return fail("%v", err)
|
||||
}
|
||||
digest, err := snapshotHeadDigest(head, doc.Head)
|
||||
if err != nil {
|
||||
return fail("HEAD identity: %v", err)
|
||||
}
|
||||
state := string(e.Extended[extSnapState])
|
||||
if state != SnapActive && state != SnapDeleting {
|
||||
return fail("state %q", state)
|
||||
@@ -684,7 +689,7 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) {
|
||||
VolumeID: doc.VolumeID, Name: doc.Name, HeadGen: head.Gen, HeadEpoch: head.Epoch, CutLSN: head.RemoteLSN,
|
||||
CreatedNs: doc.CreatedNs, State: state, ChunkCount: manifestCount(head), ManifestBytes: len(e.GetContent()),
|
||||
Consistency: doc.Consistency, Labels: doc.Labels, Parent: doc.Parent, ExpiresAtNs: doc.ExpiresAtNs,
|
||||
Class: doc.Class, head: head, geo: doc.Geometry,
|
||||
Class: doc.Class, head: head, geo: doc.Geometry, digest: digest,
|
||||
}, doc.RequestID, nil
|
||||
}
|
||||
|
||||
@@ -870,6 +875,11 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe
|
||||
return SnapshotInfo{}, refuseDeleted(vol, "it cannot be snapshotted")
|
||||
}
|
||||
|
||||
head, upgradeIDs, err := c.prepareLegacyHead(ctx, root, head, head, v.Geometry)
|
||||
defer c.dropManifestIntents(ctx, root, upgradeIDs)
|
||||
if err != nil {
|
||||
return SnapshotInfo{}, err
|
||||
}
|
||||
headEnt, err := headEntry(head)
|
||||
if err != nil {
|
||||
return SnapshotInfo{}, err
|
||||
@@ -1231,10 +1241,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error)
|
||||
return ForkResult{}, fmt.Errorf("chunkstore: snapshot %s/%s has no geometry", req.Source, req.Snapshot)
|
||||
}
|
||||
src := snap.Head()
|
||||
digest, err := headDigest(src)
|
||||
if err != nil {
|
||||
return ForkResult{}, err
|
||||
}
|
||||
digest := snap.digest
|
||||
head := storage.ChunkHead{Gen: 1, Epoch: 0, Holder: "", RemoteLSN: src.RemoteLSN, Chunks: make(map[uint64]storage.ChunkRef, len(src.Chunks)), State: storage.ChunkHeadActive}
|
||||
qualified := 0
|
||||
if src.Segments != nil {
|
||||
@@ -1285,6 +1292,11 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error)
|
||||
existing = vol
|
||||
}
|
||||
|
||||
head, upgradeIDs, err := c.prepareLegacyHead(ctx, dstRoot, storage.ChunkHead{}, head, snap.geo)
|
||||
defer c.dropManifestIntents(ctx, dstRoot, upgradeIDs)
|
||||
if err != nil {
|
||||
return ForkResult{}, err
|
||||
}
|
||||
he, err := headEntry(head)
|
||||
if err != nil {
|
||||
return ForkResult{}, err
|
||||
|
||||
@@ -28,8 +28,7 @@ func intentsOf(t *testing.T, f *fakeFiler, vol string) []storage.ChunkIntent {
|
||||
|
||||
func sortedKeysOf(h storage.ChunkHead, qualify string) []string {
|
||||
var out []string
|
||||
for _, ref := range h.Chunks {
|
||||
k := ref.Key
|
||||
for _, k := range headKeys(h) {
|
||||
if qualify != "" && !strings.HasPrefix(k, "@") {
|
||||
k = "@" + qualify + "/" + k
|
||||
}
|
||||
@@ -196,11 +195,20 @@ func TestFork_IncompleteRetryBoundToOriginalImage(t *testing.T) {
|
||||
next.Chunks[k] = v
|
||||
}
|
||||
next.Chunks[5] = storage.ChunkRef{Key: "chunks/e1/c5/new", SHA256: sha256Of(chunkBytes(0x55))}
|
||||
next, ids, err := r1.PrepareManifest(ctx, h, next, h.ChunkBytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gen, err := r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: 1}, next)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next.Gen = gen
|
||||
for _, id := range ids {
|
||||
if err := r1.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-new"}, next); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -41,11 +41,20 @@ func publishSource(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string, chunks
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, intents, err := r.PrepareManifest(ctx, cur, h, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Gen = gen
|
||||
for _, id := range intents {
|
||||
if err := r.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
@@ -80,7 +89,10 @@ func chunkBytes(fill byte) []byte {
|
||||
func catalogFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) {
|
||||
t.Helper()
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
c := newCat(t, f)
|
||||
c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.EnsureVolume(context.Background(), "v1", catGeo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -233,7 +245,7 @@ func TestCatalog_DeleteMarksThenIdempotent(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
f, b, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -259,7 +271,7 @@ func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) {
|
||||
if got, _ := f.ListEntries(ctx, catBase+"/v2/intents", "", "", 0); len(got) != 0 {
|
||||
t.Fatalf("fork left %d intents", len(got))
|
||||
}
|
||||
r2, _ := NewChunkRemote(f, newFakeBlobs(), catBase+"/v2")
|
||||
r2, _ := NewChunkRemote(f, b, catBase+"/v2")
|
||||
head, err := r2.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -269,11 +281,11 @@ func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) {
|
||||
}
|
||||
for idx, ref := range head.Chunks {
|
||||
src := h.Chunks[idx]
|
||||
if ref.Key != "@v1/"+src.Key || ref.SHA256 != src.SHA256 {
|
||||
if ref.Key != qualifyManifestKey("v1", src.Key) || ref.SHA256 != src.SHA256 {
|
||||
t.Fatalf("chunk %d ref %+v, want @v1/%s with the same hash", idx, ref, src.Key)
|
||||
}
|
||||
}
|
||||
if res.HeadGen != 1 || res.HeadEpoch != 0 || res.QualifiedRefs != 2 || res.SourceGen != h.Gen || res.RemoteLSN != 42 || res.Replayed {
|
||||
if res.HeadGen != 1 || res.HeadEpoch != 0 || res.QualifiedRefs != 1 || res.ChunkCount != 2 || res.SourceGen != h.Gen || res.RemoteLSN != 42 || res.Replayed {
|
||||
t.Fatalf("result %+v", res)
|
||||
}
|
||||
v, ok, err := c.ReadVolume(ctx, "v2")
|
||||
@@ -310,7 +322,7 @@ func TestFork_ForkOfForkKeepsOriginalOwner(t *testing.T) {
|
||||
r3, _ := NewChunkRemote(f, b, catBase+"/v3")
|
||||
h3, _ := r3.GetHead(ctx)
|
||||
for idx, ref := range h3.Chunks {
|
||||
if ref.Key != "@v1/"+h.Chunks[idx].Key {
|
||||
if ref.Key != qualifyManifestKey("v1", h.Chunks[idx].Key) {
|
||||
t.Fatalf("second-level fork chunk %d names %q, want the original owner @v1/%s", idx, ref.Key, h.Chunks[idx].Key)
|
||||
}
|
||||
if got, err := r3.Get(ctx, ref.Key); err != nil || sha256.Sum256(got) != ref.SHA256 {
|
||||
@@ -648,7 +660,7 @@ func TestCatalog_EnsureVolumeCreatesTheInitialHead(t *testing.T) {
|
||||
if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if kept, _, _ := c.ReadHead(ctx, "v2"); kept.Gen != pub.Gen || len(kept.Chunks) != 1 {
|
||||
if kept, _, _ := c.ReadHead(ctx, "v2"); kept.Gen != pub.Gen || manifestCount(kept) != 1 || kept.Segments[0] != pub.Segments[0] {
|
||||
t.Fatalf("an existing HEAD was replaced by the initial one: %+v, published %+v", kept, pub)
|
||||
}
|
||||
|
||||
|
||||
@@ -339,6 +339,7 @@ func decodeIntent(p string, e *filerpb.Entry) (storage.ChunkIntent, error) {
|
||||
}
|
||||
|
||||
type headDoc struct {
|
||||
Levels int `json:"levels,omitempty"`
|
||||
Segments map[uint64]storage.ChunkSegment `json:"segments,omitempty"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes,omitempty"`
|
||||
ChunkCount int `json:"chunk_count,omitempty"`
|
||||
@@ -370,6 +371,16 @@ type refDoc struct {
|
||||
// was ever published. An entry that exists but does not decode is an
|
||||
// error, never the zero HEAD.
|
||||
func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
|
||||
h, err := r.getHeadRoot(ctx)
|
||||
if err != nil {
|
||||
return h, err
|
||||
}
|
||||
return r.resolveManifest(ctx, h)
|
||||
}
|
||||
|
||||
// getHeadRoot validates the root and its CAS attributes without reading any
|
||||
// immutable segment. CASHead only needs authority and lineage from this root.
|
||||
func (r *ChunkRemote) getHeadRoot(ctx context.Context) (storage.ChunkHead, error) {
|
||||
e, err := r.f.LookupEntry(ctx, r.root, headName)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return storage.ChunkHead{}, nil
|
||||
@@ -377,11 +388,7 @@ func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
|
||||
if err != nil {
|
||||
return storage.ChunkHead{}, err
|
||||
}
|
||||
h, err := decodeHead(path.Join(r.root, headName), e)
|
||||
if err != nil {
|
||||
return h, err
|
||||
}
|
||||
return r.resolveManifest(ctx, h)
|
||||
return decodeHead(path.Join(r.root, headName), e)
|
||||
}
|
||||
|
||||
// CASHead installs next, at generation expected.Gen+1, only if the stored
|
||||
@@ -397,7 +404,7 @@ func (r *ChunkRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer
|
||||
// Read the LSN under the same generation/epoch guard used by UpdateEntry.
|
||||
// A competing write after this read makes the conditional update fail;
|
||||
// no successful CAS can lower the committed lineage frontier.
|
||||
current, err := r.GetHead(ctx)
|
||||
current, err := r.getHeadRoot(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -439,19 +446,17 @@ func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) {
|
||||
doc.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen}
|
||||
}
|
||||
if h.Segments == nil {
|
||||
doc.Chunks = make(map[uint64]refDoc, len(h.Chunks))
|
||||
for idx, ref := range h.Chunks {
|
||||
if ref.Key == "" {
|
||||
return nil, fmt.Errorf("chunkstore: HEAD chunk %d has no key", idx)
|
||||
}
|
||||
doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])}
|
||||
if len(h.Chunks) != 0 {
|
||||
return nil, errors.New("chunkstore: data HEAD requires a segmented manifest and geometry")
|
||||
}
|
||||
doc.Chunks = map[uint64]refDoc{}
|
||||
}
|
||||
if h.Segments != nil {
|
||||
if err := validateRoot(h); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc.Format = 2
|
||||
doc.Format = 3
|
||||
doc.Levels = 1
|
||||
doc.Chunks = nil
|
||||
doc.Segments = h.Segments
|
||||
doc.ChunkBytes = h.ChunkBytes
|
||||
@@ -555,11 +560,11 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) {
|
||||
if err != nil || len(sum) != 32 || ref.Key == "" {
|
||||
return fail("chunk %d ref invalid", idx)
|
||||
}
|
||||
cr := storage.ChunkRef{Key: ref.Key}
|
||||
cr := storage.ChunkRef{Key: ref.Key, Encoding: "full", BirthLSN: doc.RemoteLSN}
|
||||
copy(cr.SHA256[:], sum)
|
||||
h.Chunks[idx] = cr
|
||||
}
|
||||
if doc.Format == 2 {
|
||||
if doc.Format == 2 || doc.Format == 3 {
|
||||
if len(doc.Chunks) != 0 {
|
||||
return fail("segmented root contains flat chunks")
|
||||
}
|
||||
|
||||
@@ -55,10 +55,22 @@ func TestChunkRemote_HeadRoundTripAndCAS(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := head(1, "a", 42, map[uint64]storage.ChunkRef{3: ref("chunks/e1/c3/n-1", d)})
|
||||
legacy := want.Chunks[3]
|
||||
legacy.Encoding, legacy.BirthLSN = "full", want.RemoteLSN
|
||||
want.Chunks[3] = legacy
|
||||
want, intents, err := r.PrepareManifest(ctx, storage.ChunkHead{}, want, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, want)
|
||||
if err != nil || gen != 1 {
|
||||
t.Fatalf("first CAS = %d, %v; want gen 1", gen, err)
|
||||
}
|
||||
for _, id := range intents {
|
||||
if err := r.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -228,7 +240,8 @@ func TestChunkRemote_UntrustedHeadIsAnError(t *testing.T) {
|
||||
f := newFakeFiler()
|
||||
r := newTestRemote(t, f, newFakeBlobs())
|
||||
h := head(1, "a", 1, map[uint64]storage.ChunkRef{0: ref("k", []byte("x"))})
|
||||
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, h); err != nil {
|
||||
h.Gen = 1
|
||||
if err := f.CreateEntry(ctx, testRoot, legacyHeadFixture(t, h), true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.mu.Lock()
|
||||
|
||||
@@ -21,10 +21,14 @@ func fuzzHeadSeeds(tb testing.TB) [][]byte {
|
||||
{Gen: 3, Epoch: 4, Holder: "r2", RemoteLSN: 9, State: storage.ChunkHeadDetached,
|
||||
DetachedBy: &storage.ChunkDetachedBy{Holder: "r2", Epoch: 4, Gen: 3}, Chunks: map[uint64]storage.ChunkRef{}},
|
||||
{Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 3, ChunkBytes: 4 << 20, ManifestChunkCount: 2,
|
||||
Segments: map[uint64]storage.ChunkSegment{0: {Key: "@v1/seg/00", SHA256: sum, Owner: "v1", Count: 2}}},
|
||||
Segments: map[uint64]storage.ChunkSegment{0: {Key: "@v1/seg/00", SHA256: sum, Owner: "v1", Count: 2, SegFormat: 2, MaxBirthLSN: 3}}},
|
||||
}
|
||||
var out [][]byte
|
||||
for _, h := range heads {
|
||||
if h.Segments == nil && len(h.Chunks) > 0 {
|
||||
out = append(out, legacyHeadFixture(tb, h).Content)
|
||||
continue
|
||||
}
|
||||
e, err := headEntry(h)
|
||||
if err != nil {
|
||||
tb.Fatalf("seed %+v: %v", h, err)
|
||||
@@ -90,6 +94,12 @@ func FuzzDecodeHeadDocument(f *testing.F) {
|
||||
return
|
||||
}
|
||||
e, err := headEntry(h)
|
||||
if h.Segments == nil && len(h.Chunks) > 0 {
|
||||
if err == nil {
|
||||
t.Fatal("read-only legacy data was writable as flat HEAD")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
if gap := knownHeadEncodeGap(h); gap != "" {
|
||||
return
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// Frozen output of the pre-format-3 CreateSnapshot/Fork producers at 3401cc60.
|
||||
func preF4ForkFixture(t *testing.T, segmented bool) (*fakeFiler, *Catalog, *ChunkRemote) {
|
||||
t.Helper()
|
||||
suffix := "false"
|
||||
if segmented {
|
||||
suffix = "true"
|
||||
}
|
||||
data, err := os.ReadFile("testdata/pre_f4_fork_" + suffix + ".json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var frozen struct {
|
||||
Entries map[string]*filerpb.Entry
|
||||
Objects map[string][]byte
|
||||
}
|
||||
if err := json.Unmarshal(data, &frozen); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
f.entries = frozen.Entries
|
||||
c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.now = func() time.Time { return time.Unix(1000, 0) }
|
||||
r, err := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Put(context.Background(), "legacy-data", bytes.Repeat([]byte{0x41}, 8*4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for key, body := range frozen.Objects {
|
||||
if err := r.Put(context.Background(), key, body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return f, c, r
|
||||
}
|
||||
func assertLegacyImage(t *testing.T, r *ChunkRemote) {
|
||||
t.Helper()
|
||||
h, err := r.GetHead(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h.RemoteLSN != 7 || len(h.Chunks) != 1 {
|
||||
t.Fatalf("legacy image/frontier lost: %+v", h)
|
||||
}
|
||||
data, err := r.Get(context.Background(), h.Chunks[0].Key)
|
||||
if err != nil || !bytes.Equal(data, bytes.Repeat([]byte{0x41}, 8*4096)) {
|
||||
t.Fatalf("legacy bytes changed: %v", err)
|
||||
}
|
||||
}
|
||||
func TestFormatUpgradeLegacyIncompleteFork(t *testing.T) {
|
||||
for _, segmented := range []bool{false, true} {
|
||||
name := "flat"
|
||||
if segmented {
|
||||
name = "segmented"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
f, c, r := preF4ForkFixture(t, segmented)
|
||||
_, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"})
|
||||
if err != nil {
|
||||
t.Fatalf("old incomplete fork retry: %v", err)
|
||||
}
|
||||
dst, err := NewChunkRemote(f, r.b, path.Join(catBase, "v2"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertLegacyImage(t, dst)
|
||||
e, err := f.LookupEntry(context.Background(), path.Join(catBase, "v2"), headName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var doc struct{ Format int }
|
||||
if json.Unmarshal(e.Content, &doc) != nil || doc.Format != 3 {
|
||||
t.Fatal("fork data must be format3")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestFormatUpgradeLegacyForkIdentityStillRefusesChangedImage(t *testing.T) {
|
||||
for _, segmented := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "flat", true: "segmented"}[segmented], func(t *testing.T) {
|
||||
f, c, _ := preF4ForkFixture(t, segmented)
|
||||
p := snapPath(t, f, "v1", "s1")
|
||||
var s snapDoc
|
||||
if err := json.Unmarshal(f.entries[p].Content, &s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var h map[string]any
|
||||
if err := json.Unmarshal(s.Head, &h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Preserve generation/frontier: only immutable content identity changes.
|
||||
if segmented {
|
||||
ref := h["segments"].(map[string]any)["0"].(map[string]any)
|
||||
sum := ref["sha256"].([]any)
|
||||
sum[0] = float64((int(sum[0].(float64)) + 1) % 256)
|
||||
} else {
|
||||
ref := h["chunks"].(map[string]any)["0"].(map[string]any)
|
||||
ref["sha256"] = strings.Repeat("0", 64)
|
||||
}
|
||||
s.Head, _ = json.Marshal(h)
|
||||
f.entries[p].Content, _ = json.Marshal(s)
|
||||
if _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}); CodeOf(err) != CodeTargetExists {
|
||||
t.Fatalf("changed image admitted or identity not reached: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestFormatUpgradeLegacySnapshotAndDelete(t *testing.T) {
|
||||
t.Run("snapshot", func(t *testing.T) {
|
||||
f, c, r := preF4ForkFixture(t, false)
|
||||
h, err := r.GetHead(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "upgraded", RequestID: "new-snapshot"}, h); err != nil {
|
||||
t.Fatalf("legacy snapshot: %v", err)
|
||||
}
|
||||
e := f.entries[snapPath(t, f, "v1", "upgraded")]
|
||||
var s snapDoc
|
||||
if err := json.Unmarshal(e.Content, &s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var doc struct{ Format int }
|
||||
json.Unmarshal(s.Head, &doc)
|
||||
if doc.Format != 3 {
|
||||
t.Fatal("snapshot contains flat data")
|
||||
}
|
||||
assertLegacyImage(t, r)
|
||||
})
|
||||
t.Run("delete", func(t *testing.T) {
|
||||
f, c, r := preF4ForkFixture(t, false)
|
||||
for p := range f.entries {
|
||||
if p != path.Join(catBase, "v1", headName) && p != path.Join(catBase, "v1", volumeName) && !bytes.Contains([]byte(p), []byte("/keys/")) {
|
||||
delete(f.entries, p)
|
||||
}
|
||||
}
|
||||
h, err := r.GetHead(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Holder = ""
|
||||
h.Epoch = 0
|
||||
f.entries[path.Join(catBase, "v1", headName)] = legacyHeadFixture(t, h)
|
||||
c.retainHook = func(stage, _ string) {
|
||||
if stage == hookHeadMarked {
|
||||
assertLegacyImage(t, r)
|
||||
e := f.entries[path.Join(catBase, "v1", headName)]
|
||||
var d struct{ Format int }
|
||||
json.Unmarshal(e.Content, &d)
|
||||
if d.Format != 3 {
|
||||
t.Fatal("delete mark contains flat data")
|
||||
}
|
||||
}
|
||||
}
|
||||
res, err := c.DeleteVolume(context.Background(), "v1", nil)
|
||||
if err != nil || !res.Completed {
|
||||
t.Fatalf("legacy delete: %+v %v", res, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type legacyUpgradeView struct{}
|
||||
|
||||
func (legacyUpgradeView) Projection() frontend.Projection {
|
||||
return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, Healthy: true}
|
||||
}
|
||||
func TestFormatUpgradeLegacyProviderTakeover(t *testing.T) {
|
||||
f, _, r := preF4ForkFixture(t, false)
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-new/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, legacyUpgradeView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { p.Close() })
|
||||
s, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatalf("legacy provider takeover: %v", err)
|
||||
}
|
||||
h, err := r.GetHead(ctx)
|
||||
if err != nil || h.Holder != "node-new/r1" || h.Epoch != 2 {
|
||||
t.Fatalf("takeover not installed: %+v %v", h, err)
|
||||
}
|
||||
e := f.entries[path.Join(catBase, "v1", headName)]
|
||||
var d struct{ Format int }
|
||||
json.Unmarshal(e.Content, &d)
|
||||
if d.Format != 3 {
|
||||
t.Fatal("takeover wrote flat data")
|
||||
}
|
||||
for i := uint32(0); i < 8; i++ {
|
||||
got, err := s.Read(i)
|
||||
if err != nil || !bytes.Equal(got, bytes.Repeat([]byte{0x41}, 4096)) {
|
||||
t.Fatalf("takeover bytes %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
assertLegacyImage(t, r)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"path"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestManifestFormatUpgradeRejectsUnsupportedOrInconsistentObjects(t *testing.T) {
|
||||
type mutation func(map[string]any)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
segment bool
|
||||
change mutation
|
||||
}{
|
||||
{"levels", false, func(v map[string]any) { v["levels"] = 2 }},
|
||||
{"missing-levels", false, func(v map[string]any) { delete(v, "levels") }},
|
||||
{"head-version", false, func(v map[string]any) { v["format"] = 4 }},
|
||||
{"head-unknown", false, func(v map[string]any) { v["future"] = true }},
|
||||
{"segment-version-ref", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["seg_format"] = 3 }},
|
||||
{"root-max", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["max_birth_lsn"] = 41 }},
|
||||
{"root-max-future", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["max_birth_lsn"] = 43 }},
|
||||
{"segment-version", true, func(v map[string]any) { v["format"] = 3 }},
|
||||
{"segment-unknown", true, func(v map[string]any) { v["future"] = true }},
|
||||
{"segment-max", true, func(v map[string]any) { v["max_birth_lsn"] = 41 }},
|
||||
{"segment-max-missing", true, func(v map[string]any) { delete(v, "max_birth_lsn") }},
|
||||
{"computed-max", true, func(v map[string]any) {
|
||||
for _, entry := range v["chunks"].(map[string]any) {
|
||||
entry.(map[string]any)["birth_lsn"] = 41
|
||||
}
|
||||
}},
|
||||
{"encoding", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["enc"] = "zstd" }},
|
||||
{"birth-future", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["birth_lsn"] = 43 }},
|
||||
{"birth-missing", true, func(v map[string]any) { delete(v["chunks"].(map[string]any)["0"].(map[string]any), "birth_lsn") }},
|
||||
{"hash-shape", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["sha256"] = "bad" }},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f, b, _, _, _ := gcFixture(t)
|
||||
r, h := publishSegmented(t, f, b)
|
||||
ctx := context.Background()
|
||||
e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var root map[string]any
|
||||
if err := json.Unmarshal(e.Content, &root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tc.segment {
|
||||
body, err := r.Get(ctx, h.Segments[0].Key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var object map[string]any
|
||||
if err := json.Unmarshal(body, &object); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tc.change(object)
|
||||
body, err = json.Marshal(object)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Put(ctx, "malformed-segment", body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := root["segments"].(map[string]any)["0"].(map[string]any)
|
||||
ref["key"] = qualifyManifestKey("v1", "malformed-segment")
|
||||
ref["sha256"] = sha256.Sum256(body)
|
||||
} else {
|
||||
tc.change(root)
|
||||
}
|
||||
e.Content, err = json.Marshal(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.GetHead(ctx); err == nil {
|
||||
t.Fatal("invalid persisted schema accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifestFormatUpgradeReadsLegacyRootGoldens(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"format":1,"gen":1,"epoch":1,"holder":"old","remote_lsn":7,"chunks":{"0":{"key":"old","sha256":"0000000000000000000000000000000000000000000000000000000000000000"}}}`,
|
||||
`{"format":2,"gen":1,"epoch":1,"holder":"old","remote_lsn":7,"chunk_bytes":4096,"chunk_count":1,"segments":{"0":{"key":"@v1/old","sha256":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"owner":"v1","count":1}}}`,
|
||||
} {
|
||||
h, err := DecodeHeadDocument("legacy", []byte(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h.Segments == nil {
|
||||
if h.Chunks[0].Encoding != "full" || h.Chunks[0].BirthLSN != 7 {
|
||||
t.Fatal("legacy flat frontier not inherited")
|
||||
}
|
||||
} else if h.Segments[0].SegFormat != 1 || h.Segments[0].MaxBirthLSN != 7 {
|
||||
t.Fatal("legacy segment maximum not inherited")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func legacySegmentedFixture(t *testing.T) (*ChunkRemote, *fakeBlobs, storage.ChunkHead) {
|
||||
t.Helper()
|
||||
f, b, _, _, _ := gcFixture(t)
|
||||
r, err := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
doc := segmentedHeadDoc{headIdentityDoc: headIdentityDoc{Format: 2, Gen: 1, Epoch: 1, Holder: "old", RemoteLSN: 42}, Segments: map[uint64]legacySegmentRefDoc{}, ChunkBytes: 4096, ChunkCount: 2}
|
||||
for group := uint64(0); group < 2; group++ {
|
||||
key := fmt.Sprintf("legacy-data-%d", group)
|
||||
data := []byte{byte(0x41 + group)}
|
||||
if err := r.Put(ctx, key, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
idx := group * (manifestSegmentBytes / 4096)
|
||||
segment := legacySegmentDoc{Format: 1, Range: group, ChunkBytes: 4096, Owner: "v1", Chunks: map[uint64]legacyChunkRefDoc{idx: {Key: qualifyManifestKey("v1", key), SHA256: sha256.Sum256(data)}}}
|
||||
body, err := json.Marshal(segment)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
segmentKey := fmt.Sprintf("legacy-segment-%d", group)
|
||||
if err := r.Put(ctx, segmentKey, body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc.Segments[group] = legacySegmentRefDoc{Key: qualifyManifestKey("v1", segmentKey), SHA256: sha256.Sum256(body), Owner: "v1", Count: 1}
|
||||
}
|
||||
e := legacyHeadFixture(t, storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "old", RemoteLSN: 42})
|
||||
e.Content, err = json.Marshal(doc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r, b.fakeBlobs, h
|
||||
}
|
||||
|
||||
func TestManifestFormatUpgradeReusesColdSegmentsWithoutUploads(t *testing.T) {
|
||||
r, b, base := legacySegmentedFixture(t)
|
||||
ctx := context.Background()
|
||||
before, _, _ := b.counts()
|
||||
unchanged, ids, err := r.PrepareManifest(ctx, base, base, base.ChunkBytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, _, _ := b.counts()
|
||||
if before != after || len(ids) != 0 || unchanged.Segments[0] != base.Segments[0] || unchanged.Segments[1] != base.Segments[1] {
|
||||
t.Fatal("zero changed groups uploaded a segment or intent")
|
||||
}
|
||||
next := base
|
||||
next.RemoteLSN = 43
|
||||
next.Chunks = map[uint64]storage.ChunkRef{}
|
||||
for idx, ref := range base.Chunks {
|
||||
next.Chunks[idx] = ref
|
||||
}
|
||||
data := []byte{0x53}
|
||||
if err := r.Put(ctx, "changed-data", data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
idx := manifestSegmentBytes / base.ChunkBytes
|
||||
next.Chunks[idx] = storage.ChunkRef{Key: qualifyManifestKey("v1", "changed-data"), SHA256: sha256.Sum256(data), Encoding: "full", BirthLSN: 43}
|
||||
before, _, _ = b.counts()
|
||||
updated, ids, err := r.PrepareManifest(ctx, base, next, base.ChunkBytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, _, _ = b.counts()
|
||||
if after-before != 1 || len(ids) != 1 || updated.Segments[0] != base.Segments[0] || updated.Segments[1].SegFormat != 2 || updated.Segments[1].MaxBirthLSN != 43 {
|
||||
t.Fatal("one changed group rewrote cold segments or lost the new format")
|
||||
}
|
||||
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, updated); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, id := range ids {
|
||||
if err := r.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
h, err := r.GetHead(ctx)
|
||||
if err != nil || h.Segments[0].SegFormat != 1 || h.Chunks[0].BirthLSN != 42 || h.Chunks[idx].BirthLSN != 43 {
|
||||
t.Fatalf("mixed legacy/new image did not resolve: %+v %v", h, err)
|
||||
}
|
||||
got, err := r.Get(ctx, h.Chunks[idx].Key)
|
||||
if err != nil || len(got) != 1 || got[0] != 0x53 {
|
||||
t.Fatal("mixed root changed bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifestFormatUpgradeAllowsInheritedZeroBirth(t *testing.T) {
|
||||
f, b, _, _, _ := gcFixture(t)
|
||||
r, err := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
base, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := []byte{0x57}
|
||||
if err := r.Put(ctx, "zero-birth", data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next := storage.ChunkHead{Epoch: 1, Holder: "base", Chunks: map[uint64]storage.ChunkRef{0: {Key: "zero-birth", SHA256: sha256.Sum256(data), Encoding: "full", BirthLSN: 0}}}
|
||||
next, ids, err := r.PrepareManifest(ctx, base, next, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, next); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, id := range ids {
|
||||
if err := r.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
h, err := r.GetHead(ctx)
|
||||
if err != nil || h.Chunks[0].BirthLSN != 0 || h.Segments[0].MaxBirthLSN != 0 {
|
||||
t.Fatalf("fresh base zero birth refused: %+v %v", h, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifestFormatUpgradeSnapshotAndForkPreserveMetadata(t *testing.T) {
|
||||
f, b, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "format3", RequestID: "format3"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snapshotPath := snapPath(t, f, "v1", "format3")
|
||||
e, err := f.LookupEntry(ctx, path.Dir(snapshotPath), path.Base(snapshotPath))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var snapshot struct {
|
||||
Head struct {
|
||||
Format int `json:"format"`
|
||||
Levels int `json:"levels"`
|
||||
} `json:"head"`
|
||||
}
|
||||
if err := json.Unmarshal(e.Content, &snapshot); err != nil || snapshot.Head.Format != 3 || snapshot.Head.Levels != 1 {
|
||||
t.Fatalf("data snapshot embedded flat HEAD: %s %v", e.Content, err)
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "format3", Target: "v2", RequestID: "format3-fork"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := NewChunkRemote(f, b, path.Join(catBase, "v2"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fork, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fork.RemoteLSN != h.RemoteLSN || len(fork.Chunks) != len(h.Chunks) {
|
||||
t.Fatal("fork lost inherited frontier or chunk count")
|
||||
}
|
||||
for idx, ref := range h.Chunks {
|
||||
if fork.Chunks[idx] != ref {
|
||||
t.Fatal("fork changed owner, encoding, birth or stored-byte hash")
|
||||
}
|
||||
}
|
||||
for group, ref := range h.Segments {
|
||||
if fork.Segments[group] != ref {
|
||||
t.Fatal("fork changed segment version or maximum")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestManifestFormatUpgradeSustainedWritesPastWALWithPeriodicFlush(t *testing.T) {
|
||||
const blocks, blockSize, chunkBlocks = 1024, 4096, 64
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
r, err := NewChunkRemote(f, b, path.Join(catBase, "sustained"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "source"), blocks, blockSize, storage.WALStoreOptions{ChunkBlocks: chunkBlocks, WMode: storage.WModeStrict})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { s.Close() })
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: 1, Holder: "source", FreshFromHead: true, BarrierBound: 2, UploadConcurrency: 2})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
walBytes := s.WALCapacityBytes()
|
||||
if walBytes == 0 || walBytes > 128<<20 {
|
||||
t.Fatalf("smoke WAL capacity outside bounded fixture: %d", walBytes)
|
||||
}
|
||||
batchBytes := uint64(blocks * blockSize)
|
||||
rounds := int(walBytes/batchBytes) + 1
|
||||
var payload, last uint64
|
||||
var finalByte byte
|
||||
for round := 0; round < rounds; round++ {
|
||||
finalByte = byte(round%251 + 1)
|
||||
data := bytes.Repeat([]byte{finalByte}, blocks*blockSize)
|
||||
batch := make([][]byte, blocks)
|
||||
for i := range batch {
|
||||
batch[i] = data[i*blockSize : (i+1)*blockSize]
|
||||
}
|
||||
if _, err := s.WriteBatch(0, batch); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
last, err = s.Sync()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload += batchBytes
|
||||
// Use the production periodic flusher, not a second checkpoint path.
|
||||
for s.CheckpointLSN() < last {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("periodic Flush did not cover batch %d: %v", round, ctx.Err())
|
||||
case <-time.After(10 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
if (round+1)%4 == 0 || round+1 == rounds {
|
||||
if _, err := l.Cut(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if payload <= walBytes || s.FlushCount() == 0 {
|
||||
t.Fatal("sustained fixture did not exceed WAL with periodic Flush")
|
||||
}
|
||||
h, err := r.GetHead(ctx)
|
||||
if err != nil || h.RemoteLSN != last {
|
||||
t.Fatalf("final frontier: %+v %v", h, err)
|
||||
}
|
||||
e, err := f.LookupEntry(ctx, path.Join(catBase, "sustained"), headName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var shape struct {
|
||||
Format int `json:"format"`
|
||||
Levels int `json:"levels"`
|
||||
}
|
||||
if err := json.Unmarshal(e.Content, &shape); err != nil || shape.Format != 3 || shape.Levels != 1 {
|
||||
t.Fatal("sustained cut did not publish format3")
|
||||
}
|
||||
fresh, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "fresh"), blocks, blockSize, storage.WALStoreOptions{ChunkBlocks: chunkBlocks, WMode: storage.WModeStrict})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { fresh.Close() })
|
||||
if _, err := fresh.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fresh.SeedChunkFrontier(last); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := storage.AttachChunkLayer(fresh, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: 2, Holder: "fresh", FreshFromHead: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := bytes.Repeat([]byte{finalByte}, blockSize)
|
||||
for lba := uint32(0); lba < blocks; lba++ {
|
||||
got, err := fresh.Read(lba)
|
||||
if err != nil || !bytes.Equal(got, want) {
|
||||
t.Fatalf("fresh read block%d: %v", lba, err)
|
||||
}
|
||||
}
|
||||
t.Logf("payload=%d > WAL=%d, checkpoint drains=%d, FlushCount=%d; full fresh lazy read exact", payload, walBytes, rounds, s.FlushCount())
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"path"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestManifestFormatUpgradeFlatWriterNeverStoresData(t *testing.T) {
|
||||
dataHead := storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{0: {Key: "k"}}}
|
||||
if _, err := headEntry(dataHead); err == nil {
|
||||
t.Fatal("flat writer accepted chunk-bearing HEAD without a manifest")
|
||||
}
|
||||
f, b, _, _, _ := gcFixture(t)
|
||||
r, err := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cur, err := r.GetHead(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, dataHead); err == nil {
|
||||
t.Fatal("direct CAS accepted geometry-free data")
|
||||
}
|
||||
after, err := r.GetHead(context.Background())
|
||||
if err != nil || after.Gen != cur.Gen {
|
||||
t.Fatal("refused flat CAS changed HEAD")
|
||||
}
|
||||
empty, err := headEntry(storage.ChunkHead{Gen: 1, State: storage.ChunkHeadActive})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var shape struct {
|
||||
Format int `json:"format"`
|
||||
}
|
||||
if err := json.Unmarshal(empty.Content, &shape); err != nil || shape.Format != 1 {
|
||||
t.Fatal("empty flat root must remain writable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifestFormatUpgradeWritesVersionedStoredByteReferences(t *testing.T) {
|
||||
f, b, _, _, _ := gcFixture(t)
|
||||
r, h := publishSegmented(t, f, b)
|
||||
ctx := context.Background()
|
||||
entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var root struct {
|
||||
Format int `json:"format"`
|
||||
Levels int `json:"levels"`
|
||||
Segments map[string]struct {
|
||||
Format int `json:"seg_format"`
|
||||
Max uint64 `json:"max_birth_lsn"`
|
||||
} `json:"segments"`
|
||||
}
|
||||
if err := json.Unmarshal(entry.Content, &root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if root.Format != 3 || root.Levels != 1 || root.Segments["0"].Format != 2 || root.Segments["0"].Max != h.RemoteLSN {
|
||||
t.Fatalf("missing format3/levels/segment2 metadata: %s", entry.Content)
|
||||
}
|
||||
body, err := r.Get(ctx, h.Segments[0].Key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var segment struct {
|
||||
Format int `json:"format"`
|
||||
Max uint64 `json:"max_birth_lsn"`
|
||||
Chunks map[string]struct {
|
||||
Encoding string `json:"enc"`
|
||||
Birth uint64 `json:"birth_lsn"`
|
||||
Hash string `json:"sha256"`
|
||||
} `json:"chunks"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &segment); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if segment.Format != 2 || segment.Max != h.RemoteLSN || len(segment.Chunks) != 2 {
|
||||
t.Fatalf("missing segment format/max: %s", body)
|
||||
}
|
||||
for _, ref := range segment.Chunks {
|
||||
if ref.Encoding != "full" || ref.Birth != h.RemoteLSN || len(ref.Hash) != 64 {
|
||||
t.Fatalf("invalid inherited chunk reference: %+v", ref)
|
||||
}
|
||||
}
|
||||
resolved, err := r.GetHead(ctx)
|
||||
if err != nil || len(resolved.Chunks) != 2 {
|
||||
t.Fatalf("format3 roundtrip: %+v %v", resolved, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifestFormatUpgradeRefusesUnknownSegmentField(t *testing.T) {
|
||||
f, b, _, _, _ := gcFixture(t)
|
||||
r, h := publishSegmented(t, f, b)
|
||||
ctx := context.Background()
|
||||
if _, err := r.GetHead(ctx); err != nil {
|
||||
t.Fatalf("valid legacy segment refused: %v", err)
|
||||
}
|
||||
ref := h.Segments[0]
|
||||
body, err := r.Get(ctx, ref.Key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Keep the object hash valid: the refusal must come from the segment schema.
|
||||
body = append(bytes.TrimSuffix(body, []byte("}")), []byte(",\"future_encoding\":\"unsupported\"}")...)
|
||||
if err := r.Put(ctx, "format-upgrade-unknown-field", body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref.Key = qualifyManifestKey(ref.Owner, "format-upgrade-unknown-field")
|
||||
ref.SHA256 = sha256.Sum256(body)
|
||||
h.Segments[0] = ref
|
||||
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.GetHead(ctx); err == nil {
|
||||
t.Fatal("published segment with unknown field accepted")
|
||||
}
|
||||
}
|
||||
@@ -230,6 +230,15 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
|
||||
}
|
||||
if in.Segments != nil {
|
||||
h := storage.ChunkHead{Segments: in.Segments, ChunkBytes: in.ChunkBytes}
|
||||
// Intents protect keys without carrying a published frontier.
|
||||
// Validate segment maxima against the reference maxima here.
|
||||
for group, ref := range h.Segments {
|
||||
if ref.SegFormat == 0 {
|
||||
ref.SegFormat = 1
|
||||
h.Segments[group] = ref
|
||||
}
|
||||
h.RemoteLSN = max(h.RemoteLSN, ref.MaxBirthLSN)
|
||||
}
|
||||
for _, ref := range in.Segments {
|
||||
h.ManifestChunkCount += ref.Count
|
||||
}
|
||||
|
||||
@@ -164,7 +164,7 @@ func TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace(t *testing.T) {
|
||||
t.Fatalf("first unrooted mark: %+v %v", result, e)
|
||||
}
|
||||
*now = now.Add(time.Hour)
|
||||
if result, e := g.Run(ctx); e != nil || result.Reclaimed != 1 {
|
||||
if result, e := g.Run(ctx); e != nil || result.Reclaimed != 2 {
|
||||
t.Fatalf("deleted attempt retained chunks forever: %+v %v", result, e)
|
||||
}
|
||||
if _, e := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath)); e != nil {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type rootCASFiler struct {
|
||||
Filer
|
||||
roots, children int
|
||||
refuseChildren bool
|
||||
}
|
||||
|
||||
func (f *rootCASFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
if name == headName {
|
||||
f.roots++
|
||||
} else {
|
||||
f.children++
|
||||
if f.refuseChildren {
|
||||
return nil, errors.New("segment service unavailable")
|
||||
}
|
||||
}
|
||||
return f.Filer.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
|
||||
// A HEAD CAS validates root authority, not the availability of every immutable
|
||||
// segment. Ordinary GetHead still resolves and verifies all segment contents.
|
||||
func TestManifest_CASReadsOnlyRoot(t *testing.T) {
|
||||
f, b, _, _, _ := gcFixture(t)
|
||||
_, h := publishSegmented(t, f, b)
|
||||
tracked := &rootCASFiler{Filer: f, refuseChildren: true}
|
||||
r, err := NewChunkRemote(tracked, b, path.Join(catBase, "v1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next := h
|
||||
next.RemoteLSN++
|
||||
gen, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next)
|
||||
if err != nil {
|
||||
t.Fatalf("root-only CAS must not depend on segments: %v", err)
|
||||
}
|
||||
if gen != h.Gen+1 || tracked.roots != 1 || tracked.children != 0 {
|
||||
t.Fatalf("CAS gen=%d root reads=%d child reads=%d", gen, tracked.roots, tracked.children)
|
||||
}
|
||||
if _, err := r.GetHead(context.Background()); err == nil {
|
||||
t.Fatal("GetHead skipped segment resolution")
|
||||
}
|
||||
tracked.refuseChildren = false
|
||||
got, err := r.GetHead(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Gen != gen || got.RemoteLSN != next.RemoteLSN || !reflect.DeepEqual(got.Chunks, h.Chunks) || !reflect.DeepEqual(got.Segments, h.Segments) {
|
||||
t.Fatalf("CAS changed content or lost frontier: %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -26,9 +26,30 @@ type flatHeadDoc struct {
|
||||
}
|
||||
type segmentedHeadDoc struct {
|
||||
headIdentityDoc
|
||||
Segments map[uint64]storage.ChunkSegment `json:"segments"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes"`
|
||||
ChunkCount int `json:"chunk_count"`
|
||||
Segments map[uint64]legacySegmentRefDoc `json:"segments"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes"`
|
||||
ChunkCount int `json:"chunk_count"`
|
||||
}
|
||||
|
||||
type legacySegmentRefDoc struct {
|
||||
Key string `json:"key"`
|
||||
SHA256 [32]byte `json:"sha256"`
|
||||
Owner string `json:"owner"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type segmentRefV3Doc struct {
|
||||
legacySegmentRefDoc
|
||||
MaxBirthLSN *uint64 `json:"max_birth_lsn"`
|
||||
SegFormat int `json:"seg_format"`
|
||||
}
|
||||
|
||||
type levelHeadDoc struct {
|
||||
headIdentityDoc
|
||||
Levels int `json:"levels"`
|
||||
Segments map[uint64]segmentRefV3Doc `json:"segments"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes"`
|
||||
ChunkCount int `json:"chunk_count"`
|
||||
}
|
||||
|
||||
func (d headIdentityDoc) document() headDoc {
|
||||
@@ -61,7 +82,29 @@ func decodeFormatHead(content []byte) (headDoc, error) {
|
||||
return headDoc{}, err
|
||||
}
|
||||
doc := segmented.headIdentityDoc.document()
|
||||
doc.Segments, doc.ChunkBytes, doc.ChunkCount = segmented.Segments, segmented.ChunkBytes, segmented.ChunkCount
|
||||
doc.Segments = make(map[uint64]storage.ChunkSegment, len(segmented.Segments))
|
||||
for group, ref := range segmented.Segments {
|
||||
doc.Segments[group] = storage.ChunkSegment{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count, SegFormat: 1, MaxBirthLSN: doc.RemoteLSN}
|
||||
}
|
||||
doc.ChunkBytes, doc.ChunkCount = segmented.ChunkBytes, segmented.ChunkCount
|
||||
return doc, nil
|
||||
case 3:
|
||||
var root levelHeadDoc
|
||||
if err := decoder.Decode(&root); err != nil {
|
||||
return headDoc{}, err
|
||||
}
|
||||
if root.Levels != 1 {
|
||||
return headDoc{}, fmt.Errorf("chunkstore: unsupported levels %d", root.Levels)
|
||||
}
|
||||
doc := root.headIdentityDoc.document()
|
||||
doc.Levels, doc.ChunkBytes, doc.ChunkCount = root.Levels, root.ChunkBytes, root.ChunkCount
|
||||
doc.Segments = make(map[uint64]storage.ChunkSegment, len(root.Segments))
|
||||
for group, ref := range root.Segments {
|
||||
if ref.MaxBirthLSN == nil || (ref.SegFormat != 1 && ref.SegFormat != 2) || *ref.MaxBirthLSN > root.RemoteLSN {
|
||||
return headDoc{}, fmt.Errorf("chunkstore: invalid segment version/birth maximum")
|
||||
}
|
||||
doc.Segments[group] = storage.ChunkSegment{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count, SegFormat: ref.SegFormat, MaxBirthLSN: *ref.MaxBirthLSN}
|
||||
}
|
||||
return doc, nil
|
||||
default:
|
||||
return headDoc{}, fmt.Errorf("chunkstore: unsupported HEAD format %d", discriminator.Format)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// Only old-reader fixtures bypass the production format-1 data-write refusal.
|
||||
func legacyHeadFixture(t testing.TB, h storage.ChunkHead) *filerpb.Entry {
|
||||
t.Helper()
|
||||
doc := headDoc{Format: 1, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: h.State, Chunks: map[uint64]refDoc{}}
|
||||
for idx, ref := range h.Chunks {
|
||||
doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])}
|
||||
}
|
||||
body, err := json.Marshal(doc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &filerpb.Entry{Name: headName, Content: body, Extended: map[string][]byte{extKind: []byte(kindChunkHead), extGen: []byte(strconv.FormatUint(h.Gen, 10)), extEpoch: []byte(strconv.FormatUint(h.Epoch, 10)), extHolder: []byte(h.Holder)}}
|
||||
}
|
||||
@@ -48,6 +48,9 @@ func validateRoot(h storage.ChunkHead) error {
|
||||
}
|
||||
count := 0
|
||||
for group, ref := range h.Segments {
|
||||
if (ref.SegFormat != 1 && ref.SegFormat != 2) || ref.MaxBirthLSN > h.RemoteLSN {
|
||||
return errors.New("chunkstore: invalid segment version/birth maximum")
|
||||
}
|
||||
if CheckVolumeID(ref.Owner) != nil || storage.ValidChunkKey(ref.Key) != nil || ref.Count <= 0 || uint64(ref.Count) > manifestSegmentBytes/h.ChunkBytes || group > ^uint64(0)/(manifestSegmentBytes/h.ChunkBytes) {
|
||||
return errors.New("chunkstore: invalid segment reference")
|
||||
}
|
||||
@@ -76,6 +79,12 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch
|
||||
groups := map[uint64]map[uint64]storage.ChunkRef{}
|
||||
canonical := make(map[uint64]storage.ChunkRef, len(next.Chunks))
|
||||
for idx, ref := range next.Chunks {
|
||||
if ref.Encoding == "" {
|
||||
ref.Encoding, ref.BirthLSN = "full", next.RemoteLSN
|
||||
}
|
||||
if ref.Encoding != "full" || ref.BirthLSN > next.RemoteLSN {
|
||||
return next, nil, errors.New("chunkstore: invalid chunk encoding/birth")
|
||||
}
|
||||
ref.Key = qualifyManifestKey(owner, ref.Key)
|
||||
canonical[idx] = ref
|
||||
group := idx / per
|
||||
@@ -94,6 +103,9 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch
|
||||
// segment group. Keep the same qualified-key comparison for segment reuse.
|
||||
baseGroups := map[uint64]map[uint64]storage.ChunkRef{}
|
||||
for idx, ref := range base.Chunks {
|
||||
if ref.Encoding == "" {
|
||||
ref.Encoding, ref.BirthLSN = "full", base.RemoteLSN
|
||||
}
|
||||
group := idx / per
|
||||
if baseGroups[group] == nil {
|
||||
baseGroups[group] = map[uint64]storage.ChunkRef{}
|
||||
@@ -104,10 +116,14 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch
|
||||
for group, chunks := range groups {
|
||||
old := baseGroups[group]
|
||||
if previous, ok := base.Segments[group]; ok && base.ChunkBytes == chunkBytes && reflect.DeepEqual(chunks, old) {
|
||||
// Legacy groups keep a conservative upper bound until rewritten.
|
||||
if previous.SegFormat == 0 {
|
||||
previous.SegFormat, previous.MaxBirthLSN = 1, base.RemoteLSN
|
||||
}
|
||||
next.Segments[group] = previous
|
||||
continue
|
||||
}
|
||||
body, err := json.Marshal(segmentDoc{1, group, chunkBytes, owner, chunks})
|
||||
body, maxBirth, err := encodeSegmentV2(group, chunkBytes, owner, chunks)
|
||||
if err != nil {
|
||||
return next, nil, err
|
||||
}
|
||||
@@ -119,7 +135,7 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch
|
||||
return next, nil, err
|
||||
}
|
||||
key := fmt.Sprintf("seg/%x", nonce)
|
||||
next.Segments[group] = storage.ChunkSegment{Key: qualifyManifestKey(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks)}
|
||||
next.Segments[group] = storage.ChunkSegment{Key: qualifyManifestKey(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks), SegFormat: 2, MaxBirthLSN: maxBirth}
|
||||
uploads = append(uploads, upload{key, body})
|
||||
}
|
||||
if err := validateRoot(next); err != nil {
|
||||
@@ -161,11 +177,11 @@ func (r *ChunkRemote) resolveManifest(ctx context.Context, h storage.ChunkHead)
|
||||
if len(body) > maxManifestBytes || sha256.Sum256(body) != ref.SHA256 {
|
||||
return h, errors.New("chunkstore: segment hash/size mismatch")
|
||||
}
|
||||
var doc segmentDoc
|
||||
if err := decodeManifestJSON(body, &doc); err != nil {
|
||||
doc, err := decodeSegment(body, ref, h.RemoteLSN)
|
||||
if err != nil {
|
||||
return h, err
|
||||
}
|
||||
if doc.Format != 1 || doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count {
|
||||
if doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count {
|
||||
return h, errors.New("chunkstore: invalid segment contents")
|
||||
}
|
||||
for idx, cr := range doc.Chunks {
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type segmentChunkV2Doc struct {
|
||||
Key string `json:"key"`
|
||||
// SHA256 covers stored object bytes, before any encoding is decoded.
|
||||
SHA256 string `json:"sha256"`
|
||||
Encoding string `json:"enc"`
|
||||
BirthLSN *uint64 `json:"birth_lsn"`
|
||||
}
|
||||
|
||||
type segmentV2Doc struct {
|
||||
Format int `json:"format"`
|
||||
Range uint64 `json:"range"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes"`
|
||||
Owner string `json:"owner"`
|
||||
MaxBirthLSN *uint64 `json:"max_birth_lsn"`
|
||||
Chunks map[uint64]segmentChunkV2Doc `json:"chunks"`
|
||||
}
|
||||
|
||||
type legacyChunkRefDoc struct {
|
||||
Key string
|
||||
SHA256 [32]byte
|
||||
}
|
||||
|
||||
type legacySegmentDoc struct {
|
||||
Format int `json:"format"`
|
||||
Range uint64 `json:"range"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes"`
|
||||
Owner string `json:"owner"`
|
||||
Chunks map[uint64]legacyChunkRefDoc `json:"chunks"`
|
||||
}
|
||||
|
||||
func encodeSegmentV2(group, chunkBytes uint64, owner string, chunks map[uint64]storage.ChunkRef) ([]byte, uint64, error) {
|
||||
doc := segmentV2Doc{Format: 2, Range: group, ChunkBytes: chunkBytes, Owner: owner, Chunks: map[uint64]segmentChunkV2Doc{}}
|
||||
var maxBirth uint64
|
||||
for idx, ref := range chunks {
|
||||
birth := ref.BirthLSN
|
||||
doc.Chunks[idx] = segmentChunkV2Doc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:]), Encoding: ref.Encoding, BirthLSN: &birth}
|
||||
maxBirth = max(maxBirth, birth)
|
||||
}
|
||||
doc.MaxBirthLSN = &maxBirth
|
||||
body, err := json.Marshal(doc)
|
||||
return body, maxBirth, err
|
||||
}
|
||||
|
||||
func decodeSegment(body []byte, ref storage.ChunkSegment, remoteLSN uint64) (segmentDoc, error) {
|
||||
var discriminator struct {
|
||||
Format int `json:"format"`
|
||||
}
|
||||
if err := decodeManifestJSON(body, &discriminator); err != nil {
|
||||
return segmentDoc{}, err
|
||||
}
|
||||
if discriminator.Format != ref.SegFormat {
|
||||
return segmentDoc{}, errors.New("chunkstore: segment format/reference mismatch")
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(body))
|
||||
d.DisallowUnknownFields()
|
||||
result := segmentDoc{Chunks: map[uint64]storage.ChunkRef{}}
|
||||
switch discriminator.Format {
|
||||
case 1:
|
||||
var doc legacySegmentDoc
|
||||
if err := d.Decode(&doc); err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Format, result.Range, result.ChunkBytes, result.Owner = doc.Format, doc.Range, doc.ChunkBytes, doc.Owner
|
||||
for idx, cr := range doc.Chunks {
|
||||
result.Chunks[idx] = storage.ChunkRef{Key: cr.Key, SHA256: cr.SHA256, Encoding: "full", BirthLSN: ref.MaxBirthLSN}
|
||||
}
|
||||
case 2:
|
||||
var doc segmentV2Doc
|
||||
if err := d.Decode(&doc); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if doc.MaxBirthLSN == nil || *doc.MaxBirthLSN != ref.MaxBirthLSN || *doc.MaxBirthLSN > remoteLSN {
|
||||
return result, errors.New("chunkstore: segment birth maximum mismatch")
|
||||
}
|
||||
result.Format, result.Range, result.ChunkBytes, result.Owner = doc.Format, doc.Range, doc.ChunkBytes, doc.Owner
|
||||
var maxBirth uint64
|
||||
for idx, cr := range doc.Chunks {
|
||||
sum, err := hex.DecodeString(cr.SHA256)
|
||||
if err != nil || len(sum) != 32 || cr.Encoding != "full" || cr.BirthLSN == nil || *cr.BirthLSN > remoteLSN {
|
||||
return result, errors.New("chunkstore: invalid segment chunk encoding/hash/birth")
|
||||
}
|
||||
v := storage.ChunkRef{Key: cr.Key, Encoding: cr.Encoding, BirthLSN: *cr.BirthLSN}
|
||||
copy(v.SHA256[:], sum)
|
||||
result.Chunks[idx] = v
|
||||
maxBirth = max(maxBirth, v.BirthLSN)
|
||||
}
|
||||
if maxBirth != *doc.MaxBirthLSN {
|
||||
return result, errors.New("chunkstore: incorrect segment birth maximum")
|
||||
}
|
||||
default:
|
||||
return result, errors.New("chunkstore: unsupported segment format")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -54,7 +54,7 @@ func TestManifest_CapturePublishesSegmentRoot(t *testing.T) {
|
||||
if err = json.Unmarshal(e.Content, &doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if doc.Format != 2 || len(doc.Chunks) != 0 || len(doc.Segments) != 1 {
|
||||
if doc.Format != 3 || len(doc.Chunks) != 0 || len(doc.Segments) != 1 {
|
||||
t.Fatalf("cut did not publish a small segmented root: %s", e.Content)
|
||||
}
|
||||
h, err := r.GetHead(ctx)
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func (c *Catalog) prepareLegacyHead(ctx context.Context, root string, base, next storage.ChunkHead, geo Geometry) (storage.ChunkHead, []string, error) {
|
||||
if next.Segments != nil || len(next.Chunks) == 0 {
|
||||
return next, nil, nil
|
||||
}
|
||||
if c.blobs == nil {
|
||||
return next, nil, errors.New("chunkstore: legacy data upgrade needs blob storage")
|
||||
}
|
||||
r, err := NewChunkRemote(c.f, c.blobs, root)
|
||||
if err != nil {
|
||||
return next, nil, err
|
||||
}
|
||||
return r.PrepareManifest(ctx, base, next, uint64(geo.BlockSize)*uint64(geo.ChunkBlocks))
|
||||
}
|
||||
func (c *Catalog) dropManifestIntents(ctx context.Context, root string, ids []string) {
|
||||
for _, id := range ids {
|
||||
c.dropIntent(ctx, root, id)
|
||||
}
|
||||
}
|
||||
|
||||
// Fork identity is a persisted protocol. Old snapshots keep the pre-format-3
|
||||
// canonical encoding even when their next publication upgrades the manifest.
|
||||
func snapshotHeadDigest(h storage.ChunkHead, embedded json.RawMessage) (string, error) {
|
||||
var version struct {
|
||||
Format int `json:"format"`
|
||||
}
|
||||
if err := json.Unmarshal(embedded, &version); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if version.Format == 3 {
|
||||
return headDigest(h)
|
||||
}
|
||||
type oldHead struct {
|
||||
Segments map[uint64]legacySegmentRefDoc `json:"segments,omitempty"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes,omitempty"`
|
||||
ChunkCount int `json:"chunk_count,omitempty"`
|
||||
Format int `json:"format"`
|
||||
Gen uint64 `json:"gen"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Holder string `json:"holder"`
|
||||
RemoteLSN uint64 `json:"remote_lsn"`
|
||||
Chunks map[uint64]refDoc `json:"chunks,omitempty"`
|
||||
State string `json:"state,omitempty"`
|
||||
DetachedBy *detachedByDoc `json:"detachedBy,omitempty"`
|
||||
}
|
||||
d := oldHead{Format: version.Format, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: h.State}
|
||||
if h.DetachedBy != nil {
|
||||
d.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen}
|
||||
}
|
||||
if version.Format == 2 {
|
||||
d.Segments = map[uint64]legacySegmentRefDoc{}
|
||||
d.ChunkBytes = h.ChunkBytes
|
||||
d.ChunkCount = h.ManifestChunkCount
|
||||
for idx, ref := range h.Segments {
|
||||
d.Segments[idx] = legacySegmentRefDoc{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count}
|
||||
}
|
||||
} else {
|
||||
d.Chunks = map[uint64]refDoc{}
|
||||
for idx, ref := range h.Chunks {
|
||||
d.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])}
|
||||
}
|
||||
}
|
||||
body, err := json.Marshal(d)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
return hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
@@ -338,11 +338,20 @@ func publishTagged(t *testing.T, f *fakeFiler, b *fakeBlobs, vol, tag string, ch
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, ids, err := r.PrepareManifest(ctx, cur, h, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Gen = gen
|
||||
for _, id := range ids {
|
||||
if err := r.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
@@ -353,6 +362,19 @@ func TestCatalog_UsageFromManifests(t *testing.T) {
|
||||
f, b, c, h := catalogFixture(t) // HEAD: chunks 0 and 3
|
||||
ctx := context.Background()
|
||||
full := uint64(catGeo.ChunkBlocks) * uint64(catGeo.BlockSize)
|
||||
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
manifestBytes := func(head storage.ChunkHead) uint64 {
|
||||
var total uint64
|
||||
for _, ref := range head.Segments {
|
||||
body, err := r.Get(ctx, ref.Key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
total += uint64(len(body))
|
||||
}
|
||||
return total
|
||||
}
|
||||
expectedManifestBytes := manifestBytes(h)
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -363,12 +385,13 @@ func TestCatalog_UsageFromManifests(t *testing.T) {
|
||||
if u.LiveChunks != 2 || u.LiveBytes != 2*full || len(u.Snapshots) != 1 || u.Snapshots[0].ExclusiveBytes != 0 {
|
||||
t.Fatalf("shared chunks: %+v", u)
|
||||
}
|
||||
if u.StoredBindings != 2 || u.StoredBytes != 2*full || u.StoredUpperBound {
|
||||
if u.StoredBindings != 3 || u.ManifestBindings != 1 || expectedManifestBytes == 0 || u.ManifestBytes != expectedManifestBytes || u.StoredBytes != 2*full+expectedManifestBytes || u.StoredUpperBound {
|
||||
t.Fatalf("stored: %+v; want 2 bindings, exact", u)
|
||||
}
|
||||
|
||||
// HEAD moves on: chunk 0 is rewritten, so s1 alone holds the old one.
|
||||
publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)})
|
||||
newHead := publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)})
|
||||
expectedManifestBytes += manifestBytes(newHead)
|
||||
u, err = c.Usage(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -377,7 +400,7 @@ func TestCatalog_UsageFromManifests(t *testing.T) {
|
||||
// both of s1's chunks are now exclusive: the new HEAD uses e2 keys
|
||||
t.Fatalf("after HEAD moved: s1 exclusive %d, want %d", u.Snapshots[0].ExclusiveBytes, 2*full)
|
||||
}
|
||||
if u.StoredBindings != 4 || u.StoredBytes != 4*full || u.StoredUpperBound {
|
||||
if u.StoredBindings != 6 || u.ManifestBindings != 2 || u.ManifestBytes != expectedManifestBytes || u.StoredBytes != 4*full+expectedManifestBytes || u.StoredUpperBound {
|
||||
t.Fatalf("stored after HEAD moved: %+v; want 4 bindings, exact", u)
|
||||
}
|
||||
|
||||
@@ -390,7 +413,7 @@ func TestCatalog_UsageFromManifests(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(u.Snapshots) != 0 || u.StoredBindings != 4 || !u.StoredUpperBound {
|
||||
if len(u.Snapshots) != 0 || u.StoredBindings != 6 || !u.StoredUpperBound {
|
||||
t.Fatalf("after delete: %+v; want no snapshots, 4 bindings, upper bound", u)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func FuzzDecodeVersionedSegment(f *testing.F) {
|
||||
sum := sha256.Sum256([]byte("stored bytes"))
|
||||
refs := map[uint64]storage.ChunkRef{0: {Key: "@v1/k", SHA256: sum, Encoding: "full", BirthLSN: 7}}
|
||||
body, _, err := encodeSegmentV2(0, 4096, "v1", refs)
|
||||
if err != nil {
|
||||
f.Fatal(err)
|
||||
}
|
||||
f.Add(body, uint8(2))
|
||||
legacy, err := json.Marshal(legacySegmentDoc{Format: 1, Range: 0, ChunkBytes: 4096, Owner: "v1", Chunks: map[uint64]legacyChunkRefDoc{0: {Key: "@v1/k", SHA256: sum}}})
|
||||
if err != nil {
|
||||
f.Fatal(err)
|
||||
}
|
||||
f.Add(legacy, uint8(1))
|
||||
f.Add([]byte(`{"format":2,"format":1}`), uint8(2))
|
||||
f.Add([]byte(`{"format":3}`), uint8(3))
|
||||
f.Fuzz(func(t *testing.T, body []byte, version uint8) {
|
||||
ref := storage.ChunkSegment{SegFormat: int(version), MaxBirthLSN: 7}
|
||||
got, err := decodeSegment(body, ref, 7)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if got.Format != 1 && got.Format != 2 {
|
||||
t.Fatalf("accepted format %d", got.Format)
|
||||
}
|
||||
for _, cr := range got.Chunks {
|
||||
if cr.Encoding != "full" || cr.BirthLSN > 7 {
|
||||
t.Fatalf("accepted unsupported chunk metadata: %+v", cr)
|
||||
}
|
||||
}
|
||||
if got.Format == 2 {
|
||||
encoded, maxBirth, err := encodeSegmentV2(got.Range, got.ChunkBytes, got.Owner, got.Chunks)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref.MaxBirthLSN = maxBirth
|
||||
again, err := decodeSegment(encoded, ref, 7)
|
||||
if err != nil || !reflect.DeepEqual(got, again) {
|
||||
t.Fatalf("round trip: %+v / %+v: %v", got, again, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"Entries":{"/swblock/chunks/v1/HEAD":{"name":"HEAD","attributes":{"file_size":190,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.epoch":"MQ==","swb.gen":"Mg==","swb.holder":"b2xk","swb.kind":"Y2h1bmtoZWFk"},"content":"eyJmb3JtYXQiOjEsImdlbiI6MiwiZXBvY2giOjEsImhvbGRlciI6Im9sZCIsInJlbW90ZV9sc24iOjcsImNodW5rcyI6eyIwIjp7ImtleSI6ImxlZ2FjeS1kYXRhIiwic2hhMjU2IjoiNWZmMDc0ZGRhZDg4YjdmY2I0MzM5Y2I3YTNlNjgzNDEwNjE3OTI4NjllNDM2NzNiMmRlODUyNWE3NTQ3NmJkOCJ9fSwic3RhdGUiOiJhY3RpdmUifQ=="},"/swblock/chunks/v1/VOLUME":{"name":"VOLUME","attributes":{"file_size":139,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiY3JlYXRlIiwiY3JlYXRlZF9ucyI6MTAwMDAwMDAwMDAwMCwicGFyZW50IjpudWxsfQ=="},"/swblock/chunks/v1/snapnames/s1":{"name":"s1","attributes":{"file_size":127,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi01NTJjZmRhNGU0YzI3YzA1","swb.kind":"Y2h1bmtzbmFwbmFtZQ==","swb.req":"b2xkLXNuYXBzaG90"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImF0dGVtcHQiOiIyLTU1MmNmZGE0ZTRjMjdjMDUiLCJjcmVhdGVkX25zIjoxMDAwMDAwMDAwMDAwfQ=="},"/swblock/chunks/v1/snaps/s1/2-552cfda4e4c27c05":{"name":"2-552cfda4e4c27c05","attributes":{"file_size":442,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi01NTJjZmRhNGU0YzI3YzA1","swb.kind":"Y2h1bmtzbmFw","swb.req":"b2xkLXNuYXBzaG90","swb.snap.claims":"WyJ2Mi9vbGQtZm9yayJd","swb.snap.epoch":"MQ==","swb.snap.gen":"Mg==","swb.snap.lsn":"Nw==","swb.snap.state":"YWN0aXZl"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsImNyZWF0ZWRfYnkiOiIiLCJjb25zaXN0ZW5jeSI6ImNyYXNoIiwiaGVhZCI6eyJmb3JtYXQiOjEsImdlbiI6MiwiZXBvY2giOjEsImhvbGRlciI6Im9sZCIsInJlbW90ZV9sc24iOjcsImNodW5rcyI6eyIwIjp7ImtleSI6ImxlZ2FjeS1kYXRhIiwic2hhMjU2IjoiNWZmMDc0ZGRhZDg4YjdmY2I0MzM5Y2I3YTNlNjgzNDEwNjE3OTI4NjllNDM2NzNiMmRlODUyNWE3NTQ3NmJkOCJ9fSwic3RhdGUiOiJhY3RpdmUifSwiZ2VvbWV0cnkiOnsibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OH0sInBhcmVudCI6bnVsbCwibGFiZWxzIjpudWxsLCJleHBpcmVzX2F0X25zIjowfQ=="},"/swblock/chunks/v2/VOLUME":{"name":"VOLUME","attributes":{"file_size":384,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU=","swb.req":"b2xkLWZvcms="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYyIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiZm9yayIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsInBhcmVudCI6eyJ2b2x1bWVfaWQiOiJ2MSIsInNuYXBzaG90IjoiczEiLCJnZW4iOjJ9LCJmb3JrIjp7InJlcXVlc3RfaWQiOiJvbGQtZm9yayIsInNvdXJjZSI6InYxIiwic25hcHNob3QiOiJzMSIsInNvdXJjZV9nZW4iOjIsImhlYWRfc2hhMjU2IjoiNGZlZGEwZWY2ZTA1OGRjNzNmYmFlMWUyZWEwOGU3ZTdlMGVjZWE0OTk2NjY0Y2ViYTFjYTNmODA5ZGFiYTk3MiIsInJlbW90ZV9sc24iOjcsImNodW5rX2NvdW50IjoxLCJxdWFsaWZpZWRfcmVmcyI6MX19"}},"Objects":{}}
|
||||
@@ -0,0 +1 @@
|
||||
{"Entries":{"/swblock/chunks/v1/HEAD":{"name":"HEAD","attributes":{"file_size":331,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.epoch":"MQ==","swb.gen":"Mg==","swb.holder":"b2xk","swb.kind":"Y2h1bmtoZWFk"},"content":"eyJzZWdtZW50cyI6eyIwIjp7ImtleSI6IkB2MS9zZWcvZTdiM2VkZGUwNTYwYTM3MjQxZTkxMDJkNjA3ZWJjMTQiLCJzaGEyNTYiOls3NSwyMTgsMTMyLDExMywxNTgsMTcxLDQ1LDIxNCwyMjUsMjE5LDEwNywxNzYsMTczLDQ4LDI0MiwxNTMsMTIsMjMwLDExOCwyMjcsOTAsMTQxLDI0Nyw0LDExMSw1Nyw0OSwyMzcsOTQsMTg0LDg0LDk0XSwib3duZXIiOiJ2MSIsImNvdW50IjoxfX0sImNodW5rX2J5dGVzIjozMjc2OCwiY2h1bmtfY291bnQiOjEsImZvcm1hdCI6MiwiZ2VuIjoyLCJlcG9jaCI6MSwiaG9sZGVyIjoib2xkIiwicmVtb3RlX2xzbiI6Nywic3RhdGUiOiJhY3RpdmUifQ=="},"/swblock/chunks/v1/VOLUME":{"name":"VOLUME","attributes":{"file_size":139,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiY3JlYXRlIiwiY3JlYXRlZF9ucyI6MTAwMDAwMDAwMDAwMCwicGFyZW50IjpudWxsfQ=="},"/swblock/chunks/v1/snapnames/s1":{"name":"s1","attributes":{"file_size":127,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi03ZDc0ZTg5MWU0MTZhMmI5","swb.kind":"Y2h1bmtzbmFwbmFtZQ==","swb.req":"b2xkLXNuYXBzaG90"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImF0dGVtcHQiOiIyLTdkNzRlODkxZTQxNmEyYjkiLCJjcmVhdGVkX25zIjoxMDAwMDAwMDAwMDAwfQ=="},"/swblock/chunks/v1/snaps/s1/2-7d74e891e416a2b9":{"name":"2-7d74e891e416a2b9","attributes":{"file_size":583,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi03ZDc0ZTg5MWU0MTZhMmI5","swb.kind":"Y2h1bmtzbmFw","swb.req":"b2xkLXNuYXBzaG90","swb.snap.claims":"WyJ2Mi9vbGQtZm9yayJd","swb.snap.epoch":"MQ==","swb.snap.gen":"Mg==","swb.snap.lsn":"Nw==","swb.snap.state":"YWN0aXZl"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsImNyZWF0ZWRfYnkiOiIiLCJjb25zaXN0ZW5jeSI6ImNyYXNoIiwiaGVhZCI6eyJzZWdtZW50cyI6eyIwIjp7ImtleSI6IkB2MS9zZWcvZTdiM2VkZGUwNTYwYTM3MjQxZTkxMDJkNjA3ZWJjMTQiLCJzaGEyNTYiOls3NSwyMTgsMTMyLDExMywxNTgsMTcxLDQ1LDIxNCwyMjUsMjE5LDEwNywxNzYsMTczLDQ4LDI0MiwxNTMsMTIsMjMwLDExOCwyMjcsOTAsMTQxLDI0Nyw0LDExMSw1Nyw0OSwyMzcsOTQsMTg0LDg0LDk0XSwib3duZXIiOiJ2MSIsImNvdW50IjoxfX0sImNodW5rX2J5dGVzIjozMjc2OCwiY2h1bmtfY291bnQiOjEsImZvcm1hdCI6MiwiZ2VuIjoyLCJlcG9jaCI6MSwiaG9sZGVyIjoib2xkIiwicmVtb3RlX2xzbiI6Nywic3RhdGUiOiJhY3RpdmUifSwiZ2VvbWV0cnkiOnsibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OH0sInBhcmVudCI6bnVsbCwibGFiZWxzIjpudWxsLCJleHBpcmVzX2F0X25zIjowfQ=="},"/swblock/chunks/v2/VOLUME":{"name":"VOLUME","attributes":{"file_size":384,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU=","swb.req":"b2xkLWZvcms="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYyIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiZm9yayIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsInBhcmVudCI6eyJ2b2x1bWVfaWQiOiJ2MSIsInNuYXBzaG90IjoiczEiLCJnZW4iOjJ9LCJmb3JrIjp7InJlcXVlc3RfaWQiOiJvbGQtZm9yayIsInNvdXJjZSI6InYxIiwic25hcHNob3QiOiJzMSIsInNvdXJjZV9nZW4iOjIsImhlYWRfc2hhMjU2IjoiY2U3OTJiODQ3NWQ2OGY3OTcwNzNlMTA0Nzc1NTFlYmUzYzBlMTQ2NzdmNTNmYjIxMzZkYmM2MDQ4YmVlODU1MSIsInJlbW90ZV9sc24iOjcsImNodW5rX2NvdW50IjoxLCJxdWFsaWZpZWRfcmVmcyI6MX19"}},"Objects":{"seg/e7b3edde0560a37241e9102d607ebc14":"eyJmb3JtYXQiOjEsInJhbmdlIjowLCJjaHVua19ieXRlcyI6MzI3NjgsIm93bmVyIjoidjEiLCJjaHVua3MiOnsiMCI6eyJLZXkiOiJAdjEvbGVnYWN5LWRhdGEiLCJTSEEyNTYiOls5NSwyNDAsMTE2LDIyMSwxNzMsMTM2LDE4MywyNTIsMTgwLDUxLDE1NiwxODMsMTYzLDIzMCwxMzEsNjUsNiwyMywxNDYsMTM0LDE1OCw2NywxMDMsNTksNDUsMjMyLDgyLDkwLDExNyw3MSwxMDcsMjE2XX19fQ=="}}
|
||||
@@ -244,17 +244,38 @@ func headDeletingOrDeleted(h storage.ChunkHead) bool {
|
||||
// refuses to anyone else.
|
||||
func (c *Catalog) writeHead(ctx context.Context, root string, cur, next storage.ChunkHead) error {
|
||||
next.Gen = cur.Gen + 1
|
||||
var ids []string
|
||||
if next.Segments == nil && len(next.Chunks) != 0 {
|
||||
v, ok, err := c.ReadVolume(ctx, path.Base(root))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return errors.New("chunkstore: legacy delete needs VOLUME geometry")
|
||||
}
|
||||
next, ids, err = c.prepareLegacyHead(ctx, root, cur, next, v.Geometry)
|
||||
if err != nil {
|
||||
c.dropManifestIntents(ctx, root, ids)
|
||||
return err
|
||||
}
|
||||
}
|
||||
e, err := headEntry(next)
|
||||
if err != nil {
|
||||
c.dropManifestIntents(ctx, root, ids)
|
||||
return err
|
||||
}
|
||||
if cur.Gen == 0 {
|
||||
return c.f.CreateEntry(ctx, root, e, true)
|
||||
err = c.f.CreateEntry(ctx, root, e, true)
|
||||
} else {
|
||||
err = c.f.UpdateEntry(ctx, root, e, map[string][]byte{
|
||||
extGen: []byte(strconv.FormatUint(cur.Gen, 10)), extEpoch: []byte(strconv.FormatUint(cur.Epoch, 10)),
|
||||
})
|
||||
}
|
||||
return c.f.UpdateEntry(ctx, root, e, map[string][]byte{
|
||||
extGen: []byte(strconv.FormatUint(cur.Gen, 10)),
|
||||
extEpoch: []byte(strconv.FormatUint(cur.Epoch, 10)),
|
||||
})
|
||||
// Unknown publication retains protection; a later sweep can settle it.
|
||||
if err == nil || lostCondition(err) {
|
||||
c.dropManifestIntents(ctx, root, ids)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func lostCondition(err error) bool {
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package durable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type cumulativeReadStorage struct {
|
||||
storage.LogicalStorage
|
||||
remaining time.Duration
|
||||
}
|
||||
|
||||
func (s *cumulativeReadStorage) Read(uint32) ([]byte, error) {
|
||||
time.Sleep(2750 * time.Millisecond)
|
||||
return make([]byte, 4096), nil
|
||||
}
|
||||
func (s *cumulativeReadStorage) ReadContext(ctx context.Context, _ uint32) ([]byte, error) {
|
||||
deadline, _ := ctx.Deadline()
|
||||
s.remaining = time.Until(deadline)
|
||||
timer := time.NewTimer(2750 * time.Millisecond)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
return make([]byte, 4096), nil
|
||||
case <-ctx.Done():
|
||||
return nil, errors.Join(storage.ErrChunkHydrationPending, ctx.Err())
|
||||
}
|
||||
}
|
||||
func TestAttachAndHydrationUseOneArrivalDeadline(t *testing.T) {
|
||||
id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1}
|
||||
store := &cumulativeReadStorage{}
|
||||
b := &StorageBackend{storage: store, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}}
|
||||
b.setChunkAttachPending("pending")
|
||||
var once sync.Once
|
||||
var timer *time.Timer
|
||||
fired := make(chan struct{})
|
||||
b.testBeforeReadReadyWait = func() {
|
||||
once.Do(func() {
|
||||
timer = time.AfterFunc(2500*time.Millisecond, func() { defer close(fired); b.SetOperational(true, "attached") })
|
||||
})
|
||||
}
|
||||
defer func() {
|
||||
if timer != nil && !timer.Stop() {
|
||||
<-fired
|
||||
}
|
||||
}()
|
||||
start := time.Now()
|
||||
n, err := b.Read(context.Background(), 0, make([]byte, 4096))
|
||||
elapsed := time.Since(start)
|
||||
if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) || elapsed >= 5*time.Second || store.remaining > 2*time.Second {
|
||||
t.Fatalf("n=%d err=%v elapsed=%s hydration remaining=%s", n, err, elapsed, store.remaining)
|
||||
}
|
||||
t.Logf("combined attach+hydration: %s; remaining at hydration: %s", elapsed, store.remaining)
|
||||
}
|
||||
|
||||
// Both the command context and the capped attach context use this same
|
||||
// absolute deadline. Hold the registered wait until it has expired so
|
||||
// notification selection cannot accidentally make the oracle pass.
|
||||
type combinedReadProbe struct {
|
||||
storage.LogicalStorage
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (s *combinedReadProbe) Read(uint32) ([]byte, error) {
|
||||
s.calls.Add(1)
|
||||
return make([]byte, 4096), nil
|
||||
}
|
||||
func (s *combinedReadProbe) ReadContext(context.Context, uint32) ([]byte, error) {
|
||||
s.calls.Add(1)
|
||||
return make([]byte, 4096), nil
|
||||
}
|
||||
func TestCombinedRead_TiedAttachAndCommandDeadline(t *testing.T) {
|
||||
for _, state := range []string{"pending", "published", "fenced"} {
|
||||
t.Run(state, func(t *testing.T) {
|
||||
id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1}
|
||||
probe := &combinedReadProbe{}
|
||||
b := &StorageBackend{storage: probe, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}}
|
||||
b.setChunkAttachPending("pending")
|
||||
// Queue residence consumes three seconds of the original four-second
|
||||
// allowance. The attach child's three-second limit is capped by it.
|
||||
ctx, cancel := frontend.WithReadBudget(context.Background(), time.Now().Add(-3*time.Second))
|
||||
defer cancel()
|
||||
registered, resume, joined := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
var once, releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(resume) }) }
|
||||
b.testBeforeReadReadyWait = func() { once.Do(func() { close(registered) }); <-resume }
|
||||
result := make(chan error, 1)
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
release()
|
||||
select {
|
||||
case <-joined:
|
||||
case <-time.After(time.Second):
|
||||
t.Error("combined read did not settle")
|
||||
}
|
||||
})
|
||||
start := time.Now()
|
||||
go func() {
|
||||
defer close(joined)
|
||||
n, err := b.Read(ctx, 0, make([]byte, 4096))
|
||||
if n != 0 {
|
||||
t.Errorf("expired read returned %d bytes", n)
|
||||
}
|
||||
result <- err
|
||||
}()
|
||||
select {
|
||||
case <-registered:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("attach waiter not registered before deadline")
|
||||
}
|
||||
<-ctx.Done()
|
||||
switch state {
|
||||
case "published":
|
||||
b.SetOperational(true, "attached at expiry")
|
||||
case "fenced":
|
||||
b.mu.Lock()
|
||||
b.chunkFenced = func() bool { return true }
|
||||
b.mu.Unlock()
|
||||
b.SetOperational(false, "fenced at expiry")
|
||||
}
|
||||
release()
|
||||
select {
|
||||
case err := <-result:
|
||||
if state == "fenced" {
|
||||
if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) {
|
||||
t.Fatalf("deadline hid fence: %v", err)
|
||||
}
|
||||
} else if !errors.Is(err, frontend.ErrNotReady) || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) || errors.Is(err, storage.ErrChunkHydrationPending) {
|
||||
t.Fatalf("attach classification must win before hydration: %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("expired combined read did not return")
|
||||
}
|
||||
if probe.calls.Load() != 0 {
|
||||
t.Fatal("expired command entered storage")
|
||||
}
|
||||
if time.Since(start) >= 5*time.Second {
|
||||
t.Fatal("cooperative combined deadline exceeded command budget")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestCombinedRead_ExpiryAfterAdmissionKeepsAttachClassification(t *testing.T) {
|
||||
id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1}
|
||||
probe := &combinedReadProbe{}
|
||||
b := &StorageBackend{storage: probe, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}}
|
||||
b.SetOperational(true, "attached")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
b.testBeforeIOLock = func() { <-ctx.Done() }
|
||||
n, err := b.Read(ctx, 0, make([]byte, 4096))
|
||||
if n != 0 || probe.calls.Load() != 0 || !errors.Is(err, frontend.ErrNotReady) || !errors.Is(err, frontend.ErrBackendBusy) || errors.Is(err, storage.ErrChunkHydrationPending) {
|
||||
t.Fatalf("post-admission expiry: n=%d calls=%d err=%v", n, probe.calls.Load(), err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestDurableProvider_CheckpointPersistenceStatus(t *testing.T) {
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096,
|
||||
NumBlocks: 64, ChunkBlocks: 4, ChunkCaptureInterval: 0,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { p.Close() })
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
be, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := be.Write(context.Background(), 0, make([]byte, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := be.Sync(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
statuses := p.DurableStatuses()
|
||||
raw, err := json.Marshal(statuses)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wire []struct {
|
||||
CheckpointPersistence *struct {
|
||||
Successes uint64
|
||||
Refusals uint64
|
||||
Failures uint64
|
||||
CheckpointLSN uint64
|
||||
Advances uint64
|
||||
LastAdvance time.Time
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(raw, &wire); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(wire) == 1 && wire[0].CheckpointPersistence != nil && wire[0].CheckpointPersistence.Successes > 0 &&
|
||||
wire[0].CheckpointPersistence.CheckpointLSN > 0 && wire[0].CheckpointPersistence.Advances > 0 &&
|
||||
!wire[0].CheckpointPersistence.LastAdvance.IsZero() {
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("no checkpoint persist status in durable response: %s", raw)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -24,3 +24,8 @@ func SetTestDetachTrace(p *DurableProvider, f func(stage string, deadline time.T
|
||||
// SetTestBeforeIOLock runs f in the backend's admission, right before the I/O
|
||||
// lock (test-only).
|
||||
func SetTestBeforeIOLock(b frontend.Backend, f func()) { b.(*StorageBackend).testBeforeIOLock = f }
|
||||
|
||||
// SetTestBeforeAttachWait observes the first registered readiness wait.
|
||||
func SetTestBeforeAttachWait(b frontend.Backend, f func()) {
|
||||
b.(*StorageBackend).testBeforeReadReadyWait = f
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestDurableHydration_ConfiguredLimitsReachStatus(t *testing.T) {
|
||||
for _, configured := range []bool{false, true} {
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks}
|
||||
r := storage.NewMemChunkRemote()
|
||||
cfg.ChunkRemoteFor = func(string) (storage.ChunkRemote, error) { return r, nil }
|
||||
wantWorkers, wantDepth := 2, 64
|
||||
if configured {
|
||||
cfg.ChunkHydrationWorkers, cfg.ChunkHydrationQueueDepth = 3, 17
|
||||
wantWorkers, wantDepth = 3, 17
|
||||
}
|
||||
p, err := durable.NewDurableProvider(cfg, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
openRecovered(t, p)
|
||||
st := p.DurableStatuses()
|
||||
if len(st) != 1 || st[0].Chunk == nil {
|
||||
t.Fatalf("missing chunk status: %+v", st)
|
||||
}
|
||||
h := st[0].Chunk.Stats.Hydration
|
||||
if h.WorkerLimit != wantWorkers || h.QueueDepth != wantDepth {
|
||||
t.Fatalf("configured=%t hydration=%+v", configured, h)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type faultyHydrationRemote struct {
|
||||
storage.ChunkRemote
|
||||
fault error
|
||||
corrupt bool
|
||||
}
|
||||
|
||||
func (r *faultyHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
if r.fault != nil {
|
||||
return nil, r.fault
|
||||
}
|
||||
b, err := r.ChunkRemote.Get(ctx, key)
|
||||
if err == nil && r.corrupt && len(b) > 0 {
|
||||
b = append([]byte(nil), b...)
|
||||
b[0] ^= 0xff
|
||||
}
|
||||
return b, err
|
||||
}
|
||||
|
||||
func TestDurableHydration_NVMePreservesPhysicalAndHashErrors(t *testing.T) {
|
||||
for _, corrupt := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "joined physical", true: "hash"}[corrupt], func(t *testing.T) {
|
||||
r := &faultyHydrationRemote{ChunkRemote: seededRemote(t), corrupt: corrupt}
|
||||
if !corrupt {
|
||||
r.fault = errors.Join(context.DeadlineExceeded, errors.New("physical remote read failure"))
|
||||
}
|
||||
p := chunkProvider(t, t.TempDir(), r, v1View(), 0)
|
||||
openRecovered(t, p)
|
||||
b, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: b, BlockSize: 4096, VolumeSize: pcBlocks * 4096})
|
||||
res := h.Handle(context.Background(), nvme.IOCommand{Opcode: 2, NSID: 1, SLBA: 33, NLB: 1})
|
||||
if res.SC != nvme.SCInternalError || len(res.Data) != 0 {
|
||||
t.Fatalf("terminal hydration failure: %+v", res)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type pacedHydrationRemote struct {
|
||||
storage.ChunkRemote
|
||||
gets atomic.Int64
|
||||
second chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (r *pacedHydrationRemote) release() { r.once.Do(func() { close(r.second) }) }
|
||||
func (r *pacedHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
if r.gets.Add(1) == 1 {
|
||||
timer := time.NewTimer(120 * time.Millisecond)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
} else {
|
||||
select {
|
||||
case <-r.second:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
return r.ChunkRemote.Get(ctx, key)
|
||||
}
|
||||
|
||||
func TestDurableHydration_MultipleChunksShareOneDeadline(t *testing.T) {
|
||||
r := &pacedHydrationRemote{ChunkRemote: seededRemote(t), second: make(chan struct{})}
|
||||
p := chunkProvider(t, t.TempDir(), r, v1View(), 0)
|
||||
t.Cleanup(r.release)
|
||||
openRecovered(t, p)
|
||||
b, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 220*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
buf := make([]byte, (101-33)*4096)
|
||||
n, err := b.Read(ctx, 33*4096, buf)
|
||||
if !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) || n != (96-33)*4096 {
|
||||
t.Fatalf("shared deadline n=%d err=%v gets=%d", n, err, r.gets.Load())
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed >= 450*time.Millisecond {
|
||||
t.Fatalf("read budget renewed: %s", elapsed)
|
||||
}
|
||||
if !bytes.Equal(buf[:4096], block(0x33)) {
|
||||
t.Fatal("first chunk prefix changed")
|
||||
}
|
||||
r.release()
|
||||
ctx2, cancel2 := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel2()
|
||||
last := make([]byte, 4096)
|
||||
if n, err := b.Read(ctx2, 100*4096, last); n != 4096 || err != nil || !bytes.Equal(last, block(0x64)) {
|
||||
t.Fatalf("shared work after timeout: n=%d err=%v", n, err)
|
||||
}
|
||||
if r.gets.Load() != 2 {
|
||||
t.Fatalf("retry restarted shared fetch: %d", r.gets.Load())
|
||||
}
|
||||
}
|
||||
|
||||
type heldHydrationRemote struct {
|
||||
storage.ChunkRemote
|
||||
gate chan struct{}
|
||||
once sync.Once
|
||||
gets atomic.Int64
|
||||
entered chan struct{}
|
||||
}
|
||||
|
||||
func (r *heldHydrationRemote) release() { r.once.Do(func() { close(r.gate) }) }
|
||||
func (r *heldHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
r.gets.Add(1)
|
||||
if r.entered != nil {
|
||||
select {
|
||||
case r.entered <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-r.gate:
|
||||
return r.ChunkRemote.Get(ctx, key)
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurableHydration_HostRetriesJoinOwnedFetch(t *testing.T) {
|
||||
r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)}
|
||||
p := chunkProvider(t, t.TempDir(), r, v1View(), 0)
|
||||
t.Cleanup(r.release)
|
||||
openRecovered(t, p)
|
||||
b, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: b, BlockSize: 4096, VolumeSize: pcBlocks * 4096})
|
||||
// Start the hold only after the first actual Get. No setup time counts
|
||||
// toward the delay that the host's retry sequence must bridge.
|
||||
joined := make(chan struct{})
|
||||
stop := make(chan struct{})
|
||||
t.Cleanup(func() { close(stop); r.release(); <-joined })
|
||||
go func() {
|
||||
defer close(joined)
|
||||
select {
|
||||
case <-r.entered:
|
||||
case <-stop:
|
||||
return
|
||||
}
|
||||
timer := time.NewTimer(120 * time.Millisecond)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
r.release()
|
||||
case <-stop:
|
||||
}
|
||||
}()
|
||||
busy := 0
|
||||
for attempt := 0; attempt < 6; attempt++ {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
res := h.Handle(ctx, nvme.IOCommand{Opcode: 2, NSID: 1, SLBA: 33, NLB: 1})
|
||||
cancel()
|
||||
if res.SC == nvme.SCSuccess {
|
||||
if busy == 0 || !bytes.Equal(res.Data, block(0x33)) || r.gets.Load() != 1 {
|
||||
t.Fatalf("busy=%d Gets=%d bytes=%d", busy, r.gets.Load(), len(res.Data))
|
||||
}
|
||||
return
|
||||
}
|
||||
if res.SC != nvme.SCNamespaceNotReady || len(res.Data) != 0 {
|
||||
t.Fatalf("attempt %d: %+v", attempt, res)
|
||||
}
|
||||
busy++
|
||||
}
|
||||
t.Fatal("six immediate host attempts exhausted despite surviving shared fill")
|
||||
}
|
||||
|
||||
func TestDurableHydration_FenceWinsCallerExpiry(t *testing.T) {
|
||||
r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)}
|
||||
view := v1View()
|
||||
p := chunkProvider(t, t.TempDir(), r, view, 0)
|
||||
t.Cleanup(r.release)
|
||||
openRecovered(t, p)
|
||||
b, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
joined := make(chan struct{})
|
||||
result := make(chan error, 1)
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
r.release()
|
||||
select {
|
||||
case <-joined:
|
||||
case <-time.After(time.Second):
|
||||
t.Error("fenced hydration waiter not joined")
|
||||
}
|
||||
})
|
||||
go func() {
|
||||
defer close(joined)
|
||||
_, err := b.Read(ctx, 33*4096, make([]byte, 4096))
|
||||
result <- err
|
||||
}()
|
||||
select {
|
||||
case <-r.entered:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("cold read never reached Get")
|
||||
}
|
||||
view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 1}))
|
||||
cancel()
|
||||
select {
|
||||
case err := <-result:
|
||||
if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) {
|
||||
t.Fatalf("expiry hid fencing: %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("fenced waiter did not detach")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurableHydration_ReadAndRMWPreserveCallerBudget(t *testing.T) {
|
||||
for _, rmw := range []bool{false, true} {
|
||||
name := "read"
|
||||
if rmw {
|
||||
name = "rmw"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{})}
|
||||
p := chunkProvider(t, t.TempDir(), r, v1View(), 0)
|
||||
t.Cleanup(r.release)
|
||||
s, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.RecoverVolume(context.Background(), "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := s.NextLSN()
|
||||
fired := make(chan struct{})
|
||||
timer := time.AfterFunc(500*time.Millisecond, func() { defer close(fired); r.release() })
|
||||
t.Cleanup(func() {
|
||||
r.release()
|
||||
if !timer.Stop() {
|
||||
<-fired
|
||||
}
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
var n int
|
||||
if rmw {
|
||||
n, err = b.Write(ctx, 33*4096+1, []byte{0x74})
|
||||
} else {
|
||||
n, err = b.Read(ctx, 33*4096, make([]byte, 4096))
|
||||
}
|
||||
if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("request deadline: n=%d err=%v elapsed=%s", n, err, time.Since(start))
|
||||
}
|
||||
if time.Since(start) >= 350*time.Millisecond {
|
||||
t.Fatal("read/RMW did not share caller budget")
|
||||
}
|
||||
if s.NextLSN() != before {
|
||||
t.Fatal("refused RMW appended data")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurableHydration_RMWFenceWinsCallerExpiry(t *testing.T) {
|
||||
r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)}
|
||||
view := v1View()
|
||||
p := chunkProvider(t, t.TempDir(), r, view, 0)
|
||||
t.Cleanup(r.release)
|
||||
openRecovered(t, p)
|
||||
b, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := store.NextLSN()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
|
||||
defer cancel()
|
||||
joined := make(chan struct{})
|
||||
result := make(chan error, 1)
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
r.release()
|
||||
select {
|
||||
case <-joined:
|
||||
case <-time.After(time.Second):
|
||||
t.Error("fenced hydration waiter not joined")
|
||||
}
|
||||
})
|
||||
go func() {
|
||||
defer close(joined)
|
||||
n, err := b.Write(ctx, 33*4096+1, []byte{0x74})
|
||||
if n != 0 {
|
||||
t.Errorf("unexpected RMW prefix %d: %v", n, err)
|
||||
}
|
||||
result <- err
|
||||
}()
|
||||
select {
|
||||
case <-r.entered:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("cold read never reached Get")
|
||||
}
|
||||
view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 1}))
|
||||
select {
|
||||
case err := <-result:
|
||||
if store.NextLSN() != before {
|
||||
t.Fatal("fenced RMW appended data")
|
||||
}
|
||||
if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) {
|
||||
t.Fatalf("expiry hid fencing: %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("fenced waiter did not detach")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurableHydration_RMWFenceKeepsCommittedPrefix(t *testing.T) {
|
||||
r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)}
|
||||
view := v1View()
|
||||
p := chunkProvider(t, t.TempDir(), r, view, 0)
|
||||
t.Cleanup(r.release)
|
||||
openRecovered(t, p)
|
||||
b, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := store.NextLSN()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
|
||||
defer cancel()
|
||||
joined := make(chan struct{})
|
||||
result := make(chan error, 1)
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
r.release()
|
||||
select {
|
||||
case <-joined:
|
||||
case <-time.After(time.Second):
|
||||
t.Error("fenced hydration waiter not joined")
|
||||
}
|
||||
})
|
||||
go func() {
|
||||
defer close(joined)
|
||||
n, err := b.Write(ctx, 32*4096, bytes.Repeat([]byte{0x74}, 4097))
|
||||
if n != 4096 {
|
||||
t.Errorf("unexpected RMW prefix %d: %v", n, err)
|
||||
}
|
||||
result <- err
|
||||
}()
|
||||
select {
|
||||
case <-r.entered:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("cold read never reached Get")
|
||||
}
|
||||
view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 1}))
|
||||
select {
|
||||
case err := <-result:
|
||||
if store.NextLSN() != before+1 {
|
||||
t.Fatal("fenced RMW lost its exact committed prefix")
|
||||
}
|
||||
if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) {
|
||||
t.Fatalf("expiry hid fencing: %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("fenced waiter did not detach")
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,9 @@ type ProviderConfig struct {
|
||||
// ChunkReadMissTimeout bounds one remote fetch of an absent block.
|
||||
// Zero: the storage default.
|
||||
ChunkReadMissTimeout time.Duration
|
||||
// Per-volume hydration bounds; zero selects 2 workers and 64 distinct chunks.
|
||||
ChunkHydrationWorkers int
|
||||
ChunkHydrationQueueDepth int
|
||||
// ChunkCaptureInterval: an automatic cut is due once this long has
|
||||
// passed since the volume's last successful cut (of any kind). Zero
|
||||
// disables the timer.
|
||||
@@ -173,10 +176,12 @@ type ProviderConfig struct {
|
||||
// host's 30 s I/O timeout; a freeze past the 5 s target is logged as an
|
||||
// alarm. Cooperative: a syscall that never returns is not bounded.
|
||||
DetachFreezeTimeout time.Duration
|
||||
// ChunkDirtyThreshold is the bound on one cut's barrier copy, in
|
||||
// chunks. It never triggers a cut: the remote holds snapshots, and
|
||||
// cuts are published only by CaptureVolume, MakeVolumeRemoteDurable
|
||||
// (snapshot, detach) and the timer. Zero: unbounded.
|
||||
// ChunkDirtyThreshold is the number of candidate chunks above which
|
||||
// a cut pre-copies (stages) chunks before its barrier, in rounds of
|
||||
// this size; copy-before-write copies the rest outside the barrier.
|
||||
// It never triggers a cut: the remote holds snapshots, and cuts are
|
||||
// published only by CaptureVolume, MakeVolumeRemoteDurable
|
||||
// (snapshot, detach) and the timer. Zero: no pre-copy.
|
||||
ChunkDirtyThreshold int
|
||||
// ChunkUploadConcurrency bounds remote uploads; zero defaults to 8.
|
||||
ChunkUploadConcurrency int
|
||||
@@ -251,21 +256,22 @@ type volHandle struct {
|
||||
// handle. It intentionally exposes lineage and readiness facts without giving
|
||||
// callers a control surface.
|
||||
type VolumeStatus struct {
|
||||
VolumeID string
|
||||
Path string
|
||||
Impl string
|
||||
ReplicaID string
|
||||
Epoch uint64
|
||||
EndpointVersion uint64
|
||||
Latched bool
|
||||
Operational bool
|
||||
FrontierKnown bool
|
||||
DurableLSN uint64
|
||||
RetainedLSN uint64
|
||||
HeadLSN uint64
|
||||
Evidence string
|
||||
Closed bool
|
||||
WriteProfile WriteProfileStatus
|
||||
VolumeID string
|
||||
Path string
|
||||
Impl string
|
||||
ReplicaID string
|
||||
Epoch uint64
|
||||
EndpointVersion uint64
|
||||
Latched bool
|
||||
Operational bool
|
||||
FrontierKnown bool
|
||||
DurableLSN uint64
|
||||
RetainedLSN uint64
|
||||
HeadLSN uint64
|
||||
Evidence string
|
||||
Closed bool
|
||||
WriteProfile WriteProfileStatus
|
||||
CheckpointPersistence *storage.CheckpointPersistenceStatus `json:",omitempty"`
|
||||
// Chunk is the chunk layer's state and cut counters; walstore-chunk
|
||||
// volumes only.
|
||||
Chunk *ChunkStatus
|
||||
@@ -875,7 +881,7 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R
|
||||
// Recovered; I/O stays refused until the layer attaches under
|
||||
// the master's assignment (the authority wait flips it).
|
||||
report.Evidence += "; chunk layer awaiting master authority"
|
||||
h.backend.SetOperational(false, report.Evidence)
|
||||
h.backend.setChunkAttachPending(report.Evidence)
|
||||
return report, nil
|
||||
}
|
||||
if err := chunkFenced(volumeID, h); err != nil {
|
||||
|
||||
@@ -364,13 +364,16 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
|
||||
remote = &manifestBoundRemote{closeBoundRemote: bound, builder: builder}
|
||||
}
|
||||
cfg := storage.ChunkLayerConfig{
|
||||
ChunkBlocks: p.cfg.ChunkBlocks,
|
||||
Epoch: lin.epoch,
|
||||
Holder: holder,
|
||||
FreshFromHead: h.fresh,
|
||||
ReadMissTimeout: p.cfg.ChunkReadMissTimeout,
|
||||
BarrierBound: p.cfg.ChunkDirtyThreshold,
|
||||
UploadConcurrency: p.cfg.ChunkUploadConcurrency,
|
||||
ChunkBlocks: p.cfg.ChunkBlocks,
|
||||
RestoreChunkBytes: uint64(ws.BlockSize()) * uint64(p.cfg.ChunkBlocks),
|
||||
Epoch: lin.epoch,
|
||||
Holder: holder,
|
||||
FreshFromHead: h.fresh,
|
||||
ReadMissTimeout: p.cfg.ChunkReadMissTimeout,
|
||||
HydrationWorkers: p.cfg.ChunkHydrationWorkers,
|
||||
HydrationQueueDepth: p.cfg.ChunkHydrationQueueDepth,
|
||||
BarrierBound: p.cfg.ChunkDirtyThreshold,
|
||||
UploadConcurrency: p.cfg.ChunkUploadConcurrency,
|
||||
CaptureAllowed: func() error {
|
||||
cur := p.view.Projection()
|
||||
if !cur.Healthy || cur.VolumeID != volumeID || lin.volumeID != volumeID {
|
||||
|
||||
@@ -4,7 +4,9 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/recovery"
|
||||
@@ -15,6 +17,19 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Preserve the typed backend cause alongside the actual NVMe handler result.
|
||||
// This test submits writes synchronously, so lastError has one caller.
|
||||
type noFlushBackend struct {
|
||||
frontend.Backend
|
||||
lastError error
|
||||
}
|
||||
|
||||
func (b *noFlushBackend) Write(ctx context.Context, offset int64, data []byte) (int, error) {
|
||||
n, err := b.Backend.Write(ctx, offset, data)
|
||||
b.lastError = err
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Public provider + actual NVMe handler, file-backed v3 with the default
|
||||
// 64 MiB WAL. No injected I/O failures, private selector, or flusher control.
|
||||
func TestWALStoreChunkV3_NoClientFlushBurst(t *testing.T) {
|
||||
@@ -63,8 +78,10 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
|
||||
}
|
||||
syncsBefore := ws.WALSyncCount()
|
||||
var durations []time.Duration
|
||||
busyCount := 0
|
||||
t.Logf("before HEAD gen=%d remoteLSN=%d cp=%d next=%d retention=%d", before.Gen, before.RemoteLSN, ws.CheckpointLSN(), ws.NextLSN(), ws.RecoveryRetentionLSNs())
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: be, BlockSize: 4096, VolumeSize: 1 << 30})
|
||||
recorded := &noFlushBackend{Backend: be}
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: recorded, BlockSize: 4096, VolumeSize: 1 << 30})
|
||||
data := make([]byte, transfer)
|
||||
start := time.Now()
|
||||
for off := 0; off < total; off += transfer {
|
||||
@@ -73,14 +90,50 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
|
||||
binary.LittleEndian.PutUint64(data[i:i+8], uint64(off+i))
|
||||
}
|
||||
}
|
||||
writeStart := time.Now()
|
||||
r := h.Handle(ctx, nvme.IOCommand{Opcode: 0x01, NSID: 1, SLBA: uint64(off / 4096), NLB: transfer / 4096, Data: data})
|
||||
durations = append(durations, time.Since(writeStart))
|
||||
if r.AsError() != nil {
|
||||
dump := make([]byte, 2<<20)
|
||||
n := runtime.Stack(dump, true)
|
||||
t.Logf("TIMEOUT STACKS\n%s", dump[:n])
|
||||
t.Fatalf("NO FLUSH write bytes=%d elapsed=%v result=%+v cp=%d next=%d", off, time.Since(start), r, ws.CheckpointLSN(), ws.NextLSN())
|
||||
retryDeadline := time.Now().Add(30 * time.Second)
|
||||
cpBefore := ws.CheckpointLSN()
|
||||
retried := false
|
||||
for {
|
||||
writeStart := time.Now()
|
||||
r := h.Handle(ctx, nvme.IOCommand{Opcode: 0x01, NSID: 1, SLBA: uint64(off / 4096), NLB: transfer / 4096, Data: data})
|
||||
elapsed := time.Since(writeStart)
|
||||
durations = append(durations, elapsed)
|
||||
if elapsed >= 5*time.Second || time.Since(start) >= 2*time.Minute || time.Now().After(retryDeadline) {
|
||||
dump := make([]byte, 2<<20)
|
||||
n := runtime.Stack(dump, true)
|
||||
t.Logf("TIMEOUT STACKS\n%s", dump[:n])
|
||||
t.Fatalf("NO FLUSH exceeded wait bound bytes=%d attempt=%v total=%v busy=%d result=%+v cp=%d next=%d", off, elapsed, time.Since(start), busyCount, r, ws.CheckpointLSN(), ws.NextLSN())
|
||||
}
|
||||
if r.AsError() == nil {
|
||||
if retried {
|
||||
t.Logf("NO FLUSH resumed bytes=%d cp=%d->%d next=%d syncs=%d busy=%d", off, cpBefore, ws.CheckpointLSN(), ws.NextLSN(), ws.WALSyncCount(), busyCount)
|
||||
}
|
||||
break
|
||||
}
|
||||
if !errors.Is(recorded.lastError, frontend.ErrBackendBusy) || r.SCT != nvme.SCTGeneric || r.SC != nvme.SCNamespaceNotReady {
|
||||
t.Fatalf("NO FLUSH non-retryable write bytes=%d result=%+v cause=%v", off, r, recorded.lastError)
|
||||
}
|
||||
busyCount++
|
||||
retried = true
|
||||
t.Logf("NO FLUSH retry bytes=%d busy=%d attempt=%v cp=%d next=%d syncs=%d", off, busyCount, elapsed, ws.CheckpointLSN(), ws.NextLSN(), ws.WALSyncCount())
|
||||
if busyCount == 1 {
|
||||
passiveStart := time.Now()
|
||||
cpAtBusy := ws.CheckpointLSN()
|
||||
target := ws.NextLSN() - 1
|
||||
cpObserved := cpAtBusy
|
||||
// Getters only: no Write, Sync, NotifyUrgent or Close may
|
||||
// drive progress before the first retry.
|
||||
for cpAtBusy < target && cpObserved <= cpAtBusy && time.Since(passiveStart) < 10*time.Second {
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
cpObserved = ws.CheckpointLSN()
|
||||
}
|
||||
t.Logf("NO FLUSH passive bytes=%d wait=%v cpBefore=%d cpAtBusy=%d cpObserved=%d target=%d", off, time.Since(passiveStart), cpBefore, cpAtBusy, cpObserved, target)
|
||||
if time.Since(passiveStart) >= 10*time.Second || (cpAtBusy < target && cpObserved <= cpAtBusy) {
|
||||
t.Fatalf("NO FLUSH passive checkpoint did not advance without another write: bytes=%d cp=%d busy=%d", off, cpObserved, busyCount)
|
||||
}
|
||||
}
|
||||
// Retry the identical command; no caller Flush drives reclamation.
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
}
|
||||
if (off+transfer)%(16*1024*1024) == 0 {
|
||||
t.Logf("NO FLUSH progress bytes=%d elapsed=%v cp=%d next=%d", off+transfer, time.Since(start), ws.CheckpointLSN(), ws.NextLSN())
|
||||
@@ -109,7 +162,7 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
|
||||
if mode == storage.WModeStrict {
|
||||
fsyncs *= 2
|
||||
}
|
||||
t.Logf("COST mode=%d bytes=%d pressureBatches=%d internalFsyncsPerGiB=%.2f writeP99=%v max=%v", mode, total, batches, float64(fsyncs)/(float64(total)/(1<<30)), durations[(len(durations)-1)*99/100], durations[len(durations)-1])
|
||||
t.Logf("COST mode=%d bytes=%d busy=%d pressureBatches=%d internalFsyncsPerGiB=%.2f attemptP99=%v maxAttempt=%v", mode, total, busyCount, batches, float64(fsyncs)/(float64(total)/(1<<30)), durations[(len(durations)-1)*99/100], durations[len(durations)-1])
|
||||
after, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -155,7 +208,8 @@ func TestWALStoreChunkV3NoFlushWithActiveRF2CatchupPin(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ws.SetRecycleFloorSource(c)
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: be, BlockSize: 4096, VolumeSize: 1 << 30})
|
||||
recorded := &noFlushBackend{Backend: be}
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: recorded, BlockSize: 4096, VolumeSize: 1 << 30})
|
||||
data := bytes.Repeat([]byte{0x5a}, 128*1024)
|
||||
var stalled bool
|
||||
for off := 0; off < 80*1024*1024; off += len(data) {
|
||||
@@ -183,8 +237,29 @@ func TestWALStoreChunkV3NoFlushWithActiveRF2CatchupPin(t *testing.T) {
|
||||
t.Fatalf("retained catch-up records=%d err=%v", count, err)
|
||||
}
|
||||
c.EndSession("r2")
|
||||
r := h.Handle(ctx, nvme.IOCommand{Opcode: 1, NSID: 1, SLBA: 20000, NLB: 32, Data: data})
|
||||
if err := r.AsError(); err != nil {
|
||||
t.Fatalf("no-Flush progress after catch-up release: %v", err)
|
||||
retryDeadline := time.Now().Add(30 * time.Second)
|
||||
busy := 0
|
||||
for {
|
||||
start := time.Now()
|
||||
r := h.Handle(ctx, nvme.IOCommand{Opcode: 1, NSID: 1, SLBA: 20000, NLB: 32, Data: data})
|
||||
if time.Since(start) >= 5*time.Second || time.Now().After(retryDeadline) {
|
||||
t.Fatalf("released pin exceeded bound: attempt=%v busy=%d result=%+v", time.Since(start), busy, r)
|
||||
}
|
||||
if r.AsError() == nil {
|
||||
break
|
||||
}
|
||||
if !errors.Is(recorded.lastError, frontend.ErrBackendBusy) || r.SCT != nvme.SCTGeneric || r.SC != nvme.SCNamespaceNotReady {
|
||||
t.Fatalf("non-retryable released-pin write: %+v cause=%v", r, recorded.lastError)
|
||||
}
|
||||
busy++
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
}
|
||||
got := make([]byte, len(data))
|
||||
if n, err := be.Read(ctx, 20000*4096, got); err != nil || n != len(got) || !bytes.Equal(got, data) {
|
||||
t.Fatalf("released-pin readback n=%d err=%v", n, err)
|
||||
}
|
||||
if ws.CheckpointLSN() == 0 {
|
||||
t.Fatal("released pin did not permit checkpoint progress")
|
||||
}
|
||||
t.Logf("released pin completed: busy=%d checkpoint=%d", busy, ws.CheckpointLSN())
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package durable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
)
|
||||
|
||||
func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) {
|
||||
for _, mode := range []string{"close", "drain-then-close", "fence", "write-close"} {
|
||||
name := mode
|
||||
t.Run(name, func(t *testing.T) {
|
||||
// No storage is needed: this read must never pass the operational gate.
|
||||
b := &StorageBackend{waitAttachReady: true}
|
||||
b.opEvidence.Store("attachment pending")
|
||||
registered := make(chan struct{}, 1)
|
||||
resume := make(chan struct{})
|
||||
var once sync.Once
|
||||
release := func() { once.Do(func() { close(resume) }) }
|
||||
b.testBeforeReadReadyWait = func() {
|
||||
select {
|
||||
case registered <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
<-resume
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
joined := make(chan struct{})
|
||||
t.Cleanup(func() {
|
||||
release()
|
||||
_ = b.Close()
|
||||
select {
|
||||
case <-joined:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("pending read did not settle after release and Close")
|
||||
}
|
||||
})
|
||||
go func() {
|
||||
defer close(joined)
|
||||
var err error
|
||||
if mode == "write-close" {
|
||||
_, err = b.Write(context.Background(), 0, make([]byte, 4096))
|
||||
} else {
|
||||
_, err = b.Read(context.Background(), 0, make([]byte, 4096))
|
||||
}
|
||||
done <- err
|
||||
}()
|
||||
select {
|
||||
case <-registered:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("read did not register a readiness notification")
|
||||
}
|
||||
if mode == "drain-then-close" {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := b.StopIO(ctx, "attachment still pending"); err != nil {
|
||||
t.Fatalf("waiting read held I/O admission: %v", err)
|
||||
}
|
||||
}
|
||||
want := frontend.ErrBackendClosed
|
||||
if mode == "fence" {
|
||||
b.mu.Lock()
|
||||
b.chunkFenced = func() bool { return true }
|
||||
b.mu.Unlock()
|
||||
b.SetOperational(false, "fenced")
|
||||
want = frontend.ErrStalePrimary
|
||||
} else if err := b.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, want) {
|
||||
t.Fatalf("Close wake error=%v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Close did not wake registered read")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type readinessProjection frontend.Projection
|
||||
|
||||
func (p readinessProjection) Projection() frontend.Projection { return frontend.Projection(p) }
|
||||
|
||||
func TestAttachReadinessTimeoutPreservesStaleLineage(t *testing.T) {
|
||||
id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1}
|
||||
b := &StorageBackend{id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 2, EndpointVersion: 1, Healthy: true}}
|
||||
b.setChunkAttachPending("pending")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
b.testBeforeReadReadyWait = func() { b.SetOperational(true, "attached under another epoch"); cancel() }
|
||||
_, err := b.Read(ctx, 0, make([]byte, 4096))
|
||||
if !errors.Is(err, frontend.ErrStalePrimary) {
|
||||
t.Fatalf("timeout lost stale lineage: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachReadinessPublicationRetriesAdmission(t *testing.T) {
|
||||
id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1}
|
||||
b := &StorageBackend{id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}}
|
||||
b.setChunkAttachPending("pending")
|
||||
b.testAfterAttachRefusal = func() { b.SetOperational(true, "attached") }
|
||||
if _, err := b.Read(context.Background(), 0, nil); err != nil {
|
||||
t.Fatalf("readiness publication returned the old refusal: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -149,6 +149,9 @@ type StorageBackend struct {
|
||||
// testBeforeIOLock, test-only, runs in admit after the readiness check,
|
||||
// right before the I/O lock (an arrival handshake for queued I/O).
|
||||
testBeforeIOLock func()
|
||||
// Runs outside locks after a read registers its readiness notification.
|
||||
testBeforeReadReadyWait func()
|
||||
testAfterAttachRefusal func()
|
||||
|
||||
storage storage.LogicalStorage
|
||||
view frontend.ProjectionView
|
||||
@@ -159,8 +162,12 @@ type StorageBackend struct {
|
||||
// false; provider flips true after Recover() succeeds (T3b).
|
||||
// opEvidence is the reason reported when operational=false
|
||||
// (e.g., "awaiting recovery", "local epoch ahead of assignment").
|
||||
operational atomic.Bool
|
||||
opEvidence atomic.Value // string
|
||||
// Only a successfully recovered chunk volume awaiting attachment may wait.
|
||||
// waitAttachReady and readyChanged are protected by mu.
|
||||
waitAttachReady bool
|
||||
readyChanged chan struct{}
|
||||
operational atomic.Bool
|
||||
opEvidence atomic.Value // string
|
||||
|
||||
// ioMu is the I/O admission boundary: every Read, Write and Sync holds
|
||||
// its read side for the whole operation, gate included, so StopIO can
|
||||
@@ -288,6 +295,13 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
|
||||
if c, ok := b.storage.(interface{ HolesSuspected() uint64 }); ok {
|
||||
holes = c.HolesSuspected()
|
||||
}
|
||||
var checkpoint *storage.CheckpointPersistenceStatus
|
||||
if reporter, ok := b.storage.(interface {
|
||||
CheckpointPersistence() storage.CheckpointPersistenceStatus
|
||||
}); ok {
|
||||
snapshot := reporter.CheckpointPersistence()
|
||||
checkpoint = &snapshot
|
||||
}
|
||||
writeProfile := b.WriteProfile()
|
||||
if instrumented, ok := b.storage.(storage.WriteInstrumented); ok {
|
||||
storageProfile := instrumented.WriteInstrumentation()
|
||||
@@ -316,23 +330,24 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
|
||||
writeProfile.DirtyMapUpdateDurationNanos = storageProfile.DirtyMapUpdateDurationNanos
|
||||
}
|
||||
return VolumeStatus{
|
||||
Warnings: warnings,
|
||||
HolesSuspected: holes,
|
||||
VolumeID: volumeID,
|
||||
Path: path,
|
||||
Impl: impl,
|
||||
ReplicaID: id.ReplicaID,
|
||||
Epoch: id.Epoch,
|
||||
EndpointVersion: id.EndpointVersion,
|
||||
Latched: id.Epoch > 0 && id.EndpointVersion > 0,
|
||||
Operational: b.operational.Load(),
|
||||
FrontierKnown: true,
|
||||
DurableLSN: durableLSN,
|
||||
RetainedLSN: retainedLSN,
|
||||
HeadLSN: headLSN,
|
||||
Evidence: evidence,
|
||||
Closed: closed,
|
||||
WriteProfile: writeProfile,
|
||||
Warnings: warnings,
|
||||
HolesSuspected: holes,
|
||||
VolumeID: volumeID,
|
||||
Path: path,
|
||||
Impl: impl,
|
||||
ReplicaID: id.ReplicaID,
|
||||
Epoch: id.Epoch,
|
||||
EndpointVersion: id.EndpointVersion,
|
||||
Latched: id.Epoch > 0 && id.EndpointVersion > 0,
|
||||
Operational: b.operational.Load(),
|
||||
FrontierKnown: true,
|
||||
DurableLSN: durableLSN,
|
||||
RetainedLSN: retainedLSN,
|
||||
HeadLSN: headLSN,
|
||||
Evidence: evidence,
|
||||
Closed: closed,
|
||||
WriteProfile: writeProfile,
|
||||
CheckpointPersistence: checkpoint,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -343,6 +358,7 @@ func (b *StorageBackend) Close() error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.closed = true
|
||||
b.notifyReadReadyLocked()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -371,12 +387,14 @@ func (b *StorageBackend) SetWriteObserver(obs WriteObserver) error {
|
||||
err = fmt.Errorf("durable: write observer not installed: ship LSN: %w", err)
|
||||
b.mu.Lock()
|
||||
b.observerErr = err
|
||||
b.notifyReadReadyLocked()
|
||||
b.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
}
|
||||
b.mu.Lock()
|
||||
b.observer, b.observerErr = obs, nil
|
||||
b.notifyReadReadyLocked()
|
||||
b.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
@@ -401,6 +419,7 @@ func (b *StorageBackend) seedAndRebase(seed func() error) error {
|
||||
err = fmt.Errorf("durable: write observer ship LSN after the frontier seed: %w", err)
|
||||
b.mu.Lock()
|
||||
b.observerErr = err
|
||||
b.notifyReadReadyLocked()
|
||||
b.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
@@ -444,8 +463,12 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) {
|
||||
evidence = "not operational"
|
||||
}
|
||||
}
|
||||
b.mu.Lock()
|
||||
b.opEvidence.Store(evidence)
|
||||
b.operational.Store(ok)
|
||||
b.waitAttachReady = false
|
||||
b.notifyReadReadyLocked()
|
||||
b.mu.Unlock()
|
||||
}
|
||||
|
||||
// StopIO makes the backend refuse every new Read, Write and Sync with
|
||||
@@ -531,7 +554,9 @@ func (b *StorageBackend) Sync(ctx context.Context) error {
|
||||
// Read copies up to len(p) bytes starting at offset. Reads past
|
||||
// end-of-volume return zero bytes (no error). Every read is gated.
|
||||
func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, error) {
|
||||
release, err := b.admit()
|
||||
ctx, cancel := frontend.WithReadBudget(ctx, time.Time{})
|
||||
defer cancel()
|
||||
release, err := b.admitAfterAttach(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -539,7 +564,104 @@ func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int,
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
return b.readBytes(offset, p)
|
||||
if ctx.Err() != nil {
|
||||
return 0, b.attachReadyTimeout(ctx.Err())
|
||||
}
|
||||
n, err := b.readBytes(ctx, offset, p)
|
||||
if hydrationPendingOnly(err) {
|
||||
if gateErr := b.gate(); gateErr != nil {
|
||||
return 0, gateErr
|
||||
}
|
||||
return n, fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// setChunkAttachPending is used only after successful local recovery.
|
||||
func (b *StorageBackend) setChunkAttachPending(evidence string) {
|
||||
b.mu.Lock()
|
||||
b.opEvidence.Store(evidence)
|
||||
b.operational.Store(false)
|
||||
b.waitAttachReady = true
|
||||
b.notifyReadReadyLocked()
|
||||
b.mu.Unlock()
|
||||
}
|
||||
|
||||
func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) {
|
||||
release, err := b.admit()
|
||||
if !errors.Is(err, frontend.ErrNotReady) {
|
||||
return release, err
|
||||
}
|
||||
if hook := b.testAfterAttachRefusal; hook != nil {
|
||||
hook()
|
||||
}
|
||||
b.mu.Lock()
|
||||
pending := b.waitAttachReady
|
||||
b.mu.Unlock()
|
||||
if !pending {
|
||||
// Readiness may have published after the initial refusal.
|
||||
return b.admit()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
return b.awaitAttachAdmission(ctx)
|
||||
}
|
||||
|
||||
// notifyReadReadyLocked wakes waiting I/O without making them hold ioMu while
|
||||
// the provider is attaching or draining the backend. Caller holds mu.
|
||||
func (b *StorageBackend) notifyReadReadyLocked() {
|
||||
if b.readyChanged != nil {
|
||||
close(b.readyChanged)
|
||||
b.readyChanged = nil
|
||||
}
|
||||
}
|
||||
|
||||
// awaitAttachAdmission waits only after a gate refusal, before any storage I/O.
|
||||
// The three-second readiness allowance is capped by an earlier caller deadline.
|
||||
func (b *StorageBackend) awaitAttachAdmission(ctx context.Context) (func(), error) {
|
||||
for {
|
||||
b.mu.Lock()
|
||||
if b.readyChanged == nil {
|
||||
b.readyChanged = make(chan struct{})
|
||||
}
|
||||
changed := b.readyChanged
|
||||
terminal := b.closed || b.observerErr != nil || !b.waitAttachReady
|
||||
b.mu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, b.attachReadyTimeout(err)
|
||||
}
|
||||
release, err := b.admit()
|
||||
if err == nil {
|
||||
if cause := ctx.Err(); cause != nil {
|
||||
release()
|
||||
return nil, b.attachReadyTimeout(cause)
|
||||
}
|
||||
return release, nil
|
||||
}
|
||||
if !errors.Is(err, frontend.ErrNotReady) || terminal || b.operational.Load() {
|
||||
return release, err
|
||||
}
|
||||
if hook := b.testBeforeReadReadyWait; hook != nil {
|
||||
hook()
|
||||
}
|
||||
select {
|
||||
case <-changed:
|
||||
case <-ctx.Done():
|
||||
return nil, b.attachReadyTimeout(ctx.Err())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *StorageBackend) attachReadyTimeout(cause error) error {
|
||||
// A concurrent Close, fence or observer failure must retain its gate error.
|
||||
err := b.gate()
|
||||
b.mu.Lock()
|
||||
observerFailed := b.observerErr != nil
|
||||
b.mu.Unlock()
|
||||
if err != nil && (!errors.Is(err, frontend.ErrNotReady) || observerFailed) {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w: %w: chunk attachment readiness: %w", frontend.ErrNotReady, frontend.ErrBackendBusy, cause)
|
||||
}
|
||||
|
||||
// Write persists up to len(p) bytes at offset. Partial-block
|
||||
@@ -547,9 +669,11 @@ func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int,
|
||||
// overlay the partial range, write the full block back.
|
||||
// Every write is gated.
|
||||
func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int, error) {
|
||||
ctx, cancel := frontend.WithWriteBudget(ctx, time.Time{})
|
||||
defer cancel()
|
||||
iolatency.BackendEnter(ctx)
|
||||
defer iolatency.BackendExit(ctx)
|
||||
release, err := b.admit()
|
||||
release, err := b.admitAfterAttach(ctx)
|
||||
if err != nil {
|
||||
log.Printf("durable: StorageBackend.Write gate-rejected offset=%d: %v", offset, err)
|
||||
return 0, err
|
||||
@@ -558,10 +682,18 @@ func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return 0, b.attachReadyTimeout(ctx.Err())
|
||||
}
|
||||
b.profile.recordBackendWriteRequest(len(p))
|
||||
start := time.Now()
|
||||
n, err := b.writeBytes(ctx, offset, p)
|
||||
if errors.Is(err, storage.ErrWALPressureTimeout) {
|
||||
if hydrationPendingOnly(err) {
|
||||
if gateErr := b.gate(); gateErr != nil {
|
||||
err = gateErr
|
||||
}
|
||||
}
|
||||
if errors.Is(err, storage.ErrWALPressureTimeout) || hydrationPendingOnly(err) {
|
||||
err = fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err)
|
||||
}
|
||||
if n > 0 {
|
||||
@@ -654,6 +786,54 @@ func (b *StorageBackend) lineageCheck() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// readStorageBlock shares the request deadline across blocks and partial-write
|
||||
// RMW. Legacy engines may still perform contextless local I/O (#221).
|
||||
func (b *StorageBackend) readStorageBlock(ctx context.Context, lba uint32) ([]byte, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("%w: %w", storage.ErrChunkHydrationPending, err)
|
||||
}
|
||||
var data []byte
|
||||
var err error
|
||||
if r, ok := b.storage.(storage.ContextReader); ok {
|
||||
data, err = r.ReadContext(ctx, lba)
|
||||
} else {
|
||||
data, err = b.storage.Read(lba)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} // a known substrate failure wins expiry
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("%w: %w", storage.ErrChunkHydrationPending, err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func hydrationPendingOnly(err error) bool {
|
||||
return errors.Is(err, storage.ErrChunkHydrationPending) && hydrationPendingCauseOnly(err)
|
||||
}
|
||||
|
||||
func hydrationPendingCauseOnly(err error) bool {
|
||||
if err == storage.ErrChunkHydrationPending || err == context.DeadlineExceeded || err == context.Canceled {
|
||||
return true
|
||||
}
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if j, ok := err.(interface{ Unwrap() []error }); ok {
|
||||
causes := j.Unwrap()
|
||||
if len(causes) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, cause := range causes {
|
||||
if !hydrationPendingCauseOnly(cause) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return hydrationPendingCauseOnly(errors.Unwrap(err))
|
||||
}
|
||||
|
||||
// readBytes performs the byte-range → LBA-range fanout for Read.
|
||||
// Reads block-at-a-time, copying the sub-slice covered by the
|
||||
// current byte range. Handles three cases:
|
||||
@@ -661,7 +841,7 @@ func (b *StorageBackend) lineageCheck() error {
|
||||
// - offset aligned, len >= block: copy full block, advance.
|
||||
// - offset misaligned: copy tail of first block only.
|
||||
// - final block, len < available: copy prefix only.
|
||||
func (b *StorageBackend) readBytes(offset int64, p []byte) (int, error) {
|
||||
func (b *StorageBackend) readBytes(ctx context.Context, offset int64, p []byte) (int, error) {
|
||||
if offset < 0 {
|
||||
return 0, errInvalidOffset
|
||||
}
|
||||
@@ -671,7 +851,7 @@ func (b *StorageBackend) readBytes(offset int64, p []byte) (int, error) {
|
||||
pos := offset
|
||||
for len(buf) > 0 {
|
||||
lba := uint32(pos / bs)
|
||||
block, err := b.storage.Read(lba)
|
||||
block, err := b.readStorageBlock(ctx, lba)
|
||||
if err != nil {
|
||||
return total, fmt.Errorf("durable: read lba=%d: %w", lba, err)
|
||||
}
|
||||
@@ -748,7 +928,7 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte)
|
||||
block = buf[:chunkLen]
|
||||
} else {
|
||||
// Partial-block: RMW.
|
||||
existing, err := b.storage.Read(lba)
|
||||
existing, err := b.readStorageBlock(ctx, lba)
|
||||
if err != nil {
|
||||
writeLock.Unlock()
|
||||
return total, fmt.Errorf("durable: RMW read lba=%d: %w", lba, err)
|
||||
@@ -762,7 +942,13 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte)
|
||||
return total, fmt.Errorf("%w: no write observer installed", ErrReplicationAckUnavailable)
|
||||
}
|
||||
|
||||
lsn, err := b.storage.Write(lba, block)
|
||||
var lsn uint64
|
||||
var err error
|
||||
if writer, ok := b.storage.(storage.ContextWriter); ok {
|
||||
lsn, err = writer.WriteContext(ctx, lba, block)
|
||||
} else if err = expiredCommand(ctx); err == nil {
|
||||
lsn, err = b.storage.Write(lba, block)
|
||||
}
|
||||
writeLock.Unlock()
|
||||
if err != nil {
|
||||
return total, fmt.Errorf("durable: write lba=%d: %w", lba, err)
|
||||
@@ -798,7 +984,13 @@ func (b *StorageBackend) writeFullBlockBatch(ctx context.Context, startLBA uint3
|
||||
blocks[i] = p[i*bs : (i+1)*bs]
|
||||
}
|
||||
unlock := b.lockLBARange(startLBA, blockCount)
|
||||
lsns, err := batcher.WriteBatch(startLBA, blocks)
|
||||
var lsns []uint64
|
||||
var err error
|
||||
if writer, ok := batcher.(storage.ContextWriteBatcher); ok {
|
||||
lsns, err = writer.WriteBatchContext(ctx, startLBA, blocks)
|
||||
} else if err = expiredCommand(ctx); err == nil {
|
||||
lsns, err = batcher.WriteBatch(startLBA, blocks)
|
||||
}
|
||||
unlock()
|
||||
if len(lsns) > 0 {
|
||||
b.profile.recordBackendStorageWrite(len(lsns), true)
|
||||
@@ -809,14 +1001,14 @@ func (b *StorageBackend) writeFullBlockBatch(ctx context.Context, startLBA uint3
|
||||
log.Printf("durable: replication batch fan-out failed lba=%d blocks=%d: %v",
|
||||
startLBA, len(lsns), obsErr)
|
||||
if policy == WriteAckRequireObserverAck {
|
||||
return len(lsns) * bs, fmt.Errorf("%w: %w", ErrReplicationAckUnavailable, obsErr)
|
||||
return len(lsns) * bs, replicationWriteError(ctx, withStorageCause(startLBA, blockCount, err, obsErr))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i, lsn := range lsns {
|
||||
block := blocks[i]
|
||||
lba := startLBA + uint32(i)
|
||||
if obsErr := b.observeWrite(ctx, lba, lsn, block, obs, policy); obsErr != nil {
|
||||
if obsErr := b.observeWriteCause(ctx, lba, lsn, block, obs, policy, withStorageCause(startLBA, blockCount, err, nil)); obsErr != nil {
|
||||
return (i + 1) * bs, obsErr
|
||||
}
|
||||
}
|
||||
@@ -852,6 +1044,13 @@ func (b *StorageBackend) lockLBARange(startLBA uint32, blockCount int) func() {
|
||||
}
|
||||
|
||||
func (b *StorageBackend) observeWrite(ctx context.Context, lba uint32, lsn uint64, block []byte, obs WriteObserver, policy WriteAckPolicy) error {
|
||||
return b.observeWriteCause(ctx, lba, lsn, block, obs, policy, nil)
|
||||
}
|
||||
|
||||
// observeWriteCause is observeWrite with the storage failure of the same
|
||||
// command (nil if none): a required observer's error is classified together
|
||||
// with it, so a physical storage fault is never reclassified as retryable.
|
||||
func (b *StorageBackend) observeWriteCause(ctx context.Context, lba uint32, lsn uint64, block []byte, obs WriteObserver, policy WriteAckPolicy, storageErr error) error {
|
||||
// Replication fan-out (T4a-6 hook). Error is logged best-effort
|
||||
// unless the ack policy requires observer acknowledgement.
|
||||
if obs == nil {
|
||||
@@ -861,12 +1060,53 @@ func (b *StorageBackend) observeWrite(ctx context.Context, lba uint32, lsn uint6
|
||||
log.Printf("durable: replication fan-out failed lba=%d lsn=%d: %v",
|
||||
lba, lsn, werr)
|
||||
if policy == WriteAckRequireObserverAck {
|
||||
return fmt.Errorf("%w: %w", ErrReplicationAckUnavailable, werr)
|
||||
if storageErr != nil {
|
||||
werr = errors.Join(storageErr, werr)
|
||||
}
|
||||
return replicationWriteError(ctx, werr)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// withStorageCause joins a batch's storage error (nil if none) with an
|
||||
// observer error, so the classifier sees the complete error set (#252):
|
||||
// a committed prefix may come back together with a physical failure.
|
||||
func withStorageCause(startLBA uint32, blockCount int, storageErr, obsErr error) error {
|
||||
if storageErr == nil {
|
||||
return obsErr
|
||||
}
|
||||
se := fmt.Errorf("durable: write batch lba=%d blocks=%d: %w", startLBA, blockCount, storageErr)
|
||||
if obsErr == nil {
|
||||
return se
|
||||
}
|
||||
return errors.Join(se, obsErr)
|
||||
}
|
||||
|
||||
// Classify the observer cause before adding the acknowledgement sentinel;
|
||||
// otherwise that sentinel would obscure a pure caller deadline at the target.
|
||||
func replicationWriteError(ctx context.Context, err error) error {
|
||||
wrapped := fmt.Errorf("%w: %w", ErrReplicationAckUnavailable, err)
|
||||
if frontend.IsWriteDeadline(ctx, err) {
|
||||
return fmt.Errorf("%w: %w", frontend.ErrBackendBusy, wrapped)
|
||||
}
|
||||
return wrapped
|
||||
}
|
||||
|
||||
// Compile-time check that StorageBackend satisfies frontend.Backend.
|
||||
// Catches interface drift at build time rather than runtime.
|
||||
var _ frontend.Backend = (*StorageBackend)(nil)
|
||||
|
||||
// expiredCommand refuses a fresh mutation through a contextless storage
|
||||
// fallback once the command is already expired or cancelled (#252); a pure
|
||||
// deadline is retryable busy, as on the context-aware path.
|
||||
func expiredCommand(ctx context.Context) error {
|
||||
err := ctx.Err()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if frontend.IsWriteDeadline(ctx, err) {
|
||||
return fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// External observers see the committed takeover HEAD while attachment is
|
||||
// held in the provider-owned worker, without a separate test goroutine.
|
||||
type heldTakeoverClaim struct {
|
||||
storage.ChunkRemote
|
||||
claimed chan struct{}
|
||||
release chan struct{}
|
||||
once, releaseOnce sync.Once
|
||||
holdFor time.Duration
|
||||
readRegistered chan struct{}
|
||||
}
|
||||
|
||||
func (r *heldTakeoverClaim) unblock() { r.releaseOnce.Do(func() { close(r.release) }) }
|
||||
func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) {
|
||||
gen, err := r.ChunkRemote.CASHead(ctx, expected, next)
|
||||
if err != nil || next.Epoch != 4 {
|
||||
return gen, err
|
||||
}
|
||||
r.once.Do(func() { close(r.claimed) })
|
||||
var expired <-chan time.Time
|
||||
if r.holdFor > 0 {
|
||||
select {
|
||||
case <-r.readRegistered:
|
||||
case <-r.release:
|
||||
return gen, nil
|
||||
case <-ctx.Done():
|
||||
return gen, ctx.Err()
|
||||
}
|
||||
timer := time.NewTimer(r.holdFor)
|
||||
defer timer.Stop()
|
||||
expired = timer.C
|
||||
}
|
||||
select {
|
||||
case <-r.release:
|
||||
return gen, nil
|
||||
case <-expired:
|
||||
return gen, nil
|
||||
case <-ctx.Done():
|
||||
return gen, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func pendingTakeoverRead(t *testing.T, hold time.Duration) (*durable.DurableProvider, frontend.Backend, *nvme.IOHandler) {
|
||||
t.Helper()
|
||||
remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{}), holdFor: hold, readRegistered: make(chan struct{})}
|
||||
view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"})
|
||||
p := chunkProvider(t, t.TempDir(), remote, view, 0)
|
||||
// Registered after provider cleanup, so release precedes its worker join.
|
||||
t.Cleanup(remote.unblock)
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2}))
|
||||
select {
|
||||
case <-remote.claimed:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("takeover CAS never became visible")
|
||||
}
|
||||
head, err := remote.GetHead(context.Background())
|
||||
if err != nil || head.Epoch != 4 || head.Holder != "r1" {
|
||||
t.Fatalf("takeover HEAD: %+v, %v", head, err)
|
||||
}
|
||||
backend, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var firstWait sync.Once
|
||||
durable.SetTestBeforeAttachWait(backend, func() { firstWait.Do(func() { close(remote.readRegistered) }) })
|
||||
handler := nvme.NewIOHandler(nvme.HandlerConfig{Backend: backend, BlockSize: 4096, VolumeSize: pcBlocks * 4096, NSID: 1})
|
||||
return p, backend, handler
|
||||
}
|
||||
|
||||
// Model Linux max_retries=5 and CRD=0: at most six attempts, no sleeps.
|
||||
// A status-only fix exhausts them during attachment and becomes guest EIO.
|
||||
func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) {
|
||||
_, _, handler := pendingTakeoverRead(t, 2500*time.Millisecond)
|
||||
command := nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1}
|
||||
start := time.Now()
|
||||
for attempt := 0; attempt <= 5; attempt++ {
|
||||
result := handler.Handle(context.Background(), command)
|
||||
if result.AsError() == nil {
|
||||
if !bytes.Equal(result.Data, block(0x33)) {
|
||||
t.Fatal("guest read returned incorrect HEAD bytes")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed >= 5*time.Second {
|
||||
t.Fatalf("guest read took %s", elapsed)
|
||||
}
|
||||
t.Logf("guest read succeeded on attempt%d after%s (max5 immediate retries)", attempt+1, time.Since(start))
|
||||
return
|
||||
}
|
||||
if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady {
|
||||
t.Fatalf("guest read terminal status: %v", result.AsError())
|
||||
}
|
||||
}
|
||||
t.Fatal("guest EIO: all six immediate attempts exhausted before chunk attach")
|
||||
}
|
||||
|
||||
func TestWALStoreChunk_PendingReadWaitIsBounded(t *testing.T) {
|
||||
_, _, handler := pendingTakeoverRead(t, 0)
|
||||
start := time.Now()
|
||||
result := handler.Handle(context.Background(), nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1})
|
||||
elapsed := time.Since(start)
|
||||
if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 {
|
||||
t.Fatalf("pending read result: %+v", result)
|
||||
}
|
||||
if elapsed < 2500*time.Millisecond || elapsed >= 5*time.Second {
|
||||
t.Fatalf("pending read wait=%s; want bounded readiness wait below5s", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreChunk_PendingReadHonoursEarlierDeadline(t *testing.T) {
|
||||
_, backend, _ := pendingTakeoverRead(t, 0)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
n, err := backend.Read(ctx, 33*4096, make([]byte, 4096))
|
||||
if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("deadline read: n=%d err=%v", n, err)
|
||||
}
|
||||
if time.Since(start) >= time.Second {
|
||||
t.Fatal("read ignored earlier deadline")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreChunk_TakeoverWriteWaitsForAttach(t *testing.T) {
|
||||
_, backend, _ := pendingTakeoverRead(t, 2500*time.Millisecond)
|
||||
start := time.Now()
|
||||
n, err := backend.Write(context.Background(), 33*4096, block(0x74))
|
||||
if err != nil || n != 4096 {
|
||||
t.Fatalf("pending write: n=%d err=%v", n, err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed >= 5*time.Second {
|
||||
t.Fatalf("write waited %s", elapsed)
|
||||
}
|
||||
got := make([]byte, 4096)
|
||||
if n, err := backend.Read(context.Background(), 33*4096, got); err != nil || n != 4096 || !bytes.Equal(got, block(0x74)) {
|
||||
t.Fatalf("attached write readback: n=%d err=%v", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreChunk_PendingWriteHonoursEarlierDeadline(t *testing.T) {
|
||||
_, backend, _ := pendingTakeoverRead(t, 0)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond)
|
||||
defer cancel()
|
||||
n, err := backend.Write(ctx, 33*4096, block(0x74))
|
||||
if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("pending write deadline: n=%d err=%v", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreChunk_PendingAttachBeyondHostRetryBudget(t *testing.T) {
|
||||
_, _, handler := pendingTakeoverRead(t, 0)
|
||||
for attempt := 0; attempt <= 5; attempt++ {
|
||||
start := time.Now()
|
||||
result := handler.Handle(context.Background(), nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1})
|
||||
if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 {
|
||||
t.Fatalf("attempt%d exposed data or terminal status: %+v", attempt, result)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed < 2500*time.Millisecond || elapsed >= 5*time.Second {
|
||||
t.Fatalf("attempt%d wait=%s", attempt, elapsed)
|
||||
}
|
||||
}
|
||||
// A permanently unavailable backend still exhausts a finite host retry policy;
|
||||
// this control promises retryable completions and no bytes, not infinite availability.
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// partialFaultStore commits the first block of a batch and returns that prefix
|
||||
// together with a physical error (the shape parallelwal and smartwal return),
|
||||
// after the command's deadline has passed.
|
||||
type partialFaultStore struct {
|
||||
storage.LogicalStorage
|
||||
fault error
|
||||
}
|
||||
|
||||
func (s *partialFaultStore) WriteBatch(lba uint32, blocks [][]byte) ([]uint64, error) {
|
||||
lsn, err := s.LogicalStorage.Write(lba, blocks[0])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []uint64{lsn}, s.fault
|
||||
}
|
||||
func (s *partialFaultStore) WriteBatchContext(ctx context.Context, lba uint32, blocks [][]byte) ([]uint64, error) {
|
||||
<-ctx.Done()
|
||||
return s.WriteBatch(lba, blocks)
|
||||
}
|
||||
|
||||
// #252 P1-3: a committed prefix plus a physical storage error, then a required
|
||||
// batch observer that reports a pure expired deadline: the physical fault must
|
||||
// stay in the error (terminal), never be reclassified as retryable busy.
|
||||
func TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline(t *testing.T) {
|
||||
for _, batchObserver := range []bool{true, false} {
|
||||
name := map[bool]string{true: "batch-observer", false: "per-block-observer"}[batchObserver]
|
||||
t.Run(name, func(t *testing.T) {
|
||||
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
|
||||
physical := errors.New("injected physical WAL append failure")
|
||||
s := &partialFaultStore{LogicalStorage: storage.NewBlockStore(8, 4096), fault: physical}
|
||||
b := durable.NewStorageBackend(s, newStubView(healthyProj(id)), id)
|
||||
b.SetOperational(true, "test")
|
||||
deadlineOnly := func(ctx context.Context) error { return ctx.Err() }
|
||||
obs := writeObserverFunc{observe: func(ctx context.Context, _ uint32, _ uint64, _ []byte) error { return deadlineOnly(ctx) }}
|
||||
if batchObserver {
|
||||
b.SetWriteObserver(batchWriteObserverFunc{writeObserverFunc: obs, observeBatch: func(ctx context.Context, _ uint32, _ []uint64, _ [][]byte) error { return deadlineOnly(ctx) }})
|
||||
} else {
|
||||
b.SetWriteObserver(obs)
|
||||
b.SetWriteAckPolicy(durable.WriteAckBestEffort) // the per-block path is taken without a batch observer only off the required policy
|
||||
}
|
||||
if batchObserver {
|
||||
b.SetWriteAckPolicy(durable.WriteAckRequireObserverAck)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
|
||||
defer cancel()
|
||||
data := append(bytes.Repeat([]byte{0xA1}, 4096), bytes.Repeat([]byte{0xB2}, 4096)...)
|
||||
n, err := b.Write(ctx, 0, data)
|
||||
if n != 4096 {
|
||||
t.Fatalf("committed bytes %d, want exactly the 4096-byte prefix (err %v)", n, err)
|
||||
}
|
||||
if !errors.Is(err, physical) {
|
||||
t.Fatalf("physical storage fault lost: %v", err)
|
||||
}
|
||||
if errors.Is(err, frontend.ErrBackendBusy) {
|
||||
t.Fatalf("physical storage fault reclassified as retryable busy: %v", err)
|
||||
}
|
||||
if batchObserver && !errors.Is(err, durable.ErrReplicationAckUnavailable) {
|
||||
t.Fatalf("required observer failure lost its ACK identity: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type deadlineStorage struct {
|
||||
storage.LogicalStorage
|
||||
deadlines []time.Time
|
||||
legacyCalls int
|
||||
}
|
||||
|
||||
func (s *deadlineStorage) Write(lba uint32, p []byte) (uint64, error) {
|
||||
s.legacyCalls++
|
||||
return s.LogicalStorage.Write(lba, p)
|
||||
}
|
||||
func (s *deadlineStorage) WriteBatch(lba uint32, blocks [][]byte) ([]uint64, error) {
|
||||
s.legacyCalls++
|
||||
return nil, errors.New("contextless batch called")
|
||||
}
|
||||
func (s *deadlineStorage) WriteContext(ctx context.Context, lba uint32, p []byte) (uint64, error) {
|
||||
deadline, _ := ctx.Deadline()
|
||||
s.deadlines = append(s.deadlines, deadline)
|
||||
return s.LogicalStorage.Write(lba, p)
|
||||
}
|
||||
func (s *deadlineStorage) WriteBatchContext(ctx context.Context, lba uint32, blocks [][]byte) ([]uint64, error) {
|
||||
deadline, _ := ctx.Deadline()
|
||||
s.deadlines = append(s.deadlines, deadline)
|
||||
var lsns []uint64
|
||||
for i, p := range blocks {
|
||||
lsn, err := s.LogicalStorage.Write(lba+uint32(i), p)
|
||||
if err != nil {
|
||||
return lsns, err
|
||||
}
|
||||
lsns = append(lsns, lsn)
|
||||
}
|
||||
return lsns, nil
|
||||
}
|
||||
func TestStorageBackendWriteKeepsOneDeadlineAcrossBatches(t *testing.T) {
|
||||
_, view, base := newTestBackend(t, logicalStorageFactories()[0], 160, 4096)
|
||||
wrapped := &deadlineStorage{LogicalStorage: base}
|
||||
b := durable.NewStorageBackend(wrapped, view, frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1})
|
||||
b.SetOperational(true, "test")
|
||||
want := time.Now().Add(2 * time.Second)
|
||||
ctx, cancel := context.WithDeadline(context.Background(), want)
|
||||
defer cancel()
|
||||
if n, err := b.Write(ctx, 0, make([]byte, 130*4096)); err != nil || n != 130*4096 {
|
||||
t.Fatalf("write %d %v", n, err)
|
||||
}
|
||||
if _, err := b.Write(ctx, 130*4096, make([]byte, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if wrapped.legacyCalls != 0 || len(wrapped.deadlines) != 4 {
|
||||
t.Fatalf("dispatch legacy=%d deadlines=%v", wrapped.legacyCalls, wrapped.deadlines)
|
||||
}
|
||||
for _, got := range wrapped.deadlines {
|
||||
if !got.Equal(want) {
|
||||
t.Fatalf("deadline reset %v want%v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestStorageBackendExpiredWriteDoesNotAppend(t *testing.T) {
|
||||
b, _, s := newTestBackend(t, logicalStorageFactories()[0], 16, 4096)
|
||||
before := s.NextLSN()
|
||||
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
|
||||
defer cancel()
|
||||
for _, size := range []int{4096, 8192} {
|
||||
n, err := b.Write(ctx, 0, make([]byte, size))
|
||||
if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || s.NextLSN() != before {
|
||||
t.Fatalf("expired write n=%d err=%v next=%d", n, err, s.NextLSN())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type deadlineAckStore struct{ storage.LogicalStorage }
|
||||
|
||||
func (s *deadlineAckStore) WriteContext(ctx context.Context, lba uint32, p []byte) (uint64, error) {
|
||||
<-ctx.Done()
|
||||
return s.LogicalStorage.Write(lba, p)
|
||||
}
|
||||
func (s *deadlineAckStore) WriteBatch(lba uint32, blocks [][]byte) ([]uint64, error) {
|
||||
var lsns []uint64
|
||||
for i, p := range blocks {
|
||||
lsn, err := s.LogicalStorage.Write(lba+uint32(i), p)
|
||||
if err != nil {
|
||||
return lsns, err
|
||||
}
|
||||
lsns = append(lsns, lsn)
|
||||
}
|
||||
return lsns, nil
|
||||
}
|
||||
func (s *deadlineAckStore) WriteBatchContext(ctx context.Context, lba uint32, blocks [][]byte) ([]uint64, error) {
|
||||
<-ctx.Done()
|
||||
return s.WriteBatch(lba, blocks)
|
||||
}
|
||||
func TestStorageBackendRequiredObserverDeadlineStaysRetryable(t *testing.T) {
|
||||
for _, batch := range []bool{false, true} {
|
||||
for _, physical := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("batch=%t/physical=%t", batch, physical), func(t *testing.T) {
|
||||
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
|
||||
s := &deadlineAckStore{storage.NewBlockStore(8, 4096)}
|
||||
b := durable.NewStorageBackend(s, newStubView(healthyProj(id)), id)
|
||||
b.SetOperational(true, "test")
|
||||
injected := errors.New("physical observer failure")
|
||||
outcome := func(ctx context.Context) error {
|
||||
if physical {
|
||||
return errors.Join(injected, ctx.Err())
|
||||
}
|
||||
return fmt.Errorf("ack wait: %w", ctx.Err())
|
||||
}
|
||||
b.SetWriteObserver(batchWriteObserverFunc{writeObserverFunc: writeObserverFunc{observe: func(ctx context.Context, _ uint32, _ uint64, _ []byte) error { return outcome(ctx) }}, observeBatch: func(ctx context.Context, _ uint32, _ []uint64, _ [][]byte) error { return outcome(ctx) }})
|
||||
b.SetWriteAckPolicy(durable.WriteAckRequireObserverAck)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
|
||||
defer cancel()
|
||||
size := 4096
|
||||
if batch {
|
||||
size *= 2
|
||||
}
|
||||
n, err := b.Write(ctx, 0, make([]byte, size))
|
||||
if n != size || !errors.Is(err, durable.ErrReplicationAckUnavailable) {
|
||||
t.Fatalf("committed error n=%d err=%v", n, err)
|
||||
}
|
||||
if physical {
|
||||
if !errors.Is(err, injected) || errors.Is(err, frontend.ErrBackendBusy) {
|
||||
t.Fatalf("physical fault masked: %v", err)
|
||||
}
|
||||
} else {
|
||||
if !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("observer deadline lost retryability: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@ import "errors"
|
||||
var ErrStalePrimary = errors.New("frontend: stale primary lineage")
|
||||
|
||||
// ErrNotReady is returned by Provider.Open when the projection
|
||||
// never reports healthy before the context deadline.
|
||||
// never reports healthy before the context deadline, and by a Backend
|
||||
// while local recovery or chunk attachment is not yet operational.
|
||||
var ErrNotReady = errors.New("frontend: volume not ready")
|
||||
|
||||
// ErrBackendClosed is returned by Backend.Read / Backend.Write
|
||||
|
||||
@@ -76,7 +76,7 @@ type IOResult struct {
|
||||
SC uint8
|
||||
Data []byte // read payload (nil for writes / errors)
|
||||
Reason string
|
||||
retryable bool // only transient backend pressure clears wire DNR
|
||||
retryable bool // transient pressure or readiness refusal clears wire DNR
|
||||
}
|
||||
|
||||
func (r IOResult) completionStatus() uint16 { return MakeStatusField(r.SCT, r.SC, !r.retryable) }
|
||||
@@ -263,6 +263,8 @@ func (h *IOHandler) read(ctx context.Context, cmd IOCommand) IOResult {
|
||||
}
|
||||
|
||||
func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult {
|
||||
ctx, cancel := frontend.WithWriteBudget(ctx, time.Time{})
|
||||
defer cancel()
|
||||
if cmd.NLB == 0 {
|
||||
return IOResult{SCT: SCTGeneric, SC: SCInvalidField, Reason: "NLB=0"}
|
||||
}
|
||||
@@ -281,22 +283,32 @@ func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult {
|
||||
start := time.Now()
|
||||
n, err := h.backend.Write(ctx, int64(cmd.SLBA)*int64(h.blockSize), cmd.Data[:expectedBytes])
|
||||
if err != nil {
|
||||
return mapBackendError(err, "write")
|
||||
return mapWriteBudgetError(ctx, err, "write")
|
||||
}
|
||||
if rec, ok := h.backend.(targetWriteRecorder); ok {
|
||||
rec.RecordTargetWrite(n, time.Since(start))
|
||||
}
|
||||
if cmd.FUA {
|
||||
if err := h.backend.Sync(ctx); err != nil {
|
||||
return mapBackendError(err, "FUA sync")
|
||||
return mapWriteBudgetError(ctx, err, "FUA sync")
|
||||
}
|
||||
}
|
||||
return IOResult{SCT: SCTGeneric, SC: SCSuccess}
|
||||
}
|
||||
|
||||
// Only a pure command-deadline cause is transient. A joined physical error
|
||||
// must retain its terminal mapping even when the command deadline also passed.
|
||||
func mapWriteBudgetError(ctx context.Context, err error, op string) IOResult {
|
||||
if frontend.IsWriteDeadline(ctx, err) {
|
||||
return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, retryable: true, Reason: "command deadline on " + op + ": " + err.Error()}
|
||||
}
|
||||
return mapBackendError(err, op)
|
||||
}
|
||||
|
||||
// mapBackendError translates frontend errors into NVMe CQE
|
||||
// status tuples. ErrStalePrimary → ANA Transition;
|
||||
// ErrBackendClosed → ANA Inaccessible; anything else → Internal
|
||||
// ErrBackendClosed → ANA Inaccessible; ErrNotReady → retryable Namespace
|
||||
// Not Ready; anything else → Internal
|
||||
// Error (fail-closed; real-backend-specific mapping lands with
|
||||
// T3).
|
||||
func mapBackendError(err error, op string) IOResult {
|
||||
@@ -317,6 +329,9 @@ func mapBackendError(err error, op string) IOResult {
|
||||
Reason: "backend closed on " + op,
|
||||
}
|
||||
}
|
||||
if errors.Is(err, frontend.ErrNotReady) {
|
||||
return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, Reason: "backend not ready on " + op + ": " + err.Error(), retryable: true}
|
||||
}
|
||||
return IOResult{
|
||||
SCT: SCTGeneric,
|
||||
SC: SCInternalError,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package nvme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
|
||||
)
|
||||
|
||||
type budgetReadBackend struct {
|
||||
frontend.Backend
|
||||
deadline time.Time
|
||||
physical bool
|
||||
}
|
||||
|
||||
func (b *budgetReadBackend) Read(ctx context.Context, _ int64, p []byte) (int, error) {
|
||||
b.deadline, _ = ctx.Deadline()
|
||||
<-ctx.Done()
|
||||
if b.physical {
|
||||
return 0, errors.Join(ctx.Err(), errors.New("physical read failure"))
|
||||
}
|
||||
return 0, frontend.ErrBackendBusy
|
||||
}
|
||||
|
||||
func TestSessionReadBudgetIncludesQueueResidence(t *testing.T) {
|
||||
for _, physical := range []bool{false, true} {
|
||||
b := &budgetReadBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), physical: physical}
|
||||
s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), respCh: make(chan *response, 1), done: make(chan struct{})}
|
||||
arrival := time.Now().Add(-5 * time.Second)
|
||||
req := &Request{receivedAt: arrival, dispatchReadyAt: time.Now()}
|
||||
req.capsule.OpCode, req.capsule.NSID = ioRead, 1
|
||||
s.handleRead(context.Background(), req)
|
||||
resp := <-s.respCh
|
||||
want := MakeStatusField(SCTGeneric, SCNamespaceNotReady, false)
|
||||
if physical {
|
||||
want = MakeStatusField(SCTGeneric, SCInternalError, true)
|
||||
}
|
||||
if !b.deadline.Equal(arrival.Add(frontend.ReadCommandBudget)) || resp.resp.Status != want || len(resp.c2hData) != 0 {
|
||||
t.Fatalf("physical=%t deadline=%v status=%#x data=%d", physical, b.deadline, resp.resp.Status, len(resp.c2hData))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package nvme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
|
||||
)
|
||||
|
||||
type readyReadBackend struct {
|
||||
frontend.Backend
|
||||
err error
|
||||
}
|
||||
|
||||
func (b *readyReadBackend) Read(context.Context, int64, []byte) (int, error) { return 0, b.err }
|
||||
|
||||
func TestSessionReadNotReadyIsRetryable(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
err error
|
||||
sct, sc uint8
|
||||
dnr bool
|
||||
}{
|
||||
{"attach-pending", fmt.Errorf("awaiting HEAD attach: %w", frontend.ErrNotReady), SCTGeneric, SCNamespaceNotReady, false},
|
||||
{"not-ready-closed", errors.Join(frontend.ErrNotReady, frontend.ErrBackendClosed), SCTPathRelated, SCPathAsymAccessInaccessible, true},
|
||||
{"not-ready-stale", errors.Join(frontend.ErrNotReady, frontend.ErrStalePrimary), SCTPathRelated, SCPathAsymAccessTransition, true},
|
||||
{"physical-fault", errors.New("physical read failure"), SCTGeneric, SCInternalError, true},
|
||||
{"closed", frontend.ErrBackendClosed, SCTPathRelated, SCPathAsymAccessInaccessible, true},
|
||||
{"stale", frontend.ErrStalePrimary, SCTPathRelated, SCPathAsymAccessTransition, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
backend := &readyReadBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: tc.err}
|
||||
s := &Session{handler: NewIOHandler(HandlerConfig{Backend: backend}), respCh: make(chan *response, 1), done: make(chan struct{})}
|
||||
req := &Request{}
|
||||
req.capsule.OpCode = ioRead
|
||||
req.capsule.NSID = 1
|
||||
s.handleRead(context.Background(), req)
|
||||
resp := <-s.respCh
|
||||
if want := MakeStatusField(tc.sct, tc.sc, tc.dnr); resp.resp.Status != want {
|
||||
t.Fatalf("wire status=%#x want=%#x", resp.resp.Status, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadinessRetryDelayIsNotAdvertised(t *testing.T) {
|
||||
s := &Session{target: &Target{cfg: TargetConfig{VolumeID: "v1"}}, handler: &IOHandler{}, ctrl: &adminController{}, respCh: make(chan *response, 1), done: make(chan struct{})}
|
||||
controller := s.buildIdentifyController()
|
||||
for offset := 128; offset < 134; offset++ {
|
||||
if controller[offset] != 0 {
|
||||
t.Fatalf("CRDT byte%d=%d; host-policy control assumes no retry delay", offset, controller[offset])
|
||||
}
|
||||
}
|
||||
req := &Request{}
|
||||
req.capsule.D10 = 0x16 // Host Behavior Support, including ACRE.
|
||||
if err := s.handleSetFeatures(req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := (<-s.respCh).resp.Status; got != MakeStatusField(SCTGeneric, SCInvalidField, true) {
|
||||
t.Fatalf("unsupported Host Behavior status=%#x", got)
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
@@ -80,7 +81,8 @@ type Request struct {
|
||||
capsule CapsuleCommand
|
||||
payload []byte // inline/R2T-collected data for Write
|
||||
resp CapsuleResponse
|
||||
c2hData []byte // non-nil for Read/Identify responses
|
||||
c2hData []byte // non-nil for Read/Identify responses
|
||||
receivedAt time.Time // capsule arrival, including queued/R2T time
|
||||
dispatchReadyAt time.Time
|
||||
}
|
||||
|
||||
@@ -266,7 +268,7 @@ func (s *Session) parseCapsule() (*Request, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
req := &Request{capsule: capsule, payload: payload}
|
||||
req := &Request{capsule: capsule, payload: payload, receivedAt: start}
|
||||
req.resp.CID = capsule.CID
|
||||
if s.qid > 0 && capsule.OpCode == ioWrite {
|
||||
s.recordWriteCapsuleReceiveParse(time.Since(start))
|
||||
@@ -572,6 +574,12 @@ func (s *Session) enqueueResponse(resp *response) {
|
||||
// ---------- IO handlers (run in goroutines) ----------
|
||||
|
||||
func (s *Session) handleRead(ctx context.Context, req *Request) {
|
||||
arrival := req.receivedAt
|
||||
if arrival.IsZero() {
|
||||
arrival = req.dispatchReadyAt
|
||||
}
|
||||
ctx, cancel := frontend.WithReadBudget(ctx, arrival)
|
||||
defer cancel()
|
||||
s.recordReadCommand()
|
||||
res := s.handler.Handle(ctx, IOCommand{
|
||||
Opcode: req.capsule.OpCode,
|
||||
@@ -588,6 +596,12 @@ func (s *Session) handleRead(ctx context.Context, req *Request) {
|
||||
}
|
||||
|
||||
func (s *Session) handleWrite(ctx context.Context, req *Request) {
|
||||
arrival := req.receivedAt
|
||||
if arrival.IsZero() {
|
||||
arrival = req.dispatchReadyAt
|
||||
}
|
||||
ctx, cancel := frontend.WithWriteBudget(ctx, arrival)
|
||||
defer cancel()
|
||||
s.recordWriteCommand()
|
||||
s.recordWriteDispatchWait(time.Since(req.dispatchReadyAt))
|
||||
handlerStart := time.Now()
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package nvme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
|
||||
)
|
||||
|
||||
type expiredDispatchBackend struct {
|
||||
frontend.Backend
|
||||
deadline time.Time
|
||||
calls int
|
||||
}
|
||||
|
||||
func (b *expiredDispatchBackend) Write(ctx context.Context, _ int64, _ []byte) (int, error) {
|
||||
b.calls++
|
||||
b.deadline, _ = ctx.Deadline()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return 0, frontend.ErrBackendBusy
|
||||
}
|
||||
return 512, nil
|
||||
}
|
||||
func TestSessionWriteBudgetIncludesDispatchQueue(t *testing.T) {
|
||||
b := &expiredDispatchBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"})}
|
||||
s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), respCh: make(chan *response, 1), done: make(chan struct{})}
|
||||
arrived := time.Now().Add(-5 * time.Second)
|
||||
req := &Request{payload: make([]byte, 512), receivedAt: arrived, dispatchReadyAt: time.Now()}
|
||||
req.capsule.OpCode = ioWrite
|
||||
req.capsule.NSID = 1
|
||||
s.handleWrite(context.Background(), req)
|
||||
resp := <-s.respCh
|
||||
if b.calls != 1 || !b.deadline.Equal(arrived.Add(frontend.WriteCommandBudget)) || resp.resp.Status != MakeStatusField(SCTGeneric, SCNamespaceNotReady, false) {
|
||||
t.Fatalf("deadline=%v status=%#x calls=%d", b.deadline, resp.resp.Status, b.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// An already-issued write is joined even if its deadline passes. A subsequent
|
||||
// FUA wait may return deadline exceeded, but must not turn transient expiry
|
||||
// into a permanent device error. Physical failures still win.
|
||||
type joinedBudgetBackend struct {
|
||||
frontend.Backend
|
||||
fua, physical bool
|
||||
}
|
||||
|
||||
func (b *joinedBudgetBackend) result(ctx context.Context) error {
|
||||
if b.physical {
|
||||
return errors.Join(errors.New("physical fsync failure"), ctx.Err())
|
||||
}
|
||||
return fmt.Errorf("durability wait: %w", ctx.Err())
|
||||
}
|
||||
func (b *joinedBudgetBackend) Write(ctx context.Context, _ int64, p []byte) (int, error) {
|
||||
<-ctx.Done()
|
||||
if b.fua {
|
||||
return len(p), nil
|
||||
}
|
||||
return 0, b.result(ctx)
|
||||
}
|
||||
func (b *joinedBudgetBackend) Sync(ctx context.Context) error { return b.result(ctx) }
|
||||
func TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA(t *testing.T) {
|
||||
for _, fua := range []bool{false, true} {
|
||||
for _, physical := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("fua=%t/physical=%t", fua, physical), func(t *testing.T) {
|
||||
b := &joinedBudgetBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), fua: fua, physical: physical}
|
||||
s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), respCh: make(chan *response, 1), done: make(chan struct{})}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
|
||||
defer cancel()
|
||||
req := &Request{payload: make([]byte, 512)}
|
||||
req.capsule.OpCode = ioWrite
|
||||
req.capsule.NSID = 1
|
||||
if fua {
|
||||
req.capsule.D12 |= 1 << 30
|
||||
}
|
||||
s.handleWrite(ctx, req)
|
||||
got := (<-s.respCh).resp.Status
|
||||
want := MakeStatusField(SCTGeneric, SCNamespaceNotReady, false)
|
||||
if physical {
|
||||
want = MakeStatusField(SCTGeneric, SCInternalError, true)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("completion=%#x want%#x", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package frontend
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
const ReadCommandBudget = WriteCommandBudget
|
||||
|
||||
// WithReadBudget includes queue residence and all cooperative attachment and
|
||||
// hydration waits. A previously established, earlier deadline is never reset.
|
||||
func WithReadBudget(ctx context.Context, arrival time.Time) (context.Context, context.CancelFunc) {
|
||||
return WithWriteBudget(ctx, arrival)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package frontend
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
const WriteCommandBudget = 4 * time.Second
|
||||
|
||||
// WithWriteBudget preserves an earlier caller deadline, including time spent
|
||||
// queued before dispatch. A zero arrival denotes a direct backend call.
|
||||
func WithWriteBudget(ctx context.Context, arrival time.Time) (context.Context, context.CancelFunc) {
|
||||
if arrival.IsZero() {
|
||||
arrival = time.Now()
|
||||
}
|
||||
deadline := arrival.Add(WriteCommandBudget)
|
||||
if prior, ok := ctx.Deadline(); ok && !deadline.Before(prior) {
|
||||
return ctx, func() {}
|
||||
}
|
||||
return context.WithDeadline(ctx, deadline)
|
||||
}
|
||||
|
||||
// IsWriteDeadline recognizes only an expired caller's pure deadline cause.
|
||||
// Joined physical/unknown errors retain their terminal classification.
|
||||
func IsWriteDeadline(ctx context.Context, err error) bool {
|
||||
return ctx.Err() == context.DeadlineExceeded && deadlineCausesOnly(err)
|
||||
}
|
||||
func deadlineCausesOnly(err error) bool {
|
||||
if err == context.DeadlineExceeded {
|
||||
return true
|
||||
}
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if joined, ok := err.(interface{ Unwrap() []error }); ok {
|
||||
causes := joined.Unwrap()
|
||||
if len(causes) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, cause := range causes {
|
||||
if !deadlineCausesOnly(cause) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return deadlineCausesOnly(errors.Unwrap(err))
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type syncBuffer struct {
|
||||
mu sync.Mutex
|
||||
b bytes.Buffer
|
||||
}
|
||||
|
||||
func (s *syncBuffer) Write(p []byte) (int, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.b.Write(p)
|
||||
}
|
||||
|
||||
func (s *syncBuffer) String() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.b.String()
|
||||
}
|
||||
|
||||
// A refused move names the precondition that failed, in the gRPC status and
|
||||
// in the master log: an unknown source, an unregistered target node, a
|
||||
// target that is the source, or target endpoints that are not registered
|
||||
// (with what is registered: the node's pair, or the volume's live bindings
|
||||
// on that node).
|
||||
func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) {
|
||||
logs := &syncBuffer{}
|
||||
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true,
|
||||
Logger: log.New(logs, "", 0),
|
||||
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
|
||||
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Start()
|
||||
defer closeTestMaster(t, m)
|
||||
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn)
|
||||
for _, n := range []lifecycle.NodeRegistration{
|
||||
{ServerID: "node-a", DataAddr: "127.0.0.1:19101", CtrlAddr: "127.0.0.1:19102"},
|
||||
{ServerID: "node-b", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"},
|
||||
} {
|
||||
if _, err := m.Lifecycle().Nodes.RegisterNode(n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, v := range []string{"placed", "unplaced", "bound"} {
|
||||
if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: v, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "placed", DesiredRF: 1,
|
||||
Candidates: []lifecycle.PlacementCandidate{{VolumeID: "placed", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// "bound" has explicit per-volume bindings: its source on node-a and a
|
||||
// prepared target on node-b at slot 2.
|
||||
for _, b := range []*control.WorkspaceBinding{
|
||||
{VolumeId: "bound", ServerId: "node-a", DataAddr: "127.0.0.1:19121", CtrlAddr: "127.0.0.1:19122"},
|
||||
{VolumeId: "bound", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"},
|
||||
} {
|
||||
if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "bound", ServerId: "node-a", ReplicaId: "r1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
move := func(vol, server, data, ctrl string) *control.WorkspaceMove {
|
||||
return &control.WorkspaceMove{RequestId: vol + "-" + server + "-" + data, VolumeId: vol, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
|
||||
TargetServerId: server, TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"}
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
q *control.WorkspaceMove
|
||||
want string
|
||||
}{
|
||||
{"unknown source", move("unplaced", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), `move source unknown: no issued move or placement names replica "r1" at epoch 1`},
|
||||
{"unknown target node", move("placed", "node-z", "127.0.0.1:19301", "127.0.0.1:19302"), `move target node "node-z" is not registered`},
|
||||
{"target is the source", move("placed", "node-a", "127.0.0.1:19101", "127.0.0.1:19102"), `move target "node-a" is the current source host`},
|
||||
{"target on another host", move("placed", "node-b", "10.9.9.9:19311", "127.0.0.1:19312"),
|
||||
`move target endpoints 10.9.9.9:19311/127.0.0.1:19312 on "node-b" are not registered (not on the node's hosts: it registers 127.0.0.1:19301/127.0.0.1:19302; no per-volume binding is prepared)`},
|
||||
{"explicit binding elsewhere", move("bound", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"),
|
||||
`move target endpoints 127.0.0.1:19301/127.0.0.1:19302 on "node-b" are not registered (live bindings on that node: 127.0.0.1:19321/127.0.0.1:19322)`},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
_, err := ws.MoveWorkspace(ctx, c.q)
|
||||
if status.Code(err) != codes.FailedPrecondition || status.Convert(err).Message() != c.want {
|
||||
t.Fatalf("refusal %v; want FailedPrecondition %q", err, c.want)
|
||||
}
|
||||
if line := `MoveWorkspace refused volume="` + c.q.VolumeId + `" request="` + c.q.RequestId + `": ` + c.want; !strings.Contains(logs.String(), line) {
|
||||
t.Fatalf("log lacks %q:\n%s", line, logs.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
// Slot-0 and slot-1 targets on the node's host pass these preconditions
|
||||
// (they fail later, at the clean-move ACK check, for a different reason).
|
||||
for _, data := range []string{"127.0.0.1:19301", "127.0.0.1:19311"} {
|
||||
_, err = ws.MoveWorkspace(ctx, move("placed", "node-b", data, "127.0.0.1:19312"))
|
||||
if err == nil || strings.Contains(err.Error(), "move target") || strings.Contains(err.Error(), "move source") {
|
||||
t.Fatalf("target %s on the node's host: %v; want past the endpoint preconditions", data, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// blockingWriter blocks the first write that contains marker until
|
||||
// released; other writes pass.
|
||||
type blockingWriter struct {
|
||||
marker string
|
||||
entered, release chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (b *blockingWriter) Write(p []byte) (int, error) {
|
||||
if !strings.Contains(string(p), b.marker) {
|
||||
return len(p), nil
|
||||
}
|
||||
first := false
|
||||
b.once.Do(func() { first = true })
|
||||
if first {
|
||||
close(b.entered)
|
||||
<-b.release
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// A refused move is logged after workspaceMu is released: while the log
|
||||
// writer is blocked, another workspace RPC still gets the lock.
|
||||
func TestWorkspaceMoveRefusalLogsOutsideTheWorkspaceLock(t *testing.T) {
|
||||
w := &blockingWriter{marker: "MoveWorkspace refused", entered: make(chan struct{}), release: make(chan struct{})}
|
||||
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, Logger: log.New(w, "", 0),
|
||||
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Start()
|
||||
defer closeTestMaster(t, m)
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(w.release) }) }
|
||||
defer release()
|
||||
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
ws := control.NewWorkspaceServiceClient(conn)
|
||||
if _, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "r", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"})
|
||||
done <- err
|
||||
}()
|
||||
select {
|
||||
case <-w.entered:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("the refusal was never logged")
|
||||
}
|
||||
qctx, qcancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer qcancel()
|
||||
if _, err := ws.QueryWorkspace(qctx, &control.WorkspaceVolume{VolumeId: "v"}); err != nil {
|
||||
t.Fatalf("workspace RPC while the refusal log is blocked: %v; want workspaceMu free", err)
|
||||
}
|
||||
release()
|
||||
select {
|
||||
case err := <-done:
|
||||
if status.Code(err) != codes.FailedPrecondition {
|
||||
t.Fatalf("move: %v", err)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("the move did not return after the log was released")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
// The T08 shape: two volumes without per-volume bindings, nodes registered
|
||||
// at slot 0 of their host. "a1" holds slot 0 on node-a; "a2" lives on
|
||||
// node-b and moves back to node-a. Its target lands on slot 1 (slot 0 is
|
||||
// held) and is granted; a target on a1's live slot-0 endpoints is refused by
|
||||
// the collision check, and one on another host's address by the ownership
|
||||
// check. The grant routes a2 to the slot-1 endpoints it asked for.
|
||||
func TestWorkspaceMoveToAnotherSlotOnTheTargetHost(t *testing.T) {
|
||||
heads := map[string]authority.WorkspaceHead{"a2": {Gen: 9, Epoch: 1, Holder: "node-b/r1", RemoteLSN: 42, Detached: true}}
|
||||
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true,
|
||||
WorkspaceHeadReader: func(_ context.Context, v string) (authority.WorkspaceHead, error) { return heads[v], nil }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Start()
|
||||
defer closeTestMaster(t, m)
|
||||
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn)
|
||||
slot := func(base, n int) (string, string) {
|
||||
return "127.0.0.1:" + strconv.Itoa(base+10*n+1), "127.0.0.1:" + strconv.Itoa(base+10*n+2)
|
||||
}
|
||||
for _, n := range []struct {
|
||||
id string
|
||||
base int
|
||||
}{{"node-a", 19100}, {"node-b", 19300}} {
|
||||
d, c := slot(n.base, 0)
|
||||
if _, err := m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: n.id, DataAddr: d, CtrlAddr: c}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
place := func(vol, server string, base int) authority.AuthorityBasis {
|
||||
t.Helper()
|
||||
if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: vol, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: vol, DesiredRF: 1,
|
||||
Candidates: []lifecycle.PlacementCandidate{{VolumeID: vol, ServerID: server, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, c := slot(base, 0)
|
||||
if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
|
||||
Slots: []*control.HeartbeatSlot{{VolumeId: vol, ReplicaId: "r1", DataAddr: d, CtrlAddr: c}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := m.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return waitAuthorityLine(t, m.Publisher(), vol)
|
||||
}
|
||||
a1 := place("a1", "node-a", 19100) // holds node-a slot 0
|
||||
a2 := place("a2", "node-b", 19300)
|
||||
if a1.DataAddr != "127.0.0.1:19101" || a2.DataAddr != "127.0.0.1:19301" {
|
||||
t.Fatalf("fixture lines a1=%+v a2=%+v", a1, a2)
|
||||
}
|
||||
// a2 stops cleanly on node-b: lease, revocation, ACK of its detached HEAD.
|
||||
id := &control.WorkspaceIdentity{VolumeId: "a2", ReplicaId: "r1", Epoch: a2.Epoch}
|
||||
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ws.RevokeWorkspace(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
move := func(req, data, ctrl string) *control.WorkspaceMove {
|
||||
return &control.WorkspaceMove{RequestId: req, VolumeId: "a2", ExpectedReplicaId: "r1", ExpectedEpoch: a2.Epoch, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-a", TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"}
|
||||
}
|
||||
d0, c0 := slot(19100, 0)
|
||||
if _, err := ws.MoveWorkspace(ctx, move("onto-a1", d0, c0)); err == nil || !strings.Contains(err.Error(), "endpoint belongs to live assignment") {
|
||||
t.Fatalf("move onto a1's live slot-0 endpoints: %v; want the collision refusal", err)
|
||||
}
|
||||
if _, err := ws.MoveWorkspace(ctx, move("other-host", "10.9.9.9:19111", "10.9.9.9:19112")); err == nil || !strings.Contains(err.Error(), `endpoints 10.9.9.9:19111/10.9.9.9:19112 on "node-a" are not registered`) {
|
||||
t.Fatalf("move to another host's address: %v; want the ownership refusal", err)
|
||||
}
|
||||
d1, c1 := slot(19100, 1)
|
||||
if _, err := ws.MoveWorkspace(ctx, move("ctrl-other-host", d1, "10.9.9.9:19112")); err == nil || !strings.Contains(err.Error(), `on "node-a" are not registered`) {
|
||||
t.Fatalf("move with its ctrl endpoint on another host: %v; want the ownership refusal", err)
|
||||
}
|
||||
// Invalid endpoints on the right host are refused before anything is
|
||||
// written: the epoch, the journal, the lease and the ACK stay as they were.
|
||||
before := m.Publisher().WorkspaceState("a2")
|
||||
for _, bad := range []struct{ name, data, ctrl string }{
|
||||
{"non-numeric port", "127.0.0.1:bad", c1},
|
||||
{"port 0", "127.0.0.1:0", c1},
|
||||
{"port 65536", d1, "127.0.0.1:65536"},
|
||||
{"empty port", "127.0.0.1:", c1},
|
||||
{"data equals ctrl", d1, d1},
|
||||
} {
|
||||
if _, err := ws.MoveWorkspace(ctx, move("bad-"+bad.name, bad.data, bad.ctrl)); err == nil || !strings.Contains(err.Error(), "move target endpoints invalid") {
|
||||
t.Fatalf("%s: %v; want the invalid-endpoint refusal", bad.name, err)
|
||||
}
|
||||
after := m.Publisher().WorkspaceState("a2")
|
||||
line, _ := m.Publisher().VolumeAuthorityLine("a2")
|
||||
if line.Epoch != a2.Epoch || after == nil || len(after.Moves) != 0 || after.Ack == nil || before.Ack == nil || *after.Ack != *before.Ack || after.Lease == nil || !after.Lease.Revoking {
|
||||
t.Fatalf("%s: state changed by a refused move: line %+v state %+v", bad.name, line, after)
|
||||
}
|
||||
}
|
||||
g, err := ws.MoveWorkspace(ctx, move("slot-1", d1, c1))
|
||||
if err != nil {
|
||||
t.Fatalf("move to node-a slot 1 while slot 0 is held: %v", err)
|
||||
}
|
||||
line, ok := m.Publisher().VolumeAuthorityLine("a2")
|
||||
if !g.Issued || g.NewHost != "node-a" || g.OldHost != "node-b" || !ok || line.Epoch != g.NewEpoch || line.DataAddr != d1 || line.CtrlAddr != c1 {
|
||||
t.Fatalf("grant %+v line %+v; want a2 issued on node-a at %s/%s", g, line, d1, c1)
|
||||
}
|
||||
if l1, _ := m.Publisher().VolumeAuthorityLine("a1"); l1.DataAddr != d0 || l1.Epoch != a1.Epoch {
|
||||
t.Fatalf("a1 changed: %+v", l1)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
@@ -143,6 +145,14 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
}
|
||||
// Remote reads never hold the workspace mutation lock. Re-read every
|
||||
// local precondition below; Publisher checks the expected epoch atomically.
|
||||
// A refusal is logged after the lock is released (deferred first, so it
|
||||
// runs last): a slow log writer never holds workspaceMu.
|
||||
var refusal string
|
||||
defer func() {
|
||||
if refusal != "" {
|
||||
s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal)
|
||||
}
|
||||
}()
|
||||
s.host.workspaceMu.Lock()
|
||||
defer s.host.workspaceMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
@@ -157,14 +167,32 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
if err != nil {
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
matched := !explicit && target.DataAddr == q.GetTargetDataAddr() && target.CtrlAddr == q.GetTargetCtrlAddr()
|
||||
// A volume without per-volume bindings may move to any port on the
|
||||
// target node's registered hosts (a host runs several slots): the host
|
||||
// match ties the endpoints to that node's registration (it trusts the
|
||||
// registration; it is not an identity proof). The collision check below
|
||||
// still refuses endpoints another assignment or binding owns.
|
||||
matched := !explicit && sameHost(q.GetTargetDataAddr(), target.DataAddr) && sameHost(q.GetTargetCtrlAddr(), target.CtrlAddr)
|
||||
endpointErr := lifecycle.ValidateWorkspaceEndpoints(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: q.GetTargetServerId(), DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()})
|
||||
for _, b := range bindings {
|
||||
if !b.Retired && b.ServerID == q.GetTargetServerId() && b.DataAddr == q.GetTargetDataAddr() && b.CtrlAddr == q.GetTargetCtrlAddr() {
|
||||
matched = true
|
||||
}
|
||||
}
|
||||
if oldHost == "" || !ok || target.ServerID == oldHost || !matched {
|
||||
return nil, status.Error(codes.FailedPrecondition, "move needs known source slot and registered target endpoints")
|
||||
switch {
|
||||
case endpointErr != nil:
|
||||
refusal = fmt.Sprintf("move target endpoints invalid: %v", endpointErr)
|
||||
case oldHost == "":
|
||||
refusal = fmt.Sprintf("move source unknown: no issued move or placement names replica %q at epoch %d", q.GetExpectedReplicaId(), q.GetExpectedEpoch())
|
||||
case !ok:
|
||||
refusal = fmt.Sprintf("move target node %q is not registered", q.GetTargetServerId())
|
||||
case target.ServerID == oldHost:
|
||||
refusal = fmt.Sprintf("move target %q is the current source host", target.ServerID)
|
||||
case !matched:
|
||||
refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit))
|
||||
}
|
||||
if refusal != "" {
|
||||
return nil, status.Error(codes.FailedPrecondition, refusal)
|
||||
}
|
||||
if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil {
|
||||
return nil, workspaceError(err)
|
||||
@@ -180,6 +208,32 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
return grantFact(r), nil
|
||||
}
|
||||
|
||||
// sameHost reports whether two host:port addresses name the same host:
|
||||
// canonical host parts (equivalent IP spellings equal), no name resolution.
|
||||
func sameHost(a, b string) bool {
|
||||
ha := lifecycle.WorkspaceEndpointHost(a)
|
||||
return ha != "" && ha == lifecycle.WorkspaceEndpointHost(b)
|
||||
}
|
||||
|
||||
// registeredTargetEndpoints describes what a move to target may name: the
|
||||
// node's own pair for a volume without explicit bindings, else its live
|
||||
// bindings on that node.
|
||||
func registeredTargetEndpoints(target lifecycle.NodeRegistration, bindings []lifecycle.WorkspaceBinding, explicit bool) string {
|
||||
if !explicit {
|
||||
return fmt.Sprintf("not on the node's hosts: it registers %s/%s; no per-volume binding is prepared", target.DataAddr, target.CtrlAddr)
|
||||
}
|
||||
var live []string
|
||||
for _, b := range bindings {
|
||||
if !b.Retired && b.ServerID == target.ServerID {
|
||||
live = append(live, b.DataAddr+"/"+b.CtrlAddr)
|
||||
}
|
||||
}
|
||||
if len(live) == 0 {
|
||||
return "the volume has explicit bindings but none live on that node"
|
||||
}
|
||||
return "live bindings on that node: " + strings.Join(live, ", ")
|
||||
}
|
||||
|
||||
func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolume) (*control.WorkspaceStatus, error) {
|
||||
s.host.workspaceMu.Lock()
|
||||
defer s.host.workspaceMu.Unlock()
|
||||
|
||||
@@ -3,7 +3,9 @@ package volume
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
@@ -19,6 +21,30 @@ type fakeChunkProvider struct {
|
||||
lastMin uint64
|
||||
}
|
||||
|
||||
type adapterManifestFiler struct {
|
||||
chunkstore.Filer
|
||||
mu sync.Mutex
|
||||
blobs map[string][]byte
|
||||
}
|
||||
|
||||
func (f *adapterManifestFiler) Put(_ context.Context, b []byte) (string, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
id := fmt.Sprintf("fixture-%d", len(f.blobs))
|
||||
f.blobs[id] = append([]byte(nil), b...)
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (f *adapterManifestFiler) Get(_ context.Context, id string) ([]byte, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
b, ok := f.blobs[id]
|
||||
if !ok {
|
||||
return nil, chunkstore.ErrNotFound
|
||||
}
|
||||
return append([]byte(nil), b...), nil
|
||||
}
|
||||
|
||||
func (f *fakeChunkProvider) CutVolume(_ context.Context, _ string, minLSN uint64) (storage.ChunkCutResult, error) {
|
||||
f.cuts++
|
||||
f.lastMin = minLSN
|
||||
@@ -36,8 +62,17 @@ func adapterFixture(t *testing.T) (*fakeChunkProvider, ChunkControl) {
|
||||
t.Helper()
|
||||
head := storage.ChunkHead{Gen: 3, Epoch: 2, Holder: "r1", RemoteLSN: 9, State: storage.ChunkHeadActive,
|
||||
Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e2/c0/k1"}, 5: {Key: "chunks/e2/c5/k2"}}}
|
||||
f := &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}}
|
||||
r, err := chunkstore.NewChunkRemote(f, f, "/swblock/chunks/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head, _, err = r.PrepareManifest(context.Background(), storage.ChunkHead{}, head, 8*4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fp := &fakeChunkProvider{cut: storage.ChunkCutResult{H: 9, Head: head}}
|
||||
cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), "/swblock/chunks")
|
||||
cat, err := chunkstore.NewCatalog(f, "/swblock/chunks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -66,6 +66,11 @@ type Config struct {
|
||||
// their documented non-healthy projection).
|
||||
EnableT1Readiness bool
|
||||
WorkspaceLease bool // Opt-in: require a workspace lease before I/O or capture.
|
||||
// RF1Only, when set, is why this volume serves single-replica only
|
||||
// (walstore-chunk): every assignment with replica slots, primary with
|
||||
// peers or supporting replica, is refused before any peer set, role or
|
||||
// readiness is installed, and latched like a failed role admission.
|
||||
RF1Only string
|
||||
|
||||
// ReplicationVolume, when non-nil, receives peer-set updates on
|
||||
// every self-replica AssignmentFact. The Host calls
|
||||
@@ -143,6 +148,15 @@ type Host struct {
|
||||
// even on a host that was healthy at its prior epoch; only a later
|
||||
// successful role call for the current role and epoch clears it.
|
||||
roleAdmissionFailed atomic.Value // string reason; "" = not failed
|
||||
// RF1Only admission state, one unit under rf1Mu (field access only, no
|
||||
// calls): the highest refused epoch with its reason ("" = cleared), and the
|
||||
// highest epoch an RF1 fact was admitted at. A clear removes only the
|
||||
// refusal it can still see as not newer than its own fact.
|
||||
rf1Mu sync.Mutex
|
||||
rf1Reason string
|
||||
rf1Refused uint64
|
||||
rf1Admitted uint64
|
||||
rf1BeforeAdmit func() // test hook: between the stale check and the admit
|
||||
|
||||
conn *grpc.ClientConn
|
||||
obsCli control.ObservationServiceClient
|
||||
@@ -428,6 +442,12 @@ func (h *Host) latchRoleAdmission(role selfRole, epoch uint64, err error) {
|
||||
// call on this host's replica listener failed, and why. The projection view
|
||||
// treats a failure as not Healthy.
|
||||
func (h *Host) RoleAdmissionFailure() (bool, string) {
|
||||
h.rf1Mu.Lock()
|
||||
rf1 := h.rf1Reason
|
||||
h.rf1Mu.Unlock()
|
||||
if rf1 != "" {
|
||||
return true, rf1
|
||||
}
|
||||
reason, _ := h.roleAdmissionFailed.Load().(string)
|
||||
return reason != "", reason
|
||||
}
|
||||
@@ -780,6 +800,10 @@ func (h *Host) applyFact(fact *control.AssignmentFact) {
|
||||
h.cfg.VolumeID, reason, info.ReplicaID, info.Epoch, info.EndpointVersion)
|
||||
return
|
||||
}
|
||||
if h.cfg.RF1Only != "" {
|
||||
h.refuseRF1("a supporting replica role", info.Epoch)
|
||||
return
|
||||
}
|
||||
if err := h.fenceSelf(selfRoleReplica, info.Epoch); err != nil {
|
||||
// G1: fail closed, as for the primary path; stream replay
|
||||
// redelivers the fact and a later success clears the latch.
|
||||
@@ -817,6 +841,23 @@ func (h *Host) applyFact(fact *control.AssignmentFact) {
|
||||
return
|
||||
}
|
||||
|
||||
// An RF1-only volume refuses replica peers before anything is installed,
|
||||
// and a fact below a refused epoch is stale: it neither adopts nor clears.
|
||||
if h.cfg.RF1Only != "" {
|
||||
if len(fact.Peers) > 0 {
|
||||
h.refuseRF1(fmt.Sprintf("a primary role with %d replica peers", len(fact.Peers)), fact.Epoch)
|
||||
return
|
||||
}
|
||||
h.rf1Mu.Lock()
|
||||
refused := h.rf1Refused
|
||||
h.rf1Mu.Unlock()
|
||||
if fact.Epoch < refused {
|
||||
h.log.Printf("blockvolume: volume %s stale RF1 assignment at epoch %d below refused epoch %d — NOT applying to adapter",
|
||||
h.cfg.VolumeID, fact.Epoch, refused)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Step (2a): install replication peer set first. Decoded via
|
||||
// the separate host-only decodeReplicaTargets path (not through
|
||||
// AssignmentInfo), so the TestNoOtherAssignmentInfoConstruction
|
||||
@@ -855,6 +896,11 @@ func (h *Host) applyFact(fact *control.AssignmentFact) {
|
||||
h.cfg.VolumeID, info.Epoch, err)
|
||||
return
|
||||
}
|
||||
if h.cfg.RF1Only != "" && !h.admitRF1(fact.Epoch) {
|
||||
h.log.Printf("blockvolume: volume %s RF1 assignment at epoch %d overtaken by a newer refusal — NOT applying to adapter",
|
||||
h.cfg.VolumeID, fact.Epoch)
|
||||
return
|
||||
}
|
||||
h.adpt.OnAssignment(info)
|
||||
h.log.Printf("blockvolume: volume %s adopted as PRIMARY at %s@%d (EV=%d)",
|
||||
h.cfg.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion)
|
||||
@@ -866,6 +912,42 @@ func (h *Host) applyFact(fact *control.AssignmentFact) {
|
||||
}
|
||||
}
|
||||
|
||||
// refuseRF1 latches the refusal of a role with replica slots on an RF1-only
|
||||
// volume (Config.RF1Only): no peer set, role or readiness was installed.
|
||||
func (h *Host) refuseRF1(what string, epoch uint64) {
|
||||
reason := fmt.Sprintf("volume %s refuses %s at epoch %d: %s", h.cfg.VolumeID, what, epoch, h.cfg.RF1Only)
|
||||
h.rf1Mu.Lock()
|
||||
stale := epoch < h.rf1Admitted // older than an admitted RF1 fact: does not re-latch
|
||||
if !stale && epoch >= h.rf1Refused {
|
||||
h.rf1Refused, h.rf1Reason = epoch, reason
|
||||
}
|
||||
h.rf1Mu.Unlock()
|
||||
if stale {
|
||||
h.log.Printf("blockvolume: stale %s (admitted RF1 epoch is newer) — NOT applying to adapter", reason)
|
||||
return
|
||||
}
|
||||
h.log.Printf("blockvolume: %s — NOT applying to adapter (fail-closed)", reason)
|
||||
}
|
||||
|
||||
// admitRF1 clears the RF1 refusal for an RF1 fact whose role was admitted,
|
||||
// unless a refusal at a newer epoch was latched meanwhile (then it reports
|
||||
// false and the fact must not be adopted).
|
||||
func (h *Host) admitRF1(epoch uint64) bool {
|
||||
if hook := h.rf1BeforeAdmit; hook != nil {
|
||||
hook()
|
||||
}
|
||||
h.rf1Mu.Lock()
|
||||
defer h.rf1Mu.Unlock()
|
||||
if epoch < h.rf1Refused {
|
||||
return false
|
||||
}
|
||||
h.rf1Reason = ""
|
||||
if epoch > h.rf1Admitted {
|
||||
h.rf1Admitted = epoch
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *Host) emitSupportingReadyMarker(info adapter.AssignmentInfo) {
|
||||
if h.cfg.ReadyMarker == nil || info.Epoch == 0 {
|
||||
return
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
"github.com/seaweedfs/seaweed-block/core/engine"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage/memorywal"
|
||||
)
|
||||
|
||||
func rf2PrimaryFact(epoch uint64) *control.AssignmentFact {
|
||||
return &control.AssignmentFact{
|
||||
VolumeId: "vol1", ReplicaId: "r1", Epoch: epoch, EndpointVersion: 1,
|
||||
DataAddr: "127.0.0.1:1000", CtrlAddr: "127.0.0.1:1001", PeerSetGeneration: epoch,
|
||||
Peers: []*control.ReplicaDescriptor{{ReplicaId: "r2", Epoch: epoch, EndpointVersion: 1, DataAddr: "127.0.0.1:2000", CtrlAddr: "127.0.0.1:2001"}},
|
||||
}
|
||||
}
|
||||
|
||||
// The production start schedule of an RF1-only (walstore-chunk) volume: the
|
||||
// host starts with local readiness blocked, a retained RF2 fact arrives and is
|
||||
// stored, and installing the replication volume replays it with no self fence
|
||||
// installed yet. The host must refuse it before any peer set, adoption or
|
||||
// readiness marker, and latch the refusal; a later RF1 fact is adopted.
|
||||
func TestRF1Only_RetainedReplicatedFactReplayedBeforeSelfFence(t *testing.T) {
|
||||
rec := &orderingRecorder{}
|
||||
h, a, r := newStubbedHost(t, "vol1", "r1", rec)
|
||||
ready := make(chan adapter.AssignmentInfo, 4)
|
||||
h.cfg.ReadyMarker, h.cfg.RF1Only = ready, "chunk snapshots need RF1"
|
||||
rv := h.replication
|
||||
h.replication = nil
|
||||
h.BlockLocalReadiness("awaiting durable recovery")
|
||||
|
||||
h.applyFact(rf2PrimaryFact(3)) // stored for replay
|
||||
h.ClearLocalReadinessBlock()
|
||||
h.replicationMu.Lock()
|
||||
h.setReplicationLocked(rv) // what SetReplicationVolume does, then it replays
|
||||
h.replicationMu.Unlock()
|
||||
h.replayLocalReadinessFactIfReady()
|
||||
|
||||
if h.selfFence != nil {
|
||||
t.Fatal("fixture: a self fence is installed")
|
||||
}
|
||||
if r.callCount.Load() != 0 || a.callCount.Load() != 0 || len(ready) != 0 {
|
||||
t.Fatalf("replayed RF2 fact installed something: peers=%d adopt=%d ready=%d %v", r.callCount.Load(), a.callCount.Load(), len(ready), rec.snapshot())
|
||||
}
|
||||
failed, reason := h.RoleAdmissionFailure()
|
||||
if !failed || !strings.Contains(reason, "refuses a primary role with 1 replica peers at epoch 3") || !strings.Contains(reason, "chunk snapshots need RF1") {
|
||||
t.Fatalf("no refusal latch: %v %q", failed, reason)
|
||||
}
|
||||
|
||||
// A supporting-replica fact (another primary lists this replica) is refused too.
|
||||
sup := rf2PrimaryFact(4)
|
||||
sup.ReplicaId, sup.Peers[0].ReplicaId = "r2", "r1"
|
||||
h.applyFact(sup)
|
||||
if r.callCount.Load() != 0 || a.callCount.Load() != 0 || len(ready) != 0 {
|
||||
t.Fatal("supporting replica admitted on an RF1-only volume")
|
||||
}
|
||||
if _, reason := h.RoleAdmissionFailure(); !strings.Contains(reason, "refuses a supporting replica role at epoch 4") {
|
||||
t.Fatalf("supporting refusal not latched: %q", reason)
|
||||
}
|
||||
|
||||
// The master moves the volume to RF1: adopted, latch cleared, ready emitted.
|
||||
rf1 := rf2PrimaryFact(5)
|
||||
rf1.Peers = nil
|
||||
h.applyFact(rf1)
|
||||
if a.callCount.Load() != 1 || len(ready) != 1 {
|
||||
t.Fatalf("RF1 primary not adopted: adopt=%d ready=%d", a.callCount.Load(), len(ready))
|
||||
}
|
||||
if failed, reason := h.RoleAdmissionFailure(); failed {
|
||||
t.Fatalf("latch not cleared by an RF1 fact: %q", reason)
|
||||
}
|
||||
}
|
||||
|
||||
// Control: without the rule the same replayed RF2 fact installs its peer set
|
||||
// and is adopted (today's behaviour for replicated volumes).
|
||||
func TestRF1Only_UnsetKeepsReplicatedAdoption(t *testing.T) {
|
||||
h, a, r := newStubbedHost(t, "vol1", "r1", &orderingRecorder{})
|
||||
h.applyFact(rf2PrimaryFact(3))
|
||||
if r.callCount.Load() != 1 || a.callCount.Load() != 1 {
|
||||
t.Fatalf("replicated fact not applied: peers=%d adopt=%d", r.callCount.Load(), a.callCount.Load())
|
||||
}
|
||||
if failed, _ := h.RoleAdmissionFailure(); failed {
|
||||
t.Fatal("latched without the rule")
|
||||
}
|
||||
}
|
||||
|
||||
// A refusal is bound to its epoch: RF1@2 healthy and writing, RF2@3 refused
|
||||
// (writes stop), then a stale RF1@2 replay must neither adopt nor clear the
|
||||
// refusal (writes stay refused, no peers installed); only RF1 at the refused
|
||||
// epoch or newer, once its role is admitted, clears it.
|
||||
func TestRF1Only_StaleRF1FactDoesNotClearANewerRefusal(t *testing.T) {
|
||||
f := newRF1BackendHost(t)
|
||||
f.h.applyFact(rf1Fact(2))
|
||||
if f.a.callCount.Load() != 1 {
|
||||
t.Fatal("fixture: RF1@2 not adopted")
|
||||
}
|
||||
f.mustWrite(t, 2, 0xD2)
|
||||
f.h.applyFact(rf2PrimaryFact(3))
|
||||
f.assertRefusedAt(t, 3)
|
||||
f.h.applyFact(rf1Fact(2)) // stale replay below the refused epoch
|
||||
f.assertRefusedAt(t, 3)
|
||||
if f.a.callCount.Load() != 1 || f.r.callCount.Load() != 1 {
|
||||
t.Fatalf("stale RF1@2 adopted or RF2 peers installed: adopt=%d peerSets=%d", f.a.callCount.Load(), f.r.callCount.Load())
|
||||
}
|
||||
f.fencer.fail.Store(true) // RF1@3 whose role fence fails: a failed attempt does not clear the refusal
|
||||
f.h.applyFact(rf1Fact(3))
|
||||
if _, reason := f.h.RoleAdmissionFailure(); !strings.Contains(reason, "refuses a primary role") || f.a.callCount.Load() != 1 {
|
||||
t.Fatalf("failed RF1@3 attempt cleared the refusal: %q adopt=%d", reason, f.a.callCount.Load())
|
||||
}
|
||||
f.fencer.fail.Store(false)
|
||||
f.h.applyFact(rf1Fact(3))
|
||||
if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 {
|
||||
t.Fatalf("RF1@3 did not reconcile: %v %q adopt=%d", failed, reason, f.a.callCount.Load())
|
||||
}
|
||||
f.mustWrite(t, 3, 0xD3)
|
||||
}
|
||||
|
||||
type rf1Fixture struct {
|
||||
fencer *switchFencer
|
||||
h *Host
|
||||
a *stubAdapter
|
||||
r *stubReplication
|
||||
proj *mutableProjector
|
||||
store *memorywal.Store
|
||||
}
|
||||
|
||||
func newRF1BackendHost(t *testing.T) *rf1Fixture {
|
||||
t.Helper()
|
||||
h, a, r := newStubbedHost(t, "vol1", "r1", &orderingRecorder{})
|
||||
h.cfg.RF1Only = "chunk snapshots need RF1"
|
||||
proj := &mutableProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 2, EndpointVersion: 1}}
|
||||
h.view = NewAdapterProjectionView(proj, "vol1", "r1", h)
|
||||
fencer := &switchFencer{}
|
||||
if err := h.SetSelfFence(fencer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := memorywal.NewStore(8, 4096)
|
||||
t.Cleanup(func() { _ = store.Close() })
|
||||
return &rf1Fixture{fencer: fencer, h: h, a: a, r: r, proj: proj, store: store}
|
||||
}
|
||||
|
||||
// backend is a frontend at this epoch's identity, with the engine projection
|
||||
// at that epoch (only called while no applyFact runs).
|
||||
func (f *rf1Fixture) backend(epoch uint64) *durable.StorageBackend {
|
||||
f.proj.p = engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: epoch, EndpointVersion: 1}
|
||||
b := durable.NewStorageBackend(f.store, f.h.view, frontend.Identity{VolumeID: "vol1", ReplicaID: "r1", Epoch: epoch, EndpointVersion: 1})
|
||||
b.SetOperational(true, "rf1 fixture")
|
||||
return b
|
||||
}
|
||||
|
||||
// mustWrite writes one block at the epoch's identity and reads it back.
|
||||
func (f *rf1Fixture) mustWrite(t *testing.T, epoch uint64, fill byte) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
b := f.backend(epoch)
|
||||
data := bytes.Repeat([]byte{fill}, 4096)
|
||||
if n, err := b.Write(ctx, 0, data); n != len(data) || err != nil {
|
||||
t.Fatalf("write at epoch %d: n=%d err=%v", epoch, n, err)
|
||||
}
|
||||
got := make([]byte, len(data))
|
||||
if n, err := b.Read(ctx, 0, got); n != len(got) || err != nil || !bytes.Equal(got, data) {
|
||||
t.Fatalf("readback at epoch %d: n=%d err=%v equal=%v", epoch, n, err, bytes.Equal(got, data))
|
||||
}
|
||||
}
|
||||
|
||||
func rf1Fact(epoch uint64) *control.AssignmentFact {
|
||||
f := rf2PrimaryFact(epoch)
|
||||
f.Peers = nil
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *rf1Fixture) assertRefusedAt(t *testing.T, epoch uint64) {
|
||||
t.Helper()
|
||||
if failed, reason := f.h.RoleAdmissionFailure(); !failed || !strings.Contains(reason, fmt.Sprintf("at epoch %d", epoch)) {
|
||||
t.Fatalf("want the refusal at epoch %d latched: %v %q", epoch, failed, reason)
|
||||
}
|
||||
if _, err := f.backend(epoch-1).Write(context.Background(), 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrStalePrimary) {
|
||||
t.Fatalf("write at the old identity after the refusal: %v", err)
|
||||
}
|
||||
if len(f.r.lastTargetIDs) != 0 {
|
||||
t.Fatalf("forbidden peers installed: %v", f.r.lastTargetIDs)
|
||||
}
|
||||
}
|
||||
|
||||
// Serial interleaving: an allowed RF1@2 replay passes the stale check, and
|
||||
// before it admits, the stream latches an RF2@3 refusal. The replay must not
|
||||
// clear that newer refusal nor adopt. RF1@3 then admits and serves at epoch 3.
|
||||
func TestRF1Only_HeldRF1ReplayDoesNotClearANewerRefusal(t *testing.T) {
|
||||
f := newRF1BackendHost(t)
|
||||
f.h.applyFact(rf1Fact(2))
|
||||
f.mustWrite(t, 2, 0xA2)
|
||||
fired := false
|
||||
f.h.rf1BeforeAdmit = func() {
|
||||
if !fired {
|
||||
fired = true
|
||||
f.h.applyFact(rf2PrimaryFact(3))
|
||||
}
|
||||
}
|
||||
f.h.applyFact(rf1Fact(2))
|
||||
f.h.rf1BeforeAdmit = nil
|
||||
if !fired || f.a.callCount.Load() != 1 {
|
||||
t.Fatalf("fixture fired=%v; held RF1@2 adopted=%d", fired, f.a.callCount.Load())
|
||||
}
|
||||
f.assertRefusedAt(t, 3)
|
||||
f.h.applyFact(rf1Fact(3))
|
||||
if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 || f.a.lastInfo.Epoch != 3 {
|
||||
t.Fatalf("current RF1@3 not admitted: %v %q adopt=%d", failed, reason, f.a.callCount.Load())
|
||||
}
|
||||
f.mustWrite(t, 3, 0xA3)
|
||||
}
|
||||
|
||||
// holdingUpdater parks the first armed UpdateReplicaSet until released.
|
||||
type holdingUpdater struct {
|
||||
inner replicaSetUpdater
|
||||
armed atomic.Bool
|
||||
entered, release chan struct{}
|
||||
}
|
||||
|
||||
func (u *holdingUpdater) UpdateReplicaSet(gen uint64, targets []replication.ReplicaTarget) error {
|
||||
if u.armed.CompareAndSwap(true, false) {
|
||||
close(u.entered)
|
||||
<-u.release
|
||||
}
|
||||
return u.inner.UpdateReplicaSet(gen, targets)
|
||||
}
|
||||
|
||||
// Two workers: the replay worker's RF1@2 passes the stale check and parks in
|
||||
// the peer-set update; the stream worker's RF2@3 is refused meanwhile; the
|
||||
// replay then resumes. Bounded by timeouts.
|
||||
func TestRF1Only_ParallelHeldReplayAndNewerRefusal(t *testing.T) {
|
||||
f := newRF1BackendHost(t)
|
||||
f.h.applyFact(rf1Fact(2))
|
||||
f.mustWrite(t, 2, 0xB2)
|
||||
u := &holdingUpdater{inner: f.r, entered: make(chan struct{}), release: make(chan struct{})}
|
||||
u.armed.Store(true)
|
||||
f.h.replicationMu.Lock()
|
||||
f.h.setReplicationLocked(u)
|
||||
f.h.replicationMu.Unlock()
|
||||
|
||||
// Registered before any worker starts: every exit path (including a Fatal
|
||||
// below) releases the parked replay and joins both workers, bounded.
|
||||
var once sync.Once
|
||||
release := func() { once.Do(func() { close(u.release) }) }
|
||||
replay, stream := make(chan struct{}), make(chan struct{})
|
||||
replayStarted, streamStarted := false, false
|
||||
t.Cleanup(func() {
|
||||
release()
|
||||
for _, w := range []struct {
|
||||
started bool
|
||||
done chan struct{}
|
||||
name string
|
||||
}{{replayStarted, replay, "replay"}, {streamStarted, stream, "stream"}} {
|
||||
if !w.started {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case <-w.done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Errorf("%s worker did not finish after release", w.name)
|
||||
}
|
||||
}
|
||||
})
|
||||
replayStarted = true
|
||||
go func() { defer close(replay); f.h.applyFact(rf1Fact(2)) }()
|
||||
select {
|
||||
case <-u.entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("replay worker did not reach the peer-set update")
|
||||
}
|
||||
streamStarted = true
|
||||
go func() { defer close(stream); f.h.applyFact(rf2PrimaryFact(3)) }()
|
||||
select {
|
||||
case <-stream:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("stream worker blocked behind the parked replay")
|
||||
}
|
||||
release()
|
||||
select {
|
||||
case <-replay:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("replay worker did not finish")
|
||||
}
|
||||
if f.a.callCount.Load() != 1 {
|
||||
t.Fatalf("parked RF1@2 adopted after the newer refusal: adopt=%d", f.a.callCount.Load())
|
||||
}
|
||||
f.assertRefusedAt(t, 3)
|
||||
f.h.applyFact(rf1Fact(3))
|
||||
if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 {
|
||||
t.Fatalf("current RF1@3 not admitted: %v %q", failed, reason)
|
||||
}
|
||||
f.mustWrite(t, 3, 0xB3)
|
||||
}
|
||||
|
||||
// A stale RF2 below an admitted RF1 epoch does not re-latch the refusal.
|
||||
func TestRF1Only_StaleRF2AfterNewerRF1DoesNotRelatch(t *testing.T) {
|
||||
f := newRF1BackendHost(t)
|
||||
f.h.applyFact(rf1Fact(2))
|
||||
f.h.applyFact(rf2PrimaryFact(3))
|
||||
f.h.applyFact(rf1Fact(4))
|
||||
if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 {
|
||||
t.Fatalf("RF1@4 not admitted: %v %q adopt=%d", failed, reason, f.a.callCount.Load())
|
||||
}
|
||||
f.h.applyFact(rf2PrimaryFact(3)) // stale replay
|
||||
if failed, reason := f.h.RoleAdmissionFailure(); failed {
|
||||
t.Fatalf("stale RF2@3 re-latched after RF1@4: %q", reason)
|
||||
}
|
||||
f.mustWrite(t, 4, 0xC4)
|
||||
f.h.applyFact(rf2PrimaryFact(4)) // same epoch, peers added: refused
|
||||
if failed, _ := f.h.RoleAdmissionFailure(); !failed {
|
||||
t.Fatal("RF2 at the admitted epoch not refused")
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -981,15 +982,16 @@ func TestStatusServer_DurableStatusEndpoint_EnabledAfterStart_ReturnsLineage(t *
|
||||
}
|
||||
defer func() { _ = s.Close(context.Background()) }()
|
||||
s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{
|
||||
VolumeID: "v1",
|
||||
Path: "/tmp/v1.bin",
|
||||
Impl: "smartwal",
|
||||
ReplicaID: "r1",
|
||||
Epoch: 1,
|
||||
EndpointVersion: 1,
|
||||
Latched: true,
|
||||
Operational: true,
|
||||
Evidence: "recovered LSN=0",
|
||||
VolumeID: "v1",
|
||||
Path: "/tmp/v1.bin",
|
||||
Impl: "smartwal",
|
||||
ReplicaID: "r1",
|
||||
Epoch: 1,
|
||||
EndpointVersion: 1,
|
||||
Latched: true,
|
||||
Operational: true,
|
||||
Evidence: "recovered LSN=0",
|
||||
CheckpointPersistence: &storage.CheckpointPersistenceStatus{Successes: 3, Refusals: 2, Failures: 1},
|
||||
}}})
|
||||
|
||||
resp, err := http.Get("http://" + addr + "/status/durable?volume=v1")
|
||||
@@ -1015,6 +1017,10 @@ func TestStatusServer_DurableStatusEndpoint_EnabledAfterStart_ReturnsLineage(t *
|
||||
if len(body.Volumes) != 1 || !body.Volumes[0].Latched || !body.Volumes[0].Operational || body.Volumes[0].Epoch != 1 {
|
||||
t.Fatalf("unexpected durable volume body: %+v", body.Volumes)
|
||||
}
|
||||
checkpoint := body.Volumes[0].CheckpointPersistence
|
||||
if checkpoint == nil || checkpoint.Successes != 3 || checkpoint.Refusals != 2 || checkpoint.Failures != 1 {
|
||||
t.Fatalf("checkpoint counters missing from HTTP response: %+v", checkpoint)
|
||||
}
|
||||
}
|
||||
|
||||
func TestG9B_StatusProjection_ReturnedReplicaCanBeDurableReadyButFrontendNotReady(t *testing.T) {
|
||||
|
||||
@@ -119,6 +119,25 @@ func validateWorkspaceBinding(b WorkspaceBinding) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateWorkspaceEndpoints applies a binding's endpoint rules (host:port
|
||||
// with a numeric port 1..65535, data and ctrl distinct) without registering
|
||||
// anything.
|
||||
func ValidateWorkspaceEndpoints(b WorkspaceBinding) error { return validateWorkspaceBinding(b) }
|
||||
|
||||
// WorkspaceEndpointHost returns addr's host in canonical form (equivalent IP
|
||||
// spellings compare equal; names lower-cased; no DNS), or "" if addr is not
|
||||
// host:port.
|
||||
func WorkspaceEndpointHost(addr string) string {
|
||||
h, _, err := net.SplitHostPort(addr)
|
||||
if err != nil || h == "" {
|
||||
return ""
|
||||
}
|
||||
if ip := net.ParseIP(h); ip != nil {
|
||||
return ip.String()
|
||||
}
|
||||
return strings.ToLower(h)
|
||||
}
|
||||
|
||||
// Compare numeric ports and equivalent IP spellings without DNS/network I/O.
|
||||
func workspaceEndpointKey(addr string) string {
|
||||
h, p, err := net.SplitHostPort(addr)
|
||||
|
||||
@@ -196,7 +196,7 @@ func (s *receiverAckStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error
|
||||
|
||||
func (s *receiverAckStore) WriteExtentDirect(lba uint32, data []byte) error { return nil }
|
||||
|
||||
func (s *receiverAckStore) AllBlocks() map[uint32][]byte { return nil }
|
||||
func (s *receiverAckStore) AllBlocks() (map[uint32][]byte, error) { return nil, nil }
|
||||
|
||||
func (s *receiverAckStore) ScanLBAs(fromLSN uint64, fn func(storage.RecoveryEntry) error) error {
|
||||
return nil
|
||||
|
||||
@@ -793,7 +793,10 @@ func (c *Cluster) allConverged() bool {
|
||||
}
|
||||
|
||||
func (c *Cluster) replicaConverged(r *ReplicaNode) bool {
|
||||
pBlocks := c.primary.Store.AllBlocks()
|
||||
pBlocks, err := c.primary.Store.AllBlocks()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for lba, pData := range pBlocks {
|
||||
rData, _ := r.Store.Read(lba)
|
||||
if !bytes.Equal(pData, rData) {
|
||||
@@ -816,7 +819,10 @@ func (c *Cluster) divergenceReport() string {
|
||||
|
||||
func (c *Cluster) divergenceReportFor(r *ReplicaNode) string {
|
||||
var diffs []string
|
||||
pBlocks := c.primary.Store.AllBlocks()
|
||||
pBlocks, err := c.primary.Store.AllBlocks()
|
||||
if err != nil {
|
||||
return fmt.Sprintf("primary snapshot failed: %v", err)
|
||||
}
|
||||
for lba, pData := range pBlocks {
|
||||
rData, _ := r.Store.Read(lba)
|
||||
if !bytes.Equal(pData, rData) {
|
||||
|
||||
@@ -423,7 +423,7 @@ func (s *WALStore) applyEntryV3(lba uint32, data []byte, lsn uint64, installLane
|
||||
return fmt.Errorf("%w: %d above %d", ErrInstallLSNGap, lsn, anchor)
|
||||
}
|
||||
dataCopy := append([]byte(nil), data...)
|
||||
phys, err := s.appendWriteV3(lba, dataCopy, lsn)
|
||||
phys, err := s.appendWriteV3(lba, dataCopy, lsn, nil)
|
||||
s.walMutation.Add(1)
|
||||
if err != nil {
|
||||
if installLane && errors.Is(err, errWALFull) {
|
||||
@@ -517,6 +517,7 @@ func (s *WALStore) markBaseCompleteV3(id [16]byte) error {
|
||||
v.syncMu.Lock()
|
||||
defer v.syncMu.Unlock()
|
||||
if !v.flushLifetimeValidV3(gen) {
|
||||
prepared.abandonV3()
|
||||
return ErrMapCoverageStale // a recovery or reset ran meanwhile
|
||||
}
|
||||
installed := func(n *descriptorV3) error {
|
||||
@@ -633,7 +634,15 @@ func (s *WALStore) markMapUnknownV3(lba uint64) {
|
||||
if v.ownedMap == nil {
|
||||
return
|
||||
}
|
||||
v.mapEntries[lba/v.ownedMap.chunkBlocks].Unknown = true
|
||||
e := &v.mapEntries[lba/v.ownedMap.chunkBlocks]
|
||||
e.Unknown = true
|
||||
// A BASE byte has no WAL record: inherit its image frontier, not an
|
||||
// unrelated later write. Keep UNKNOWN conservative as before.
|
||||
birth := s.nextLSN - 1
|
||||
if d := v.pub.current(); d.BaseState == BaseInstalling {
|
||||
birth = d.BaseLSN
|
||||
}
|
||||
e.LSN = max(e.LSN, birth)
|
||||
}
|
||||
|
||||
// InstalledBaseLSN reports a completed local BASE obligation, not a normal
|
||||
|
||||
@@ -0,0 +1,705 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) {
|
||||
s, _ := newMappedCheckpointStoreV3(t)
|
||||
remote := newFakeChunkRemote()
|
||||
mustAttach(t, s, remote, ctConfig(1))
|
||||
if _, err := s.Write(0, blk(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
realSync := s.v3.ownedMap.syncFile
|
||||
t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync })
|
||||
refusals := 0
|
||||
previousCP := uint64(0)
|
||||
for round := uint32(0); round < 8; round++ {
|
||||
injected := false
|
||||
s.v3.ownedMap.syncFile = func() error {
|
||||
if !injected {
|
||||
injected = true
|
||||
if _, err := s.Write(round+1, blk(byte(round+2))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return realSync()
|
||||
}
|
||||
err := s.flusher.flushOnce()
|
||||
s.v3.ownedMap.syncFile = realSync
|
||||
if err != nil && !errors.Is(err, ErrMapCoverageStale) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if errors.Is(err, ErrMapCoverageStale) {
|
||||
refusals++
|
||||
}
|
||||
if !injected {
|
||||
t.Fatal("cycle did not overlap a write")
|
||||
}
|
||||
if cp := s.CheckpointLSN(); cp <= previousCP {
|
||||
t.Fatalf("cycle %d: checkpoint %d did not advance beyond %d", round, cp, previousCP)
|
||||
} else {
|
||||
previousCP = cp
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
cp := s.CheckpointLSN()
|
||||
t.Logf("continuous writes: cycles8 refusals%d cp%d wack%d dirty%d", refusals, cp, s.v3.wack.Load(), s.dm.len())
|
||||
if cp == 0 {
|
||||
t.Fatal("checkpoint made no progress across eight completed extent/map persistence cycles while newer appends continued")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix(t *testing.T) {
|
||||
s, path := newMappedCheckpointStoreV3(t)
|
||||
remote := newFakeChunkRemote()
|
||||
layer := mustAttach(t, s, remote, ctConfig(1))
|
||||
if _, err := s.Write(1, blk(0x11)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.v3.testMapPrepared = func() {
|
||||
if _, err := s.WriteBatch(1, [][]byte{blk(0xB2), blk(0xC3)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.v3.testMapPrepared = nil
|
||||
d := s.v3.pub.current()
|
||||
if d.CheckpointLSN != 1 || d.MapCoveredCheckpoint != 1 || s.dm.len() != 2 {
|
||||
t.Fatalf("prefix cp=%d C=%d dirty=%d", d.CheckpointLSN, d.MapCoveredCheckpoint, s.dm.len())
|
||||
}
|
||||
if err := layer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
s.mu.Lock()
|
||||
s.closed = true
|
||||
s.mu.Unlock()
|
||||
r, err := openWALStoreV3ForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err = r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for lba, want := range map[uint32][]byte{1: blk(0xB2), 2: blk(0xC3)} {
|
||||
if !bytes.Equal(readV3(t, r, lba), want) {
|
||||
t.Fatalf("replayed LBA%d lost", lba)
|
||||
}
|
||||
}
|
||||
restored := mustAttach(t, r, remote, ctConfig(1))
|
||||
cut, err := restored.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
image := remote.imageOf(t, cut.Head)
|
||||
if !bytes.Equal(image[4096:8192], blk(0xB2)) || !bytes.Equal(image[8192:12288], blk(0xC3)) {
|
||||
t.Fatal("capture omitted newer replayed batch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof(t *testing.T) {
|
||||
s, _ := newMappedCheckpointStoreV3(t)
|
||||
h := beginV3(t, s, 0, idA)
|
||||
cp := s.CheckpointLSN()
|
||||
prepared, err := s.prepareOwnedMapCheckpointV3(cp)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := s.v3.pub.current()
|
||||
if err = h.WriteBase(1, blk(0xA7)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); !errors.Is(err, ErrMapCoverageStale) {
|
||||
t.Fatalf("effective BASE mutation proof accepted: %v", err)
|
||||
}
|
||||
if s.v3.pub.current() != before {
|
||||
t.Fatal("stale BASE candidate changed slots")
|
||||
}
|
||||
}
|
||||
|
||||
// Removing append-driven increments must not bypass terminal exhaustion.
|
||||
func TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend(t *testing.T) {
|
||||
for _, batch := range []bool{false, true} {
|
||||
s, _ := newMappedCheckpointStoreV3(t)
|
||||
before := s.NextLSN()
|
||||
s.v3.mapProof.mutation.Store(counterMaxV3)
|
||||
var err error
|
||||
if batch {
|
||||
_, err = s.WriteBatch(1, [][]byte{blk(1), blk(2)})
|
||||
} else {
|
||||
_, err = s.Write(1, blk(1))
|
||||
}
|
||||
if !errors.Is(err, ErrCounterExhausted) || s.NextLSN() != before || s.dm.len() != 0 {
|
||||
t.Fatalf("exhaustion bypassed: batch=%t err=%v next=%d dirty=%d", batch, err, s.NextLSN(), s.dm.len())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A write's real fallback rollover can run after a map candidate was prepared.
|
||||
// It preserves the older prefix and the later append remains available to replay.
|
||||
func TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix(t *testing.T) {
|
||||
s, path := newMappedCheckpointStoreV3(t)
|
||||
s.SetRecoveryRetentionLSNs(1)
|
||||
writeSynced(t, s, 1, 2)
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prepared, err := s.prepareOwnedMapCheckpointV3(2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tail := s.v3.w.reclaimThroughV3(2)
|
||||
before := s.v3.pub.current()
|
||||
if tail <= before.RetainedTail {
|
||||
t.Fatal("setup: no releasable retained record")
|
||||
}
|
||||
// One real slot publication advances the current tail only. The next Write
|
||||
// must bring the fallback forward before it can reuse that released range.
|
||||
if _, err := s.v3.pub.publish(nil, nil, func(d *descriptorV3) error {
|
||||
d.RetainedTail = tail
|
||||
d.RetainedHead = max(d.RetainedHead, tail)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current, floor, ok := s.v3.pub.walSnapshotV3()
|
||||
if !ok || floor >= tail {
|
||||
t.Fatal("setup: fallback did not pin rollover")
|
||||
}
|
||||
if lsn, err := s.Write(3, blk(0xD3)); err != nil || lsn != 3 {
|
||||
t.Fatalf("write: lsn %d err %v", lsn, err)
|
||||
}
|
||||
after := s.v3.pub.current()
|
||||
if after.SlotGen != current.SlotGen+1 {
|
||||
t.Fatal("Write did not execute the fallback rollover")
|
||||
}
|
||||
if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil {
|
||||
t.Fatalf("prefix publication after rollover: %v", err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, floor, ok := s.v3.pub.walSnapshotV3()
|
||||
if !ok || d.CheckpointLSN != 2 || d.MapCoveredCheckpoint != 2 || d.W < 3 || floor != tail || d.RetainedTail != tail {
|
||||
t.Fatalf("prefix/suffix boundary: cp%d C%d W%d floor%d tail%d want%d", d.CheckpointLSN, d.MapCoveredCheckpoint, d.W, floor, d.RetainedTail, tail)
|
||||
}
|
||||
s.SetRecoveryRetentionLSNs(1)
|
||||
var scanned []RecoveryEntry
|
||||
if err := s.ScanLBAs(3, func(e RecoveryEntry) error { scanned = append(scanned, e); return nil }); err != nil || len(scanned) != 1 || scanned[0].LSN != 3 || !bytes.Equal(scanned[0].Data, blk(0xD3)) {
|
||||
t.Fatalf("retained suffix: %+v err %v", scanned, err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
s.mu.Lock()
|
||||
s.closed = true
|
||||
s.mu.Unlock()
|
||||
r, err := openWALStoreV3ForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(readV3(t, r, 3), blk(0xD3)) {
|
||||
t.Fatal("retained suffix lost after reopen")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "hydrating")
|
||||
s, err := createMappedWALStoreV3ForTest(path, ctNumBlocks, ctBlockSize, v3TestWAL, WModeStrict, ctChunkBlocks)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
image := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
copy(image[9*ctBlockSize:], blk(0xA9))
|
||||
remote := newFakeChunkRemote()
|
||||
remote.seedHead(t, image, 10, 1)
|
||||
if err := s.SeedChunkFrontier(10); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := ctConfig(2)
|
||||
cfg.FreshFromHead = true
|
||||
layer := mustAttach(t, s, remote, cfg).(*chunkLayerImpl)
|
||||
prepared, err := s.prepareOwnedMapCheckpointV3(10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
layer.stMu.Lock()
|
||||
absent := layer.absent[2]
|
||||
layer.stMu.Unlock()
|
||||
if !absent {
|
||||
t.Fatal("setup: chunk is not absent")
|
||||
}
|
||||
if got, err := s.Read(9); err != nil || !bytes.Equal(got, blk(0xA9)) {
|
||||
t.Fatalf("lazy read: %v", err)
|
||||
}
|
||||
layer.stMu.Lock()
|
||||
absent = layer.absent[2]
|
||||
layer.stMu.Unlock()
|
||||
if absent {
|
||||
t.Fatal("read did not hydrate chunk")
|
||||
}
|
||||
if !prepared.proof.validV3(s.v3.mapProof) {
|
||||
t.Fatal("lazy fill invalidated the checkpoint prefix")
|
||||
}
|
||||
if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil {
|
||||
t.Fatalf("publish after lazy fill: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// At every cycle the ring reaches the real admission soft-pressure range.
|
||||
// An append overlaps map persistence, yet each completed cycle must reclaim;
|
||||
// none may require a cut or new remote HEAD to escape repeated proof refusal.
|
||||
func TestChunkLayerV3_CheckpointProgressAtWALPressure(t *testing.T) {
|
||||
for _, mode := range []WMode{WModeStrict, WModeLagged} {
|
||||
t.Run(map[WMode]string{WModeStrict: "A", WModeLagged: "C"}[mode], func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "pressure")
|
||||
s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 64*1024, mode, 4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
mustAttach(t, s, newFakeChunkRemote(), ctConfig(1))
|
||||
realSync := s.v3.ownedMap.syncFile
|
||||
t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync })
|
||||
previousCP := uint64(0)
|
||||
expected := make(map[uint32][]byte)
|
||||
write := func() error {
|
||||
lsn := s.NextLSN()
|
||||
lba := uint32(lsn % 64)
|
||||
data := checkpointProgressBlock(lsn)
|
||||
if _, err := s.Write(lba, data); err != nil {
|
||||
return err
|
||||
}
|
||||
expected[lba] = data
|
||||
return nil
|
||||
}
|
||||
for cycle := 0; cycle < 8; cycle++ {
|
||||
for s.walUsedFraction() < 0.72 {
|
||||
if err := write(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
injected := false
|
||||
s.v3.ownedMap.syncFile = func() error {
|
||||
if !injected {
|
||||
injected = true
|
||||
if err := write(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return realSync()
|
||||
}
|
||||
err := s.flusher.flushOnce()
|
||||
s.v3.ownedMap.syncFile = realSync
|
||||
if err != nil {
|
||||
t.Fatalf("pressure cycle%d: %v", cycle, err)
|
||||
}
|
||||
cp := s.CheckpointLSN()
|
||||
if !injected || cp <= previousCP {
|
||||
t.Fatalf("no progress cycle%d cp%d previous%d", cycle, cp, previousCP)
|
||||
}
|
||||
previousCP = cp
|
||||
}
|
||||
floor, ok := s.v3.pub.reuseFloor()
|
||||
if !ok || floor < 5*64*1024 {
|
||||
t.Fatalf("no sustained ring reuse: floor%d", floor)
|
||||
}
|
||||
for lba, want := range expected {
|
||||
if got, err := s.Read(lba); err != nil || !bytes.Equal(got, want) {
|
||||
t.Fatalf("no-Flush readback LBA%d: %v", lba, err)
|
||||
}
|
||||
}
|
||||
t.Logf("no client Sync: cycles8 checkpoint%d floor%d busy0", previousCP, floor)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func checkpointProgressBlock(lsn uint64) []byte {
|
||||
data := make([]byte, 4096)
|
||||
for i := 0; i < len(data); i += 8 {
|
||||
binary.LittleEndian.PutUint64(data[i:i+8], lsn*4096+uint64(i))
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// An active history pin gives one bounded, typed refusal; local flusher work
|
||||
// after releasing it restores progress without a client Sync or new remote cut.
|
||||
func TestCheckpointV3_NoFlushPressureWithRealPin(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "pinned")
|
||||
s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 64*1024, WModeStrict, 4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
mustAttach(t, s, newFakeChunkRemote(), ctConfig(1))
|
||||
s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 0, anyActive: true})
|
||||
expected := make(map[uint32][]byte)
|
||||
for s.walUsedFraction() < 0.90 {
|
||||
lsn := s.NextLSN()
|
||||
lba := uint32(lsn)
|
||||
data := checkpointProgressBlock(lsn)
|
||||
if _, err := s.Write(lba, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected[lba] = data
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.CheckpointLSN() != 0 || s.v3.wack.Load() == 0 {
|
||||
t.Fatal("real retention pin did not constrain an internally synced checkpoint")
|
||||
}
|
||||
next := s.NextLSN()
|
||||
start := time.Now()
|
||||
_, err = s.Write(uint32(next), checkpointProgressBlock(next))
|
||||
elapsed := time.Since(start)
|
||||
if !errors.Is(err, ErrWALPressureTimeout) || elapsed >= 5*time.Second || s.NextLSN() != next {
|
||||
t.Fatalf("pinned busy: err%v elapsed%v next%d want%d", err, elapsed, s.NextLSN(), next)
|
||||
}
|
||||
count := 0
|
||||
if err := s.ScanLBAs(1, func(e RecoveryEntry) error {
|
||||
count++
|
||||
if e.LSN != uint64(count) || !bytes.Equal(e.Data, expected[e.LBA]) {
|
||||
return errors.New("pinned retained prefix differs from submitted bytes")
|
||||
}
|
||||
return nil
|
||||
}); err != nil || count != len(expected) {
|
||||
t.Fatalf("pinned exact prefix count%d want%d: %v", count, len(expected), err)
|
||||
}
|
||||
s.SetRecycleFloorSource(nil)
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
} // no Write/Sync wakes it
|
||||
if s.CheckpointLSN() != next-1 {
|
||||
t.Fatal("released pin did not permit passive local checkpoint progress")
|
||||
}
|
||||
if lsn, err := s.Write(uint32(next), checkpointProgressBlock(next)); err != nil || lsn != next {
|
||||
t.Fatalf("retry: %d %v", lsn, err)
|
||||
}
|
||||
expected[uint32(next)] = checkpointProgressBlock(next)
|
||||
for lba, want := range expected {
|
||||
if got, err := s.Read(lba); err != nil || !bytes.Equal(got, want) {
|
||||
t.Fatalf("pinned readback LBA%d: %v", lba, err)
|
||||
}
|
||||
}
|
||||
t.Logf("busy1 elapsed%v retained%d checkpoint%d", elapsed, count, s.CheckpointLSN())
|
||||
}
|
||||
|
||||
func TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate(t *testing.T) {
|
||||
s, _ := newMappedCheckpointStoreV3(t)
|
||||
s.SetRecoveryRetentionLSNs(1)
|
||||
writeSynced(t, s, 1, 2)
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prepared, err := s.prepareOwnedMapCheckpointV3(2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tail := s.v3.w.reclaimThroughV3(2)
|
||||
if _, err := s.v3.pub.publish(nil, nil, func(d *descriptorV3) error {
|
||||
d.RetainedTail = tail
|
||||
d.RetainedHead = max(d.RetainedHead, tail)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := s.v3.pub.current()
|
||||
_, floor, ok := s.v3.pub.walSnapshotV3()
|
||||
if !ok || floor >= tail {
|
||||
t.Fatal("setup: no pinned fallback")
|
||||
}
|
||||
injected := errors.New("append rollover slot fault")
|
||||
s.v3.testBeforeSlotWrite = func() error { return injected }
|
||||
_, err = s.Write(3, blk(0xD3))
|
||||
s.v3.testBeforeSlotWrite = nil
|
||||
if !errors.Is(err, injected) || s.stickyIOFault() == nil || s.NextLSN() != 3 || s.dm.len() != 0 {
|
||||
t.Fatalf("rollover fault: %v next%d dirty%d", err, s.NextLSN(), s.dm.len())
|
||||
}
|
||||
if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil {
|
||||
t.Fatal("held candidate published through sticky rollover failure")
|
||||
}
|
||||
if s.v3.pub.current() != before {
|
||||
t.Fatal("rollover fault changed authoritative tuple")
|
||||
}
|
||||
if nextFloor, valid := s.v3.pub.reuseFloor(); valid || nextFloor != 0 {
|
||||
t.Fatal("uncertain rollover must disable reuse until reopen")
|
||||
}
|
||||
}
|
||||
|
||||
// Max-LSN map entries may include unsynced writes above both cp and W. A
|
||||
// reused LSN can then set UNKNOWN without changing the prefix proof token.
|
||||
func TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix(t *testing.T) {
|
||||
s, path := newMappedCheckpointStoreV3(t)
|
||||
remote := newFakeChunkRemote()
|
||||
layer := mustAttach(t, s, remote, ctConfig(1))
|
||||
if _, err := s.Write(1, blk(0xA1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layer.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.v3.mapEntries[0].Unknown {
|
||||
t.Fatal("setup: initial definite cut did not clear UNKNOWN")
|
||||
}
|
||||
if _, err := s.Write(1, blk(0xA2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(1, blk(0xA3)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prepared, err := s.prepareOwnedMapCheckpointV3(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := s.v3.pub.current()
|
||||
e := prepared.candidate.entries[0]
|
||||
if e.LSN != 3 || e.Unknown || d.CheckpointLSN != 1 || d.W != 1 {
|
||||
t.Fatalf("speculative maximum: entry%+v cp%d W%d", e, d.CheckpointLSN, d.W)
|
||||
}
|
||||
if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := layer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
s.mu.Lock()
|
||||
s.closed = true
|
||||
s.mu.Unlock()
|
||||
damageRecord(t, path, 2) // unacknowledged record2 tears; the following3 is dropped
|
||||
r, err := openWALStoreV3ForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.NextLSN() != 2 || r.v3.mapEntries[0].LSN != 3 {
|
||||
t.Fatal("dropped suffix did not leave the conservative persisted maximum")
|
||||
}
|
||||
held, err := r.prepareOwnedMapCheckpointV3(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if held.candidate.entries[0].Unknown {
|
||||
t.Fatal("setup: held candidate already UNKNOWN")
|
||||
}
|
||||
if lsn, err := r.Write(1, blk(0xB2)); err != nil || lsn != 2 {
|
||||
t.Fatalf("reused LSN: %d %v", lsn, err)
|
||||
}
|
||||
if !r.v3.mapEntries[0].Unknown || r.v3.mapEntries[0].LSN != 3 {
|
||||
t.Fatal("reused LSN did not conservatively set UNKNOWN beneath the high maximum")
|
||||
}
|
||||
if !held.proof.validV3(r.v3.mapProof) {
|
||||
t.Fatal("reused ordered append invalidated the older prefix")
|
||||
}
|
||||
if _, err := r.v3.pub.publishMapV3(&r.mu, nil, held, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, r)
|
||||
r.mu.Lock()
|
||||
r.closed = true
|
||||
r.mu.Unlock()
|
||||
r2, err := openWALStoreV3ForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r2.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r2.Close() })
|
||||
if _, err := r2.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !r2.v3.mapEntries[0].Unknown || !bytes.Equal(readV3(t, r2, 1), blk(0xB2)) {
|
||||
t.Fatal("replay did not restore UNKNOWN and exact reused-LSN bytes")
|
||||
}
|
||||
restored := mustAttach(t, r2, remote, ctConfig(2))
|
||||
cut, err := restored.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
image := remote.imageOf(t, cut.Head)
|
||||
if !bytes.Equal(image[4096:8192], blk(0xB2)) {
|
||||
t.Fatal("capture treated the speculative maximum as remotely clean")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) {
|
||||
for _, flush := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "wal", true: "extent"}[flush], func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "hydrating")
|
||||
s, err := createMappedWALStoreV3ForTest(path, ctNumBlocks, ctBlockSize, v3TestWAL, WModeStrict, ctChunkBlocks)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
image := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
copy(image[8*ctBlockSize:], blk(0xA8))
|
||||
copy(image[9*ctBlockSize:], blk(0xA9))
|
||||
remote := newFakeChunkRemote()
|
||||
remote.seedHead(t, image, 10, 1)
|
||||
if err := s.SeedChunkFrontier(10); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := ctConfig(2)
|
||||
cfg.FreshFromHead = true
|
||||
layer := mustAttach(t, s, remote, cfg)
|
||||
held, err := s.prepareOwnedMapCheckpointV3(10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entered, release := holdNextGet(t, remote)
|
||||
done := make(chan error, 1)
|
||||
joined := make(chan struct{})
|
||||
// Release the fetch before joining, including failures before release().
|
||||
// Register before launch so store/layer cleanup never precedes the join.
|
||||
t.Cleanup(func() {
|
||||
release()
|
||||
select {
|
||||
case <-joined:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Errorf("held hydration reader did not settle within %v after release", ctLocalBound)
|
||||
}
|
||||
})
|
||||
go func() {
|
||||
defer close(joined)
|
||||
got, err := s.Read(9)
|
||||
if err == nil && !bytes.Equal(got, blk(0xB9)) {
|
||||
err = errors.New("held read did not return newer local bytes")
|
||||
}
|
||||
done <- err
|
||||
}()
|
||||
waitKey(t, entered, "cold fill before a competing local write")
|
||||
within(t, "local write and optional flush while hydration is held", func() error {
|
||||
if _, err := s.Write(9, blk(0xB9)); err != nil {
|
||||
return err
|
||||
}
|
||||
if flush {
|
||||
if _, err := s.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.flusher.flushOnce()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
dirty := s.dm.len()
|
||||
release()
|
||||
if err := waitErr(t, done, "fill and post-miss WAL recheck"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.dm.len() != dirty || !held.proof.validV3(s.v3.mapProof) {
|
||||
t.Fatal("hydration manufactured logical dirt or invalidated the prefix proof")
|
||||
}
|
||||
before := s.v3.pub.current()
|
||||
_, err = s.v3.pub.publishMapV3(&s.mu, nil, held, nil)
|
||||
if flush {
|
||||
if !errors.Is(err, ErrMapCoverageStale) || s.v3.pub.current() != before {
|
||||
t.Fatalf("superseded candidate after flush: %v", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Cover the hydrated extent bytes too before the reopen oracle.
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(readV3(t, s, 8), blk(0xA8)) || !bytes.Equal(readV3(t, s, 9), blk(0xB9)) {
|
||||
t.Fatal("HEAD fill or local write was overwritten")
|
||||
}
|
||||
if err := layer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
s.mu.Lock()
|
||||
s.closed = true
|
||||
s.mu.Unlock()
|
||||
r, err := openWALStoreV3ForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(readV3(t, r, 8), blk(0xA8)) || !bytes.Equal(readV3(t, r, 9), blk(0xB9)) {
|
||||
t.Fatal("reopen lost exact hydrated/local bytes")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof(t *testing.T) {
|
||||
s, _ := newMappedCheckpointStoreV3(t)
|
||||
layer := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1))
|
||||
writeSynced(t, s, 1, 1)
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
held, err := s.prepareOwnedMapCheckpointV3(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !s.v3.mapEntries[0].Unknown {
|
||||
t.Fatal("setup: no UNKNOWN to clear")
|
||||
}
|
||||
if _, err := layer.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.v3.mapEntries[0].Unknown {
|
||||
t.Fatal("definite cut did not clear UNKNOWN")
|
||||
}
|
||||
// Inspect the proof itself so the newer map generation cannot mask a missing
|
||||
// clear-invalidation guard in the publication refusal below.
|
||||
if held.proof.validV3(s.v3.mapProof) {
|
||||
t.Fatal("capture UNKNOWN clearing left the old proof valid")
|
||||
}
|
||||
before := s.v3.pub.current()
|
||||
if _, err := s.v3.pub.publishMapV3(&s.mu, nil, held, nil); !errors.Is(err, ErrMapCoverageStale) {
|
||||
t.Fatalf("old capture proof: %v", err)
|
||||
}
|
||||
if s.v3.pub.current() != before {
|
||||
t.Fatal("capture-stale candidate changed a slot")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CheckpointPersistenceStatus counts flusher checkpoint calls in this open.
|
||||
// Success includes a safely clamped/unchanged checkpoint; it is not a slot-write
|
||||
// count. Advances counts only the successes that moved the persisted
|
||||
// CheckpointLSN, and LastAdvance is when the latest one did (zero: none in
|
||||
// this open), so a starved checkpoint shows Successes rising while
|
||||
// LastAdvance stays frozen. Fields are cumulative atomic observations, not a
|
||||
// coherent frontier.
|
||||
type CheckpointPersistenceStatus struct {
|
||||
Successes uint64
|
||||
Refusals uint64
|
||||
Failures uint64
|
||||
CheckpointLSN uint64
|
||||
Advances uint64
|
||||
LastAdvance time.Time
|
||||
}
|
||||
|
||||
func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus {
|
||||
if s.flusher == nil {
|
||||
return CheckpointPersistenceStatus{CheckpointLSN: s.CheckpointLSN()}
|
||||
}
|
||||
i := &s.flusher.instr
|
||||
st := CheckpointPersistenceStatus{
|
||||
Successes: i.checkpointSuccesses.Load(),
|
||||
Refusals: i.checkpointRefusals.Load(),
|
||||
Failures: i.checkpointFailures.Load(),
|
||||
CheckpointLSN: s.CheckpointLSN(),
|
||||
Advances: i.checkpointAdvances.Load(),
|
||||
}
|
||||
if ns := i.checkpointLastAdvanceNanos.Load(); ns != 0 {
|
||||
st.LastAdvance = time.Unix(0, ns)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// recordCheckpoint classifies one flusher checkpoint call; before and after
|
||||
// are the persisted CheckpointLSN around it.
|
||||
func (i *flusherInstrumentation) recordCheckpoint(err error, before, after uint64, now time.Time) {
|
||||
switch {
|
||||
case err == nil:
|
||||
i.checkpointSuccesses.Add(1)
|
||||
if after > before {
|
||||
i.checkpointAdvances.Add(1)
|
||||
i.checkpointLastAdvanceNanos.Store(now.UnixNano())
|
||||
}
|
||||
case errors.Is(err, ErrMapCoverageStale):
|
||||
i.checkpointRefusals.Add(1)
|
||||
default:
|
||||
i.checkpointFailures.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
type mapCoverageRefusal string
|
||||
|
||||
func (r mapCoverageRefusal) Error() string { return ErrMapCoverageStale.Error() + ": " + string(r) }
|
||||
func (r mapCoverageRefusal) Unwrap() error { return ErrMapCoverageStale }
|
||||
|
||||
// Owned exclusively by the flusher run loop; no storage lock or I/O ordering
|
||||
// changes. Terminal errors are never rate limited.
|
||||
type checkpointLogLimiter struct {
|
||||
last time.Time
|
||||
suppressed uint64
|
||||
}
|
||||
|
||||
func (l *checkpointLogLimiter) report(err error, now time.Time) {
|
||||
if !errors.Is(err, ErrMapCoverageStale) {
|
||||
log.Printf("storage: flusher: %v", err)
|
||||
return
|
||||
}
|
||||
if !l.last.IsZero() && now.Sub(l.last) < 30*time.Second {
|
||||
l.suppressed++
|
||||
return
|
||||
}
|
||||
var reason mapCoverageRefusal
|
||||
if !errors.As(err, &reason) {
|
||||
reason = "unspecified"
|
||||
}
|
||||
log.Printf("storage: flusher: checkpoint deferred reason=%s suppressed=%d: %v", string(reason), l.suppressed, err)
|
||||
l.last, l.suppressed = now, 0
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) {
|
||||
s, _ := newMappedCheckpointStoreV3(t)
|
||||
mustAttach(t, s, newFakeChunkRemote(), ctConfig(1))
|
||||
writeSynced(t, s, 1, 1)
|
||||
s.v3.testMapPrepared = func() {
|
||||
if _, err := s.Write(2, blk(2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Simulate the effective-mutation class; newer WAL appends alone are safe.
|
||||
if err := s.v3.mapProof.mutatedV3(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
before := s.v3.pub.current()
|
||||
err := s.flusher.flushOnce()
|
||||
if !errors.Is(err, ErrMapCoverageStale) {
|
||||
t.Fatalf("refusal: %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "proof_changed") {
|
||||
t.Errorf("missing refusal reason: %v", err)
|
||||
}
|
||||
if s.v3.pub.current() != before || s.dm.len() != 2 || s.stickyIOFault() != nil {
|
||||
t.Fatal("refusal changed publication/retry/fault state")
|
||||
}
|
||||
raw, _ := json.Marshal(s.FlusherInstrumentation())
|
||||
var counts map[string]uint64
|
||||
if err := json.Unmarshal(raw, &counts); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if counts["CheckpointRefusals"] != 1 || counts["CheckpointSuccesses"] != 0 {
|
||||
t.Fatalf("refusal counters: %s", raw)
|
||||
}
|
||||
s.v3.testMapPrepared = nil
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ = json.Marshal(s.FlusherInstrumentation())
|
||||
if err := json.Unmarshal(raw, &counts); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if counts["CheckpointRefusals"] != 1 || counts["CheckpointSuccesses"] != 1 || s.CheckpointLSN() != 2 || s.dm.len() != 0 {
|
||||
t.Fatalf("retry counters/state: %s cp=%d", raw, s.CheckpointLSN())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckpointDiagnostics_PrepareRefusalAndIOFailure(t *testing.T) {
|
||||
for _, fault := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(fault), func(t *testing.T) {
|
||||
s, _ := newMappedCheckpointStoreV3(t)
|
||||
mustAttach(t, s, newFakeChunkRemote(), ctConfig(1))
|
||||
writeSynced(t, s, 1, 1)
|
||||
realSync := s.v3.ownedMap.syncFile
|
||||
injected := errors.New("checkpoint map fsync fault")
|
||||
once := false
|
||||
s.v3.ownedMap.syncFile = func() error {
|
||||
if fault {
|
||||
return injected
|
||||
}
|
||||
if !once {
|
||||
once = true
|
||||
if _, err := s.Write(2, blk(2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.v3.mapProof.mutatedV3(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return realSync()
|
||||
}
|
||||
err := s.flusher.flushOnce()
|
||||
got := s.CheckpointPersistence()
|
||||
if fault {
|
||||
if !errors.Is(err, injected) || got.Failures != 1 || got.Refusals != 0 || s.stickyIOFault() == nil {
|
||||
t.Fatalf("fault %v counts=%+v", err, got)
|
||||
}
|
||||
} else {
|
||||
if !errors.Is(err, ErrMapCoverageStale) || !strings.Contains(err.Error(), "proof_changed_during_prepare") || got.Refusals != 1 || got.Failures != 0 || s.stickyIOFault() != nil {
|
||||
t.Fatalf("refusal %v counts=%+v", err, got)
|
||||
}
|
||||
}
|
||||
if got.Successes != 0 || s.CheckpointLSN() != 0 || s.dm.len() == 0 {
|
||||
t.Fatal("failed checkpoint advanced or lost retry ownership")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckpointDiagnostics_LogRateLimit(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
old := log.Writer()
|
||||
log.SetOutput(&out)
|
||||
t.Cleanup(func() { log.SetOutput(old) })
|
||||
var limiter checkpointLogLimiter
|
||||
now := time.Unix(100, 0)
|
||||
stale := fmt.Errorf("persist checkpoint: %w", mapCoverageRefusal("proof_changed"))
|
||||
limiter.report(stale, now)
|
||||
for i := 0; i < 5; i++ {
|
||||
limiter.report(stale, now.Add(time.Second))
|
||||
}
|
||||
// A terminal failure must remain visible while refusals are suppressed.
|
||||
terminal := errors.New("real fsync fault")
|
||||
limiter.report(terminal, now.Add(2*time.Second))
|
||||
limiter.report(terminal, now.Add(3*time.Second))
|
||||
limiter.report(stale, now.Add(30*time.Second))
|
||||
got := out.String()
|
||||
if strings.Count(got, "checkpoint deferred") != 2 || strings.Count(got, "real fsync fault") != 2 || !strings.Contains(got, "reason=proof_changed suppressed=5") {
|
||||
t.Fatalf("logs: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A starved checkpoint: flush cycles keep succeeding (clamped to the
|
||||
// acknowledged frontier, nothing persisted moves) while the persisted
|
||||
// CheckpointLSN and the last advance stay frozen. Only a real move of the
|
||||
// persisted checkpoint counts as an advance.
|
||||
func TestCheckpointDiagnostics_StarvedCheckpointIsVisible(t *testing.T) {
|
||||
s, _ := newMappedCheckpointStoreV3(t)
|
||||
mustAttach(t, s, newFakeChunkRemote(), ctConfig(1))
|
||||
writeSynced(t, s, 1, 1)
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := s.CheckpointPersistence()
|
||||
if first.CheckpointLSN != 1 || first.Advances != 1 || first.LastAdvance.IsZero() || first.Successes != 1 {
|
||||
t.Fatalf("first checkpoint: %+v", first)
|
||||
}
|
||||
for i := uint32(0); i < 3; i++ { // written, never synced: the checkpoint is clamped at 1
|
||||
if _, err := s.Write(2+i, blk(byte(2+i))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
starved := s.CheckpointPersistence()
|
||||
if starved.Successes <= first.Successes {
|
||||
t.Fatalf("flush cycles did not keep succeeding: %+v", starved)
|
||||
}
|
||||
if starved.CheckpointLSN != 1 || starved.Advances != 1 || !starved.LastAdvance.Equal(first.LastAdvance) {
|
||||
t.Fatalf("a clamped success counted as an advance: first %+v starved %+v", first, starved)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
moved := s.CheckpointPersistence()
|
||||
if moved.CheckpointLSN != s.CheckpointLSN() || moved.CheckpointLSN <= 1 || moved.Advances != 2 || !moved.LastAdvance.After(first.LastAdvance) {
|
||||
t.Fatalf("after sync the checkpoint advance was not recorded: %+v", moved)
|
||||
}
|
||||
}
|
||||
|
||||
// Only an advancing success moves LastAdvance; an unchanged success, a
|
||||
// refusal and a failure leave the latest advance time as it was.
|
||||
func TestCheckpointDiagnostics_LastAdvanceFollowsOnlyAdvances(t *testing.T) {
|
||||
var i flusherInstrumentation
|
||||
t0 := time.Unix(1000, 0)
|
||||
at := func() time.Time { return time.Unix(0, i.checkpointLastAdvanceNanos.Load()) }
|
||||
i.recordCheckpoint(nil, 0, 5, t0)
|
||||
if !at().Equal(t0) || i.checkpointAdvances.Load() != 1 {
|
||||
t.Fatalf("first advance: %v %d", at(), i.checkpointAdvances.Load())
|
||||
}
|
||||
i.recordCheckpoint(nil, 5, 5, t0.Add(time.Second))
|
||||
i.recordCheckpoint(mapCoverageRefusal("proof_changed"), 5, 5, t0.Add(2*time.Second))
|
||||
i.recordCheckpoint(errors.New("fsync fault"), 5, 5, t0.Add(3*time.Second))
|
||||
if !at().Equal(t0) || i.checkpointAdvances.Load() != 1 {
|
||||
t.Fatalf("a non-advance moved LastAdvance: %v advances=%d", at(), i.checkpointAdvances.Load())
|
||||
}
|
||||
t1 := t0.Add(4 * time.Second)
|
||||
i.recordCheckpoint(nil, 5, 9, t1)
|
||||
if !at().Equal(t1) || i.checkpointAdvances.Load() != 2 {
|
||||
t.Fatalf("second advance: %v %d", at(), i.checkpointAdvances.Load())
|
||||
}
|
||||
if i.checkpointSuccesses.Load() != 3 || i.checkpointRefusals.Load() != 1 || i.checkpointFailures.Load() != 1 {
|
||||
t.Fatalf("classification: s=%d r=%d f=%d", i.checkpointSuccesses.Load(), i.checkpointRefusals.Load(), i.checkpointFailures.Load())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package storage
|
||||
|
||||
// The caller holds captureMu exclusive, with no layer state lock held.
|
||||
// An owned-map max is conservative: recovery can drop an unacked suffix
|
||||
// while retaining its maximum. Bound it by the same-barrier cut frontier;
|
||||
// the captured image has no later writes. Preserve lower inherited births.
|
||||
func (l *chunkLayerImpl) captureBirths(candidates map[uint64]bool, frontier uint64) map[uint64]uint64 {
|
||||
out := make(map[uint64]uint64, len(candidates))
|
||||
l.s.mu.RLock()
|
||||
defer l.s.mu.RUnlock()
|
||||
for idx := range candidates {
|
||||
birth := frontier
|
||||
if l.usesOwnedMapV3() {
|
||||
birth = min(l.s.v3.mapEntries[idx].LSN, frontier)
|
||||
}
|
||||
out[idx] = birth
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Metadata-only maximum-volume/default-chunk shape; no volume-sized image or
|
||||
// device is allocated. This measures the added sampler, not a complete cut.
|
||||
func BenchmarkCaptureBirthsMaxVolumeDefaultChunk(b *testing.B) {
|
||||
const count = 1 << 22 // ceil((16 TiB - 4 KiB) / 4 MiB)
|
||||
candidates := make(map[uint64]bool, count)
|
||||
s := &WALStore{v3: &walStoreV3State{mapEntries: make([]chunkLSNEntryV3, count), mapProof: newMapProofEpochV3()}}
|
||||
for i := uint64(0); i < count; i++ {
|
||||
candidates[i] = true
|
||||
s.v3.mapEntries[i].LSN = i + 1
|
||||
}
|
||||
l := &chunkLayerImpl{s: s}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
s.captureMu.Lock()
|
||||
out := l.captureBirths(candidates, count)
|
||||
s.captureMu.Unlock()
|
||||
if len(out) != count || out[0] != 1 || out[count-1] != count {
|
||||
b.Fatal("worst-shape birth mismatch")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestCaptureBirthsIncludesStoreLockWait(t *testing.T) {
|
||||
s := &WALStore{}
|
||||
l := &chunkLayerImpl{s: s}
|
||||
candidates := map[uint64]bool{0: true}
|
||||
s.mu.Lock()
|
||||
locked := true
|
||||
done := make(chan map[uint64]uint64, 1)
|
||||
t.Cleanup(func() {
|
||||
if locked {
|
||||
s.mu.Unlock()
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("sampler did not join")
|
||||
}
|
||||
})
|
||||
go func() { s.captureMu.Lock(); out := l.captureBirths(candidates, 7); s.captureMu.Unlock(); done <- out }()
|
||||
select {
|
||||
case out := <-done:
|
||||
done <- out
|
||||
t.Fatal("sampler bypassed store lock")
|
||||
case <-time.After(25 * time.Millisecond):
|
||||
}
|
||||
s.mu.Unlock()
|
||||
locked = false
|
||||
select {
|
||||
case out := <-done:
|
||||
done <- out
|
||||
if out[0] != 7 {
|
||||
t.Fatal("legacy frontier changed")
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("sampler did not finish after lock release")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// DroppedSuffixBirthStoreForTest exposes only the recovery fixture to the
|
||||
// external-package regression, which uses chunkstore's real manifest builder.
|
||||
func DroppedSuffixBirthStoreForTest(t *testing.T, remote ChunkRemote) *WALStore {
|
||||
t.Helper()
|
||||
s, path := newMappedCheckpointStoreV3(t)
|
||||
layer := mustAttach(t, s, remote, ctConfig(1))
|
||||
if _, err := s.Write(1, blk(0xA1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layer.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(1, blk(0xA2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(1, blk(0xA3)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prepared, err := s.prepareOwnedMapCheckpointV3(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := s.v3.pub.current()
|
||||
if e := prepared.candidate.entries[0]; e.LSN != 3 || d.CheckpointLSN != 1 || d.W != 1 {
|
||||
t.Fatalf("setup entry%+v cp%d W%d", e, d.CheckpointLSN, d.W)
|
||||
}
|
||||
if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := layer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
s.mu.Lock()
|
||||
s.closed = true
|
||||
s.mu.Unlock()
|
||||
damageRecord(t, path, 2)
|
||||
reopen := func() *WALStore {
|
||||
r, err := openWALStoreV3ForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
r := reopen()
|
||||
if r.NextLSN() != 2 || r.v3.mapEntries[0].LSN != 3 {
|
||||
t.Fatal("missing conservative maximum after dropped suffix")
|
||||
}
|
||||
if n, err := r.Write(1, blk(0xB2)); err != nil || n != 2 {
|
||||
t.Fatalf("reused LSN %d: %v", n, err)
|
||||
}
|
||||
if _, err := r.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, r)
|
||||
r.mu.Lock()
|
||||
r.closed = true
|
||||
r.mu.Unlock()
|
||||
r2 := reopen()
|
||||
if e := r2.v3.mapEntries[0]; e.LSN != 3 || !e.Unknown || r2.NextLSN() != 3 || !bytes.Equal(readV3(t, r2, 1), blk(0xB2)) {
|
||||
t.Fatalf("recovered reused image: entry%+v next%d", e, r2.NextLSN())
|
||||
}
|
||||
return r2
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package storage_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// Only the metadata/blob transports are in memory; capture, recovery,
|
||||
// PrepareManifest, segment encoding, CAS and resolved reads are production.
|
||||
type birthFiler struct {
|
||||
mu sync.Mutex
|
||||
entries map[string]*filerpb.Entry
|
||||
}
|
||||
|
||||
func (f *birthFiler) LookupEntry(_ context.Context, d, n string) (*filerpb.Entry, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
e := f.entries[path.Join(d, n)]
|
||||
if e == nil {
|
||||
return nil, chunkstore.ErrNotFound
|
||||
}
|
||||
return proto.Clone(e).(*filerpb.Entry), nil
|
||||
}
|
||||
func (f *birthFiler) CreateEntry(_ context.Context, d string, e *filerpb.Entry, excl bool) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
k := path.Join(d, e.Name)
|
||||
if excl && f.entries[k] != nil {
|
||||
return chunkstore.ErrExists
|
||||
}
|
||||
f.entries[k] = proto.Clone(e).(*filerpb.Entry)
|
||||
return nil
|
||||
}
|
||||
func (f *birthFiler) UpdateEntry(_ context.Context, d string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
k := path.Join(d, e.Name)
|
||||
old := f.entries[k]
|
||||
if old == nil {
|
||||
return chunkstore.ErrNotFound
|
||||
}
|
||||
for k, v := range expected {
|
||||
if !bytes.Equal(old.Extended[k], v) {
|
||||
return chunkstore.ErrPrecondition
|
||||
}
|
||||
}
|
||||
f.entries[k] = proto.Clone(e).(*filerpb.Entry)
|
||||
return nil
|
||||
}
|
||||
func (f *birthFiler) DeleteEntry(_ context.Context, d, n string, expected map[string][]byte) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
k := path.Join(d, n)
|
||||
for key, v := range expected {
|
||||
if f.entries[k] == nil || !bytes.Equal(f.entries[k].Extended[key], v) {
|
||||
return chunkstore.ErrPrecondition
|
||||
}
|
||||
}
|
||||
delete(f.entries, k)
|
||||
return nil
|
||||
}
|
||||
func (f *birthFiler) ListEntries(_ context.Context, d, prefix, after string, limit uint32) ([]*filerpb.Entry, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
var out []*filerpb.Entry
|
||||
for k, e := range f.entries {
|
||||
if path.Dir(k) == d && strings.HasPrefix(e.Name, prefix) && e.Name > after {
|
||||
out = append(out, proto.Clone(e).(*filerpb.Entry))
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
if limit > 0 && len(out) > int(limit) {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type birthBlobs struct {
|
||||
mu sync.Mutex
|
||||
data map[string][]byte
|
||||
}
|
||||
|
||||
func (b *birthBlobs) Put(_ context.Context, d []byte) (string, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
id := fmt.Sprint(len(b.data) + 1)
|
||||
b.data[id] = bytes.Clone(d)
|
||||
return id, nil
|
||||
}
|
||||
func (b *birthBlobs) Get(_ context.Context, id string) ([]byte, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
d, ok := b.data[id]
|
||||
if !ok {
|
||||
return nil, chunkstore.ErrNotFound
|
||||
}
|
||||
return bytes.Clone(d), nil
|
||||
}
|
||||
|
||||
func TestChunkBirthDroppedSuffixPublishesWithRealManifest(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
f := &birthFiler{entries: map[string]*filerpb.Entry{}}
|
||||
b := &birthBlobs{data: map[string][]byte{}}
|
||||
remote, err := chunkstore.NewChunkRemote(f, b, "/birth/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := storage.DroppedSuffixBirthStoreForTest(t, remote)
|
||||
layer, err := storage.AttachChunkLayer(s, remote, storage.ChunkLayerConfig{ChunkBlocks: 4, Epoch: 2, Holder: "host-a"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = layer.Close() })
|
||||
cut, err := layer.Cut(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("reused-LSN cut must publish without another write: %v", err)
|
||||
}
|
||||
h, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cut.Head.RemoteLSN != 2 || h.RemoteLSN != 2 || h.Chunks[0].BirthLSN != 2 || h.Segments[0].MaxBirthLSN != 2 {
|
||||
t.Fatalf("cut-image frontier/birth: %+v", h)
|
||||
}
|
||||
data, err := remote.Get(ctx, h.Chunks[0].Key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := make([]byte, 4*4096)
|
||||
copy(want[4096:], bytes.Repeat([]byte{0xB2}, 4096))
|
||||
if !bytes.Equal(data, want) {
|
||||
t.Fatal("published cut differs from recovered B2 image")
|
||||
}
|
||||
// The real builder's future-birth guard must still reject corrupt proposals.
|
||||
invalid := h
|
||||
invalid.Chunks = map[uint64]storage.ChunkRef{0: h.Chunks[0]}
|
||||
ref := invalid.Chunks[0]
|
||||
ref.BirthLSN = 3
|
||||
invalid.Chunks[0] = ref
|
||||
if _, _, err := remote.PrepareManifest(ctx, h, invalid, 4*4096); err == nil {
|
||||
t.Fatal("future birth was accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestChunkBirthMigrationCarriesImageFrontier(t *testing.T) {
|
||||
s, path := newChunkTestStore(t)
|
||||
d := s.v3.pub.current()
|
||||
mapPath := s.v3.ownedMap.fd.Name()
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := MigrationSourceV3{UUID: d.UUID, VolumeSize: d.VolumeSize, ExtentSize: d.ExtentSize, BlockSize: d.BlockSize, OldWALOffset: 4096, OldWALSize: d.WALSize + 4096, CreatedAt: d.CreatedAt, CheckpointLSN: 7, ChunkBlocks: ctChunkBlocks}
|
||||
plan, err := PrepareMigrationV3(mapPath, src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fd, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { fd.Close() })
|
||||
// Actual offline migration's map and slot encoder, on a small flushed
|
||||
// image. No legacy engine or fabricated in-memory owned-map entries.
|
||||
for _, part := range []struct {
|
||||
offset int64
|
||||
data []byte
|
||||
}{{MigrationSlotBOffset, plan.PreparedB}, {MigrationSlotAOffset, plan.CommittedA}, {MigrationSlotBOffset, plan.RolloverB}} {
|
||||
if _, err := fd.WriteAt(part.data, part.offset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fd.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
want := makeBlock(ctBlockSize, 0x57)
|
||||
if _, err := fd.WriteAt(want, int64(d.WALOffset+d.WALSize)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fd.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := OpenWALStoreWithOptions(path, WALStoreOptions{ChunkBlocks: ctChunkBlocks})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { closeBounded(t, r) })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := newFakeChunkRemote()
|
||||
l := mustAttach(t, r, f, ctConfig(1))
|
||||
newest, err := r.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x41))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cut, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cut.Head.Chunks[0].BirthLSN != 7 || cut.Head.Chunks[1].BirthLSN != newest {
|
||||
t.Fatalf("migrated image birth lost: %+v", cut.Head)
|
||||
}
|
||||
if !bytes.Equal(f.imageOf(t, cut.Head)[:ctBlockSize], want) {
|
||||
t.Fatal("migration cut changed inherited bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkBirthSeededFrontierPreservesInheritedImage(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
if err := s.SeedChunkFrontier(7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := newFakeChunkRemote()
|
||||
image := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
copy(image[ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, 0x57))
|
||||
f.seedHead(t, image, 7, 1)
|
||||
cfg := ctConfig(2)
|
||||
cfg.FreshFromHead = true
|
||||
l := mustAttach(t, s, f, cfg)
|
||||
newest, err := s.Write(0, makeBlock(ctBlockSize, 0x41))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cut, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cut.Head.Chunks[1].BirthLSN != 7 || cut.Head.Chunks[0].BirthLSN != newest {
|
||||
t.Fatalf("seeded image birth lost: %+v", cut.Head)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestChunkBirthLegacyEngineUsesCutFrontierUpperBound(t *testing.T) {
|
||||
s, _ := newLegacyChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
l := mustAttach(t, s, f, cfg)
|
||||
if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
last, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cut, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, idx := range []uint64{0, 1} {
|
||||
if cr := cut.Head.Chunks[idx]; cr.Encoding != "full" || cr.BirthLSN != last {
|
||||
t.Fatalf("legacy chunk %d metadata %+v, want frontier %d", idx, cr, last)
|
||||
}
|
||||
}
|
||||
want := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
copy(want, makeBlock(ctBlockSize, 0x41))
|
||||
copy(want[ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, 0x42))
|
||||
assertImage(t, "legacy inherited image", f.imageOf(t, cut.Head), want)
|
||||
}
|
||||
|
||||
func TestChunkBirthBASEUsesInheritedFrontierIncludingZero(t *testing.T) {
|
||||
for _, frontier := range []uint64{0, 7} {
|
||||
t.Run(string(rune('0'+frontier)), func(t *testing.T) {
|
||||
s, _, l := mappedBASELayerV3(t)
|
||||
h, err := s.BeginBaseInstall(frontier, idA)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := h.WriteBase(5, blk(0x55)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := h.MarkBaseComplete(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newest, err := s.Write(0, blk(0x41))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cut, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cut.Head.Chunks[1].BirthLSN != frontier || cut.Head.Chunks[0].BirthLSN != newest {
|
||||
t.Fatalf("BASE birth drifted with unrelated WAL writes: %+v, inherited %d", cut.Head, frontier)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkBirthCOWDoesNotObservePostBarrierWrite(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
cfg.FreshFromHead = true
|
||||
cfg.BarrierBound = 0
|
||||
cfg.UploadConcurrency = 1
|
||||
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
|
||||
if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
var once, releaseOnce sync.Once
|
||||
unblock := func() { releaseOnce.Do(func() { close(release) }) }
|
||||
l.testCOWRead = func(idx uint64, _ bool) {
|
||||
if idx == 0 {
|
||||
once.Do(func() { close(entered) })
|
||||
<-release
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
done := make(chan error, 1)
|
||||
joined := make(chan struct{})
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
unblock()
|
||||
select {
|
||||
case <-joined:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Error("birth COW worker not joined")
|
||||
}
|
||||
})
|
||||
go func() { defer close(joined); _, err := l.Cut(ctx); done <- err }()
|
||||
cowWaitSignal(t, entered, "copy after the birth barrier")
|
||||
after, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x43))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unblock()
|
||||
if err := waitErr(t, done, "birth COW cut"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cowWaitSignal(t, joined, "birth COW join")
|
||||
first := f.installedHeads()[0]
|
||||
if first.Chunks[1].BirthLSN != before || !bytes.Equal(f.imageOf(t, first)[ctChunkBlocks*ctBlockSize:(ctChunkBlocks+1)*ctBlockSize], makeBlock(ctBlockSize, 0x42)) {
|
||||
t.Fatal("post-barrier write changed the saved image or its birth")
|
||||
}
|
||||
l.testCOWRead = nil
|
||||
second, err := l.Cut(ctTimeout(t))
|
||||
if err != nil || second.Head.Chunks[1].BirthLSN != after {
|
||||
t.Fatalf("next version lost post-barrier birth: %+v %v", second, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkBirthTracksNewestLocalWriteAtCut(t *testing.T) {
|
||||
for _, bound := range []int{0, 1} {
|
||||
t.Run(string(rune('0'+bound)), func(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
cfg.FreshFromHead = true
|
||||
cfg.BarrierBound = bound
|
||||
l := mustAttach(t, s, f, cfg)
|
||||
x, err := s.Write(0, makeBlock(ctBlockSize, 0x41))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
y, err := s.Write(ctChunkBlocks+1, makeBlock(ctBlockSize, 0x43))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.Head.Chunks[0].BirthLSN != x || first.Head.Chunks[1].BirthLSN != y || first.Head.Chunks[0].Encoding != "full" || first.Head.RemoteLSN != y {
|
||||
t.Fatalf("births did not preserve distinct local write frontiers: %+v, want %d/%d", first.Head, x, y)
|
||||
}
|
||||
z, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x44))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if second.Head.Chunks[0] != first.Head.Chunks[0] || second.Head.Chunks[1].BirthLSN != z {
|
||||
t.Fatal("rewrite changed a cold chunk birth or failed to advance the changed version")
|
||||
}
|
||||
for _, lba := range []uint32{ctChunkBlocks, ctChunkBlocks + 1} {
|
||||
if _, err := s.Write(lba, makeBlock(ctBlockSize, 0)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
third, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, exists := third.Head.Chunks[1]; exists || third.Head.Chunks[0] != first.Head.Chunks[0] {
|
||||
t.Fatal("zero-chunk deletion retained a reference or changed the cold birth")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -386,7 +386,7 @@ func (f *fakeChunkRemote) seedHead(t *testing.T, image []byte, remoteLSN, epoch
|
||||
key := fmt.Sprintf("seed/%d", idx)
|
||||
f.objs[key] = append([]byte(nil), c...)
|
||||
f.everStored[key] = true
|
||||
head.Chunks[uint64(idx)] = chunkRef{Key: key, SHA256: sha256.Sum256(c)}
|
||||
head.Chunks[uint64(idx)] = chunkRef{Key: key, SHA256: sha256.Sum256(c), Encoding: "full", BirthLSN: remoteLSN}
|
||||
}
|
||||
f.installLocked(head)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// ErrChunkHydrationPending means no guest bytes were admitted: hydration
|
||||
// is queued/in flight or the caller's wait expired. Owned work may continue.
|
||||
var ErrChunkHydrationPending = errors.New("storage: chunk hydration pending")
|
||||
|
||||
const defaultHydrationWorkers = 2
|
||||
const defaultHydrationQueueDepth = 64
|
||||
|
||||
// ChunkHydrationStats separates wait refusals from owned fetch outcomes.
|
||||
// A wait refusal is not necessarily a wire completion (a caller may cancel).
|
||||
type ChunkHydrationStats struct {
|
||||
WorkerLimit int
|
||||
QueueDepth int
|
||||
Active int
|
||||
Queued int
|
||||
WaitCalls uint64
|
||||
Joined uint64
|
||||
WaitRefusals uint64
|
||||
Fetches uint64
|
||||
Completed uint64
|
||||
FetchErrors uint64
|
||||
}
|
||||
|
||||
type chunkHydrationFlight struct {
|
||||
idx, gen uint64
|
||||
ref chunkRef
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
running bool
|
||||
waiters int
|
||||
err error
|
||||
}
|
||||
|
||||
func hydrationPending(cause error) error {
|
||||
if cause == nil {
|
||||
return ErrChunkHydrationPending
|
||||
}
|
||||
return fmt.Errorf("%w: %w", ErrChunkHydrationPending, cause)
|
||||
}
|
||||
|
||||
// The promise and worker lifetime belong to the layer, not any one caller.
|
||||
// stMu protects admission, queue membership and waiter counts. Nobody holds
|
||||
// it (or a store/capture/lifecycle lock) while awaiting or fetching bytes.
|
||||
func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]byte, error) {
|
||||
idx := l.chunkOf(lba)
|
||||
counted := false
|
||||
for {
|
||||
l.stMu.Lock()
|
||||
if l.closed {
|
||||
l.stMu.Unlock()
|
||||
return nil, errChunkLayerClosed
|
||||
}
|
||||
if !l.absent[idx] || l.localBlocks[lba] {
|
||||
l.stMu.Unlock()
|
||||
return nil, nil
|
||||
}
|
||||
ref, ok := l.head.Chunks[idx]
|
||||
if !ok {
|
||||
l.stMu.Unlock()
|
||||
return make([]byte, l.blockSize), nil
|
||||
}
|
||||
if !counted {
|
||||
l.stats.Hydration.WaitCalls++
|
||||
counted = true
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
l.stats.Hydration.WaitRefusals++
|
||||
l.stMu.Unlock()
|
||||
return nil, hydrationPending(err)
|
||||
}
|
||||
gen := l.absentGen[idx]
|
||||
f := l.hydration[idx]
|
||||
stale := f != nil && (f.gen != gen || f.ref != ref)
|
||||
if stale {
|
||||
f.cancel()
|
||||
// The old worker remains owned and joined, but cannot delay a
|
||||
// new generation or remove its replacement when it finishes.
|
||||
delete(l.hydration, idx)
|
||||
close(f.done)
|
||||
f = nil
|
||||
}
|
||||
if f != nil && !stale {
|
||||
l.stats.Hydration.Joined++
|
||||
}
|
||||
if f == nil {
|
||||
if len(l.hydration) >= l.cfg.HydrationQueueDepth {
|
||||
l.stats.Hydration.WaitRefusals++
|
||||
l.stMu.Unlock()
|
||||
return nil, hydrationPending(nil)
|
||||
}
|
||||
if !l.hydrationStarted {
|
||||
l.hydration = make(map[uint64]*chunkHydrationFlight)
|
||||
l.hydrationWake = make(chan struct{}, 1)
|
||||
l.hydrationStarted = true
|
||||
l.wg.Add(l.cfg.HydrationWorkers)
|
||||
for i := 0; i < l.cfg.HydrationWorkers; i++ {
|
||||
go l.hydrationWorker()
|
||||
}
|
||||
}
|
||||
work, cancel := context.WithCancel(l.ctx)
|
||||
f = &chunkHydrationFlight{idx: idx, gen: gen, ref: ref, ctx: work, cancel: cancel, done: make(chan struct{})}
|
||||
l.hydration[idx] = f
|
||||
}
|
||||
f.waiters++
|
||||
l.wakeHydrationLocked()
|
||||
l.stMu.Unlock()
|
||||
if hook := l.testHydrationWait; hook != nil {
|
||||
hook(idx)
|
||||
}
|
||||
select {
|
||||
case <-l.ctx.Done():
|
||||
l.stMu.Lock()
|
||||
f.waiters--
|
||||
l.stMu.Unlock()
|
||||
return nil, errChunkLayerClosed
|
||||
case <-f.done:
|
||||
case <-ctx.Done():
|
||||
// A completed fault wins a simultaneous caller deadline.
|
||||
select {
|
||||
case <-f.done:
|
||||
default:
|
||||
l.stMu.Lock()
|
||||
f.waiters--
|
||||
l.stats.Hydration.WaitRefusals++
|
||||
l.stMu.Unlock()
|
||||
return nil, hydrationPending(ctx.Err())
|
||||
}
|
||||
}
|
||||
l.stMu.Lock()
|
||||
f.waiters--
|
||||
closed := l.closed
|
||||
changed := l.absentGen[idx] != f.gen || l.head.Chunks[idx] != f.ref
|
||||
err := f.err
|
||||
if !closed && !changed && errors.Is(err, ErrChunkHydrationPending) {
|
||||
l.stats.Hydration.WaitRefusals++
|
||||
}
|
||||
l.stMu.Unlock()
|
||||
if closed {
|
||||
return nil, errChunkLayerClosed
|
||||
}
|
||||
if changed {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A local override or an intervening HEAD/absence change is resolved
|
||||
// through the normal path, under the same original caller deadline.
|
||||
}
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) wakeHydrationLocked() {
|
||||
select {
|
||||
case l.hydrationWake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) hydrationWorker() {
|
||||
defer l.wg.Done()
|
||||
for {
|
||||
l.stMu.Lock()
|
||||
if l.closed {
|
||||
l.stMu.Unlock()
|
||||
return
|
||||
}
|
||||
var next *chunkHydrationFlight
|
||||
for _, f := range l.hydration {
|
||||
if !f.running && (next == nil || (f.waiters > 0 && next.waiters == 0)) {
|
||||
next = f
|
||||
}
|
||||
}
|
||||
if next == nil {
|
||||
l.stMu.Unlock()
|
||||
select {
|
||||
case <-l.hydrationWake:
|
||||
continue
|
||||
case <-l.ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
next.running = true
|
||||
l.stats.Hydration.Active++
|
||||
l.stats.Hydration.Fetches++
|
||||
l.wakeHydrationLocked()
|
||||
l.stMu.Unlock()
|
||||
fetch, cancel := context.WithTimeout(next.ctx, l.cfg.ReadMissTimeout)
|
||||
resolved, err := l.fillOnce(fetch, next.idx, next.gen, next.ref)
|
||||
cancel()
|
||||
next.cancel()
|
||||
l.stMu.Lock()
|
||||
if hydrationContextCauseOnly(err) {
|
||||
err = hydrationPending(err)
|
||||
}
|
||||
if err != nil {
|
||||
l.stats.Hydration.FetchErrors++
|
||||
} else if resolved {
|
||||
l.stats.Hydration.Completed++
|
||||
}
|
||||
l.stats.Hydration.Active--
|
||||
next.err = err
|
||||
if l.hydration[next.idx] == next {
|
||||
delete(l.hydration, next.idx)
|
||||
close(next.done)
|
||||
}
|
||||
l.wakeHydrationLocked()
|
||||
l.stMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// Caller holds stMu, before Close begins joining wg. Running fills remain
|
||||
// owned until their worker finishes; queued promises settle without I/O.
|
||||
func (l *chunkLayerImpl) closeHydrationLocked() {
|
||||
for idx, f := range l.hydration {
|
||||
f.cancel()
|
||||
if !f.running {
|
||||
f.err = errChunkLayerClosed
|
||||
delete(l.hydration, idx)
|
||||
close(f.done)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Joined physical/unknown errors must not become retryable just because they
|
||||
// also contain a context cause.
|
||||
func hydrationContextCauseOnly(err error) bool {
|
||||
if err == context.DeadlineExceeded || err == context.Canceled {
|
||||
return true
|
||||
}
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if j, ok := err.(interface{ Unwrap() []error }); ok {
|
||||
causes := j.Unwrap()
|
||||
if len(causes) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, cause := range causes {
|
||||
if !hydrationContextCauseOnly(cause) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return hydrationContextCauseOnly(errors.Unwrap(err))
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func hydrationReadContext(s *WALStore, ctx context.Context, lba uint32) ([]byte, error) {
|
||||
if r, ok := any(s).(interface {
|
||||
ReadContext(context.Context, uint32) ([]byte, error)
|
||||
}); ok {
|
||||
return r.ReadContext(ctx, lba)
|
||||
}
|
||||
return s.Read(lba)
|
||||
}
|
||||
|
||||
func TestChunkHydration_DeadlineDetachesWithoutCancellingFill(t *testing.T) {
|
||||
src := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
copy(src[8*ctBlockSize:], makeBlock(ctBlockSize, 0x88))
|
||||
remote := newFakeChunkRemote()
|
||||
remote.seedHead(t, src, 50, 1)
|
||||
s, _ := newChunkTestStore(t)
|
||||
cfg := ctConfig(2)
|
||||
cfg.FreshFromHead = true
|
||||
mustAttach(t, s, remote, cfg)
|
||||
_, release := holdNextGet(t, remote)
|
||||
fired := make(chan struct{})
|
||||
timer := time.AfterFunc(500*time.Millisecond, func() { defer close(fired); release() })
|
||||
t.Cleanup(func() {
|
||||
release()
|
||||
if !timer.Stop() {
|
||||
<-fired
|
||||
}
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
got, err := hydrationReadContext(s, ctx, 8)
|
||||
elapsed := time.Since(start)
|
||||
if len(got) != 0 || !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("deadline must detach before fill: bytes=%d err=%v elapsed=%s", len(got), err, elapsed)
|
||||
}
|
||||
if elapsed >= 350*time.Millisecond {
|
||||
t.Fatalf("hydration ignored caller budget: %s", elapsed)
|
||||
}
|
||||
retry, cancelRetry := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancelRetry()
|
||||
got, err = hydrationReadContext(s, retry, 8)
|
||||
if err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, 0x88)) {
|
||||
t.Fatalf("retry did not get exact bytes: %v", err)
|
||||
}
|
||||
if n := remote.stats().gets; n != 1 {
|
||||
t.Fatalf("retry cancelled/restarted shared fetch: Gets=%d want1", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Internal readers have no frontend command budget: the remote fill owns its timeout.
|
||||
func TestChunkHydration_ContextlessReadAllowsSlowFill(t *testing.T) {
|
||||
s, layer, remote, _ := hydrationFixture(t, 2, 64)
|
||||
layer.cfg.ReadMissTimeout = 30 * time.Second
|
||||
entered, release := holdGets(t, remote)
|
||||
defer release()
|
||||
result := make(chan hydrationResult, 1)
|
||||
go func() { data, err := s.Read(8); result <- hydrationResult{data, err} }()
|
||||
waitKey(t, entered, "contextless slow fill")
|
||||
timer := time.NewTimer(6 * time.Second)
|
||||
defer timer.Stop()
|
||||
<-timer.C
|
||||
release()
|
||||
select {
|
||||
case got := <-result:
|
||||
if got.err != nil || !bytes.Equal(got.data, makeBlock(ctBlockSize, 0x48)) {
|
||||
t.Fatalf("contextless reader lost slow fill: %v", got.err)
|
||||
}
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("contextless reader did not settle after release")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkHydration_SnapshotFailsOnReadError(t *testing.T) {
|
||||
s, _, remote, _ := hydrationFixture(t, 2, 64)
|
||||
if _, err := s.Write(0, makeBlock(ctBlockSize, 0x77)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fault := errors.New("remote snapshot read fault")
|
||||
remote.mu.Lock()
|
||||
remote.failGet = fault
|
||||
remote.mu.Unlock()
|
||||
got, err := s.AllBlocks()
|
||||
if !errors.Is(err, fault) || got != nil {
|
||||
t.Fatalf("snapshot silently lost unreadable blocks: entries=%d err=%v", len(got), err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type hydrationResult struct {
|
||||
data []byte
|
||||
err error
|
||||
}
|
||||
|
||||
func hydrationFixture(t *testing.T, workers, depth int) (*WALStore, *chunkLayerImpl, *fakeChunkRemote, <-chan uint64) {
|
||||
t.Helper()
|
||||
image := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
for i := uint32(0); i < ctNumBlocks; i++ {
|
||||
copy(image[int(i)*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+i)))
|
||||
}
|
||||
remote := newFakeChunkRemote()
|
||||
remote.seedHead(t, image, 50, 1)
|
||||
s, _ := newChunkTestStore(t)
|
||||
if err := s.SeedChunkFrontier(50); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := ctConfig(2)
|
||||
cfg.FreshFromHead = true
|
||||
cfg.HydrationWorkers = workers
|
||||
cfg.HydrationQueueDepth = depth
|
||||
layer := mustAttach(t, s, remote, cfg).(*chunkLayerImpl)
|
||||
registered := make(chan uint64, 128)
|
||||
layer.testHydrationWait = func(idx uint64) { registered <- idx }
|
||||
return s, layer, remote, registered
|
||||
}
|
||||
|
||||
func startHydrationRead(t *testing.T, s *WALStore, parent context.Context, lba uint32) <-chan hydrationResult {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
result := make(chan hydrationResult, 1)
|
||||
joined := make(chan struct{})
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
select {
|
||||
case <-joined:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Error("hydration reader failed to settle")
|
||||
}
|
||||
})
|
||||
go func() {
|
||||
defer close(joined)
|
||||
data, err := hydrationReadContext(s, ctx, lba)
|
||||
result <- hydrationResult{data, err}
|
||||
}()
|
||||
return result
|
||||
}
|
||||
func waitHydrationRegistration(t *testing.T, c <-chan uint64, n int) {
|
||||
t.Helper()
|
||||
for i := 0; i < n; i++ {
|
||||
select {
|
||||
case <-c:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("hydration waiter was not registered")
|
||||
}
|
||||
}
|
||||
}
|
||||
func hydrationOutcome(t *testing.T, c <-chan hydrationResult) hydrationResult {
|
||||
t.Helper()
|
||||
select {
|
||||
case r := <-c:
|
||||
return r
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("hydration read did not finish")
|
||||
return hydrationResult{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkHydration_ConcurrentReadersShareOneGet(t *testing.T) {
|
||||
s, _, remote, registered := hydrationFixture(t, 2, 64)
|
||||
entered, release := holdGets(t, remote)
|
||||
defer release()
|
||||
const readers = 12
|
||||
results := make([]<-chan hydrationResult, readers)
|
||||
for i := range results {
|
||||
results[i] = startHydrationRead(t, s, context.Background(), 8)
|
||||
}
|
||||
waitHydrationRegistration(t, registered, readers)
|
||||
waitKey(t, entered, "shared hydration")
|
||||
if got := remote.stats().gets; got != 1 {
|
||||
t.Fatalf("same-chunk readers started %d Gets", got)
|
||||
}
|
||||
release()
|
||||
for _, c := range results {
|
||||
r := hydrationOutcome(t, c)
|
||||
if r.err != nil || !bytes.Equal(r.data, makeBlock(ctBlockSize, 0x48)) {
|
||||
t.Fatalf("shared fill bytes: %v", r.err)
|
||||
}
|
||||
}
|
||||
if got := remote.stats().gets; got != 1 {
|
||||
t.Fatalf("shared fill restarted: Gets=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkHydration_QueueAndWorkerLimitsAreBounded(t *testing.T) {
|
||||
s, layer, remote, registered := hydrationFixture(t, 1, 2)
|
||||
entered, release := holdGets(t, remote)
|
||||
defer release()
|
||||
first := startHydrationRead(t, s, context.Background(), 8)
|
||||
waitKey(t, entered, "first worker")
|
||||
waitHydrationRegistration(t, registered, 1)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond)
|
||||
defer cancel()
|
||||
second := startHydrationRead(t, s, ctx, 12)
|
||||
waitHydrationRegistration(t, registered, 1)
|
||||
if r := hydrationOutcome(t, second); !errors.Is(r.err, ErrChunkHydrationPending) {
|
||||
t.Fatalf("queued timeout: %v", r.err)
|
||||
}
|
||||
_, err := hydrationReadContext(s, context.Background(), 16)
|
||||
if !errors.Is(err, ErrChunkHydrationPending) {
|
||||
t.Fatalf("full queue did not refuse: %v", err)
|
||||
}
|
||||
if got := remote.stats().gets; got != 1 {
|
||||
t.Fatalf("worker bound exceeded: Gets=%d", got)
|
||||
}
|
||||
stats := layer.Stats().Hydration
|
||||
if stats.WorkerLimit != 1 || stats.QueueDepth != 2 || stats.Active != 1 || stats.Queued != 1 || stats.WaitRefusals != 2 || stats.Fetches != 1 {
|
||||
t.Fatalf("hydration status does not reflect bounded pressure: %+v", stats)
|
||||
}
|
||||
release()
|
||||
if r := hydrationOutcome(t, first); r.err != nil {
|
||||
t.Fatal(r.err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkHydration_ActiveDemandPrecedesExpiredWaiter(t *testing.T) {
|
||||
s, _, remote, registered := hydrationFixture(t, 1, 3)
|
||||
entered, release := holdGets(t, remote)
|
||||
defer release()
|
||||
first := startHydrationRead(t, s, context.Background(), 8)
|
||||
waitKey(t, entered, "occupied worker")
|
||||
waitHydrationRegistration(t, registered, 1)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond)
|
||||
defer cancel()
|
||||
expired := startHydrationRead(t, s, ctx, 12)
|
||||
waitHydrationRegistration(t, registered, 1)
|
||||
if r := hydrationOutcome(t, expired); !errors.Is(r.err, ErrChunkHydrationPending) {
|
||||
t.Fatalf("expired queued read: %v", r.err)
|
||||
}
|
||||
demand := startHydrationRead(t, s, context.Background(), 16)
|
||||
waitHydrationRegistration(t, registered, 1)
|
||||
release()
|
||||
if r := hydrationOutcome(t, first); r.err != nil {
|
||||
t.Fatal(r.err)
|
||||
}
|
||||
if r := hydrationOutcome(t, demand); r.err != nil || !bytes.Equal(r.data, makeBlock(ctBlockSize, 0x50)) {
|
||||
t.Fatalf("demand: %v", r.err)
|
||||
}
|
||||
var gets []string
|
||||
for _, op := range remote.stats().ops {
|
||||
if strings.HasPrefix(op, "get:") {
|
||||
gets = append(gets, strings.TrimPrefix(op, "get:"))
|
||||
}
|
||||
}
|
||||
if want := remote.stats().head.Chunks[4].Key; len(gets) < 2 || gets[1] != want {
|
||||
t.Fatalf("fetch order %v, want demand %q second", gets, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkHydration_CloseSettlesQueuedAndRunningReaders(t *testing.T) {
|
||||
s, layer, remote, registered := hydrationFixture(t, 1, 2)
|
||||
entered, release := holdGets(t, remote)
|
||||
defer release()
|
||||
first := startHydrationRead(t, s, context.Background(), 8)
|
||||
waitKey(t, entered, "running Get")
|
||||
second := startHydrationRead(t, s, context.Background(), 12)
|
||||
waitHydrationRegistration(t, registered, 2)
|
||||
if err := layer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, c := range []<-chan hydrationResult{first, second} {
|
||||
if r := hydrationOutcome(t, c); !errors.Is(r.err, errChunkLayerClosed) {
|
||||
t.Fatalf("close outcome: %v", r.err)
|
||||
}
|
||||
}
|
||||
if got := remote.stats().gets; got != 1 {
|
||||
t.Fatalf("queued work started after Close: Gets=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkHydration_ConfiguredWorkersBoundConcurrentGets(t *testing.T) {
|
||||
s, _, remote, registered := hydrationFixture(t, 2, 3)
|
||||
entered, release := holdGets(t, remote)
|
||||
defer release()
|
||||
a := startHydrationRead(t, s, context.Background(), 8)
|
||||
b := startHydrationRead(t, s, context.Background(), 12)
|
||||
waitKey(t, entered, "worker1")
|
||||
waitKey(t, entered, "worker2")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
c := startHydrationRead(t, s, ctx, 16)
|
||||
waitHydrationRegistration(t, registered, 3)
|
||||
if r := hydrationOutcome(t, c); !errors.Is(r.err, ErrChunkHydrationPending) {
|
||||
t.Fatalf("queued read: %v", r.err)
|
||||
}
|
||||
if got := remote.stats().gets; got != 2 {
|
||||
t.Fatalf("configured2 workers started%d Gets", got)
|
||||
}
|
||||
release()
|
||||
if r := hydrationOutcome(t, a); r.err != nil {
|
||||
t.Fatal(r.err)
|
||||
}
|
||||
if r := hydrationOutcome(t, b); r.err != nil {
|
||||
t.Fatal(r.err)
|
||||
}
|
||||
}
|
||||
|
||||
type uninterruptibleHydrationRemote struct {
|
||||
*fakeChunkRemote
|
||||
entered, release chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (r *uninterruptibleHydrationRemote) Get(_ context.Context, key string) ([]byte, error) {
|
||||
r.once.Do(func() { close(r.entered) })
|
||||
<-r.release
|
||||
return r.fakeChunkRemote.Get(context.Background(), key)
|
||||
}
|
||||
|
||||
func TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet(t *testing.T) {
|
||||
image := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
copy(image[8*ctBlockSize:], makeBlock(ctBlockSize, 0x88))
|
||||
f := newFakeChunkRemote()
|
||||
f.seedHead(t, image, 50, 1)
|
||||
r := &uninterruptibleHydrationRemote{fakeChunkRemote: f, entered: make(chan struct{}), release: make(chan struct{})}
|
||||
var once sync.Once
|
||||
release := func() { once.Do(func() { close(r.release) }) }
|
||||
s, _ := newChunkTestStore(t)
|
||||
cfg := ctConfig(2)
|
||||
cfg.FreshFromHead = true
|
||||
layer := mustAttach(t, s, r, cfg)
|
||||
t.Cleanup(release)
|
||||
result := startHydrationRead(t, s, context.Background(), 8)
|
||||
select {
|
||||
case <-r.entered:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("Get not entered")
|
||||
}
|
||||
closed := make(chan struct{})
|
||||
t.Cleanup(func() {
|
||||
release()
|
||||
select {
|
||||
case <-closed:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Error("Close did not join Get")
|
||||
}
|
||||
})
|
||||
go func() { _ = layer.Close(); close(closed) }()
|
||||
select {
|
||||
case got := <-result:
|
||||
if !errors.Is(got.err, errChunkLayerClosed) {
|
||||
t.Fatalf("Close lost closed cause: %v", got.err)
|
||||
}
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
t.Fatal("Close did not wake hydration caller")
|
||||
}
|
||||
select {
|
||||
case <-closed:
|
||||
t.Fatal("Close abandoned uninterruptible Get")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
release()
|
||||
select {
|
||||
case <-closed:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("Close did not settle after Get release")
|
||||
}
|
||||
}
|
||||
|
||||
// Only the old generation ignores cancellation; a spare worker can serve the new one.
|
||||
type staleHydrationRemote struct {
|
||||
*fakeChunkRemote
|
||||
oldKey string
|
||||
newEntered, newRelease chan struct{}
|
||||
entered, release chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (r *staleHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
if key == r.oldKey {
|
||||
r.once.Do(func() { close(r.entered) })
|
||||
<-r.release
|
||||
return r.fakeChunkRemote.Get(context.Background(), key)
|
||||
}
|
||||
if r.newRelease != nil {
|
||||
select {
|
||||
case r.newEntered <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case <-r.newRelease:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
return r.fakeChunkRemote.Get(ctx, key)
|
||||
}
|
||||
func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) {
|
||||
s, layer, remote, registered := hydrationFixture(t, 2, 64)
|
||||
layer.stMu.Lock()
|
||||
oldRef, newRef := layer.head.Chunks[2], layer.head.Chunks[3]
|
||||
layer.stMu.Unlock()
|
||||
r := &staleHydrationRemote{fakeChunkRemote: remote, oldKey: oldRef.Key, entered: make(chan struct{}), release: make(chan struct{})}
|
||||
layer.remote = r
|
||||
var once sync.Once
|
||||
release := func() { once.Do(func() { close(r.release) }) }
|
||||
t.Cleanup(release)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
old := startHydrationRead(t, s, ctx, 8)
|
||||
waitHydrationRegistration(t, registered, 1)
|
||||
select {
|
||||
case <-r.entered:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("old Get not entered")
|
||||
}
|
||||
layer.stMu.Lock()
|
||||
layer.head.Chunks[2] = newRef
|
||||
layer.absentGen[2]++
|
||||
layer.stMu.Unlock()
|
||||
newer := startHydrationRead(t, s, ctx, 8)
|
||||
waitHydrationRegistration(t, registered, 1)
|
||||
select {
|
||||
case got := <-newer:
|
||||
if got.err != nil || !bytes.Equal(got.data, makeBlock(ctBlockSize, 0x4c)) {
|
||||
t.Fatalf("new generation blocked by stale Get or wrong bytes: %v", got.err)
|
||||
}
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
release()
|
||||
t.Fatal("new generation joined cancellation-ignoring old Get")
|
||||
}
|
||||
release()
|
||||
if got := hydrationOutcome(t, old); got.err != nil || !bytes.Equal(got.data, makeBlock(ctBlockSize, 0x4c)) {
|
||||
t.Fatalf("old waiter failed to follow new generation: %v", got.err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkHydration_StaleCompletionKeepsReplacement(t *testing.T) {
|
||||
s, layer, remote, registered := hydrationFixture(t, 2, 64)
|
||||
layer.stMu.Lock()
|
||||
oldRef, newRef := layer.head.Chunks[2], layer.head.Chunks[3]
|
||||
layer.stMu.Unlock()
|
||||
r := &staleHydrationRemote{fakeChunkRemote: remote, oldKey: oldRef.Key, entered: make(chan struct{}), release: make(chan struct{}), newEntered: make(chan struct{}, 1), newRelease: make(chan struct{})}
|
||||
layer.remote = r
|
||||
var oldOnce, newOnce sync.Once
|
||||
releaseOld := func() { oldOnce.Do(func() { close(r.release) }) }
|
||||
releaseNew := func() { newOnce.Do(func() { close(r.newRelease) }) }
|
||||
t.Cleanup(func() { releaseOld(); releaseNew() })
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
old := startHydrationRead(t, s, ctx, 8)
|
||||
waitHydrationRegistration(t, registered, 1)
|
||||
select {
|
||||
case <-r.entered:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("old Get not entered")
|
||||
}
|
||||
layer.stMu.Lock()
|
||||
layer.head.Chunks[2] = newRef
|
||||
layer.absentGen[2]++
|
||||
layer.stMu.Unlock()
|
||||
newer := startHydrationRead(t, s, ctx, 8)
|
||||
select {
|
||||
case <-r.newEntered:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("replacement Get not entered")
|
||||
}
|
||||
layer.stMu.Lock()
|
||||
replacement := layer.hydration[2]
|
||||
layer.stMu.Unlock()
|
||||
releaseOld()
|
||||
deadline := time.NewTimer(time.Second)
|
||||
defer deadline.Stop()
|
||||
tick := time.NewTicker(time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for layer.Stats().Hydration.Active != 1 {
|
||||
select {
|
||||
case <-tick.C:
|
||||
case <-deadline.C:
|
||||
t.Fatal("stale worker did not settle")
|
||||
}
|
||||
}
|
||||
layer.stMu.Lock()
|
||||
kept := layer.hydration[2] == replacement
|
||||
layer.stMu.Unlock()
|
||||
if !kept {
|
||||
t.Fatal("stale completion removed replacement promise")
|
||||
}
|
||||
releaseNew()
|
||||
for _, result := range []<-chan hydrationResult{old, newer} {
|
||||
if got := hydrationOutcome(t, result); got.err != nil || !bytes.Equal(got.data, makeBlock(ctBlockSize, 0x4c)) {
|
||||
t.Fatalf("replacement data: %v", got.err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,10 @@ type chunkLayerImpl struct {
|
||||
bmMu sync.Mutex // serializes bitmap store calls
|
||||
presMu sync.Mutex // serializes a whole presence save: snapshot, fsync, replace, version
|
||||
|
||||
closeDone chan struct{} // closed when Close has finished
|
||||
hydration map[uint64]*chunkHydrationFlight // under stMu
|
||||
hydrationWake chan struct{}
|
||||
hydrationStarted bool
|
||||
closeDone chan struct{} // closed when Close has finished
|
||||
|
||||
stMu sync.Mutex
|
||||
closed bool
|
||||
@@ -123,6 +126,7 @@ type chunkLayerImpl struct {
|
||||
keySeq uint64
|
||||
|
||||
// Test-only scheduling hooks; nil in production.
|
||||
testHydrationWait func(uint64) // after promise registration, outside locks
|
||||
testCOWWait func()
|
||||
testCOWRead func(idx uint64, saved bool)
|
||||
testCOWSave func() error
|
||||
@@ -178,6 +182,15 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
if cfg.UploadConcurrency == 0 {
|
||||
cfg.UploadConcurrency = 8
|
||||
}
|
||||
if cfg.HydrationWorkers < 0 || cfg.HydrationWorkers > 64 || cfg.HydrationQueueDepth < 0 || cfg.HydrationQueueDepth > 65536 {
|
||||
return nil, errors.New("storage: hydration workers must be 1..64 and queue depth 1..65536 (0 uses defaults)")
|
||||
}
|
||||
if cfg.HydrationWorkers == 0 {
|
||||
cfg.HydrationWorkers = defaultHydrationWorkers
|
||||
}
|
||||
if cfg.HydrationQueueDepth == 0 {
|
||||
cfg.HydrationQueueDepth = defaultHydrationQueueDepth
|
||||
}
|
||||
if cfg.ReadMissTimeout <= 0 {
|
||||
cfg.ReadMissTimeout = defaultReadMissTimeout
|
||||
}
|
||||
@@ -534,45 +547,7 @@ func sortedKeys(m map[uint64]bool) []uint64 {
|
||||
// block that has no newer local version, then lets the store read its
|
||||
// extent. It runs with no walstore lock held.
|
||||
func (l *chunkLayerImpl) OnReadMiss(lba uint64) ([]byte, error) {
|
||||
idx := l.chunkOf(lba)
|
||||
l.stMu.Lock()
|
||||
if l.closed || !l.absent[idx] || l.localBlocks[lba] {
|
||||
l.stMu.Unlock()
|
||||
return nil, nil
|
||||
}
|
||||
l.wg.Add(1)
|
||||
l.stMu.Unlock()
|
||||
defer l.wg.Done()
|
||||
// One deadline covers every attempt. Each attempt fetches the chunk as
|
||||
// the current HEAD names it; a fill that went stale (eviction generation
|
||||
// or HEAD ref changed meanwhile) installs nothing and the read retries,
|
||||
// so the extent is read only once the block is resolved: the chunk is no
|
||||
// longer absent, or the block has a local version.
|
||||
ctx, cancel := context.WithTimeout(l.ctx, l.cfg.ReadMissTimeout)
|
||||
defer cancel()
|
||||
for {
|
||||
l.stMu.Lock()
|
||||
if !l.absent[idx] || l.localBlocks[lba] {
|
||||
l.stMu.Unlock()
|
||||
return nil, nil
|
||||
}
|
||||
ref, ok := l.head.Chunks[idx]
|
||||
gen := l.absentGen[idx]
|
||||
l.stMu.Unlock()
|
||||
if !ok { // ZERO in the current HEAD
|
||||
return make([]byte, l.blockSize), nil
|
||||
}
|
||||
resolved, err := l.fillOnce(ctx, idx, gen, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resolved {
|
||||
return nil, nil
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("storage: chunk %d fetch: fill kept going stale: %w", idx, err)
|
||||
}
|
||||
}
|
||||
return l.OnReadMissContext(context.Background(), lba)
|
||||
}
|
||||
|
||||
// fillOnce fetches one chunk version and installs every block that has no
|
||||
@@ -780,11 +755,12 @@ func (l *chunkLayerImpl) MakeRemoteDurable(ctx context.Context, t uint64) error
|
||||
}
|
||||
|
||||
type capturedChunk struct {
|
||||
idx uint64
|
||||
data []byte
|
||||
sum [32]byte
|
||||
zero bool
|
||||
key string // staged: already uploaded under this key (data is nil)
|
||||
idx uint64
|
||||
data []byte
|
||||
sum [32]byte
|
||||
zero bool
|
||||
key string // staged: already uploaded under this key (data is nil)
|
||||
birth uint64
|
||||
}
|
||||
|
||||
// stagedChunk is a chunk pre-copied outside the barrier at chunk version
|
||||
@@ -907,6 +883,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
l.cutLSN = h
|
||||
baseHead := copyHead(l.head)
|
||||
l.stMu.Unlock()
|
||||
// Candidates, mutation versions and births belong to the same barrier.
|
||||
// Do not sample the owned map after COW writers are admitted again.
|
||||
births := l.captureBirths(candidates, h)
|
||||
|
||||
st.CandidateChunks = len(candidates)
|
||||
var copyErr error
|
||||
@@ -974,6 +953,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
}
|
||||
var uploads []upload
|
||||
for _, c := range captured {
|
||||
c.birth = births[c.idx]
|
||||
ref, had := baseHead.Chunks[c.idx]
|
||||
switch {
|
||||
case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum:
|
||||
@@ -986,7 +966,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
continue
|
||||
}
|
||||
if c.key != "" { // staged: uploaded before the barrier
|
||||
next.Chunks[c.idx] = chunkRef{Key: c.key, SHA256: c.sum}
|
||||
next.Chunks[c.idx] = chunkRef{Key: c.key, SHA256: c.sum, Encoding: "full", BirthLSN: c.birth}
|
||||
newKeys[c.idx] = c.key
|
||||
changed = append(changed, c.idx)
|
||||
st.StagedChunksUsed++
|
||||
@@ -1012,14 +992,14 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
}
|
||||
if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error {
|
||||
u := uploads[i]
|
||||
return l.remote.Put(ctx, u.key, u.c.data)
|
||||
return l.putCaptured(ctx, u.key, u.c.data)
|
||||
}); err != nil {
|
||||
l.abortCut(all)
|
||||
l.dropIntents(ctx, intents)
|
||||
return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w: %w", errChunkRemoteUnavailable, err)
|
||||
}
|
||||
for _, u := range uploads {
|
||||
next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum}
|
||||
next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum, Encoding: "full", BirthLSN: u.c.birth}
|
||||
newKeys[u.c.idx] = u.key
|
||||
changed = append(changed, u.c.idx)
|
||||
st.UploadedChunks++
|
||||
@@ -1397,6 +1377,13 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error
|
||||
func (l *chunkLayerImpl) Stats() chunkLayerStats {
|
||||
l.stMu.Lock()
|
||||
out := l.stats
|
||||
out.Hydration.WorkerLimit = l.cfg.HydrationWorkers
|
||||
out.Hydration.QueueDepth = l.cfg.HydrationQueueDepth
|
||||
for _, f := range l.hydration {
|
||||
if !f.running {
|
||||
out.Hydration.Queued++
|
||||
}
|
||||
}
|
||||
out.CutsRefused = make(map[string]uint64, len(l.stats.CutsRefused))
|
||||
for k, v := range l.stats.CutsRefused {
|
||||
out.CutsRefused[k] = v
|
||||
@@ -1731,7 +1718,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint
|
||||
intents = append(intents, id)
|
||||
if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error {
|
||||
u := uploads[i]
|
||||
return l.remote.Put(ctx, u.key, u.data)
|
||||
return l.putCaptured(ctx, u.key, u.data)
|
||||
}); err != nil {
|
||||
return nil, intents, fmt.Errorf("storage: capture stage upload: %w: %w", errChunkRemoteUnavailable, err)
|
||||
}
|
||||
@@ -2006,6 +1993,7 @@ func (l *chunkLayerImpl) Close() error {
|
||||
return nil
|
||||
}
|
||||
l.closed = true
|
||||
l.closeHydrationLocked()
|
||||
l.stMu.Unlock()
|
||||
l.cowMu.Lock()
|
||||
l.cowClosed = true
|
||||
|
||||
@@ -9,7 +9,8 @@ func (l *chunkLayerImpl) usesOwnedMapV3() bool { return l.s.v3 != nil && l.s.v3.
|
||||
// (or an authority-checked no-op), outside bmMu/stMu and the capture barrier.
|
||||
// The capture's mutation versions were sampled under the quiesced barrier.
|
||||
// Store.mu prevents a WAL append from slipping between the version check and
|
||||
// the UNKNOWN update. A later write updates max LSN and invalidates proofs.
|
||||
// the UNKNOWN update. A later WAL append updates max LSN and stays retained;
|
||||
// an effective UNKNOWN change or lifecycle transition invalidates proofs.
|
||||
// A failed map publication leaves the old disk UNKNOWN conservative; a map
|
||||
// persistence failure also latches the store, while the remote HEAD remains
|
||||
// the successfully captured image. No remote durability claim is undone.
|
||||
|
||||
@@ -129,6 +129,12 @@ func TestChunkLayer_StaleFillCannotInstallAfterReEviction(t *testing.T) {
|
||||
}
|
||||
|
||||
held, releaseA := holdNextGet(t, f)
|
||||
// Schedule an old-generation physical fill directly. Guest readers now
|
||||
// share one flight, so two guest reads cannot create this overlap.
|
||||
impl := layer.(*chunkLayerImpl)
|
||||
impl.stMu.Lock()
|
||||
oldGen, oldRef := impl.absentGen[2], impl.head.Chunks[2]
|
||||
impl.stMu.Unlock()
|
||||
readA := make(chan error, 1)
|
||||
joinedA := make(chan struct{})
|
||||
t.Cleanup(func() {
|
||||
@@ -141,7 +147,7 @@ func TestChunkLayer_StaleFillCannotInstallAfterReEviction(t *testing.T) {
|
||||
})
|
||||
go func() {
|
||||
defer close(joinedA)
|
||||
_, err := s.Read(8)
|
||||
_, err := impl.fillOnce(ctTimeout(t), 2, oldGen, oldRef)
|
||||
readA <- err
|
||||
}()
|
||||
waitKey(t, held, "fetch A")
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package storage
|
||||
|
||||
// Dark impl-3 COW map, DESIGN r15 9.2-9.5. All bytes are append-only;
|
||||
// neither fallback slots nor pending candidates can lose a dependency.
|
||||
// Impl-3 COW map. Pages and roots are immutable once written; their extents
|
||||
// are reused only after no live root references them
|
||||
// (chunk_map_extents_v3.go), so neither slot root nor a pending candidate can
|
||||
// lose a dependency.
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
@@ -242,6 +244,14 @@ type chunkLSNMapV3 struct {
|
||||
syncFile func() error
|
||||
syncDirectory func() error
|
||||
latchPersistence func(error)
|
||||
// liveMu guards live (chunk_map_extents_v3.go); never held across I/O.
|
||||
liveMu sync.Mutex
|
||||
live chunkMapLiveV3
|
||||
}
|
||||
|
||||
func (m *chunkLSNMapV3) initLiveV3() {
|
||||
m.live.roots = map[mapRootKeyV3]mapRootExtentsV3{}
|
||||
m.live.inflight = map[mapRootKeyV3]bool{}
|
||||
}
|
||||
|
||||
func createChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, error) {
|
||||
@@ -256,6 +266,7 @@ func createChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3
|
||||
return nil, e
|
||||
}
|
||||
m := &chunkLSNMapV3{fd: f, identity: d, chunkBlocks: cb}
|
||||
m.initLiveV3()
|
||||
m.syncFile = f.Sync
|
||||
m.syncDirectory = func() error { return syncDir(filepath.Dir(path)) }
|
||||
if e = m.syncFile(); e == nil {
|
||||
@@ -281,6 +292,13 @@ func openChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3,
|
||||
return nil, nil, e
|
||||
}
|
||||
m := &chunkLSNMapV3{fd: f, identity: d, chunkBlocks: cb, lastGeneration: d.MapGeneration}
|
||||
m.initLiveV3()
|
||||
if s, e := mapShapeForV3(d, cb); e == nil {
|
||||
m.registerRootV3(d.MapGeneration, d.MapRootLocator, s.aligned, refs)
|
||||
}
|
||||
if info, e := f.Stat(); e == nil && info.Size() > 0 {
|
||||
m.live.fileBytes.Store(uint64(info.Size()))
|
||||
}
|
||||
m.syncFile = f.Sync
|
||||
m.syncDirectory = func() error { return syncDir(filepath.Dir(path)) }
|
||||
c := &chunkMapCandidateV3{owner: m, generation: d.MapGeneration, covered: d.MapCoveredCheckpoint, rootOffset: d.MapRootLocator, hash: d.MapRootHash, refs: refs, entries: es}
|
||||
@@ -291,7 +309,9 @@ func openChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3,
|
||||
// It returns a pinned tuple, never a descriptor publication or reuse authority.
|
||||
// Preflight and Stat errors do not latch. Once the append transaction starts,
|
||||
// an error latches and refuses subsequent persistence I/O until reopen.
|
||||
// No pages are reclaimed in this append-only implementation.
|
||||
// New pages and the root go into extents no live root references
|
||||
// (chunk_map_extents_v3.go); the candidate stays live until a publication
|
||||
// names it or supersedes it.
|
||||
func (m *chunkLSNMapV3) Prepare(g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (out *chunkMapCandidateV3, err error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@@ -300,7 +320,8 @@ func (m *chunkLSNMapV3) Prepare(g, C uint64, entries []chunkLSNEntryV3, prior *c
|
||||
|
||||
// Generation reservation and persistence share the existing sidecar mutex.
|
||||
// Concurrent preparers cannot select the same generation; no new lock or
|
||||
// scheduler is introduced, and aborted candidates remain immutable orphans.
|
||||
// scheduler is introduced. A candidate known never to reach a slot is
|
||||
// released (abandonCandidateV3); an uncertain one stays pinned until reopen.
|
||||
func (m *chunkLSNMapV3) prepareNextV3(C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (*chunkMapCandidateV3, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@@ -342,11 +363,14 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3,
|
||||
if info.Size() < 0 {
|
||||
return nil, ErrMapInvalid
|
||||
}
|
||||
off := uint64(info.Size())
|
||||
if off > math.MaxInt64-4095 {
|
||||
fileBytes := uint64(info.Size())
|
||||
if fileBytes > math.MaxInt64-4095 {
|
||||
return nil, ErrCounterExhausted
|
||||
}
|
||||
off = (off + 4095) &^ uint64(4095)
|
||||
// The live set: every page and root extent a live root references.
|
||||
// Roots are only added here (under m.mu); the publisher's report only
|
||||
// removes them, so this snapshot is a superset for the whole prepare.
|
||||
used, liveBytes := usedPagesV3(m.liveSnapshotV3())
|
||||
defer func() {
|
||||
if err != nil {
|
||||
m.failed = err
|
||||
@@ -355,19 +379,39 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3,
|
||||
}
|
||||
}
|
||||
}()
|
||||
// Bounded file: truncate the free tail once the file exceeds 4 x the
|
||||
// live bytes. Nothing at or below the highest live page is touched, so
|
||||
// a root the fallback slot names stays readable.
|
||||
if liveBytes > 0 && fileBytes > 4*liveBytes {
|
||||
keep := (used[len(used)-1] + 1) * 4096
|
||||
if keep < fileBytes {
|
||||
if e := m.fd.Truncate(int64(keep)); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
fileBytes = keep
|
||||
m.live.fileBytes.Store(keep) // the file is shorter even if the fsync fails
|
||||
m.live.truncations.Add(1)
|
||||
if e := m.syncFile(); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
}
|
||||
alloc := newExtentAllocatorV3(used, fileBytes)
|
||||
write := func(b []byte) (uint64, error) {
|
||||
if uint64(len(b)) > math.MaxInt64-off {
|
||||
at := alloc.alloc(uint64(len(b)+4095) / 4096)
|
||||
if uint64(len(b)) > math.MaxInt64-at {
|
||||
return 0, ErrCounterExhausted
|
||||
}
|
||||
at := off
|
||||
n, e := m.fd.WriteAt(b, int64(at))
|
||||
if end := at + uint64(n); end > m.live.fileBytes.Load() {
|
||||
m.live.fileBytes.Store(end) // also on a failed or short write
|
||||
}
|
||||
if e == nil && n != len(b) {
|
||||
e = io.ErrShortWrite
|
||||
}
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
off += uint64(len(b))
|
||||
return at, nil
|
||||
}
|
||||
refs := make([]mapPageRefV3, s.pages)
|
||||
@@ -416,6 +460,15 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3,
|
||||
}
|
||||
m.lastGeneration = g
|
||||
out = &chunkMapCandidateV3{owner: m, generation: g, covered: C, rootOffset: at, hash: mapDigestV3(mapRootDomainV3, root[:s.raw-32]), refs: refs, entries: append([]chunkLSNEntryV3(nil), entries...)}
|
||||
// The candidate is live (in flight) until a publication names it or
|
||||
// supersedes it.
|
||||
x := rootExtentsV3(at, s.aligned, refs)
|
||||
m.liveMu.Lock()
|
||||
k := mapRootKeyV3{at, g}
|
||||
m.live.roots[k] = x
|
||||
m.live.inflight[k] = true
|
||||
m.liveMu.Unlock()
|
||||
m.live.fileBytes.Store(max(alloc.end*4096, fileBytes))
|
||||
return out, nil
|
||||
}
|
||||
func (m *chunkLSNMapV3) Close() error {
|
||||
|
||||
@@ -5,14 +5,16 @@ import "context"
|
||||
// ChunkSegment names an immutable range manifest. Owner is the namespace in
|
||||
// which that manifest was encoded; forks preserve it without rewriting data.
|
||||
type ChunkSegment struct {
|
||||
Key string `json:"key"`
|
||||
SHA256 [32]byte `json:"sha256"`
|
||||
Owner string `json:"owner"`
|
||||
Count int `json:"count"`
|
||||
Key string `json:"key"`
|
||||
SHA256 [32]byte `json:"sha256"`
|
||||
Owner string `json:"owner"`
|
||||
Count int `json:"count"`
|
||||
MaxBirthLSN uint64 `json:"max_birth_lsn"`
|
||||
SegFormat int `json:"seg_format"`
|
||||
}
|
||||
|
||||
// ChunkManifestBuilder prepares immutable segments before the existing root
|
||||
// CAS. Returned intents belong to the cut and follow its settlement rules.
|
||||
// CAS. Returned intents belong to the publishing caller and follow its settlement rules.
|
||||
type ChunkManifestBuilder interface {
|
||||
PrepareManifest(context.Context, ChunkHead, ChunkHead, uint64) (ChunkHead, []string, error)
|
||||
}
|
||||
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user