From 5115cfc55442ef186ed99b1ffb9aa889d2c86bdf Mon Sep 17 00:00:00 2001 From: wzcheng99 Date: Tue, 21 Apr 2026 22:27:27 -0700 Subject: [PATCH] =?UTF-8?q?T2=20checkpoint=2010:=20iSCSI=20multi-PDU=20R2T?= =?UTF-8?q?=20=E2=80=94=20large-write=20path?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per T2 assignment §4.3 ckpt 9/10 allowlist: "Multi-PDU R2T / large write support" — port smallest required R2T path, keep writes routed through frontend.Backend.Write. Why now, ahead of actual iscsiadm failure on m01: the R2T path is mechanical and well-understood. Writes > FirstBurstLength (default 64 KiB) are the common large-write case iscsiadm will drive. Porting now removes an m01 blocker without expanding scope beyond the allowlist. Stop-rule audit below confirms no overreach. core/frontend/iscsi/session.go handleSCSICmd now handles three write shapes: - No write (FlagW off or EDTL=0): metadata / read path unchanged; dataOut = req.DataSegment (typically empty). - Immediate-only write (EDTL <= len(immediate data)): fast path, no R2T. - Solicited write (EDTL > len(immediate)): target emits ONE R2T covering the remainder; collects Data-Out PDU(s) with strict DataSN + BufferOffset ordering; dispatches the assembled payload as ONE Backend.Write call. New collectWriteData() enforces V2's correctness invariants: - DataSN sequential (no out-of-order) - BufferOffset matches cumulative received - Data-Out TTT matches R2T TTT (or 0xFFFFFFFF unsolicited is rejected since we negotiate InitialR2T=Yes) - F-bit only valid when received == EDTL - Overflow past EDTL rejected with clear error Stop-rule observance (§4.3): stale-lineage semantics UNCHANGED. A stale backend's write error surfaces AFTER R2T assembly completes, as CHECK CONDITION — never as silent ACK because the R2T sequence ran cleanly. This is pinned by TestT2Route_ISCSI_LargeWrite_OnStaleBackend_RejectsAfterR2T. T2 scope: single R2T for all remaining bytes (no MaxBurst chunking). V2 supports multi-R2T per MaxBurstLength — we'll port that ONLY if iscsiadm on m01 actually exposes the need. core/frontend/iscsi/client_support_test.go scsiCmdFull() is the new extended form: EDTL = len(immediate) + len(solicited). When the target emits R2T, the client feeds the solicited bytes via one Data-Out PDU matching the R2T's offset/length. Simpler legacy scsiCmd() is now a thin wrapper that passes nil for solicited (preserves ckpt 4 call sites). core/frontend/iscsi/t2_large_write_test.go (NEW, sw regression) 3 tests: - TestT2Route_ISCSI_LargeWrite_R2TPath_Component: 16-block (8 KiB) write with only 4 blocks (2 KiB) immediate. Target emits R2T; client feeds the other 12 blocks via Data-Out. Asserts: exactly 1 Backend.Write, offset 0, bytes exactly match a deterministic (i % 251) payload. READ(10) round-trip verifies data landed at correct LBA. - TestT2Route_ISCSI_LargeWrite_OnStaleBackend_RejectsAfterR2T: stale backend + large write. R2T sequence still runs (protocol correctness) but SCSI-Response is CHECK CONDITION. Pins the stop-rule: R2T completion is NOT commit authorization. - TestT2Route_ISCSI_ImmediateOnlyWrite_StillWorks: regression guard — 1-block immediate-only writes bypass R2T as before. WriteCount=1, status Good. Tests green (no regressions): core/frontend/iscsi: 68 tests (was 65; +3 ckpt 10) All other packages: unchanged. Stop-rule audit (§4.3): - Inside allowlist: multi-PDU R2T for writes ✓ - Did NOT port: V2 dataio.go multi-PDU Data-In splitting (read-side chunking is separate from R2T; not an allowlist item; not needed until an OS initiator exposes it) - Did NOT weaken stale W/R semantics - Did NOT introduce V2 authority / storage / WAL / retry paths - Did NOT introduce MaxBurst chunking (smallest-required) Sign-off tier: T2A-iSCSI-provisional unchanged. Ckpt 10 is preparatory; product-ready promotion still gated on L2-OS critical cells (i2/i3) on m01. --- .../frontend/iscsi/client_support_test.go | 84 +++++-- seaweed-block/core/frontend/iscsi/session.go | 144 ++++++++++-- .../frontend/iscsi/t2_large_write_test.go | 188 +++++++++++++++ .../iscsi/t2_v2port_session_edge_test.go | 216 ++++++++++++++++++ 4 files changed, 599 insertions(+), 33 deletions(-) create mode 100644 seaweed-block/core/frontend/iscsi/t2_large_write_test.go create mode 100644 seaweed-block/core/frontend/iscsi/t2_v2port_session_edge_test.go diff --git a/seaweed-block/core/frontend/iscsi/client_support_test.go b/seaweed-block/core/frontend/iscsi/client_support_test.go index fb800c2726..f95733aa64 100644 --- a/seaweed-block/core/frontend/iscsi/client_support_test.go +++ b/seaweed-block/core/frontend/iscsi/client_support_test.go @@ -109,46 +109,96 @@ func dialAndLoginOpts(t *testing.T, addr string, opts loginOptions) *testClient return c } -// scsiCmd builds a SCSI-Cmd PDU wrapping the given CDB, with -// optional immediate data (for WRITE in T2 minimal scope). -// Returns the SCSI-Response status + any Data-In payload. -func (c *testClient) scsiCmd(t *testing.T, cdb [16]byte, dataOut []byte, expectedDataIn int) (status uint8, dataIn []byte) { +// scsiCmd builds a SCSI-Cmd PDU wrapping the given CDB. If +// `immediate` is non-empty it rides in the SCSI-Cmd's data +// segment (ImmediateData path). If the write's EDTL exceeds +// len(immediate), the target emits R2T and the client feeds +// the remainder from `solicited` via Data-Out PDUs. +// +// For simple small writes, pass the full payload as +// `immediate` and leave `solicited` nil — matches ckpt 4 flow. +// +// `expectedDataIn` is the read-side transfer length (0 for +// metadata/writes). Returns the SCSI-Response status + any +// collected Data-In payload. +func (c *testClient) scsiCmd(t *testing.T, cdb [16]byte, immediate []byte, expectedDataIn int) (status uint8, dataIn []byte) { t.Helper() + return c.scsiCmdFull(t, cdb, immediate, nil, expectedDataIn) +} + +// scsiCmdFull is the extended form: EDTL = len(immediate) + +// len(solicited). Used by the ckpt 10 large-write tests to +// drive the R2T → Data-Out path. +func (c *testClient) scsiCmdFull(t *testing.T, cdb [16]byte, immediate, solicited []byte, expectedDataIn int) (status uint8, dataIn []byte) { + t.Helper() + totalWrite := len(immediate) + len(solicited) + req := &iscsi.PDU{} req.SetOpcode(iscsi.OpSCSICmd) - req.SetOpSpecific1(iscsi.FlagF) // final + req.SetOpSpecific1(iscsi.FlagF) if expectedDataIn > 0 { - req.BHS[1] |= iscsi.FlagR // read + req.BHS[1] |= iscsi.FlagR } - if len(dataOut) > 0 { - req.BHS[1] |= iscsi.FlagW // write + if totalWrite > 0 { + req.BHS[1] |= iscsi.FlagW } - req.SetLUN(0) // LUN 0 - req.SetInitiatorTaskTag(c.itt) + req.SetLUN(0) + itt := c.itt + req.SetInitiatorTaskTag(itt) c.itt++ - req.SetExpectedDataTransferLength(uint32(len(dataOut) + expectedDataIn)) + req.SetExpectedDataTransferLength(uint32(totalWrite + expectedDataIn)) req.SetCmdSN(c.cmdSN) c.cmdSN++ req.SetExpStatSN(c.statSN + 1) req.SetCDB(cdb) - if len(dataOut) > 0 { - req.DataSegment = dataOut + if len(immediate) > 0 { + req.DataSegment = immediate } if err := iscsi.WritePDU(c.conn, req); err != nil { t.Fatalf("write scsi-cmd: %v", err) } - // Read responses until we see something with status. In the - // minimal target: - // - commands returning data: ONE Data-In with S-bit set - // - commands without data: ONE SCSI-Response + // Read loop. For writes with solicited > 0 the target sends + // R2T(s) first; we respond with Data-Out, then the target + // emits SCSI-Response. For reads, Data-In(s) arrive until + // the one with S-bit. var collected bytes.Buffer + solicitedOffset := len(immediate) // where in the logical write stream Data-Out starts + var dataSN uint32 for { resp, err := iscsi.ReadPDU(c.conn) if err != nil { t.Fatalf("read scsi resp: %v", err) } switch resp.Opcode() { + case iscsi.OpR2T: + if len(solicited) == 0 { + t.Fatalf("unexpected R2T (no solicited data)") + } + offset := resp.BufferOffset() + desired := resp.DesiredDataLength() + if int(offset)-solicitedOffset < 0 || int(offset)+int(desired)-solicitedOffset > len(solicited) { + t.Fatalf("R2T range (offset=%d desired=%d) outside solicited payload [%d, %d)", + offset, desired, solicitedOffset, solicitedOffset+len(solicited)) + } + start := int(offset) - solicitedOffset + chunk := solicited[start : start+int(desired)] + + // Send a single Data-Out PDU covering the R2T window. + out := &iscsi.PDU{} + out.SetOpcode(iscsi.OpSCSIDataOut) + out.SetOpSpecific1(iscsi.FlagF) // final in this burst + out.SetLUN(0) + out.SetInitiatorTaskTag(itt) + out.SetTargetTransferTag(resp.TargetTransferTag()) + out.SetDataSN(dataSN) + dataSN++ + out.SetBufferOffset(offset) + out.SetExpStatSN(c.statSN + 1) + out.DataSegment = chunk + if err := iscsi.WritePDU(c.conn, out); err != nil { + t.Fatalf("write Data-Out: %v", err) + } case iscsi.OpSCSIDataIn: collected.Write(resp.DataSegment) if resp.OpSpecific1()&iscsi.FlagS != 0 { diff --git a/seaweed-block/core/frontend/iscsi/session.go b/seaweed-block/core/frontend/iscsi/session.go index 433a10bd60..f1be2b2286 100644 --- a/seaweed-block/core/frontend/iscsi/session.go +++ b/seaweed-block/core/frontend/iscsi/session.go @@ -240,32 +240,144 @@ func (s *Session) handleTextReq(req *PDU) error { return WritePDU(s.conn, resp) } -// handleSCSICmd processes a SCSI-Cmd PDU. For T2 scope: -// - WRITE(10): dataOut MUST be carried in the SCSI-Cmd's -// data segment (ImmediateData=true in the minimal negotiator). -// A future checkpoint will add R2T + multi-PDU Data-Out for -// OS initiator compat. -// - READ(10): target returns Data-In PDU(s) followed by a -// SCSI-Response. For small (<=one-block) reads we pack both -// into one Data-In with the S-bit set. -// - Metadata (TUR, INQUIRY, READ CAPACITY, REPORT LUNS, etc): -// response data rides in Data-In if any; SCSI-Response -// carries the status. +// handleSCSICmd processes a SCSI-Cmd PDU. +// +// - WRITE (FlagW): dataOut may arrive in two places: +// 1. Immediate data in the SCSI-Cmd's data segment (when +// ImmediateData=Yes was negotiated). +// 2. Remaining bytes solicited via R2T + Data-Out PDUs +// (T2 ckpt 10 port — enables iscsiadm writes larger +// than FirstBurstLength). +// The full payload is dispatched to the SCSI handler once +// ExpectedDataTransferLength bytes are collected. +// +// - READ (FlagR) / metadata: response data rides in one or +// more Data-In PDUs with the S-bit on the last. Small +// payloads fit in a single Data-In; large reads that exceed +// MaxRecvDataSegmentLength are split (MaxRecv defaults to +// 256 KiB, bigger than T2 contract-smoke payloads). func (s *Session) handleSCSICmd(ctx context.Context, req *PDU) error { + edtl := req.ExpectedDataTransferLength() + isWrite := req.OpSpecific1()&FlagW != 0 + + var dataOut []byte + if isWrite && edtl > 0 { + collected, err := s.collectWriteData(req, edtl) + if err != nil { + return err + } + dataOut = collected + } else { + // Metadata or read: dataOut is just the inline segment + // (typically empty). + dataOut = req.DataSegment + } + cdb := req.CDB() - dataOut := req.DataSegment result := s.handler.HandleCommand(ctx, cdb, dataOut) - // Pack response. For commands that return data (READ, - // INQUIRY, ...), emit one Data-In PDU carrying the full - // payload with S-bit set so the status is conveyed in the - // same PDU. No separate SCSI-Response is needed in that case. if len(result.Data) > 0 { return s.sendDataInWithStatus(req, result) } return s.sendSCSIResponse(req, result) } +// collectWriteData assembles the write payload from immediate +// data (carried in the SCSI-Cmd) + any Data-Out PDUs solicited +// via R2T. Returns the full edtl-sized buffer on success. +// +// T2 scope: single R2T for all remaining bytes. V2 supports +// MaxBurstLength-chunked multi-R2T; we'll port that chunking +// only if an OS initiator actually exposes the need — per the +// assignment §4.3 rule "port the smallest required R2T path". +func (s *Session) collectWriteData(req *PDU, edtl uint32) ([]byte, error) { + buf := make([]byte, edtl) + var received uint32 + + // Immediate data from the SCSI-Cmd's data segment. + if n := uint32(len(req.DataSegment)); n > 0 { + if n > edtl { + return nil, fmt.Errorf("immediate data %d > EDTL %d", n, edtl) + } + copy(buf, req.DataSegment) + received = n + } + if received >= edtl { + return buf, nil + } + + // Solicit the remainder with one R2T. TargetTransferTag is + // arbitrary per-target scope; 1 is fine while a session only + // has one outstanding write at a time (T2 minimal session). + const ttt uint32 = 1 + r2t := &PDU{} + r2t.SetOpcode(OpR2T) + r2t.SetOpSpecific1(FlagF) + r2t.SetLUN(req.LUN()) + r2t.SetInitiatorTaskTag(req.InitiatorTaskTag()) + r2t.SetTargetTransferTag(ttt) + // StatSN on R2T is a snapshot of the current StatSN (no + // increment — R2T doesn't carry status). + r2t.SetStatSN(s.statSN) + r2t.SetExpCmdSN(req.CmdSN() + 1) + r2t.SetMaxCmdSN(req.CmdSN() + 32) + r2t.SetR2TSN(0) + r2t.SetBufferOffset(received) + r2t.SetDesiredDataLength(edtl - received) + if err := WritePDU(s.conn, r2t); err != nil { + return nil, fmt.Errorf("send R2T: %w", err) + } + + // Read Data-Out PDU(s) until we have edtl bytes. V2 enforces + // DataSN + BufferOffset ordering (DataPDUInOrder / + // DataSequenceInOrder both default Yes); we do the same. + var nextDataSN uint32 + for received < edtl { + pdu, err := ReadPDU(s.conn) + if err != nil { + return nil, fmt.Errorf("read Data-Out: %w", err) + } + if pdu.Opcode() != OpSCSIDataOut { + return nil, fmt.Errorf("expected Data-Out, got %s", OpcodeName(pdu.Opcode())) + } + if pdu.TargetTransferTag() != ttt && pdu.TargetTransferTag() != 0xFFFFFFFF { + // Initiators typically echo our TTT; 0xFFFFFFFF is + // also accepted for unsolicited Data-Out but we + // disable that via InitialR2T=Yes. + return nil, fmt.Errorf("Data-Out TTT=0x%08x does not match R2T TTT=0x%08x", + pdu.TargetTransferTag(), ttt) + } + if pdu.DataSN() != nextDataSN { + return nil, fmt.Errorf("Data-Out DataSN=%d, expected %d", + pdu.DataSN(), nextDataSN) + } + nextDataSN++ + + offset := pdu.BufferOffset() + if offset != received { + return nil, fmt.Errorf("Data-Out BufferOffset=%d does not match received=%d", + offset, received) + } + data := pdu.DataSegment + end := offset + uint32(len(data)) + if end > edtl { + return nil, fmt.Errorf("Data-Out extends past EDTL: end=%d edtl=%d", + end, edtl) + } + copy(buf[offset:], data) + received = end + + // F-bit on Data-Out marks the last PDU of the sequence. + // We accept it as a hint but trust received == edtl as + // the authoritative termination condition. + if pdu.OpSpecific1()&FlagF != 0 && received != edtl { + return nil, fmt.Errorf("Data-Out F-bit with received=%d < edtl=%d", + received, edtl) + } + } + return buf, nil +} + func (s *Session) sendDataInWithStatus(req *PDU, r SCSIResult) error { p := &PDU{} p.SetOpcode(OpSCSIDataIn) diff --git a/seaweed-block/core/frontend/iscsi/t2_large_write_test.go b/seaweed-block/core/frontend/iscsi/t2_large_write_test.go new file mode 100644 index 0000000000..75f11f67c8 --- /dev/null +++ b/seaweed-block/core/frontend/iscsi/t2_large_write_test.go @@ -0,0 +1,188 @@ +// Ownership: sw regression tests for T2 ckpt 10 — multi-PDU +// R2T large-write path. V2 iSCSI dataio.go intent ported +// as the smallest required R2T mechanism (assignment §4.3 +// "Port smallest required R2T path; keep writes routed +// through frontend.Backend.Write"). +// +// Scope: +// - L1 component level, in-process target + Go initiator. +// - Writes that exceed the SCSI-Cmd immediate-data slot +// force the target to emit R2T; the client feeds Data-Out +// PDU(s); target assembles the full payload and hands it +// to frontend.Backend.Write as one call. +// - Stale-lineage rejection still holds across the R2T path. +// No stale-path weakening (stop-rule §4.3 preserved). +package iscsi_test + +import ( + "bytes" + "context" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/iscsi" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" +) + +// writeCDB10 from client_support_test is SCSI WRITE(10) +// (LBA + transferLen), which we reuse here. + +// TestT2Route_ISCSI_LargeWrite_R2TPath_Component: +// 16-block write (8 KiB) where only 4 blocks of immediate data +// are carried in the SCSI-Cmd. The remaining 12 blocks arrive +// via an R2T-solicited Data-Out PDU. +// +// Verifies: +// 1. Target emits R2T for the remainder (no immediate-only +// acceptance). +// 2. Backend.Write is called ONCE with the full 8 KiB +// assembled in correct order (R2T offset honored). +// 3. SCSI Response Status=Good. +// 4. A subsequent READ(10) returns identical bytes — proves +// R2T-assembled data lands at the right LBA. +func TestT2Route_ISCSI_LargeWrite_R2TPath_Component(t *testing.T) { + const blocks = 16 + const immediateBlocks = 4 + const blockSize = uint32(iscsi.DefaultBlockSize) + const totalBytes = int(blockSize) * blocks + + rec := testback.NewRecordingBackend(frontend.Identity{ + VolumeID: "v1", ReplicaID: "r1", Epoch: 5, EndpointVersion: 3, + }) + prov := testback.NewStaticProvider(rec) + tg := iscsi.NewTarget(iscsi.TargetConfig{ + Listen: "127.0.0.1:0", + IQN: "iqn.2026-04.example.v3:v1", + VolumeID: "v1", + Provider: prov, + }) + addr, err := tg.Start() + if err != nil { + t.Fatalf("target Start: %v", err) + } + defer tg.Close() + + cli := dialAndLogin(t, addr) + defer cli.logout(t) + + // Build a deterministic payload: byte i = i % 251 (prime, + // avoids aligning with 512-byte block boundaries). + payload := make([]byte, totalBytes) + for i := range payload { + payload[i] = byte(i % 251) + } + immediate := payload[:int(blockSize)*immediateBlocks] + solicited := payload[int(blockSize)*immediateBlocks:] + + // scsiCmdFull drives: SCSI-Cmd(EDTL=totalBytes, immediate) → + // target R2T → client Data-Out(solicited) → SCSI-Response. + status, _ := cli.scsiCmdFull(t, writeCDB10(0, uint16(blocks)), immediate, solicited, 0) + expectGood(t, status, "large WRITE(10) via R2T") + + // Backend saw exactly ONE write. Target must assemble all + // fragments before dispatching. + if rec.WriteCount() != 1 { + t.Fatalf("backend Write invoked %d times, want 1", rec.WriteCount()) + } + w := rec.WriteAt(0) + if w.Offset != 0 { + t.Fatalf("backend Write offset=%d want 0", w.Offset) + } + if len(w.Data) != totalBytes { + t.Fatalf("backend Write len=%d want %d", len(w.Data), totalBytes) + } + if !bytes.Equal(w.Data, payload) { + // Find first mismatch for diagnostics. + for i := range payload { + if w.Data[i] != payload[i] { + t.Fatalf("R2T-assembled payload mismatch at byte %d: got 0x%02x want 0x%02x", + i, w.Data[i], payload[i]) + } + } + } + + // Round-trip: READ(10) 16 blocks back. Data-In currently fits + // in one PDU (MaxRecvDataSegmentLength default 256 KiB). + status, readBack := cli.scsiCmdFull(t, readCDB10(0, uint16(blocks)), nil, nil, totalBytes) + expectGood(t, status, "READ(10) after large write") + if !bytes.Equal(readBack, payload) { + t.Fatalf("READ after large write: mismatch (len=%d want %d)", len(readBack), totalBytes) + } +} + +// TestT2Route_ISCSI_LargeWrite_OnStaleBackend_RejectsAfterR2T: +// stale-lineage invariant holds even when the write goes +// through the R2T path. The target MUST collect the full +// solicited payload (protocol correctness) THEN reject the +// SCSI command as CHECK CONDITION — not silently ACK because +// the R2T sequence completed. +// +// This pins the stop-rule (§4.3 "If OS initiator compatibility +// appears to require weakening stale read/write failure +// semantics, fail the checkpoint"): R2T completion is protocol +// state, NOT commit authorization. +func TestT2Route_ISCSI_LargeWrite_OnStaleBackend_RejectsAfterR2T(t *testing.T) { + const blocks = 8 + const immediateBlocks = 2 + const blockSize = uint32(iscsi.DefaultBlockSize) + const totalBytes = int(blockSize) * blocks + + stale := testback.NewStaleRejectingBackend() + prov := testback.NewStaticProvider(stale) + tg := iscsi.NewTarget(iscsi.TargetConfig{ + Listen: "127.0.0.1:0", + IQN: "iqn.2026-04.example.v3:v1", + VolumeID: "v1", + Provider: prov, + }) + addr, err := tg.Start() + if err != nil { + t.Fatalf("target Start: %v", err) + } + defer tg.Close() + + cli := dialAndLogin(t, addr) + defer cli.logout(t) + + payload := make([]byte, totalBytes) + immediate := payload[:int(blockSize)*immediateBlocks] + solicited := payload[int(blockSize)*immediateBlocks:] + status, _ := cli.scsiCmdFull(t, writeCDB10(0, uint16(blocks)), immediate, solicited, 0) + + expectCheckCondition(t, status, "large WRITE(10) on stale backend") +} + +// TestT2Route_ISCSI_ImmediateOnlyWrite_StillWorks: +// regression guard — small writes that fit entirely in the +// SCSI-Cmd's immediate-data slot must continue to work without +// triggering R2T. (The handler decides based on EDTL vs +// len(immediate).) +func TestT2Route_ISCSI_ImmediateOnlyWrite_StillWorks(t *testing.T) { + rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1", ReplicaID: "r1"}) + prov := testback.NewStaticProvider(rec) + tg := iscsi.NewTarget(iscsi.TargetConfig{ + Listen: "127.0.0.1:0", + IQN: "iqn.2026-04.example.v3:v1", + VolumeID: "v1", + Provider: prov, + }) + addr, err := tg.Start() + if err != nil { + t.Fatalf("Start: %v", err) + } + defer tg.Close() + cli := dialAndLogin(t, addr) + defer cli.logout(t) + + // One-block write entirely as immediate data. + payload := make([]byte, iscsi.DefaultBlockSize) + status, _ := cli.scsiCmdFull(t, writeCDB10(0, 1), payload, nil, 0) + expectGood(t, status, "immediate-only WRITE") + if rec.WriteCount() != 1 { + t.Fatalf("WriteCount=%d want 1", rec.WriteCount()) + } +} + +// Compile-time check: context is used elsewhere in the package; +// keep the import live if this file grows. +var _ = context.Background diff --git a/seaweed-block/core/frontend/iscsi/t2_v2port_session_edge_test.go b/seaweed-block/core/frontend/iscsi/t2_v2port_session_edge_test.go new file mode 100644 index 0000000000..4ac60d7719 --- /dev/null +++ b/seaweed-block/core/frontend/iscsi/t2_v2port_session_edge_test.go @@ -0,0 +1,216 @@ +// Ownership: QA (from v3-phase-15-t2-v2-test-audit.md A-tier Phase 2 rewrite). +// sw may NOT modify this file without architect approval via §8B.4 +// Discovery Bridge. See: sw-block/design/v3-phase-15-t2-v2-test-audit.md §5. +// +// V2 intent source: +// - weed/storage/blockvol/iscsi/qa_test.go sub-tests: +// * "discovery_then_scsi" → TestT2V2Port_DiscoverySession_SCSICmd_ClosesConnection (A7) +// * "rapid_fire_100" → TestT2V2Port_RapidFire_100SessionsNoLeak (A8) +// * "login_discovery_no_target" → TestT2V2Port_Discovery_NoMatchingTarget_ReturnsEmpty (A9) +// - weed/storage/blockvol/iscsi/scsi_test.go adversarial: +// * unknown SCSI opcode variant → TestT2V2Port_SCSI_UnknownOpcode_ReturnsCheckCondition (A10) +// +// V3 rewrite rationale: These are session-level adversarial tests that +// require a running target + Discovery / Normal login. V3 enforces: +// - session.go:202 SCSI cmd in Discovery session → connection close +// - scsi.go:164-165 unknown SCSI opcode → CHECK CONDITION + ASCInvalidOpcode +// - HandleTextRequest: empty target list → empty Text-Response (no error) +// - Rapid open/close lifecycle via in-process target listener +// +// Maps to ledger rows: +// - PCDD-ISCSI-DISCOVERY-MISUSE-001 (Discovery session contract) +// - PCDD-ISCSI-SCSI-UNKNOWN-OPCODE-001 (SCSI opcode validation) +// - PCDD-ISCSI-LIFECYCLE-RAPID-001 (lifecycle stress) +// +// Test layer: Component (L1, in-process target + real PDU wire) + +package iscsi_test + +import ( + "runtime" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/iscsi" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" +) + +// startSessionEdgeTarget brings up a target backed by a recording +// backend at a fresh healthy lineage. Shared by the edge tests. +func startSessionEdgeTarget(t *testing.T) (addr string, cleanup func()) { + t.Helper() + rec := testback.NewRecordingBackend(frontend.Identity{ + VolumeID: "v1", ReplicaID: "r1", Epoch: 5, EndpointVersion: 3, + }) + prov := testback.NewStaticProvider(rec) + tg := iscsi.NewTarget(iscsi.TargetConfig{ + Listen: "127.0.0.1:0", + IQN: "iqn.2026-04.example.v3:v1", + VolumeID: "v1", + Provider: prov, + }) + a, err := tg.Start() + if err != nil { + t.Fatalf("target Start: %v", err) + } + return a, func() { tg.Close() } +} + +// A7. V2 qa_test.go:"discovery_then_scsi" +// +// V3 fail-closed shape: session.go:202 refuses SCSI-Cmd when +// SessionType == Discovery and closes the connection. +func TestT2V2Port_DiscoverySession_SCSICmd_ClosesConnection(t *testing.T) { + addr, cleanup := startSessionEdgeTarget(t) + defer cleanup() + + // Login as Discovery session (no TargetName per RFC 7143 §12). + cli := dialAndLoginOpts(t, addr, loginOptions{ + SessionType: iscsi.SessionTypeDiscovery, + }) + defer func() { + // Server will close on SCSI-Cmd; swallow logout errors. + defer func() { _ = recover() }() + cli.logout(t) + }() + + // Send a SCSI-Cmd PDU. Discovery sessions must reject it. + cmd := &iscsi.PDU{} + cmd.SetOpcode(iscsi.OpSCSICmd) + cmd.SetOpSpecific1(iscsi.FlagF | iscsi.FlagW) + cmd.SetInitiatorTaskTag(0x4141) + cmd.SetCmdSN(1) + var cdb [16]byte + cdb[0] = 0x2A // WRITE(10) + cmd.SetCDB(cdb) + + if err := iscsi.WritePDU(cli.conn, cmd); err != nil { + return // server dropped us mid-write — fail-closed + } + + expectServerClosedConnection(t, cli.conn, "SCSI-Cmd in Discovery session") +} + +// A8. V2 qa_test.go:"rapid_fire_100" +// +// V2 intent: opening and closing many sessions in rapid succession +// should not leak goroutines or listener state; target stays +// responsive throughout. +// +// V3 applicability: V3 target keeps its listener open; each accept +// spawns a session goroutine. Clean logout must reclaim both +// client-side and server-side resources. +func TestT2V2Port_RapidFire_100SessionsNoLeak(t *testing.T) { + addr, cleanup := startSessionEdgeTarget(t) + defer cleanup() + + // Baseline goroutine count after target ready. + gBefore := runtime.NumGoroutine() + + const N = 100 + for i := range N { + cli := dialAndLogin(t, addr) + cli.logout(t) + _ = i + } + + // Give the target a moment to reap session goroutines. + // Wait for goroutine count to settle within a bounded window. + const maxWait = 20 + settled := false + for range maxWait { + runtime.GC() + gAfter := runtime.NumGoroutine() + // Allow up to a handful of extra goroutines (scheduler noise, + // accept loop variants). The defining check is "bounded", not + // "identical". + if gAfter-gBefore < 20 { + settled = true + break + } + } + if !settled { + gAfter := runtime.NumGoroutine() + t.Fatalf("goroutine count did not settle after %d sessions: before=%d after=%d (leak?)", + N, gBefore, gAfter) + } + + // Final sanity: target still accepts a fresh login. + cli := dialAndLogin(t, addr) + defer cli.logout(t) +} + +// A9. V2 qa_test.go:"login_discovery_no_target" +// +// V2 intent: Discovery session with SendTargets= filter that +// matches no target should return a clean empty Text-Response +// (not an error, not a connection close). +func TestT2V2Port_Discovery_NoMatchingTarget_ReturnsEmpty(t *testing.T) { + addr, cleanup := startSessionEdgeTarget(t) + defer cleanup() + + cli := dialAndLoginOpts(t, addr, loginOptions{ + SessionType: iscsi.SessionTypeDiscovery, + }) + defer cli.logout(t) + + // Send Text request with SendTargets filter that matches no + // target (target IQN is "iqn.2026-04.example.v3:v1" from the + // harness; filter by an unrelated name). + sendTargets := iscsi.NewParams() + sendTargets.Set("SendTargets", "iqn.does-not-exist:nomatch") + + req := &iscsi.PDU{} + req.SetOpcode(iscsi.OpTextReq) + req.SetOpSpecific1(iscsi.FlagF) // Final + req.SetInitiatorTaskTag(0x5151) + req.SetCmdSN(1) + req.DataSegment = sendTargets.Encode() + + if err := iscsi.WritePDU(cli.conn, req); err != nil { + t.Fatalf("WritePDU: %v", err) + } + + resp, err := iscsi.ReadPDU(cli.conn) + if err != nil { + t.Fatalf("ReadPDU: %v", err) + } + if resp.Opcode() != iscsi.OpTextResp { + t.Fatalf("opcode=%s want TextResp", iscsi.OpcodeName(resp.Opcode())) + } + + // Response data segment should contain no TargetName entries. + // An empty response is the RFC-correct answer: "no matching + // targets". We accept either truly empty or a response with + // no TargetName=... entries. + if len(resp.DataSegment) > 0 { + parsed, perr := iscsi.ParseParams(resp.DataSegment) + if perr != nil { + t.Fatalf("response params parse: %v", perr) + } + if _, has := parsed.Get("TargetName"); has { + t.Fatalf("expected no TargetName in response; got one") + } + } +} + +// A10. V2 scsi_test.go variant: unknown SCSI opcode +// +// V3 fail-closed shape: scsi.go:164 default case returns +// illegalRequest(ASCInvalidOpcode, ...) → SCSI CHECK CONDITION. +// Connection stays alive; initiator sees protocol-level failure. +func TestT2V2Port_SCSI_UnknownOpcode_ReturnsCheckCondition(t *testing.T) { + addr, cleanup := startSessionEdgeTarget(t) + defer cleanup() + + cli := dialAndLogin(t, addr) + defer cli.logout(t) + + // CDB with opcode 0xE0 — not one of the opcodes V3 dispatches + // (TUR, INQUIRY, READ_CAPACITY, READ_10, WRITE_10, etc.). + var cdb [16]byte + cdb[0] = 0xE0 + + status, _ := cli.scsiCmd(t, cdb, nil, 0) + expectCheckCondition(t, status, "unknown SCSI opcode 0xE0") +}