mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
T3b: DurableProvider + Recovery + iSCSI SYNC_CACHE + NVMe Flush + cmd wire
Atomic per T3b mini plan §3 stop rule #1 — all 5 deliverables one commit.
## Scope delivered (mini plan §0)
### 1. DurableProvider (G-int.4)
New core/frontend/durable/provider.go:
- `ImplName` ("smartwal" | "walstore"); production default smartwal
per PM direction
- `ProviderConfig` with StorageRoot + Impl + geometry + OpenTimeout
- `NewDurableProvider` validates selector; mkdir storage root
- `Open(ctx, volumeID)` caches handle per volumeID; opens existing
file (verifying magic vs selector) or creates fresh
- `RecoverVolume(ctx, volumeID)` runs LogicalStorage.Recover on
the cached storage, flips backend operational bit per report
- `Close()` tears down in correct order (backend close → storage
close); idempotent
- ImplKind mismatch detection: peeks 4-byte magic BEFORE storage
Open so the error message names selector vs on-disk kind
(ErrImplKindMismatch). Never silently coerces (Addendum A #2).
- testback.StaticProvider unchanged (audit §11 G-int.4).
### 2. Recovery wrapper (G-int.5)
New core/frontend/durable/recovery.go:
- Pure function `Recover(storage, volumeID) RecoveryReport`
- Report carries VolumeID, RecoveredLSN, Evidence string, Err
- Zero side-effects on backend — Provider (or cmd) flips
SetOperational based on report
- Option 3 from audit §10.5 honored: no local epoch mirror;
per-I/O adapter fence check remains sole authority-drift guard
- §3.2 boundary: no new publication path; readiness surfaces
via existing /status + adapter's SetOperational
### 3. iSCSI SYNC_CACHE wire
core/frontend/iscsi/scsi.go:
- SYNCHRONIZE_CACHE(10) [0x35] + SYNCHRONIZE_CACHE(16) [0x91]
dispatch to backend.Sync(ctx) (formerly no-op Good)
- Sync errors map to CHECK CONDITION / MEDIUM_ERROR /
WRITE_ERROR (SPC-5 §D.2.14). Stop rule §3.6 (error-faithful
Sync wire): swallowing to Good is forbidden.
core/frontend/iscsi/errors.go:
- Added `ASCWriteError = 0x0C` (SPC-5 ASC table)
### 4. NVMe Flush wire
core/frontend/nvme/io.go + session.go:
- `ioFlush` opcode (0x00) handler dispatches to backend.Sync via
IOHandler.Handle
- Session dispatchIO routes Flush through the handler (was:
direct Success enqueue)
- Sync errors map via mapBackendError; ErrStalePrimary → ANA
Transition, generic → Internal Error
### 5. cmd/blockvolume wire
Added flags:
- --durable-root PATH enables DurableProvider; empty = memback
- --durable-impl NAME "smartwal" (default) | "walstore"
- --durable-blocks N first-create geometry
- --durable-blocksize N first-create block size
Startup sequence (when --durable-root is set):
1. Build DurableProvider
2. Open the served volumeID (creates storage if absent)
3. RecoverVolume → flips adapter operational bit per outcome
4. Use the provider for both iSCSI and NVMe target wiring
5. On shutdown, Close the provider (backend + storage) in order
memback path unchanged when --durable-root is empty.
### 6. Adapter lifecycle design note
Backend.Close() does NOT tear down underlying LogicalStorage
(already was the T3a contract). Provider.Close() is the only
teardown path for storage; both are idempotent.
## Acceptance (mini plan §2)
#1 `TestT3b_DurableProvider_ImplementsProvider` ✅ both impls
#2 `TestT3b_DurableProvider_Open_SelectsImpl_Matrix` ✅ (file magic verified on disk)
#3 `TestT3b_DurableProvider_Open_StartsNotOperational` ✅ Read/Write/Sync → ErrNotReady
#4 `TestT3b_DurableProvider_Open_ImplKindMismatch_FailsFast` ✅ ErrImplKindMismatch named
#5 `TestT3b_Recovery_CleanRecover_FlipsOperational` ✅ + `*UnopenedVolume*` + pure-fn tests
#6 `TestT3b_ISCSI_SyncCache_DispatchesToBackend` ✅ SYNC_CACHE(10) + (16)
#7 `TestT3b_NVMe_Flush_DispatchesToBackend` ✅ ioFlush → backend.Sync
#8 `TestT3b_DurableProvider_Lifecycle_*` ✅ close isolation + double-close idempotent
#9 Full regression ✅ 17/17 core packages ok
#10 Boundary guard ✅ core/frontend/durable/ auto-covered
## Regression
go test ./core/... -count=1 → 17/17 packages ok
- core/frontend/durable: 0.5s (16 T3a + 13 T3b subtests all green)
- core/frontend/iscsi: 31.5s
- core/frontend/nvme: 61.3s
- core/host: 122.8s (no regression)
- all others sub-second or unchanged
## Stop rules honored
#1 atomic (5 deliverables one commit) ✅
#2 no OnDegraded reinstated ✅
#3 no local epoch mirror ✅
#4 no new publication path ✅
#5 Provider.Impl is config-driven string; no compile branch ✅
#6 iSCSI + NVMe Sync errors map faithfully ✅
#7 no scenarios / no perf landed in T3b ✅
## Ledger rows queued ACTIVE at T3b close
- INV-DURABLE-PROVIDER-SELECT-001
- INV-DURABLE-RECOVERY-READSIDE-001
- INV-DURABLE-SYNC-WIRED-001
Existing (T3a / T1) rows stay ACTIVE:
- INV-DURABLE-OPGATE-001, INV-DURABLE-IMPL-IDENTITY-001
- INV-FRONTEND-002.{EPOCH,EV,REPLICA,HEALTHY}
## Out of T3b (per mini plan)
- 4 G6 scenarios → T3c
- m01 iSCSI + NVMe fs-workload smoke → T3c
- Perf baseline → T3c
- T3 closure report + T3-end three-sign → T3c
## References
sw-block/design/v3-phase-15-t3a-mini-plan.md (CLOSED 10cd117)
sw-block/design/v3-phase-15-t3b-mini-plan.md (this batch)
feedback_porting_discipline.md (port-model discipline)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
10cd117bb4
commit
29e3d0de0c
11 files changed
+1012
-9
No files matched your search
@@ -16,6 +16,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/memback"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
@@ -59,6 +61,16 @@ type flags struct {
|
||||
nvmeListen string
|
||||
nvmeSubsysNQN string
|
||||
nvmeNS uint
|
||||
|
||||
// T3b durable-backend flags. When --durable-root is set, the
|
||||
// iSCSI and NVMe providers use DurableProvider instead of
|
||||
// memback. --durable-impl selects walstore or smartwal
|
||||
// (default smartwal per PM direction). --durable-blocks +
|
||||
// --durable-blocksize are used on first-time storage create.
|
||||
durableRoot string
|
||||
durableImpl string // "smartwal" | "walstore"
|
||||
durableBlocks uint
|
||||
durableBlockSize uint
|
||||
}
|
||||
|
||||
func parseFlags(args []string) (flags, error) {
|
||||
@@ -80,6 +92,10 @@ func parseFlags(args []string) (flags, error) {
|
||||
fs.StringVar(&f.nvmeListen, "nvme-listen", "", "NVMe/TCP target bind address (e.g. 127.0.0.1:0); empty disables. Loopback-only in T2 scope (no auth)")
|
||||
fs.StringVar(&f.nvmeSubsysNQN, "nvme-subsysnqn", "", "NVMe subsystem NQN (required if --nvme-listen is set)")
|
||||
fs.UintVar(&f.nvmeNS, "nvme-ns", 1, "NVMe namespace id (default 1)")
|
||||
fs.StringVar(&f.durableRoot, "durable-root", "", "directory for persistent storage files; empty = memback (non-durable)")
|
||||
fs.StringVar(&f.durableImpl, "durable-impl", "smartwal", "LogicalStorage impl: smartwal (default) or walstore; ignored unless --durable-root is set")
|
||||
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")
|
||||
fs.SetOutput(os.Stderr)
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return flags{}, err
|
||||
@@ -251,12 +267,71 @@ func run(f flags) int {
|
||||
}()
|
||||
}
|
||||
|
||||
var iscsiTarget *iscsi.Target
|
||||
if f.iscsiListen != "" {
|
||||
// memback provider wraps the volume's AdapterProjectionView
|
||||
// T3b: pick Provider per --durable-root flag. When the flag is
|
||||
// unset, fall back to memback (non-durable, legacy behavior).
|
||||
// When set, DurableProvider opens (or creates) on-disk storage
|
||||
// per --durable-impl and runs Recovery before the frontends
|
||||
// accept connections.
|
||||
var provider frontend.Provider
|
||||
var durableProv *durable.DurableProvider
|
||||
if f.durableRoot != "" {
|
||||
cfg := durable.ProviderConfig{
|
||||
Impl: durable.ImplName(f.durableImpl),
|
||||
StorageRoot: f.durableRoot,
|
||||
BlockSize: int(f.durableBlockSize),
|
||||
NumBlocks: uint32(f.durableBlocks),
|
||||
}
|
||||
dp, err := durable.NewDurableProvider(cfg, h.ProjectionView())
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: durable provider:", err)
|
||||
if status != nil {
|
||||
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
_ = status.Close(shutCtx)
|
||||
shutCancel()
|
||||
}
|
||||
_ = h.Close()
|
||||
return 1
|
||||
}
|
||||
durableProv = dp
|
||||
provider = dp
|
||||
// Eagerly open + recover the served volume so the
|
||||
// frontend-side Open returns an operational=true backend.
|
||||
// Opens the underlying storage + runs LogicalStorage.Recover;
|
||||
// on error we surface to stderr + /status but don't panic.
|
||||
openCtx, openCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
if _, err := dp.Open(openCtx, f.volumeID); err != nil {
|
||||
openCancel()
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: durable open:", err)
|
||||
_ = dp.Close()
|
||||
if status != nil {
|
||||
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
_ = status.Close(shutCtx)
|
||||
shutCancel()
|
||||
}
|
||||
_ = h.Close()
|
||||
return 1
|
||||
}
|
||||
report, err := dp.RecoverVolume(openCtx, f.volumeID)
|
||||
openCancel()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: durable recovery failed:", report.Evidence)
|
||||
// Keep running so /status can surface NotReady — the
|
||||
// adapter is already flipped to non-operational with
|
||||
// evidence; frontends will reject I/O per INV-DURABLE-
|
||||
// OPGATE-001 read-side path.
|
||||
} else {
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: durable recovered:", report.Evidence)
|
||||
}
|
||||
} else {
|
||||
// memback fallback — wraps the volume's AdapterProjectionView
|
||||
// so per-op lineage fence + supersede fence still apply at
|
||||
// SCSI command granularity.
|
||||
prov := memback.NewProvider(h.ProjectionView())
|
||||
provider = memback.NewProvider(h.ProjectionView())
|
||||
}
|
||||
|
||||
var iscsiTarget *iscsi.Target
|
||||
if f.iscsiListen != "" {
|
||||
prov := provider
|
||||
iscsiTarget = iscsi.NewTarget(iscsi.TargetConfig{
|
||||
Listen: f.iscsiListen,
|
||||
IQN: f.iscsiIQN,
|
||||
@@ -284,7 +359,7 @@ func run(f flags) int {
|
||||
|
||||
var nvmeTarget *nvme.Target
|
||||
if f.nvmeListen != "" {
|
||||
prov := memback.NewProvider(h.ProjectionView())
|
||||
prov := provider
|
||||
nvmeTarget = nvme.NewTarget(nvme.TargetConfig{
|
||||
Listen: f.nvmeListen,
|
||||
SubsysNQN: f.nvmeSubsysNQN,
|
||||
@@ -324,6 +399,12 @@ func run(f flags) int {
|
||||
if iscsiTarget != nil {
|
||||
_ = iscsiTarget.Close()
|
||||
}
|
||||
// T3b: close DurableProvider in correct order — Provider.Close
|
||||
// closes backends first (flags them closed) then storage files
|
||||
// (releases fd + final fsync).
|
||||
if durableProv != nil {
|
||||
_ = durableProv.Close()
|
||||
}
|
||||
if status != nil {
|
||||
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
_ = status.Close(shutCtx)
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
package durable
|
||||
|
||||
// Package durable G-int.4 — DurableProvider.
|
||||
//
|
||||
// DurableProvider implements frontend.Provider for production
|
||||
// `cmd/blockvolume`. On Open it:
|
||||
// 1. Builds the on-disk path per config for the volumeID
|
||||
// 2. If the file exists, verifies on-disk magic matches the
|
||||
// configured selector (ImplKind mismatch → ErrImplKindMismatch;
|
||||
// fail-fast, never silently coerce)
|
||||
// 3. Opens (or creates) the LogicalStorage
|
||||
// 4. Returns a StorageBackend with operational=FALSE
|
||||
//
|
||||
// Operational=true is not flipped by Open. The caller (cmd/
|
||||
// blockvolume) calls RecoverVolume after Open; RecoverVolume runs
|
||||
// LogicalStorage.Recover and flips the backend operational bit
|
||||
// based on the outcome. This keeps Recovery readiness a distinct
|
||||
// step (INV-DURABLE-OPGATE-001) rather than a side-effect of Open.
|
||||
//
|
||||
// Per-volume handles are cached: multiple Open calls for the same
|
||||
// volumeID return the same StorageBackend, sharing LogicalStorage
|
||||
// state. This matches memback's per-Identity cache pattern — every
|
||||
// session opened against the same volume sees the same bytes.
|
||||
//
|
||||
// testback.StaticProvider remains unchanged (audit §11 G-int.4).
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage/smartwal"
|
||||
)
|
||||
|
||||
// ImplName is the user-facing selector for the LogicalStorage
|
||||
// implementation. Config sets one of these; Provider picks the
|
||||
// matching open/create functions.
|
||||
type ImplName string
|
||||
|
||||
const (
|
||||
ImplSmartWAL ImplName = "smartwal" // production default per PM direction
|
||||
ImplWALStore ImplName = "walstore"
|
||||
)
|
||||
|
||||
// ErrImplKindMismatch is returned by Open when the configured
|
||||
// selector does not match the on-disk superblock magic. Named so
|
||||
// tests can errors.Is on it.
|
||||
var ErrImplKindMismatch = errors.New("durable: impl kind mismatch between selector and on-disk superblock")
|
||||
|
||||
// ErrVolumeNotOpen is returned by RecoverVolume / Close when the
|
||||
// volumeID has not been Open'd.
|
||||
var ErrVolumeNotOpen = errors.New("durable: volume not opened")
|
||||
|
||||
// ProviderConfig configures a DurableProvider.
|
||||
type ProviderConfig struct {
|
||||
// Impl selects which LogicalStorage implementation to open or
|
||||
// create. Zero value (""): ImplSmartWAL (production default).
|
||||
Impl ImplName
|
||||
|
||||
// StorageRoot is the directory under which per-volume files
|
||||
// live. Required.
|
||||
StorageRoot string
|
||||
|
||||
// BlockSize / NumBlocks are used ONLY on create (file doesn't
|
||||
// exist yet). Zero values: BlockSize=4096; NumBlocks must be
|
||||
// non-zero on first Open, zero means "open existing only".
|
||||
BlockSize int
|
||||
NumBlocks uint32
|
||||
|
||||
// OpenTimeout caps how long Open waits for the projection to
|
||||
// report healthy for the requested volumeID. Zero → default 5s.
|
||||
OpenTimeout time.Duration
|
||||
}
|
||||
|
||||
// DurableProvider is the production frontend.Provider implementation.
|
||||
type DurableProvider struct {
|
||||
cfg ProviderConfig
|
||||
view frontend.ProjectionView
|
||||
|
||||
mu sync.Mutex
|
||||
volumes map[string]*volHandle // keyed by volumeID
|
||||
closed bool
|
||||
}
|
||||
|
||||
type volHandle struct {
|
||||
storage storage.LogicalStorage
|
||||
backend *StorageBackend
|
||||
path string
|
||||
}
|
||||
|
||||
// NewDurableProvider constructs a provider. view is the ONLY
|
||||
// source of authority lineage the provider is allowed to consult
|
||||
// (sketch §9 boundary).
|
||||
func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*DurableProvider, error) {
|
||||
if cfg.StorageRoot == "" {
|
||||
return nil, fmt.Errorf("durable: ProviderConfig.StorageRoot required")
|
||||
}
|
||||
if cfg.Impl == "" {
|
||||
cfg.Impl = ImplSmartWAL
|
||||
}
|
||||
if cfg.Impl != ImplSmartWAL && cfg.Impl != ImplWALStore {
|
||||
return nil, fmt.Errorf("durable: unknown impl %q (want %q or %q)",
|
||||
cfg.Impl, ImplSmartWAL, ImplWALStore)
|
||||
}
|
||||
if cfg.BlockSize == 0 {
|
||||
cfg.BlockSize = 4096
|
||||
}
|
||||
if cfg.OpenTimeout == 0 {
|
||||
cfg.OpenTimeout = 5 * time.Second
|
||||
}
|
||||
if err := os.MkdirAll(cfg.StorageRoot, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("durable: mkdir %s: %w", cfg.StorageRoot, err)
|
||||
}
|
||||
return &DurableProvider{
|
||||
cfg: cfg,
|
||||
view: view,
|
||||
volumes: map[string]*volHandle{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// volumePath returns the on-disk path for a volumeID. Volume IDs
|
||||
// are used as filenames; callers are responsible for passing
|
||||
// filesystem-safe strings (the master/adapter layer already does).
|
||||
func (p *DurableProvider) volumePath(volumeID string) string {
|
||||
return filepath.Join(p.cfg.StorageRoot, volumeID+".bin")
|
||||
}
|
||||
|
||||
// Open implements frontend.Provider. Returns the cached backend
|
||||
// for volumeID if already opened; otherwise opens (or creates)
|
||||
// storage and caches the handle.
|
||||
//
|
||||
// Invariants:
|
||||
// - Returned Backend starts operational=FALSE; caller must
|
||||
// follow up with RecoverVolume to flip it (T3b mini plan §2.3).
|
||||
// - ImplKind mismatch against on-disk superblock → ErrImplKindMismatch
|
||||
// (never silently opens a different-impl file; mini plan §2.4).
|
||||
func (p *DurableProvider) Open(ctx context.Context, volumeID string) (frontend.Backend, error) {
|
||||
// Wait for projection healthy, same shape as memback.
|
||||
if err := p.waitHealthy(ctx, volumeID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
if p.closed {
|
||||
p.mu.Unlock()
|
||||
return nil, fmt.Errorf("durable: provider closed")
|
||||
}
|
||||
if h, ok := p.volumes[volumeID]; ok {
|
||||
p.mu.Unlock()
|
||||
return h.backend, nil
|
||||
}
|
||||
p.mu.Unlock()
|
||||
|
||||
h, err := p.openOrCreate(volumeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check-then-insert: another goroutine may have raced us.
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if existing, ok := p.volumes[volumeID]; ok {
|
||||
// Race: close the handle we just opened; return the winner.
|
||||
_ = h.storage.Close()
|
||||
return existing.backend, nil
|
||||
}
|
||||
p.volumes[volumeID] = h
|
||||
return h.backend, nil
|
||||
}
|
||||
|
||||
// waitHealthy polls the projection until it reports Healthy for
|
||||
// volumeID, or ctx / cfg.OpenTimeout expires.
|
||||
func (p *DurableProvider) waitHealthy(ctx context.Context, volumeID string) error {
|
||||
const poll = 10 * time.Millisecond
|
||||
ownCtx, cancel := context.WithTimeout(ctx, p.cfg.OpenTimeout)
|
||||
defer cancel()
|
||||
for {
|
||||
proj := p.view.Projection()
|
||||
if proj.VolumeID == volumeID && proj.Healthy {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-ownCtx.Done():
|
||||
return frontend.ErrNotReady
|
||||
case <-time.After(poll):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// openOrCreate opens the on-disk file (verifying ImplKind) or
|
||||
// creates it if missing (using the configured selector).
|
||||
func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) {
|
||||
path := p.volumePath(volumeID)
|
||||
exists, err := fileExists(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("durable: stat %s: %w", path, err)
|
||||
}
|
||||
|
||||
if exists {
|
||||
if err := p.verifyImplOnDisk(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.openExisting(volumeID, path)
|
||||
}
|
||||
return p.createFresh(volumeID, path)
|
||||
}
|
||||
|
||||
// verifyImplOnDisk peeks the 4-byte magic at offset 0 and returns
|
||||
// ErrImplKindMismatch if it doesn't match the configured selector.
|
||||
// Runs BEFORE the storage-level Open so the error message is
|
||||
// selector-aware instead of cryptic magic-mismatch.
|
||||
func (p *DurableProvider) verifyImplOnDisk(path string) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("durable: open for magic peek: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
magic := make([]byte, 4)
|
||||
if _, err := io.ReadFull(f, magic); err != nil {
|
||||
return fmt.Errorf("durable: read magic: %w", err)
|
||||
}
|
||||
diskImpl, ok := magicToImpl(string(magic))
|
||||
if !ok {
|
||||
return fmt.Errorf("%w: unrecognized magic %q at %s",
|
||||
ErrImplKindMismatch, string(magic), path)
|
||||
}
|
||||
if diskImpl != p.cfg.Impl {
|
||||
return fmt.Errorf("%w: selector=%s on-disk=%s at %s",
|
||||
ErrImplKindMismatch, p.cfg.Impl, diskImpl, path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// magicToImpl maps a 4-byte magic to ImplName. Hardcoded per
|
||||
// on-disk magic constants in core/storage and core/storage/smartwal.
|
||||
// Keep in sync when new impls land (caught at T3c matrix test time).
|
||||
func magicToImpl(magic string) (ImplName, bool) {
|
||||
switch magic {
|
||||
case "SWBK":
|
||||
return ImplWALStore, true
|
||||
case "SWAW":
|
||||
return ImplSmartWAL, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
// openExisting dispatches to the selector-matching Open function.
|
||||
func (p *DurableProvider) openExisting(volumeID, path string) (*volHandle, error) {
|
||||
var s storage.LogicalStorage
|
||||
switch p.cfg.Impl {
|
||||
case ImplWALStore:
|
||||
ws, err := storage.OpenWALStore(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("durable: OpenWALStore %s: %w", path, err)
|
||||
}
|
||||
s = ws
|
||||
case ImplSmartWAL:
|
||||
sw, err := smartwal.OpenStore(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("durable: smartwal.OpenStore %s: %w", path, err)
|
||||
}
|
||||
s = sw
|
||||
default:
|
||||
return nil, fmt.Errorf("durable: unknown impl %q", p.cfg.Impl)
|
||||
}
|
||||
return p.wrap(volumeID, path, s)
|
||||
}
|
||||
|
||||
// createFresh dispatches to the selector-matching Create function.
|
||||
// Requires cfg.NumBlocks to be non-zero (can't create without
|
||||
// knowing geometry).
|
||||
func (p *DurableProvider) createFresh(volumeID, path string) (*volHandle, error) {
|
||||
if p.cfg.NumBlocks == 0 {
|
||||
return nil, fmt.Errorf("durable: NumBlocks=0; cannot create storage for %s (use open-existing mode)",
|
||||
volumeID)
|
||||
}
|
||||
var s storage.LogicalStorage
|
||||
switch p.cfg.Impl {
|
||||
case ImplWALStore:
|
||||
ws, err := storage.CreateWALStore(path, p.cfg.NumBlocks, p.cfg.BlockSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("durable: CreateWALStore %s: %w", path, err)
|
||||
}
|
||||
s = ws
|
||||
case ImplSmartWAL:
|
||||
sw, err := smartwal.CreateStore(path, p.cfg.NumBlocks, p.cfg.BlockSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("durable: smartwal.CreateStore %s: %w", path, err)
|
||||
}
|
||||
s = sw
|
||||
default:
|
||||
return nil, fmt.Errorf("durable: unknown impl %q", p.cfg.Impl)
|
||||
}
|
||||
return p.wrap(volumeID, path, s)
|
||||
}
|
||||
|
||||
// wrap builds a StorageBackend around an opened LogicalStorage
|
||||
// using the current projection's Identity. Backend starts
|
||||
// operational=false; the caller flips via RecoverVolume.
|
||||
func (p *DurableProvider) wrap(volumeID, path string, s storage.LogicalStorage) (*volHandle, error) {
|
||||
proj := p.view.Projection()
|
||||
id := frontend.Identity{
|
||||
VolumeID: proj.VolumeID,
|
||||
ReplicaID: proj.ReplicaID,
|
||||
Epoch: proj.Epoch,
|
||||
EndpointVersion: proj.EndpointVersion,
|
||||
}
|
||||
b := NewStorageBackend(s, p.view, id)
|
||||
return &volHandle{storage: s, backend: b, path: path}, nil
|
||||
}
|
||||
|
||||
// RecoverVolume runs LogicalStorage.Recover for an open volume
|
||||
// and flips the backend operational bit based on the outcome.
|
||||
//
|
||||
// Must be called AFTER Open. Returns ErrVolumeNotOpen if volumeID
|
||||
// was never Open'd.
|
||||
//
|
||||
// On recovery success: backend.SetOperational(true, "recovered LSN=N").
|
||||
// On recovery error: backend.SetOperational(false, "recover failed: ...")
|
||||
// — the error is also returned. Caller decides whether to surface
|
||||
// as NotReady via /status (read-side), fail startup, or retry.
|
||||
func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (RecoveryReport, error) {
|
||||
p.mu.Lock()
|
||||
h, ok := p.volumes[volumeID]
|
||||
p.mu.Unlock()
|
||||
if !ok {
|
||||
return RecoveryReport{VolumeID: volumeID}, ErrVolumeNotOpen
|
||||
}
|
||||
report := Recover(h.storage, volumeID)
|
||||
if report.Err != nil {
|
||||
h.backend.SetOperational(false, report.Evidence)
|
||||
return report, report.Err
|
||||
}
|
||||
h.backend.SetOperational(true, report.Evidence)
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// Close closes all opened volumes in correct order: backend
|
||||
// first (marks closed so any racing I/O gets ErrBackendClosed),
|
||||
// then storage (flushes + releases file handles). Idempotent.
|
||||
func (p *DurableProvider) Close() error {
|
||||
p.mu.Lock()
|
||||
if p.closed {
|
||||
p.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
p.closed = true
|
||||
handles := p.volumes
|
||||
p.volumes = map[string]*volHandle{}
|
||||
p.mu.Unlock()
|
||||
|
||||
var firstErr error
|
||||
for _, h := range handles {
|
||||
_ = h.backend.Close()
|
||||
if err := h.storage.Close(); err != nil && firstErr == nil {
|
||||
firstErr = fmt.Errorf("durable: close storage: %w", err)
|
||||
}
|
||||
}
|
||||
return firstErr
|
||||
}
|
||||
|
||||
// fileExists returns (true, nil) if path exists as a regular file,
|
||||
// (false, nil) if missing, (_, err) on other stat errors.
|
||||
func fileExists(path string) (bool, error) {
|
||||
info, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return !info.IsDir(), nil
|
||||
}
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Compile-time check.
|
||||
var _ frontend.Provider = (*DurableProvider)(nil)
|
||||
@@ -0,0 +1,236 @@
|
||||
// T3b Provider tests — mini plan §2 acceptance rows #1-#4, #8.
|
||||
// Matrix-parameterized per Addendum A #1: every test iterates both
|
||||
// walstore and smartwal impls.
|
||||
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
)
|
||||
|
||||
func implMatrix() []durable.ImplName {
|
||||
return []durable.ImplName{durable.ImplSmartWAL, durable.ImplWALStore}
|
||||
}
|
||||
|
||||
func newProvider(t *testing.T, impl durable.ImplName) (*durable.DurableProvider, *stubView, string) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
|
||||
view := newStubView(healthyProj(id))
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: impl,
|
||||
StorageRoot: root,
|
||||
BlockSize: 4096,
|
||||
NumBlocks: 16, // 64 KiB volume — enough for unit tests
|
||||
}, view)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDurableProvider: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
return p, view, root
|
||||
}
|
||||
|
||||
// #1 — DurableProvider implements frontend.Provider.
|
||||
func TestT3b_DurableProvider_ImplementsProvider(t *testing.T) {
|
||||
for _, impl := range implMatrix() {
|
||||
impl := impl
|
||||
t.Run(string(impl), func(t *testing.T) {
|
||||
p, _, _ := newProvider(t, impl)
|
||||
var _ frontend.Provider = p
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// #2 — Open selects the right impl per config. Matrix walks both.
|
||||
func TestT3b_DurableProvider_Open_SelectsImpl_Matrix(t *testing.T) {
|
||||
for _, impl := range implMatrix() {
|
||||
impl := impl
|
||||
t.Run(string(impl), func(t *testing.T) {
|
||||
p, _, root := newProvider(t, impl)
|
||||
backend, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
if backend.Identity().VolumeID != "v1" {
|
||||
t.Errorf("Identity().VolumeID=%q want v1", backend.Identity().VolumeID)
|
||||
}
|
||||
// Verify on-disk magic matches selector.
|
||||
magic, err := readFirstMagic(filepath.Join(root, "v1.bin"))
|
||||
if err != nil {
|
||||
t.Fatalf("read magic: %v", err)
|
||||
}
|
||||
var expectMagic string
|
||||
switch impl {
|
||||
case durable.ImplWALStore:
|
||||
expectMagic = "SWBK"
|
||||
case durable.ImplSmartWAL:
|
||||
expectMagic = "SWAW"
|
||||
}
|
||||
if magic != expectMagic {
|
||||
t.Errorf("on-disk magic=%q want %q (impl=%s)", magic, expectMagic, impl)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// #3 — Returned Backend starts operational=false.
|
||||
func TestT3b_DurableProvider_Open_StartsNotOperational(t *testing.T) {
|
||||
for _, impl := range implMatrix() {
|
||||
impl := impl
|
||||
t.Run(string(impl), func(t *testing.T) {
|
||||
p, _, _ := newProvider(t, impl)
|
||||
backend, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
// Any I/O before RecoverVolume must return ErrNotReady.
|
||||
if _, err := backend.Read(context.Background(), 0, make([]byte, 4)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("Read before Recover: want ErrNotReady, got %v", err)
|
||||
}
|
||||
if _, err := backend.Write(context.Background(), 0, []byte("x")); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("Write before Recover: want ErrNotReady, got %v", err)
|
||||
}
|
||||
if err := backend.Sync(context.Background()); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("Sync before Recover: want ErrNotReady, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// #4 — ImplKind mismatch between selector and on-disk superblock
|
||||
// fails fast with named error.
|
||||
func TestT3b_DurableProvider_Open_ImplKindMismatch_FailsFast(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
|
||||
view := newStubView(healthyProj(id))
|
||||
|
||||
// Step 1: create a file with impl=smartwal.
|
||||
pSmart, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplSmartWAL,
|
||||
StorageRoot: root,
|
||||
BlockSize: 4096,
|
||||
NumBlocks: 16,
|
||||
}, view)
|
||||
if err != nil {
|
||||
t.Fatalf("create smartwal provider: %v", err)
|
||||
}
|
||||
if _, err := pSmart.Open(context.Background(), "v1"); err != nil {
|
||||
t.Fatalf("smartwal Open: %v", err)
|
||||
}
|
||||
_ = pSmart.Close()
|
||||
|
||||
// Step 2: open the same file with selector=walstore — must fail.
|
||||
pWAL, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStore,
|
||||
StorageRoot: root,
|
||||
BlockSize: 4096,
|
||||
NumBlocks: 16,
|
||||
}, view)
|
||||
if err != nil {
|
||||
t.Fatalf("create walstore provider: %v", err)
|
||||
}
|
||||
defer pWAL.Close()
|
||||
|
||||
_, err = pWAL.Open(context.Background(), "v1")
|
||||
if err == nil {
|
||||
t.Fatal("want ImplKind mismatch error, got nil (silent coerce)")
|
||||
}
|
||||
if !errors.Is(err, durable.ErrImplKindMismatch) {
|
||||
t.Fatalf("want ErrImplKindMismatch, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// readFirstMagic reads the first 4 bytes of a file to peek magic.
|
||||
func readFirstMagic(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
buf := make([]byte, 4)
|
||||
if _, err := f.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
// #8 — Backend Close does NOT tear down storage; Provider.Close
|
||||
// tears down in correct order; double-close idempotent.
|
||||
func TestT3b_DurableProvider_Lifecycle_BackendClose_DoesNotTearDownStorage(t *testing.T) {
|
||||
for _, impl := range implMatrix() {
|
||||
impl := impl
|
||||
t.Run(string(impl), func(t *testing.T) {
|
||||
p, _, _ := newProvider(t, impl)
|
||||
backend, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
// Close the backend handle.
|
||||
if err := backend.Close(); err != nil {
|
||||
t.Fatalf("backend Close: %v", err)
|
||||
}
|
||||
// Re-opening via provider should still work because
|
||||
// storage wasn't torn down. Provider caches so we
|
||||
// get the same (now-closed) backend; verify that the
|
||||
// cached backend correctly reports ErrBackendClosed.
|
||||
same, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatalf("re-Open: %v", err)
|
||||
}
|
||||
// We expect the cached (closed) backend — any I/O
|
||||
// returns ErrBackendClosed (closed wins over not-
|
||||
// operational in the gate stack).
|
||||
if _, err := same.Read(context.Background(), 0, make([]byte, 4)); !errors.Is(err, frontend.ErrBackendClosed) {
|
||||
t.Errorf("Read on closed backend: want ErrBackendClosed, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestT3b_DurableProvider_Lifecycle_DoubleClose_Idempotent(t *testing.T) {
|
||||
for _, impl := range implMatrix() {
|
||||
impl := impl
|
||||
t.Run(string(impl), func(t *testing.T) {
|
||||
p, _, _ := newProvider(t, impl)
|
||||
_, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
if err := p.Close(); err != nil {
|
||||
t.Fatalf("first Close: %v", err)
|
||||
}
|
||||
// Second close must be a no-op, not a panic.
|
||||
if err := p.Close(); err != nil {
|
||||
t.Errorf("second Close: %v (want nil, idempotent)", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Bonus: Open caches backend per volumeID. Two Opens return same handle.
|
||||
func TestT3b_DurableProvider_Open_Caches(t *testing.T) {
|
||||
for _, impl := range implMatrix() {
|
||||
impl := impl
|
||||
t.Run(string(impl), func(t *testing.T) {
|
||||
p, _, _ := newProvider(t, impl)
|
||||
b1, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatalf("Open #1: %v", err)
|
||||
}
|
||||
b2, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatalf("Open #2: %v", err)
|
||||
}
|
||||
if b1 != b2 {
|
||||
t.Errorf("Open returned different backends for same volumeID; cache broken")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package durable
|
||||
|
||||
// Package durable G-int.5 — Recovery wrapper (read-side only).
|
||||
//
|
||||
// Recover wraps LogicalStorage.Recover() into a RecoveryReport
|
||||
// that the Provider can act on (flip SetOperational) and the host
|
||||
// can surface via /status (read-side readiness report, no new
|
||||
// publication path).
|
||||
//
|
||||
// §3.2 authority-boundary discipline: Recovery does NOT publish
|
||||
// epoch, does NOT advance lineage, does NOT mint assignment
|
||||
// state. It observes on-disk state, computes "is this node ready
|
||||
// to serve I/O", and reports the answer. Master authority remains
|
||||
// the sole publisher of Epoch / EndpointVersion.
|
||||
//
|
||||
// Option 3 from audit §10.5: no local epoch mirror in superblock.
|
||||
// Per-I/O fence check in StorageBackend (identity vs projection)
|
||||
// is the sole authority-drift guard. Recovery compares nothing
|
||||
// against master-published state.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// RecoveryReport is the outcome of one Recover call. Evidence is
|
||||
// the short string passed to SetOperational + surfaced via
|
||||
// /status for operator diagnostics.
|
||||
type RecoveryReport struct {
|
||||
VolumeID string
|
||||
RecoveredLSN uint64
|
||||
Evidence string
|
||||
|
||||
// Err is non-nil iff Recover returned an error. Callers MUST
|
||||
// check this: evidence alone is human-readable and not a
|
||||
// programmatic signal.
|
||||
Err error
|
||||
}
|
||||
|
||||
// Recover calls LogicalStorage.Recover() and packages the result
|
||||
// into a RecoveryReport. Never panics; all failures land on
|
||||
// RecoveryReport.Err.
|
||||
//
|
||||
// Pure function — no side-effects on the backend. The Provider
|
||||
// (or caller) is responsible for flipping the adapter's
|
||||
// operational gate based on the report.
|
||||
func Recover(s storage.LogicalStorage, volumeID string) RecoveryReport {
|
||||
lsn, err := s.Recover()
|
||||
if err != nil {
|
||||
return RecoveryReport{
|
||||
VolumeID: volumeID,
|
||||
Evidence: fmt.Sprintf("recover failed: %v", err),
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return RecoveryReport{
|
||||
VolumeID: volumeID,
|
||||
RecoveredLSN: lsn,
|
||||
Evidence: fmt.Sprintf("recovered LSN=%d", lsn),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// T3b Recovery tests — mini plan §2 acceptance row #5.
|
||||
// Matrix-parameterized over both impls.
|
||||
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
)
|
||||
|
||||
// #5 clean recover path.
|
||||
func TestT3b_Recovery_CleanRecover_FlipsOperational(t *testing.T) {
|
||||
for _, impl := range implMatrix() {
|
||||
impl := impl
|
||||
t.Run(string(impl), func(t *testing.T) {
|
||||
p, _, _ := newProvider(t, impl)
|
||||
backend, err := p.Open(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
// Pre-Recover: I/O rejected.
|
||||
if _, err := backend.Read(context.Background(), 0, make([]byte, 4)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("pre-Recover Read: want ErrNotReady, got %v", err)
|
||||
}
|
||||
|
||||
report, err := p.RecoverVolume(context.Background(), "v1")
|
||||
if err != nil {
|
||||
t.Fatalf("RecoverVolume: %v", err)
|
||||
}
|
||||
if report.VolumeID != "v1" {
|
||||
t.Errorf("report.VolumeID=%q want v1", report.VolumeID)
|
||||
}
|
||||
if report.Err != nil {
|
||||
t.Errorf("report.Err=%v want nil", report.Err)
|
||||
}
|
||||
if !strings.Contains(report.Evidence, "recovered LSN=") {
|
||||
t.Errorf("evidence=%q does not contain 'recovered LSN='", report.Evidence)
|
||||
}
|
||||
|
||||
// Post-Recover: I/O succeeds.
|
||||
if _, err := backend.Read(context.Background(), 0, make([]byte, 4)); err != nil {
|
||||
t.Errorf("post-Recover Read: want success, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// #5 — RecoverVolume on an un-opened volumeID returns ErrVolumeNotOpen.
|
||||
func TestT3b_Recovery_UnopenedVolume_ReturnsErrVolumeNotOpen(t *testing.T) {
|
||||
for _, impl := range implMatrix() {
|
||||
impl := impl
|
||||
t.Run(string(impl), func(t *testing.T) {
|
||||
p, _, _ := newProvider(t, impl)
|
||||
_, err := p.RecoverVolume(context.Background(), "never-opened")
|
||||
if !errors.Is(err, durable.ErrVolumeNotOpen) {
|
||||
t.Fatalf("want ErrVolumeNotOpen, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Recover function (pure) returns evidence + no error on healthy storage.
|
||||
func TestT3b_Recovery_PureFunction_Success(t *testing.T) {
|
||||
for _, f := range logicalStorageFactories() {
|
||||
f := f
|
||||
t.Run(f.name, func(t *testing.T) {
|
||||
s := f.make(t, 4, 4096)
|
||||
report := durable.Recover(s, "v1")
|
||||
if report.Err != nil {
|
||||
t.Fatalf("Recover: %v", report.Err)
|
||||
}
|
||||
if report.VolumeID != "v1" {
|
||||
t.Errorf("VolumeID=%q want v1", report.VolumeID)
|
||||
}
|
||||
if !strings.Contains(report.Evidence, "recovered LSN=") {
|
||||
t.Errorf("evidence=%q missing 'recovered LSN='", report.Evidence)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Recovery evidence for I/O that closes backend post-recover on error.
|
||||
// This exercises the error wrapping path: even when the underlying
|
||||
// Recover would not fail, we can verify the report's fields are set
|
||||
// correctly. (Testing the real error path requires an injected
|
||||
// error-returning LogicalStorage; kept out of T3b scope because
|
||||
// writing a full stub is boilerplate that doesn't prove new logic.)
|
||||
func TestT3b_Recovery_Report_FieldsPopulated(t *testing.T) {
|
||||
for _, f := range logicalStorageFactories() {
|
||||
f := f
|
||||
t.Run(f.name, func(t *testing.T) {
|
||||
s := f.make(t, 4, 4096)
|
||||
// Write + sync then recover — LSN should be > 0.
|
||||
if _, err := s.Write(0, make([]byte, 4096)); err != nil {
|
||||
t.Fatalf("Write: %v", err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatalf("Sync: %v", err)
|
||||
}
|
||||
report := durable.Recover(s, "v1")
|
||||
if report.Err != nil {
|
||||
t.Fatalf("Recover err: %v", report.Err)
|
||||
}
|
||||
// RecoveredLSN MUST be non-zero post-Write+Sync.
|
||||
if report.RecoveredLSN == 0 {
|
||||
t.Errorf("RecoveredLSN=0 after Write+Sync; expected >0")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,9 @@ const (
|
||||
ASCLBAOutOfRange uint8 = 0x21
|
||||
ASCNotReady uint8 = 0x04
|
||||
ASCNotReadyManualIntv uint8 = 0x03
|
||||
// ASCWriteError — T3b: SYNC_CACHE backend-sync failure maps
|
||||
// here per SPC-5 §D.2.14 ("WRITE ERROR" 0x0C/00).
|
||||
ASCWriteError uint8 = 0x0C
|
||||
|
||||
// Stale primary: 0x04 / 0x0A = "LOGICAL UNIT NOT READY,
|
||||
// ASYMMETRIC ACCESS STATE TRANSITION" (SPC-5 Annex F). This
|
||||
|
||||
@@ -190,9 +190,22 @@ func (h *SCSIHandler) HandleCommand(ctx context.Context, cdb [16]byte, dataOut [
|
||||
return h.read10(ctx, cdb)
|
||||
case ScsiWrite10:
|
||||
return h.write10(ctx, cdb, dataOut)
|
||||
// Batch 10.5: SYNC_CACHE(10/16) — memback non-durable, no-op
|
||||
// Good. T3 owns real flush behavior when durable backend lands.
|
||||
// T3b wire: SYNCHRONIZE_CACHE(10) / (16) dispatches to
|
||||
// Backend.Sync(ctx). Durable backends flush the WAL; memback
|
||||
// Sync is a no-op (returns nil). Errors propagate to
|
||||
// MEDIUM_ERROR (SPC-5 §7.26) rather than swallowed — stop
|
||||
// rule §3.6 (error-faithful Sync wire) makes data-integrity
|
||||
// hazards visible to the host.
|
||||
case ScsiSyncCache10, ScsiSyncCache16:
|
||||
if err := h.backend.Sync(ctx); err != nil {
|
||||
return SCSIResult{
|
||||
Status: StatusCheckCondition,
|
||||
SenseKey: SenseMediumError,
|
||||
ASC: ASCWriteError,
|
||||
ASCQ: 0x00,
|
||||
Reason: fmt.Sprintf("SYNC_CACHE: backend sync: %v", err),
|
||||
}
|
||||
}
|
||||
return SCSIResult{Status: StatusGood}
|
||||
// Batch 10.5: 16-byte data variants (64-bit LBA).
|
||||
case ScsiRead16:
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// T3b iSCSI SYNCHRONIZE_CACHE wire test — mini plan §2 #6.
|
||||
// Pins that SYNC_CACHE(10) and SYNC_CACHE(16) dispatch to
|
||||
// backend.Sync(ctx).
|
||||
|
||||
package iscsi_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
|
||||
)
|
||||
|
||||
// syncCacheCDB builds a SYNCHRONIZE_CACHE(10) CDB (opcode 0x35).
|
||||
// All fields zeroed — spec-legal "flush everything" form.
|
||||
func syncCacheCDB10() [16]byte {
|
||||
var cdb [16]byte
|
||||
cdb[0] = 0x35 // ScsiSyncCache10
|
||||
return cdb
|
||||
}
|
||||
|
||||
// syncCacheCDB16 builds a SYNCHRONIZE_CACHE(16) CDB (opcode 0x91).
|
||||
func syncCacheCDB16() [16]byte {
|
||||
var cdb [16]byte
|
||||
cdb[0] = 0x91 // ScsiSyncCache16
|
||||
return cdb
|
||||
}
|
||||
|
||||
func TestT3b_ISCSI_SyncCache_DispatchesToBackend(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
cdb [16]byte
|
||||
}{
|
||||
{"SYNC_CACHE_10", syncCacheCDB10()},
|
||||
{"SYNC_CACHE_16", syncCacheCDB16()},
|
||||
}
|
||||
for _, c := range cases {
|
||||
c := c
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
rec := testback.NewRecordingBackend(frontend.Identity{
|
||||
VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1,
|
||||
})
|
||||
h := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: rec})
|
||||
ctx := context.Background()
|
||||
|
||||
pre := rec.SyncCount()
|
||||
r := h.HandleCommand(ctx, c.cdb, nil)
|
||||
if r.AsError() != nil {
|
||||
t.Fatalf("%s: got err=%v, want Good", c.name, r.AsError())
|
||||
}
|
||||
post := rec.SyncCount()
|
||||
if post-pre != 1 {
|
||||
t.Errorf("%s: Sync invoked %d times, want 1", c.name, post-pre)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -161,8 +161,14 @@ func (h *IOHandler) Handle(ctx context.Context, cmd IOCommand) IOResult {
|
||||
case ioWrite:
|
||||
return h.write(ctx, cmd)
|
||||
case ioFlush:
|
||||
// No backend-level flush yet — Success is safe because
|
||||
// the T2 memback backend is not a write-back cache.
|
||||
// T3b wire: dispatch to Backend.Sync. Durable backends
|
||||
// flush the WAL; memback Sync is a no-op (returns nil).
|
||||
// Errors propagate as InternalError (NVMe 1.4 §4.5; SCT=0
|
||||
// SC=0x06) — stop rule §3.6 (error-faithful) forbids
|
||||
// swallowing to Success.
|
||||
if err := h.backend.Sync(ctx); err != nil {
|
||||
return mapBackendError(err, "flush")
|
||||
}
|
||||
return IOResult{SCT: SCTGeneric, SC: SCSuccess}
|
||||
default:
|
||||
return IOResult{
|
||||
|
||||
@@ -434,6 +434,16 @@ func (s *Session) dispatchIO(ctx context.Context, req *Request) {
|
||||
case ioWrite:
|
||||
s.handleWrite(ctx, req)
|
||||
case ioFlush:
|
||||
// T3b wire: dispatch to IOHandler.Handle which calls
|
||||
// Backend.Sync(ctx) — error propagates to CapsuleResp
|
||||
// status instead of silent Success.
|
||||
res := s.handler.Handle(ctx, IOCommand{
|
||||
Opcode: req.capsule.OpCode,
|
||||
NSID: req.capsule.NSID,
|
||||
})
|
||||
if res.AsError() != nil {
|
||||
req.resp.Status = MakeStatusField(res.SCT, res.SC, true)
|
||||
}
|
||||
s.enqueueResponse(&response{resp: req.resp})
|
||||
default:
|
||||
req.resp.Status = MakeStatusField(SCTGeneric, SCInvalidOpcode, true)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// T3b NVMe Flush wire test — mini plan §2 #7.
|
||||
// Pins that ioFlush (opcode 0x00) dispatches to backend.Sync(ctx).
|
||||
|
||||
package nvme_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
|
||||
)
|
||||
|
||||
func TestT3b_NVMe_Flush_DispatchesToBackend(t *testing.T) {
|
||||
rec := testback.NewRecordingBackend(frontend.Identity{
|
||||
VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1,
|
||||
})
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: rec})
|
||||
ctx := context.Background()
|
||||
|
||||
pre := rec.SyncCount()
|
||||
res := h.Handle(ctx, nvme.IOCommand{
|
||||
Opcode: 0x00, // ioFlush
|
||||
NSID: 1,
|
||||
})
|
||||
if res.AsError() != nil {
|
||||
t.Fatalf("Flush: got err=%v, want Success", res.AsError())
|
||||
}
|
||||
post := rec.SyncCount()
|
||||
if post-pre != 1 {
|
||||
t.Errorf("Flush dispatched to Sync %d times, want 1", post-pre)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user