mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
Merge remote-tracking branch 'origin/main' into test/oss-four-findings
This commit is contained in:
commit
48527ef2ce
446 files changed
+43793
-1107
No files matched your search
+17
-4
@@ -18,7 +18,10 @@ concurrency:
|
||||
jobs:
|
||||
test:
|
||||
name: go test (linux)
|
||||
runs-on: ubuntu-latest
|
||||
# Pushes and same-repo PRs run on the team's tp04 runner (seaweed.slice,
|
||||
# capped at 8 cores / 8 GiB). Fork PRs never reach it: they stay on a
|
||||
# GitHub-hosted runner.
|
||||
runs-on: ${{ (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && 'tp04-seaweed-block' || 'ubuntu-latest' }}
|
||||
timeout-minutes: 25
|
||||
env:
|
||||
# Pure-Go build: no package in the default build needs cgo, and the
|
||||
@@ -34,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
|
||||
@@ -46,5 +53,11 @@ jobs:
|
||||
- name: Vet
|
||||
run: go vet ./...
|
||||
|
||||
- name: Test
|
||||
run: go test -short -count=1 -timeout 10m ./...
|
||||
- name: Test default configuration
|
||||
run: go test -p=1 -short -count=1 -timeout 10m ./...
|
||||
|
||||
- name: Test legacy-fixture configuration
|
||||
# Legacy-input fixtures and native caller controls stay executable after
|
||||
# their constructors move behind the explicit test-only build tag.
|
||||
# Bound package concurrency for existing short wall-clock assertions.
|
||||
run: go test -p=1 -short -tags=swblock_format_v3_test -count=1 -timeout 10m ./...
|
||||
@@ -71,3 +71,19 @@ Strong success criteria let agents loop independently. Weak criteria such as
|
||||
These guidelines are working if there are fewer unnecessary changes in diffs,
|
||||
fewer rewrites due to overcomplication, and clarifying questions come before
|
||||
implementation rather than after mistakes.
|
||||
|
||||
## Protocol contract
|
||||
|
||||
Seaweed Block's state machines and invariants are in
|
||||
[`docs/design/invariants.md`](docs/design/invariants.md). Read it before
|
||||
changing a protocol path: the storage engines, durability and `Sync`,
|
||||
authority and epochs, replication and replica roles, the chunk layer and the
|
||||
cut, the catalog, GC and volume delete, or the workspace lease.
|
||||
|
||||
- Find the machine and transition (Part A) and the invariant IDs (Part B)
|
||||
your change touches, and name them in the PR.
|
||||
- Follow the change rules (Part C): a new or changed state or transition
|
||||
updates Part A, the design-doc diagram, the ledger and the TLA+ spec that
|
||||
covers it; an ACTIVE row never loses its test; a bug found by tests, soak
|
||||
or TLA+ becomes a regression test plus a ledger row.
|
||||
- Do not weaken a guard listed under "Enforced in" without updating its row.
|
||||
+16
-9
@@ -62,21 +62,26 @@ read-only status (stale evidence is `Ready=Unknown`, never a false ready).
|
||||
|
||||
Lab runs, median of 3; not SLOs. Workloads: Firecracker microVMs (4 vCPU,
|
||||
4 GiB) on one bare-metal host over NVMe/TCP loopback, against a local
|
||||
file-backed disk. Snapshot and fork: a host-side proxy without network
|
||||
latency, guest `fsync` or the block frontend.
|
||||
file-backed disk. The two `fsync` rows marked "ublk" come from a later run on
|
||||
the same host with the ublk frontend, after the group-commit fix
|
||||
([#173](https://github.com/seaweedfs/seaweed-block/pull/173)). Snapshot and
|
||||
fork: a host-side proxy without network latency, guest `fsync` or the block
|
||||
frontend.
|
||||
|
||||
| Measurement | Seaweed Block | Local disk |
|
||||
|---|---|---|
|
||||
| `npm ci` (617 packages, offline) / `git clone` (Go 1.23, local) | 2.14 s / 7.10 s | 2.14 s / 6.99 s |
|
||||
| Untar 100,000 files / cold `find` + `stat` over them | 1.10 s / 0.32 s | 1.06 s / 0.33 s |
|
||||
| 2,000 × create + write + `fsync` | 14.33 s | 6.09 s |
|
||||
| 2,000 × create + write + `fsync` (ublk) | 8.48 s | 6.11 s |
|
||||
| Guest `fsync` median, fio 4 KiB random write, one at a time (ublk) | 3.23 ms | 2.74 ms |
|
||||
| Snapshot / fork of a 10 GiB volume (2,560 chunks) | 0.18 ms / 0.29 ms | |
|
||||
| Two-host lifecycle: create, snapshot, fork, move, stale holder, delete, GC | 35 of 35 checks | |
|
||||
|
||||
Metadata-heavy workloads run at local-disk speed. The cost in these runs is
|
||||
`fsync` latency, about 7 ms against 3 ms local, measured with the NVMe/TCP
|
||||
loopback frontend. The ublk frontend and per-stage `fsync` histograms are on
|
||||
`main` now; latency improvement is in progress.
|
||||
Metadata-heavy workloads run at local-disk speed. The remaining cost is
|
||||
`fsync`: a median of 3.23 ms against 2.74 ms local with the ublk frontend
|
||||
(3.59 ms over NVMe/TCP loopback), down from about 7 ms before the group-commit
|
||||
fix. Every guest `fsync` still reaches the backend sync; no write cache is
|
||||
turned off to get there.
|
||||
[Workspace measurements](docs/workspace-measurements.md) has every number and
|
||||
how each was measured.
|
||||
|
||||
@@ -180,7 +185,8 @@ run evidence: [release notes](docs/releases/README.md).
|
||||
### Not claimed yet
|
||||
|
||||
- Production readiness, SLOs, or a published performance, RTO or RPO claim.
|
||||
- `fsync` parity with local disk (in progress, see Measured results).
|
||||
- `fsync` parity with local disk. Today it is about 1.2× local (see Measured
|
||||
results).
|
||||
- ublk at high density. Unprivileged per-volume servers need a privileged
|
||||
control broker, which is not done.
|
||||
- Crash-restart recovery of a ublk server. A crashed server fails closed.
|
||||
@@ -209,7 +215,8 @@ run evidence: [release notes](docs/releases/README.md).
|
||||
## Documentation
|
||||
|
||||
- Design: [core](docs/design/block-design.md), [agent workspace](docs/design/agent-workspace-design.md),
|
||||
[Kubernetes block](docs/design/kubernetes-block-design.md), [TLA+ specifications](docs/spec/README.md),
|
||||
[Kubernetes block](docs/design/kubernetes-block-design.md), [invariants and state machines](docs/design/invariants.md),
|
||||
[TLA+ specifications](docs/spec/README.md),
|
||||
[workspace measurements](docs/workspace-measurements.md)
|
||||
- Operations: [standalone deployment](docs/standalone-deployment.md),
|
||||
[Kubernetes quickstart](docs/quickstart-kubernetes.md), [user capabilities](docs/user-capabilities.md)
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -148,60 +150,54 @@ func TestDurableStartup_Issue51_SmartWALTornTailRecovers(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// walstore interim: the same mid-history
|
||||
// corruption on a walstore volume does not become an outage: startup is
|
||||
// ready, and the durable status carries the typed warning.
|
||||
func TestDurableStartup_Issue51_WALStoreHoleIsAWarningNotAnOutage(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, BlockSize: 4096, NumBlocks: 16}
|
||||
path := filepath.Join(root, "v1.bin")
|
||||
// A crashed walstore: entries synced, nothing checkpointed (the file
|
||||
// as it is right after Sync; a clean close would checkpoint).
|
||||
s, err := storage.CreateWALStore(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for i := uint32(0); i < 4; i++ {
|
||||
data := make([]byte, 4096)
|
||||
data[0] = byte(0xD0 + i)
|
||||
if _, err := s.Write(i, data); err != nil {
|
||||
// V3 replaces the legacy warning-only recovery policy with nonce-bound,
|
||||
// contiguous WAL recovery. Corruption below strict W must block readiness.
|
||||
// The old v2 warning control is retained in walstore_midhistory_hole_test.go.
|
||||
func TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness(t *testing.T) {
|
||||
const childEnv = "SWBLOCK_V3_STARTUP_CRASH_PATH"
|
||||
if path := os.Getenv(childEnv); path != "" {
|
||||
s, err := storage.CreateWALStoreWithOptions(path, 16, 4096, storage.WALStoreOptions{WMode: storage.WModeStrict})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashed, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = s.Close()
|
||||
// Corrupt a payload byte of the second entry (walstore's WAL starts at
|
||||
// 4096; a one-block entry is 38+4096 bytes).
|
||||
crashed[4096+(38+4096)+38+100] ^= 0xFF
|
||||
if err := os.WriteFile(path, crashed, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dp, err := durable.NewDurableProvider(cfg, healthyView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer dp.Close()
|
||||
h := &spyHost{}
|
||||
outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", 5*time.Second)
|
||||
if outcome != durableStartupReady || len(h.reported) != 0 {
|
||||
t.Fatalf("walstore hole: outcome=%v reported=%v evidence=%q err=%v; want ready (no outage)", outcome, h.reported, evidence, err)
|
||||
}
|
||||
warned := false
|
||||
for _, st := range dp.DurableStatuses() {
|
||||
for _, w := range st.Warnings {
|
||||
if strings.HasPrefix(w, storage.WarningWALHoleSuspected+":") {
|
||||
warned = st.HolesSuspected == 1
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for i := uint32(0); i < 4; i++ {
|
||||
data := make([]byte, 4096)
|
||||
data[0] = byte(0xd0 + i)
|
||||
if _, err := s.Write(i, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.Exit(0) // deliberately no Close/checkpoint; OS releases the owner lock
|
||||
}
|
||||
if !warned {
|
||||
t.Fatalf("durable statuses %+v; want the %s warning, counted once", dp.DurableStatuses(), storage.WarningWALHoleSuspected)
|
||||
root := t.TempDir()
|
||||
path := filepath.Join(root, "v1.bin")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness$")
|
||||
cmd.Env = append(os.Environ(), childEnv+"="+path)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("crash fixture: %v\n%s", err, out)
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
at := int64(8192 + (70 + 4096) + 62 + 100) // v3 second record payload
|
||||
b := make([]byte, 1)
|
||||
_, re := f.ReadAt(b, at)
|
||||
b[0] ^= 0xff
|
||||
_, we := f.WriteAt(b, at)
|
||||
ce := f.Close()
|
||||
if re != nil || we != nil || ce != nil {
|
||||
t.Fatal(re, we, ce)
|
||||
}
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, BlockSize: 4096, NumBlocks: 16}
|
||||
outcome, h := startAfterCorruption(t, cfg)
|
||||
if outcome != durableStartupFaulted || len(h.reported) != 1 || h.reported[0] != volume.UnhealthyWALCorrupt || len(h.blocked) == 0 {
|
||||
t.Fatalf("committed hole: outcome=%v reported=%v blocked=%v; want wal_corrupt and blocked", outcome, h.reported, h.blocked)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestExistingDurableVolumeIgnoresCreateGeometry(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s, err := storage.CreateWALStore(filepath.Join(root, "v1.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := bytes.Repeat([]byte{0x73}, 4096)
|
||||
if _, err = s.Write(0, want); err != nil {
|
||||
s.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.Sync(); err != nil {
|
||||
s.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args := append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl=walstore", "--durable-blocks=4294967295", "--durable-blocksize=8192")
|
||||
f, err := parseFlags(args)
|
||||
if err != nil {
|
||||
t.Fatalf("existing storage must ignore create-only geometry: %v", err)
|
||||
}
|
||||
blocks, blockSize, err := durableCreateGeometry(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if blocks != 0 {
|
||||
t.Fatal("existing file must select open-only mode")
|
||||
}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplName(f.durableImpl), StorageRoot: f.durableRoot, NumBlocks: blocks, BlockSize: blockSize}, healthyView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { p.Close() })
|
||||
result, _, err := openAndRecoverDurable(p, &spyHost{}, "v1", 5*time.Second)
|
||||
if err != nil || result != durableStartupReady {
|
||||
t.Fatalf("existing recovery: %v %v", result, err)
|
||||
}
|
||||
st, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.NumBlocks() != 16 || st.BlockSize() != 4096 {
|
||||
t.Fatalf("existing geometry changed: %d x %d", st.NumBlocks(), st.BlockSize())
|
||||
}
|
||||
got := make([]byte, 4096)
|
||||
b, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = b.Read(context.Background(), 0, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatal("existing bytes changed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExistingDurableVolumeDisappearsDoesNotCreateFromIgnoredFlags(t *testing.T) {
|
||||
if strconv.IntSize < 64 {
|
||||
t.Skip("64-bit CLI uint overflow case")
|
||||
}
|
||||
for _, impl := range []durable.ImplName{durable.ImplWALStore, durable.ImplWALStoreChunk} {
|
||||
t.Run(string(impl), func(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
path := filepath.Join(root, "v1.bin")
|
||||
s, err := storage.CreateWALStore(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args := append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl="+string(impl), "--durable-blocks=4294967297")
|
||||
if impl == durable.ImplWALStoreChunk {
|
||||
args = append(args, "--chunk-filer=127.0.0.1:18888")
|
||||
}
|
||||
f, err := parseFlags(args)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
blocks, bs, err := durableCreateGeometry(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if blocks != 0 {
|
||||
t.Fatal("not open-only")
|
||||
}
|
||||
if err = os.Remove(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err = durableCreateGeometry(f); err == nil {
|
||||
t.Fatal("fresh recheck accepted original overflowing count")
|
||||
}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: blocks, BlockSize: bs, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) {
|
||||
return nil, errors.New("unexpected remote access for missing open-only volume")
|
||||
}}, healthyView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { p.Close() })
|
||||
if _, err = p.EnsureStorage("v1"); err == nil {
|
||||
t.Fatal("created replacement from ignored flags")
|
||||
}
|
||||
if _, err = os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatalf("replacement file exists: %v", err)
|
||||
}
|
||||
if _, err = os.Stat(path + ".chunkfresh"); !os.IsNotExist(err) {
|
||||
t.Fatalf("open-only refusal left a fresh marker: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvmerdma"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/ublk"
|
||||
"github.com/seaweedfs/seaweed-block/core/geometry"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
"github.com/seaweedfs/seaweed-block/core/recovery"
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
@@ -193,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")
|
||||
@@ -270,6 +273,11 @@ func parseFlags(args []string) (flags, error) {
|
||||
return flags{}, fmt.Errorf("--durable-wal-recovery-test-disable-flusher requires --durable-impl=walstore")
|
||||
}
|
||||
}
|
||||
if f.durableRoot != "" {
|
||||
if _, _, err := durableCreateGeometry(f); err != nil {
|
||||
return flags{}, err
|
||||
}
|
||||
}
|
||||
if f.iscsiCHAPUser == "" {
|
||||
f.iscsiCHAPUser = os.Getenv("SW_BLOCK_ISCSI_CHAP_USERNAME")
|
||||
}
|
||||
@@ -523,22 +531,26 @@ type nvmeReadyLine struct {
|
||||
SubsysNQN string `json:"subsys_nqn"`
|
||||
}
|
||||
|
||||
// durableCreateGeometry leaves existing volumes in open-only mode. If the
|
||||
// observed file disappears before Open, NumBlocks=0 prevents a replacement
|
||||
// from being created using narrowed or otherwise ignored CLI values.
|
||||
func durableCreateGeometry(f flags) (uint32, int, error) {
|
||||
path := filepath.Join(f.durableRoot, f.volumeID+".bin")
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return 0, 0, nil
|
||||
} else if !os.IsNotExist(err) {
|
||||
return 0, 0, fmt.Errorf("durable volume geometry: %w", err)
|
||||
}
|
||||
if err := geometry.ValidateBlockGeometry(uint64(f.durableBlocks), uint64(f.durableBlockSize)); err != nil {
|
||||
return 0, 0, fmt.Errorf("--durable-blocks/--durable-blocksize: %w", err)
|
||||
}
|
||||
return uint32(f.durableBlocks), int(f.durableBlockSize), nil
|
||||
}
|
||||
|
||||
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
|
||||
@@ -591,11 +603,12 @@ func run(f flags) int {
|
||||
var durableProv *durable.DurableProvider
|
||||
var workspaceRemoteFor func(string) (storage.ChunkRemote, error)
|
||||
if f.durableRoot != "" {
|
||||
blocks, blockSize, geometryErr := durableCreateGeometry(f)
|
||||
cfg := durable.ProviderConfig{
|
||||
Impl: durable.ImplName(f.durableImpl),
|
||||
StorageRoot: f.durableRoot,
|
||||
BlockSize: int(f.durableBlockSize),
|
||||
NumBlocks: uint32(f.durableBlocks),
|
||||
BlockSize: blockSize,
|
||||
NumBlocks: blocks,
|
||||
WALRetentionLSNs: f.walRetentionLSNs,
|
||||
WALMultiBlockRecords: f.durableWALMultiBlockRecords,
|
||||
WALRecoveryTestDisableFlusher: f.durableWALRecoveryTestDisableFlusher,
|
||||
@@ -607,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
|
||||
@@ -615,7 +630,11 @@ func run(f flags) int {
|
||||
defer chunk.close()
|
||||
}
|
||||
}
|
||||
dp, err := durable.NewDurableProvider(cfg, h.ProjectionView())
|
||||
var dp *durable.DurableProvider
|
||||
err := geometryErr
|
||||
if err == nil {
|
||||
dp, err = durable.NewDurableProvider(cfg, h.ProjectionView())
|
||||
}
|
||||
if chunkErr != nil {
|
||||
err = chunkErr
|
||||
}
|
||||
@@ -871,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()
|
||||
@@ -1168,6 +1186,9 @@ func run(f flags) int {
|
||||
select {
|
||||
case <-shutdownCtx.Done():
|
||||
case request := <-leaseRequests:
|
||||
// The lease guard fenced and asks for the drain; it logs its cause as
|
||||
// "workspace lease: fenced ...". Say here that this is why we stop (#205).
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: stopping: the workspace lease guard fenced and requested the drain")
|
||||
leaseStop = &request
|
||||
case err := <-leaseDone:
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err)
|
||||
@@ -1430,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 {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDurableCreateFlagsValidateOriginalGeometry(t *testing.T) {
|
||||
if strconv.IntSize < 64 {
|
||||
t.Skip("64-bit CLI uint overflow case")
|
||||
}
|
||||
for _, blocks := range []string{"4294967297", "18446744073709551615"} {
|
||||
args := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-blocks="+blocks)
|
||||
if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "durable-blocks") {
|
||||
t.Fatalf("blocks %s: %v", blocks, err)
|
||||
}
|
||||
}
|
||||
args := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-blocks=4294967295", "--durable-blocksize=4096")
|
||||
if _, err := parseFlags(args); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args = append(args, "--durable-blocksize=8192")
|
||||
if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
|
||||
t.Fatalf("oversize geometry: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -39,15 +39,34 @@ func runPersistDemo(opts options) int {
|
||||
}
|
||||
path := filepath.Join(dir, "sparrow-persist.dat")
|
||||
|
||||
// The owned COW map is a file. Refuse an unexpected directory before
|
||||
// changing the prior demo; never recursively remove a caller's directory.
|
||||
mapPath := path + ".chunkmap"
|
||||
if st, err := os.Lstat(mapPath); err == nil && st.IsDir() {
|
||||
fmt.Fprintln(os.Stderr, "sparrow: persist demo: unexpected directory at map file path")
|
||||
return 3
|
||||
} else if err != nil && !os.IsNotExist(err) {
|
||||
fmt.Fprintf(os.Stderr, "sparrow: persist demo: inspect map: %v\n", err)
|
||||
return 3
|
||||
}
|
||||
|
||||
// Demo is meant to be reproducible: every invocation creates a
|
||||
// fresh file. If a previous demo left bytes behind, remove them
|
||||
// before Round 1 so CreateWALStore's O_EXCL doesn't collide.
|
||||
// We only remove the demo file we know we own — never the dir.
|
||||
// Only the named demo file and its owned map sidecar are retired; the
|
||||
// supplied parent directory and unrelated siblings are preserved.
|
||||
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
|
||||
fmt.Fprintf(os.Stderr, "sparrow: persist demo: cannot remove prior file %s: %v\n", path, err)
|
||||
return 3
|
||||
}
|
||||
|
||||
// V3 owns a COW map file at this exact sibling path.
|
||||
// Removing only the volume would leave the next O_EXCL map create blocked.
|
||||
if err := os.Remove(mapPath); err != nil && !os.IsNotExist(err) {
|
||||
fmt.Fprintf(os.Stderr, "sparrow: persist demo: cannot remove prior map: %v\n", err)
|
||||
return 3
|
||||
}
|
||||
|
||||
const (
|
||||
numBlocks = 16
|
||||
blockSize = 4096
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRunPersistDemoRetiresOnlyItsOwnedMap(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "sparrow-persist.dat")
|
||||
if err := os.WriteFile(path, []byte("prior demo"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stale := path + ".chunkmap"
|
||||
if err := os.WriteFile(stale, []byte("stale map"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other := path + ".unrelated"
|
||||
if err := os.WriteFile(other, []byte("keep"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code := runPersistDemo(options{json: true, persistDemo: true, persistDir: dir}); code != 0 {
|
||||
t.Fatalf("demo exit=%d", code)
|
||||
}
|
||||
if got, err := os.ReadFile(stale); err == nil && string(got) == "stale map" {
|
||||
t.Fatal("prior map file survives")
|
||||
} else if err != nil && !os.IsNotExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := os.ReadFile(other); err != nil || string(got) != "keep" {
|
||||
t.Fatalf("unrelated sibling changed: %q %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPersistDemoRefusesUnexpectedMapDirectory(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
mapPath := filepath.Join(dir, "sparrow-persist.dat.chunkmap")
|
||||
if err := os.Mkdir(mapPath, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keep := filepath.Join(mapPath, "keep")
|
||||
if err := os.WriteFile(keep, []byte("unrecognized directory"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code := runPersistDemo(options{json: true, persistDemo: true, persistDir: dir}); code != 3 {
|
||||
t.Fatalf("unexpected map directory exit=%d want3", code)
|
||||
}
|
||||
if got, err := os.ReadFile(keep); err != nil || string(got) != "unrecognized directory" {
|
||||
t.Fatalf("unexpected directory changed: %q %v", got, err)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
//go:build swblock_format_v3_test
|
||||
|
||||
package v2legacy
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TODO(format-v3 row 14a): retain raw-codec controls in the default suite;
|
||||
// these real v2-engine fixtures remain explicit in the tagged migration suite.
|
||||
func TestReadSuperblockRefusesOtherFormats(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "v2")
|
||||
s, err := storage.CreateLegacyWALStoreTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb, err := ReadSuperblock(raw[:SuperblockSize])
|
||||
if err != nil || sb.WALOffset != SuperblockSize || sb.BlockSize != 4096 {
|
||||
t.Fatalf("real v2 superblock: %+v, %v", sb, err)
|
||||
}
|
||||
impl2 := append([]byte(nil), raw[:SuperblockSize]...)
|
||||
binary.LittleEndian.PutUint32(impl2[92:], 2)
|
||||
if _, err := ReadSuperblock(impl2); !errors.Is(err, ErrImplUnsupported) {
|
||||
t.Fatalf("impl version 2: err = %v, want ErrImplUnsupported", err)
|
||||
}
|
||||
v3 := append([]byte(nil), raw[:SuperblockSize]...)
|
||||
binary.LittleEndian.PutUint16(v3[4:], 3)
|
||||
if _, err := ReadSuperblock(v3); !errors.Is(err, ErrNotV2) {
|
||||
t.Fatalf("version 3: err = %v, want ErrNotV2", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Real v2 stores: a cleanly closed, flushed store scans clean; a store with
|
||||
// synced records that were never flushed (a crash) refuses, even though
|
||||
// its superblock may say head = tail (the #156 shape: bounds not persisted
|
||||
// by an ordinary Sync).
|
||||
func TestScanCleanOnRealV2Stores(t *testing.T) {
|
||||
scan := func(t *testing.T, path string) []Finding {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb, err := ReadSuperblock(raw[:SuperblockSize])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ScanClean(raw[SuperblockSize:SuperblockSize+sb.WALSize], sb.WALCheckpointLSN)
|
||||
}
|
||||
blk := make([]byte, 4096)
|
||||
t.Run("cleanly closed", func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "clean")
|
||||
s, err := storage.CreateLegacyWALStoreTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for lba := uint32(0); lba < 4; lba++ {
|
||||
if _, err := s.Write(lba, blk); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f := scan(t, path); len(f) != 0 {
|
||||
t.Fatalf("a cleanly closed v2 store refused: %+v", f[0])
|
||||
}
|
||||
})
|
||||
t.Run("synced, never flushed", func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "dirty")
|
||||
s, err := storage.CreateLegacyWALStoreTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for lba := uint32(0); lba < 2; lba++ {
|
||||
if _, err := s.Write(lba, blk); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f := scan(t, path); len(f) == 0 {
|
||||
t.Fatal("synced unflushed v2 records scanned clean")
|
||||
}
|
||||
_ = s.Close()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// Package v2legacy is the frozen v2/impl1 reader used only by the offline
|
||||
// migration tool (`sw-block migrate-v3`, format bump v3, DESIGN r17.4
|
||||
// section 10.1; plan row 13). It is a copy of the v2 superblock layout and
|
||||
// the v2 WAL entry framing as they stand before the format bump, kept here
|
||||
// so that the v3 open code holds no legacy reader and row 14 can delete the
|
||||
// legacy production code. Nothing here writes, recovers or replays: the
|
||||
// scan only decides whether the tool must refuse.
|
||||
package v2legacy
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
)
|
||||
|
||||
// SuperblockSize is the v2 superblock region at offset 0; the v2 WAL starts
|
||||
// right after it.
|
||||
const SuperblockSize = 4096
|
||||
|
||||
const (
|
||||
magic = "SWBK"
|
||||
version = 2
|
||||
implWALStore = 1
|
||||
implVersion1 = 1
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNotV2 is any offset-0 content that is not a v2 superblock.
|
||||
ErrNotV2 = errors.New("v2legacy: offset 0 is not a v2 superblock")
|
||||
// ErrImplUnsupported is a v2 superblock of another impl or impl version
|
||||
// (impl 2, C12, is refused by the tool, DESIGN 10).
|
||||
ErrImplUnsupported = errors.New("v2legacy: not walstore impl version 1")
|
||||
)
|
||||
|
||||
// Superblock is the frozen v2 superblock (core/storage/superblock.go at
|
||||
// format version 2).
|
||||
type Superblock struct {
|
||||
Version uint16
|
||||
Flags uint16
|
||||
UUID [16]byte
|
||||
VolumeSize uint64
|
||||
ExtentSize uint32
|
||||
BlockSize uint32
|
||||
WALOffset uint64
|
||||
WALSize uint64
|
||||
WALHead uint64
|
||||
WALTail uint64
|
||||
WALCheckpointLSN uint64
|
||||
CreatedAt uint64
|
||||
ImplKind uint8
|
||||
ImplVersion uint32
|
||||
}
|
||||
|
||||
// ReadSuperblock decodes and validates a v2/impl1 superblock (precondition
|
||||
// 2: magic, version 2, ImplKind walstore, ImplVersion 1).
|
||||
func ReadSuperblock(buf []byte) (Superblock, error) {
|
||||
if len(buf) < SuperblockSize {
|
||||
return Superblock{}, fmt.Errorf("%w: short header (%d bytes)", ErrNotV2, len(buf))
|
||||
}
|
||||
le := binary.LittleEndian
|
||||
if string(buf[0:4]) != magic {
|
||||
return Superblock{}, fmt.Errorf("%w: bad magic", ErrNotV2)
|
||||
}
|
||||
var sb Superblock
|
||||
sb.Version = le.Uint16(buf[4:])
|
||||
if sb.Version != version {
|
||||
return Superblock{}, fmt.Errorf("%w: version %d", ErrNotV2, sb.Version)
|
||||
}
|
||||
sb.Flags = le.Uint16(buf[6:])
|
||||
copy(sb.UUID[:], buf[8:24])
|
||||
sb.VolumeSize = le.Uint64(buf[24:])
|
||||
sb.ExtentSize = le.Uint32(buf[32:])
|
||||
sb.BlockSize = le.Uint32(buf[36:])
|
||||
sb.WALOffset = le.Uint64(buf[40:])
|
||||
sb.WALSize = le.Uint64(buf[48:])
|
||||
sb.WALHead = le.Uint64(buf[56:])
|
||||
sb.WALTail = le.Uint64(buf[64:])
|
||||
sb.WALCheckpointLSN = le.Uint64(buf[72:])
|
||||
sb.CreatedAt = le.Uint64(buf[80:])
|
||||
sb.ImplKind = buf[88]
|
||||
sb.ImplVersion = le.Uint32(buf[92:])
|
||||
switch {
|
||||
case sb.VolumeSize == 0, sb.BlockSize == 0, sb.ExtentSize == 0, sb.WALSize == 0:
|
||||
return Superblock{}, fmt.Errorf("%w: zero geometry field", ErrNotV2)
|
||||
case sb.WALOffset != SuperblockSize:
|
||||
return Superblock{}, fmt.Errorf("%w: WALOffset %d", ErrNotV2, sb.WALOffset)
|
||||
case sb.VolumeSize%uint64(sb.BlockSize) != 0:
|
||||
return Superblock{}, fmt.Errorf("%w: VolumeSize not block aligned", ErrNotV2)
|
||||
}
|
||||
if sb.ImplKind != implWALStore || sb.ImplVersion != implVersion1 {
|
||||
return Superblock{}, fmt.Errorf("%w: ImplKind %d ImplVersion %d", ErrImplUnsupported, sb.ImplKind, sb.ImplVersion)
|
||||
}
|
||||
return sb, nil
|
||||
}
|
||||
|
||||
// The frozen v2 WAL entry framing (core/storage/wal_entry.go): a 30-byte
|
||||
// prefix LSN(8) Reserved(8) Type(1) Flags(1) LBA(8) Length(4), then the
|
||||
// payload (write, batch and padding only), then CRC32-IEEE(4) over prefix
|
||||
// and payload, and EntrySize(4).
|
||||
const (
|
||||
entryPrefix = 30
|
||||
entryHeader = 38
|
||||
|
||||
typeWrite = 0x01
|
||||
typeTrim = 0x02
|
||||
typeBarrier = 0x03
|
||||
typeBatch = 0x04
|
||||
typePadding = 0xFF
|
||||
)
|
||||
|
||||
// Finding is one offset of the WAL region that refuses the migration.
|
||||
type Finding struct {
|
||||
Offset uint64 // relative to the WAL region start
|
||||
Type uint8
|
||||
LSN uint64 // the record's last LSN (a batch counts by its last)
|
||||
Reason string
|
||||
Covered bool // LSN <= checkpoint: not a refusal (reported for tests only)
|
||||
}
|
||||
|
||||
// ScanClean is precondition 3 of DESIGN 10.1: an exhaustive,
|
||||
// refusal-biased scan of the whole v2 WAL region. It tries the frozen
|
||||
// decoder at every byte offset, reading circularly so a record crossing the
|
||||
// region end is tried too. An offset refuses when it decodes as a known
|
||||
// type whose type-derived footprint (38 + Length for write, batch and
|
||||
// padding; 38 for trim and barrier) fits in the region, whose CRC and
|
||||
// EntrySize are valid, and whose last LSN is above checkpoint; or when a
|
||||
// CRC-valid candidate of a known type cannot be classified (a zero or
|
||||
// overflowing batch count). A CRC-valid record at or below the checkpoint
|
||||
// is already in the extent and is ignored. It never runs recovery or
|
||||
// replay. It returns the refusing findings, in offset order.
|
||||
func ScanClean(wal []byte, checkpoint uint64) []Finding {
|
||||
n := uint64(len(wal))
|
||||
var out []Finding
|
||||
at := func(i uint64) byte { return wal[i%n] }
|
||||
read := func(off, length uint64) []byte {
|
||||
b := make([]byte, length)
|
||||
for i := range b {
|
||||
b[i] = at(off + uint64(i))
|
||||
}
|
||||
return b
|
||||
}
|
||||
for off := uint64(0); off < n && n >= entryHeader; off++ {
|
||||
typ := at(off + 16)
|
||||
var payload bool
|
||||
switch typ {
|
||||
case typeWrite, typeBatch, typePadding:
|
||||
payload = true
|
||||
case typeTrim, typeBarrier:
|
||||
default:
|
||||
continue
|
||||
}
|
||||
prefix := read(off, entryPrefix)
|
||||
length := uint64(binary.LittleEndian.Uint32(prefix[26:]))
|
||||
footprint := uint64(entryHeader)
|
||||
if payload {
|
||||
footprint += length
|
||||
}
|
||||
if footprint > n {
|
||||
continue // cannot be a record of this region
|
||||
}
|
||||
body := read(off, footprint)
|
||||
dataEnd := footprint - 8
|
||||
if binary.LittleEndian.Uint32(body[dataEnd:]) != crc32.ChecksumIEEE(body[:dataEnd]) ||
|
||||
uint64(binary.LittleEndian.Uint32(body[dataEnd+4:])) != footprint {
|
||||
continue
|
||||
}
|
||||
lsn := binary.LittleEndian.Uint64(body[0:])
|
||||
last := lsn
|
||||
f := Finding{Offset: off, Type: typ}
|
||||
if typ == typeBatch {
|
||||
count := binary.LittleEndian.Uint64(body[8:])
|
||||
if count == 0 || lsn+count-1 < lsn {
|
||||
f.LSN, f.Reason = lsn, "CRC-valid batch with an unclassifiable block count"
|
||||
out = append(out, f)
|
||||
continue
|
||||
}
|
||||
last = lsn + count - 1
|
||||
}
|
||||
f.LSN = last
|
||||
if last <= checkpoint {
|
||||
continue // already in the extent
|
||||
}
|
||||
f.Reason = fmt.Sprintf("CRC-valid v2 record type %#x with LSN %d above the checkpoint %d", typ, last, checkpoint)
|
||||
out = append(out, f)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package v2legacy
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Plan row 13a controls (DESIGN r17.4 section 10.1 precondition 3; owner
|
||||
// claude03): the frozen v2 decoder and the exhaustive, refusal-biased scan.
|
||||
|
||||
// encode is a test-only encoder of the frozen v2 framing.
|
||||
func encode(lsn, reserved uint64, typ uint8, lba uint64, length uint32, data []byte) []byte {
|
||||
b := make([]byte, entryPrefix+len(data)+8)
|
||||
le := binary.LittleEndian
|
||||
le.PutUint64(b[0:], lsn)
|
||||
le.PutUint64(b[8:], reserved)
|
||||
b[16] = typ
|
||||
le.PutUint64(b[18:], lba)
|
||||
le.PutUint32(b[26:], length)
|
||||
copy(b[entryPrefix:], data)
|
||||
end := entryPrefix + len(data)
|
||||
le.PutUint32(b[end:], crc32.ChecksumIEEE(b[:end]))
|
||||
le.PutUint32(b[end+4:], uint32(entryHeader+len(data)))
|
||||
return b
|
||||
}
|
||||
|
||||
func region(n int, at int, recs ...[]byte) []byte {
|
||||
w := make([]byte, n)
|
||||
for _, r := range recs {
|
||||
for i := range r {
|
||||
w[(at+i)%n] = r[i]
|
||||
}
|
||||
at += len(r)
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func write(lsn uint64) []byte { return encode(lsn, 0, typeWrite, 1, 64, make([]byte, 64)) }
|
||||
|
||||
func TestScanCleanFindsEveryUnflushedV2RecordShape(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
wal []byte
|
||||
checkpoint uint64
|
||||
refuse bool
|
||||
}{
|
||||
{"an empty region", make([]byte, 4096), 0, false},
|
||||
{"a write above the checkpoint", region(4096, 100, write(5)), 4, true},
|
||||
{"a write at the checkpoint is in the extent", region(4096, 100, write(5)), 5, false},
|
||||
{"a record wrapping across the region end", region(4096, 4096-50, write(9)), 0, true},
|
||||
{"a trim whose affected range exceeds the region (footprint 38)", region(4096, 0, encode(7, 0, typeTrim, 0, 1<<30, nil)), 6, true},
|
||||
{"a barrier above the checkpoint", region(4096, 0, encode(7, 0, typeBarrier, 0, 0, nil)), 6, true},
|
||||
{"a batch counts by its last LSN", region(4096, 0, encode(3, 3, typeBatch, 0, 64, make([]byte, 64))), 4, true},
|
||||
{"a batch fully below the checkpoint", region(4096, 0, encode(3, 3, typeBatch, 0, 64, make([]byte, 64))), 5, false},
|
||||
{"a CRC-valid batch with a zero count is unclassifiable", region(4096, 0, encode(3, 0, typeBatch, 0, 64, make([]byte, 64))), 9, true},
|
||||
{"a record embedded in another record's payload", region(4096, 0, encode(2, 0, typeWrite, 1, uint32(len(write(9))), write(9))), 5, true},
|
||||
{"a corrupt CRC is no record", func() []byte { w := region(4096, 0, write(9)); w[40] ^= 0xFF; return w }(), 0, false},
|
||||
{"a record larger than the region cannot be one", encode(9, 0, typeWrite, 1, 100, make([]byte, 100))[:64], 0, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got := ScanClean(c.wal, c.checkpoint)
|
||||
if (len(got) > 0) != c.refuse {
|
||||
t.Fatalf("findings %+v, want refuse = %v", got, c.refuse)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -77,13 +77,16 @@ func run(args []string, stdout, stderr io.Writer) int {
|
||||
fmt.Fprintln(stdout, buildinfo.Version("sw-block"))
|
||||
return ops.VolumeStatusExitOK
|
||||
}
|
||||
if args[0] == "migrate-v3" {
|
||||
return runMigrateV3(args[1:], stdout, stderr)
|
||||
}
|
||||
if args[0] != "ops" {
|
||||
fmt.Fprintf(stderr, "sw-block: unknown command %q\n", args[0])
|
||||
usage(stderr)
|
||||
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
|
||||
}
|
||||
@@ -126,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)
|
||||
@@ -2293,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,269 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/cmd/sw-block/internal/v2legacy"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// `sw-block migrate-v3` (format bump v3, DESIGN r17.4 section 10.1; plan row
|
||||
// 13b): the offline, in-place v2/impl1 -> v3/impl3 descriptor rewrite of a
|
||||
// cleanly closed volume whose WAL is fully flushed. No record is converted
|
||||
// and no extent byte is touched. Every step is durable before the next.
|
||||
|
||||
// errMigrateNotClean is DESIGN 10.1's ErrMigrateNotClean.
|
||||
var errMigrateNotClean = errors.New("migrate-v3: the volume is not cleanly flushed: open with the old binary, flush, close cleanly, retry")
|
||||
|
||||
// errMigrateNeitherSlot: neither offset 0 nor offset 4096 holds a valid
|
||||
// slot or v2 superblock; nothing is changed.
|
||||
var errMigrateNeitherSlot = errors.New("migrate-v3: no valid v2 superblock or v3 descriptor slot; nothing changed")
|
||||
|
||||
// migrateStepHook, when set by a test, runs after each durable step with
|
||||
// its name; returning an error stops the tool there (a simulated crash).
|
||||
var migrateStepHook func(step string) error
|
||||
|
||||
// syncDirHook, when set by a test, runs at every directory fsync; an error
|
||||
// fails that fsync.
|
||||
var syncDirHook func(path string) error
|
||||
|
||||
func runMigrateV3(args []string, stdout, stderr io.Writer) int {
|
||||
fs := flag.NewFlagSet("migrate-v3", flag.ContinueOnError)
|
||||
fs.SetOutput(stderr)
|
||||
chunkBlocks := fs.Uint64("chunk-blocks", 0, "the provider's chunk size in blocks (the map geometry); required")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 2
|
||||
}
|
||||
if fs.NArg() != 1 || *chunkBlocks == 0 {
|
||||
fmt.Fprintln(stderr, "usage: sw-block migrate-v3 --chunk-blocks N <volume-file>")
|
||||
return 2
|
||||
}
|
||||
if err := migrateV3(fs.Arg(0), *chunkBlocks, stdout); err != nil {
|
||||
fmt.Fprintln(stderr, err)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func migrateV3(path string, chunkBlocks uint64, out io.Writer) error {
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
if err := storage.LockWALStoreFile(f); err != nil {
|
||||
return err
|
||||
}
|
||||
head := make([]byte, 2*storage.MigrationSlotSize)
|
||||
if _, err := f.ReadAt(head, 0); err != nil {
|
||||
return fmt.Errorf("migrate-v3: read the descriptor region: %w", err)
|
||||
}
|
||||
a, b := head[:storage.MigrationSlotSize], head[storage.MigrationSlotSize:]
|
||||
sb, v2err := v2legacy.ReadSuperblock(a)
|
||||
switch {
|
||||
case v2err == nil:
|
||||
// Not committed: restart from step 1 with a full rescan (the old
|
||||
// binary may have run since; nothing earlier is trusted).
|
||||
return migrateFromV2(f, path, sb, chunkBlocks, out)
|
||||
case errors.Is(v2err, v2legacy.ErrImplUnsupported):
|
||||
return fmt.Errorf("migrate-v3: %w (an impl-2 volume stays on its old binary)", v2err)
|
||||
}
|
||||
stA, genA := storage.ClassifyMigrationSlotV3(a)
|
||||
stB, _ := storage.ClassifyMigrationSlotV3(b)
|
||||
switch {
|
||||
case stA == storage.MigrationSlotCommitted:
|
||||
// Committed. Finish step 6 if B was never rewritten, then step 7.
|
||||
if genA == 2 && stB != storage.MigrationSlotCommitted {
|
||||
rb, err := storage.RolloverSlotV3(a)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := pwriteSync(f, rb, storage.MigrationSlotBOffset); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return retireC11(path)
|
||||
case stB == storage.MigrationSlotCommitted:
|
||||
// Committed and possibly in use: only step 7.
|
||||
return retireC11(path)
|
||||
case stB == storage.MigrationSlotPrepared:
|
||||
// A torn step 5 or an old-binary run after preparation followed by
|
||||
// damage to A: the bytes cannot tell; never guess.
|
||||
return fmt.Errorf("migrate-v3: %w; nothing changed (an operator decision, using the backup)", storage.ErrMigrationIncomplete)
|
||||
default:
|
||||
return errMigrateNeitherSlot
|
||||
}
|
||||
}
|
||||
|
||||
func migrateFromV2(f *os.File, path string, sb v2legacy.Superblock, chunkBlocks uint64, out io.Writer) error {
|
||||
src := storage.MigrationSourceV3{
|
||||
UUID: sb.UUID, VolumeSize: sb.VolumeSize, ExtentSize: sb.ExtentSize, BlockSize: sb.BlockSize,
|
||||
OldWALOffset: sb.WALOffset, OldWALSize: sb.WALSize, CreatedAt: sb.CreatedAt,
|
||||
CheckpointLSN: sb.WALCheckpointLSN, ChunkBlocks: chunkBlocks,
|
||||
}
|
||||
// Precondition 4 first (read-only): the geometry, including the checked
|
||||
// extent end, refuses before the WAL is read or anything is written.
|
||||
if err := storage.ValidateMigrationV3(src); err != nil {
|
||||
return err
|
||||
}
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if size := uint64(fi.Size()); sb.WALOffset > size || sb.WALSize > size-sb.WALOffset { // no wrapping sum
|
||||
return fmt.Errorf("%w: the v2 WAL [%d, %d) extends past the file end %d", storage.ErrMigrateGeometry, sb.WALOffset, sb.WALOffset+sb.WALSize, fi.Size())
|
||||
}
|
||||
// Step 1: precondition 3, read-only and before any write.
|
||||
if sb.WALHead != sb.WALTail {
|
||||
return fmt.Errorf("%w (WALHead %d != WALTail %d)", errMigrateNotClean, sb.WALHead, sb.WALTail)
|
||||
}
|
||||
wal := make([]byte, sb.WALSize)
|
||||
if _, err := f.ReadAt(wal, int64(sb.WALOffset)); err != nil {
|
||||
return fmt.Errorf("migrate-v3: read the v2 WAL: %w", err)
|
||||
}
|
||||
if found := v2legacy.ScanClean(wal, sb.WALCheckpointLSN); len(found) > 0 {
|
||||
return fmt.Errorf("%w (%d unflushed record(s); first at WAL offset %d: %s)", errMigrateNotClean, len(found), found[0].Offset, found[0].Reason)
|
||||
}
|
||||
if err := step("scanned"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 2: the atomic operator backup of the v2 superblock.
|
||||
raw := make([]byte, v2legacy.SuperblockSize)
|
||||
if _, err := f.ReadAt(raw, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeFileAtomic(path+".v2-superblock.bak", raw); err != nil {
|
||||
return fmt.Errorf("migrate-v3: backup: %w", err)
|
||||
}
|
||||
if err := step("backup"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 3: the initial map sidecar (all UNKNOWN), durable.
|
||||
plan, err := storage.PrepareMigrationV3(path+".chunkmap", src)
|
||||
if err != nil {
|
||||
return fmt.Errorf("migrate-v3: initial map: %w", err)
|
||||
}
|
||||
if err := syncDirOf(path); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := step("map"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 4: the prepared slot B, over the old WAL's first 4 KiB.
|
||||
if err := pwriteSync(f, plan.PreparedB, storage.MigrationSlotBOffset); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := step("prepared"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 5: slot A, phase 0: the commit point.
|
||||
if err := pwriteSync(f, plan.CommittedA, storage.MigrationSlotAOffset); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := step("committed"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 6: slot B rewritten at phase 0 (two-slot redundancy).
|
||||
if err := pwriteSync(f, plan.RolloverB, storage.MigrationSlotBOffset); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := step("rollover"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 7: retire the v2 C11 bitmap, only after the commit.
|
||||
if err := retireC11(path); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 8.
|
||||
fmt.Fprintf(out, "migrated %s to v3: descriptor sha256 %s; backups left in place\n", path, hex.EncodeToString(plan.DescriptorHash[:]))
|
||||
return nil
|
||||
}
|
||||
|
||||
func step(name string) error {
|
||||
if h := migrateStepHook; h != nil {
|
||||
return h(name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pwriteSync(f *os.File, b []byte, off int64) error {
|
||||
if _, err := f.WriteAt(b, off); err != nil {
|
||||
return fmt.Errorf("migrate-v3: write at %d: %w", off, err)
|
||||
}
|
||||
if err := f.Sync(); err != nil {
|
||||
return fmt.Errorf("migrate-v3: fsync: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeFileAtomic writes b to name via name.tmp, fsync, rename and a
|
||||
// directory fsync; a leftover .tmp from an earlier run is replaced.
|
||||
func writeFileAtomic(name string, b []byte) error {
|
||||
tmp := name + ".tmp"
|
||||
if err := os.Remove(tmp); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
t, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := t.Write(b); err != nil {
|
||||
t.Close()
|
||||
return err
|
||||
}
|
||||
if err := t.Sync(); err != nil {
|
||||
t.Close()
|
||||
return err
|
||||
}
|
||||
if err := t.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, name); err != nil {
|
||||
return err
|
||||
}
|
||||
return syncDirOf(name)
|
||||
}
|
||||
|
||||
// retireC11 is step 7: rename a v2 .chunkbitmap sidecar to
|
||||
// <file>.v2-chunkbitmap.bak and fsync the directory. Absent is done.
|
||||
func retireC11(path string) error {
|
||||
err := os.Rename(path+".chunkbitmap", path+".v2-chunkbitmap.bak")
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
if _, serr := os.Stat(path + ".v2-chunkbitmap.bak"); serr != nil {
|
||||
return nil // there was no v2 bitmap
|
||||
}
|
||||
// An earlier run renamed it; its directory fsync may have failed, so
|
||||
// make the rename durable now (codex01 row 13b P2).
|
||||
return syncDirOf(path)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("migrate-v3: retire the v2 chunk bitmap: %w", err)
|
||||
}
|
||||
return syncDirOf(path)
|
||||
}
|
||||
|
||||
// syncDirOf fsyncs the directory holding path. A directory cannot be
|
||||
// fsynced on Windows; there it is a no-op, as in the provider.
|
||||
func syncDirOf(path string) error {
|
||||
if h := syncDirHook; h != nil {
|
||||
if err := h(path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
return nil
|
||||
}
|
||||
d, err := os.Open(filepath.Dir(path))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer d.Close()
|
||||
return d.Sync()
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//go:build swblock_format_v3_test
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestMigrateV3ExcludesOpenUntilCommitFinishes(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
parked, resume := make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
release := func() { once.Do(func() { close(resume) }) }
|
||||
defer release()
|
||||
migrateStepHook = func(step string) error {
|
||||
if step == "committed" {
|
||||
close(parked)
|
||||
<-resume
|
||||
}
|
||||
return nil
|
||||
}
|
||||
finished := make(chan error, 1)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
finished <- migrateV3(path, 4, &bytes.Buffer{})
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
release()
|
||||
select {
|
||||
case <-done:
|
||||
migrateStepHook = nil
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Error("migration worker did not stop during cleanup")
|
||||
}
|
||||
})
|
||||
select {
|
||||
case <-parked:
|
||||
case err := <-finished:
|
||||
t.Fatalf("migration stopped before the held commit: %v", err)
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("migration did not reach the held commit")
|
||||
}
|
||||
if s, err := storage.OpenMappedWALStoreV3Test(path); !errors.Is(err, storage.ErrWALStoreLocked) {
|
||||
if s != nil {
|
||||
_ = s.Close()
|
||||
}
|
||||
t.Fatalf("open during migration: %v, want volume locked", err)
|
||||
}
|
||||
release()
|
||||
select {
|
||||
case err := <-finished:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("migration did not release its lock")
|
||||
}
|
||||
s, err := storage.OpenMappedWALStoreV3Test(path)
|
||||
if err != nil {
|
||||
t.Fatalf("open after migration: %v", err)
|
||||
}
|
||||
_ = s.Close()
|
||||
}
|
||||
|
||||
func TestMigrateV3RefusesAnOpenV3Volume(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "volume")
|
||||
s, err := storage.CreateMappedWALStoreV3Test(path, 64, migBlock, 4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
// Windows byte-range locks reject reads through a second handle. Snapshot
|
||||
// only while no owner is open, then hold the real owner for the CLI call.
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := snapshotFiles(t, path)
|
||||
s, err = storage.OpenMappedWALStoreV3Test(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, msg := migrate(t, path)
|
||||
if code != 1 || !strings.Contains(msg, "locked") {
|
||||
t.Fatalf("migration must refuse an open v3 volume: exit=%d message=%s", code, msg)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !sameFiles(before, snapshotFiles(t, path)) {
|
||||
t.Fatal("refused migration modified the open volume")
|
||||
}
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("migration after owner close: exit=%d message=%s", code, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// Row 13b through the actual v3 open (tag swblock_format_v3_test).
|
||||
|
||||
// A migrated volume opens as v3 and serves the v2 blocks unchanged; its
|
||||
// map is the initial one (all UNKNOWN, covered = the v2 checkpoint); a
|
||||
// v3 write and a reopen work. Mutant: an initial map with clean entries
|
||||
// fails here.
|
||||
func TestMigrateV3VolumeOpensAsV3(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("migrate: %s", msg)
|
||||
}
|
||||
s, err := storage.OpenMappedWALStoreV3Test(path)
|
||||
if err != nil {
|
||||
t.Fatalf("v3 open of a migrated volume: %v", err)
|
||||
}
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
covered, allUnknown := storage.MapCoverageV3Test(s)
|
||||
if !allUnknown || covered != s.CheckpointLSN() {
|
||||
t.Fatalf("initial map: covered %d (checkpoint %d), all UNKNOWN %v", covered, s.CheckpointLSN(), allUnknown)
|
||||
}
|
||||
for lba := uint32(0); lba < 4; lba++ {
|
||||
got, err := s.Read(lba)
|
||||
if err != nil || !bytes.Equal(got, migBlk(0x10+byte(lba))) {
|
||||
t.Fatalf("LBA %d after migration: err %v", lba, err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Write(7, migBlk(0x77)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := storage.OpenMappedWALStoreV3Test(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Close()
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := r.Read(7); !bytes.Equal(got, migBlk(0x77)) {
|
||||
t.Fatal("a v3 write after migration did not survive a reopen")
|
||||
}
|
||||
}
|
||||
|
||||
// A prepared-only volume (stopped before the commit, A then damaged) is
|
||||
// refused by v3 open with ErrMigrationIncomplete, as by the tool.
|
||||
func TestMigrateV3PreparedOnlyRefusedByV3Open(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
migrateStepHook = func(s string) error {
|
||||
if s == "prepared" {
|
||||
return errors.New("stop")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
migrate(t, path)
|
||||
migrateStepHook = nil
|
||||
damageSlotA(t, path)
|
||||
if s, err := storage.OpenMappedWALStoreV3Test(path); !errors.Is(err, storage.ErrMigrationIncomplete) {
|
||||
if s != nil {
|
||||
_ = s.Close()
|
||||
}
|
||||
t.Fatalf("v3 open of a prepared-only volume: err = %v, want ErrMigrationIncomplete", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
//go:build swblock_format_v3_test
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/cmd/sw-block/internal/v2legacy"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// Plan row 13b controls (DESIGN r17.4 section 10.1; owner claude03), all
|
||||
// through the actual CLI entry (run).
|
||||
|
||||
const migBlock = 4096
|
||||
|
||||
func migBlk(b byte) []byte { return bytes.Repeat([]byte{b}, migBlock) }
|
||||
|
||||
// v2Volume creates a real v2/impl1 volume with 4 written blocks; clean
|
||||
// closes it (flushing), otherwise it is left synced but unflushed.
|
||||
func v2Volume(t *testing.T, clean bool) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "vol")
|
||||
s, err := storage.CreateLegacyWALStoreTest(path, 64, migBlock)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !clean {
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
}
|
||||
for lba := uint32(0); lba < 4; lba++ {
|
||||
if _, err := s.Write(lba, migBlk(0x10+byte(lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if clean {
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func migrate(t *testing.T, path string) (int, string) {
|
||||
t.Helper()
|
||||
var out, errb bytes.Buffer
|
||||
code := run([]string{"migrate-v3", "--chunk-blocks", "4", path}, &out, &errb)
|
||||
return code, out.String() + errb.String()
|
||||
}
|
||||
|
||||
// snapshotFiles reads the volume and every sidecar next to it.
|
||||
func snapshotFiles(t *testing.T, path string) map[string][]byte {
|
||||
t.Helper()
|
||||
got := map[string][]byte{}
|
||||
matches, _ := filepath.Glob(path + "*")
|
||||
for _, m := range matches {
|
||||
b, err := os.ReadFile(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got[filepath.Base(m)] = b
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func sameFiles(a, b map[string][]byte) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for k, v := range a {
|
||||
if !bytes.Equal(v, b[k]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// A clean v2 volume migrates: slot A committed (slotGen 2), slot B rolled
|
||||
// over (slotGen 3), every extent byte unchanged, the backup holds the old
|
||||
// superblock, a v2 chunk bitmap is retired, the old binary now refuses the
|
||||
// file, and a rerun changes no byte.
|
||||
func TestMigrateV3CleanVolume(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
if err := os.WriteFile(path+".chunkbitmap", []byte("c11"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb, err := v2legacy.ReadSuperblock(before)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
extentBase := sb.WALOffset + sb.WALSize
|
||||
if code, msg := migrate(t, path); code != 0 || !strings.Contains(msg, "descriptor sha256") {
|
||||
t.Fatalf("migrate: exit %d: %s", code, msg)
|
||||
}
|
||||
after, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(after[extentBase:], before[extentBase:]) {
|
||||
t.Fatal("the migration changed extent bytes")
|
||||
}
|
||||
if st, gen := storage.ClassifyMigrationSlotV3(after[:4096]); st != storage.MigrationSlotCommitted || gen != 2 {
|
||||
t.Fatalf("slot A: state %d gen %d, want committed gen 2", st, gen)
|
||||
}
|
||||
if st, gen := storage.ClassifyMigrationSlotV3(after[4096:8192]); st != storage.MigrationSlotCommitted || gen != 3 {
|
||||
t.Fatalf("slot B: state %d gen %d, want committed gen 3", st, gen)
|
||||
}
|
||||
if bak, err := os.ReadFile(path + ".v2-superblock.bak"); err != nil || !bytes.Equal(bak, before[:4096]) {
|
||||
t.Fatalf("backup: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(path + ".chunkbitmap"); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal("the v2 chunk bitmap was not retired")
|
||||
}
|
||||
if _, err := os.Stat(path + ".v2-chunkbitmap.bak"); err != nil {
|
||||
t.Fatalf("retired bitmap: %v", err)
|
||||
}
|
||||
if s, err := storage.OpenLegacyWALStoreTest(path); err == nil {
|
||||
_ = s.Close()
|
||||
t.Fatal("the old binary opened a migrated volume")
|
||||
}
|
||||
snap := snapshotFiles(t, path)
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("rerun: exit %d: %s", code, msg)
|
||||
}
|
||||
if !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatal("a rerun on a committed volume changed bytes")
|
||||
}
|
||||
}
|
||||
|
||||
// Refusals change no byte of the volume or any sidecar: an unflushed WAL
|
||||
// (ErrMigrateNotClean with the operator remedy), an impl-2 volume, and a
|
||||
// file with neither a v2 superblock nor a valid v3 slot. Mutant: skipping
|
||||
// the clean scan migrates the unflushed volume and fails here.
|
||||
func TestMigrateV3RefusalsChangeNothing(t *testing.T) {
|
||||
t.Run("unflushed WAL", func(t *testing.T) {
|
||||
path := v2Volume(t, false)
|
||||
snap := snapshotFiles(t, path)
|
||||
code, msg := migrate(t, path)
|
||||
if code == 0 || !strings.Contains(msg, "open with the old binary, flush, close cleanly, retry") {
|
||||
t.Fatalf("exit %d: %s", code, msg)
|
||||
}
|
||||
if !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatal("a refused migration changed bytes")
|
||||
}
|
||||
})
|
||||
t.Run("impl 2", func(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.WriteAt([]byte{2, 0, 0, 0}, 92); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
snap := snapshotFiles(t, path)
|
||||
if code, _ := migrate(t, path); code == 0 || !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatal("an impl-2 volume was not refused unchanged")
|
||||
}
|
||||
})
|
||||
t.Run("neither valid", func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "junk")
|
||||
if err := os.WriteFile(path, bytes.Repeat([]byte{0xEE}, 3*4096), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snap := snapshotFiles(t, path)
|
||||
if code, _ := migrate(t, path); code == 0 || !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatal("neither-valid was not refused unchanged")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A crash after each step is resumable from the slot bytes alone: before
|
||||
// the commit the rerun restarts with a full rescan; after it, the rerun
|
||||
// only finishes the rollover and the bitmap retirement.
|
||||
func TestMigrateV3CrashAfterEachStepIsResumable(t *testing.T) {
|
||||
for _, stop := range []string{"scanned", "backup", "map", "prepared", "committed", "rollover"} {
|
||||
t.Run(stop, func(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
if err := os.WriteFile(path+".chunkbitmap", []byte("c11"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
migrateStepHook = func(s string) error {
|
||||
if s == stop {
|
||||
return errors.New("simulated crash after " + s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
code, _ := migrate(t, path)
|
||||
migrateStepHook = nil
|
||||
if code == 0 {
|
||||
t.Fatal("the simulated crash did not stop the tool")
|
||||
}
|
||||
// Before the commit point (step 5) slot A is still the v2
|
||||
// superblock and the v2 bitmap is not retired; after it A is a
|
||||
// committed v3 slot.
|
||||
crashed, _ := os.ReadFile(path)
|
||||
_, v2err := v2legacy.ReadSuperblock(crashed[:4096])
|
||||
_, bitmapErr := os.Stat(path + ".chunkbitmap")
|
||||
if committed := stop == "committed" || stop == "rollover"; committed {
|
||||
if st, _ := storage.ClassifyMigrationSlotV3(crashed[:4096]); st != storage.MigrationSlotCommitted {
|
||||
t.Fatalf("crash after %s: slot A state %d, want committed", stop, st)
|
||||
}
|
||||
} else if v2err != nil || bitmapErr != nil {
|
||||
t.Fatalf("crash after %s: A still v2 = %v, bitmap present = %v; want both before the commit", stop, v2err == nil, bitmapErr == nil)
|
||||
}
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("rerun after a crash at %s: exit %d: %s", stop, code, msg)
|
||||
}
|
||||
raw, _ := os.ReadFile(path)
|
||||
if st, _ := storage.ClassifyMigrationSlotV3(raw[:4096]); st != storage.MigrationSlotCommitted {
|
||||
t.Fatalf("after the rerun slot A state %d, want committed", st)
|
||||
}
|
||||
if st, _ := storage.ClassifyMigrationSlotV3(raw[4096:8192]); st != storage.MigrationSlotCommitted {
|
||||
t.Fatalf("after the rerun slot B state %d, want committed", st)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The old binary runs after preparation (A is still v2, so it opens): the
|
||||
// rerun finds A still v2 and restarts with a full rescan; it refuses while
|
||||
// the old binary's writes are unflushed and migrates once it flushed and
|
||||
// closed. A prepared B with a damaged A is ambiguous and refused with
|
||||
// ErrMigrationIncomplete, writing nothing.
|
||||
func TestMigrateV3OldBinaryAfterPreparation(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
migrateStepHook = func(s string) error {
|
||||
if s == "prepared" {
|
||||
return errors.New("stop after preparation")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
migrate(t, path)
|
||||
migrateStepHook = nil
|
||||
s, err := storage.OpenLegacyWALStoreTest(path)
|
||||
if err != nil {
|
||||
t.Fatalf("the old binary refused a prepared-only volume: %v", err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := s.Write(9, migBlk(0x99)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snap := snapshotFiles(t, path)
|
||||
if code, msg := migrate(t, path); code == 0 || !strings.Contains(msg, "not cleanly flushed") {
|
||||
t.Fatalf("rerun over the old binary's unflushed write: exit %d: %s", code, msg)
|
||||
}
|
||||
if !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatal("a refused rerun changed bytes")
|
||||
}
|
||||
_ = s.Close() // stopped without a flush: still not clean
|
||||
if code, _ := migrate(t, path); code == 0 {
|
||||
t.Fatal("the rerun migrated a volume the old binary left unflushed")
|
||||
}
|
||||
// The operator remedy: open with the old binary, flush, close cleanly.
|
||||
s2, err := storage.OpenLegacyWALStoreTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s2.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s2.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("rerun after the old binary closed cleanly: exit %d: %s", code, msg)
|
||||
}
|
||||
|
||||
t.Run("prepared B with a damaged A", func(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
migrateStepHook = func(s string) error {
|
||||
if s == "prepared" {
|
||||
return errors.New("stop after preparation")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
migrate(t, path)
|
||||
migrateStepHook = nil
|
||||
f, _ := os.OpenFile(path, os.O_RDWR, 0)
|
||||
_, _ = f.WriteAt(bytes.Repeat([]byte{0xEE}, 4096), 0)
|
||||
f.Close()
|
||||
snap := snapshotFiles(t, path)
|
||||
code, msg := migrate(t, path)
|
||||
if code == 0 || !strings.Contains(msg, storage.ErrMigrationIncomplete.Error()) || !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatalf("exit %d: %s", code, msg)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The tool never reads or restores its backup: a committed volume reruns
|
||||
// to success with the backup damaged and its slots untouched.
|
||||
func TestMigrateV3NeverRestoresTheBackup(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("migrate: %s", msg)
|
||||
}
|
||||
if err := os.WriteFile(path+".v2-superblock.bak", []byte("damaged"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := os.ReadFile(path)
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("rerun: %s", msg)
|
||||
}
|
||||
now, _ := os.ReadFile(path)
|
||||
if !bytes.Equal(raw, now) {
|
||||
t.Fatal("a rerun changed the committed volume")
|
||||
}
|
||||
}
|
||||
|
||||
// The old v2 WAL starts at offset 4096, over the prepared slot B, so an
|
||||
// old-binary run can overwrite B partly or wholly (codex03 r8). Either way B
|
||||
// is an invalid slot, never prepared or committed: with A still v2 the rerun
|
||||
// restarts and migrates; with A damaged too, neither slot is valid and the
|
||||
// rerun refuses with no byte changed.
|
||||
func TestMigrateV3OldWALOverwritesThePreparedSlot(t *testing.T) {
|
||||
for _, n := range []int{100, 4096} {
|
||||
for _, damageA := range []bool{false, true} {
|
||||
name := map[int]string{100: "partial", 4096: "full"}[n]
|
||||
if damageA {
|
||||
name += " with A damaged"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
migrateStepHook = func(s string) error {
|
||||
if s == "prepared" {
|
||||
return errors.New("stop after preparation")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
migrate(t, path)
|
||||
migrateStepHook = nil
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.WriteAt(bytes.Repeat([]byte{0xA5}, n), 4096); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if damageA {
|
||||
if _, err := f.WriteAt(bytes.Repeat([]byte{0xEE}, 4096), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
f.Close()
|
||||
raw, _ := os.ReadFile(path)
|
||||
if st, _ := storage.ClassifyMigrationSlotV3(raw[4096:8192]); st != storage.MigrationSlotInvalid {
|
||||
t.Fatalf("an overwritten B classifies as %d, want invalid", st)
|
||||
}
|
||||
snap := snapshotFiles(t, path)
|
||||
code, msg := migrate(t, path)
|
||||
if damageA {
|
||||
if code == 0 || !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatalf("neither valid: exit %d, bytes changed: %s", code, msg)
|
||||
}
|
||||
return
|
||||
}
|
||||
if code != 0 {
|
||||
t.Fatalf("rerun with A still v2: exit %d: %s", code, msg)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func damageSlotA(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
if _, err := f.WriteAt(bytes.Repeat([]byte{0xEE}, 4096), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func patchSuperblock(t *testing.T, path string, off int64, v uint64) {
|
||||
t.Helper()
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
var b [8]byte
|
||||
for i := range b {
|
||||
b[i] = byte(v >> (8 * i))
|
||||
}
|
||||
if _, err := f.WriteAt(b[:], off); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// codex01 row 13b P1 and P2: geometry the v3 slot validation would refuse
|
||||
// is refused before ANY write (no backup, no map, the volume unchanged):
|
||||
// an aligned VolumeSize whose extent end overflows, and a v2 WAL size that
|
||||
// extends past the file end (refused before the scan allocates it).
|
||||
// Mutants: no checked extent end in ValidateMigrationV3, no file-size
|
||||
// bound before the WAL read.
|
||||
func TestMigrateV3BadGeometryRefusedBeforeAnyWrite(t *testing.T) {
|
||||
for name, patch := range map[string][2]uint64{
|
||||
"extent end overflows": {24, 1 << 63}, // VolumeSize, block aligned
|
||||
"WAL past the file end": {48, 1<<45 + 4096}, // WALSize, v3 size aligned
|
||||
"WAL region wraps": {48, ^uint64(0) - 4095}, // WALSize 2^64-4096: every sum wraps
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
patchSuperblock(t, path, int64(patch[0]), patch[1])
|
||||
snap := snapshotFiles(t, path)
|
||||
code, msg := migrate(t, path)
|
||||
if code == 0 || !strings.Contains(msg, "cannot be migrated in place") {
|
||||
t.Fatalf("exit %d: %s", code, msg)
|
||||
}
|
||||
if !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatal("a geometry refusal wrote a backup, a map or volume bytes")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// codex01 row 13b P2: an earlier run renamed the v2 chunk bitmap but its
|
||||
// directory fsync failed; the rerun (source gone) still fsyncs the
|
||||
// directory so the rename is durable. Mutant: treating the missing source
|
||||
// as done without the fsync fails here.
|
||||
func TestMigrateV3RetirementRerunFsyncsTheDirectory(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
if err := os.WriteFile(path+".chunkbitmap", []byte("c11"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failed := false
|
||||
syncDirHook = func(string) error {
|
||||
if _, err := os.Stat(path + ".v2-chunkbitmap.bak"); err == nil && !failed {
|
||||
failed = true
|
||||
return errors.New("injected directory fsync failure")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
defer func() { syncDirHook = nil }()
|
||||
if code, _ := migrate(t, path); code == 0 {
|
||||
t.Fatal("the injected retirement fsync failure did not fail the tool")
|
||||
}
|
||||
calls := 0
|
||||
syncDirHook = func(string) error { calls++; return nil }
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("rerun: exit %d: %s", code, msg)
|
||||
}
|
||||
if calls == 0 {
|
||||
t.Fatal("the rerun did not fsync the directory of the earlier rename")
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -157,12 +157,21 @@ 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
|
||||
workspaceUncertain map[string]bool
|
||||
workspaceNow func() time.Time
|
||||
workspaceTTL time.Duration
|
||||
workspaceMaxClockSkew time.Duration
|
||||
workspaceLeaseDeadline map[string]time.Time
|
||||
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
|
||||
workspaceMaxClockSkew time.Duration
|
||||
|
||||
// Lease renewal state (workspace_lease_view.go). leaseMu is a memory-only
|
||||
// leaf: lock order p.mu -> leaseMu, never the reverse, and nothing is
|
||||
// acquired, waited on or written while it is held.
|
||||
leaseMu sync.Mutex
|
||||
leaseViews map[string]*leaseView
|
||||
leaseClosing bool
|
||||
extWG sync.WaitGroup
|
||||
extendFailures map[string]int // guarded by mu
|
||||
}
|
||||
|
||||
// PublicationAdmission surrounds an ordinary mint with local ownership/lifetime
|
||||
@@ -221,15 +230,17 @@ func WithPublishObserver(observer PublishObserver) PublisherOption {
|
||||
// the pieces.
|
||||
func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher {
|
||||
p := &Publisher{
|
||||
dir: dir,
|
||||
state: make(map[subKey]assignmentState),
|
||||
subs: make(map[subKey][]*subscription),
|
||||
writeSeqByVolume: map[string]uint64{},
|
||||
workspace: map[string]*WorkspaceState{},
|
||||
workspaceUncertain: map[string]bool{},
|
||||
workspaceNow: time.Now,
|
||||
workspaceTTL: 30 * time.Second,
|
||||
workspaceLeaseDeadline: map[string]time.Time{},
|
||||
dir: dir,
|
||||
state: make(map[subKey]assignmentState),
|
||||
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,
|
||||
leaseViews: map[string]*leaseView{},
|
||||
extendFailures: map[string]int{},
|
||||
}
|
||||
for _, opt := range opts {
|
||||
if opt != nil {
|
||||
@@ -256,9 +267,6 @@ func (p *Publisher) reloadFromStore() {
|
||||
for _, rec := range records {
|
||||
if rec.Workspace != nil {
|
||||
p.workspace[rec.VolumeID] = cloneWorkspace(rec.Workspace)
|
||||
// Conservatively cover every previously granted TTL after restart.
|
||||
// Persisted wall time alone must never shorten a live host's lease.
|
||||
p.workspaceLeaseDeadline[rec.VolumeID] = p.workspaceNow().Add(p.workspaceTTL)
|
||||
}
|
||||
key := subKey{volumeID: rec.VolumeID, replicaID: rec.ReplicaID}
|
||||
p.state[key] = assignmentState{
|
||||
@@ -277,6 +285,20 @@ 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 {
|
||||
// Conservatively cover every previously granted TTL after restart.
|
||||
// Persisted wall time alone must never shorten a live host's lease.
|
||||
p.setLeaseDeadlineLocked(rec.VolumeID, p.workspaceNow().Add(p.workspaceTTL), false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LoadErrors returns the per-record skip errors observed during
|
||||
@@ -474,6 +496,15 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
|
||||
p.mu.Unlock()
|
||||
return ErrBindAlreadyBound
|
||||
}
|
||||
// Bind is genesis for the VOLUME, not only for this slot: once
|
||||
// any slot of the volume holds an authority line, a Bind for
|
||||
// another slot would mint a second epoch-1 line beside it.
|
||||
// Moving authority to another slot is IntentReassign.
|
||||
if bound, ok := boundReplicaForVolume(p.state, ask.VolumeID); ok {
|
||||
p.mu.Unlock()
|
||||
return fmt.Errorf("%w: volume %s is already bound to replica %s; use Reassign",
|
||||
ErrBindAlreadyBound, ask.VolumeID, bound)
|
||||
}
|
||||
next = adapter.AssignmentInfo{
|
||||
VolumeID: ask.VolumeID,
|
||||
ReplicaID: ask.ReplicaID,
|
||||
@@ -566,6 +597,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
|
||||
// unwind. Just report the failure.
|
||||
if record.Workspace != nil {
|
||||
p.workspaceUncertain[ask.VolumeID] = true
|
||||
p.refreshLeaseViewLocked(ask.VolumeID)
|
||||
}
|
||||
p.mu.Unlock()
|
||||
return fmt.Errorf("authority: durable Put failed, rolling back mint: %w", err)
|
||||
@@ -574,10 +606,13 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
|
||||
}
|
||||
if issuedWorkspace != nil {
|
||||
p.workspace[ask.VolumeID] = issuedWorkspace
|
||||
delete(p.workspaceLeaseDeadline, ask.VolumeID)
|
||||
}
|
||||
|
||||
p.state[k] = assignmentState{info: next, present: true}
|
||||
p.refreshLeaseViewLocked(ask.VolumeID)
|
||||
if issuedWorkspace != nil {
|
||||
p.setLeaseDeadlineLocked(ask.VolumeID, time.Time{}, false) // the issued move clears the lease
|
||||
}
|
||||
|
||||
// Snapshot subscribers under lock, release the lock BEFORE
|
||||
// delivering. This prevents a slow consumer goroutine from
|
||||
@@ -610,6 +645,22 @@ func safeInvokePublishObserver(observer func(PublishEvent), event PublishEvent)
|
||||
// treat that as "no per-volume authority line to advance".
|
||||
//
|
||||
// Must be called with p.mu held; reads p.state.
|
||||
// boundReplicaForVolume reports whether any slot of volumeID holds a
|
||||
// published authority line, and names one (the lowest replica id, so the
|
||||
// error text is deterministic). Presence, not the epoch value, decides.
|
||||
func boundReplicaForVolume(state map[subKey]assignmentState, volumeID string) (string, bool) {
|
||||
bound, found := "", false
|
||||
for k, st := range state {
|
||||
if !st.present || k.volumeID != volumeID {
|
||||
continue
|
||||
}
|
||||
if !found || k.replicaID < bound {
|
||||
bound, found = k.replicaID, true
|
||||
}
|
||||
}
|
||||
return bound, found
|
||||
}
|
||||
|
||||
func maxPublishedEpochForVolume(state map[subKey]assignmentState, volumeID string) uint64 {
|
||||
var max uint64
|
||||
for k, st := range state {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -362,6 +362,12 @@ func TestDurableAuthority_StoreWriteCallerAllowlist_BoundaryGuard(t *testing.T)
|
||||
if !strings.HasSuffix(path, ".go") {
|
||||
return nil
|
||||
}
|
||||
// Test doubles outside the package (for example a slow-store wrapper
|
||||
// that delays and then delegates Put) are not production write
|
||||
// callers; the guard is about the production tree.
|
||||
if strings.HasSuffix(path, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// The authority package itself is the only legitimate
|
||||
// write caller.
|
||||
if strings.Contains(path, string(filepath.Separator)+"core"+string(filepath.Separator)+"authority"+string(filepath.Separator)) {
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// #183: Bind is genesis for the volume. These cover the branches around
|
||||
// the per-volume check; the Run-path reproducer is
|
||||
// TestPublisher_RunRejectsSecondSlotGenesisBind.
|
||||
|
||||
func bindAsk(volumeID, replicaID string) AssignmentAsk {
|
||||
return AssignmentAsk{VolumeID: volumeID, ReplicaID: replicaID, DataAddr: "d-" + replicaID, CtrlAddr: "c-" + replicaID, Intent: IntentBind}
|
||||
}
|
||||
|
||||
func reassignAsk(volumeID, replicaID string) AssignmentAsk {
|
||||
ask := bindAsk(volumeID, replicaID)
|
||||
ask.Intent = IntentReassign
|
||||
return ask
|
||||
}
|
||||
|
||||
func TestPublisher_BindSecondSlotOfBoundVolumeRejected(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
if err := pub.apply(bindAsk("v1", "r1")); err != nil {
|
||||
t.Fatalf("first Bind: %v", err)
|
||||
}
|
||||
if err := pub.apply(bindAsk("v1", "r2")); !errors.Is(err, ErrBindAlreadyBound) {
|
||||
t.Fatalf("second-slot Bind: want ErrBindAlreadyBound, got %v", err)
|
||||
}
|
||||
if got, ok := pub.LastPublished("v1", "r2"); ok {
|
||||
t.Fatalf("second slot was published: %+v", got)
|
||||
}
|
||||
if got, ok := pub.LastPublished("v1", "r1"); !ok || got.Epoch != 1 || got.EndpointVersion != 1 {
|
||||
t.Fatalf("first slot line changed: %+v ok=%t", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_BindOtherVolumeUnaffected(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
if err := pub.apply(bindAsk("v1", "r1")); err != nil {
|
||||
t.Fatalf("Bind v1: %v", err)
|
||||
}
|
||||
if err := pub.apply(bindAsk("v2", "r2")); err != nil {
|
||||
t.Fatalf("Bind of a fresh volume rejected: %v", err)
|
||||
}
|
||||
if got, ok := pub.LastPublished("v2", "r2"); !ok || got.Epoch != 1 {
|
||||
t.Fatalf("fresh volume line=%+v ok=%t want epoch 1", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
if err := pub.apply(bindAsk("v1", "r1")); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
if err := pub.apply(reassignAsk("v1", "r2")); err != nil {
|
||||
t.Fatalf("Reassign to another slot: %v", err)
|
||||
}
|
||||
if got, ok := pub.LastPublished("v1", "r2"); !ok || got.Epoch != 2 {
|
||||
t.Fatalf("reassigned line=%+v ok=%t want epoch 2", got, ok)
|
||||
}
|
||||
for _, r := range []string{"r1", "r2", "r3"} {
|
||||
if err := pub.apply(bindAsk("v1", r)); !errors.Is(err, ErrBindAlreadyBound) {
|
||||
t.Fatalf("Bind %s after Reassign: want ErrBindAlreadyBound, got %v", r, err)
|
||||
}
|
||||
}
|
||||
if _, ok := pub.LastPublished("v1", "r3"); ok {
|
||||
t.Fatal("r3 was published by a Bind")
|
||||
}
|
||||
}
|
||||
|
||||
// The file store keeps one record per volume, so after a restart only the
|
||||
// current slot is in memory. A Bind for the earlier slot must still be
|
||||
// refused: the volume, not the key, is bound.
|
||||
func TestPublisher_BindAfterRestartRejectedForAnySlot(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
storeA, err := NewFileAuthorityStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pubA := NewPublisher(NewStaticDirective(nil), WithStore(storeA))
|
||||
if err := pubA.apply(bindAsk("v1", "r1")); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
if err := pubA.apply(reassignAsk("v1", "r2")); err != nil {
|
||||
t.Fatalf("Reassign: %v", err)
|
||||
}
|
||||
_ = storeA.Close()
|
||||
|
||||
storeB, err := NewFileAuthorityStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer storeB.Close()
|
||||
pubB := NewPublisher(NewStaticDirective(nil), WithStore(storeB))
|
||||
for _, r := range []string{"r1", "r2", "r3"} {
|
||||
if err := pubB.apply(bindAsk("v1", r)); !errors.Is(err, ErrBindAlreadyBound) {
|
||||
t.Fatalf("Bind %s after restart: want ErrBindAlreadyBound, got %v", r, err)
|
||||
}
|
||||
}
|
||||
if got, ok := pubB.LastPublished("v1", "r2"); !ok || got.Epoch != 2 {
|
||||
t.Fatalf("reloaded line=%+v ok=%t want r2 epoch 2", got, ok)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type bindRegressionDirective struct {
|
||||
asks *StaticDirective
|
||||
processed chan struct{}
|
||||
calls int
|
||||
}
|
||||
|
||||
func (d *bindRegressionDirective) Next(ctx context.Context) (AssignmentAsk, error) {
|
||||
d.calls++
|
||||
if d.calls == 3 {
|
||||
// Run requests another ask only after it settles the preceding apply.
|
||||
close(d.processed)
|
||||
<-ctx.Done()
|
||||
return AssignmentAsk{}, ctx.Err()
|
||||
}
|
||||
return d.asks.Next(ctx)
|
||||
}
|
||||
|
||||
func TestPublisher_RunRejectsSecondSlotGenesisBind(t *testing.T) {
|
||||
d := &bindRegressionDirective{processed: make(chan struct{}), asks: NewStaticDirective([]AssignmentAsk{
|
||||
{VolumeID: "v", ReplicaID: "r1", DataAddr: "d1", CtrlAddr: "c1", Intent: IntentBind},
|
||||
{VolumeID: "v", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentBind},
|
||||
})}
|
||||
pub := NewPublisher(d)
|
||||
first, cancelFirst := pub.Subscribe("v", "r1")
|
||||
defer cancelFirst()
|
||||
second, cancelSecond := pub.Subscribe("v", "r2")
|
||||
defer cancelSecond()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- pub.Run(ctx) }()
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Error("publisher did not stop")
|
||||
}
|
||||
})
|
||||
select {
|
||||
case <-first:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("first Bind did not publish")
|
||||
}
|
||||
select {
|
||||
case <-d.processed:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("publisher did not settle both asks")
|
||||
}
|
||||
select {
|
||||
case got := <-second:
|
||||
t.Fatalf("second slot received genesis authority: %+v; first volume Bind must exclude a second genesis", got)
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -26,8 +26,10 @@ type AskIntent int
|
||||
|
||||
const (
|
||||
// IntentBind: first-time binding for (VolumeID, ReplicaID).
|
||||
// Publisher mints Epoch=1, EndpointVersion=1. Rejected if a
|
||||
// prior publish already exists for the key.
|
||||
// Publisher mints Epoch=1, EndpointVersion=1. Rejected
|
||||
// (ErrBindAlreadyBound) if a prior publish already exists for the
|
||||
// key or for any other slot of the same volume: Bind is genesis
|
||||
// for the volume; another slot is reached by IntentReassign.
|
||||
IntentBind AskIntent = iota + 1
|
||||
|
||||
// IntentRefreshEndpoint: same volume/replica, new transport
|
||||
|
||||
@@ -92,41 +92,6 @@ func (p *Publisher) workspaceSkew(lease *WorkspaceLease) time.Duration {
|
||||
return skew
|
||||
}
|
||||
|
||||
func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return WorkspaceLease{}, err
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
_, line, ok := p.workspaceLineLocked(volume)
|
||||
if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch {
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority")
|
||||
}
|
||||
s := cloneWorkspace(p.workspace[volume])
|
||||
if s == nil {
|
||||
s = &WorkspaceState{}
|
||||
}
|
||||
if len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued {
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: move pending")
|
||||
}
|
||||
now := p.workspaceNow()
|
||||
if s.Lease != nil {
|
||||
if s.Lease.Revoking {
|
||||
return *s.Lease, nil
|
||||
} // tell the host to drain; never extend
|
||||
if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.workspaceLeaseDeadline[volume]) {
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease expired or revoking")
|
||||
}
|
||||
}
|
||||
lease := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(s.Lease))}
|
||||
s.Lease = &lease
|
||||
if err := p.persistWorkspaceLocked(volume, s); err != nil {
|
||||
return WorkspaceLease{}, err
|
||||
}
|
||||
p.workspaceLeaseDeadline[volume] = now.Add(p.workspaceTTL)
|
||||
return lease, nil
|
||||
}
|
||||
|
||||
// Replica IDs are logical assignment identities; HEAD.Holder is qualified
|
||||
// as <server-id>/<replica-id> and is checked separately against ExpectedHost.
|
||||
type WorkspaceMoveRequest struct {
|
||||
@@ -246,7 +211,7 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a
|
||||
return fmt.Errorf("workspace revoke ACK: stale or unsolicited")
|
||||
}
|
||||
now := p.workspaceNow()
|
||||
if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.workspaceLeaseDeadline[volume]) {
|
||||
if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.leaseDeadlineLocked(volume)) {
|
||||
return fmt.Errorf("workspace revoke ACK: lease expired; forced move required")
|
||||
}
|
||||
if s.Ack != nil && *s.Ack != ack {
|
||||
@@ -286,10 +251,12 @@ func (p *Publisher) persistWorkspaceLocked(volume string, s *WorkspaceState) err
|
||||
WriteSeq: p.writeSeqByVolume[volume] + 1, Workspace: cloneWorkspace(s)}
|
||||
if err := p.store.Put(record); err != nil {
|
||||
p.workspaceUncertain[volume] = true
|
||||
p.refreshLeaseViewLocked(volume)
|
||||
return err
|
||||
}
|
||||
p.writeSeqByVolume[volume] = record.WriteSeq
|
||||
p.workspace[volume] = cloneWorkspace(s)
|
||||
p.refreshLeaseViewLocked(volume)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -313,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.workspaceLeaseDeadline[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.
|
||||
@@ -327,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
|
||||
@@ -352,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
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,61 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// #242: a renewal refused for lack of host validity formats its error from
|
||||
// the lease view; that read must happen under leaseMu, because the extender
|
||||
// (refreshLeaseViewLocked) rewrites the view under leaseMu at any time.
|
||||
// Run with -race: renewals that take the refusal run while another goroutine
|
||||
// rewrites the view, as the extender does.
|
||||
func TestWorkspaceLeaseRefusalReadsTheViewUnderTheLock(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
c := newTestClock()
|
||||
p := newLeasePublisher(t, disk, 3*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
// Force the no-host-validity refusal: the horizon just ahead, a skew
|
||||
// bound far larger than what is left of it; the granted deadline later.
|
||||
p.leaseMu.Lock()
|
||||
lv := p.leaseViews["v"]
|
||||
lv.d.horizon = c.now().Add(time.Millisecond).UnixNano()
|
||||
lv.d.maxSkewNS = int64(time.Hour)
|
||||
lv.deadline = c.now().Add(time.Hour)
|
||||
p.leaseMu.Unlock()
|
||||
|
||||
const rounds = 200
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() { // the extender's republish: a write of the view under leaseMu
|
||||
defer wg.Done()
|
||||
for i := 0; i < rounds; i++ {
|
||||
p.leaseMu.Lock()
|
||||
d := lv.d
|
||||
lv.d = d
|
||||
p.leaseMu.Unlock()
|
||||
}
|
||||
}()
|
||||
errs := make(chan error, 1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < rounds; i++ {
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil || !strings.Contains(err.Error(), "leaves no host validity") {
|
||||
select {
|
||||
case errs <- err:
|
||||
default:
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
wg.Wait()
|
||||
select {
|
||||
case err := <-errs:
|
||||
t.Fatalf("renewal with no host validity: %v; want the refusal", err)
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// leaseDerived is the part of a volume's lease view that is a pure function
|
||||
// of published publisher state (derive). Writers recompute it under
|
||||
// p.mu -> leaseMu at every point where an input changes, so that whenever
|
||||
// p.mu is released the view equals derive(published) (INV-LEASE-VIEW-001).
|
||||
type leaseDerived struct {
|
||||
bound bool // an authority line exists for the volume
|
||||
replica string
|
||||
epoch uint64
|
||||
leasePresent bool
|
||||
revoking bool
|
||||
movePending bool // the last workspace move is reserved, not issued
|
||||
uncertain bool // a workspace write of the volume failed (INV-AUTH-UNCERTAIN-001)
|
||||
storeless bool
|
||||
horizon int64 // published Lease.ExpiresAtNS: durable upper bound of every grant
|
||||
maxSkewNS int64
|
||||
lease WorkspaceLease // the published (durable) lease
|
||||
}
|
||||
|
||||
// leaseView is one volume's renewal state. Guarded by Publisher.leaseMu.
|
||||
// deadline (the latest grant, or the restart rule's now+TTL) and extending
|
||||
// are owned by the view; d is derived.
|
||||
type leaseView struct {
|
||||
d leaseDerived
|
||||
deadline time.Time
|
||||
extending bool
|
||||
clamped bool // a renewal was clamped below now+TTL; logged once per streak
|
||||
}
|
||||
|
||||
// deriveLeaseLocked computes the derived lease view from published state.
|
||||
// Caller holds p.mu.
|
||||
func (p *Publisher) deriveLeaseLocked(volume string) leaseDerived {
|
||||
d := leaseDerived{uncertain: p.workspaceUncertain[volume], storeless: p.store == nil, maxSkewNS: int64(p.workspaceSkew(nil))}
|
||||
if _, line, ok := p.workspaceLineLocked(volume); ok {
|
||||
d.bound, d.replica, d.epoch = true, line.info.ReplicaID, line.info.Epoch
|
||||
}
|
||||
if s := p.workspace[volume]; s != nil {
|
||||
d.movePending = len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued
|
||||
if s.Lease != nil {
|
||||
d.leasePresent, d.revoking, d.horizon, d.lease = true, s.Lease.Revoking, s.Lease.ExpiresAtNS, *s.Lease
|
||||
d.maxSkewNS = int64(p.workspaceSkew(s.Lease))
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// refreshLeaseViewLocked republishes the derived view of volume. Caller holds
|
||||
// p.mu; this takes leaseMu (the only p.mu -> leaseMu edge besides deadline
|
||||
// reads). Called at every mutation of a derive input: the authority line, the
|
||||
// published workspace state, uncertainty, and closing.
|
||||
func (p *Publisher) refreshLeaseViewLocked(volume string) {
|
||||
d := p.deriveLeaseLocked(volume)
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
lv := p.leaseViews[volume]
|
||||
if lv == nil {
|
||||
lv = &leaseView{}
|
||||
p.leaseViews[volume] = lv
|
||||
}
|
||||
lv.d = d
|
||||
}
|
||||
|
||||
// leaseDeadlineLocked reads the granted deadline. Caller holds p.mu.
|
||||
func (p *Publisher) leaseDeadlineLocked(volume string) time.Time {
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
if lv := p.leaseViews[volume]; lv != nil {
|
||||
return lv.deadline
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
// setLeaseDeadlineLocked replaces the deadline (restart rule, move issue) or,
|
||||
// with raise, raises it to at least t (a grant). Caller holds p.mu.
|
||||
func (p *Publisher) setLeaseDeadlineLocked(volume string, t time.Time, raise bool) {
|
||||
d := p.deriveLeaseLocked(volume)
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
lv := p.leaseViews[volume]
|
||||
if lv == nil {
|
||||
lv = &leaseView{d: d}
|
||||
p.leaseViews[volume] = lv
|
||||
}
|
||||
if !raise || t.After(lv.deadline) {
|
||||
lv.deadline = t
|
||||
}
|
||||
}
|
||||
|
||||
// replyExpiryNS is the expiry reported to a host: never the raw durable
|
||||
// horizon, only what was granted (min(horizon, deadline)).
|
||||
func (lv *leaseView) replyExpiryNS() int64 {
|
||||
if lv.deadline.IsZero() {
|
||||
return lv.d.horizon // unreachable: a published lease always has a deadline
|
||||
}
|
||||
if dl := lv.deadline.UnixNano(); dl < lv.d.horizon {
|
||||
return dl
|
||||
}
|
||||
return lv.d.horizon
|
||||
}
|
||||
|
||||
// WorkspaceLeaseReply returns the published lease with its expiry clamped to
|
||||
// what was granted (min(durable horizon, granted deadline)), for replies that
|
||||
// report a lease to a host or operator. ok is false without a lease.
|
||||
func (p *Publisher) WorkspaceLeaseReply(volume string) (WorkspaceLease, bool) {
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
lv := p.leaseViews[volume]
|
||||
if lv == nil || !lv.d.leasePresent {
|
||||
return WorkspaceLease{}, false
|
||||
}
|
||||
l := lv.d.lease
|
||||
l.ExpiresAtNS = lv.replyExpiryNS()
|
||||
return l, true
|
||||
}
|
||||
|
||||
// RenewWorkspaceLease answers a live holder from memory: it takes only the
|
||||
// leaf leaseMu, does no I/O and never waits on p.mu or the store. The grant
|
||||
// is min(now+TTL, durable horizon); a background extender (an ordinary p.mu
|
||||
// writer) pushes the horizon ahead. Only the first grant of a lease writes
|
||||
// synchronously (firstWorkspaceGrant).
|
||||
func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return WorkspaceLease{}, err
|
||||
}
|
||||
p.leaseMu.Lock()
|
||||
now := p.workspaceNow() // read under leaseMu: the forced-barrier argument needs it
|
||||
lv := p.leaseViews[volume]
|
||||
if lv == nil || !lv.d.bound || lv.d.replica != holder || lv.d.epoch != epoch {
|
||||
p.leaseMu.Unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority")
|
||||
}
|
||||
if lv.d.movePending {
|
||||
p.leaseMu.Unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: move pending")
|
||||
}
|
||||
if !lv.d.leasePresent {
|
||||
p.leaseMu.Unlock() // never re-enter p.mu while holding the leaf
|
||||
return p.firstWorkspaceGrant(ctx, volume, holder, epoch)
|
||||
}
|
||||
if lv.d.revoking { // tell the host to drain; never extend
|
||||
l := lv.d.lease
|
||||
l.ExpiresAtNS = lv.replyExpiryNS()
|
||||
p.leaseMu.Unlock()
|
||||
return l, nil
|
||||
}
|
||||
if now.UnixNano() >= lv.d.horizon || !now.Before(lv.deadline) {
|
||||
p.leaseMu.Unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease expired or revoking")
|
||||
}
|
||||
// Where the synchronous write used to refuse (persistWorkspaceLocked):
|
||||
// a renewal never bypasses uncertainty (INV-AUTH-UNCERTAIN-001).
|
||||
if lv.d.storeless || lv.d.uncertain {
|
||||
p.leaseMu.Unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain")
|
||||
}
|
||||
grant := now.Add(p.workspaceTTL).UnixNano()
|
||||
clamped := grant > lv.d.horizon
|
||||
if clamped {
|
||||
grant = lv.d.horizon
|
||||
}
|
||||
// A grant without positive host validity (expiry minus half the skew
|
||||
// bound, leaseFact) would make the host fence on an invalid reply and lose
|
||||
// its remaining validity; refuse with an error instead.
|
||||
if grant-lv.d.maxSkewNS/2 <= now.UnixNano() {
|
||||
horizon := lv.d.horizon // the view is leaseMu's: read it before the unlock (#242)
|
||||
p.leaseMu.Unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, horizon).UTC().Format(time.RFC3339Nano))
|
||||
}
|
||||
if g := time.Unix(0, grant); g.After(lv.deadline) {
|
||||
lv.deadline = g
|
||||
}
|
||||
var note string
|
||||
switch {
|
||||
case clamped && !lv.clamped:
|
||||
lv.clamped = true
|
||||
note = fmt.Sprintf("workspace lease: grants of volume=%s are clamped to the durable horizon %s (%s remaining); extensions are behind",
|
||||
volume, time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano), time.Duration(lv.d.horizon-now.UnixNano()).Round(time.Millisecond))
|
||||
case !clamped && lv.clamped:
|
||||
lv.clamped = false
|
||||
note = fmt.Sprintf("workspace lease: grants of volume=%s are no longer clamped (horizon %s)", volume, time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano))
|
||||
}
|
||||
if lv.d.horizon < now.Add(p.workspaceTTL+p.workspaceTTL/4).UnixNano() && !lv.extending && !p.leaseClosing {
|
||||
lv.extending = true
|
||||
p.extWG.Add(1) // under leaseMu with !closing: no Add can follow CloseWorkspaceExtenders
|
||||
go p.extendWorkspaceLease(volume, holder, epoch, now)
|
||||
}
|
||||
l := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS}
|
||||
p.leaseMu.Unlock()
|
||||
if note != "" {
|
||||
log.Print(note)
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// firstWorkspaceGrant creates a lease synchronously under p.mu (one write per
|
||||
// assignment epoch). A host whose first renewal fails does not fence: it has
|
||||
// no deadline yet and retries. The durable horizon starts at now+1.5*TTL.
|
||||
func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
|
||||
p.mu.Lock()
|
||||
_, line, ok := p.workspaceLineLocked(volume)
|
||||
if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch {
|
||||
p.mu.Unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority")
|
||||
}
|
||||
s := cloneWorkspace(p.workspace[volume])
|
||||
if s == nil {
|
||||
s = &WorkspaceState{}
|
||||
}
|
||||
if len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued {
|
||||
p.mu.Unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: move pending")
|
||||
}
|
||||
if s.Lease != nil {
|
||||
// Another writer created the lease after the view was read. Do not
|
||||
// re-enter the memory path from here (no mutual recursion): the host has
|
||||
// no deadline yet, so a failed first renewal does not fence it, and its
|
||||
// retry takes the memory path.
|
||||
p.mu.Unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: created concurrently; retry")
|
||||
}
|
||||
now := p.workspaceNow()
|
||||
skew := int64(p.workspaceSkew(nil))
|
||||
grant := now.Add(p.workspaceTTL)
|
||||
s.Lease = &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: skew}
|
||||
if err := p.persistWorkspaceLocked(volume, s); err != nil {
|
||||
p.mu.Unlock()
|
||||
return WorkspaceLease{}, err
|
||||
}
|
||||
p.setLeaseDeadlineLocked(volume, grant, true)
|
||||
p.mu.Unlock()
|
||||
return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: skew}, nil
|
||||
}
|
||||
|
||||
// extendWorkspaceLease is an ordinary writer: under p.mu it rechecks the
|
||||
// lease and writes horizon H = trigger + 1.5*TTL through
|
||||
// persistWorkspaceLocked, so its write and its publication are one p.mu
|
||||
// section. Any write error is an unknown write and latches uncertainty
|
||||
// (INV-AUTH-UNCERTAIN-001); a failed recheck is a known no-write.
|
||||
func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, trigger time.Time) {
|
||||
defer p.extWG.Done()
|
||||
var note string
|
||||
defer func() {
|
||||
if note != "" {
|
||||
log.Print(note)
|
||||
}
|
||||
}()
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
defer func() {
|
||||
p.leaseMu.Lock()
|
||||
if lv := p.leaseViews[volume]; lv != nil {
|
||||
lv.extending = false
|
||||
}
|
||||
p.leaseMu.Unlock()
|
||||
}()
|
||||
p.leaseMu.Lock()
|
||||
closing := p.leaseClosing
|
||||
p.leaseMu.Unlock()
|
||||
if closing {
|
||||
return
|
||||
}
|
||||
_, line, ok := p.workspaceLineLocked(volume)
|
||||
s := cloneWorkspace(p.workspace[volume])
|
||||
if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch || s == nil || s.Lease == nil || s.Lease.Revoking ||
|
||||
s.Lease.ReplicaID != holder || s.Lease.Epoch != epoch || (len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued) ||
|
||||
p.workspaceUncertain[volume] || p.store == nil {
|
||||
return
|
||||
}
|
||||
h := trigger.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano()
|
||||
old := s.Lease.ExpiresAtNS
|
||||
if h <= old {
|
||||
return
|
||||
}
|
||||
s.Lease.ExpiresAtNS = h
|
||||
start := time.Now()
|
||||
err := p.persistWorkspaceLocked(volume, s)
|
||||
took := time.Since(start).Round(time.Millisecond)
|
||||
if err != nil {
|
||||
if p.extendFailures[volume] == 0 {
|
||||
note = fmt.Sprintf("workspace lease: extension of volume=%s failed after %s (horizon %s, %s remaining); the volume is now uncertain and its renewals are refused: %v",
|
||||
volume, took, time.Unix(0, old).UTC().Format(time.RFC3339Nano), time.Until(time.Unix(0, old)).Round(time.Millisecond), err)
|
||||
}
|
||||
p.extendFailures[volume]++
|
||||
return
|
||||
}
|
||||
if n := p.extendFailures[volume]; n > 0 {
|
||||
note = fmt.Sprintf("workspace lease: extension of volume=%s recovered after %d failures, took %s, horizon now %s", volume, n, took, time.Unix(0, h).UTC().Format(time.RFC3339Nano))
|
||||
delete(p.extendFailures, volume)
|
||||
}
|
||||
}
|
||||
|
||||
// CloseWorkspaceExtenders stops admitting lease extensions and joins every
|
||||
// admitted extender. Owners call it before closing the authority store:
|
||||
// closing is set under p.mu -> leaseMu, so an extender either finished its
|
||||
// write before or sees closing and does not write.
|
||||
func (p *Publisher) CloseWorkspaceExtenders() {
|
||||
p.mu.Lock()
|
||||
p.leaseMu.Lock()
|
||||
p.leaseClosing = true
|
||||
p.leaseMu.Unlock()
|
||||
p.mu.Unlock()
|
||||
p.extWG.Wait()
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// slowLeaseStore delays every workspace-lease Put once armed, standing in for
|
||||
// a master disk whose fsync stalls under heavy I/O (issue #205).
|
||||
type slowLeaseStore struct {
|
||||
AuthorityStore
|
||||
delayNS atomic.Int64
|
||||
puts atomic.Int64 // delayed (armed) lease writes: proves the stall was exercised
|
||||
}
|
||||
|
||||
func (s *slowLeaseStore) Put(r DurableRecord) error {
|
||||
if d := time.Duration(s.delayNS.Load()); d > 0 && r.Workspace != nil && r.Workspace.Lease != nil {
|
||||
s.puts.Add(1)
|
||||
time.Sleep(d)
|
||||
}
|
||||
return s.AuthorityStore.Put(r)
|
||||
}
|
||||
|
||||
// A renewal of a live lease must not wait for the authority store's fsync:
|
||||
// the host's renewal RPC times out after 2 s, so a slower store write on the
|
||||
// renewal path turns into a host fence and a volume shutdown (issue #205).
|
||||
func TestWorkspaceRenewalDoesNotWaitForSlowStore(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
slow := &slowLeaseStore{AuthorityStore: disk}
|
||||
var nowNS atomic.Int64
|
||||
nowNS.Store(time.Unix(1000, 0).UnixNano())
|
||||
p := NewPublisher(nil, WithStore(slow), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) }))
|
||||
t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := p.RenewWorkspaceLease(context.Background(), "v", "old", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
slow.delayNS.Store(int64(2500 * time.Millisecond))
|
||||
t.Cleanup(func() { slow.delayNS.Store(0) })
|
||||
nowNS.Add(int64(10 * time.Second))
|
||||
start := time.Now()
|
||||
second, err := p.RenewWorkspaceLease(context.Background(), "v", "old", 1)
|
||||
took := time.Since(start)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if second.ExpiresAtNS <= first.ExpiresAtNS {
|
||||
t.Fatalf("renewal did not extend the grant: first=%d second=%d", first.ExpiresAtNS, second.ExpiresAtNS)
|
||||
}
|
||||
if took >= 2*time.Second {
|
||||
t.Fatalf("renewal of a live lease took %s behind a 2.5 s store write; the host's renewal RPC times out at 2 s", took.Round(time.Millisecond))
|
||||
}
|
||||
t.Logf("renewal took %s", took)
|
||||
waitExtenders(t, p)
|
||||
if slow.puts.Load() == 0 {
|
||||
t.Fatal("no lease write went through the 2.5 s stall: the test did not exercise it")
|
||||
}
|
||||
}
|
||||
|
||||
// Renewals of different volumes must not queue behind each other's store
|
||||
// writes: with six volumes and a 0.5 s write each, serializing them makes the
|
||||
// last renewal wait about 3 s, past the host's 2 s renewal timeout.
|
||||
func TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
slow := &slowLeaseStore{AuthorityStore: disk}
|
||||
var nowNS atomic.Int64
|
||||
nowNS.Store(time.Unix(1000, 0).UnixNano())
|
||||
p := NewPublisher(nil, WithStore(slow), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) }))
|
||||
t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes
|
||||
const n = 6
|
||||
for i := 0; i < n; i++ {
|
||||
v := fmt.Sprintf("v%d", i)
|
||||
if err := p.apply(AssignmentAsk{VolumeID: v, ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), v, "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
slow.delayNS.Store(int64(500 * time.Millisecond))
|
||||
t.Cleanup(func() { slow.delayNS.Store(0) })
|
||||
nowNS.Add(int64(10 * time.Second))
|
||||
var wg sync.WaitGroup
|
||||
took := make([]time.Duration, n)
|
||||
errs := make([]error, n)
|
||||
gate := make(chan struct{})
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
<-gate
|
||||
start := time.Now()
|
||||
_, errs[i] = p.RenewWorkspaceLease(context.Background(), fmt.Sprintf("v%d", i), "r", 1)
|
||||
took[i] = time.Since(start)
|
||||
}(i)
|
||||
}
|
||||
close(gate)
|
||||
wg.Wait()
|
||||
var slowest time.Duration
|
||||
for i := 0; i < n; i++ {
|
||||
if errs[i] != nil {
|
||||
t.Fatalf("v%d: %v", i, errs[i])
|
||||
}
|
||||
if took[i] > slowest {
|
||||
slowest = took[i]
|
||||
}
|
||||
}
|
||||
if slowest >= 2*time.Second {
|
||||
t.Fatalf("slowest of %d concurrent renewals took %s (all: %v); renewals serialize behind each other's store writes", n, slowest.Round(time.Millisecond), took)
|
||||
}
|
||||
t.Logf("slowest of %d concurrent renewals took %s", n, slowest)
|
||||
waitExtenders(t, p)
|
||||
if slow.puts.Load() == 0 {
|
||||
t.Fatal("no lease write went through the 0.5 s stall: the test did not exercise it")
|
||||
}
|
||||
}
|
||||
|
||||
// heldWriteStore blocks the first Put that matches hold until release closes,
|
||||
// standing in for one slow synchronous authority write.
|
||||
type heldWriteStore struct {
|
||||
AuthorityStore
|
||||
hold func(DurableRecord) bool
|
||||
once sync.Once
|
||||
entered chan struct{}
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (s *heldWriteStore) Put(r DurableRecord) error {
|
||||
if s.hold != nil && s.hold(r) {
|
||||
held := false
|
||||
s.once.Do(func() { held = true })
|
||||
if held {
|
||||
close(s.entered)
|
||||
<-s.release
|
||||
}
|
||||
}
|
||||
return s.AuthorityStore.Put(r)
|
||||
}
|
||||
|
||||
// A slow synchronous write of one volume (here the revocation of a) must not
|
||||
// block the renewal of an unrelated volume b: renewal needs no write of its
|
||||
// own, so it must not wait on a's store I/O (issue #205).
|
||||
func TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
held := &heldWriteStore{AuthorityStore: disk, entered: make(chan struct{}), release: make(chan struct{}),
|
||||
hold: func(r DurableRecord) bool {
|
||||
return r.VolumeID == "a" && r.Workspace != nil && r.Workspace.Lease != nil && r.Workspace.Lease.Revoking
|
||||
}}
|
||||
var nowNS atomic.Int64
|
||||
nowNS.Store(time.Unix(1000, 0).UnixNano())
|
||||
p := NewPublisher(nil, WithStore(held), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) }))
|
||||
t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes
|
||||
for _, v := range []string{"a", "b"} {
|
||||
if err := p.apply(AssignmentAsk{VolumeID: v, ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), v, "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(held.release) }) }
|
||||
revoked := make(chan error, 1)
|
||||
go func() { revoked <- p.BeginWorkspaceRevocation(context.Background(), "a", "r", 1) }()
|
||||
// Bounded cleanup: release the held write first, then settle the worker.
|
||||
t.Cleanup(func() {
|
||||
release()
|
||||
select {
|
||||
case <-revoked:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("held revocation of a did not settle within 5 s after release")
|
||||
}
|
||||
})
|
||||
select {
|
||||
case <-held.entered:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("revocation of a never reached the store")
|
||||
}
|
||||
nowNS.Add(int64(10 * time.Second))
|
||||
renewed := make(chan error, 1)
|
||||
start := time.Now()
|
||||
go func() {
|
||||
_, err := p.RenewWorkspaceLease(context.Background(), "b", "r", 1)
|
||||
renewed <- err
|
||||
}()
|
||||
select {
|
||||
case err := <-renewed:
|
||||
if err != nil {
|
||||
t.Fatalf("renewal of b: %v", err)
|
||||
}
|
||||
t.Logf("renewal of b took %s while a's write was held", time.Since(start))
|
||||
case <-time.After(2 * time.Second):
|
||||
blocked := time.Since(start).Round(time.Millisecond)
|
||||
release()
|
||||
select {
|
||||
case err := <-renewed:
|
||||
t.Fatalf("renewal of b was still blocked %s behind the held store write of a (it returned only after a was released, err=%v)", blocked, err)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("renewal of b was still blocked %s behind the held store write of a, and did not settle within 5 s after release", blocked)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,10 @@ func TestWorkspaceClockSkewPersistsAndProtectsRestart(t *testing.T) {
|
||||
if lease.MaxClockSkewNS != int64(4*time.Second) {
|
||||
t.Fatal("configured margin not in durable grant", lease)
|
||||
}
|
||||
boundary := start.Add(10 * time.Second)
|
||||
// The first grant persists the durable horizon start+1.5*TTL (9 s),
|
||||
// the upper bound of every later grant; the forced barrier is
|
||||
// horizon + skew, TTL/2 later than the grant itself (#205).
|
||||
boundary := start.Add(9*time.Second + 4*time.Second)
|
||||
if restart {
|
||||
now = start.Add(7 * time.Second)
|
||||
p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(6*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(time.Second))
|
||||
|
||||
@@ -35,7 +35,8 @@ func TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant(t *testing.T) {
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "old", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now = now.Add(2 * time.Second)
|
||||
// Past the durable horizon (1.5*TTL) plus skew, not only the grant (#205).
|
||||
now = now.Add(3 * time.Second)
|
||||
req := WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
|
||||
head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42}
|
||||
fault.failIssue = true
|
||||
@@ -224,7 +225,8 @@ func TestWorkspaceMoveUsesQualifiedHEADHolder(t *testing.T) {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "same", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now = now.Add(2 * time.Second)
|
||||
// Past the durable horizon (1.5*TTL) plus skew, not only the grant (#205).
|
||||
now = now.Add(3 * time.Second)
|
||||
q := WorkspaceMoveRequest{RequestID: "qualified", VolumeID: "v", ExpectedReplicaID: "same", TargetReplicaID: "same", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
|
||||
for _, holder := range []string{"same", "other-node/same", "old-node/other"} {
|
||||
if _, err := p.MoveWorkspace(ctx, q, WorkspaceHead{Gen: 7, Epoch: 1, Holder: holder, RemoteLSN: 42}); err == nil {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
csipb "github.com/container-storage-interface/spec/lib/go/csi"
|
||||
"github.com/seaweedfs/seaweed-block/core/geometry"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
@@ -248,6 +249,9 @@ func volumeSpecFromCreateRequest(req *csipb.CreateVolumeRequest) (VolumeSpec, er
|
||||
if size <= 0 {
|
||||
return VolumeSpec{}, status.Error(codes.InvalidArgument, "capacity is required")
|
||||
}
|
||||
if err := geometry.ValidateVolumeSize(uint64(size)); err != nil {
|
||||
return VolumeSpec{}, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
if len(req.GetVolumeCapabilities()) == 0 {
|
||||
return VolumeSpec{}, status.Error(codes.InvalidArgument, "volume capabilities are required")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package csi
|
||||
|
||||
import (
|
||||
"context"
|
||||
csipb "github.com/container-storage-interface/spec/lib/go/csi"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCSICreateVolumeCapacityCapBeforeProvision(t *testing.T) {
|
||||
const capBytes = int64(17592186040320)
|
||||
p := &stubProvisioner{}
|
||||
s := NewControllerServerWithProvisioner(&stubLookup{}, p)
|
||||
req := &csipb.CreateVolumeRequest{Name: "v", CapacityRange: &csipb.CapacityRange{RequiredBytes: capBytes}, VolumeCapabilities: []*csipb.VolumeCapability{testVolumeCapability()}}
|
||||
if _, err := s.CreateVolume(context.Background(), req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.calls = nil
|
||||
req.CapacityRange.RequiredBytes = capBytes + 4096
|
||||
_, err := s.CreateVolume(context.Background(), req)
|
||||
if status.Code(err) != codes.InvalidArgument || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
|
||||
t.Fatalf("want clear InvalidArgument, got %v", err)
|
||||
}
|
||||
if len(p.calls) != 0 {
|
||||
t.Fatal("oversized request reached provisioner")
|
||||
}
|
||||
}
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/geometry"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
@@ -227,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.
|
||||
@@ -487,6 +489,9 @@ func (c *Catalog) EnsureVolume(ctx context.Context, vol string, g Geometry) (Vol
|
||||
return VolumeInfo{}, err
|
||||
}
|
||||
if !ok {
|
||||
if g.BlockSize != 0 && g.NumBlocks > geometry.MaxVolumeBytes/uint64(g.BlockSize) {
|
||||
return VolumeInfo{}, catErr(CodeGeometryMismatch, false, nil, "volume size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes)
|
||||
}
|
||||
v = VolumeInfo{Format: volumeFormat, VolumeID: vol, Geometry: g, Origin: OriginCreate, CreatedNs: c.now().UnixNano()}
|
||||
e, err := volumeEntry(v, "")
|
||||
if err != nil {
|
||||
@@ -669,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)
|
||||
@@ -680,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
|
||||
}
|
||||
|
||||
@@ -866,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
|
||||
@@ -1227,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 {
|
||||
@@ -1281,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
|
||||
@@ -1352,6 +1368,9 @@ func (c *Catalog) claimForkParent(ctx context.Context, req ForkRequest) (Snapsho
|
||||
if ref.info.State == SnapDeleting {
|
||||
return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot)
|
||||
}
|
||||
if ref.info.geo.BlockSize != 0 && ref.info.geo.NumBlocks > geometry.MaxVolumeBytes/uint64(ref.info.geo.BlockSize) {
|
||||
return SnapshotInfo{}, catErr(CodeGeometryMismatch, false, nil, "fork size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes)
|
||||
}
|
||||
claims := decodeClaims(ref.entry)
|
||||
for _, cl := range claims {
|
||||
if cl == token {
|
||||
|
||||
@@ -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 {
|
||||
@@ -403,7 +415,7 @@ func TestFork_ThenFreshHostReadsSnapshotImage(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := filepath.Join(dir, vol)
|
||||
s, err := storage.CreateWALStore(p, blocks, 4096)
|
||||
s, err := storage.CreateWALStoreWithOptions(p, blocks, 4096, storage.WALStoreOptions{ChunkBlocks: chunkBlocks})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -411,8 +423,7 @@ func TestFork_ThenFreshHostReadsSnapshotImage(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, _ := NewChunkRemote(f, b, path.Join(catBase, vol))
|
||||
cfg := storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: epoch, Holder: vol, FreshFromHead: fresh,
|
||||
Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap")}
|
||||
cfg := storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: epoch, Holder: vol, FreshFromHead: fresh}
|
||||
if fresh {
|
||||
// This low-level fixture bypasses the provider: perform the same
|
||||
// takeover and durable frontier seed before attaching its layer.
|
||||
@@ -577,7 +588,7 @@ func TestDetach_ProductionSerializedHead(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
p := filepath.Join(t.TempDir(), "v1")
|
||||
s, err := storage.CreateWALStore(p, 64, 4096)
|
||||
s, err := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -586,8 +597,7 @@ func TestDetach_ProductionSerializedHead(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, _ := NewChunkRemote(f, b, catBase+"/v1")
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 3, Holder: "host-a",
|
||||
Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap")})
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 3, Holder: "host-a"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -650,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")
|
||||
}
|
||||
|
||||
@@ -219,7 +219,7 @@ func TestIntegration_ChunkLayerCaptureThenFreshHost(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
attach := func(name string, fresh bool) (*storage.WALStore, storage.ChunkLayer) {
|
||||
p := filepath.Join(dir, name)
|
||||
s, err := storage.CreateWALStore(p, blocks, 4096)
|
||||
s, err := storage.CreateWALStoreWithOptions(p, blocks, 4096, storage.WALStoreOptions{ChunkBlocks: chunkBlocks})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -228,7 +228,6 @@ func TestIntegration_ChunkLayerCaptureThenFreshHost(t *testing.T) {
|
||||
}
|
||||
l, err := storage.AttachChunkLayer(s, c.remote(t, root), storage.ChunkLayerConfig{
|
||||
ChunkBlocks: chunkBlocks, Epoch: 1, Holder: name, FreshFromHead: fresh,
|
||||
Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -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()
|
||||
@@ -252,7 +265,7 @@ func TestChunkRemote_ChunkLayerCaptureThenFreshHost(t *testing.T) {
|
||||
|
||||
attach := func(name string, fresh bool) (*storage.WALStore, storage.ChunkLayer) {
|
||||
p := filepath.Join(dir, name)
|
||||
s, err := storage.CreateWALStore(p, blocks, 4096)
|
||||
s, err := storage.CreateWALStoreWithOptions(p, blocks, 4096, storage.WALStoreOptions{ChunkBlocks: chunkBlocks})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -262,7 +275,6 @@ func TestChunkRemote_ChunkLayerCaptureThenFreshHost(t *testing.T) {
|
||||
r := newTestRemote(t, f, b)
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{
|
||||
ChunkBlocks: chunkBlocks, Epoch: 1, Holder: name, FreshFromHead: fresh,
|
||||
Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -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,61 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
)
|
||||
|
||||
// A legacy catalog may already contain oversized geometry. A new fork is
|
||||
// still a new volume: it must not bypass the creation cap by inheritance.
|
||||
func TestForkRejectsLegacyOversizedGeometry(t *testing.T) {
|
||||
for _, blocks := range []uint64{4294967295, 4294967296} {
|
||||
f, b, c, _, _ := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
v, ok, err := c.ReadVolume(ctx, "v1")
|
||||
if err != nil || !ok {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v.NumBlocks = blocks
|
||||
e, err := volumeEntry(v, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)})
|
||||
_, err = c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "fork", IsDirectory: true}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "fork", RequestID: "f"})
|
||||
if blocks == 4294967295 {
|
||||
if err != nil {
|
||||
t.Fatalf("at-cap fork: %v", err)
|
||||
}
|
||||
got, ok, e := c.ReadVolume(ctx, "fork")
|
||||
if e != nil || !ok || got.NumBlocks != blocks {
|
||||
t.Fatalf("at-cap geometry not inherited: %+v %v", got, e)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
|
||||
t.Fatalf("oversized fork must refuse: %v", err)
|
||||
}
|
||||
if _, ok, e := c.ReadVolume(ctx, "fork"); e != nil || ok {
|
||||
t.Fatalf("oversized fork persisted target: %v %v", ok, e)
|
||||
}
|
||||
// Observe claim cleanup through the public retention operation: an
|
||||
// uncompleted fork claim would make this snapshot undeletable.
|
||||
if _, deleteErr := c.DeleteSnapshot(ctx, "v1", "s1"); deleteErr != nil {
|
||||
t.Fatalf("capacity refusal blocked snapshot deletion: %v", deleteErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -69,7 +69,7 @@ func TestGC_StalledCutRemainsReadableAfterTwoMarks(t *testing.T) {
|
||||
}
|
||||
held := &heldGCRemote{remote, make(chan struct{}), make(chan struct{})}
|
||||
p := filepath.Join(t.TempDir(), "volume")
|
||||
s, e := storage.CreateWALStore(p, 64, 4096)
|
||||
s, e := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
@@ -77,8 +77,7 @@ func TestGC_StalledCutRemainsReadableAfterTwoMarks(t *testing.T) {
|
||||
if _, e = s.Recover(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
layer, e := storage.AttachChunkLayer(s, held, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", Bitmap: storage.NewFileChunkBitmapStore(p + ".bitmap"),
|
||||
FreshFromHead: true}) // a new, empty store: its dirty set is known (empty)
|
||||
layer, e := storage.AttachChunkLayer(s, held, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true}) // a new, empty store: its dirty set is known (empty)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -90,19 +99,31 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch
|
||||
data []byte
|
||||
}
|
||||
var uploads []upload
|
||||
for group, chunks := range groups {
|
||||
old := map[uint64]storage.ChunkRef{}
|
||||
for idx, ref := range base.Chunks {
|
||||
if idx/per == group {
|
||||
ref.Key = qualifyManifestKey(owner, ref.Key)
|
||||
old[idx] = ref
|
||||
}
|
||||
// Partition the base once, rather than scanning every base chunk for each
|
||||
// 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{}
|
||||
}
|
||||
ref.Key = qualifyManifestKey(owner, ref.Key)
|
||||
baseGroups[group][idx] = ref
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -114,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 {
|
||||
@@ -156,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
|
||||
}
|
||||
@@ -67,7 +67,7 @@ func TestManifestPerf_64DirtyChunks(t *testing.T) {
|
||||
if _, err = s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 1024, Epoch: 1, Holder: "h1", FreshFromHead: true, UploadConcurrency: parallel, Bitmap: storage.NewFileChunkBitmapStore(filepath.Join(dir, "bitmap"))})
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 1024, Epoch: 1, Holder: "h1", FreshFromHead: true, UploadConcurrency: parallel})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// Metadata-only scaling probe: one chunk per 1-GiB segment, all unchanged.
|
||||
// No volume data allocation or remote I/O is included. Report ns/op and allocs;
|
||||
// the old per-group scan visits groups*groups base references.
|
||||
func BenchmarkPrepareManifestUnchangedGroups(b *testing.B) {
|
||||
for _, n := range []int{256, 1024, 4096} {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
r, err := NewChunkRemote(newFakeFiler(), newFakeBlobs(), "/chunks/v1")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
base := storage.ChunkHead{Chunks: map[uint64]storage.ChunkRef{}, Segments: map[uint64]storage.ChunkSegment{}, ChunkBytes: 1 << 30, ManifestChunkCount: n}
|
||||
for i := 0; i < n; i++ {
|
||||
base.Chunks[uint64(i)] = storage.ChunkRef{Key: fmt.Sprintf("@v1/chunk/%d", i)}
|
||||
base.Segments[uint64(i)] = storage.ChunkSegment{Key: fmt.Sprintf("@v1/seg/%d", i), Owner: "v1", Count: 1}
|
||||
}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
next, ids, err := r.PrepareManifest(context.Background(), base, base, 1<<30)
|
||||
if err != nil || len(ids) != 0 || len(next.Segments) != n {
|
||||
b.Fatalf("unchanged segment reuse: %v, intents=%v", err, ids)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ func TestManifest_CapturePublishesSegmentRoot(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := filepath.Join(t.TempDir(), "volume")
|
||||
s, err := storage.CreateWALStore(p, 64, 4096)
|
||||
s, err := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -31,7 +31,7 @@ func TestManifest_CapturePublishesSegmentRoot(t *testing.T) {
|
||||
if _, err = s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true, Bitmap: storage.NewFileChunkBitmapStore(p + ".bitmap")})
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -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)
|
||||
@@ -281,7 +281,7 @@ func TestManifest_NoopFlatUpgradeUsesOneNormalGeneration(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := filepath.Join(t.TempDir(), "store")
|
||||
s, err := storage.CreateWALStore(p, 64, 4096)
|
||||
s, err := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -289,7 +289,7 @@ func TestManifest_NoopFlatUpgradeUsesOneNormalGeneration(t *testing.T) {
|
||||
if _, err = s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true, Bitmap: storage.NewFileChunkBitmapStore(p + ".bitmap")})
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -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,28 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEnsureVolumeRejectsBeyondUint32LBACap(t *testing.T) {
|
||||
f, b, _, _, _ := gcFixture(t)
|
||||
c, err := NewCatalog(manifestFilerBlobs{f, b}, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
if _, err = c.EnsureVolume(ctx, "at-cap", Geometry{NumBlocks: 4294967295, BlockSize: 4096, ChunkBlocks: 1024}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, blocks := range []uint64{4294967296, ^uint64(0)} {
|
||||
_, err = c.EnsureVolume(ctx, "too-large", Geometry{NumBlocks: blocks, BlockSize: 4096, ChunkBlocks: 1024})
|
||||
if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") {
|
||||
t.Fatalf("blocks %d: want capacity refusal, got %v", blocks, err)
|
||||
}
|
||||
if _, ok, e := c.ReadVolume(ctx, "too-large"); e != nil || ok {
|
||||
t.Fatalf("refusal changed catalog: exists=%v err=%v", ok, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,31 @@
|
||||
package durable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
)
|
||||
|
||||
// SetTestAfterChunkResolve installs the test-only hook CutVolume runs right
|
||||
// after it resolves the volume's handle and layer.
|
||||
func SetTestAfterChunkResolve(p *DurableProvider, f func()) { p.testAfterChunkResolve = f }
|
||||
|
||||
// SetTestDetachStopIO replaces DetachVolume's StopIO call (test-only).
|
||||
func SetTestDetachStopIO(p *DurableProvider, f func(ctx context.Context) error) {
|
||||
p.testDetachStopIO = f
|
||||
}
|
||||
|
||||
// SetTestDetachTrace observes DetachVolume's stages and deadlines (test-only).
|
||||
func SetTestDetachTrace(p *DurableProvider, f func(stage string, deadline time.Time)) {
|
||||
p.testDetachTrace = f
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/geometry"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage/parallelwal"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage/smartwal"
|
||||
@@ -81,6 +82,14 @@ var ErrImplKindMismatch = errors.New("durable: impl kind mismatch between select
|
||||
// volumeID has not been Open'd.
|
||||
var ErrVolumeNotOpen = errors.New("durable: volume not opened")
|
||||
|
||||
// ErrDetachAborted: the detach did not happen (its final cut provably did not
|
||||
// publish), so the volume resumed serving on this host (MIGRATION E4).
|
||||
var ErrDetachAborted = errors.New("durable: detach aborted; the volume keeps serving on this host")
|
||||
|
||||
// ErrDetachOutcomeUnknown: whether the detach landed cannot be decided yet;
|
||||
// I/O stays stopped (never resumed on a possibly detached HEAD).
|
||||
var ErrDetachOutcomeUnknown = errors.New("durable: detach outcome unknown; I/O stays stopped")
|
||||
|
||||
// ProviderConfig configures a DurableProvider.
|
||||
type ProviderConfig struct {
|
||||
// Impl selects which LogicalStorage implementation to open or
|
||||
@@ -153,14 +162,26 @@ 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.
|
||||
ChunkCaptureInterval 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.
|
||||
// DetachFreezeTimeout bounds how long a failing DetachVolume keeps guest
|
||||
// I/O stopped before it resumes or settles: the drain and final cut get
|
||||
// three quarters of it, the settlement of a failed cut the rest (the
|
||||
// caller's context can only shorten the cut part). Zero: 20 s, below the
|
||||
// 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 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
|
||||
@@ -179,6 +200,18 @@ type DurableProvider struct {
|
||||
// testAfterChunkResolve, test-only, runs in CutVolume right after the
|
||||
// volume's handle and layer are resolved.
|
||||
testAfterChunkResolve func()
|
||||
// testDetachStopIO, test-only, replaces DetachVolume's StopIO call (so a
|
||||
// test can force the failed-drain branch); testDetachTrace, test-only,
|
||||
// observes the detach's stages and their deadlines ("cut", "settle").
|
||||
testDetachStopIO func(ctx context.Context) error
|
||||
testDetachTrace func(stage string, deadline time.Time)
|
||||
|
||||
// testBeforeChunkFreshRetire holds the real post-presence/pre-marker boundary.
|
||||
testBeforeChunkFreshRetire func() error
|
||||
|
||||
// testWALStoreFactory selects a dark store only in provider caller controls.
|
||||
// No production option, flag or environment variable installs it.
|
||||
testWALStoreFactory func(path string, create bool) (*storage.WALStore, error)
|
||||
|
||||
// walstore-chunk: closeCtx ends with Close and cancels in-flight
|
||||
// remote attachment; inflight counts RecoverVolume calls admitted
|
||||
@@ -209,6 +242,8 @@ type volHandle struct {
|
||||
recoverGen uint64
|
||||
waitGen uint64
|
||||
chunk storage.ChunkLayer // after RecoverVolume
|
||||
// Private until the owner commit succeeds; retained for attach retry.
|
||||
chunkPending storage.ChunkLayer
|
||||
// chunkDetach is set (under attachMu) when DetachVolume starts and
|
||||
// never cleared in this process: frontend I/O stays stopped, through
|
||||
// any later RecoverVolume, until a new lifetime attaches the volume.
|
||||
@@ -221,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
|
||||
@@ -587,6 +623,13 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) {
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
// Existing storage ignores create geometry; admission precedes all fresh sidecars.
|
||||
if p.cfg.NumBlocks == 0 {
|
||||
return nil, fmt.Errorf("durable: NumBlocks=0; cannot create storage for %s (use open-existing mode)", volumeID)
|
||||
}
|
||||
if err := geometry.ValidateBlockGeometry(uint64(p.cfg.NumBlocks), uint64(p.cfg.BlockSize)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p.cfg.Impl == ImplWALStoreChunk {
|
||||
// Durable before the volume file exists: a crash anywhere between
|
||||
// here and the first successful attach leaves a fresh volume.
|
||||
@@ -627,6 +670,8 @@ func (p *DurableProvider) verifyImplOnDisk(path string) (ImplName, error) {
|
||||
// the format's real header selector instead of rejecting on byte 0.
|
||||
if err := parallelwal.ProbeStore(path); err == nil {
|
||||
diskImpl, ok = ImplParallelWALStore, true
|
||||
} else if err := storage.ProbeWALStoreV3(path); err == nil {
|
||||
diskImpl, ok = ImplWALStore, true
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
@@ -668,13 +713,23 @@ func (p *DurableProvider) openExisting(volumeID, path string, impl ImplName) (*v
|
||||
var s storage.LogicalStorage
|
||||
switch impl {
|
||||
case ImplWALStore, ImplWALStoreChunk:
|
||||
ws, err := storage.OpenWALStore(path)
|
||||
var ws *storage.WALStore
|
||||
var err error
|
||||
if p.testWALStoreFactory != nil {
|
||||
ws, err = p.testWALStoreFactory(path, false)
|
||||
} else {
|
||||
ws, err = storage.OpenWALStore(path)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("durable: OpenWALStore %s: %w", path, err)
|
||||
}
|
||||
// G6 §1.A α: plumb operator-tunable retention into walstore.
|
||||
// Zero (pre-G6 default) preserves strict checkpoint-driven
|
||||
// recycle.
|
||||
// Defer before Recover can publish a completed BASE away.
|
||||
if impl == ImplWALStoreChunk && p.cfg.ChunkRemoteFor != nil {
|
||||
ws.DeferBaseRetirementV3()
|
||||
}
|
||||
if p.cfg.WALRetentionLSNs > 0 {
|
||||
ws.SetRecoveryRetentionLSNs(p.cfg.WALRetentionLSNs)
|
||||
}
|
||||
@@ -714,11 +769,21 @@ func (p *DurableProvider) createFresh(volumeID, path string, impl ImplName) (*vo
|
||||
var s storage.LogicalStorage
|
||||
switch impl {
|
||||
case ImplWALStore, ImplWALStoreChunk:
|
||||
ws, err := storage.CreateWALStore(path, p.cfg.NumBlocks, p.cfg.BlockSize)
|
||||
var ws *storage.WALStore
|
||||
var err error
|
||||
if p.testWALStoreFactory != nil {
|
||||
ws, err = p.testWALStoreFactory(path, true)
|
||||
} else {
|
||||
ws, err = storage.CreateWALStoreWithOptions(path, p.cfg.NumBlocks, p.cfg.BlockSize, storage.WALStoreOptions{ChunkBlocks: p.cfg.ChunkBlocks})
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("durable: CreateWALStore %s: %w", path, err)
|
||||
}
|
||||
// G6 §1.A α (see openExisting comment for semantics).
|
||||
// Defer before Recover can publish a completed BASE away.
|
||||
if impl == ImplWALStoreChunk && p.cfg.ChunkRemoteFor != nil {
|
||||
ws.DeferBaseRetirementV3()
|
||||
}
|
||||
if p.cfg.WALRetentionLSNs > 0 {
|
||||
ws.SetRecoveryRetentionLSNs(p.cfg.WALRetentionLSNs)
|
||||
}
|
||||
@@ -816,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 {
|
||||
@@ -889,6 +954,11 @@ func chunkSidecars(path string) ([]string, error) {
|
||||
}
|
||||
var out []string
|
||||
for _, e := range entries {
|
||||
// The owned v3 LSN map belongs to plain walstore as well. Remote
|
||||
// chunk identity still has its own presence/fresh/HEAD sidecars.
|
||||
if e.Name() == base+".chunkmap" {
|
||||
continue
|
||||
}
|
||||
if !e.IsDir() && strings.HasPrefix(e.Name(), base+".chunk") {
|
||||
out = append(out, e.Name())
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
@@ -75,6 +76,41 @@ func TestDurableProvider_AutoCreatesWALStore(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurableProvider_AutoOpensV3FallbackSlot(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
p := autoProvider(t, root, durable.ImplWALStore)
|
||||
s, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(3, bytes.Repeat([]byte{0x73}, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(root, "v1.bin")
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = f.WriteAt([]byte{0xff}, 0)
|
||||
ce := f.Close()
|
||||
if err != nil || ce != nil {
|
||||
t.Fatal(err, ce)
|
||||
}
|
||||
auto := autoProvider(t, root, durable.ImplAuto)
|
||||
if _, err := auto.EnsureStorage("v1"); err != nil {
|
||||
t.Fatalf("valid v3 fallback must pass the auto probe: %v", err)
|
||||
}
|
||||
if _, err := auto.RecoverVolume(context.Background(), "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurableProvider_AutoOpensExistingVolumeByOnDiskFormat(t *testing.T) {
|
||||
for _, impl := range []durable.ImplName{durable.ImplSmartWAL, durable.ImplWALStore, durable.ImplParallelWALStore} {
|
||||
t.Run(string(impl), func(t *testing.T) {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -84,6 +85,25 @@ func chunkAuthority(proj frontend.Projection, volumeID string) bool {
|
||||
return proj.VolumeID == volumeID && proj.Healthy && proj.Epoch > 0 && proj.ReplicaID != ""
|
||||
}
|
||||
|
||||
// chunkAuthorityGap names the projection fields that fail chunkAuthority,
|
||||
// for the logs ("" when none fails).
|
||||
func chunkAuthorityGap(proj frontend.Projection, volumeID string) string {
|
||||
var gap []string
|
||||
if proj.VolumeID != volumeID {
|
||||
gap = append(gap, fmt.Sprintf("volume=%q", proj.VolumeID))
|
||||
}
|
||||
if !proj.Healthy {
|
||||
gap = append(gap, "healthy=false")
|
||||
}
|
||||
if proj.Epoch == 0 {
|
||||
gap = append(gap, "epoch=0")
|
||||
}
|
||||
if proj.ReplicaID == "" {
|
||||
gap = append(gap, `replica=""`)
|
||||
}
|
||||
return strings.Join(gap, " ")
|
||||
}
|
||||
|
||||
// recoverChunk runs after a successful local Recover, generation gen. It
|
||||
// attaches the layer when the projection already carries master authority
|
||||
// and reports true. Otherwise it starts an authority wait bound to gen
|
||||
@@ -126,6 +146,13 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
|
||||
if limit <= 0 {
|
||||
limit = 30 * time.Second
|
||||
}
|
||||
start := time.Now()
|
||||
log.Printf("durable: chunk layer for volume=%s waits for master authority (up to %s): projection lacks %s",
|
||||
volumeID, limit, chunkAuthorityGap(p.view.Projection(), volumeID))
|
||||
ended := "superseded by a later recovery"
|
||||
defer func() {
|
||||
log.Printf("durable: chunk authority wait for volume=%s ended after %s: %s", volumeID, time.Since(start), ended)
|
||||
}()
|
||||
waitCtx, endWait := context.WithTimeout(p.closeCtx, limit)
|
||||
defer endWait()
|
||||
defer func() {
|
||||
@@ -136,6 +163,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
|
||||
h.attachMu.Lock()
|
||||
defer h.attachMu.Unlock()
|
||||
if p.current(h, gen) && h.chunk == nil {
|
||||
ended = fmt.Sprintf("assignment unavailable, not serving (projection lacks %s)", chunkAuthorityGap(p.view.Projection(), volumeID))
|
||||
h.backend.SetOperational(false, "chunk assignment unavailable: "+waitCtx.Err().Error())
|
||||
}
|
||||
}()
|
||||
@@ -148,18 +176,28 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
|
||||
}()
|
||||
t := time.NewTicker(chunkAuthorityPoll)
|
||||
defer t.Stop()
|
||||
attempts := 0
|
||||
for {
|
||||
select {
|
||||
case <-waitCtx.Done():
|
||||
ended = "provider closed"
|
||||
if errors.Is(waitCtx.Err(), context.DeadlineExceeded) {
|
||||
ended = "deadline"
|
||||
}
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
if !p.current(h, gen) {
|
||||
return // a later recovery (successful or failed) owns the volume
|
||||
}
|
||||
if !chunkAuthority(p.view.Projection(), volumeID) {
|
||||
proj := p.view.Projection()
|
||||
if !chunkAuthority(proj, volumeID) {
|
||||
continue
|
||||
}
|
||||
if attempts++; attempts == 1 {
|
||||
log.Printf("durable: chunk layer for volume=%s: master authority after %s (replica=%q epoch=%d endpoint=%d); first attach attempt",
|
||||
volumeID, time.Since(start), proj.ReplicaID, proj.Epoch, proj.EndpointVersion)
|
||||
}
|
||||
h.attachMu.Lock()
|
||||
if !p.current(h, gen) { // re-checked under the per-volume serialization
|
||||
h.attachMu.Unlock()
|
||||
@@ -176,9 +214,14 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
|
||||
}
|
||||
h.attachMu.Unlock()
|
||||
switch {
|
||||
case err == nil, errors.Is(err, errProviderClosed):
|
||||
case err == nil:
|
||||
ended = fmt.Sprintf("attached after %d attempt(s)", attempts)
|
||||
return
|
||||
case errors.Is(err, errProviderClosed):
|
||||
ended = "provider closed"
|
||||
return
|
||||
case errors.Is(err, storage.ErrChunkLayerFenced):
|
||||
ended = "fenced, not serving"
|
||||
log.Printf("durable: chunk layer for volume=%s: %v (not serving)", volumeID, err)
|
||||
if errors.Is(err, ErrChunkStaleLocalRoot) {
|
||||
h.attachMu.Lock()
|
||||
@@ -189,11 +232,17 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
|
||||
}
|
||||
return
|
||||
case errors.Is(err, errChunkNoAuthority):
|
||||
log.Printf("durable: chunk layer attach for volume=%s: authority lost before attempt %d (projection lacks %s); waiting",
|
||||
volumeID, attempts, chunkAuthorityGap(p.view.Projection(), volumeID))
|
||||
continue
|
||||
}
|
||||
log.Printf("durable: chunk layer attach for volume=%s: %v (retrying)", volumeID, err)
|
||||
select {
|
||||
case <-waitCtx.Done():
|
||||
ended = "provider closed during the retry backoff"
|
||||
if errors.Is(waitCtx.Err(), context.DeadlineExceeded) {
|
||||
ended = "deadline during the retry backoff"
|
||||
}
|
||||
return
|
||||
case <-time.After(chunkAttachRetry):
|
||||
}
|
||||
@@ -207,6 +256,9 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
|
||||
func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *volHandle) error {
|
||||
p.mu.Lock()
|
||||
layer := h.chunk
|
||||
if layer == nil {
|
||||
layer = h.chunkPending
|
||||
}
|
||||
p.mu.Unlock()
|
||||
if layer == nil {
|
||||
var err error
|
||||
@@ -215,33 +267,66 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v
|
||||
}
|
||||
p.mu.Lock()
|
||||
if p.closed {
|
||||
// Not published: the store still owns the layer and closes it
|
||||
// in WALStore.Close, which Close runs after this call settles.
|
||||
// The store owns this unpublished layer and closes it after
|
||||
// the admitted attach settles.
|
||||
p.mu.Unlock()
|
||||
return errProviderClosed
|
||||
}
|
||||
h.chunkPending = layer
|
||||
p.mu.Unlock()
|
||||
}
|
||||
// The owner commit is serialized with a later BASE begin. The callback
|
||||
// does marker I/O only: no store/layer reentry while installMu is held.
|
||||
commit := func() error {
|
||||
if h.fresh {
|
||||
return removeChunkFreshMarker(h.path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if h.fresh {
|
||||
if hook := p.testBeforeChunkFreshRetire; hook != nil {
|
||||
if err := hook(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if ws, ok := h.storage.(*storage.WALStore); ok {
|
||||
if err := ws.CommitChunkAttachV3(commit); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err := commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.closed {
|
||||
return errProviderClosed
|
||||
}
|
||||
h.fresh = false
|
||||
if h.chunk == nil {
|
||||
// No explicit operation can resolve the layer, and no scheduler
|
||||
// can publish, until marker retirement is durably committed.
|
||||
h.chunk = layer
|
||||
h.chunkPending = nil
|
||||
h.backend.mu.Lock()
|
||||
h.backend.chunkFenced = layer.Fenced
|
||||
h.backend.mu.Unlock()
|
||||
if p.cfg.ChunkCaptureInterval > 0 {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
h.chunkStop, h.chunkDone = cancel, make(chan struct{})
|
||||
go p.chunkLoop(ctx, volumeID, layer, h.chunkDone)
|
||||
}
|
||||
p.mu.Unlock()
|
||||
}
|
||||
if h.fresh {
|
||||
// The attach persisted the absence of every HEAD chunk; only now
|
||||
// may a restart treat the local volume as authoritative.
|
||||
if err := removeChunkFreshMarker(h.path); err != nil {
|
||||
return err
|
||||
}
|
||||
h.fresh = false
|
||||
p.startChunkLoop(volumeID, h, layer)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// startChunkLoop starts the periodic cuts of an attached layer, if configured
|
||||
// and not already running. The caller holds h.attachMu and p.mu.
|
||||
func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer storage.ChunkLayer) {
|
||||
if p.cfg.ChunkCaptureInterval <= 0 || h.chunkStop != nil {
|
||||
return
|
||||
}
|
||||
loopCtx, cancel := context.WithCancel(context.Background())
|
||||
h.chunkStop, h.chunkDone = cancel, make(chan struct{})
|
||||
go p.chunkLoop(loopCtx, volumeID, layer, h.chunkDone)
|
||||
}
|
||||
|
||||
func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) {
|
||||
ws, ok := h.storage.(*storage.WALStore)
|
||||
if !ok {
|
||||
@@ -279,14 +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,
|
||||
Bitmap: storage.NewFileChunkBitmapStore(h.path + ".chunkbitmap"),
|
||||
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 {
|
||||
@@ -320,6 +407,17 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
|
||||
// Attach preparation is gated. Seed the exact observed HEAD before
|
||||
// its takeover CAS; only then finalize lazy attachment and expose I/O.
|
||||
cfg.PrepareRestore = func(head storage.ChunkHead) error {
|
||||
log.Printf("durable: HEAD claim for volume=%s observed HEAD gen=%d epoch=%d holder=%q state=%v remote_lsn=%d; preparing",
|
||||
volumeID, head.Gen, head.Epoch, head.Holder, head.State, head.RemoteLSN)
|
||||
if baseLSN, complete := ws.InstalledBaseLSN(); complete {
|
||||
// The fresh marker can outlive a full local BASE. It is not
|
||||
// permission to seed backwards or to fill from an older HEAD.
|
||||
if head.RemoteLSN > baseLSN {
|
||||
return fmt.Errorf("durable: completed BASE frontier %d is behind HEAD %d", baseLSN, head.RemoteLSN)
|
||||
}
|
||||
cfg.FreshFromHead = false
|
||||
return nil
|
||||
}
|
||||
// No HEAD is a new lineage; preserve any pre-assignment local
|
||||
// writes instead of replacing their frontier with zero.
|
||||
if head.Gen == 0 {
|
||||
@@ -339,10 +437,18 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
|
||||
// restore here, so HEAD is never claimed for a mis-ordered ship.
|
||||
return h.backend.seedAndRebase(func() error { return ws.SeedChunkFrontier(head.RemoteLSN) })
|
||||
}
|
||||
claimStart := time.Now()
|
||||
log.Printf("durable: HEAD claim for volume=%s starting: target epoch=%d holder=%q", volumeID, cfg.Epoch, cfg.Holder)
|
||||
head, err := storage.ClaimChunkHead(ctx, remote, cfg)
|
||||
if err != nil {
|
||||
log.Printf("durable: HEAD claim for volume=%s failed after %s: %v", volumeID, time.Since(claimStart), err)
|
||||
return nil, fmt.Errorf("durable: restore HEAD claim: %w", err)
|
||||
}
|
||||
claimed := "claimed"
|
||||
if head.Gen == 0 {
|
||||
claimed = "no HEAD to claim (new lineage)"
|
||||
}
|
||||
log.Printf("durable: HEAD claim for volume=%s done in %s: gen=%d epoch=%d holder=%q, %s", volumeID, time.Since(claimStart), head.Gen, head.Epoch, head.Holder, claimed)
|
||||
cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}
|
||||
}
|
||||
|
||||
@@ -706,12 +812,19 @@ func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN
|
||||
}
|
||||
|
||||
// DetachVolume is a clean stop's final cut (B9 W2 §3.6): it stops the
|
||||
// volume's frontend I/O and waits (bounded by ctx) for the I/O already
|
||||
// admitted to finish, stops the periodic cuts, then publishes one cut with
|
||||
// HEAD state detached. It also returns the last LSN written. From its
|
||||
// start, the volume stays stopped for this process, through any later
|
||||
// RecoverVolume, even when the detach fails; a retry settles it and a
|
||||
// repeated call returns the first result.
|
||||
// volume's frontend I/O and waits for the I/O already admitted to finish,
|
||||
// stops the periodic cuts, then publishes one cut with HEAD state detached.
|
||||
// It also returns the last LSN written. The freeze (drain + final cut) is
|
||||
// bounded by DetachFreezeTimeout and ctx. After a successful detach the
|
||||
// volume stays stopped for this process, through any later RecoverVolume,
|
||||
// and a repeated call returns the first result. A failed detach never leaves
|
||||
// the guest frozen by a detach that did not happen (MIGRATION E4):
|
||||
// - nothing published (the drain or the cut failed before its CAS, or the
|
||||
// CAS was refused, or an unresolved detach CAS was cancelled): serving
|
||||
// resumes and ErrDetachAborted is returned;
|
||||
// - the detach CAS applied (its reply was lost): the detached result;
|
||||
// - HEAD belongs to another holder: stays stopped (fenced);
|
||||
// - undecidable (HEAD unreadable): stays stopped, ErrDetachOutcomeUnknown.
|
||||
func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) {
|
||||
p.mu.Lock()
|
||||
h, ok := p.volumes[volumeID]
|
||||
@@ -725,16 +838,83 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st
|
||||
if err != nil {
|
||||
return storage.ChunkCutResult{}, 0, err
|
||||
}
|
||||
freeze := p.cfg.DetachFreezeTimeout
|
||||
if freeze <= 0 {
|
||||
freeze = defaultDetachFreezeTimeout
|
||||
}
|
||||
// One freeze budget covers the drain, the final cut AND the settlement:
|
||||
// the cut gets three quarters, the settlement what is left. The bound is
|
||||
// cooperative (contexts): a syscall that never returns is not bounded here.
|
||||
start := time.Now()
|
||||
cutCtx, cancel := context.WithDeadline(ctx, start.Add(freeze*3/4))
|
||||
defer cancel()
|
||||
defer func() {
|
||||
if d := time.Since(start); d > detachFreezeTarget {
|
||||
log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze)
|
||||
}
|
||||
}()
|
||||
if trace := p.testDetachTrace; trace != nil {
|
||||
dl, _ := cutCtx.Deadline()
|
||||
trace("cut", dl)
|
||||
}
|
||||
h.chunkDetach = true
|
||||
if err := h.backend.StopIO(ctx, "chunk detach: I/O stopped until a new attach"); err != nil {
|
||||
return storage.ChunkCutResult{}, 0, err
|
||||
if stop := p.testDetachStopIO; stop != nil {
|
||||
err = stop(cutCtx)
|
||||
} else {
|
||||
err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach")
|
||||
}
|
||||
p.stopChunkLoop(h)
|
||||
r, err := layer.Detach(ctx)
|
||||
if err != nil {
|
||||
return storage.ChunkCutResult{}, 0, err
|
||||
if err == nil {
|
||||
p.stopChunkLoop(h)
|
||||
var r storage.ChunkCutResult
|
||||
if r, err = layer.Detach(cutCtx); err == nil {
|
||||
return r, h.storage.NextLSN() - 1, nil
|
||||
}
|
||||
}
|
||||
return r, h.storage.NextLSN() - 1, nil
|
||||
// Every failure, a failed drain included, is settled before anything
|
||||
// resumes: an earlier detach that applied, an unresolved detach CAS or a
|
||||
// fenced layer must never resume serving. The settlement keeps the rest
|
||||
// of the freeze budget even when the caller's context is gone.
|
||||
sctx, scancel := context.WithDeadline(context.WithoutCancel(ctx), start.Add(freeze))
|
||||
defer scancel()
|
||||
if trace := p.testDetachTrace; trace != nil {
|
||||
dl, _ := sctx.Deadline()
|
||||
trace("settle", dl)
|
||||
}
|
||||
how, dr, serr := layer.SettleDetach(sctx)
|
||||
switch {
|
||||
case serr != nil:
|
||||
return storage.ChunkCutResult{}, 0, fmt.Errorf("%w: %w (settle: %w)", ErrDetachOutcomeUnknown, err, serr)
|
||||
case how == storage.DetachApplied:
|
||||
return dr, h.storage.NextLSN() - 1, nil
|
||||
case how == storage.DetachFenced:
|
||||
return storage.ChunkCutResult{}, 0, fmt.Errorf("durable: detach of %s: HEAD belongs to a newer epoch or another holder; I/O stays stopped: %w: %w", volumeID, storage.ErrChunkLayerFenced, err)
|
||||
default:
|
||||
return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err)
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
defaultDetachFreezeTimeout = 20 * time.Second
|
||||
detachFreezeTarget = 5 * time.Second
|
||||
)
|
||||
|
||||
// resumeAfterDetach undoes a detach that provably did not happen: the
|
||||
// periodic cuts restart, the stop is lifted, and the volume serves again.
|
||||
// The caller holds h.attachMu.
|
||||
func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer storage.ChunkLayer, cause error) error {
|
||||
p.mu.Lock()
|
||||
closed := p.closed || h.chunk != layer
|
||||
if !closed {
|
||||
p.startChunkLoop(volumeID, h, layer)
|
||||
}
|
||||
p.mu.Unlock()
|
||||
if closed { // a concurrent Close or detach of the layer owns the volume now
|
||||
return fmt.Errorf("durable: detach of %s aborted while the provider closed: %w", volumeID, cause)
|
||||
}
|
||||
h.chunkDetach = false
|
||||
h.backend.SetOperational(true, "chunk detach aborted: serving resumed")
|
||||
log.Printf("durable: detach of volume=%s aborted, nothing published; serving resumed: %v", volumeID, cause)
|
||||
return fmt.Errorf("%w: %w", ErrDetachAborted, cause)
|
||||
}
|
||||
|
||||
// Preserve the optional manifest capability only when the inner remote has it;
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type lockedLog struct {
|
||||
mu sync.Mutex
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (l *lockedLog) Write(p []byte) (int, error) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.buf.Write(p)
|
||||
}
|
||||
|
||||
func (l *lockedLog) String() string {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.buf.String()
|
||||
}
|
||||
|
||||
// waitLog waits until the log holds want, then returns the log.
|
||||
func waitLog(t *testing.T, l *lockedLog, want string) string {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for !strings.Contains(l.String(), want) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("log never held %q:\n%s", want, l.String())
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
return l.String()
|
||||
}
|
||||
|
||||
// inOrder checks that every line holding a want[i] fragment set appears,
|
||||
// each after the previous one.
|
||||
func inOrder(t *testing.T, logs string, want ...[]string) {
|
||||
t.Helper()
|
||||
lines := strings.Split(logs, "\n")
|
||||
at := 0
|
||||
next:
|
||||
for _, frags := range want {
|
||||
for ; at < len(lines); at++ {
|
||||
ok := true
|
||||
for _, f := range frags {
|
||||
ok = ok && strings.Contains(lines[at], f)
|
||||
}
|
||||
if ok {
|
||||
at++
|
||||
continue next
|
||||
}
|
||||
}
|
||||
t.Fatalf("no line with %q after the previous expected line:\n%s", frags, logs)
|
||||
}
|
||||
}
|
||||
|
||||
// The deferred attach logs its wait (with the projection fields that
|
||||
// fail), the first attach attempt, the HEAD claim and how the wait ended.
|
||||
func TestChunkAuthorityWaitLogsTheWaitTheClaimAndTheEnd(t *testing.T) {
|
||||
logs := &lockedLog{}
|
||||
captureWriteLogs(t, logs)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})}
|
||||
p := chunkProviderForAssignment(t, v)
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v.active.Store(true)
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitLog(t, logs, "waits for master authority")
|
||||
close(v.assigned)
|
||||
got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after")
|
||||
inOrder(t, got,
|
||||
[]string{"volume=v1 waits for master authority (up to 30s): projection lacks healthy=false epoch=0"},
|
||||
[]string{"volume=v1: master authority after", `replica="r1" epoch=3 endpoint=1`, "first attach attempt"},
|
||||
[]string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`},
|
||||
[]string{`HEAD claim for volume=v1 observed HEAD gen=0 epoch=0 holder=""`, "; preparing"},
|
||||
[]string{"HEAD claim for volume=v1 done in ", `gen=0 epoch=0 holder="", no HEAD to claim (new lineage)`},
|
||||
[]string{"chunk authority wait for volume=v1 ended after", ": attached after 1 attempt(s)"},
|
||||
)
|
||||
if strings.Count(got, "first attach attempt") != 1 {
|
||||
t.Fatalf("first attach attempt logged more than once:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A wait that reaches its bound logs the assignment-unavailable transition
|
||||
// with the fields still missing; a wait ended by Close says so.
|
||||
func TestChunkAuthorityWaitLogsDeadlineAndClose(t *testing.T) {
|
||||
for _, mode := range []string{"limit", "close"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
logs := &lockedLog{}
|
||||
captureWriteLogs(t, logs)
|
||||
v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})}
|
||||
limit := 40 * time.Millisecond
|
||||
if mode == "close" {
|
||||
limit = time.Minute
|
||||
}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4,
|
||||
ChunkAssignmentTimeout: limit,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil },
|
||||
}, v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer p.Close()
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v.active.Store(true)
|
||||
if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "ended after"
|
||||
if mode == "close" {
|
||||
waitLog(t, logs, "waits for master authority")
|
||||
if err := p.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got := waitLog(t, logs, want)
|
||||
end := ": assignment unavailable, not serving (projection lacks healthy=false epoch=0)"
|
||||
if mode == "close" {
|
||||
end = ": provider closed"
|
||||
}
|
||||
inOrder(t, got,
|
||||
[]string{"volume=v1 waits for master authority (up to " + limit.String() + "): projection lacks healthy=false epoch=0"},
|
||||
[]string{"chunk authority wait for volume=v1 ended after", end},
|
||||
)
|
||||
if strings.Contains(got, "first attach attempt") || strings.Contains(got, "HEAD claim for") {
|
||||
t.Fatalf("attach logged without authority:\n%s", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// headFailRemote fails GetHead while fails > 0 (forever when < 0).
|
||||
type headFailRemote struct {
|
||||
*storage.MemChunkRemote
|
||||
fails atomic.Int32
|
||||
}
|
||||
|
||||
var errHeadRead = errors.New("injected HEAD read failure")
|
||||
|
||||
func (r *headFailRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
|
||||
if n := r.fails.Load(); n != 0 {
|
||||
if n > 0 {
|
||||
r.fails.Add(-1)
|
||||
}
|
||||
return storage.ChunkHead{}, errHeadRead
|
||||
}
|
||||
return r.MemChunkRemote.GetHead(ctx)
|
||||
}
|
||||
|
||||
// A claim whose first HEAD read fails logs its start and its failure with
|
||||
// the elapsed time; the retry then claims. Close during the retry backoff
|
||||
// ends the wait as closed, not superseded.
|
||||
func TestChunkAuthorityWaitLogsAFailedClaim(t *testing.T) {
|
||||
for _, mode := range []string{"retried", "closed in backoff"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
logs := &lockedLog{}
|
||||
captureWriteLogs(t, logs)
|
||||
remote := &headFailRemote{MemChunkRemote: storage.NewMemChunkRemote()}
|
||||
remote.fails.Store(1)
|
||||
if mode != "retried" {
|
||||
remote.fails.Store(-1)
|
||||
}
|
||||
v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
}, v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer p.Close()
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v.active.Store(true)
|
||||
if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitLog(t, logs, "waits for master authority")
|
||||
close(v.assigned)
|
||||
if mode == "retried" {
|
||||
got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after")
|
||||
inOrder(t, got,
|
||||
[]string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`},
|
||||
[]string{"HEAD claim for volume=v1 failed after ", errHeadRead.Error()},
|
||||
[]string{"chunk layer attach for volume=v1:", "(retrying)"},
|
||||
[]string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`},
|
||||
[]string{"HEAD claim for volume=v1 observed HEAD gen=0"},
|
||||
[]string{"HEAD claim for volume=v1 done in "},
|
||||
[]string{"chunk authority wait for volume=v1 ended after", ": attached after 2 attempt(s)"},
|
||||
)
|
||||
return
|
||||
}
|
||||
waitLog(t, logs, "(retrying)")
|
||||
if err := p.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after")
|
||||
inOrder(t, got,
|
||||
[]string{"HEAD claim for volume=v1 failed after ", errHeadRead.Error()},
|
||||
[]string{"chunk authority wait for volume=v1 ended after", ": provider closed during the retry backoff"},
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 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_SequentialBurstFlush(t *testing.T) {
|
||||
const total = 320 * 1024 * 1024
|
||||
const transfer = 128 * 1024
|
||||
const flushEvery = 48 * 1024 * 1024
|
||||
ctx := context.Background()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096,
|
||||
NumBlocks: total / 4096, ChunkBlocks: 1024,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := p.Close(); err != nil {
|
||||
t.Logf("close: %v", err)
|
||||
}
|
||||
})
|
||||
s, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
be, err := p.Open(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: be, BlockSize: 4096, VolumeSize: total})
|
||||
data := make([]byte, transfer)
|
||||
start := time.Now()
|
||||
for off := 0; off < total; off += transfer {
|
||||
fillBurstTransfer(data, off)
|
||||
r := h.Handle(ctx, nvme.IOCommand{Opcode: 0x01, NSID: 1, SLBA: uint64(off / 4096), NLB: transfer / 4096, Data: data})
|
||||
if r.AsError() != nil {
|
||||
_, syncErr := s.Sync()
|
||||
t.Fatalf("write bytes=%d elapsed=%v result=%+v exact Sync=%T %v", off, time.Since(start), r, syncErr, syncErr)
|
||||
}
|
||||
if (off+transfer)%flushEvery == 0 || off+transfer == total {
|
||||
r = h.Handle(ctx, nvme.IOCommand{Opcode: 0x00, NSID: 1})
|
||||
if r.AsError() != nil {
|
||||
_, syncErr := s.Sync()
|
||||
t.Fatalf("flush bytes=%d elapsed=%v result=%+v exact Sync=%T %v", off+transfer, time.Since(start), r, syncErr, syncErr)
|
||||
}
|
||||
t.Logf("flush bytes=%d elapsed=%v", off+transfer, time.Since(start))
|
||||
}
|
||||
}
|
||||
// The expected bytes come from the submitted pattern, not another reader.
|
||||
for off := 0; off < total; off += transfer {
|
||||
got := make([]byte, transfer)
|
||||
n, err := be.Read(ctx, int64(off), got)
|
||||
if err != nil {
|
||||
t.Fatalf("readback at%d: %v", off, err)
|
||||
}
|
||||
if n != transfer {
|
||||
t.Fatalf("short readback at%d: %d", off, n)
|
||||
}
|
||||
for i := 0; i < len(got); i += 8 {
|
||||
if word := binary.LittleEndian.Uint64(got[i : i+8]); word != uint64(off+i) {
|
||||
t.Fatalf("readback word at byte%d=%d want%d", off+i, word, off+i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func fillBurstTransfer(data []byte, off int) {
|
||||
for i := 0; i < len(data); i += 8 {
|
||||
binary.LittleEndian.PutUint64(data[i:i+8], uint64(off+i))
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreChunkV3_BurstPatternBindsFullLBA(t *testing.T) {
|
||||
const transfer = 128 * 1024
|
||||
zero, later := make([]byte, transfer), make([]byte, transfer)
|
||||
fillBurstTransfer(zero, 0)
|
||||
for _, off := range []int{32 * 1024 * 1024, 64 * 1024 * 1024, 256 * 1024 * 1024} {
|
||||
fillBurstTransfer(later, off)
|
||||
if bytes.Equal(zero, later) {
|
||||
t.Fatalf("pattern aliases LBA0 and LBA%d", off/4096)
|
||||
}
|
||||
for _, i := range []int{0, 4096, len(later) - 8} {
|
||||
if got := binary.LittleEndian.Uint64(later[i : i+8]); got != uint64(off+i) {
|
||||
t.Fatalf("word at byte%d=%d want%d", off+i, got, off+i)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
package durable_test
|
||||
|
||||
// A failed detach (design MIGRATION E4, review S6): the guest is never left
|
||||
// frozen by a detach that did not happen. When the final cut provably did not
|
||||
// publish (a failed upload, a refused CAS, an unresolved detach CAS that a
|
||||
// cancel at the same base settles), serving resumes on this host. When the
|
||||
// detach landed, the volume stays stopped with the detached result. When the
|
||||
// outcome cannot be decided (HEAD unreadable), it stays stopped: never resume
|
||||
// on top of a possibly detached HEAD.
|
||||
|
||||
import (
|
||||
"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/storage"
|
||||
)
|
||||
|
||||
// faultRemote injects one fault into the next detach's remote calls.
|
||||
type faultRemote struct {
|
||||
*storage.MemChunkRemote
|
||||
mu sync.Mutex
|
||||
putErr error // returned by every Put while set
|
||||
casMode string // "", "precondition", "lost" (not applied, error), "applied-lost" (applied, error), "hold"
|
||||
getHeadErr error // returned by every GetHead while set
|
||||
getHeadFail int // the next N GetHead calls fail
|
||||
getHeadHold bool // every GetHead blocks until its caller gives up
|
||||
// "delayed": the CAS's reply is lost now, the CAS itself reaches the
|
||||
// remote only when release closes; its own result goes to delayedErr.
|
||||
release chan struct{}
|
||||
delayedErr chan error
|
||||
}
|
||||
|
||||
var errInjected = errors.New("injected remote fault")
|
||||
|
||||
func (r *faultRemote) set(f func(r *faultRemote)) { r.mu.Lock(); f(r); r.mu.Unlock() }
|
||||
|
||||
func (r *faultRemote) Put(ctx context.Context, key string, data []byte) error {
|
||||
r.mu.Lock()
|
||||
err := r.putErr
|
||||
r.mu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.MemChunkRemote.Put(ctx, key, data)
|
||||
}
|
||||
|
||||
func (r *faultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
|
||||
r.mu.Lock()
|
||||
hold := r.getHeadHold
|
||||
err := r.getHeadErr
|
||||
if err == nil && r.getHeadFail > 0 {
|
||||
r.getHeadFail--
|
||||
err = errInjected
|
||||
}
|
||||
r.mu.Unlock()
|
||||
if hold {
|
||||
<-ctx.Done()
|
||||
return storage.ChunkHead{}, ctx.Err()
|
||||
}
|
||||
if err != nil {
|
||||
return storage.ChunkHead{}, err
|
||||
}
|
||||
return r.MemChunkRemote.GetHead(ctx)
|
||||
}
|
||||
|
||||
func (r *faultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) {
|
||||
r.mu.Lock()
|
||||
mode := r.casMode
|
||||
r.casMode = "" // one fault, on the next CAS only
|
||||
r.mu.Unlock()
|
||||
switch mode {
|
||||
case "precondition":
|
||||
return 0, storage.ErrChunkHeadPrecondition
|
||||
case "lost":
|
||||
return 0, errInjected
|
||||
case "hold": // held until the caller gives up: not applied
|
||||
<-ctx.Done()
|
||||
return 0, ctx.Err()
|
||||
case "delayed":
|
||||
r.mu.Lock()
|
||||
release, out := r.release, r.delayedErr
|
||||
r.mu.Unlock()
|
||||
go func() {
|
||||
<-release
|
||||
_, err := r.MemChunkRemote.CASHead(context.Background(), expected, next)
|
||||
out <- err
|
||||
}()
|
||||
return 0, errInjected
|
||||
case "applied-lost":
|
||||
if _, err := r.MemChunkRemote.CASHead(ctx, expected, next); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return 0, errInjected
|
||||
}
|
||||
return r.MemChunkRemote.CASHead(ctx, expected, next)
|
||||
}
|
||||
|
||||
// detachFixture: a chunk volume with one cut published and one more write
|
||||
// (dirty), so the detach's final cut has something to upload.
|
||||
func detachFixture(t *testing.T) (*faultRemote, *durable.DurableProvider, frontend.Backend) {
|
||||
t.Helper()
|
||||
remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()}
|
||||
p := chunkProvider(t, t.TempDir(), remote, v1View(), 0)
|
||||
openRecovered(t, p)
|
||||
b, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.Write(context.Background(), 4096, block(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.CutVolume(context.Background(), "v1", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.Write(context.Background(), 8192, block(2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return remote, p, b
|
||||
}
|
||||
|
||||
// assertServing: the volume accepts writes and a cut publishes them, with a
|
||||
// HEAD that is not detached.
|
||||
func assertServing(t *testing.T, p *durable.DurableProvider, b frontend.Backend, remote *faultRemote) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
if _, err := b.Write(ctx, 12288, block(3)); err != nil {
|
||||
t.Fatalf("write after an aborted detach: %v; want the volume serving again", err)
|
||||
}
|
||||
r, err := p.CutVolume(ctx, "v1", 0)
|
||||
if err != nil {
|
||||
t.Fatalf("cut after an aborted detach: %v", err)
|
||||
}
|
||||
if r.Head.State == storage.ChunkHeadDetached {
|
||||
t.Fatal("HEAD is detached after a detach that was reported aborted")
|
||||
}
|
||||
if !bytesEqual(headBlock(t, remote.MemChunkRemote, 2), block(2)) || !bytesEqual(headBlock(t, remote.MemChunkRemote, 3), block(3)) {
|
||||
t.Fatal("the cut after an aborted detach lost the dirty blocks")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreChunk_FailedDetachUploadResumes(t *testing.T) {
|
||||
remote, p, b := detachFixture(t)
|
||||
remote.set(func(r *faultRemote) { r.putErr = errInjected })
|
||||
if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) {
|
||||
t.Fatalf("detach with failing uploads: %v; want ErrDetachAborted", err)
|
||||
}
|
||||
remote.set(func(r *faultRemote) { r.putErr = nil })
|
||||
assertServing(t, p, b, remote)
|
||||
}
|
||||
|
||||
func TestWALStoreChunk_RefusedDetachCASResumes(t *testing.T) {
|
||||
remote, p, b := detachFixture(t)
|
||||
remote.set(func(r *faultRemote) { r.casMode = "precondition" })
|
||||
if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) {
|
||||
t.Fatalf("detach with a refused CAS: %v; want ErrDetachAborted", err)
|
||||
}
|
||||
assertServing(t, p, b, remote)
|
||||
}
|
||||
|
||||
// The detach CAS's reply is lost and it did not apply: the settle cancels it
|
||||
// with a CAS at the same base, so it can never land, and serving resumes.
|
||||
func TestWALStoreChunk_LostDetachCASNotAppliedIsCancelledAndResumes(t *testing.T) {
|
||||
remote, p, b := detachFixture(t)
|
||||
base, _ := remote.MemChunkRemote.GetHead(context.Background())
|
||||
remote.set(func(r *faultRemote) { r.casMode = "lost" })
|
||||
if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) {
|
||||
t.Fatalf("detach with a lost, unapplied CAS: %v; want ErrDetachAborted after the cancel", err)
|
||||
}
|
||||
// The cancel is a real CAS at the detach's base: HEAD moved one generation
|
||||
// and is not detached, so the lost detach CAS can never land afterwards.
|
||||
if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached || head.Gen != base.Gen+1 {
|
||||
t.Fatalf("HEAD after the cancel: gen %d state %q; want gen %d, not detached", head.Gen, head.State, base.Gen+1)
|
||||
}
|
||||
assertServing(t, p, b, remote)
|
||||
}
|
||||
|
||||
// The detach CAS's reply is lost but it applied: the detach succeeded, the
|
||||
// volume stays stopped and DetachVolume returns the detached result.
|
||||
func TestWALStoreChunk_LostDetachCASAppliedStaysDetached(t *testing.T) {
|
||||
remote, p, b := detachFixture(t)
|
||||
remote.set(func(r *faultRemote) { r.casMode = "applied-lost" })
|
||||
r, _, err := p.DetachVolume(context.Background(), "v1")
|
||||
if err != nil || r.Head.State != storage.ChunkHeadDetached {
|
||||
t.Fatalf("detach whose CAS applied but lost its reply: %+v %v; want the detached result", r, err)
|
||||
}
|
||||
if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("write after an applied detach: %v; want ErrNotReady", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The detach CAS applied but its reply was lost AND the cut's own HEAD re-read
|
||||
// failed: only the settle can tell. It reads HEAD, finds the detach, and the
|
||||
// detach succeeds (stays stopped) instead of resuming on a detached HEAD.
|
||||
func TestWALStoreChunk_LostDetachCASAppliedFoundBySettle(t *testing.T) {
|
||||
remote, p, b := detachFixture(t)
|
||||
remote.set(func(r *faultRemote) { r.casMode = "applied-lost"; r.getHeadFail = 1 })
|
||||
r, _, err := p.DetachVolume(context.Background(), "v1")
|
||||
if err != nil || r.Head.State != storage.ChunkHeadDetached {
|
||||
t.Fatalf("detach whose applied CAS only the settle can see: %+v %v; want the detached result", r, err)
|
||||
}
|
||||
if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("write after a settled, applied detach: %v; want ErrNotReady", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The detach CAS's reply is lost and HEAD cannot be read: the outcome is
|
||||
// unknown, so the volume stays stopped (also through a recovery).
|
||||
func TestWALStoreChunk_UndecidableDetachStaysStopped(t *testing.T) {
|
||||
remote, p, b := detachFixture(t)
|
||||
remote.set(func(r *faultRemote) { r.casMode = "lost"; r.getHeadErr = errInjected })
|
||||
if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) {
|
||||
t.Fatalf("detach with an undecidable outcome: %v; want ErrDetachOutcomeUnknown", err)
|
||||
}
|
||||
if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("write after an undecidable detach: %v; want ErrNotReady", err)
|
||||
}
|
||||
if _, err := p.RecoverVolume(context.Background(), "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) {
|
||||
t.Fatalf("recovery after an undecidable detach: %v; want the volume to stay stopped", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The freeze is bounded by DetachFreezeTimeout: a CAS that hangs ends there,
|
||||
// the outcome is settled (HEAD still at base: cancelled) and serving resumes,
|
||||
// all well inside bound + settle.
|
||||
func TestWALStoreChunk_DetachFreezeIsBoundedThenResumes(t *testing.T) {
|
||||
remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk,
|
||||
StorageRoot: t.TempDir(),
|
||||
BlockSize: 4096,
|
||||
NumBlocks: pcBlocks,
|
||||
ChunkBlocks: pcChunkBlocks,
|
||||
DetachFreezeTimeout: 300 * time.Millisecond,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
openRecovered(t, p)
|
||||
b, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.Write(context.Background(), 4096, block(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.CutVolume(context.Background(), "v1", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.Write(context.Background(), 8192, block(2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote.set(func(r *faultRemote) { r.casMode = "hold" })
|
||||
start := time.Now()
|
||||
_, _, err = p.DetachVolume(context.Background(), "v1")
|
||||
took := time.Since(start)
|
||||
if !errors.Is(err, durable.ErrDetachAborted) || !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("detach with a hung CAS: %v; want an aborted detach at the freeze bound", err)
|
||||
}
|
||||
// The cut gets three quarters of the bound, the settlement the rest.
|
||||
if took < 225*time.Millisecond || took > 300*time.Millisecond+200*time.Millisecond {
|
||||
t.Fatalf("detach with a hung CAS took %v; want the cut ended at 3/4 of the 300 ms freeze bound and the total within it", took)
|
||||
}
|
||||
assertServing(t, p, b, remote)
|
||||
}
|
||||
|
||||
// HEAD belongs to a newer epoch: the detach's CAS is refused and the volume
|
||||
// is fenced; it stays stopped (never resumes against another holder).
|
||||
func TestWALStoreChunk_DetachAgainstNewerEpochStaysStopped(t *testing.T) {
|
||||
remote, p, b := detachFixture(t)
|
||||
ctx := context.Background()
|
||||
cur, err := remote.MemChunkRemote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newer := cur
|
||||
newer.Epoch, newer.Holder = cur.Epoch+1, "another-holder"
|
||||
if _, err := remote.MemChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, newer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) || errors.Is(err, durable.ErrDetachAborted) {
|
||||
t.Fatalf("detach against a newer epoch: %v; want fenced, not aborted", err)
|
||||
}
|
||||
if _, err := b.Write(ctx, 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) && !errors.Is(err, frontend.ErrStalePrimary) {
|
||||
t.Fatalf("write after a fenced detach: %v; want it refused (not ready / stale primary)", err)
|
||||
}
|
||||
}
|
||||
|
||||
// P1 (review): a repeated detach after a successful one, with a cancelled
|
||||
// context (its StopIO fails at once), returns the first result and never
|
||||
// resumes serving.
|
||||
func TestWALStoreChunk_RepeatDetachWithCancelledContextNeverResumes(t *testing.T) {
|
||||
_, p, b := detachFixture(t)
|
||||
r1, _, err := p.DetachVolume(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
forced := false
|
||||
durable.SetTestDetachStopIO(p, func(context.Context) error { forced = true; return context.Canceled }) // the drain fails
|
||||
r2, _, err := p.DetachVolume(context.Background(), "v1")
|
||||
if !forced {
|
||||
t.Fatal("the failed-drain branch was not taken")
|
||||
}
|
||||
if err != nil || r2.Head.Gen != r1.Head.Gen || r2.Head.State != storage.ChunkHeadDetached {
|
||||
t.Fatalf("repeated detach with a cancelled context: %+v %v; want the first result %+v", r2, err, r1)
|
||||
}
|
||||
if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("write after a repeated detach: %v; want ErrNotReady (never resumed)", err)
|
||||
}
|
||||
}
|
||||
|
||||
// P1 (review): after an undecidable detach, a retry whose StopIO fails (a
|
||||
// cancelled context) settles first and stays stopped while the outcome is
|
||||
// still unknown.
|
||||
func TestWALStoreChunk_RetryAfterUndecidableDetachNeverResumes(t *testing.T) {
|
||||
remote, p, b := detachFixture(t)
|
||||
remote.set(func(r *faultRemote) { r.casMode = "lost"; r.getHeadErr = errInjected })
|
||||
if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) {
|
||||
t.Fatalf("first detach: %v; want ErrDetachOutcomeUnknown", err)
|
||||
}
|
||||
forced := false
|
||||
durable.SetTestDetachStopIO(p, func(context.Context) error { forced = true; return context.Canceled }) // the drain fails
|
||||
_, _, err := p.DetachVolume(context.Background(), "v1")
|
||||
if !forced {
|
||||
t.Fatal("the failed-drain branch was not taken")
|
||||
}
|
||||
if !errors.Is(err, durable.ErrDetachOutcomeUnknown) || errors.Is(err, durable.ErrDetachAborted) {
|
||||
t.Fatalf("retry over an unresolved detach CAS: %v; want still unknown, never aborted", err)
|
||||
}
|
||||
if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("write after a retry over an unknown detach: %v; want ErrNotReady", err)
|
||||
}
|
||||
}
|
||||
|
||||
// P1 (review): one freeze budget covers the cut AND the settlement: with the
|
||||
// CAS and every HEAD read hung, DetachVolume returns within the bound (here
|
||||
// undecided, so the volume stays stopped).
|
||||
func TestWALStoreChunk_DetachFreezeBoundCoversTheSettle(t *testing.T) {
|
||||
const freeze = 400 * time.Millisecond
|
||||
remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
|
||||
DetachFreezeTimeout: freeze,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
openRecovered(t, p)
|
||||
b, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.Write(context.Background(), 4096, block(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote.set(func(r *faultRemote) { r.casMode = "hold"; r.getHeadHold = true })
|
||||
deadlines := map[string]time.Time{}
|
||||
durable.SetTestDetachTrace(p, func(stage string, d time.Time) { deadlines[stage] = d })
|
||||
start := time.Now()
|
||||
_, _, err = p.DetachVolume(context.Background(), "v1")
|
||||
took := time.Since(start)
|
||||
cutAt, settleAt := deadlines["cut"].Sub(start), deadlines["settle"].Sub(start)
|
||||
if cutAt < freeze*3/4-50*time.Millisecond || cutAt > freeze*3/4+50*time.Millisecond || settleAt < freeze-50*time.Millisecond || settleAt > freeze+50*time.Millisecond {
|
||||
t.Fatalf("deadlines: cut %v, settle %v after the start; want three quarters of the %v freeze, then the bound", cutAt, settleAt, freeze)
|
||||
}
|
||||
if !errors.Is(err, durable.ErrDetachOutcomeUnknown) {
|
||||
t.Fatalf("detach with a hung CAS and hung HEAD reads: %v; want the outcome unknown", err)
|
||||
}
|
||||
if took > freeze+200*time.Millisecond {
|
||||
t.Fatalf("detach took %v; the %v freeze bound must cover the settlement too", took, freeze)
|
||||
}
|
||||
if _, err := b.Write(context.Background(), 8192, block(2)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("write after an undecided detach: %v; want ErrNotReady", err)
|
||||
}
|
||||
}
|
||||
|
||||
// P2 (review): the lost detach CAS really is in flight. It reaches the remote
|
||||
// only after the cancel landed, and then fails its precondition: HEAD stays
|
||||
// active.
|
||||
func TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel(t *testing.T) {
|
||||
remote, p, b := detachFixture(t)
|
||||
release, delayed := make(chan struct{}), make(chan error, 1)
|
||||
var once sync.Once
|
||||
unblock := func() { once.Do(func() { close(release) }) }
|
||||
joined := false
|
||||
t.Cleanup(func() { // join the delayed CAS worker, bounded
|
||||
unblock()
|
||||
if !joined {
|
||||
select {
|
||||
case <-delayed:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("delayed CAS worker not joined")
|
||||
}
|
||||
}
|
||||
})
|
||||
remote.set(func(r *faultRemote) { r.casMode = "delayed"; r.release, r.delayedErr = release, delayed })
|
||||
if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) {
|
||||
t.Fatalf("detach with a delayed CAS: %v; want ErrDetachAborted after the cancel", err)
|
||||
}
|
||||
unblock()
|
||||
var derr error
|
||||
select {
|
||||
case derr = <-delayed:
|
||||
joined = true
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the delayed detach CAS did not complete after its release")
|
||||
}
|
||||
if !errors.Is(derr, storage.ErrChunkHeadPrecondition) {
|
||||
t.Fatalf("the delayed detach CAS after the cancel: %v; want a precondition failure", derr)
|
||||
}
|
||||
if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached {
|
||||
t.Fatal("the delayed detach CAS landed after the cancel")
|
||||
}
|
||||
assertServing(t, p, b, remote)
|
||||
}
|
||||
@@ -118,10 +118,11 @@ func TestWALStoreChunk_DetachDrainsAdmittedWrite(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The drain is bounded by the caller's context: a detach that cannot drain
|
||||
// fails, publishes nothing and keeps I/O stopped, also through a recovery;
|
||||
// once the admitted write finishes, a retry settles the detach with it.
|
||||
func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) {
|
||||
// The drain is bounded (the caller's context or the freeze bound): a detach
|
||||
// that cannot drain publishes nothing, so it aborts and the volume serves
|
||||
// again (MIGRATION E4; it used to stay stopped, review S6); once the admitted
|
||||
// write finishes, a retry detaches with every acknowledged write.
|
||||
func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p, view := parkedProvider(t, remote)
|
||||
@@ -139,21 +140,54 @@ func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) {
|
||||
dctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
|
||||
_, _, err = p.DetachVolume(dctx, "v1")
|
||||
cancel()
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("detach that cannot drain: %v; want the context's deadline", err)
|
||||
if !errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, durable.ErrDetachAborted) {
|
||||
t.Fatalf("detach that cannot drain: %v; want an aborted detach on the context's deadline", err)
|
||||
}
|
||||
if head, _ := remote.GetHead(ctx); head.State == storage.ChunkHeadDetached {
|
||||
t.Fatalf("a detach that did not drain published a detached HEAD: %+v", head)
|
||||
}
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) {
|
||||
t.Fatalf("recovery after a failed detach: %v; want the volume to stay stopped", err)
|
||||
// Serving resumes: a new write is accepted. The drain still pending from
|
||||
// the aborted stop orders new I/O after the I/O admitted before it, so
|
||||
// this write completes once that admitted write does (never on the
|
||||
// detach itself).
|
||||
arrived := make(chan struct{})
|
||||
var arriveOnce sync.Once
|
||||
durable.SetTestBeforeIOLock(b, func() { arriveOnce.Do(func() { close(arrived) }) })
|
||||
nerr := make(chan error, 1)
|
||||
go func() { _, err := b.Write(ctx, 8192, block(6)); nerr <- err }()
|
||||
bounded := func(what string, ch <-chan struct{}) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-ch:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("%s did not happen within 5s", what)
|
||||
}
|
||||
}
|
||||
if _, err := b.Write(ctx, 8192, block(6)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("new write after a failed detach and a recovery: %v; want ErrNotReady", err)
|
||||
bounded("the new write passing the operational gate (serving resumed)", arrived)
|
||||
select {
|
||||
case err := <-nerr:
|
||||
t.Fatalf("new write completed (%v) ahead of the write admitted before the stop", err)
|
||||
default: // queued behind the admitted write at the I/O lock, as the drain orders it
|
||||
}
|
||||
|
||||
view.unpark()
|
||||
acked := <-werr == nil
|
||||
recv := func(what string, ch <-chan error) error {
|
||||
t.Helper()
|
||||
select {
|
||||
case err := <-ch:
|
||||
return err
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("%s did not complete within 5s", what)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
acked := recv("the admitted write", werr) == nil
|
||||
if err := recv("the new write", nerr); err != nil {
|
||||
t.Fatalf("new write after an aborted detach: %v; want it accepted", err)
|
||||
}
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatalf("recovery after an aborted detach: %v; want it to succeed", err)
|
||||
}
|
||||
o := detachOutcome{}
|
||||
o.r, o.last, o.err = p.DetachVolume(ctx, "v1")
|
||||
if o.err != nil || o.r.Head.State != storage.ChunkHeadDetached {
|
||||
@@ -162,6 +196,9 @@ func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) {
|
||||
if acked && !bytesEqual(headBlock(t, remote, 1), block(5)) {
|
||||
t.Fatal("the write admitted before the stop was acknowledged but is not in the detached HEAD")
|
||||
}
|
||||
if !bytesEqual(headBlock(t, remote, 2), block(6)) {
|
||||
t.Fatal("the write accepted after the aborted detach is not in the detached HEAD")
|
||||
}
|
||||
}
|
||||
|
||||
// After a successful detach, RecoverVolume keeps I/O stopped and a repeated
|
||||
|
||||
@@ -401,9 +401,52 @@ func TestWALStoreChunk_ConcurrentRecoverAttachesOnce(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The caller's recovery deadline governs the attach's first remote call,
|
||||
// with no Close and no hold release.
|
||||
// A caller deadline can expire during local recovery, before the first
|
||||
// remote call, or while that call is held. Both must return the deadline
|
||||
// error without Close or releasing the remote hold.
|
||||
func TestWALStoreChunk_RecoverHonoursCallerDeadline(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
timeout time.Duration
|
||||
}{
|
||||
{"during_recovery_or_attach", 300 * time.Millisecond},
|
||||
{"before_recovery", -time.Millisecond},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
g := newGated(storage.NewMemChunkRemote())
|
||||
g.holdGetHead = make(chan struct{})
|
||||
g.honourCtx = true
|
||||
t.Cleanup(g.release)
|
||||
p := chunkProvider(t, t.TempDir(), g, v1View(), 0)
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), tc.timeout)
|
||||
defer cancel()
|
||||
recErr := make(chan error, 1)
|
||||
go func() { _, err := p.RecoverVolume(ctx, "v1"); recErr <- err }()
|
||||
var err error
|
||||
select {
|
||||
case what := <-g.entered:
|
||||
if what != "gethead" {
|
||||
t.Fatalf("held call %q, want gethead", what)
|
||||
}
|
||||
err = recvErr(t, recErr, "RecoverVolume past its caller deadline")
|
||||
case err = <-recErr:
|
||||
// Local recovery may consume the deadline before attach starts.
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("RecoverVolume neither returned nor reached the held remote")
|
||||
}
|
||||
if !errors.Is(err, context.DeadlineExceeded) || ctx.Err() != context.DeadlineExceeded {
|
||||
t.Fatalf("RecoverVolume=%v caller=%v, want deadline exceeded", err, ctx.Err())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// This handshake separately guarantees that the caller's cancellation is
|
||||
// tested with a remote call already in flight, independent of local I/O speed.
|
||||
func TestWALStoreChunk_RecoverHonoursCallerCancellationAfterRemoteEntry(t *testing.T) {
|
||||
g := newGated(storage.NewMemChunkRemote())
|
||||
g.holdGetHead = make(chan struct{})
|
||||
g.honourCtx = true
|
||||
@@ -412,13 +455,14 @@ func TestWALStoreChunk_RecoverHonoursCallerDeadline(t *testing.T) {
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
recErr := make(chan error, 1)
|
||||
go func() { _, err := p.RecoverVolume(ctx, "v1"); recErr <- err }()
|
||||
waitEntered(t, g, "gethead")
|
||||
if err := recvErr(t, recErr, "RecoverVolume past its caller deadline"); err == nil {
|
||||
t.Fatal("RecoverVolume succeeded although its deadline expired during attach")
|
||||
cancel()
|
||||
if err := recvErr(t, recErr, "RecoverVolume after caller cancellation"); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("RecoverVolume=%v, want caller cancellation", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -542,24 +586,65 @@ func TestWALStoreChunk_CloseSettlesDeferredAttach(t *testing.T) {
|
||||
// recovery refuses as a WAL integrity fault. It returns a restore func.
|
||||
func corruptWALWrite(t *testing.T, path string, fill byte) func() {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(path)
|
||||
// Read the known fixture geometry without touching the owner's locked
|
||||
// byte zero, and search only the WAL (the extent may contain a copy).
|
||||
source, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload := bytes.Repeat([]byte{fill}, 4096)
|
||||
at := bytes.Index(raw, payload)
|
||||
if at < 30 || bytes.Index(raw[at+1:], payload) >= 0 {
|
||||
t.Fatalf("WAL record for fill %#x not found exactly once", fill)
|
||||
defer source.Close()
|
||||
var geometry [16]byte
|
||||
if _, err := source.ReadAt(geometry[:], 48); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const hdr = 30 // LSN 8, Reserved 8, Type 1, Flags 1, LBA 8, Length 4
|
||||
start := at - hdr
|
||||
rec := append([]byte(nil), raw[start:at+4096+8]...)
|
||||
walStart := binary.LittleEndian.Uint64(geometry[:8])
|
||||
walSize := binary.LittleEndian.Uint64(geometry[8:])
|
||||
if walStart != 8192 || walSize > 64*1024*1024 || walSize < 4096+70 {
|
||||
t.Fatalf("unexpected v3 fixture geometry %d/%d", walStart, walSize)
|
||||
}
|
||||
wal := make([]byte, int(walSize))
|
||||
if _, err := source.ReadAt(wal, int64(walStart)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload := bytes.Repeat([]byte{fill}, 4096)
|
||||
// Search every overlapping payload occurrence, accepting only a complete,
|
||||
// CRC-valid single-write record. A nonce/trailer byte may equal fill, so
|
||||
// the first bytes.Index match is not necessarily the payload boundary.
|
||||
const hdr, recordSize = 62, 62 + 4096 + 8
|
||||
table := crc32.MakeTable(crc32.Castagnoli)
|
||||
at, matches := -1, 0
|
||||
for search := 0; search <= len(wal)-len(payload); {
|
||||
relative := bytes.Index(wal[search:], payload)
|
||||
if relative < 0 {
|
||||
break
|
||||
}
|
||||
candidate := search + relative
|
||||
search = candidate + 1
|
||||
if candidate < hdr || candidate+4096+8 > len(wal) {
|
||||
continue
|
||||
}
|
||||
record := wal[candidate-hdr : candidate+4096+8]
|
||||
if record[16] != 0x01 || record[17] != 0 ||
|
||||
binary.LittleEndian.Uint64(record[8:16]) != 0 ||
|
||||
binary.LittleEndian.Uint32(record[26:30]) != 4096 ||
|
||||
binary.LittleEndian.Uint64(record[38:46])%walSize != uint64(candidate-hdr) ||
|
||||
binary.LittleEndian.Uint32(record[hdr+4096:]) != crc32.Checksum(record[:hdr+4096], table) ||
|
||||
binary.LittleEndian.Uint32(record[hdr+4096+4:]) != recordSize {
|
||||
continue
|
||||
}
|
||||
at, matches = candidate, matches+1
|
||||
}
|
||||
if matches != 1 {
|
||||
t.Fatalf("CRC-valid WAL write payload %#x matched %d records; want exactly one", fill, matches)
|
||||
}
|
||||
start := int64(walStart) + int64(at-hdr)
|
||||
rec := append([]byte(nil), wal[at-hdr:at+4096+8]...)
|
||||
orig := append([]byte(nil), rec...)
|
||||
if rec[16] != 0x01 || binary.LittleEndian.Uint64(rec[8:]) != 0 {
|
||||
t.Fatalf("unexpected WAL record header % x", rec[:hdr])
|
||||
}
|
||||
rec[16] = 0x04 // write batch, Reserved stays 0: invalid
|
||||
binary.LittleEndian.PutUint32(rec[hdr+4096:], crc32.ChecksumIEEE(rec[:hdr+4096]))
|
||||
rec[16] = 0x04 // invalid native batch: BatchCount remains zero
|
||||
binary.LittleEndian.PutUint32(rec[hdr+4096:], crc32.Checksum(rec[:hdr+4096], crc32.MakeTable(crc32.Castagnoli)))
|
||||
f, err := os.OpenFile(path, os.O_WRONLY, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -580,6 +665,47 @@ func corruptWALWrite(t *testing.T, path string, fill byte) func() {
|
||||
}
|
||||
}
|
||||
|
||||
// The nonce ends immediately before the payload. A matching last nonce byte
|
||||
// must not shift the corruption target one byte into the header.
|
||||
func TestCorruptWALWrite_NoncePayloadOverlap(t *testing.T) {
|
||||
const prefix, payloadSize, walStart, walSize = 62, 4096, 8192, 16384
|
||||
path := filepath.Join(t.TempDir(), "overlap.bin")
|
||||
image := make([]byte, walStart+walSize)
|
||||
binary.LittleEndian.PutUint64(image[48:56], walStart)
|
||||
binary.LittleEndian.PutUint64(image[56:64], walSize)
|
||||
rec := image[walStart : walStart+prefix+payloadSize+8]
|
||||
binary.LittleEndian.PutUint64(rec[:8], 1)
|
||||
rec[16] = 0x01
|
||||
binary.LittleEndian.PutUint64(rec[18:26], 5)
|
||||
binary.LittleEndian.PutUint32(rec[26:30], payloadSize)
|
||||
rec[61] = 0xa7 // legal nonce: old bytes.Index reports 61, not payload offset 62
|
||||
copy(rec[prefix:], bytes.Repeat([]byte{0xa7}, payloadSize))
|
||||
binary.LittleEndian.PutUint32(rec[prefix+payloadSize:], crc32.Checksum(rec[:prefix+payloadSize], crc32.MakeTable(crc32.Castagnoli)))
|
||||
binary.LittleEndian.PutUint32(rec[prefix+payloadSize+4:], uint32(len(rec)))
|
||||
if err := os.WriteFile(path, image, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restore := corruptWALWrite(t, path, 0xa7)
|
||||
changed, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := append([]byte(nil), image...)
|
||||
want[walStart+16] = 0x04
|
||||
binary.LittleEndian.PutUint32(want[walStart+prefix+payloadSize:], crc32.Checksum(want[walStart:walStart+prefix+payloadSize], crc32.MakeTable(crc32.Castagnoli)))
|
||||
if !bytes.Equal(changed, want) {
|
||||
t.Fatal("corruption changed bytes outside the intended type/CRC")
|
||||
}
|
||||
restore()
|
||||
repaired, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(repaired, image) {
|
||||
t.Fatal("restore did not recover the exact original image")
|
||||
}
|
||||
}
|
||||
|
||||
// A deferred attach belongs to the recovery that registered it. Recovery
|
||||
// A succeeds before authority; recovery B then fails on a real WAL
|
||||
// integrity fault; when authority arrives, A's wait must neither attach
|
||||
@@ -609,6 +735,15 @@ func TestWALStoreChunk_StaleWaiterCannotOverrideFailedRecovery(t *testing.T) {
|
||||
if _, err := s.Write(5, block(0xA7)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// This oracle requires corruption below a persisted W. Default mode C
|
||||
// intentionally permits losing its newest uncheckpointed batch instead.
|
||||
ws, ok := s.(*storage.WALStore)
|
||||
if !ok {
|
||||
t.Fatalf("unexpected native store %T", s)
|
||||
}
|
||||
if err := ws.SetWMode(storage.WModeStrict); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -683,6 +818,15 @@ func TestWALStoreChunk_FailedRecoveryRetiresAuthorityWait(t *testing.T) {
|
||||
if _, err := s.Write(5, block(0xA7)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// This oracle requires corruption below a persisted W. Default mode C
|
||||
// intentionally permits losing its newest uncheckpointed batch instead.
|
||||
ws, ok := s.(*storage.WALStore)
|
||||
if !ok {
|
||||
t.Fatalf("unexpected native store %T", s)
|
||||
}
|
||||
if err := ws.SetWMode(storage.WModeStrict); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -774,6 +918,15 @@ func TestWALStoreChunk_StaleWaiterPastTickCheckCannotAttach(t *testing.T) {
|
||||
if _, err := s.Write(5, block(0xA7)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// This oracle requires corruption below a persisted W. Default mode C
|
||||
// intentionally permits losing its newest uncheckpointed batch instead.
|
||||
ws, ok := s.(*storage.WALStore)
|
||||
if !ok {
|
||||
t.Fatalf("unexpected native store %T", s)
|
||||
}
|
||||
if err := ws.SetWMode(storage.WModeStrict); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -781,6 +934,7 @@ func TestWALStoreChunk_StaleWaiterPastTickCheckCannotAttach(t *testing.T) {
|
||||
|
||||
// Park A's wait inside its projection read, after its tick check.
|
||||
view.arm()
|
||||
t.Cleanup(func() { close(view.release) })
|
||||
select {
|
||||
case <-view.parked:
|
||||
case <-time.After(10 * time.Second):
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
package durable_test
|
||||
|
||||
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"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"runtime"
|
||||
"sort"
|
||||
"testing"
|
||||
"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) {
|
||||
for _, mode := range []storage.WMode{storage.WModeLagged, storage.WModeStrict} {
|
||||
t.Run(fmt.Sprintf("mode-%d", mode), func(t *testing.T) {
|
||||
runNoClientFlushBurst(t, mode)
|
||||
})
|
||||
}
|
||||
}
|
||||
func runNoClientFlushBurst(t *testing.T, mode storage.WMode) {
|
||||
const total = 400 * 1024 * 1024
|
||||
const transfer = 128 * 1024
|
||||
ctx := context.Background()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096,
|
||||
NumBlocks: (1 << 30) / 4096, ChunkBlocks: 1024, ChunkCaptureInterval: 0,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := p.Close(); err != nil {
|
||||
t.Logf("close: %v", err)
|
||||
}
|
||||
})
|
||||
s, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
be, err := p.Open(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ws := s.(*storage.WALStore)
|
||||
if err := ws.SetWMode(mode); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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())
|
||||
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 {
|
||||
for i := range data {
|
||||
if i%8 == 0 {
|
||||
binary.LittleEndian.PutUint64(data[i:i+8], uint64(off+i))
|
||||
}
|
||||
}
|
||||
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())
|
||||
}
|
||||
}
|
||||
// The expected bytes come from the submitted pattern, not another reader.
|
||||
for off := 0; off < total; off += transfer {
|
||||
got := make([]byte, transfer)
|
||||
n, err := be.Read(ctx, int64(off), got)
|
||||
if err != nil {
|
||||
t.Fatalf("readback at%d: %v", off, err)
|
||||
}
|
||||
if n != transfer {
|
||||
t.Fatalf("short readback at%d: %d", off, n)
|
||||
}
|
||||
for i := 0; i < len(got); i += 8 {
|
||||
if value := binary.LittleEndian.Uint64(got[i : i+8]); value != uint64(off+i) {
|
||||
t.Fatalf("readback offset%d got%d", off+i, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort.Slice(durations, func(i, j int) bool { return durations[i] < durations[j] })
|
||||
batches := ws.WALSyncCount() - syncsBefore
|
||||
fsyncs := batches
|
||||
if mode == storage.WModeStrict {
|
||||
fsyncs *= 2
|
||||
}
|
||||
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)
|
||||
}
|
||||
st := p.DurableStatuses()
|
||||
if after.Gen != before.Gen || after.RemoteLSN != before.RemoteLSN {
|
||||
t.Fatalf("remote moved without explicit cut: before=%+v after=%+v", before, after)
|
||||
}
|
||||
if len(st) != 1 || st[0].Chunk == nil || st[0].Chunk.Stats.CutsOK != 0 {
|
||||
t.Fatalf("unexpected cuts: %+v", st)
|
||||
}
|
||||
if ws.CheckpointLSN() == 0 || st[0].WriteProfile.WALAppendWrapCount == 0 {
|
||||
t.Fatal("no checkpoint or physical wrap observed")
|
||||
}
|
||||
t.Logf("after HEAD gen=%d remoteLSN=%d cp=%d next=%d wraps=%d cuts=%d", after.Gen, after.RemoteLSN, ws.CheckpointLSN(), ws.NextLSN(), st[0].WriteProfile.WALAppendWrapCount, st[0].Chunk.Stats.CutsOK)
|
||||
|
||||
}
|
||||
|
||||
// Actual RF2 coordinator pins retained history even after an internal fsync.
|
||||
// Expiry is retryable; ending the session restores local no-Flush progress.
|
||||
func TestWALStoreChunkV3NoFlushWithActiveRF2CatchupPin(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
s, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
be, err := p.Open(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ws := s.(*storage.WALStore)
|
||||
c := recovery.NewPeerShipCoordinator()
|
||||
if err := c.StartSession("r2", 1, 0, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ws.SetRecycleFloorSource(c)
|
||||
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) {
|
||||
start := time.Now()
|
||||
r := h.Handle(ctx, nvme.IOCommand{Opcode: 1, NSID: 1, SLBA: uint64(off / 4096), NLB: 32, Data: data})
|
||||
if r.AsError() != nil {
|
||||
if r.SCT != nvme.SCTGeneric || r.SC != nvme.SCNamespaceNotReady || time.Since(start) >= 5*time.Second {
|
||||
t.Fatalf("pin wait status=%+v elapsed=%v", r, time.Since(start))
|
||||
}
|
||||
stalled = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !stalled || ws.CheckpointLSN() != 0 {
|
||||
t.Fatalf("pin did not constrain checkpoint: stalled=%v cp=%d", stalled, ws.CheckpointLSN())
|
||||
}
|
||||
count := 0
|
||||
if err := ws.ScanLBAs(1, func(e storage.RecoveryEntry) error {
|
||||
count++
|
||||
if !bytes.Equal(e.Data, bytes.Repeat([]byte{0x5a}, 4096)) {
|
||||
return fmt.Errorf("pinned catch-up bytes changed")
|
||||
}
|
||||
return nil
|
||||
}); err != nil || count == 0 {
|
||||
t.Fatalf("retained catch-up records=%d err=%v", count, err)
|
||||
}
|
||||
c.EndSession("r2")
|
||||
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,270 @@
|
||||
//go:build swblock_format_v3_test
|
||||
|
||||
package durable
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDurableProviderV3_AttachedChunkBASEInstallAndCapture(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p := mappedProviderV3(t, t.TempDir(), remote)
|
||||
st, e := p.EnsureStorage("v1")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.RecoverVolume(ctx, "v1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var id [16]byte
|
||||
id[0] = 1
|
||||
h, e := storage.BeginInstall(st, 0, id)
|
||||
if e != nil {
|
||||
t.Fatalf("real provider attached BASE begin refused: %v", e)
|
||||
}
|
||||
want := bytes.Repeat([]byte{0x69}, 4096)
|
||||
if e = h.WriteBase(5, want); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.CaptureVolume(ctx, "v1"); e == nil {
|
||||
t.Fatal("partial BASE was captured")
|
||||
}
|
||||
if e = h.MarkBaseComplete(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.CaptureVolume(ctx, "v1"); e != nil {
|
||||
t.Fatalf("completed BASE capture refused: %v", e)
|
||||
}
|
||||
head, e := remote.GetHead(ctx)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ref, ok := head.Chunks[1]
|
||||
if !ok {
|
||||
t.Fatal("completed BASE chunk omitted")
|
||||
}
|
||||
chunk, e := remote.Get(ctx, ref.Key)
|
||||
if e != nil || len(chunk) < 8192 || !bytes.Equal(chunk[4096:8192], want) {
|
||||
t.Fatalf("captured BASE mismatch: %v", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurableProviderV3_AttachesCompletedChunkBASE(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
p := mappedProviderV3(t, t.TempDir(), storage.NewMemChunkRemote())
|
||||
st, e := p.EnsureStorage("v1")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = st.Recover(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var id [16]byte
|
||||
id[0] = 2
|
||||
h, e := storage.BeginInstall(st, 7, id)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = h.WriteBase(5, bytes.Repeat([]byte{0x37}, 4096)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = h.MarkBaseComplete(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.RecoverVolume(ctx, "v1"); e != nil {
|
||||
t.Fatalf("real provider completed BASE attach refused: %v", e)
|
||||
}
|
||||
got := make([]byte, 4096)
|
||||
if n, e := p.Backend("v1").Read(ctx, 5*4096, got); e != nil || n != 4096 || !bytes.Equal(got, bytes.Repeat([]byte{0x37}, 4096)) {
|
||||
t.Fatalf("completed BASE read n=%d err=%v", n, e)
|
||||
}
|
||||
}
|
||||
|
||||
// A complete local BASE is not an empty fresh restore, even while the
|
||||
// provider's first-attach marker exists and HEAD still names an older image.
|
||||
func TestDurableProviderV3_CompletedBASEDoesNotRestoreOlderHEAD(t *testing.T) {
|
||||
completedBASEDoesNotRestoreOlderHEAD(t, false)
|
||||
}
|
||||
|
||||
func TestDurableProviderV3_DefersBASERetirementUntilLocalPresence(t *testing.T) {
|
||||
completedBASEDoesNotRestoreOlderHEAD(t, true)
|
||||
}
|
||||
|
||||
func completedBASEDoesNotRestoreOlderHEAD(t *testing.T, retire bool) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
source := mappedProviderV3(t, t.TempDir(), remote)
|
||||
if _, e := source.EnsureStorage("v1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := source.RecoverVolume(ctx, "v1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, lba := range []int64{5, 9} {
|
||||
if n, e := source.Backend("v1").Write(ctx, lba*4096, bytes.Repeat([]byte{0x11}, 4096)); e != nil || n != 4096 {
|
||||
t.Fatal(n, e)
|
||||
}
|
||||
}
|
||||
if e := source.Backend("v1").Sync(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := source.CaptureVolume(ctx, "v1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := source.Close(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
root := t.TempDir()
|
||||
target := mappedProviderV3(t, root, remote)
|
||||
st, e := target.EnsureStorage("v1")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = st.Recover(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var id [16]byte
|
||||
id[0] = 3
|
||||
h, e := storage.BeginInstall(st, 7, id)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
want := bytes.Repeat([]byte{0x78}, 4096)
|
||||
if e = h.WriteBase(5, want); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = h.WriteBase(9, make([]byte, 4096)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if retire {
|
||||
if e = h.ApplyInstallEntry(5, want, 8); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if e = h.MarkBaseComplete(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if retire {
|
||||
if _, e = st.Sync(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = storage.FlushMappedWALStoreV3Test(st.(*storage.WALStore)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
state, _ := storage.BaseStateV3Test(st.(*storage.WALStore))
|
||||
if _, ok := st.(*storage.WALStore).InstalledBaseLSN(); !ok || state != storage.BaseInstalled || st.(*storage.WALStore).CheckpointLSN() < 8 {
|
||||
t.Fatalf("BASE retired before durable local presence: state=%v checkpoint=%d", state, st.(*storage.WALStore).CheckpointLSN())
|
||||
}
|
||||
// The provider must restore the opt-in gate before recovery can
|
||||
// publish a descriptor on a reopened store.
|
||||
if e = target.Close(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
target = mappedProviderV3(t, root, remote)
|
||||
st, e = target.EnsureStorage("v1")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if _, e = target.RecoverVolume(ctx, "v1"); e != nil {
|
||||
t.Fatalf("completed local BASE was treated as empty remote restore: %v", e)
|
||||
}
|
||||
check := func() {
|
||||
t.Helper()
|
||||
for lba, expected := range map[int64][]byte{5: want, 9: make([]byte, 4096)} {
|
||||
got := make([]byte, 4096)
|
||||
if n, e := target.Backend("v1").Read(ctx, lba*4096, got); e != nil || n != 4096 || !bytes.Equal(got, expected) {
|
||||
t.Fatalf("local BASE lba%d bytes lost: n%d err%v", lba, n, e)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
check()
|
||||
if retire {
|
||||
if _, e = st.Sync(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = storage.FlushMappedWALStoreV3Test(st.(*storage.WALStore)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
state, _ := storage.BaseStateV3Test(st.(*storage.WALStore))
|
||||
if state != storage.BaseNone {
|
||||
t.Fatalf("durable local presence did not release retirement: %v", state)
|
||||
}
|
||||
}
|
||||
if e = target.Close(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
target = mappedProviderV3(t, root, remote)
|
||||
if _, e = target.EnsureStorage("v1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = target.RecoverVolume(ctx, "v1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
check()
|
||||
}
|
||||
|
||||
// A seeded checkpoint is not proof that any extent data was materialized.
|
||||
func TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
source := mappedProviderV3(t, t.TempDir(), remote)
|
||||
if _, err := source.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := source.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := bytes.Repeat([]byte{0x4d}, 4096)
|
||||
if n, err := source.Backend("v1").Write(ctx, 5*4096, want); err != nil || n != len(want) {
|
||||
t.Fatal(n, err)
|
||||
}
|
||||
if err := source.Backend("v1").Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := source.CaptureVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := source.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target := mappedProviderV3(t, t.TempDir(), remote)
|
||||
st, err := target.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = st.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = st.(*storage.WALStore).SeedChunkFrontier(head.RemoteLSN); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.(*storage.WALStore).CheckpointLSN() == 0 || st.NextLSN() <= 1 {
|
||||
t.Fatal("seed did not establish the ambiguous frontier")
|
||||
}
|
||||
if _, ok := st.(*storage.WALStore).InstalledBaseLSN(); ok {
|
||||
t.Fatal("seed became a completed BASE")
|
||||
}
|
||||
if _, err = target.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := make([]byte, 4096)
|
||||
if n, err := target.Backend("v1").Read(ctx, 5*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) {
|
||||
t.Fatalf("seed-only restore lost remote bytes: n=%d err=%v equal=%v", n, err, bytes.Equal(got, want))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
//go:build swblock_format_v3_test
|
||||
|
||||
package durable
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type freshCrashImage struct {
|
||||
Head storage.ChunkHead
|
||||
Objects map[string][]byte
|
||||
}
|
||||
|
||||
func freshCrashRemote(t *testing.T, path string) *storage.MemChunkRemote {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var img freshCrashImage
|
||||
if err = json.Unmarshal(raw, &img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote := storage.NewMemChunkRemote()
|
||||
ctx := context.Background()
|
||||
for key, data := range img.Objects {
|
||||
if err = remote.Put(ctx, key, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for gen := uint64(0); gen < img.Head.Gen; gen++ {
|
||||
current, e := remote.GetHead(ctx)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: current.Gen, Epoch: current.Epoch}, img.Head); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
return remote
|
||||
}
|
||||
|
||||
// The child exits after presence is durable but before the fresh marker is
|
||||
// removed. No Close or provider cleanup runs on the successful crash path.
|
||||
func TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE(t *testing.T) {
|
||||
freshMarkerCrashKeepsCompletedBASE(t, "attach")
|
||||
}
|
||||
|
||||
func TestDurableProviderV3_FreshMarkerCompletionCrashKeepsCompletedBASE(t *testing.T) {
|
||||
freshMarkerCrashKeepsCompletedBASE(t, "complete")
|
||||
}
|
||||
|
||||
func TestDurableProviderV3_FreshMarkerCaptureCrashKeepsCompletedBASE(t *testing.T) {
|
||||
freshMarkerCrashKeepsCompletedBASE(t, "capture")
|
||||
}
|
||||
|
||||
func freshMarkerCrashKeepsCompletedBASE(t *testing.T, mode string) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if root := os.Getenv("SWBLOCK_V3_FRESH_CRASH_ROOT"); root != "" {
|
||||
remote := freshCrashRemote(t, filepath.Join(root, "remote.json"))
|
||||
p := mappedProviderV3(t, root, remote)
|
||||
if os.Getenv("SWBLOCK_V3_FRESH_CRASH_MODE") == "capture" {
|
||||
p.cfg.ChunkCaptureInterval = time.Hour
|
||||
}
|
||||
st, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ws := st.(*storage.WALStore)
|
||||
if _, err = ws.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var h storage.InstallHandle
|
||||
install := func() {
|
||||
var id [16]byte
|
||||
id[0] = 23
|
||||
h, err = storage.BeginInstall(ws, 7, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := bytes.Repeat([]byte{0x78}, 4096)
|
||||
if err = h.WriteBase(5, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = h.WriteBase(9, make([]byte, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = h.ApplyInstallEntry(5, data, 8); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = h.MarkBaseComplete(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = ws.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = storage.FlushMappedWALStoreV3Test(ws); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
mode = os.Getenv("SWBLOCK_V3_FRESH_CRASH_MODE")
|
||||
if mode != "complete" {
|
||||
install()
|
||||
}
|
||||
p.testBeforeChunkFreshRetire = func() error {
|
||||
if mode == "complete" {
|
||||
install()
|
||||
}
|
||||
if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := h.ApplyInstallEntry(5, bytes.Repeat([]byte{0x79}, 4096), 9); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ws.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mode == "capture" {
|
||||
before, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
beforeBytes, err := json.Marshal(before)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
puts := remote.Puts()
|
||||
if _, err := p.CaptureVolume(ctx, "v1"); !errors.Is(err, ErrNotChunkVolume) {
|
||||
t.Fatal("precommit CaptureVolume published before durable owner commit")
|
||||
}
|
||||
if _, err := p.CutVolume(ctx, "v1", 9); !errors.Is(err, ErrNotChunkVolume) {
|
||||
t.Fatal("precommit CutVolume was admitted")
|
||||
}
|
||||
if err := p.MakeVolumeRemoteDurable(ctx, "v1", 9); !errors.Is(err, ErrNotChunkVolume) {
|
||||
t.Fatal("precommit MakeVolumeRemoteDurable was admitted")
|
||||
}
|
||||
after, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
afterBytes, err := json.Marshal(after)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
intents, err := remote.ListIntents(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(beforeBytes, afterBytes) || remote.Puts() != puts || len(intents) != 0 {
|
||||
t.Fatal("refused precommit publication changed remote state")
|
||||
}
|
||||
p.mu.Lock()
|
||||
handle := p.volumes["v1"]
|
||||
exposed := handle.chunk != nil || handle.chunkStop != nil || handle.chunkDone != nil
|
||||
p.mu.Unlock()
|
||||
if exposed {
|
||||
t.Fatal("precommit layer or scheduler was exposed")
|
||||
}
|
||||
fmt.Println("FRESH_CAPTURE_REFUSED no_remote_effect=true scheduler_hidden=true")
|
||||
}
|
||||
fmt.Println("FRESH_CRASH_READY presence_saved=true marker_present=true ack=9 no_Close=true")
|
||||
os.Exit(0)
|
||||
return nil
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Fatal("crash boundary not reached")
|
||||
}
|
||||
root := t.TempDir()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
source := mappedProviderV3(t, t.TempDir(), remote)
|
||||
if _, err := source.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := source.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, lba := range []int64{5, 9} {
|
||||
if n, err := source.Backend("v1").Write(ctx, lba*4096, bytes.Repeat([]byte{0x11}, 4096)); err != nil || n != 4096 {
|
||||
t.Fatal(n, err)
|
||||
}
|
||||
}
|
||||
if err := source.Backend("v1").Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := source.CaptureVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := source.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
img := freshCrashImage{Head: head, Objects: map[string][]byte{}}
|
||||
for _, ref := range head.Chunks {
|
||||
data, e := remote.Get(ctx, ref.Key)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
img.Objects[ref.Key] = data
|
||||
}
|
||||
raw, err := json.Marshal(img)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.WriteFile(filepath.Join(root, "remote.json"), raw, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE$", "-test.v")
|
||||
cmd.WaitDelay = 2 * time.Second
|
||||
cmd.Env = append(os.Environ(), "SWBLOCK_V3_FRESH_CRASH_ROOT="+root, "SWBLOCK_V3_FRESH_CRASH_MODE="+mode)
|
||||
out, err := cmd.CombinedOutput()
|
||||
t.Logf("%s", out)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Contains(out, []byte("FRESH_CRASH_READY presence_saved=true marker_present=true ack=9 no_Close=true")) {
|
||||
t.Fatal("child missed crash boundary")
|
||||
}
|
||||
p := mappedProviderV3(t, root, freshCrashRemote(t, filepath.Join(root, "remote.json")))
|
||||
if _, err = os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil {
|
||||
t.Fatal("crash marker missing", err)
|
||||
}
|
||||
if _, err = p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatalf("post-presence/pre-marker crash lost completed BASE recovery: %v", err)
|
||||
}
|
||||
for lba, want := range map[int64][]byte{5: bytes.Repeat([]byte{0x79}, 4096), 9: make([]byte, 4096)} {
|
||||
got := make([]byte, 4096)
|
||||
if n, err := p.Backend("v1").Read(ctx, lba*4096, got); err != nil || n != 4096 || !bytes.Equal(got, want) {
|
||||
t.Fatalf("crash BASE bytes lba=%d n=%d err=%v equal=%v", lba, n, err, bytes.Equal(got, want))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A failed owner commit keeps the layer private without leaking or trying
|
||||
// to attach it twice. Success publishes it and starts its scheduler once.
|
||||
func TestDurableProviderV3_AttachCommitRetryKeepsLayerPrivate(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p := mappedProviderV3(t, t.TempDir(), remote)
|
||||
p.cfg.ChunkCaptureInterval = time.Hour
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
injected := errors.New("hold durable owner commit")
|
||||
p.testBeforeChunkFreshRetire = func() error { return injected }
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, injected) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.mu.Lock()
|
||||
h := p.volumes["v1"]
|
||||
pending := h.chunkPending
|
||||
exposed := h.chunk != nil || h.chunkStop != nil || h.chunkDone != nil
|
||||
p.mu.Unlock()
|
||||
if pending == nil || exposed {
|
||||
t.Fatal("failed commit exposed or lost pending layer")
|
||||
}
|
||||
if _, err := p.CaptureVolume(ctx, "v1"); !errors.Is(err, ErrNotChunkVolume) {
|
||||
t.Fatal("failed commit capture", err)
|
||||
}
|
||||
if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.testBeforeChunkFreshRetire = nil
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal("commit retry", err)
|
||||
}
|
||||
p.mu.Lock()
|
||||
correct := h.chunk == pending && h.chunkPending == nil && h.chunkStop != nil && h.chunkDone != nil
|
||||
p.mu.Unlock()
|
||||
if !correct {
|
||||
t.Fatal("commit did not publish the same pending layer and scheduler")
|
||||
}
|
||||
if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); !os.IsNotExist(err) {
|
||||
t.Fatal("committed marker remains", err)
|
||||
}
|
||||
if _, err := p.CaptureVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal("postcommit capture", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
//go:build swblock_format_v3_test
|
||||
|
||||
package durable
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type formatV3View struct{}
|
||||
|
||||
func (formatV3View) Projection() frontend.Projection {
|
||||
return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true}
|
||||
}
|
||||
|
||||
func mappedProviderV3(t *testing.T, root string, remote storage.ChunkRemote) *DurableProvider {
|
||||
t.Helper()
|
||||
p, err := NewDurableProvider(ProviderConfig{
|
||||
Impl: ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4,
|
||||
WALRecoveryTestDisableFlusher: true,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
}, formatV3View{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
// Activation closure: use the production selector and provider geometry.
|
||||
return p
|
||||
}
|
||||
|
||||
func TestDurableProviderV3_MappedCheckpointCaptureAndReopen(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
root := t.TempDir()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p := mappedProviderV3(t, root, remote)
|
||||
st, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b := p.Backend("v1")
|
||||
data := bytes.Repeat([]byte{0x57}, 4096)
|
||||
if n, err := b.Write(ctx, 5*4096, data); err != nil || n != len(data) {
|
||||
t.Fatalf("Write: %d %v", n, err)
|
||||
}
|
||||
if err = b.Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = storage.FlushMappedWALStoreV3Test(st.(*storage.WALStore)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.CaptureVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check := func(want []byte) {
|
||||
t.Helper()
|
||||
head, e := remote.GetHead(ctx)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ref, ok := head.Chunks[1]
|
||||
if !ok {
|
||||
t.Fatal("capture omitted checkpointed chunk")
|
||||
}
|
||||
chunk, e := remote.Get(ctx, ref.Key)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if !bytes.Equal(chunk[4096:8192], want) {
|
||||
t.Fatal("published chunk bytes differ")
|
||||
}
|
||||
}
|
||||
check(data)
|
||||
raw, err := os.ReadFile(p.volumePath("v1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if binary.LittleEndian.Uint32(raw[12:16]) != 3 {
|
||||
t.Fatal("provider did not open impl3")
|
||||
}
|
||||
if _, err = os.Stat(p.volumePath("v1") + ".chunkbitmap"); !os.IsNotExist(err) {
|
||||
t.Fatalf("legacy bitmap exists: %v", err)
|
||||
}
|
||||
if err = p.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p2 := mappedProviderV3(t, root, remote)
|
||||
st2, err := p2.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p2.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b2 := p2.Backend("v1")
|
||||
got := make([]byte, 4096)
|
||||
if n, err := b2.Read(ctx, 5*4096, got); err != nil || n != len(got) || !bytes.Equal(got, data) {
|
||||
t.Fatalf("reopen read %d %v equal=%v", n, err, bytes.Equal(got, data))
|
||||
}
|
||||
next := bytes.Repeat([]byte{0x93}, 4096)
|
||||
if _, err = b2.Write(ctx, 5*4096, next); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = b2.Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = storage.FlushMappedWALStoreV3Test(st2.(*storage.WALStore)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := remote.Puts()
|
||||
if _, err = p2.CaptureVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if remote.Puts()-before != 1 {
|
||||
t.Fatalf("incremental capture uploaded %d chunks", remote.Puts()-before)
|
||||
}
|
||||
check(next)
|
||||
}
|
||||
|
||||
// The selector must not turn a missing owned map into a legacy bitmap path.
|
||||
func TestDurableProviderV3_MissingMapRefusesBeforeBackend(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
root := t.TempDir()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p := mappedProviderV3(t, root, remote)
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := p.volumePath("v1")
|
||||
if err := p.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Remove(path + ".chunkmap"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p2 := mappedProviderV3(t, root, remote)
|
||||
if st, err := p2.EnsureStorage("v1"); err == nil || st != nil {
|
||||
t.Fatalf("accepted missing map: store=%v err=%v", st, err)
|
||||
}
|
||||
if p2.Backend("v1") != nil {
|
||||
t.Fatal("failed open cached a backend")
|
||||
}
|
||||
if _, err := os.Stat(path + ".chunkbitmap"); !os.IsNotExist(err) {
|
||||
t.Fatalf("legacy fallback created a bitmap: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurableProviderV3_DefaultSelectorCreatesV3(t *testing.T) {
|
||||
p, err := NewDurableProvider(ProviderConfig{Impl: ImplWALStore, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096}, formatV3View{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
if _, err = p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := os.Open(p.volumePath("v1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
var hdr [16]byte
|
||||
if _, err = f.ReadAt(hdr[:], 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if binary.LittleEndian.Uint16(hdr[4:6]) != 3 || binary.LittleEndian.Uint32(hdr[12:16]) != 3 {
|
||||
t.Fatal("default provider did not select v3/impl3")
|
||||
}
|
||||
}
|
||||
|
||||
// An invalid inherited frontier must fail preparation without claiming HEAD.
|
||||
func TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 2, Holder: "old", RemoteLSN: ^uint64(0)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := mappedProviderV3(t, t.TempDir(), remote)
|
||||
if _, err = p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(p.volumePath("v1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v1"); err == nil {
|
||||
t.Fatal("invalid HEAD frontier accepted")
|
||||
}
|
||||
after, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.Gen != before.Gen || after.Epoch != before.Epoch || after.Holder != before.Holder {
|
||||
t.Fatal("failed seed claimed HEAD")
|
||||
}
|
||||
now, err := os.ReadFile(p.volumePath("v1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Recover may publish the serving scan's descriptor. It must never serialize
|
||||
// a legacy header or advance the inherited logical frontier.
|
||||
if binary.LittleEndian.Uint16(now[4:6]) != 3 || binary.LittleEndian.Uint16(raw[4:6]) != 3 {
|
||||
t.Fatal("restore serialized a legacy header")
|
||||
}
|
||||
var buf [4096]byte
|
||||
if _, err := p.Backend("v1").Read(ctx, 0, buf[:]); err == nil {
|
||||
t.Fatal("failed restore left backend operational")
|
||||
}
|
||||
}
|
||||
|
||||
// This exercises the row7 caller seam without enabling production v3. The
|
||||
// owner seed/install transaction must make this pass before restore is claimed.
|
||||
type formatV3TakeoverView struct{}
|
||||
|
||||
func (formatV3TakeoverView) Projection() frontend.Projection {
|
||||
return frontend.Projection{VolumeID: "v1", ReplicaID: "r2", Epoch: 4, EndpointVersion: 1, Healthy: true}
|
||||
}
|
||||
|
||||
type formatV3RestoreRemote struct {
|
||||
storage.ChunkRemote
|
||||
beforeClaim func() error
|
||||
loseClaimResponse bool
|
||||
}
|
||||
|
||||
func (r *formatV3RestoreRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) {
|
||||
if expected.Epoch == 3 {
|
||||
if err := r.beforeClaim(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
gen, err := r.ChunkRemote.CASHead(ctx, expected, next)
|
||||
if err == nil && expected.Epoch == 3 && r.loseClaimResponse {
|
||||
return 0, errors.New("claim response lost after commit")
|
||||
}
|
||||
return gen, err
|
||||
}
|
||||
func TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN(t *testing.T) {
|
||||
exerciseMappedHEADRestoreV3(t, false)
|
||||
}
|
||||
func TestDurableProviderV3_HEADRestoreAfterLostClaimResponse(t *testing.T) {
|
||||
exerciseMappedHEADRestoreV3(t, true)
|
||||
}
|
||||
func exerciseMappedHEADRestoreV3(t *testing.T, loseClaimResponse bool) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
source := mappedProviderV3(t, t.TempDir(), remote)
|
||||
st, err := source.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = source.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, second := bytes.Repeat([]byte{0x51}, 4096), bytes.Repeat([]byte{0xC2}, 4096)
|
||||
for lba, data := range map[int64][]byte{5: first, 12: second} {
|
||||
if _, err = source.Backend("v1").Write(ctx, lba*4096, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err = source.Backend("v1").Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = storage.FlushMappedWALStoreV3Test(st.(*storage.WALStore)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h, err := source.CaptureVolume(ctx, "v1"); err != nil || h != 2 {
|
||||
t.Fatalf("source capture H=%d err=%v", h, err)
|
||||
}
|
||||
if err = source.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := t.TempDir()
|
||||
probe := &formatV3RestoreRemote{ChunkRemote: remote, loseClaimResponse: loseClaimResponse}
|
||||
target := mappedProviderV3(t, root, probe)
|
||||
target.view = formatV3TakeoverView{}
|
||||
restored, err := target.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
probe.beforeClaim = func() error {
|
||||
if restored.NextLSN() != 3 {
|
||||
return errors.New("HEAD takeover attempted before durable seed/rebase")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, err = target.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatalf("actual mapped HEAD restore refused: %v", err)
|
||||
}
|
||||
if restored.NextLSN() != 3 {
|
||||
t.Fatalf("restored nextLSN=%d want3", restored.NextLSN())
|
||||
}
|
||||
head, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if head.RemoteLSN != 2 || head.Epoch != 4 || head.Holder != "r2" {
|
||||
t.Fatalf("takeover changed image/frontier: %+v", head)
|
||||
}
|
||||
before := remote.Puts()
|
||||
check := func(p *DurableProvider, lba int64, want []byte) {
|
||||
t.Helper()
|
||||
got := make([]byte, 4096)
|
||||
if n, e := p.Backend("v1").Read(ctx, lba*4096, got); e != nil || n != len(got) || !bytes.Equal(got, want) {
|
||||
t.Fatalf("LBA%d n=%d err=%v equal=%v", lba, n, e, bytes.Equal(got, want))
|
||||
}
|
||||
}
|
||||
check(target, 5, first)
|
||||
check(target, 12, second)
|
||||
check(target, 0, make([]byte, 4096))
|
||||
if remote.Puts() != before {
|
||||
t.Fatal("lazy read uploaded remote chunks")
|
||||
}
|
||||
next := bytes.Repeat([]byte{0x83}, 4096)
|
||||
if _, err = target.Backend("v1").Write(ctx, 5*4096, next); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if restored.NextLSN() != 4 {
|
||||
t.Fatalf("restored write reused inherited LSN: next=%d", restored.NextLSN())
|
||||
}
|
||||
if err = target.Backend("v1").Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = storage.FlushMappedWALStoreV3Test(restored.(*storage.WALStore)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h, err := target.CaptureVolume(ctx, "v1"); err != nil || h != 3 {
|
||||
t.Fatalf("restored capture H=%d err=%v", h, err)
|
||||
}
|
||||
if _, err = os.Stat(target.volumePath("v1") + ".chunkbitmap"); !os.IsNotExist(err) {
|
||||
t.Fatalf("restore used legacy bitmap: %v", err)
|
||||
}
|
||||
if err = target.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened := mappedProviderV3(t, root, remote)
|
||||
reopened.view = formatV3TakeoverView{}
|
||||
if _, err = reopened.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = reopened.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(reopened, 5, next)
|
||||
check(reopened, 12, second)
|
||||
}
|
||||
|
||||
// Exercise the same snapshots consumed by the host status endpoint, not a
|
||||
// separately constructed status object.
|
||||
func TestDurableProviderV3_StatusTracksRecoverSyncAndCapture(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
p := mappedProviderV3(t, t.TempDir(), storage.NewMemChunkRemote())
|
||||
st, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
status := func() VolumeStatus {
|
||||
t.Helper()
|
||||
all := p.DurableStatuses()
|
||||
if len(all) != 1 {
|
||||
t.Fatalf("statuses=%+v", all)
|
||||
}
|
||||
v := all[0]
|
||||
if v.VolumeID != "v1" || v.ReplicaID != "r1" || v.Epoch != 3 || !v.Latched || !v.FrontierKnown {
|
||||
t.Fatalf("lineage/frontier=%+v", v)
|
||||
}
|
||||
return v
|
||||
}
|
||||
if v := status(); v.Operational || v.Chunk == nil || v.Chunk.Attached {
|
||||
t.Fatalf("before recover=%+v", v)
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v := status(); !v.Operational || v.Chunk == nil || !v.Chunk.Attached || v.Chunk.Fenced {
|
||||
t.Fatalf("after recover=%+v", v)
|
||||
}
|
||||
if n, e := p.Backend("v1").Write(ctx, 5*4096, bytes.Repeat([]byte{0x77}, 4096)); e != nil || n != 4096 {
|
||||
t.Fatal(n, e)
|
||||
}
|
||||
if err = p.Backend("v1").Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v := status(); v.DurableLSN != 1 || v.HeadLSN != 1 || v.Chunk.RemoteLSN != 0 {
|
||||
t.Fatalf("after Sync=%+v", v)
|
||||
}
|
||||
if err = storage.FlushMappedWALStoreV3Test(st.(*storage.WALStore)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.CaptureVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v := status(); v.DurableLSN != 1 || v.Chunk.RemoteLSN != 1 || !v.Operational {
|
||||
t.Fatalf("after capture=%+v", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurableProviderV3_ContiguousWriteSurvivesCheckpointAndReopen(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
root := t.TempDir()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p := mappedProviderV3(t, root, remote)
|
||||
st, e := p.EnsureStorage("v1")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.RecoverVolume(ctx, "v1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
want := append(bytes.Repeat([]byte{0x31}, 4096), bytes.Repeat([]byte{0x72}, 4096)...)
|
||||
if n, e := p.Backend("v1").Write(ctx, 4*4096, want); e != nil || n != len(want) {
|
||||
t.Fatalf("actual provider contiguous Write: n=%d err=%v", n, e)
|
||||
}
|
||||
if e = p.Backend("v1").Sync(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = storage.FlushMappedWALStoreV3Test(st.(*storage.WALStore)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.CaptureVolume(ctx, "v1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = p.Close(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
q := mappedProviderV3(t, root, remote)
|
||||
if _, e = q.EnsureStorage("v1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = q.RecoverVolume(ctx, "v1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got := make([]byte, len(want))
|
||||
if n, e := q.Backend("v1").Read(ctx, 4*4096, got); e != nil || n != len(want) || !bytes.Equal(got, want) {
|
||||
t.Fatalf("reopen n=%d err=%v equal=%v", n, e, bytes.Equal(got, want))
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
@@ -47,7 +46,7 @@ func failSeedFD(t *testing.T, root string) func() {
|
||||
fd := -1
|
||||
for _, e := range entries {
|
||||
name, err := os.Readlink("/proc/self/fd/" + e.Name())
|
||||
if err == nil && strings.HasPrefix(name, root+string(os.PathSeparator)) {
|
||||
if err == nil && name == filepath.Join(root, "v1.bin") {
|
||||
if fd != -1 {
|
||||
t.Fatal("more than one fixture WAL descriptor")
|
||||
}
|
||||
|
||||
@@ -71,8 +71,8 @@ func TestPhase150_DurableProviderWALMultiBlockOptIn(t *testing.T) {
|
||||
|
||||
single := run(t, false)
|
||||
multi := run(t, true)
|
||||
if single != 16 {
|
||||
t.Fatalf("single encode ops=%d want 16", single)
|
||||
if single != 4 {
|
||||
t.Fatalf("native v3 batch encode ops=%d want 4 regardless of legacy option", single)
|
||||
}
|
||||
if multi != 4 {
|
||||
t.Fatalf("multi encode ops=%d want 4", multi)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 446 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user