Merge pull request #42 from seaweedfs/iscsi/csi-node-lifecycle

iscsi: add ALUA multipath and mounted failover validation
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-05-06 14:05:35 -07:00
commit d581f9d49d
27 files changed
+2776 -92

No files matched your search

@@ -144,6 +144,29 @@ func TestApplyAlphaBlockvolumes_WaitsForGeneratedManifestInsteadOfKubeSystem(t *
}
}
func TestAlphaAppDemo_CanRestartCSINodeBeforeReader(t *testing.T) {
body := g15dReadFile(t, "scripts", "run-alpha-app-demo.sh")
for _, want := range []string{
"SW_BLOCK_RESTART_CSI_NODE_BEFORE_READER",
"SW_BLOCK_DEMO_APP_MANIFEST",
"rollout restart ds/sw-block-csi-node",
"restart-csi-node-status.log",
"wait_pod_log_contains sw-block-demo-writer",
} {
if !strings.Contains(body, want) {
t.Fatalf("app demo script missing %q", want)
}
}
wrapper := g15dReadFile(t, "scripts", "run-k8s-csi-node-restart.sh")
if !strings.Contains(wrapper, "demo-app-pvc-writer-hold.yaml") {
t.Fatalf("restart wrapper must use mounted-writer manifest:\n%s", wrapper)
}
if !strings.Contains(wrapper, "export SW_BLOCK_RESTART_CSI_NODE_BEFORE_READER=1") {
t.Fatalf("restart wrapper must enable restart mode:\n%s", wrapper)
}
}
func g15dReadFile(t *testing.T, parts ...string) string {
t.Helper()
root := g15bRepoRoot(t)
@@ -0,0 +1,90 @@
package main
import (
"crypto/sha256"
"encoding/binary"
"strings"
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
"github.com/seaweedfs/seaweed-block/core/host/volume"
)
type projectionALUAProvider struct {
view *volume.AdapterProjectionView
volumeID string
replicaID string
deviceSeed string
}
var _ iscsi.ALUAProvider = (*projectionALUAProvider)(nil)
func newProjectionALUAProvider(view *volume.AdapterProjectionView, volumeID, replicaID string, deviceSeed ...string) *projectionALUAProvider {
seed := volumeID
for _, candidate := range deviceSeed {
if candidate != "" {
seed = candidate
break
}
}
return &projectionALUAProvider{
view: view,
volumeID: volumeID,
replicaID: replicaID,
deviceSeed: seed,
}
}
func (p *projectionALUAProvider) ALUAState() iscsi.ALUAState {
if p == nil || p.view == nil {
return iscsi.ALUAUnavailable
}
fp := p.view.Projection()
ep := p.view.EngineProjection()
if fp.VolumeID != p.volumeID || fp.ReplicaID != p.replicaID {
return iscsi.ALUAUnavailable
}
if fp.Healthy {
return iscsi.ALUAActiveOptimized
}
switch ep.Mode {
case engine.ModeRecovering:
return iscsi.ALUATransitioning
case engine.ModeHealthy:
return iscsi.ALUAStandby
case engine.ModeIdle:
// Supporting replicas can remain engine-idle while still serving
// ALUA/VPD path probes through the metadata probe backend. They are
// standby paths, not frontend-write-ready paths.
return iscsi.ALUAStandby
case engine.ModeDegraded:
return iscsi.ALUAUnavailable
default:
return iscsi.ALUATransitioning
}
}
func (p *projectionALUAProvider) TargetPortGroupID() uint16 {
return stableALUAID("tpg", p.deviceSeed, p.volumeID, p.replicaID)
}
func (p *projectionALUAProvider) RelativeTargetPortID() uint16 {
return stableALUAID("rtp", p.deviceSeed, p.volumeID, p.replicaID)
}
func (p *projectionALUAProvider) DeviceNAA() [8]byte {
sum := sha256.Sum256([]byte(strings.Join([]string{"naa", p.deviceSeed, p.volumeID}, "\x00")))
var out [8]byte
out[0] = 0x60 | (sum[0] & 0x0f)
copy(out[1:], sum[1:8])
return out
}
func stableALUAID(parts ...string) uint16 {
sum := sha256.Sum256([]byte(strings.Join(parts, "\x00")))
id := binary.BigEndian.Uint16(sum[:2])
if id == 0 {
return 1
}
return id
}
@@ -0,0 +1,118 @@
package main
import (
"os"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
"github.com/seaweedfs/seaweed-block/core/host/volume"
)
type aluaProjector struct{ p engine.ReplicaProjection }
func (p aluaProjector) Projection() engine.ReplicaProjection { return p.p }
type aluaSupersedeProbe struct{ yes bool }
func (p aluaSupersedeProbe) IsSuperseded(string, uint64, uint64) bool { return p.yes }
func TestProjectionALUAProvider_StateMapping(t *testing.T) {
tests := []struct {
name string
mode engine.Mode
superseded bool
want iscsi.ALUAState
}{
{name: "healthy", mode: engine.ModeHealthy, want: iscsi.ALUAActiveOptimized},
{name: "superseded healthy", mode: engine.ModeHealthy, superseded: true, want: iscsi.ALUAStandby},
{name: "recovering", mode: engine.ModeRecovering, want: iscsi.ALUATransitioning},
{name: "degraded", mode: engine.ModeDegraded, want: iscsi.ALUAUnavailable},
{name: "idle", mode: engine.ModeIdle, want: iscsi.ALUAStandby},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
view := volume.NewAdapterProjectionView(
aluaProjector{p: engine.ReplicaProjection{Mode: tt.mode, Epoch: 1, EndpointVersion: 1}},
"v1",
"r1",
aluaSupersedeProbe{yes: tt.superseded},
)
prov := newProjectionALUAProvider(view, "v1", "r1")
if got := prov.ALUAState(); got != tt.want {
t.Fatalf("ALUAState()=%s want %s", got, tt.want)
}
})
}
}
func TestProjectionALUAProvider_IdentityIsStableAndPathSpecific(t *testing.T) {
view1 := volume.NewAdapterProjectionView(
aluaProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy}},
"v1",
"r1",
nil,
)
view2 := volume.NewAdapterProjectionView(
aluaProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy}},
"v1",
"r2",
nil,
)
r1 := newProjectionALUAProvider(view1, "v1", "r1", "iqn.2026-05.io.seaweedfs:v1")
r2 := newProjectionALUAProvider(view2, "v1", "r2", "iqn.2026-05.io.seaweedfs:v1")
if got := r1.DeviceNAA()[0] & 0xf0; got != 0x60 {
t.Fatalf("DeviceNAA high nibble=%#x want 0x60", got)
}
if r1.DeviceNAA() != r2.DeviceNAA() {
t.Fatalf("same volume must expose same DeviceNAA: r1=%x r2=%x", r1.DeviceNAA(), r2.DeviceNAA())
}
if r1.TargetPortGroupID() == r2.TargetPortGroupID() {
t.Fatalf("replica paths should have distinct target port groups: %d", r1.TargetPortGroupID())
}
if r1.RelativeTargetPortID() == r2.RelativeTargetPortID() {
t.Fatalf("replica paths should have distinct relative target port ids: %d", r1.RelativeTargetPortID())
}
}
func TestProjectionALUAProvider_DeviceNAAIncludesExportSeed(t *testing.T) {
view := volume.NewAdapterProjectionView(
aluaProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy}},
"v1",
"r1",
nil,
)
a := newProjectionALUAProvider(view, "v1", "r1", "iqn.2026-05.io.seaweedfs:cluster-a:v1")
b := newProjectionALUAProvider(view, "v1", "r1", "iqn.2026-05.io.seaweedfs:cluster-b:v1")
if a.DeviceNAA() == b.DeviceNAA() {
t.Fatalf("same volume id with different export seeds produced same DeviceNAA: %x", a.DeviceNAA())
}
}
func TestProjectionALUAProvider_FailsClosedOnIdentityMismatch(t *testing.T) {
view := volume.NewAdapterProjectionView(
aluaProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy}},
"v1",
"r1",
nil,
)
prov := newProjectionALUAProvider(view, "v1", "r2")
if got := prov.ALUAState(); got != iscsi.ALUAUnavailable {
t.Fatalf("identity mismatch ALUAState()=%s want %s", got, iscsi.ALUAUnavailable)
}
}
func TestProjectionALUAProvider_DoesNotImportControlTruthDomains(t *testing.T) {
body, err := os.ReadFile("iscsi_alua_provider.go")
if err != nil {
t.Fatal(err)
}
for _, forbidden := range []string{"core/authority", "core/lifecycle", "core/rpc/control"} {
if strings.Contains(string(body), forbidden) {
t.Fatalf("projection ALUA provider must not import %s", forbidden)
}
}
}
@@ -0,0 +1,33 @@
package main
import (
"context"
"fmt"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
)
type durableProbeProvider struct {
provider *durable.DurableProvider
}
var _ interface {
ProbeBackend(context.Context, string) (frontend.Backend, error)
} = (*durableProbeProvider)(nil)
func (p *durableProbeProvider) ProbeBackend(_ context.Context, volumeID string) (frontend.Backend, error) {
if p == nil || p.provider == nil {
return nil, frontend.ErrNotReady
}
if b := p.provider.Backend(volumeID); b != nil {
return b, nil
}
if _, err := p.provider.EnsureStorage(volumeID); err != nil {
return nil, err
}
if b := p.provider.Backend(volumeID); b != nil {
return b, nil
}
return nil, fmt.Errorf("no probe backend for %s after EnsureStorage", volumeID)
}
+6
View File
@@ -744,6 +744,10 @@ func run(f flags) int {
var frontendTargets []*control.FrontendTarget
if f.iscsiListen != "" {
prov := provider
var probeProvider iscsi.ProbeBackendProvider
if durableProv != nil {
probeProvider = &durableProbeProvider{provider: durableProv}
}
negotiation := iscsi.NegotiableConfig{}
if f.iscsiCHAPSecret != "" {
negotiation = iscsi.DefaultNegotiableConfig()
@@ -758,11 +762,13 @@ func run(f flags) int {
PortalAddr: f.iscsiPortalAddr,
VolumeID: f.volumeID,
Provider: prov,
ProbeProvider: probeProvider,
Negotiation: negotiation,
DataOutTimeout: f.iscsiDataOutTTL,
Handler: iscsi.HandlerConfig{
BlockSize: frontendBlockSize,
VolumeSize: frontendVolumeSize,
ALUA: newProjectionALUAProvider(h.ProjectionView(), f.volumeID, f.replicaID, f.iscsiIQN),
},
})
iscsiAddr, err := iscsiTarget.Start()
+107
View File
@@ -0,0 +1,107 @@
package iscsi
import "encoding/binary"
// ALUAState is the SPC asymmetric logical unit access state exposed to OS
// initiators. It is protocol reporting only; authority remains outside iSCSI.
type ALUAState uint8
const (
ALUAActiveOptimized ALUAState = 0x00
ALUAActiveNonOptimized ALUAState = 0x01
ALUAStandby ALUAState = 0x02
ALUAUnavailable ALUAState = 0x0e
ALUATransitioning ALUAState = 0x0f
)
func (s ALUAState) String() string {
switch s {
case ALUAActiveOptimized:
return "active_optimized"
case ALUAActiveNonOptimized:
return "active_non_optimized"
case ALUAStandby:
return "standby"
case ALUAUnavailable:
return "unavailable"
case ALUATransitioning:
return "transitioning"
default:
return "unknown"
}
}
// ALUAProvider is an optional read-only state source for SCSIHandler. It must
// consume frontend facts only; it must not mint authority or mutate placement.
type ALUAProvider interface {
ALUAState() ALUAState
TargetPortGroupID() uint16
RelativeTargetPortID() uint16
DeviceNAA() [8]byte
}
func (h *SCSIHandler) aluaDataReject(op string) *SCSIResult {
if h.alua == nil {
return nil
}
switch h.alua.ALUAState() {
case ALUAActiveOptimized, ALUAActiveNonOptimized:
return nil
default:
r := SCSIResult{
Status: StatusCheckCondition,
SenseKey: SenseNotReady,
ASC: ASCNotReady,
ASCQ: ASCQTargetPortStandby,
Reason: "ALUA path is not active for " + op,
}
return &r
}
}
func (h *SCSIHandler) maintenanceIn(cdb [16]byte) SCSIResult {
sa := cdb[1] & 0x1f
switch sa {
case SaiReportTargetPortGroups:
return h.reportTargetPortGroups(cdb)
default:
return illegalRequest(ASCInvalidOpcode, 0x00, "unsupported MAINTENANCE IN service action")
}
}
func (h *SCSIHandler) reportTargetPortGroups(cdb [16]byte) SCSIResult {
if h.alua == nil {
return illegalRequest(ASCInvalidOpcode, 0x00, "REPORT TARGET PORT GROUPS requires ALUA provider")
}
allocLen := binary.BigEndian.Uint32(cdb[6:10])
data := make([]byte, 16)
// Layout per SPC-4 §6.27 Table 175. The 4-byte parameter list header
// is followed by one Target Port Group descriptor (12 bytes), with
// one Target Port descriptor inside it (4 bytes).
//
// data[0:4] : parameter list length = 12
// data[4] : descriptor byte 0 — PREF | reserved | AAS (bits 3:0)
// data[5] : descriptor byte 1 — T_SUP|O_SUP|LBD_SUP|U_SUP|S_SUP|AN_SUP|AO_SUP|Reserved
// data[6:8] : descriptor bytes 2-3 — Target Port Group
// data[8] : descriptor byte 4 — Reserved
// data[9] : descriptor byte 5 — Status Code
// data[10] : descriptor byte 6 — Vendor Unique
// data[11] : descriptor byte 7 — Target Port Count (= 1)
// data[12:16]: target port descriptor 0
// data[12:14] : obsolete
// data[14:16] : Relative Target Port Identifier
binary.BigEndian.PutUint32(data[0:4], 12)
data[4] = uint8(h.alua.ALUAState()) & 0x0f
// Support flags: T_SUP (bit 7) | U_SUP (bit 4) | S_SUP (bit 3) | AN_SUP (bit 2) | AO_SUP (bit 1).
// bit 0 is reserved and must be 0.
data[5] = 0x9e
binary.BigEndian.PutUint16(data[6:8], h.alua.TargetPortGroupID())
data[11] = 0x01
binary.BigEndian.PutUint16(data[14:16], h.alua.RelativeTargetPortID())
if allocLen < uint32(len(data)) {
data = data[:allocLen]
}
return SCSIResult{Status: StatusGood, Data: data}
}
+14 -13
View File
@@ -11,9 +11,9 @@ import "fmt"
// SCSI status byte values (SPC-5 §6). Only the subset we use
// directly is declared.
const (
StatusGood uint8 = 0x00
StatusCheckCondition uint8 = 0x02
StatusBusy uint8 = 0x08
StatusGood uint8 = 0x00
StatusCheckCondition uint8 = 0x02
StatusBusy uint8 = 0x08
StatusReservationConflict uint8 = 0x18
)
@@ -31,11 +31,12 @@ const (
// ASC/ASCQ (selected — full tables live in spc-5 Annex F).
const (
ASCInvalidOpcode uint8 = 0x20
ASCInvalidFieldInCDB uint8 = 0x24
ASCLBAOutOfRange uint8 = 0x21
ASCNotReady uint8 = 0x04
ASCNotReadyManualIntv uint8 = 0x03
ASCInvalidOpcode uint8 = 0x20
ASCInvalidFieldInCDB uint8 = 0x24
ASCLBAOutOfRange uint8 = 0x21
ASCNotReady uint8 = 0x04
ASCNotReadyManualIntv uint8 = 0x03
ASCQTargetPortStandby uint8 = 0x0B
// ASCWriteError — T3b: SYNC_CACHE backend-sync failure maps
// here per SPC-5 §D.2.14 ("WRITE ERROR" 0x0C/00).
ASCWriteError uint8 = 0x0C
@@ -62,11 +63,11 @@ const (
// with non-empty sense key; stale READ returns CHECK CONDITION
// and does NOT return data to initiator".
type SCSIError struct {
Status uint8
SenseKey uint8
ASC uint8
ASCQ uint8
Reason string // free-form; diagnostic only
Status uint8
SenseKey uint8
ASC uint8
ASCQ uint8
Reason string // free-form; diagnostic only
}
func (e *SCSIError) Error() string {
@@ -0,0 +1,284 @@
package iscsi_test
import (
"bytes"
"context"
"encoding/binary"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
)
type testALUAProvider struct {
state iscsi.ALUAState
tpgID uint16
rtpID uint16
naa [8]byte
}
func (p *testALUAProvider) ALUAState() iscsi.ALUAState { return p.state }
func (p *testALUAProvider) TargetPortGroupID() uint16 { return p.tpgID }
func (p *testALUAProvider) RelativeTargetPortID() uint16 { return p.rtpID }
func (p *testALUAProvider) DeviceNAA() [8]byte { return p.naa }
func aluaTestProvider(state iscsi.ALUAState) *testALUAProvider {
return &testALUAProvider{
state: state,
tpgID: 7,
rtpID: 3,
naa: [8]byte{0x60, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0x11, 0x22},
}
}
func inquiryCDB(alloc uint16) [16]byte {
var cdb [16]byte
cdb[0] = iscsi.ScsiInquiry
binary.BigEndian.PutUint16(cdb[3:5], alloc)
return cdb
}
func vpdCDB(page uint8, alloc uint16) [16]byte {
var cdb [16]byte
cdb[0] = iscsi.ScsiInquiry
cdb[1] = 0x01
cdb[2] = page
binary.BigEndian.PutUint16(cdb[3:5], alloc)
return cdb
}
func reportTPGCDB(alloc uint32) [16]byte {
var cdb [16]byte
cdb[0] = iscsi.ScsiMaintenanceIn
cdb[1] = iscsi.SaiReportTargetPortGroups
binary.BigEndian.PutUint32(cdb[6:10], alloc)
return cdb
}
func syncCache10CDB() [16]byte {
var cdb [16]byte
cdb[0] = iscsi.ScsiSyncCache10
return cdb
}
func TestP6ALUA_NoProviderDoesNotAdvertiseALUA(t *testing.T) {
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1", ReplicaID: "r1"})
h := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: rec})
inq := h.HandleCommand(context.Background(), inquiryCDB(96), nil)
if inq.Status != iscsi.StatusGood {
t.Fatalf("INQUIRY: %v", inq.AsError())
}
if got := inq.Data[5] & 0x30; got != 0 {
t.Fatalf("TPGS bits with no ALUA provider = 0x%02x, want 0", got)
}
rtpg := h.HandleCommand(context.Background(), reportTPGCDB(64), nil)
if rtpg.Status == iscsi.StatusGood {
t.Fatal("REPORT TARGET PORT GROUPS succeeded without ALUA provider")
}
if rtpg.SenseKey != iscsi.SenseIllegalRequest {
t.Fatalf("REPORT TPG no provider sense=0x%02x want IllegalRequest", rtpg.SenseKey)
}
vpd := h.HandleCommand(context.Background(), vpdCDB(0x83, 255), nil)
if vpd.Status != iscsi.StatusGood {
t.Fatalf("VPD83 no provider: %v", vpd.AsError())
}
if pageLen := binary.BigEndian.Uint16(vpd.Data[2:4]); pageLen != 12 {
t.Fatalf("VPD83 no provider pageLen=%d want 12", pageLen)
}
}
func TestP6ALUA_NonActiveStatesRejectDataPath(t *testing.T) {
for _, state := range []iscsi.ALUAState{
iscsi.ALUAStandby,
iscsi.ALUAUnavailable,
iscsi.ALUATransitioning,
} {
t.Run(state.String(), func(t *testing.T) {
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1", ReplicaID: "r1"})
payload := make([]byte, iscsi.DefaultBlockSize)
if _, err := rec.Write(context.Background(), 0, payload); err != nil {
t.Fatalf("seed Write: %v", err)
}
prov := aluaTestProvider(state)
h := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: rec, ALUA: prov})
read := h.HandleCommand(context.Background(), readCDB(0, 1), nil)
if read.Status != iscsi.StatusCheckCondition {
t.Fatalf("READ status=0x%02x want CheckCondition", read.Status)
}
if read.SenseKey != iscsi.SenseNotReady || read.ASC != iscsi.ASCNotReady || read.ASCQ != iscsi.ASCQTargetPortStandby {
t.Fatalf("READ sense=%02x/%02x/%02x want NotReady/04/0B",
read.SenseKey, read.ASC, read.ASCQ)
}
if rec.ReadCount() != 0 {
t.Fatalf("READ reached backend %d times", rec.ReadCount())
}
write := h.HandleCommand(context.Background(), writeCDB(0, 1), payload)
if write.Status != iscsi.StatusCheckCondition {
t.Fatalf("WRITE status=0x%02x want CheckCondition", write.Status)
}
if write.SenseKey != iscsi.SenseNotReady || write.ASC != iscsi.ASCNotReady || write.ASCQ != iscsi.ASCQTargetPortStandby {
t.Fatalf("WRITE sense=%02x/%02x/%02x want NotReady/04/0B",
write.SenseKey, write.ASC, write.ASCQ)
}
sync := h.HandleCommand(context.Background(), syncCache10CDB(), nil)
if sync.Status != iscsi.StatusCheckCondition {
t.Fatalf("SYNC status=0x%02x want CheckCondition", sync.Status)
}
if rec.SyncCount() != 0 {
t.Fatalf("SYNC reached backend %d times", rec.SyncCount())
}
})
}
}
func TestP6ALUA_ActiveStatesAllowDataPath(t *testing.T) {
for _, state := range []iscsi.ALUAState{
iscsi.ALUAActiveOptimized,
iscsi.ALUAActiveNonOptimized,
} {
t.Run(state.String(), func(t *testing.T) {
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1", ReplicaID: "r1"})
payload := bytes.Repeat([]byte{0x5a}, int(iscsi.DefaultBlockSize))
if _, err := rec.Write(context.Background(), 0, payload); err != nil {
t.Fatalf("seed Write: %v", err)
}
h := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: rec, ALUA: aluaTestProvider(state)})
read := h.HandleCommand(context.Background(), readCDB(0, 1), nil)
if read.Status != iscsi.StatusGood {
t.Fatalf("READ active path: %v", read.AsError())
}
write := h.HandleCommand(context.Background(), writeCDB(0, 1), payload)
if write.Status != iscsi.StatusGood {
t.Fatalf("WRITE active path: %v", write.AsError())
}
})
}
}
func TestP6ALUA_ActiveAdvertisesTPGSAndServesReportTPG(t *testing.T) {
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1", ReplicaID: "r1"})
prov := aluaTestProvider(iscsi.ALUAActiveOptimized)
h := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: rec, ALUA: prov})
inq := h.HandleCommand(context.Background(), inquiryCDB(96), nil)
if inq.Status != iscsi.StatusGood {
t.Fatalf("INQUIRY: %v", inq.AsError())
}
if got := inq.Data[5] & 0x30; got != 0x10 {
t.Fatalf("TPGS bits = 0x%02x want 0x10 implicit ALUA", got)
}
rtpg := h.HandleCommand(context.Background(), reportTPGCDB(64), nil)
if rtpg.Status != iscsi.StatusGood {
t.Fatalf("REPORT TPG: %v", rtpg.AsError())
}
if len(rtpg.Data) != 16 {
t.Fatalf("REPORT TPG len=%d want 16", len(rtpg.Data))
}
// Layout per SPC-4 §6.27 Table 175 (parameter list header + descriptor):
// [4] AAS, [5] support flags, [6:8] Target Port Group,
// [9] status code, [11] target port count,
// [14:16] Relative Target Port Identifier.
if state := iscsi.ALUAState(rtpg.Data[4] & 0x0f); state != iscsi.ALUAActiveOptimized {
t.Fatalf("REPORT TPG state=%02x want active optimized", state)
}
if tpg := binary.BigEndian.Uint16(rtpg.Data[6:8]); tpg != prov.tpgID {
t.Fatalf("REPORT TPG id=%d want %d", tpg, prov.tpgID)
}
if status := rtpg.Data[9]; status != 0 {
t.Fatalf("REPORT TPG status code=0x%02x want 0 (no transition)", status)
}
if rtp := binary.BigEndian.Uint16(rtpg.Data[14:16]); rtp != prov.rtpID {
t.Fatalf("REPORT TPG relative target port=%d want %d", rtp, prov.rtpID)
}
}
func TestP6ALUA_ReportTPGHonorsZeroAllocationLength(t *testing.T) {
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1", ReplicaID: "r1"})
h := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: rec, ALUA: aluaTestProvider(iscsi.ALUAActiveOptimized)})
rtpg := h.HandleCommand(context.Background(), reportTPGCDB(0), nil)
if rtpg.Status != iscsi.StatusGood {
t.Fatalf("REPORT TPG alloc=0: %v", rtpg.AsError())
}
if len(rtpg.Data) != 0 {
t.Fatalf("REPORT TPG alloc=0 len=%d want 0", len(rtpg.Data))
}
}
func TestP6ALUA_VPD83AddsPathDescriptorsAndTruncates(t *testing.T) {
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1", ReplicaID: "r1"})
prov := aluaTestProvider(iscsi.ALUAActiveOptimized)
h := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: rec, ALUA: prov})
vpd := h.HandleCommand(context.Background(), vpdCDB(0x83, 255), nil)
if vpd.Status != iscsi.StatusGood {
t.Fatalf("VPD83: %v", vpd.AsError())
}
if pageLen := binary.BigEndian.Uint16(vpd.Data[2:4]); pageLen != 28 {
t.Fatalf("VPD83 pageLen=%d want 28", pageLen)
}
if got := vpd.Data[8:16]; !bytes.Equal(got, prov.naa[:]) {
t.Fatalf("VPD83 NAA=%x want %x", got, prov.naa)
}
if typ := vpd.Data[17] & 0x0f; typ != 0x05 {
t.Fatalf("VPD83 second descriptor type=0x%x want target port group", typ)
}
if typ := vpd.Data[25] & 0x0f; typ != 0x04 {
t.Fatalf("VPD83 third descriptor type=0x%x want relative target port", typ)
}
short := h.HandleCommand(context.Background(), vpdCDB(0x83, 20), nil)
if short.Status != iscsi.StatusGood {
t.Fatalf("short VPD83: %v", short.AsError())
}
if len(short.Data) != 20 {
t.Fatalf("short VPD83 len=%d want 20", len(short.Data))
}
}
func TestP6ALUA_VPD00UnchangedWhenALUAEnabled(t *testing.T) {
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1", ReplicaID: "r1"})
noALUA := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: rec})
withALUA := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: rec, ALUA: aluaTestProvider(iscsi.ALUAActiveOptimized)})
a := noALUA.HandleCommand(context.Background(), vpdCDB(0x00, 255), nil)
b := withALUA.HandleCommand(context.Background(), vpdCDB(0x00, 255), nil)
if a.Status != iscsi.StatusGood || b.Status != iscsi.StatusGood {
t.Fatalf("VPD00 statuses noALUA=%v withALUA=%v", a.AsError(), b.AsError())
}
if !bytes.Equal(a.Data, b.Data) {
t.Fatalf("VPD00 changed when ALUA enabled: noALUA=%x withALUA=%x", a.Data, b.Data)
}
}
func TestP6ALUA_ReportTPGReflectsStateChanges(t *testing.T) {
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1", ReplicaID: "r1"})
prov := aluaTestProvider(iscsi.ALUAActiveOptimized)
h := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: rec, ALUA: prov})
for _, state := range []iscsi.ALUAState{
iscsi.ALUAActiveOptimized,
iscsi.ALUAActiveNonOptimized,
iscsi.ALUAStandby,
iscsi.ALUAUnavailable,
iscsi.ALUATransitioning,
} {
prov.state = state
rtpg := h.HandleCommand(context.Background(), reportTPGCDB(64), nil)
if rtpg.Status != iscsi.StatusGood {
t.Fatalf("REPORT TPG state %02x: %v", state, rtpg.AsError())
}
if got := iscsi.ALUAState(rtpg.Data[4] & 0x0f); got != state {
t.Fatalf("REPORT TPG state=%02x want %02x", got, state)
}
}
}
@@ -0,0 +1,89 @@
package iscsi_test
import (
"context"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
)
type p6ProbeProvider struct {
backend frontend.Backend
opens atomic.Int32
}
func (p *p6ProbeProvider) ProbeBackend(context.Context, string) (frontend.Backend, error) {
p.opens.Add(1)
return p.backend, nil
}
type immediateNotReadyProvider struct{}
func (p immediateNotReadyProvider) Open(context.Context, string) (frontend.Backend, error) {
return nil, frontend.ErrNotReady
}
func TestP6ALUA_NormalSessionUsesProbeBackendForStandbyPath(t *testing.T) {
primaryOpen := immediateNotReadyProvider{}
probeBackend := testback.NewRecordingBackend(frontend.Identity{
VolumeID: "v1", ReplicaID: "r2", Epoch: 1, EndpointVersion: 1,
})
probe := &p6ProbeProvider{backend: probeBackend}
tg := iscsi.NewTarget(iscsi.TargetConfig{
Listen: "127.0.0.1:0",
IQN: "iqn.2026-05.io.seaweedfs:alua-standby",
VolumeID: "v1",
Provider: primaryOpen,
ProbeProvider: probe,
Handler: iscsi.HandlerConfig{
ALUA: aluaTestProvider(iscsi.ALUAStandby),
},
})
addr, err := tg.Start()
if err != nil {
t.Fatalf("target Start: %v", err)
}
defer tg.Close()
cli := dialAndLoginOpts(t, addr, loginOptions{
TargetName: "iqn.2026-05.io.seaweedfs:alua-standby",
})
defer func() { _ = cli.conn.Close() }()
deadline := time.Now().Add(2 * time.Second)
for probe.opens.Load() == 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if got := probe.opens.Load(); got != 1 {
t.Fatalf("ProbeBackend opens=%d want 1", got)
}
var inquiry [16]byte
inquiry[0] = iscsi.ScsiInquiry
inquiry[4] = 96
status, data := cli.scsiCmd(t, inquiry, nil, 96)
expectGood(t, status, "standby inquiry")
if len(data) == 0 || data[5]&0x10 == 0 {
t.Fatalf("standby inquiry missing implicit ALUA TPGS bit: len=%d byte5=0x%02x", len(data), data[5])
}
var rtpg [16]byte
rtpg[0] = iscsi.ScsiMaintenanceIn
rtpg[1] = iscsi.SaiReportTargetPortGroups
rtpg[9] = 16
status, data = cli.scsiCmd(t, rtpg, nil, 16)
expectGood(t, status, "standby RTPG")
if got := iscsi.ALUAState(data[4] & 0x0f); got != iscsi.ALUAStandby {
t.Fatalf("RTPG ALUA state=%s want %s", got, iscsi.ALUAStandby)
}
status, _ = cli.scsiCmd(t, writeCDB10(0, 1), make([]byte, 512), 0)
expectCheckCondition(t, status, "standby write")
if probeBackend.WriteCount() != 0 {
t.Fatalf("standby write reached backend; writes=%d", probeBackend.WriteCount())
}
}
+86 -31
View File
@@ -34,11 +34,13 @@ const (
ScsiSyncCache16 uint8 = 0x91
ScsiServiceActionIn16 uint8 = 0x9e
ScsiReportLuns uint8 = 0xa0
ScsiMaintenanceIn uint8 = 0xa3
)
// Service Action codes for SERVICE ACTION IN(16) opcode 0x9e.
// Service Action codes used by supported SCSI service-action commands.
const (
SaiReadCapacity16 uint8 = 0x10
SaiReadCapacity16 uint8 = 0x10
SaiReportTargetPortGroups uint8 = 0x0a
)
// Fixed block size for the T2 contract backend. Real volumes
@@ -102,6 +104,7 @@ type SCSIHandler struct {
vendorID string // 8 bytes
productID string // 16 bytes
serialNo string
alua ALUAProvider
}
// HandlerConfig configures an SCSIHandler. Zero values pick
@@ -113,6 +116,7 @@ type HandlerConfig struct {
VendorID string
ProductID string
SerialNo string
ALUA ALUAProvider
}
// NewSCSIHandler constructs a handler. Backend MUST be non-nil.
@@ -150,6 +154,7 @@ func NewSCSIHandler(cfg HandlerConfig) *SCSIHandler {
vendorID: vendor,
productID: product,
serialNo: cfg.SerialNo,
alua: cfg.ALUA,
}
}
@@ -188,8 +193,14 @@ func (h *SCSIHandler) HandleCommand(ctx context.Context, cdb [16]byte, dataOut [
case ScsiReadCapacity10:
return h.readCapacity10()
case ScsiRead10:
if r := h.aluaDataReject("read"); r != nil {
return *r
}
return h.read10(ctx, cdb)
case ScsiWrite10:
if r := h.aluaDataReject("write"); r != nil {
return *r
}
return h.write10(ctx, cdb, dataOut)
// T3b wire: SYNCHRONIZE_CACHE(10) / (16) dispatches to
// Backend.Sync(ctx). Durable backends flush the WAL; memback
@@ -198,6 +209,9 @@ func (h *SCSIHandler) HandleCommand(ctx context.Context, cdb [16]byte, dataOut [
// rule §3.6 (error-faithful Sync wire) makes data-integrity
// hazards visible to the host.
case ScsiSyncCache10, ScsiSyncCache16:
if r := h.aluaDataReject("sync"); r != nil {
return *r
}
log.Printf("iscsi: SCSI SYNCHRONIZE_CACHE handler entry opcode=0x%02x", cdb[0])
if err := h.backend.Sync(ctx); err != nil {
log.Printf("iscsi: SCSI SYNCHRONIZE_CACHE backend.Sync FAILED: %v", err)
@@ -213,8 +227,14 @@ func (h *SCSIHandler) HandleCommand(ctx context.Context, cdb [16]byte, dataOut [
return SCSIResult{Status: StatusGood}
// Batch 10.5: 16-byte data variants (64-bit LBA).
case ScsiRead16:
if r := h.aluaDataReject("read"); r != nil {
return *r
}
return h.read16(ctx, cdb)
case ScsiWrite16:
if r := h.aluaDataReject("write"); r != nil {
return *r
}
return h.write16(ctx, cdb, dataOut)
case ScsiServiceActionIn16:
sa := cdb[1] & 0x1f
@@ -225,6 +245,8 @@ func (h *SCSIHandler) HandleCommand(ctx context.Context, cdb [16]byte, dataOut [
fmt.Sprintf("unsupported SAI16 service action 0x%02x", sa))
case ScsiReportLuns:
return h.reportLuns(cdb)
case ScsiMaintenanceIn:
return h.maintenanceIn(cdb)
default:
return illegalRequest(ASCInvalidOpcode, 0x00, fmt.Sprintf("unsupported opcode 0x%02x", cdb[0]))
}
@@ -325,18 +347,21 @@ func (h *SCSIHandler) requestSense(cdb [16]byte) SCSIResult {
// response (PM Medium finding 2026-04-22).
//
// Key V2 parity bytes we now emit:
// byte 4 = 91 Additional length (96 - 5)
// byte 7 = 0x02 CmdQue=1 — command queuing supported
// bytes 8-15 Vendor ID, 8 bytes, space-padded
// bytes 16-31 Product ID, 16 bytes, space-padded
// bytes 32-35 Product revision "0001"
// bytes 36-95 Reserved / zero
//
// Skip list compliance (ports plan §3.2):
// byte 5 bit 4 (TPGS implicit) — NOT set (ALUA is skip-list)
// byte 6 / other tuning bits — zero (V2 sets some for
// enclosure/multiPort/vendor-specific; T2 has no reason
// to advertise them)
// byte 4 = 91 Additional length (96 - 5)
// byte 7 = 0x02 CmdQue=1 — command queuing supported
// bytes 8-15 Vendor ID, 8 bytes, space-padded
// bytes 16-31 Product ID, 16 bytes, space-padded
// bytes 32-35 Product revision "0001"
// bytes 36-95 Reserved / zero
//
// ALUA discipline:
//
// byte 5 bit 4 (TPGS implicit) is set only when HandlerConfig.ALUA is
// present and REPORT TARGET PORT GROUPS is served.
// byte 6 / other tuning bits stay zero (V2 sets some for
// enclosure/multiPort/vendor-specific; T2 has no reason
// to advertise them)
//
// NOTE: the prior 36-byte minimal response still worked for
// iscsiadm attach, but under-advertised CmdQue and forced the
@@ -359,7 +384,11 @@ func (h *SCSIHandler) inquiry(cdb [16]byte) SCSIResult {
data[2] = 0x06 // Version: SPC-4
data[3] = 0x02 // Response data format (SPC-2+)
data[4] = 91 // Additional length (96 - 5)
// byte 5: SCCS / ACC / TPGS / 3PC — all zero in T2 (no ALUA)
// byte 5: SCCS / ACC / TPGS / 3PC. TPGS is enabled only when
// an ALUA provider is configured and REPORT TPG is served.
if h.alua != nil {
data[5] = 0x10 // TPGS=01b, implicit ALUA
}
// byte 6: reserved / EncServ / VS / MultiP — zero
data[7] = 0x02 // BQue=0, CmdQue=1
copy(data[8:16], padRight(h.vendorID, 8))
@@ -372,9 +401,9 @@ func (h *SCSIHandler) inquiry(cdb [16]byte) SCSIResult {
return SCSIResult{Status: StatusGood, Data: data}
}
// Batch 10.5: INQUIRY VPD. Approved pages: 0x00 (supported list),
// 0x80 (unit serial number), 0x83 (device identification, non-ALUA
// branch only). VPD 0xB0 / 0xB2 are explicitly NOT implemented
// Batch 10.5 / P6: INQUIRY VPD. Approved pages: 0x00 (supported list),
// 0x80 (unit serial number), 0x83 (device identification). VPD 0xB0 / 0xB2
// are explicitly NOT implemented
// and NOT advertised (port plan §3.3 N3 — advertised list must
// match implemented set or kernel logs errors on every probe).
func (h *SCSIHandler) inquiryVPD(pageCode uint8, allocLen uint16) SCSIResult {
@@ -418,7 +447,7 @@ func (h *SCSIHandler) inquiryVPD(pageCode uint8, allocLen uint16) SCSIResult {
}
return SCSIResult{Status: StatusGood, Data: data}
case 0x83: // Device Identification (non-ALUA branch only)
case 0x83: // Device Identification
return h.inquiryVPD83(allocLen)
default:
@@ -427,20 +456,19 @@ func (h *SCSIHandler) inquiryVPD(pageCode uint8, allocLen uint16) SCSIResult {
}
}
// inquiryVPD83 emits ONE NAA-6 Registered Extended designator
// derived from the volume identity. V2 has an ALUA branch (TPG /
// RTP descriptors); that's skipped in Batch 10.5 (ALUA is
// skip-list). V2's fallback stub NAA was a hardcoded constant —
// unusable for T2 because all volumes would report the same
// unique ID and Linux multipath / udev would conflate them
// (port plan §3.3 N1). Instead we derive a per-volume NAA from
// sha256(VolumeID)[:7] prefixed with 0x60 (NAA-6).
// inquiryVPD83 emits an NAA-6 Registered Extended designator derived from
// the volume identity. When HandlerConfig.ALUA is present, it also emits the
// target port group and relative target port designators needed by
// multipath. Without ALUA, it preserves the single-descriptor VPD 0x83 shape.
func (h *SCSIHandler) inquiryVPD83(allocLen uint16) SCSIResult {
// Designator 1: NAA-6 identifier (8 bytes). Derive from the
// frontend.Backend's captured VolumeID — stable across the
// backend's lifetime and the only authoritative identity
// the handler has access to (no extra config threading).
// backend's lifetime. ALUA providers may override it with the
// frontend path's explicit device identity.
naa := naaFromVolumeID(h.backend.Identity().VolumeID)
if h.alua != nil {
naa = h.alua.DeviceNAA()
}
naaDesc := []byte{
0x01, // code set = binary
0x03, // PIV=0, association=00 (logical unit), type=3 (NAA)
@@ -449,11 +477,31 @@ func (h *SCSIHandler) inquiryVPD83(allocLen uint16) SCSIResult {
}
naaDesc = append(naaDesc, naa[:]...)
data := make([]byte, 4+len(naaDesc))
descs := make([]byte, 0, 28)
descs = append(descs, naaDesc...)
if h.alua != nil {
const (
vpdCodeSetBinary = 0x01
vpdAssociationTarget = 0x10
vpdDesignatorTypeRTP = 0x04
vpdDesignatorTypeTPG = 0x05
vpdDesignatorIdentifier = 0x04
)
tpgID := h.alua.TargetPortGroupID()
rtpID := h.alua.RelativeTargetPortID()
descs = append(descs,
vpdCodeSetBinary, vpdAssociationTarget|vpdDesignatorTypeTPG, 0x00, vpdDesignatorIdentifier,
0x00, 0x00, byte(tpgID>>8), byte(tpgID),
vpdCodeSetBinary, vpdAssociationTarget|vpdDesignatorTypeRTP, 0x00, vpdDesignatorIdentifier,
0x00, 0x00, byte(rtpID>>8), byte(rtpID),
)
}
data := make([]byte, 4+len(descs))
data[0] = 0x00
data[1] = 0x83
binary.BigEndian.PutUint16(data[2:4], uint16(len(naaDesc)))
copy(data[4:], naaDesc)
binary.BigEndian.PutUint16(data[2:4], uint16(len(descs)))
copy(data[4:], descs)
if int(allocLen) < len(data) {
data = data[:allocLen]
}
@@ -466,6 +514,13 @@ func (h *SCSIHandler) inquiryVPD83(allocLen uint16) SCSIResult {
// sha256(VolumeID) truncated to fit. Deterministic (same VolumeID
// → same NAA across process restarts) and collision-free for
// realistic volume counts (T2 single-volume is trivially safe).
//
// Note: SPC-4 §7.6.6 specifies NAA-6 (Registered Extended) as a
// 16-byte designator; this helper produces 8 bytes, which is
// formally NAA-5 (Registered) shape with NAA-6 prefix. Linux
// multipathd accepts it and the existing T2 tests pin this exact
// shape; widening to a true 16-byte NAA-6 is tracked separately
// from the RTPG offset fix and is not part of this change.
func naaFromVolumeID(volumeID string) [8]byte {
sum := sha256.Sum256([]byte(volumeID))
var out [8]byte
+51 -13
View File
@@ -17,6 +17,7 @@ package iscsi
import (
"context"
"errors"
"fmt"
"io"
"net"
@@ -83,9 +84,10 @@ type Session struct {
// only. provider + volumeID + hcfg are captured at session
// construction; the session calls provider.Open() after
// login succeeds and builds the SCSIHandler then.
provider frontend.Provider
volumeID string
hcfg HandlerConfig
provider frontend.Provider
probeProvider ProbeBackendProvider
volumeID string
hcfg HandlerConfig
// backend holds the opened backend so serve() can Close it
// on exit. nil for Discovery sessions.
backend frontend.Backend
@@ -111,7 +113,7 @@ type Logger interface {
// provider + volumeID + hcfg are captured for post-login,
// Normal-session-only backend open (residual-risk fix). The
// backend is NOT opened at construction.
func newSession(conn net.Conn, provider frontend.Provider, volumeID string, hcfg HandlerConfig, negCfg NegotiableConfig, dataOutTimeout time.Duration, resolver TargetResolver, lister TargetLister, logger Logger) *Session {
func newSession(conn net.Conn, provider frontend.Provider, probeProvider ProbeBackendProvider, volumeID string, hcfg HandlerConfig, negCfg NegotiableConfig, dataOutTimeout time.Duration, resolver TargetResolver, lister TargetLister, logger Logger) *Session {
return &Session{
conn: conn,
logger: logger,
@@ -121,6 +123,7 @@ func newSession(conn net.Conn, provider frontend.Provider, volumeID string, hcfg
resolver: resolver,
lister: lister,
provider: provider,
probeProvider: probeProvider,
volumeID: volumeID,
hcfg: hcfg,
}
@@ -138,16 +141,9 @@ func (s *Session) serve(ctx context.Context) error {
// need SendTargets, which comes from the TargetLister that
// was wired at construction.
if s.negResult.SessionType == SessionTypeNormal {
backend, err := s.provider.Open(ctx, s.volumeID)
backend, err := s.openBackendForNormalSession(ctx)
if err != nil {
// Clean close — do NOT hold the socket. A parallel
// discovery attempt on the listen addr must still
// make progress.
if s.logger != nil {
s.logger.Printf("iscsi: Provider.Open(%s): %v (closing Normal session)",
s.volumeID, err)
}
return fmt.Errorf("provider open: %w", err)
return err
}
s.backend = backend
hcfg := s.hcfg
@@ -158,6 +154,48 @@ func (s *Session) serve(ctx context.Context) error {
return s.fullFeatureLoop(ctx)
}
func (s *Session) openBackendForNormalSession(ctx context.Context) (frontend.Backend, error) {
backend, err := s.provider.Open(ctx, s.volumeID)
if err == nil {
return backend, nil
}
if probeBackend, ok := s.tryProbeBackend(ctx, err); ok {
return probeBackend, nil
}
// Clean close — do NOT hold the socket. A parallel discovery attempt on
// the listen addr must still make progress.
if s.logger != nil {
s.logger.Printf("iscsi: Provider.Open(%s): %v (closing Normal session)",
s.volumeID, err)
}
return nil, fmt.Errorf("provider open: %w", err)
}
func (s *Session) tryProbeBackend(ctx context.Context, openErr error) (frontend.Backend, bool) {
if s.probeProvider == nil || !errors.Is(openErr, frontend.ErrNotReady) {
return nil, false
}
alua := s.hcfg.ALUA
if alua == nil {
return nil, false
}
switch alua.ALUAState() {
case ALUAActiveOptimized, ALUAActiveNonOptimized:
return nil, false
}
backend, err := s.probeProvider.ProbeBackend(ctx, s.volumeID)
if err != nil {
if s.logger != nil {
s.logger.Printf("iscsi: ProbeBackend(%s): %v", s.volumeID, err)
}
return nil, false
}
if s.logger != nil {
s.logger.Printf("iscsi: Provider.Open(%s): %v; using ALUA metadata probe backend", s.volumeID, openErr)
}
return backend, true
}
func (s *Session) loginPhase() error {
neg := NewLoginNegotiator(s.negCfg)
for s.state == SessionLogin {
+16 -1
View File
@@ -20,6 +20,13 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend"
)
// ProbeBackendProvider supplies a borrowed backend for metadata-only ALUA path
// probing when the write-ready Provider.Open path is not available. The backend
// must still fail data I/O closed through its own readiness/lineage gates.
type ProbeBackendProvider interface {
ProbeBackend(ctx context.Context, volumeID string) (frontend.Backend, error)
}
// TargetConfig configures a Target.
type TargetConfig struct {
// Listen is the TCP address the Target binds on.
@@ -43,6 +50,14 @@ type TargetConfig struct {
// Provider supplies the frontend.Backend each session uses.
Provider frontend.Provider
// ProbeProvider is optional. If a Normal-session Provider.Open returns
// frontend.ErrNotReady and ALUA reports a non-active path, the session may
// use this borrowed backend to answer metadata/path-probing commands
// (INQUIRY, VPD, RTPG, capacity). Writes remain rejected by ALUA and the
// backend's own readiness gates. Nil preserves the historical close-on-open
// failure behavior.
ProbeProvider ProbeBackendProvider
// Backend handler config (block size, volume size, INQUIRY
// vendor/product strings). Optional — zero values get the
// T2 defaults from HandlerConfig.
@@ -205,7 +220,7 @@ func (t *Target) handleConn(conn net.Conn) {
// it should at least return SendTargets. The session opens
// the backend after login succeeds, and only for Normal
// sessions.
sess := newSession(conn, t.cfg.Provider, t.cfg.VolumeID, t.cfg.Handler,
sess := newSession(conn, t.cfg.Provider, t.cfg.ProbeProvider, t.cfg.VolumeID, t.cfg.Handler,
t.cfg.Negotiation, t.cfg.DataOutTimeout, t, t, t.logger)
if err := sess.serve(ctx); err != nil && !errors.Is(err, net.ErrClosed) {
t.logger.Printf("iscsi: session error (%s): %v", conn.RemoteAddr(), err)
@@ -0,0 +1,68 @@
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: sw-block-dynamic
provisioner: block.csi.seaweedfs.com
volumeBindingMode: Immediate
allowVolumeExpansion: false
parameters:
replicationFactor: "1"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: sw-block-demo-pvc
namespace: default
spec:
accessModes:
- ReadWriteOnce
storageClassName: sw-block-dynamic
resources:
requests:
storage: 1Mi
---
apiVersion: v1
kind: Pod
metadata:
name: sw-block-demo-writer
namespace: default
spec:
restartPolicy: Never
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: busybox:1.36
securityContext:
runAsNonRoot: true
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
seccompProfile:
type: RuntimeDefault
command:
- /bin/sh
- -c
- |
set -eu
echo "[app-writer] writing through PVC mounted at /data"
dd if=/dev/urandom of=/data/demo.bin bs=4096 count=1
sha256sum /data/demo.bin > /data/demo.sha256
sync
sha256sum -c /data/demo.sha256
echo "[app-writer] wrote and verified /data/demo.bin"
echo "[app-writer] holding pod so CSI node restart happens while PVC is mounted"
sleep 3600
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: sw-block-demo-pvc
+127 -28
View File
@@ -11,6 +11,8 @@ References:
- `ref/iscsi-v2-coverage-gap-audit.md`
- `ref/iscsi-os-initiator-compat-plan.md`
- `ref/v2-frontend-protocol-gap-audit.md`
- `ref/iscsi-p6-alua-mpio-design.md`
- `ref/iscsi-alua-technical-note.md`
## Product Goal
@@ -34,12 +36,12 @@ References:
- includes RX/TX stability tests, large write memory tests, OS smoke script,
loop mode, stress mode, TestOps registry entry, and sustained sync smoke.
- iSCSI-P2 supplemental session guards:
- status: local on `iscsi/frontend-completeness`, pending milestone PR.
- status: done in PR #41.
- includes rapid login/logout goroutine budget, concurrent target close
idempotency, target same-address restart, and NOP-Out queued during
Data-Out.
- iSCSI-P3 attach/detach loop tooling:
- status: local on `iscsi/frontend-completeness`, pending milestone PR.
- status: done in PR #41.
- includes `scripts/run-k8s-attach-detach-loop.sh` and TestOps registry
scenario `iscsi-p3-attach-detach-loop`.
- iSCSI-P2/P3 lab validation:
@@ -59,6 +61,10 @@ References:
- Owner-reference alpha default:
- status: done in PR #40.
- relevant to K8s cleanup and alpha install flow.
- iSCSI-P4 CHAP / Access Control:
- status: done in PR #41.
- includes target-side CHAP, CSI node CHAP, Kubernetes Secret wiring, and
QA evidence.
## Recently Closed Milestone: iSCSI-P2 Stability
@@ -71,8 +77,7 @@ References:
- Tasks:
- add RX/TX stability test pack:
- status: done in PR #26.
- supplemental guards: local on `iscsi/frontend-completeness`, pending
milestone PR.
- supplemental guards: done in PR #41.
- rapid login/logout without goroutine leak,
- many concurrent sessions,
- target close while I/O is active,
@@ -122,8 +127,7 @@ References:
behavior, not only protocol fakes.
- Tasks:
- status: QA green on `iscsi/frontend-completeness@e7c95ee`, pending
milestone PR.
- status: done in PR #41.
- sustained write/read through mounted filesystem,
- `SYNCHRONIZE_CACHE` pressure,
- multiple sessions sharing a volume if supported,
@@ -148,16 +152,15 @@ References:
- default loop count comes from `SW_BLOCK_ATTACH_DETACH_ITERATIONS`.
- #QA status: PASS on M02, 3 iterations.
## Current Active Milestone: iSCSI-P4 CHAP / Access Control
## Recently Closed Milestone: iSCSI-P4 CHAP / Access Control
- Goal:
- reach V2-level iSCSI auth behavior before any security-facing claim.
- Tasks:
- status: QA green on `iscsi/frontend-completeness@9a1fe07`, pending
milestone PR.
- status: done in PR #41.
- target-side CHAP login negotiation:
- status: local implementation + unit tests.
- status: done in PR #41.
- direct LoginOp is rejected when CHAP is required,
- `AuthMethod=None` is rejected when CHAP is required,
- target emits CHAP MD5 challenge,
@@ -165,7 +168,7 @@ References:
- wrong response fails closed,
- missing `CHAP_R` fails closed.
- `cmd/blockvolume` opt-in flags:
- status: local implementation + parse tests.
- status: done in PR #41.
- `--iscsi-chap-username`,
- `--iscsi-chap-secret`,
- flags require `--iscsi-listen`,
@@ -179,7 +182,7 @@ References:
- CSI node consumes CHAP credentials from `NodeStageVolumeRequest.Secrets`,
- controller publish path must not copy CHAP secrets into `publish_context`,
- node configures `iscsiadm` CHAP settings after discovery and before login.
- launcher can render target-side CHAP args from a Kubernetes Secret,
- launcher can render target-side CHAP env vars from a Kubernetes Secret,
- alpha runner can create the Secret and inject StorageClass
node-stage secret refs.
- replayed challenge rejected if supported by the protocol path,
@@ -199,13 +202,15 @@ References:
- default non-CHAP regression PASS on M02.
- V2 CHAP tests are the reference coverage inventory.
## Milestone: iSCSI-P5 CSI Node Lifecycle
## Recently Closed Milestone: iSCSI-P5 CSI Node Lifecycle
- Goal:
- make kubelet retry/restart behavior safe enough for real clusters.
- Tasks:
- status: active on `iscsi/frontend-completeness`.
- status: QA green on `iscsi/csi-node-lifecycle@4ee35c0`.
- local CSI node lifecycle guards:
- status: done in PR #41.
- NodeStage idempotency,
- mounted staging path must belong to the same volume,
- mounted staging path for another volume fails closed.
@@ -225,6 +230,11 @@ References:
- local 3-cycle stage/unstage test leaves no staged state,
`.volume`, or `.transport`.
- wrong volume at staging path fails closed.
- #QA CSI node restart while PVC remains,
- script prepared: `scripts/run-k8s-csi-node-restart.sh`,
- TestOps scenario prepared: `iscsi-p5-csi-node-restart`,
- assignment: `internal/docs/qa-assignments/iscsi-p5-csi-node-lifecycle-validation.md`,
- status: QA PASS on M02.
- Close bar:
- kubelet retries do not wedge the node plugin,
@@ -232,30 +242,118 @@ References:
- repeated create/delete works without manual host cleanup.
- QA/tooling:
- #QA needs K8s scenario scripts or TestOps entries.
- #QA status: PASS on M02.
- manual kubelet poking is allowed only for first reproduction.
## Milestone: iSCSI-P6 ALUA / MPIO / Mounted Failover
## Recently Closed Milestone: iSCSI-P6 ALUA / MPIO / Mounted Failover
- Goal:
- make mounted-volume failover a real frontend behavior instead of only a
reconnect story.
- Tasks:
- status: planned.
- status: completed in PR #42 scope; QA green on
`iscsi/csi-node-lifecycle@d1025f1`.
- #design(iscsi-p6-alua-mpio-design) ALUA/MPIO policy and protocol shape:
- owner: dev.
- output: `internal/docs/ref/iscsi-p6-alua-mpio-design.md`.
- must be reviewed before changing protocol behavior.
- #design(iscsi-p6-qa-assignment) real initiator validation shape:
- owner: dev.
- output: `internal/docs/qa-assignments/iscsi-p6-alua-mpio-lab-validation.md`.
- must define the lab command, non-claims, and pass/fail criteria.
- V2 coverage alignment:
- status: design inventory added.
- do not copy V2 role/state ownership,
- do match V2 externally visible ALUA/MPIO protocol coverage unless V3
explicitly rejects a behavior.
- ALUA state model:
- active,
- status: local protocol slice done on `iscsi/csi-node-lifecycle`.
- active optimized,
- active non-optimized,
- standby,
- unavailable,
- transitioning.
- standby metadata commands allowed,
- standby write/read policy pinned,
- REPORT TARGET PORT GROUPS,
- VPD 0x83 target-port identity,
- state change while I/O is in flight,
- multipath initiator test,
- primary failover while mounted,
- old primary cannot serve stale successful I/O.
- standby command policy:
- status: local protocol slice done.
- metadata/path probing allowed,
- READ allowed for initiator path probing,
- WRITE and SYNCHRONIZE_CACHE fail closed.
- standard INQUIRY TPGS discipline:
- status: local protocol slice done.
- TPGS stays off until REPORT TARGET PORT GROUPS and ALUA VPD identity
are implemented,
- when enabled, advertise implicit ALUA only unless explicit transitions
are implemented.
- REPORT TARGET PORT GROUPS:
- status: local protocol slice done.
- no-provider rejection,
- short allocation truncation,
- five-state reporting.
- VPD 0x83 target-port identity:
- status: local protocol slice done.
- NAA stable per volume,
- target port group and relative target port distinguish paths,
- short allocation length and no-ALUA branches tested.
- VPD 0x00 remains advertised-pages-equal-implemented-pages:
- status: local protocol slice done.
- state change while I/O is in flight:
- status: local protocol state-change test done.
- concurrent REPORT TARGET PORT GROUPS and standby write reject tests:
- status: pending.
- frontend state provider wiring:
- status: local P6-C slice done on `iscsi/csi-node-lifecycle`.
- connect ALUA provider to current V3 frontend facts without importing
authority or placement.
- mapping:
- frontend Healthy => active optimized,
- locally healthy but superseded/non-writable => standby,
- recovering => transitioning,
- idle supporting path => standby for metadata/path probing,
- degraded/identity mismatch => unavailable.
- path identity:
- NAA is stable per volume,
- target port group and relative target port are stable per
volume/replica path.
- multipath initiator test:
- status: QA green on `iscsi/csi-node-lifecycle@88e9301`.
- script: `scripts/run-iscsi-alua-os-smoke.sh`.
- script: `scripts/run-iscsi-alua-multipath-smoke.sh`.
- assignment: `internal/docs/qa-assignments/iscsi-p6-alua-mpio-lab-validation.md`.
- current claim: one active path reports ALUA through real Linux `sg_inq`
and `sg_rtpg`, then completes mkfs/mount/checksum/logout.
- current two-path claim: two iSCSI portals for one volume can be logged
in by Linux, report active/standby ALUA state, reject standby WRITE,
and appear as one logical device in `multipath -ll`.
- standby/probe session prerequisite: local P6-D slice implemented.
Non-active ALUA paths may use a borrowed metadata backend after
`Provider.Open` returns not-ready, so Linux can probe INQUIRY/VPD/RTPG
without allowing writes.
- #QA Test 1B PASS on M02:
- artifact:
`/mnt/smb/work/share/g15d-k8s/20260506T093732Z-iscsi-p6-alua-mpath-fix`.
- evidence: two iSCSI paths, common NAA, distinct TPG/RTP, r1
active/optimized, r2 standby, standby WRITE rejected, `multipath -ll`
grouped both paths under `mpatha`.
- non-claim: mounted workload failover still needs P6-E.
- primary failover while mounted:
- status: QA green on `iscsi/csi-node-lifecycle@d1025f1`.
- script: `scripts/run-iscsi-alua-mounted-failover-smoke.sh`.
- assignment: `internal/docs/qa-assignments/iscsi-p6-alua-mpio-lab-validation.md`.
- verified claim: mounted Linux multipath device can read a
pre-failover checksum and write a post-failover checksum after r1 is
killed and r2 reaches `Healthy=true` at a newer epoch.
- #QA Test 2 PASS on M02:
- artifact:
`/mnt/smb/work/share/g15d-k8s/20260506T094503Z-iscsi-p6-mounted-failover`.
- evidence: `/dev/mapper/mpatha` mounted, pre-failover checksum read
after failover, post-failover checksum written and verified, r2
promoted to `Epoch=2`, old r1 gate-rejected stale writes/syncs, no
active sessions or multipath residue after cleanup.
- old primary cannot serve stale successful I/O:
- status: QA green for killed-old-primary path on `d1025f1`.
- old-primary-return proof remains future soak/fault coverage, not required
for P6 alpha close.
- Close bar:
- real initiator sees correct ALUA/MPIO behavior,
@@ -265,8 +363,9 @@ References:
- no stale-primary success.
- QA/tooling:
- #QA needs real initiator multipath setup script.
- #QA needs mounted workload failover script.
- #QA active-path ALUA OS script is ready.
- #QA two-path multipath script is green on M02.
- #QA mounted multipath failover script is green on M02.
- do not rely on in-process protocol tests only.
## Milestone: iSCSI-P7 Performance And Backend Matrix
@@ -65,9 +65,12 @@ This is the short internal roadmap. Keep it current and readable.
### Track B: iSCSI Frontend Stability
- Current: OS initiator correctness, session stability, product-backed K8s
fio/attach-detach, and CHAP are implemented and evidenced.
- Next: CSI lifecycle and restart behavior.
- Later: ALUA/MPIO and mounted failover.
fio/attach-detach, CHAP, CSI node restart, ALUA/MPIO, and mounted failover
are implemented and evidenced in PR #42.
- Next: backend comparison and repeatability evidence for regular WAL versus
smartwal.
- Later: larger compatibility coverage across host distros and initiator
versions.
### Track C: Durable State
@@ -0,0 +1,84 @@
# QA Assignment: iSCSI P5 CSI Node Lifecycle Validation
Status: QA green.
Branch: `iscsi/csi-node-lifecycle`.
Verified commit: `4ee35c065f257f0097917eb372deacff646f426f`.
Scope: Kubernetes CSI node restart while a writer pod is holding the PVC mount,
then replacement app pod reads the same PVC.
## QA Result
- Result: PASS.
- Host: M02 or equivalent Linux Kubernetes lab node.
- Artifact:
`[artifact-root]/20260505T231321Z-iscsi-p5-csi-node-restart`.
- Final line:
`[app-demo] PASS: app pod wrote data, replacement app pod read it back through the same PVC, cleanup complete`.
- `restart-csi-node-status.log` shows the `sw-block-csi-node` DaemonSet rolled
out after a real pod replacement.
- `writer.log` and `reader.log` both contain `/data/demo.bin: OK`.
- Cleanup: no sw-block iSCSI sessions, no PVC residue, no generated
`sw-blockvolume` Deployment.
## What This Verifies
- The app writer pod can write and verify data through a dynamic PVC.
- `sw-block-csi-node` can be restarted while the writer pod keeps the PVC
mounted.
- The writer pod can be deleted after the CSI node restart.
- A replacement reader pod can mount the same PVC and verify the existing data.
- Cleanup leaves no sw-block iSCSI sessions, PVCs, pods, or generated
blockvolume Deployment.
## Preconditions
- Linux Kubernetes lab node with k3s/kubectl, Docker, `iscsiadm`, and
loadable `iscsi_tcp`.
- Local images built from the same branch:
```bash
bash scripts/build-alpha-images.sh "$PWD"
```
## Test 1: CSI Node Restart Between Writer And Reader
```bash
RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)-iscsi-p5-csi-node-restart"
SW_BLOCK_ARTIFACT_DIR="/tmp/sw-block-artifacts/$RUN_ID" \
bash scripts/run-k8s-csi-node-restart.sh "$PWD"
```
Expected:
- run log includes `restart_csi_node_before_reader=1`.
- run log includes `demo-app-pvc-writer-hold.yaml`.
- `writer.log` includes `holding pod so CSI node restart happens while PVC is mounted`.
- `restart-csi-node-status.log` shows the DaemonSet rollout completed.
- `writer.log` contains `/data/demo.bin: OK`.
- `reader.log` contains `/data/demo.bin: OK`.
- final line contains:
`[app-demo] PASS: app pod wrote data, replacement app pod read it back through the same PVC, cleanup complete`.
- `iscsi-sessions.after-delete.txt` contains no `iqn.2026-05.io.seaweedfs`.
- no generated `sw-blockvolume` Deployment remains.
## Report Format
QA should report:
- branch and commit SHA,
- host and kernel,
- exact command,
- result,
- artifact path,
- final PASS line,
- `restart-csi-node-status.log`,
- writer and reader checksum lines,
- cleanup state,
- any CSI node, kubelet, or iSCSI errors.
## Non-Claims
- No blockvolume process restart durability claim.
- No mounted failover claim.
- No ALUA, MPIO, NVMe, or multi-node claim.
- No performance claim.
@@ -0,0 +1,197 @@
# QA Assignment: iSCSI P6 ALUA / MPIO Lab Validation
Status: Test 1B and Test 2 QA green.
Branch: `iscsi/csi-node-lifecycle`.
Scope: real Linux initiator validation for ALUA/MPIO and mounted failover.
## Preconditions
- Linux initiator host with:
- `open-iscsi`,
- `multipath-tools`,
- `sg3_utils` or equivalent tools for `sg_inq` and `sg_rtpg`,
- `mkfs.ext4`,
- `mount`,
- `fio` or `dd`,
- sudo access.
- Target host or Kubernetes lab capable of exposing two iSCSI paths for the
same volume.
- P6-B/P6-C implementation must be present before execution.
## Test 1: ALUA Discovery And Active Path Identity
Status: ready.
Run:
```bash
RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)-iscsi-p6-alua-active"
SW_BLOCK_ARTIFACT_DIR="/mnt/smb/work/share/g15d-k8s/${RUN_ID}" \
bash scripts/run-iscsi-alua-os-smoke.sh "$PWD"
```
Expected:
- initiator discovers and logs into the V3 iSCSI target.
- standard INQUIRY shows TPGS enabled.
- VPD 0x00 still advertises only implemented pages.
- VPD 0x83 identity is stable and path-distinguishing:
- NAA is present,
- target port group and relative target port descriptors are present.
- REPORT TARGET PORT GROUPS returns active/optimized for the current path.
- `mkfs.ext4`, mount, checksum write/read, logout, and cleanup succeed.
- final `iscsiadm -m session` shows no active sw-block session.
Evidence to collect:
- `iscsiadm -m discovery` output.
- `iscsiadm -m session -P 3` output.
- `sg_inq <device>` standard INQUIRY output.
- `sg_inq -p 0x00 <device>` supported VPD pages.
- `sg_inq -p 0x83 <device>` device identification.
- `sg_rtpg <device>` or equivalent REPORT TARGET PORT GROUPS output.
- checksum output.
- final session cleanup.
Non-claim:
- Test 1 does not prove Linux `multipathd` grouping yet.
- Test 1 does not prove standby path login or mounted failover yet.
## Test 1B: Two-Path Multipath Identity
Status: PASS on `iscsi/csi-node-lifecycle@88e9301`.
Run:
```bash
RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)-iscsi-p6-alua-mpath" \
SW_BLOCK_ARTIFACT_DIR="/mnt/smb/work/share/g15d-k8s/${RUN_ID}" \
bash scripts/run-iscsi-alua-multipath-smoke.sh "$PWD"
```
Expected:
- initiator discovers two target paths for one volume.
- `multipath -ll` shows one logical device.
- standard INQUIRY / VPD 0x83 / REPORT TARGET PORT GROUPS can be queried
through both paths.
- one path reports active/optimized.
- one path reports standby.
- VPD 0x83 exposes volume identity plus target-port identity for each path.
- standby path does not accept normal WRITE as GOOD.
- cleanup leaves no sw-block iSCSI sessions.
QA evidence:
- host: M02, Ubuntu 24.04.3 LTS, kernel 6.17.0-22-generic.
- artifact:
`/mnt/smb/work/share/g15d-k8s/20260506T093732Z-iscsi-p6-alua-mpath-fix`.
- final line:
`[iscsi-mpath] PASS: two iSCSI paths report ALUA and multipath groups one logical device`.
- wire proof:
- common NAA: `36bfc269594ef6492`.
- r1: TPG `0x9866`, RTP `0x6b22`, AAS `0x00`.
- r2: TPG `0xf866`, RTP `0xdff0`, AAS `0x02`.
- `multipath -ll`: `mpatha` contains both `sda` and `sdb` with
`hwhandler='1 alua'`.
- standby path raw WRITE returned I/O error.
- cleanup left no active iSCSI sessions.
Evidence to collect:
- two-path `iscsiadm -m session -P 3`.
- `multipath -ll`.
- `sg_inq -p 0x83` from each path.
- `sg_rtpg` from each path.
- standby write rejection evidence.
- final `iscsiadm -m session`.
Non-claim:
- Test 1B does not prove mounted workload failover.
- Test 1B does not prove Windows MPIO.
- Test 1B does not prove primary movement while the filesystem is mounted.
## Test 2: Mounted Workload Failover
Status: PASS on `iscsi/csi-node-lifecycle@d1025f1`.
Run:
```bash
RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)-iscsi-p6-mounted-failover" \
SW_BLOCK_ARTIFACT_DIR="/mnt/smb/work/share/g15d-k8s/${RUN_ID}" \
bash scripts/run-iscsi-alua-mounted-failover-smoke.sh "$PWD"
```
Expected:
- workload starts on mounted multipath device.
- active path failure triggers authority movement to the replica path.
- authority moves only after data-continuity prerequisites are met.
- final read-back is byte-equal.
- old primary path cannot acknowledge stale successful I/O.
- cleanup leaves no sw-block iSCSI sessions and no multipath residue.
QA evidence:
- host: M02, Ubuntu 24.04.3 LTS, kernel 6.17.0-22-generic.
- artifact:
`/mnt/smb/work/share/g15d-k8s/20260506T094503Z-iscsi-p6-mounted-failover`.
- final line:
`[iscsi-failover] PASS: mounted multipath workload read/wrote through r1->r2 failover`.
- wire proof:
- before failover: r1 AAS `0x00`, r2 AAS `0x02`.
- after killing r1: r2 AAS `0x00`.
- `multipath -ll`: same `mpatha` map served the mounted filesystem.
- r2 status after failover: `Epoch=2`, `AuthorityRole=primary`,
`Healthy=true`, `FrontendPrimaryReady=true`.
- pre-failover `pre.bin` checksum read back after failover.
- post-failover `post.bin` checksum written and verified.
- r1 log showed stale primary lineage rejections for post-promotion
WRITE/SYNCHRONIZE_CACHE attempts.
- cleanup left no active iSCSI sessions, no multipath map, and no stray
blockmaster/blockvolume processes.
Evidence to collect:
- pre-failover and post-failover checksum logs.
- r1/r2 target logs.
- r2 `/status` after failover showing `Healthy=true` and `Epoch>=2`.
- `multipath -ll` before and after failover.
- `sg_rtpg` before failure, during transition, and after recovery.
- `iscsiadm -m session -P 3` before and after failover.
- cleanup commands and final empty session/device state.
Non-claim:
- Test 2 is Linux multipath evidence only.
- Test 2 does not prove Kubernetes-mounted failover.
- Test 2 does not prove Windows MPIO.
- Test 2 does not claim production HA soak.
- Test 2 covers one volume and one RF=2 pair, not multi-volume soak or
repeated fault injection.
## Report Format
QA should report:
- branch and commit SHA,
- host/kernel,
- exact commands,
- `iscsiadm -m session`,
- `multipath -ll`,
- `sg_inq` standard/VPD evidence,
- `sg_rtpg` or equivalent REPORT TARGET PORT GROUPS evidence,
- workload result,
- failover event timing,
- cleanup state,
- any kernel `dmesg` I/O errors.
## Non-Claims
- No Windows MPIO claim.
- No NVMe-oF ANA claim.
- No performance claim.
- No production HA claim until soak/fault testing exists.
@@ -0,0 +1,107 @@
# iSCSI ALUA Technical Note
Status: internal reference for P6 implementation.
## What ALUA Does
ALUA is the SCSI way to tell an initiator that multiple paths reach the same
logical device, but the paths are not equivalent.
- Active optimized: preferred path; can serve normal read/write.
- Active non-optimized: usable path but less preferred.
- Standby: visible path for probing/failover, but not writable.
- Unavailable: path exists but should fail fast.
- Transitioning: path state is moving; do not silently accept writes.
Linux `multipathd` uses standard INQUIRY TPGS bits, VPD 0x83 identifiers, and
REPORT TARGET PORT GROUPS to decide whether several iSCSI sessions are one
device with multiple paths.
## V3 Design
The iSCSI layer reports ALUA state. It does not decide authority.
- `core/frontend/iscsi` owns protocol shape:
- TPGS in standard INQUIRY,
- REPORT TARGET PORT GROUPS,
- VPD 0x83 path identity,
- write/SYNC rejection on non-writable paths.
- A read-only `ALUAProvider` feeds protocol state into `SCSIHandler`.
- The provider must consume V3 frontend facts only.
- It must not import authority, placement, or publisher code.
This keeps the boundary:
- authority decides who may be primary,
- frontend facts expose current path truth,
- iSCSI translates that truth into SCSI-visible ALUA behavior.
## Current P6 Local Protocol Slice
Implemented on `iscsi/csi-node-lifecycle` in commit `bfffbbe`.
- No provider:
- TPGS remains off,
- REPORT TARGET PORT GROUPS fails closed,
- VPD 0x83 stays single NAA descriptor.
- With provider:
- TPGS advertises implicit ALUA,
- REPORT TARGET PORT GROUPS returns state, target port group ID, and
relative target port ID,
- VPD 0x83 adds target-port-group and relative-target-port descriptors,
- active optimized / active non-optimized can write,
- standby / unavailable / transitioning reject WRITE and SYNCHRONIZE_CACHE,
- non-writable states still allow READ for path probing.
## State Mapping Target
V2 behavior is the coverage baseline, not the code model.
- standalone or current primary -> active optimized
- valid non-primary path -> standby or active non-optimized
- stale / closed / unverified path -> unavailable
- authority or recovery movement not closed -> transitioning
V3 still needs P6-C wiring to map real blockvolume/frontend facts into this
provider.
## Hard Parts
- Identity stability:
- all paths for the same volume need the same device NAA,
- paths must still be distinguishable by target port group / relative target
port.
- Write safety:
- old primary must never return successful WRITE after authority moved.
- standby read probing must not become stale data leakage.
- Transition timing:
- authority moved is not enough;
- data continuity and frontend readiness must be closed before a path becomes
active.
- Real initiator behavior:
- in-process tests are not enough;
- Linux `open-iscsi`, `sg_inq`, `sg_rtpg`, `multipath -ll`, mounted workload,
and failover must be tested.
## Test Checklist
- Unit protocol:
- TPGS off without provider.
- REPORT TPG rejected without provider.
- VPD 0x83 non-ALUA branch unchanged.
- all five ALUA states report correctly.
- standby / unavailable / transitioning reject WRITE/SYNC.
- standby / transitioning READ works for path probing.
- VPD 0x00 unchanged.
- VPD 0x83 truncates safely.
- Product wiring:
- blockvolume primary path reports active.
- non-primary path reports standby/non-optimized.
- stale or closed path reports unavailable/transitioning.
- no frontend fact means no ALUA claim.
- Lab:
- `sg_inq` confirms TPGS.
- `sg_inq -p 0x83` confirms stable identity.
- `sg_rtpg` confirms path states.
- `multipath -ll` sees one device with multiple paths.
- mounted failover proves byte-equal read-back and no stale-primary success.
@@ -0,0 +1,201 @@
# iSCSI P6 ALUA / MPIO / Mounted Failover Design
Status: design draft.
Branch: `iscsi/csi-node-lifecycle`.
## Goal
Make mounted-volume failover a deliberate frontend behavior. P6 is not only
"the initiator can reconnect"; it must define what an OS initiator sees when
there are multiple paths, one path is active, another is standby, and authority
moves.
## Current State
- V3 iSCSI currently advertises no ALUA:
- standard INQUIRY TPGS bits are zero,
- VPD 0x83 emits one non-ALUA NAA designator,
- REPORT TARGET PORT GROUPS is not implemented.
- G8/G9 authority and data-continuity tests prove failover below the frontend,
but not mounted failover through a real OS initiator.
- P5 proves CSI node restart while a PVC is mounted, but not blockvolume
failover or multipath.
## V2 Alignment Inventory
This section is a coverage inventory only. Do not copy V2 state ownership or
promotion logic into V3. V3 must keep protocol reporting separate from
authority, placement, and replica readiness.
- V2 ALUA states that V3 must account for:
- `active_optimized` (`0x00`),
- `active_non_optimized` (`0x01`),
- `standby` (`0x02`),
- `unavailable` (`0x0e`),
- `transitioning` (`0x0f`).
- V2 role-to-state mapping used as a behavioral reference:
- standalone / primary -> active optimized,
- replica -> standby,
- stale -> unavailable,
- rebuilding / draining -> transitioning.
- V3 equivalent mapping must be derived from V3 frontend facts:
- current primary frontend -> active optimized,
- valid non-primary path -> standby or active non-optimized, depending on
the final MPIO policy,
- stale/closed/unverified frontend -> unavailable,
- authority or recovery movement not yet closed -> transitioning.
- V2 protocol surface that P6 must match at the test level:
- standard INQUIRY advertises TPGS only when REPORT TARGET PORT GROUPS and
ALUA VPD identity are implemented,
- VPD 0x00 remains unchanged when ALUA is enabled,
- VPD 0x83 has a non-ALUA branch and an ALUA branch,
- REPORT TARGET PORT GROUPS handles all states, short allocation lengths,
no-ALUA rejection, and concurrent state reads,
- standby and transitioning paths reject writes but still serve discovery
and path-probing reads.
## Design Rules
- Protocol state must consume frontend/authority facts. It must not decide
authority, placement, or replica readiness.
- A standby path must not acknowledge stale writes.
- Authority movement alone must not imply data continuity.
- If we expose a multipath identity, it must be stable enough for Linux
multipath and udev.
- In-process protocol tests are necessary but not sufficient; P6 closes only
with a real Linux initiator/multipath run.
## P6 Milestones
### P6-A: ALUA Contract Pinning
- Define the exported state names:
- `active_optimized`: current primary frontend may serve read/write.
- `active_non_optimized`: path is usable but should not be preferred.
- `standby`: observed target path exists but must not serve normal I/O.
- `unavailable`: target path should fail fast.
- `transitioning`: authority or readiness is changing; normal I/O must not
be silently accepted.
- Define command policy by state:
- INQUIRY, VPD, REPORT LUNS, TEST UNIT READY, READ CAPACITY, MODE SENSE,
REQUEST SENSE, and REPORT TARGET PORT GROUPS: allowed on visible paths.
- READ is allowed on standby/transitioning for OS path probing and must not
leak stale data beyond what the underlying frontend provider allows.
- WRITE and SYNCHRONIZE_CACHE are allowed only on active paths.
- standby, unavailable, and transitioning WRITE must fail with stable NOT
READY sense, not GOOD.
- Red tests:
- standby WRITE cannot return GOOD.
- standby READ/READ(16) is allowed for probing.
- unavailable and transitioning WRITE cannot return GOOD.
- state change from active -> standby -> active -> transitioning is observed
immediately by command handling and REPORT TARGET PORT GROUPS.
- TPGS bits are not enabled until REPORT TARGET PORT GROUPS and VPD identity
are implemented.
### P6-B: Protocol Surface
- Implement TPGS advertisement in standard INQUIRY:
- use implicit ALUA TPGS (`01b`) unless the design later explicitly adds
explicit ALUA transitions,
- preserve unrelated byte-5 bits and do not advertise unsupported features.
- Implement REPORT TARGET PORT GROUPS.
- Extend VPD 0x83 with ALUA-safe identity:
- NAA-6 device designator remains stable per volume,
- target port group designator identifies the path group,
- relative target port designator distinguishes paths,
- no-ALUA device still returns only the NAA branch.
- Keep VPD 0x00 advertised pages equal to implemented pages.
- Red tests:
- advertised ALUA pages and commands must be served.
- target port identity is deterministic across restart for the same path.
- different paths for the same volume are distinguishable.
- VPD 0x83 truncates safely for short allocation length.
- VPD 0x83 NAA high nibble remains NAA-6 even with hostile volume ID bytes.
- REPORT TARGET PORT GROUPS rejects no-ALUA devices.
- REPORT TARGET PORT GROUPS handles short allocation lengths.
- REPORT TARGET PORT GROUPS covers all five states.
- concurrent REPORT TARGET PORT GROUPS calls during state changes are safe.
### P6-C: Frontend State Wiring
- Add an explicit ALUA state provider interface near the iSCSI frontend.
- The provider reads current frontend facts; it does not call placement or
authority decision code.
- Provider fields:
- ALUA state,
- target port group ID,
- relative target port ID,
- stable device NAA or volume identity input.
- Blockvolume feeds:
- active when it owns the current primary frontend,
- standby/active-non-optimized when it is a valid non-primary path,
- unavailable when the local frontend is closed, stale, or unverified,
- transitioning when authority changes are observed but local readiness is
not closed.
- Red tests:
- old primary after failover cannot serve WRITE as GOOD.
- returned replica heartbeat does not make the path active.
- ALUA state provider cannot mint authority or mutate assignment.
- no frontend fact means no active/standby ALUA claim.
### P6-D: Real Initiator MPIO Lab
- Linux initiator with `open-iscsi` and `multipath-tools`.
- Two target paths for one volume.
- First executable slice:
- one active path reports ALUA through real `sg_inq` / `sg_rtpg`,
- `mkfs.ext4`, mount, checksum write/read, logout, and cleanup succeed.
- Standby/probe session slice:
- a non-active ALUA path may use a metadata-only borrowed backend when the
write-ready `Provider.Open` path is not ready,
- this is only for path probing commands such as INQUIRY, VPD, RTPG,
capacity, and mode sense,
- writes and sync still fail closed through ALUA and backend readiness.
- Expected:
- multipath sees one logical device,
- active path accepts workload,
- standby path is visible but not selected for normal writes,
- path state changes are visible after authority movement.
- Evidence:
- `sg_inq` standard INQUIRY shows TPGS enabled,
- `sg_inq -p 0x83` shows stable NAA plus path-distinguishing descriptors,
- `sg_rtpg` or equivalent shows target port group state,
- `multipath -ll` shows one logical device with two paths.
- Non-goal for P6-D:
- no automatic transparent failover claim until P6-E passes.
### P6-E: Mounted Failover
- Status:
- not started beyond the standby/probe session prerequisite.
- Start a mounted workload through the multipath device.
- Kill or close the active primary path.
- Drive authority movement to the replica path.
- Verify either:
- workload survives according to documented policy, or
- workload fails and remount/retry succeeds according to documented policy.
- Required proof:
- byte-equal read-back after failover,
- old primary cannot acknowledge stale successful I/O,
- no dangling sessions after cleanup.
## First Implementation Slice
Start with P6-A only:
- Write red tests for standby WRITE fail-closed behavior and ALUA advertisement
discipline.
- Do not enable TPGS yet.
- Do not change K8s manifests yet.
- Do not claim MPIO.
This keeps the first PR reviewable and prevents enabling multipath-looking
metadata before the actual protocol surface exists.
## Non-Claims
- No NVMe-oF ANA.
- No performance claim.
- No production HA claim.
- No silent failover claim until P6-E passes with real OS initiator evidence.
@@ -289,6 +289,45 @@ func TestISCSIP3K8sFioRegistrationBuildsShellDriver(t *testing.T) {
}
}
func TestISCSIP5CSINodeRestartRegistrationBuildsShellDriver(t *testing.T) {
repoRoot := findRepoRoot(t)
raw, err := os.Open(registrationPath(repoRoot, "iscsi-p5-csi-node-restart.json"))
if err != nil {
t.Fatalf("open registration: %v", err)
}
defer raw.Close()
registration, err := DecodeRegistration(raw)
if err != nil {
t.Fatalf("DecodeRegistration: %v", err)
}
if registration.Scenario != "iscsi-p5-csi-node-restart" || registration.Driver.Type != "shell" {
t.Fatalf("registration=%+v", registration)
}
driver, err := registration.NewDriver(repoRoot)
if err != nil {
t.Fatalf("NewDriver: %v", err)
}
shell, ok := driver.(ShellDriver)
if !ok {
t.Fatalf("driver type=%T want ShellDriver", driver)
}
if !filepath.IsAbs(shell.Path) || filepath.Base(shell.Path) != "run-k8s-csi-node-restart.sh" {
t.Fatalf("shell path=%q", shell.Path)
}
if _, err := os.Stat(shell.Path); err != nil {
t.Fatalf("shell driver path missing: %v", err)
}
for _, want := range []string{"restart-csi-node-status.log", "writer.log", "reader.log", "iscsi-sessions.after-delete.txt"} {
if !containsString(registration.Artifacts, want) {
t.Fatalf("registration artifacts missing %q: %v", want, registration.Artifacts)
}
}
if got := registration.ScenarioDefaultParams["SW_BLOCK_LAUNCHER_PVC_OWNER_REF"]; got != "1" {
t.Fatalf("owner-ref default=%q want 1", got)
}
}
func containsString(values []string, want string) bool {
for _, value := range values {
if value == want {
@@ -0,0 +1,52 @@
{
"schema_version": "1.0",
"scenario": "iscsi-p5-csi-node-restart",
"gate": "iSCSI-P5",
"layer": "L5-k8s",
"driver": {
"type": "shell",
"path": "scripts/run-k8s-csi-node-restart.sh"
},
"default_timeout_s": 900,
"required_capabilities": [
"bash",
"kubectl",
"privileged-k8s-node",
"iscsiadm",
"iscsi_tcp-loadable",
"mount"
],
"required_images": [
"sw-block:local",
"sw-block-csi:local"
],
"qa_instruction": "internal/docs/qa-assignments/iscsi-p5-csi-node-lifecycle-validation.md",
"known_green_commit": "",
"scenario_default_params": {
"SW_BLOCK_LAUNCHER_PVC_OWNER_REF": "1"
},
"artifacts": [
"run.log",
"writer.log",
"writer.describe.txt",
"reader.log",
"restart-csi-node.log",
"restart-csi-node-status.log",
"csi-node-pods.after-restart.txt",
"generated-blockvolume.yaml",
"blockmaster.log",
"blockcsi-controller.log",
"csi-provisioner.log",
"csi-attacher.log",
"blockvolume-generated.log",
"iscsi-sessions.after-delete.txt",
"cleanup.log"
],
"non_claims": [
"Single-node Kubernetes only.",
"CSI node restart while the writer pod holds the PVC mount.",
"No blockvolume restart durability claim.",
"No mounted failover, ALUA, MPIO, NVMe, or multi-node claim.",
"No performance or soak claim."
]
}
+4
View File
@@ -15,10 +15,14 @@ This directory contains developer and QA helper scripts.
| `run-k8s-alpha-large.sh` | Optional 256 MiB Kubernetes alpha smoke for larger iSCSI write coverage. |
| `run-k8s-alpha-fio.sh` | Optional 256 MiB Kubernetes alpha smoke with a 60s fio randrw workload. |
| `run-k8s-attach-detach-loop.sh` | QA loop wrapper. Repeats the app PVC attach/write/read/delete flow and stores per-iteration artifacts. |
| `run-k8s-csi-node-restart.sh` | QA wrapper. Restarts the CSI node DaemonSet between writer and reader pods using the same PVC. |
| `build-alpha-images.sh` | Builds local Docker images used by the Kubernetes alpha harness. |
| `run-alpha-k8s-dynamic.sh` | Public dynamic PVC alpha smoke entry. |
| `run-alpha-app-demo.sh` | App-demo implementation used by `run-k8s-demo.sh`. |
| `run-iscsi-os-smoke.sh` | Privileged Linux OS-initiator smoke: `iscsiadm` -> `mkfs.ext4` -> mount -> checksum -> logout on a 256 MiB target. |
| `run-iscsi-alua-os-smoke.sh` | Privileged Linux OS-initiator smoke for ALUA reporting: `iscsiadm` -> `sg_inq`/`sg_rtpg` -> mount -> checksum -> logout. |
| `run-iscsi-alua-multipath-smoke.sh` | Privileged Linux OS-initiator smoke for two iSCSI paths: two portals -> ALUA active/standby evidence -> standby write reject -> `multipath -ll`. |
| `run-iscsi-alua-mounted-failover-smoke.sh` | Privileged Linux OS-initiator smoke for mounted multipath failover: mount `/dev/mapper/*`, kill active path, wait r2 primary, verify checksum read/write. |
| `build-g15b-images.sh` | Compatibility wrapper for older QA scripts. |
| `run-g15b-k8s-static.sh` | Historical static PV Kubernetes harness. |
| `run-g15d-k8s-dynamic.sh` | Historical dynamic PVC harness used by compatibility scenarios. |
+44 -3
View File
@@ -8,10 +8,19 @@ POLL_LOG="$ARTIFACT_DIR/poll.log"
IMAGE="${SW_BLOCK_IMAGE:-sw-block:local}"
CSI_IMAGE="${SW_BLOCK_CSI_IMAGE:-sw-block-csi:local}"
LAUNCHER_PVC_OWNER_REF="${SW_BLOCK_LAUNCHER_PVC_OWNER_REF:-0}"
RESTART_CSI_NODE_BEFORE_READER="${SW_BLOCK_RESTART_CSI_NODE_BEFORE_READER:-0}"
DEFAULT_DEMO_APP_MANIFEST="$ROOT/deploy/k8s/alpha/demo-app-pvc.yaml"
DEMO_APP_MANIFEST="${SW_BLOCK_DEMO_APP_MANIFEST:-$DEFAULT_DEMO_APP_MANIFEST}"
BLOCKVOLUME_NAMESPACE="kube-system"
if [[ "$LAUNCHER_PVC_OWNER_REF" == "1" || "$LAUNCHER_PVC_OWNER_REF" == "true" ]]; then
BLOCKVOLUME_NAMESPACE="$NAMESPACE"
fi
if [[ "$RESTART_CSI_NODE_BEFORE_READER" == "1" || "$RESTART_CSI_NODE_BEFORE_READER" == "true" ]]; then
if [[ "$DEMO_APP_MANIFEST" == "$DEFAULT_DEMO_APP_MANIFEST" || "$(basename "$DEMO_APP_MANIFEST")" == "demo-app-pvc.yaml" ]]; then
echo "restart mode requires a writer manifest that keeps the PVC mounted, e.g. deploy/k8s/alpha/demo-app-pvc-writer-hold.yaml" >&2
exit 2
fi
fi
mkdir -p "$ARTIFACT_DIR"
@@ -80,7 +89,7 @@ cleanup() {
(
set +e
kubectl delete -f "$ROOT/deploy/k8s/alpha/demo-app-reader-pod.yaml" --ignore-not-found=true >>"$ARTIFACT_DIR/cleanup.log" 2>&1
kubectl delete -f "$ROOT/deploy/k8s/alpha/demo-app-pvc.yaml" --ignore-not-found=true >>"$ARTIFACT_DIR/cleanup.log" 2>&1
kubectl delete -f "$DEMO_APP_MANIFEST" --ignore-not-found=true >>"$ARTIFACT_DIR/cleanup.log" 2>&1
kubectl -n "$NAMESPACE" delete pod sw-block-demo-reader sw-block-demo-writer --ignore-not-found=true >>"$ARTIFACT_DIR/cleanup.log" 2>&1
kubectl -n "$NAMESPACE" delete pvc sw-block-demo-pvc --ignore-not-found=true >>"$ARTIFACT_DIR/cleanup.log" 2>&1
kubectl -n kube-system delete deploy -l app=sw-blockvolume --ignore-not-found=true >>"$ARTIFACT_DIR/cleanup.log" 2>&1
@@ -111,6 +120,25 @@ wait_pod_succeeded() {
return 1
}
wait_pod_log_contains() {
local pod="$1"
local pattern="$2"
local timeout_s="$3"
for _ in $(seq 1 "$timeout_s"); do
if kubectl -n "$NAMESPACE" logs "$pod" 2>/dev/null | grep -F -q "$pattern"; then
return 0
fi
phase="$(kubectl -n "$NAMESPACE" get pod "$pod" -o jsonpath='{.status.phase}' 2>/dev/null || true)"
if [[ "$phase" == "Failed" ]]; then
echo "pod $pod failed before log pattern $pattern" >&2
return 1
fi
sleep 1
done
echo "pod $pod did not emit log pattern $pattern before timeout" >&2
return 1
}
require_cmd kubectl
NODE_NAME="$(kubectl get nodes -o jsonpath='{.items[0].metadata.name}')"
@@ -148,6 +176,8 @@ log "image=$IMAGE"
log "csi_image=$CSI_IMAGE"
log "blockvolume_namespace=$BLOCKVOLUME_NAMESPACE"
log "launcher_pvc_owner_ref=$LAUNCHER_PVC_OWNER_REF"
log "restart_csi_node_before_reader=$RESTART_CSI_NODE_BEFORE_READER"
log "demo_app_manifest=$DEMO_APP_MANIFEST"
kubectl version --client=true >"$ARTIFACT_DIR/kubectl-version.txt" 2>&1 || true
kubectl get nodes -o wide >"$ARTIFACT_DIR/nodes.before.txt"
@@ -167,7 +197,7 @@ kubectl -n kube-system wait --for=condition=available deploy/sw-block-csi-contro
kubectl -n kube-system rollout status ds/sw-block-csi-node --timeout=120s
log "apply demo app PVC and writer pod"
kubectl apply -f "$ROOT/deploy/k8s/alpha/demo-app-pvc.yaml" | tee "$ARTIFACT_DIR/apply-demo-app.log"
kubectl apply -f "$DEMO_APP_MANIFEST" | tee "$ARTIFACT_DIR/apply-demo-app.log"
log "wait for launcher-generated blockvolume manifest"
for _ in $(seq 1 180); do
@@ -187,9 +217,20 @@ kubectl apply -f "$ARTIFACT_DIR/generated-blockvolume.yaml" | tee "$ARTIFACT_DIR
kubectl -n "$BLOCKVOLUME_NAMESPACE" wait --for=condition=available deploy -l app=sw-blockvolume --timeout=120s
log "wait for app writer completion"
wait_pod_succeeded sw-block-demo-writer 240
if [[ "$RESTART_CSI_NODE_BEFORE_READER" == "1" || "$RESTART_CSI_NODE_BEFORE_READER" == "true" ]]; then
wait_pod_log_contains sw-block-demo-writer "[app-writer] wrote and verified /data/demo.bin" 240
else
wait_pod_succeeded sw-block-demo-writer 240
fi
kubectl -n "$NAMESPACE" logs sw-block-demo-writer | tee "$ARTIFACT_DIR/writer.log"
if [[ "$RESTART_CSI_NODE_BEFORE_READER" == "1" || "$RESTART_CSI_NODE_BEFORE_READER" == "true" ]]; then
log "restart CSI node DaemonSet before replacing the app pod"
kubectl -n kube-system rollout restart ds/sw-block-csi-node | tee "$ARTIFACT_DIR/restart-csi-node.log"
kubectl -n kube-system rollout status ds/sw-block-csi-node --timeout=180s | tee "$ARTIFACT_DIR/restart-csi-node-status.log"
kubectl -n kube-system get pods -l app=sw-block-csi-node -o wide >"$ARTIFACT_DIR/csi-node-pods.after-restart.txt" 2>&1 || true
fi
log "delete writer pod but keep PVC"
kubectl -n "$NAMESPACE" delete pod sw-block-demo-writer --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-writer.log"
@@ -0,0 +1,379 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(pwd)}"
RUN_ID="${RUN_ID:-$(date -u +%Y%m%dT%H%M%SZ)}"
WORK_DIR="${SW_BLOCK_ISCSI_FAILOVER_WORK_DIR:-/tmp/sw-block-iscsi-failover}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${WORK_DIR}/runs/${RUN_ID}}"
IQN="${SW_BLOCK_ISCSI_IQN:-iqn.2026-05.io.seaweedfs:failover-v1}"
PORT1="${SW_BLOCK_ISCSI_PORT1:-3280}"
PORT2="${SW_BLOCK_ISCSI_PORT2:-3281}"
MASTER_ADDR="${SW_BLOCK_MASTER_ADDR:-127.0.0.1:19633}"
R1_DATA_ADDR="${SW_BLOCK_R1_DATA_ADDR:-127.0.0.1:19601}"
R1_CTRL_ADDR="${SW_BLOCK_R1_CTRL_ADDR:-127.0.0.1:19602}"
R1_STATUS_ADDR="${SW_BLOCK_R1_STATUS_ADDR:-127.0.0.1:19603}"
R2_DATA_ADDR="${SW_BLOCK_R2_DATA_ADDR:-127.0.0.1:19611}"
R2_CTRL_ADDR="${SW_BLOCK_R2_CTRL_ADDR:-127.0.0.1:19612}"
R2_STATUS_ADDR="${SW_BLOCK_R2_STATUS_ADDR:-127.0.0.1:19613}"
BLOCKS="${SW_BLOCK_DURABLE_BLOCKS:-65536}"
BLOCK_SIZE="${SW_BLOCK_DURABLE_BLOCKSIZE:-4096}"
BIN_DIR="${SW_BLOCK_BIN_DIR:-${WORK_DIR}/bin}"
RUN_DIR="${WORK_DIR}/run"
MOUNT_DIR="${SW_BLOCK_ISCSI_MOUNT_DIR:-${WORK_DIR}/mnt}"
mkdir -p "$ARTIFACT_DIR" "$BIN_DIR" "$RUN_DIR" "$MOUNT_DIR"
log() {
printf '[iscsi-failover] %s\n' "$*" | tee -a "$ARTIFACT_DIR/run.log"
}
require_cmd() {
if ! command -v "$1" >/dev/null 2>&1; then
echo "missing required command: $1" >&2
exit 2
fi
}
portal_for() {
printf '127.0.0.1:%s' "$1"
}
delete_iscsi_node() {
local port="$1"
sudo iscsiadm -m node -T "$IQN" -p "$(portal_for "$port")" --logout >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
sudo iscsiadm -m node -T "$IQN" -p "$(portal_for "$port")" -o delete >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
sudo iscsiadm -m discoverydb -t sendtargets -p "$(portal_for "$port")" -o delete >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
}
cleanup() {
set +e
log "cleanup"
mountpoint -q "$MOUNT_DIR" && sudo umount "$MOUNT_DIR" >>"$ARTIFACT_DIR/cleanup.log" 2>&1
if [[ -s "$ARTIFACT_DIR/multipath-map-name.txt" ]]; then
sudo multipath -f "$(cat "$ARTIFACT_DIR/multipath-map-name.txt")" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
fi
delete_iscsi_node "$PORT1"
delete_iscsi_node "$PORT2"
pkill -TERM -f "${BIN_DIR}/blockvolume" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
pkill -TERM -f "${BIN_DIR}/blockmaster" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
sleep 1
pkill -KILL -f "${BIN_DIR}/blockvolume" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
pkill -KILL -f "${BIN_DIR}/blockmaster" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
sudo multipath -ll >"$ARTIFACT_DIR/multipath.after.txt" 2>&1 || true
sudo iscsiadm -m session >"$ARTIFACT_DIR/iscsi-sessions.after.txt" 2>&1 || true
}
trap cleanup EXIT
require_cmd sudo
require_cmd curl
require_cmd iscsiadm
require_cmd multipath
require_cmd sg_rtpg
require_cmd mkfs.ext4
require_cmd mount
require_cmd sha256sum
require_cmd python3
log "run_id=$RUN_ID"
log "root=$ROOT"
log "artifact_dir=$ARTIFACT_DIR"
log "iqn=$IQN"
log "portals=$(portal_for "$PORT1"),$(portal_for "$PORT2")"
cd "$ROOT"
git rev-parse --short HEAD >"$ARTIFACT_DIR/git-head.txt" 2>/dev/null || true
if [[ -x "${BIN_DIR}/blockmaster" && -x "${BIN_DIR}/blockvolume" ]]; then
log "use prebuilt binaries from ${BIN_DIR}"
else
require_cmd go
log "build binaries"
go build -o "${BIN_DIR}/blockmaster" ./cmd/blockmaster
go build -o "${BIN_DIR}/blockvolume" ./cmd/blockvolume
fi
cat >"$ARTIFACT_DIR/topology.yaml" <<YAML
volumes:
- volume_id: v1
slots:
- replica_id: r1
server_id: s1
- replica_id: r2
server_id: s2
YAML
rm -rf "${RUN_DIR}/master-store" "${RUN_DIR}/r1-store" "${RUN_DIR}/r2-store"
mkdir -p "${RUN_DIR}/master-store" "${RUN_DIR}/r1-store" "${RUN_DIR}/r2-store"
pkill -KILL -f "${BIN_DIR}/blockvolume" >/dev/null 2>&1 || true
pkill -KILL -f "${BIN_DIR}/blockmaster" >/dev/null 2>&1 || true
delete_iscsi_node "$PORT1"
delete_iscsi_node "$PORT2"
sudo iscsiadm -m session >"$ARTIFACT_DIR/iscsi-sessions.before.txt" 2>&1 || true
sudo multipath -ll >"$ARTIFACT_DIR/multipath.before.txt" 2>&1 || true
log "start blockmaster"
setsid -f "${BIN_DIR}/blockmaster" \
--authority-store "${RUN_DIR}/master-store" \
--listen "$MASTER_ADDR" \
--topology "$ARTIFACT_DIR/topology.yaml" \
--expected-slots-per-volume 2 \
--freshness-window 800ms \
--pending-grace 100ms \
>"$ARTIFACT_DIR/blockmaster.log" 2>&1
sleep 1
start_blockvolume() {
local replica="$1"
local server="$2"
local port="$3"
local data_addr="$4"
local ctrl_addr="$5"
local status_addr="$6"
local store="$7"
local log_file="$8"
setsid -f "${BIN_DIR}/blockvolume" \
--master "$MASTER_ADDR" \
--server-id "$server" \
--volume-id v1 \
--replica-id "$replica" \
--data-addr "$data_addr" \
--ctrl-addr "$ctrl_addr" \
--status-addr "$status_addr" \
--heartbeat-interval 200ms \
--t1-readiness \
--durable-root "$store" \
--durable-impl smartwal \
--durable-blocks "$BLOCKS" \
--durable-blocksize "$BLOCK_SIZE" \
--iscsi-listen "127.0.0.1:${port}" \
--iscsi-iqn "$IQN" \
>"$log_file" 2>&1
}
wait_port() {
local port="$1"
for _ in $(seq 1 100); do
if bash -c "</dev/tcp/127.0.0.1/${port}" >/dev/null 2>&1; then
return 0
fi
sleep 0.1
done
echo "timed out waiting for port ${port}" >&2
exit 1
}
wait_status_healthy() {
local status_addr="$1"
local replica="$2"
local min_epoch="$3"
local out="$ARTIFACT_DIR/status-${replica}-healthy.json"
for _ in $(seq 1 120); do
if curl -fsS "http://${status_addr}/status?volume=v1" >"$out.tmp" 2>/dev/null; then
if python3 - "$out.tmp" "$replica" "$min_epoch" <<'PY'
import json, sys
path, replica, min_epoch = sys.argv[1], sys.argv[2], int(sys.argv[3])
body = json.load(open(path))
healthy = bool(body.get("Healthy"))
rid = str(body.get("ReplicaID", ""))
epoch = int(body.get("Epoch", 0))
sys.exit(0 if healthy and rid == replica and epoch >= min_epoch else 1)
PY
then
mv "$out.tmp" "$out"
return 0
fi
fi
sleep 0.25
done
curl -fsS "http://${status_addr}/status?volume=v1" >"$ARTIFACT_DIR/status-${replica}-last.json" 2>/dev/null || true
echo "timed out waiting for ${replica} Healthy epoch>=${min_epoch}" >&2
exit 1
}
wait_status_projected() {
local status_addr="$1"
local replica="$2"
local out="$ARTIFACT_DIR/status-${replica}-projected.json"
for _ in $(seq 1 120); do
if curl -fsS "http://${status_addr}/status?volume=v1" >"$out.tmp" 2>/dev/null; then
if python3 - "$out.tmp" "$replica" <<'PY'
import json, sys
path, replica = sys.argv[1], sys.argv[2]
body = json.load(open(path))
if str(body.get("ReplicaID", "")) != replica:
sys.exit(1)
authority_role = str(body.get("AuthorityRole", ""))
replication_role = str(body.get("ReplicationRole", ""))
ok = authority_role != "unknown" or replication_role != "unknown"
sys.exit(0 if ok else 1)
PY
then
mv "$out.tmp" "$out"
return 0
fi
fi
sleep 0.25
done
curl -fsS "http://${status_addr}/status?volume=v1" >"$ARTIFACT_DIR/status-${replica}-last.json" 2>/dev/null || true
echo "timed out waiting for ${replica} projection" >&2
exit 1
}
pid_for_replica() {
local replica="$1"
pgrep -f "${BIN_DIR}/blockvolume.*--replica-id ${replica}" | head -n1
}
log "start r1 active path"
start_blockvolume r1 s1 "$PORT1" "$R1_DATA_ADDR" "$R1_CTRL_ADDR" "$R1_STATUS_ADDR" \
"${RUN_DIR}/r1-store" "$ARTIFACT_DIR/blockvolume-r1.log"
wait_port "$PORT1"
wait_status_healthy "$R1_STATUS_ADDR" r1 1
log "start r2 standby path"
start_blockvolume r2 s2 "$PORT2" "$R2_DATA_ADDR" "$R2_CTRL_ADDR" "$R2_STATUS_ADDR" \
"${RUN_DIR}/r2-store" "$ARTIFACT_DIR/blockvolume-r2.log"
wait_port "$PORT2"
wait_status_healthy "$R1_STATUS_ADDR" r1 1
wait_status_projected "$R2_STATUS_ADDR" r2
discover_login() {
local port="$1"
local name="$2"
log "iscsi discovery/login ${name}"
sudo iscsiadm -m discovery -t sendtargets -p "$(portal_for "$port")" | tee "$ARTIFACT_DIR/discovery-${name}.log"
sudo iscsiadm -m node -T "$IQN" -p "$(portal_for "$port")" --login | tee "$ARTIFACT_DIR/login-${name}.log"
}
discover_login "$PORT1" r1
discover_login "$PORT2" r2
sudo iscsiadm -m session -P 3 >"$ARTIFACT_DIR/iscsi-session-P3.before-failover.txt" 2>&1 || true
find_devlink() {
local port="$1"
local pattern="/dev/disk/by-path/*ip-127.0.0.1:${port}-iscsi-${IQN}-lun-0"
local dev=""
for _ in $(seq 1 120); do
dev="$(compgen -G "$pattern" | head -n1 || true)"
if [[ -n "$dev" ]]; then
printf '%s' "$dev"
return 0
fi
sleep 0.1
done
ls -l /dev/disk/by-path >"$ARTIFACT_DIR/by-path.txt" 2>&1 || true
(sudo dmesg | tail -n 160) >"$ARTIFACT_DIR/dmesg.tail.txt" 2>&1 || true
echo "device not found for portal $(portal_for "$port")" >&2
exit 1
}
dev1="$(find_devlink "$PORT1")"
dev2="$(find_devlink "$PORT2")"
real1="$(readlink -f "$dev1")"
real2="$(readlink -f "$dev2")"
base1="$(basename "$real1")"
base2="$(basename "$real2")"
log "r1_device=$dev1 real=$real1"
log "r2_device=$dev2 real=$real2"
sudo sg_rtpg "$real1" >"$ARTIFACT_DIR/sg_rtpg.r1.before.txt" 2>&1
sudo sg_rtpg "$real2" >"$ARTIFACT_DIR/sg_rtpg.r2.before.txt" 2>&1
log "ask multipath to group both paths"
sudo multipath "$real1" >"$ARTIFACT_DIR/multipath.real1.txt" 2>&1 || true
sudo multipath "$real2" >"$ARTIFACT_DIR/multipath.real2.txt" 2>&1 || true
sudo multipath -r >"$ARTIFACT_DIR/multipath.reload.before.txt" 2>&1 || true
sleep 2
sudo multipath -ll >"$ARTIFACT_DIR/multipath.ll.before.txt" 2>&1 || true
if ! awk -v a="$base1" -v b="$base2" '
/^[[:alnum:]_.:-]+[[:space:]]+\(/ {
if (seen && hasA && hasB) {
print map
found=1
exit
}
seen=1
map=$1
hasA=0
hasB=0
}
{
if (index($0, a)) hasA=1
if (index($0, b)) hasB=1
}
END {
if (!found && seen && hasA && hasB) {
print map
found=1
}
exit(found ? 0 : 1)
}
' "$ARTIFACT_DIR/multipath.ll.before.txt" >"$ARTIFACT_DIR/multipath-map-name.txt"; then
cat "$ARTIFACT_DIR/multipath.ll.before.txt" >&2
echo "multipath did not show one map containing both ${base1} and ${base2}" >&2
exit 1
fi
map_name="$(cat "$ARTIFACT_DIR/multipath-map-name.txt")"
map_dev="/dev/mapper/${map_name}"
log "multipath_map=${map_name} dev=${map_dev}"
for _ in $(seq 1 80); do
[[ -b "$map_dev" ]] && break
sleep 0.1
done
if [[ ! -b "$map_dev" ]]; then
echo "multipath map device ${map_dev} did not appear" >&2
exit 1
fi
log "mkfs/mount multipath device"
sudo mkfs.ext4 -F "$map_dev" >"$ARTIFACT_DIR/mkfs.log" 2>&1
sudo mount "$map_dev" "$MOUNT_DIR"
log "write pre-failover payload"
sudo dd if=/dev/urandom of="$MOUNT_DIR/pre.bin" bs=4096 count=64 status=none
sync
sudo sha256sum "$MOUNT_DIR/pre.bin" | tee "$ARTIFACT_DIR/pre.sha256"
r1_pid="$(pid_for_replica r1 || true)"
if [[ -z "$r1_pid" ]]; then
echo "could not find r1 blockvolume pid" >&2
exit 1
fi
log "kill active r1 pid=${r1_pid}"
kill -TERM "$r1_pid"
sleep 1
if kill -0 "$r1_pid" >/dev/null 2>&1; then
kill -KILL "$r1_pid" >/dev/null 2>&1 || true
fi
log "wait r2 failover"
wait_status_healthy "$R2_STATUS_ADDR" r2 2
sudo sg_rtpg "$real2" >"$ARTIFACT_DIR/sg_rtpg.r2.after.txt" 2>&1 || true
sudo multipath -r >"$ARTIFACT_DIR/multipath.reload.after.txt" 2>&1 || true
sudo multipath -ll >"$ARTIFACT_DIR/multipath.ll.after.txt" 2>&1 || true
sudo iscsiadm -m session -P 3 >"$ARTIFACT_DIR/iscsi-session-P3.after-failover.txt" 2>&1 || true
log "verify mounted workload after failover"
sudo sha256sum -c "$ARTIFACT_DIR/pre.sha256" | tee "$ARTIFACT_DIR/pre-check-after-failover.log"
sudo dd if=/dev/urandom of="$MOUNT_DIR/post.bin" bs=4096 count=64 status=none
sync
sudo sha256sum "$MOUNT_DIR/post.bin" | tee "$ARTIFACT_DIR/post.sha256"
sudo sha256sum -c "$ARTIFACT_DIR/post.sha256" | tee "$ARTIFACT_DIR/post-check.log"
log "unmount"
sudo umount "$MOUNT_DIR"
log "logout both paths"
delete_iscsi_node "$PORT1"
delete_iscsi_node "$PORT2"
sudo iscsiadm -m session >"$ARTIFACT_DIR/iscsi-sessions.final.txt" 2>&1 || true
if ! grep -q "No active sessions" "$ARTIFACT_DIR/iscsi-sessions.final.txt"; then
cat "$ARTIFACT_DIR/iscsi-sessions.final.txt"
exit 1
fi
log "PASS: mounted multipath workload read/wrote through r1->r2 failover"
log "artifacts=$ARTIFACT_DIR"
+352
View File
@@ -0,0 +1,352 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(pwd)}"
RUN_ID="${RUN_ID:-$(date -u +%Y%m%dT%H%M%SZ)}"
WORK_DIR="${SW_BLOCK_ISCSI_MPATH_WORK_DIR:-/tmp/sw-block-iscsi-mpath}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${WORK_DIR}/runs/${RUN_ID}}"
IQN="${SW_BLOCK_ISCSI_IQN:-iqn.2026-05.io.seaweedfs:mpath-v1}"
PORT1="${SW_BLOCK_ISCSI_PORT1:-3270}"
PORT2="${SW_BLOCK_ISCSI_PORT2:-3271}"
MASTER_ADDR="${SW_BLOCK_MASTER_ADDR:-127.0.0.1:19533}"
R1_DATA_ADDR="${SW_BLOCK_R1_DATA_ADDR:-127.0.0.1:19501}"
R1_CTRL_ADDR="${SW_BLOCK_R1_CTRL_ADDR:-127.0.0.1:19502}"
R1_STATUS_ADDR="${SW_BLOCK_R1_STATUS_ADDR:-127.0.0.1:19503}"
R2_DATA_ADDR="${SW_BLOCK_R2_DATA_ADDR:-127.0.0.1:19511}"
R2_CTRL_ADDR="${SW_BLOCK_R2_CTRL_ADDR:-127.0.0.1:19512}"
R2_STATUS_ADDR="${SW_BLOCK_R2_STATUS_ADDR:-127.0.0.1:19513}"
BLOCKS="${SW_BLOCK_DURABLE_BLOCKS:-65536}"
BLOCK_SIZE="${SW_BLOCK_DURABLE_BLOCKSIZE:-4096}"
BIN_DIR="${SW_BLOCK_BIN_DIR:-${WORK_DIR}/bin}"
RUN_DIR="${WORK_DIR}/run"
mkdir -p "$ARTIFACT_DIR" "$BIN_DIR" "$RUN_DIR"
log() {
printf '[iscsi-mpath] %s\n' "$*" | tee -a "$ARTIFACT_DIR/run.log"
}
require_cmd() {
if ! command -v "$1" >/dev/null 2>&1; then
echo "missing required command: $1" >&2
exit 2
fi
}
portal_for() {
printf '127.0.0.1:%s' "$1"
}
delete_iscsi_node() {
local port="$1"
sudo iscsiadm -m node -T "$IQN" -p "$(portal_for "$port")" --logout >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
sudo iscsiadm -m node -T "$IQN" -p "$(portal_for "$port")" -o delete >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
sudo iscsiadm -m discoverydb -t sendtargets -p "$(portal_for "$port")" -o delete >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
}
cleanup() {
set +e
log "cleanup"
if [[ -s "$ARTIFACT_DIR/multipath-map-name.txt" ]]; then
sudo multipath -f "$(cat "$ARTIFACT_DIR/multipath-map-name.txt")" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
fi
delete_iscsi_node "$PORT1"
delete_iscsi_node "$PORT2"
pkill -TERM -f "${BIN_DIR}/blockvolume" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
pkill -TERM -f "${BIN_DIR}/blockmaster" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
sleep 1
pkill -KILL -f "${BIN_DIR}/blockvolume" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
pkill -KILL -f "${BIN_DIR}/blockmaster" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
sudo multipath -ll >"$ARTIFACT_DIR/multipath.after.txt" 2>&1 || true
sudo iscsiadm -m session >"$ARTIFACT_DIR/iscsi-sessions.after.txt" 2>&1 || true
}
trap cleanup EXIT
require_cmd sudo
require_cmd curl
require_cmd iscsiadm
require_cmd multipath
require_cmd sg_inq
require_cmd sg_rtpg
require_cmd dd
require_cmd python3
log "run_id=$RUN_ID"
log "root=$ROOT"
log "artifact_dir=$ARTIFACT_DIR"
log "iqn=$IQN"
log "portals=$(portal_for "$PORT1"),$(portal_for "$PORT2")"
cd "$ROOT"
git rev-parse --short HEAD >"$ARTIFACT_DIR/git-head.txt" 2>/dev/null || true
if [[ -x "${BIN_DIR}/blockmaster" && -x "${BIN_DIR}/blockvolume" ]]; then
log "use prebuilt binaries from ${BIN_DIR}"
else
require_cmd go
log "build binaries"
go build -o "${BIN_DIR}/blockmaster" ./cmd/blockmaster
go build -o "${BIN_DIR}/blockvolume" ./cmd/blockvolume
fi
cat >"$ARTIFACT_DIR/topology.yaml" <<YAML
volumes:
- volume_id: v1
slots:
- replica_id: r1
server_id: s1
- replica_id: r2
server_id: s2
YAML
rm -rf "${RUN_DIR}/master-store" "${RUN_DIR}/r1-store" "${RUN_DIR}/r2-store"
mkdir -p "${RUN_DIR}/master-store" "${RUN_DIR}/r1-store" "${RUN_DIR}/r2-store"
pkill -KILL -f "${BIN_DIR}/blockvolume" >/dev/null 2>&1 || true
pkill -KILL -f "${BIN_DIR}/blockmaster" >/dev/null 2>&1 || true
delete_iscsi_node "$PORT1"
delete_iscsi_node "$PORT2"
sudo iscsiadm -m session >"$ARTIFACT_DIR/iscsi-sessions.before.txt" 2>&1 || true
sudo multipath -ll >"$ARTIFACT_DIR/multipath.before.txt" 2>&1 || true
log "start blockmaster"
setsid -f "${BIN_DIR}/blockmaster" \
--authority-store "${RUN_DIR}/master-store" \
--listen "$MASTER_ADDR" \
--topology "$ARTIFACT_DIR/topology.yaml" \
--expected-slots-per-volume 2 \
>"$ARTIFACT_DIR/blockmaster.log" 2>&1
sleep 1
start_blockvolume() {
local replica="$1"
local server="$2"
local port="$3"
local data_addr="$4"
local ctrl_addr="$5"
local status_addr="$6"
local store="$7"
local log_file="$8"
setsid -f "${BIN_DIR}/blockvolume" \
--master "$MASTER_ADDR" \
--server-id "$server" \
--volume-id v1 \
--replica-id "$replica" \
--data-addr "$data_addr" \
--ctrl-addr "$ctrl_addr" \
--status-addr "$status_addr" \
--heartbeat-interval 200ms \
--t1-readiness \
--durable-root "$store" \
--durable-impl smartwal \
--durable-blocks "$BLOCKS" \
--durable-blocksize "$BLOCK_SIZE" \
--iscsi-listen "127.0.0.1:${port}" \
--iscsi-iqn "$IQN" \
>"$log_file" 2>&1
}
wait_port() {
local port="$1"
for _ in $(seq 1 100); do
if bash -c "</dev/tcp/127.0.0.1/${port}" >/dev/null 2>&1; then
return 0
fi
sleep 0.1
done
echo "timed out waiting for port ${port}" >&2
exit 1
}
wait_status_role() {
local status_addr="$1"
local replica="$2"
local role="$3"
local out="$ARTIFACT_DIR/status-${replica}-${role}.json"
for _ in $(seq 1 120); do
if curl -fsS "http://${status_addr}/status?volume=v1" >"$out.tmp" 2>/dev/null; then
if python3 - "$out.tmp" "$replica" "$role" <<'PY'
import json, sys
path, replica, role = sys.argv[1], sys.argv[2], sys.argv[3]
body = json.load(open(path))
if str(body.get("ReplicaID", "")) != replica:
sys.exit(1)
authority_role = str(body.get("AuthorityRole", ""))
frontend_ready = bool(body.get("FrontendPrimaryReady"))
replication_role = str(body.get("ReplicationRole", ""))
if role == "primary":
sys.exit(0 if authority_role == "primary" and frontend_ready else 1)
if role == "standby":
ok = authority_role == "superseded" or replication_role in ("not_ready", "replica_ready", "recovering")
sys.exit(0 if ok and authority_role != "primary" else 1)
sys.exit(1)
PY
then
mv "$out.tmp" "$out"
return 0
fi
fi
sleep 0.25
done
curl -fsS "http://${status_addr}/status?volume=v1" >"$ARTIFACT_DIR/status-${replica}-last.json" 2>/dev/null || true
echo "timed out waiting for ${replica} ${role} projection" >&2
exit 1
}
log "start r1 iSCSI path"
start_blockvolume r1 s1 "$PORT1" "$R1_DATA_ADDR" "$R1_CTRL_ADDR" "$R1_STATUS_ADDR" \
"${RUN_DIR}/r1-store" "$ARTIFACT_DIR/blockvolume-r1.log"
wait_port "$PORT1"
wait_status_role "$R1_STATUS_ADDR" r1 primary
log "start r2 iSCSI path"
start_blockvolume r2 s2 "$PORT2" "$R2_DATA_ADDR" "$R2_CTRL_ADDR" "$R2_STATUS_ADDR" \
"${RUN_DIR}/r2-store" "$ARTIFACT_DIR/blockvolume-r2.log"
wait_port "$PORT2"
wait_status_role "$R2_STATUS_ADDR" r2 standby
discover_login() {
local port="$1"
local name="$2"
log "iscsi discovery/login ${name}"
sudo iscsiadm -m discovery -t sendtargets -p "$(portal_for "$port")" | tee "$ARTIFACT_DIR/discovery-${name}.log"
sudo iscsiadm -m node -T "$IQN" -p "$(portal_for "$port")" --login | tee "$ARTIFACT_DIR/login-${name}.log"
}
discover_login "$PORT1" r1
discover_login "$PORT2" r2
sudo iscsiadm -m session -P 3 >"$ARTIFACT_DIR/iscsi-session-P3.txt" 2>&1 || true
find_devlink() {
local port="$1"
local pattern="/dev/disk/by-path/*ip-127.0.0.1:${port}-iscsi-${IQN}-lun-0"
local dev=""
for _ in $(seq 1 120); do
dev="$(compgen -G "$pattern" | head -n1 || true)"
if [[ -n "$dev" ]]; then
printf '%s' "$dev"
return 0
fi
sleep 0.1
done
ls -l /dev/disk/by-path >"$ARTIFACT_DIR/by-path.txt" 2>&1 || true
(sudo dmesg | tail -n 160) >"$ARTIFACT_DIR/dmesg.tail.txt" 2>&1 || true
echo "device not found for portal $(portal_for "$port")" >&2
exit 1
}
dev1="$(find_devlink "$PORT1")"
dev2="$(find_devlink "$PORT2")"
real1="$(readlink -f "$dev1")"
real2="$(readlink -f "$dev2")"
base1="$(basename "$real1")"
base2="$(basename "$real2")"
log "r1_device=$dev1 real=$real1"
log "r2_device=$dev2 real=$real2"
lsblk "$real1" "$real2" >"$ARTIFACT_DIR/lsblk.paths.txt" 2>&1 || true
capture_path_evidence() {
local name="$1"
local dev="$2"
sudo sg_inq "$dev" >"$ARTIFACT_DIR/sg_inq.${name}.standard.txt" 2>&1
sudo sg_inq -p 0x00 "$dev" >"$ARTIFACT_DIR/sg_inq.${name}.vpd00.txt" 2>&1
sudo sg_inq -p 0x83 "$dev" >"$ARTIFACT_DIR/sg_inq.${name}.vpd83.txt" 2>&1
sudo sg_rtpg "$dev" >"$ARTIFACT_DIR/sg_rtpg.${name}.txt" 2>&1
}
log "capture ALUA path evidence"
capture_path_evidence r1 "$real1"
capture_path_evidence r2 "$real2"
extract_aas() {
sed -n 's/.*asymmetric access state[[:space:]]*:[[:space:]]*\(0x[0-9a-fA-F]\+\).*/\1/p' "$1" | head -n1
}
state1="$(extract_aas "$ARTIFACT_DIR/sg_rtpg.r1.txt")"
state2="$(extract_aas "$ARTIFACT_DIR/sg_rtpg.r2.txt")"
log "rtpg_state_r1=${state1:-missing}"
log "rtpg_state_r2=${state2:-missing}"
if [[ -z "$state1" || -z "$state2" ]]; then
echo "missing REPORT TARGET PORT GROUPS asymmetric access state" >&2
exit 1
fi
if [[ "$state1" != "0x00" && "$state2" != "0x00" ]]; then
echo "no active/optimized path reported by RTPG" >&2
exit 1
fi
if [[ "$state1" != "0x02" && "$state2" != "0x02" ]]; then
echo "no standby path reported by RTPG" >&2
exit 1
fi
if ! grep -Eiq "target port group|relative target port|NAA" "$ARTIFACT_DIR/sg_inq.r1.vpd83.txt"; then
echo "r1 VPD 0x83 missing NAA/target-port identity evidence" >&2
exit 1
fi
if ! grep -Eiq "target port group|relative target port|NAA" "$ARTIFACT_DIR/sg_inq.r2.vpd83.txt"; then
echo "r2 VPD 0x83 missing NAA/target-port identity evidence" >&2
exit 1
fi
standby_dev=""
if [[ "$state1" == "0x02" ]]; then
standby_dev="$real1"
else
standby_dev="$real2"
fi
log "verify standby path rejects raw WRITE"
if sudo dd if=/dev/zero of="$standby_dev" bs=4096 count=1 oflag=direct status=none >"$ARTIFACT_DIR/standby-write.stdout" 2>"$ARTIFACT_DIR/standby-write.stderr"; then
echo "standby path accepted WRITE unexpectedly" >&2
exit 1
fi
log "ask multipath to group both paths"
sudo multipath "$real1" >"$ARTIFACT_DIR/multipath.real1.txt" 2>&1 || true
sudo multipath "$real2" >"$ARTIFACT_DIR/multipath.real2.txt" 2>&1 || true
sudo multipath -r >"$ARTIFACT_DIR/multipath.reload.txt" 2>&1 || true
sleep 2
sudo multipath -ll >"$ARTIFACT_DIR/multipath.ll.txt" 2>&1 || true
if ! awk -v a="$base1" -v b="$base2" '
/^[[:alnum:]_.:-]+[[:space:]]+\(/ {
if (seen && hasA && hasB) {
print map
found=1
exit
}
seen=1
map=$1
hasA=0
hasB=0
}
{
if (index($0, a)) hasA=1
if (index($0, b)) hasB=1
}
END {
if (!found && seen && hasA && hasB) {
print map
found=1
}
exit(found ? 0 : 1)
}
' "$ARTIFACT_DIR/multipath.ll.txt" >"$ARTIFACT_DIR/multipath-map-name.txt"; then
cat "$ARTIFACT_DIR/multipath.ll.txt" >&2
echo "multipath did not show one map containing both ${base1} and ${base2}" >&2
exit 1
fi
log "multipath_map=$(cat "$ARTIFACT_DIR/multipath-map-name.txt")"
log "logout both paths"
delete_iscsi_node "$PORT1"
delete_iscsi_node "$PORT2"
sudo iscsiadm -m session >"$ARTIFACT_DIR/iscsi-sessions.final.txt" 2>&1 || true
if ! grep -q "No active sessions" "$ARTIFACT_DIR/iscsi-sessions.final.txt"; then
cat "$ARTIFACT_DIR/iscsi-sessions.final.txt"
exit 1
fi
log "PASS: two iSCSI paths report ALUA and multipath groups one logical device"
log "artifacts=$ARTIFACT_DIR"
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(pwd)}"
RUN_ID="${RUN_ID:-$(date -u +%Y%m%dT%H%M%SZ)}"
WORK_DIR="${SW_BLOCK_ISCSI_ALUA_WORK_DIR:-/tmp/sw-block-iscsi-alua}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${WORK_DIR}/runs/${RUN_ID}}"
IQN="${SW_BLOCK_ISCSI_IQN:-iqn.2026-05.io.seaweedfs:alua-v1}"
PORT="${SW_BLOCK_ISCSI_PORT:-3268}"
MOUNT_DIR="${SW_BLOCK_ISCSI_MOUNT_DIR:-${WORK_DIR}/mnt}"
MASTER_ADDR="${SW_BLOCK_MASTER_ADDR:-127.0.0.1:19433}"
DATA_ADDR="${SW_BLOCK_DATA_ADDR:-127.0.0.1:19401}"
CTRL_ADDR="${SW_BLOCK_CTRL_ADDR:-127.0.0.1:19402}"
STATUS_ADDR="${SW_BLOCK_STATUS_ADDR:-127.0.0.1:19403}"
BLOCKS="${SW_BLOCK_DURABLE_BLOCKS:-65536}"
BLOCK_SIZE="${SW_BLOCK_DURABLE_BLOCKSIZE:-4096}"
BIN_DIR="${SW_BLOCK_BIN_DIR:-${WORK_DIR}/bin}"
RUN_DIR="${WORK_DIR}/run"
DEVLINK_GLOB="/dev/disk/by-path/*ip-127.0.0.1:${PORT}-iscsi-${IQN}-lun-0"
mkdir -p "$ARTIFACT_DIR" "$BIN_DIR" "$RUN_DIR" "$MOUNT_DIR"
log() {
printf '[iscsi-alua] %s\n' "$*" | tee -a "$ARTIFACT_DIR/run.log"
}
require_cmd() {
if ! command -v "$1" >/dev/null 2>&1; then
echo "missing required command: $1" >&2
exit 2
fi
}
cleanup() {
set +e
log "cleanup"
mountpoint -q "$MOUNT_DIR" && sudo umount "$MOUNT_DIR" >>"$ARTIFACT_DIR/cleanup.log" 2>&1
sudo iscsiadm -m node -T "$IQN" -p "127.0.0.1:${PORT}" --logout >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
sudo iscsiadm -m node -T "$IQN" -p "127.0.0.1:${PORT}" -o delete >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
sudo iscsiadm -m discoverydb -t sendtargets -p "127.0.0.1:${PORT}" -o delete >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
pkill -TERM -f "${BIN_DIR}/blockvolume" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
pkill -TERM -f "${BIN_DIR}/blockmaster" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
sleep 1
pkill -KILL -f "${BIN_DIR}/blockvolume" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
pkill -KILL -f "${BIN_DIR}/blockmaster" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true
sudo iscsiadm -m session >"$ARTIFACT_DIR/iscsi-sessions.after.txt" 2>&1 || true
}
trap cleanup EXIT
require_cmd sudo
require_cmd iscsiadm
require_cmd sg_inq
require_cmd sg_rtpg
require_cmd mkfs.ext4
require_cmd mount
require_cmd sha256sum
log "run_id=$RUN_ID"
log "root=$ROOT"
log "artifact_dir=$ARTIFACT_DIR"
log "iqn=$IQN"
log "portal=127.0.0.1:${PORT}"
cd "$ROOT"
git rev-parse --short HEAD >"$ARTIFACT_DIR/git-head.txt" 2>/dev/null || true
if [[ -x "${BIN_DIR}/blockmaster" && -x "${BIN_DIR}/blockvolume" ]]; then
log "use prebuilt binaries from ${BIN_DIR}"
else
require_cmd go
log "build binaries"
go build -o "${BIN_DIR}/blockmaster" ./cmd/blockmaster
go build -o "${BIN_DIR}/blockvolume" ./cmd/blockvolume
fi
cat >"$ARTIFACT_DIR/topology.yaml" <<YAML
volumes:
- volume_id: v1
slots:
- replica_id: r1
server_id: s1
YAML
rm -rf "${RUN_DIR}/master-store" "${RUN_DIR}/volume-store"
mkdir -p "${RUN_DIR}/master-store" "${RUN_DIR}/volume-store"
pkill -KILL -f "${BIN_DIR}/blockvolume" >/dev/null 2>&1 || true
pkill -KILL -f "${BIN_DIR}/blockmaster" >/dev/null 2>&1 || true
sudo iscsiadm -m node -T "$IQN" -p "127.0.0.1:${PORT}" --logout >/dev/null 2>&1 || true
sudo iscsiadm -m node -T "$IQN" -p "127.0.0.1:${PORT}" -o delete >/dev/null 2>&1 || true
sudo iscsiadm -m discoverydb -t sendtargets -p "127.0.0.1:${PORT}" -o delete >/dev/null 2>&1 || true
sudo iscsiadm -m session >"$ARTIFACT_DIR/iscsi-sessions.before.txt" 2>&1 || true
log "start blockmaster"
setsid -f "${BIN_DIR}/blockmaster" \
--authority-store "${RUN_DIR}/master-store" \
--listen "$MASTER_ADDR" \
--topology "$ARTIFACT_DIR/topology.yaml" \
--expected-slots-per-volume 1 \
>"$ARTIFACT_DIR/blockmaster.log" 2>&1
sleep 1
log "start blockvolume iSCSI target"
setsid -f "${BIN_DIR}/blockvolume" \
--master "$MASTER_ADDR" \
--server-id s1 \
--volume-id v1 \
--replica-id r1 \
--data-addr "$DATA_ADDR" \
--ctrl-addr "$CTRL_ADDR" \
--status-addr "$STATUS_ADDR" \
--heartbeat-interval 200ms \
--t1-readiness \
--durable-root "${RUN_DIR}/volume-store" \
--durable-impl smartwal \
--durable-blocks "$BLOCKS" \
--durable-blocksize "$BLOCK_SIZE" \
--iscsi-listen "127.0.0.1:${PORT}" \
--iscsi-iqn "$IQN" \
>"$ARTIFACT_DIR/blockvolume.log" 2>&1
log "wait iSCSI listener"
for _ in $(seq 1 100); do
if bash -c "</dev/tcp/127.0.0.1/${PORT}" >/dev/null 2>&1; then
break
fi
sleep 0.1
done
sleep 2
log "iscsi discovery/login"
sudo iscsiadm -m discovery -t sendtargets -p "127.0.0.1:${PORT}" | tee "$ARTIFACT_DIR/discovery.log"
sudo iscsiadm -m node -T "$IQN" -p "127.0.0.1:${PORT}" --login | tee "$ARTIFACT_DIR/login.log"
sudo iscsiadm -m session -P 3 >"$ARTIFACT_DIR/iscsi-session-P3.txt" 2>&1 || true
log "wait kernel block device"
dev=""
for _ in $(seq 1 100); do
dev="$(ls $DEVLINK_GLOB 2>/dev/null | head -n1 || true)"
if [[ -n "$dev" ]]; then
break
fi
sleep 0.1
done
if [[ -z "$dev" ]]; then
ls -l /dev/disk/by-path >"$ARTIFACT_DIR/by-path.txt" 2>&1 || true
(sudo dmesg | tail -n 120) >"$ARTIFACT_DIR/dmesg.tail.txt" 2>&1 || true
echo "device not found for IQN ${IQN}" >&2
exit 1
fi
real_dev="$(readlink -f "$dev")"
log "device=$dev real=$real_dev"
lsblk "$real_dev" >"$ARTIFACT_DIR/lsblk.txt" 2>&1 || true
log "capture ALUA inquiry evidence"
sudo sg_inq "$real_dev" >"$ARTIFACT_DIR/sg_inq.standard.txt" 2>&1
sudo sg_inq -p 0x00 "$real_dev" >"$ARTIFACT_DIR/sg_inq.vpd00.txt" 2>&1
sudo sg_inq -p 0x83 "$real_dev" >"$ARTIFACT_DIR/sg_inq.vpd83.txt" 2>&1
sudo sg_rtpg "$real_dev" >"$ARTIFACT_DIR/sg_rtpg.txt" 2>&1
if ! grep -Eiq "TPGS|target port group|asymmetric" "$ARTIFACT_DIR/sg_inq.standard.txt" "$ARTIFACT_DIR/sg_rtpg.txt"; then
echo "ALUA evidence missing from sg_inq/sg_rtpg output" >&2
exit 1
fi
if ! grep -Eiq "asymmetric access state[[:space:]]*:[[:space:]]*0x0[01]|active|optimized" "$ARTIFACT_DIR/sg_rtpg.txt"; then
echo "REPORT TARGET PORT GROUPS did not report active/optimized state" >&2
exit 1
fi
log "mkfs/mount/write/read"
sudo mkfs.ext4 -F "$real_dev" >"$ARTIFACT_DIR/mkfs.log" 2>&1
sudo mount "$real_dev" "$MOUNT_DIR"
sudo dd if=/dev/urandom of="$MOUNT_DIR/payload.bin" bs=4096 count=8 status=none
sync
sudo sha256sum "$MOUNT_DIR/payload.bin" | tee "$ARTIFACT_DIR/payload.sha256"
sudo sha256sum -c "$ARTIFACT_DIR/payload.sha256" | tee "$ARTIFACT_DIR/sha256-check.log"
sudo umount "$MOUNT_DIR"
log "logout"
sudo iscsiadm -m node -T "$IQN" -p "127.0.0.1:${PORT}" --logout | tee "$ARTIFACT_DIR/logout.log"
sudo iscsiadm -m node -T "$IQN" -p "127.0.0.1:${PORT}" -o delete >>"$ARTIFACT_DIR/logout.log" 2>&1 || true
sudo iscsiadm -m session >"$ARTIFACT_DIR/iscsi-sessions.final.txt" 2>&1 || true
if ! grep -q "No active sessions" "$ARTIFACT_DIR/iscsi-sessions.final.txt"; then
cat "$ARTIFACT_DIR/iscsi-sessions.final.txt"
exit 1
fi
log "PASS: iscsiadm login reports ALUA and completes mkfs mount write/read logout"
log "artifacts=$ARTIFACT_DIR"
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(pwd)}"
export SW_BLOCK_RUN_LABEL="${SW_BLOCK_RUN_LABEL:-csi-node-restart}"
export SW_BLOCK_LAUNCHER_PVC_OWNER_REF="${SW_BLOCK_LAUNCHER_PVC_OWNER_REF:-1}"
export SW_BLOCK_RESTART_CSI_NODE_BEFORE_READER=1
export SW_BLOCK_DEMO_APP_MANIFEST="${SW_BLOCK_DEMO_APP_MANIFEST:-$ROOT/deploy/k8s/alpha/demo-app-pvc-writer-hold.yaml}"
exec bash "$ROOT/scripts/run-alpha-app-demo.sh" "$ROOT"